diff --git a/ProtoBufDemo/.gitignore b/protubuf/ProtoBufDemo/.gitignore similarity index 100% rename from ProtoBufDemo/.gitignore rename to protubuf/ProtoBufDemo/.gitignore diff --git a/ProtoBufDemo/README.md b/protubuf/ProtoBufDemo/README.md similarity index 100% rename from ProtoBufDemo/README.md rename to protubuf/ProtoBufDemo/README.md diff --git a/ProtoBufDemo/assets/Scene.meta b/protubuf/ProtoBufDemo/assets/Scene.meta similarity index 100% rename from ProtoBufDemo/assets/Scene.meta rename to protubuf/ProtoBufDemo/assets/Scene.meta diff --git a/ProtoBufDemo/assets/Scene/helloworld.fire b/protubuf/ProtoBufDemo/assets/Scene/helloworld.fire similarity index 100% rename from ProtoBufDemo/assets/Scene/helloworld.fire rename to protubuf/ProtoBufDemo/assets/Scene/helloworld.fire diff --git a/ProtoBufDemo/assets/Scene/helloworld.fire.meta b/protubuf/ProtoBufDemo/assets/Scene/helloworld.fire.meta similarity index 100% rename from ProtoBufDemo/assets/Scene/helloworld.fire.meta rename to protubuf/ProtoBufDemo/assets/Scene/helloworld.fire.meta diff --git a/ProtoBufDemo/assets/Script.meta b/protubuf/ProtoBufDemo/assets/Script.meta similarity index 100% rename from ProtoBufDemo/assets/Script.meta rename to protubuf/ProtoBufDemo/assets/Script.meta diff --git a/ProtoBufDemo/assets/Script/HelloWorld.js b/protubuf/ProtoBufDemo/assets/Script/HelloWorld.js similarity index 100% rename from ProtoBufDemo/assets/Script/HelloWorld.js rename to protubuf/ProtoBufDemo/assets/Script/HelloWorld.js diff --git a/ProtoBufDemo/assets/Script/HelloWorld.js.meta b/protubuf/ProtoBufDemo/assets/Script/HelloWorld.js.meta similarity index 100% rename from ProtoBufDemo/assets/Script/HelloWorld.js.meta rename to protubuf/ProtoBufDemo/assets/Script/HelloWorld.js.meta diff --git a/ProtoBufDemo/assets/Script/proto.meta b/protubuf/ProtoBufDemo/assets/Script/proto.meta similarity index 100% rename from ProtoBufDemo/assets/Script/proto.meta rename to protubuf/ProtoBufDemo/assets/Script/proto.meta diff --git a/ProtoBufDemo/assets/Script/proto/Person.js b/protubuf/ProtoBufDemo/assets/Script/proto/Person.js similarity index 100% rename from ProtoBufDemo/assets/Script/proto/Person.js rename to protubuf/ProtoBufDemo/assets/Script/proto/Person.js diff --git a/ProtoBufDemo/assets/Script/proto/Person.js.meta b/protubuf/ProtoBufDemo/assets/Script/proto/Person.js.meta similarity index 100% rename from ProtoBufDemo/assets/Script/proto/Person.js.meta rename to protubuf/ProtoBufDemo/assets/Script/proto/Person.js.meta diff --git a/ProtoBufDemo/assets/Script/proto/Person.proto b/protubuf/ProtoBufDemo/assets/Script/proto/Person.proto similarity index 100% rename from ProtoBufDemo/assets/Script/proto/Person.proto rename to protubuf/ProtoBufDemo/assets/Script/proto/Person.proto diff --git a/ProtoBufDemo/assets/Script/proto/Person.proto.meta b/protubuf/ProtoBufDemo/assets/Script/proto/Person.proto.meta similarity index 100% rename from ProtoBufDemo/assets/Script/proto/Person.proto.meta rename to protubuf/ProtoBufDemo/assets/Script/proto/Person.proto.meta diff --git a/ProtoBufDemo/assets/Script/proto/PersonPb.js b/protubuf/ProtoBufDemo/assets/Script/proto/PersonPb.js similarity index 100% rename from ProtoBufDemo/assets/Script/proto/PersonPb.js rename to protubuf/ProtoBufDemo/assets/Script/proto/PersonPb.js diff --git a/ProtoBufDemo/assets/Script/proto/PersonPb.js.meta b/protubuf/ProtoBufDemo/assets/Script/proto/PersonPb.js.meta similarity index 100% rename from ProtoBufDemo/assets/Script/proto/PersonPb.js.meta rename to protubuf/ProtoBufDemo/assets/Script/proto/PersonPb.js.meta diff --git a/ProtoBufDemo/assets/Script/proto/proto.d.ts b/protubuf/ProtoBufDemo/assets/Script/proto/proto.d.ts similarity index 100% rename from ProtoBufDemo/assets/Script/proto/proto.d.ts rename to protubuf/ProtoBufDemo/assets/Script/proto/proto.d.ts diff --git a/ProtoBufDemo/assets/Script/proto/proto.js b/protubuf/ProtoBufDemo/assets/Script/proto/proto.js similarity index 100% rename from ProtoBufDemo/assets/Script/proto/proto.js rename to protubuf/ProtoBufDemo/assets/Script/proto/proto.js diff --git a/ProtoBufDemo/assets/Script/proto/protobufjs.js b/protubuf/ProtoBufDemo/assets/Script/proto/protobufjs.js similarity index 100% rename from ProtoBufDemo/assets/Script/proto/protobufjs.js rename to protubuf/ProtoBufDemo/assets/Script/proto/protobufjs.js diff --git a/ProtoBufDemo/assets/Script/proto/protobufjs.js.meta b/protubuf/ProtoBufDemo/assets/Script/proto/protobufjs.js.meta similarity index 100% rename from ProtoBufDemo/assets/Script/proto/protobufjs.js.meta rename to protubuf/ProtoBufDemo/assets/Script/proto/protobufjs.js.meta diff --git a/ProtoBufDemo/assets/Texture.meta b/protubuf/ProtoBufDemo/assets/Texture.meta similarity index 100% rename from ProtoBufDemo/assets/Texture.meta rename to protubuf/ProtoBufDemo/assets/Texture.meta diff --git a/ProtoBufDemo/assets/Texture/HelloWorld.png b/protubuf/ProtoBufDemo/assets/Texture/HelloWorld.png similarity index 100% rename from ProtoBufDemo/assets/Texture/HelloWorld.png rename to protubuf/ProtoBufDemo/assets/Texture/HelloWorld.png diff --git a/ProtoBufDemo/assets/Texture/HelloWorld.png.meta b/protubuf/ProtoBufDemo/assets/Texture/HelloWorld.png.meta similarity index 100% rename from ProtoBufDemo/assets/Texture/HelloWorld.png.meta rename to protubuf/ProtoBufDemo/assets/Texture/HelloWorld.png.meta diff --git a/ProtoBufDemo/assets/Texture/singleColor.png b/protubuf/ProtoBufDemo/assets/Texture/singleColor.png similarity index 100% rename from ProtoBufDemo/assets/Texture/singleColor.png rename to protubuf/ProtoBufDemo/assets/Texture/singleColor.png diff --git a/ProtoBufDemo/assets/Texture/singleColor.png.meta b/protubuf/ProtoBufDemo/assets/Texture/singleColor.png.meta similarity index 100% rename from ProtoBufDemo/assets/Texture/singleColor.png.meta rename to protubuf/ProtoBufDemo/assets/Texture/singleColor.png.meta diff --git a/ProtoBufDemo/creator.d.ts b/protubuf/ProtoBufDemo/creator.d.ts similarity index 100% rename from ProtoBufDemo/creator.d.ts rename to protubuf/ProtoBufDemo/creator.d.ts diff --git a/ProtoBufDemo/jsconfig.json b/protubuf/ProtoBufDemo/jsconfig.json similarity index 100% rename from ProtoBufDemo/jsconfig.json rename to protubuf/ProtoBufDemo/jsconfig.json diff --git a/ProtoBufDemo/project.json b/protubuf/ProtoBufDemo/project.json similarity index 100% rename from ProtoBufDemo/project.json rename to protubuf/ProtoBufDemo/project.json diff --git a/ProtoBufDemo/protobuf_order.txt b/protubuf/ProtoBufDemo/protobuf_order.txt similarity index 100% rename from ProtoBufDemo/protobuf_order.txt rename to protubuf/ProtoBufDemo/protobuf_order.txt diff --git a/ProtoBufDemo/settings/builder.json b/protubuf/ProtoBufDemo/settings/builder.json similarity index 100% rename from ProtoBufDemo/settings/builder.json rename to protubuf/ProtoBufDemo/settings/builder.json diff --git a/ProtoBufDemo/settings/builder.panel.json b/protubuf/ProtoBufDemo/settings/builder.panel.json similarity index 100% rename from ProtoBufDemo/settings/builder.panel.json rename to protubuf/ProtoBufDemo/settings/builder.panel.json diff --git a/ProtoBufDemo/settings/project.json b/protubuf/ProtoBufDemo/settings/project.json similarity index 100% rename from ProtoBufDemo/settings/project.json rename to protubuf/ProtoBufDemo/settings/project.json diff --git a/ProtoBufDemo/template-banner.png b/protubuf/ProtoBufDemo/template-banner.png similarity index 100% rename from ProtoBufDemo/template-banner.png rename to protubuf/ProtoBufDemo/template-banner.png diff --git a/ProtoBufDemo/template.json b/protubuf/ProtoBufDemo/template.json similarity index 100% rename from ProtoBufDemo/template.json rename to protubuf/ProtoBufDemo/template.json diff --git a/protubuf/protobuf-egret/.gitignore b/protubuf/protobuf-egret/.gitignore new file mode 100644 index 0000000..041f336 --- /dev/null +++ b/protubuf/protobuf-egret/.gitignore @@ -0,0 +1,6 @@ +node_modules +egret-project/bin-debug +egret-project/libs +egret-project/protobuf +egret-project_wxgame/js +egret-project_wxgame/resource \ No newline at end of file diff --git a/protubuf/protobuf-egret/.npmignore b/protubuf/protobuf-egret/.npmignore new file mode 100644 index 0000000..a727181 --- /dev/null +++ b/protubuf/protobuf-egret/.npmignore @@ -0,0 +1,2 @@ +egret-project +egret-project_wxgame \ No newline at end of file diff --git a/protubuf/protobuf-egret/README.md b/protubuf/protobuf-egret/README.md new file mode 100644 index 0000000..b653c14 --- /dev/null +++ b/protubuf/protobuf-egret/README.md @@ -0,0 +1,74 @@ +# egret protobuf + +## 特性 + + +1. 提供 protobuf.js 基础运行时库 +2. 提供命令行脚本,将 protofile 生成 JavaScript 代码 +3. 生成正确的 .d.ts 代码,以方便 TypeScript 项目使用 +4. 一键配置白鹭引擎的配置文件,无需开发者手动修改配置即可在项目中直接集成 +5. 本项目虽然名为 egret protobuf ,但是理论上支持所有 HTML5 游戏引擎。欢迎使用 PIXI.js , Cocos2d-js , LayaAir 等其他引擎的开发者使用本库。 + +## 原理 + +封装了 protobufjs 库及命令行。使用 protobufjs 6.8.4 的运行时库。 + +protobufjs 自身存在着 pbts 命令,虽然也可以生成 .d.ts 文件,但是在全局模式而非 ES6 module 的情况下存在一些错误,本项目致力于解决这个问题,使 protobufjs 可以在非 ES6 模块项目中(比如白鹭引擎)中也可以使用 protobufjs + +protobufjs 提供了多种使用方式,由于微信小游戏禁止 eval , new Function 等动态代码形式,所以本项目只提供了生成代码的形式,不支持通过 ```protobuf.load('awesome.proto')``` 的方式(因为这种方式也无法在微信小游戏中运行)。 + + +## 如何安装 + +``` +npm install protobufjs@6.8.4 -g +npm install @egret/protobuf -g +``` + +## 如何使用 + +``` +# 假设用户有个名为 egret-project 的白鹭项目 +cd egret-project +# 将代码和项目结构拷贝至白鹭项目中 +pb-egret add +# 将 protofile 文件放在 egret-project/protobuf/protofile 文件夹中 +pb-egret generate +# 文件将会生成到 protobuf/bundles 文件夹中 + +``` + + +## 更新日志 + +### 1.2.0 + +添加 keepCase 支持 + + +### 1.1.1 + +添加 pbconfig.json + +### 1.0.7 + +初始版本 + + +## 如何运行 Demo + +下载源代码,使用 ```egret run egret-project ```即可直接运行 demo 项目 + +## 已知问题 + +proto 文件中的每一个协议一定要从属于一个 package,否则.d.ts生成会出现错误导致 ts 文件无法正确的找到这些类 + + +## 路线图 + +* 使用 profobuf 配置文件 +* 集成 egret 构建管线 + + + + diff --git a/protubuf/protobuf-egret/dist/protobuf-library.d.ts b/protubuf/protobuf-egret/dist/protobuf-library.d.ts new file mode 100644 index 0000000..94167db --- /dev/null +++ b/protubuf/protobuf-egret/dist/protobuf-library.d.ts @@ -0,0 +1,2653 @@ +export as namespace protobuf; + +/** + * Provides common type definitions. + * Can also be used to provide additional google types or your own custom types. + * @param name Short name as in `google/protobuf/[name].proto` or full file name + * @param json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition + */ +export function common(name: string, json: { [k: string]: any }): void; + +export namespace common { + + /** Properties of a google.protobuf.Any message. */ + interface IAny { + typeUrl?: string; + bytes?: Uint8Array; + } + + /** Properties of a google.protobuf.Duration message. */ + interface IDuration { + seconds?: (number | Long); + nanos?: number; + } + + /** Properties of a google.protobuf.Timestamp message. */ + interface ITimestamp { + seconds?: (number | Long); + nanos?: number; + } + + /** Properties of a google.protobuf.Empty message. */ + interface IEmpty { + } + + /** Properties of a google.protobuf.Struct message. */ + interface IStruct { + fields?: { [k: string]: IValue }; + } + + /** Properties of a google.protobuf.Value message. */ + interface IValue { + kind?: string; + nullValue?: 0; + numberValue?: number; + stringValue?: string; + boolValue?: boolean; + structValue?: IStruct; + listValue?: IListValue; + } + + /** Properties of a google.protobuf.ListValue message. */ + interface IListValue { + values?: IValue[]; + } + + /** Properties of a google.protobuf.DoubleValue message. */ + interface IDoubleValue { + value?: number; + } + + /** Properties of a google.protobuf.FloatValue message. */ + interface IFloatValue { + value?: number; + } + + /** Properties of a google.protobuf.Int64Value message. */ + interface IInt64Value { + value?: (number | Long); + } + + /** Properties of a google.protobuf.UInt64Value message. */ + interface IUInt64Value { + value?: (number | Long); + } + + /** Properties of a google.protobuf.Int32Value message. */ + interface IInt32Value { + value?: number; + } + + /** Properties of a google.protobuf.UInt32Value message. */ + interface IUInt32Value { + value?: number; + } + + /** Properties of a google.protobuf.BoolValue message. */ + interface IBoolValue { + value?: boolean; + } + + /** Properties of a google.protobuf.StringValue message. */ + interface IStringValue { + value?: string; + } + + /** Properties of a google.protobuf.BytesValue message. */ + interface IBytesValue { + value?: Uint8Array; + } + + /** + * Gets the root definition of the specified common proto file. + * + * Bundled definitions are: + * - google/protobuf/any.proto + * - google/protobuf/duration.proto + * - google/protobuf/empty.proto + * - google/protobuf/struct.proto + * - google/protobuf/timestamp.proto + * - google/protobuf/wrappers.proto + * + * @param file Proto file name + * @returns Root definition or `null` if not defined + */ + function get(file: string): (INamespace | null); +} + +/** Runtime message from/to plain object converters. */ +export namespace converter { + + /** + * Generates a plain object to runtime message converter specific to the specified message type. + * @param mtype Message type + * @returns Codegen instance + */ + function fromObject(mtype: Type): Codegen; + + /** + * Generates a runtime message to plain object converter specific to the specified message type. + * @param mtype Message type + * @returns Codegen instance + */ + function toObject(mtype: Type): Codegen; +} + +/** + * Generates a decoder specific to the specified message type. + * @param mtype Message type + * @returns Codegen instance + */ +export function decoder(mtype: Type): Codegen; + +/** + * Generates an encoder specific to the specified message type. + * @param mtype Message type + * @returns Codegen instance + */ +export function encoder(mtype: Type): Codegen; + +/** Reflected enum. */ +export class Enum extends ReflectionObject { + + /** + * Constructs a new enum instance. + * @param name Unique name within its namespace + * @param [values] Enum values as an object, by name + * @param [options] Declared options + */ + constructor(name: string, values?: { [k: string]: number }, options?: { [k: string]: any }); + + /** Enum values by id. */ + public valuesById: { [k: number]: string }; + + /** Enum values by name. */ + public values: { [k: string]: number }; + + /** Value comment texts, if any. */ + public comments: { [k: string]: string }; + + /** Reserved ranges, if any. */ + public reserved: (number[] | string) []; + + /** + * Constructs an enum from an enum descriptor. + * @param name Enum name + * @param json Enum descriptor + * @returns Created enum + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IEnum): Enum; + + /** + * Converts this enum to an enum descriptor. + * @returns Enum descriptor + */ + public toJSON(): IEnum; + + /** + * Adds a value to this enum. + * @param name Value name + * @param id Value id + * @param [comment] Comment, if any + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a value with this name or id + */ + public add(name: string, id: number, comment?: string): Enum; + + /** + * Removes a value from this enum + * @param name Value name + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `name` is not a name of this enum + */ + public remove(name: string): Enum; + + /** + * Tests if the specified id is reserved. + * @param id Id to test + * @returns `true` if reserved, otherwise `false` + */ + public isReservedId(id: number): boolean; + + /** + * Tests if the specified name is reserved. + * @param name Name to test + * @returns `true` if reserved, otherwise `false` + */ + public isReservedName(name: string): boolean; +} + +/** Enum descriptor. */ +export interface IEnum { + + /** Enum values */ + values: { [k: string]: number }; + + /** Enum options */ + options?: { [k: string]: any }; +} + +/** Reflected message field. */ +export class Field extends FieldBase { + + /** + * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class. + * @param name Unique name within its namespace + * @param id Unique id within its namespace + * @param type Value type + * @param [rule="optional"] Field rule + * @param [extend] Extended type if different from parent + * @param [options] Declared options + */ + constructor(name: string, id: number, type: string, rule?: (string | { [k: string]: any }), extend?: (string | { [k: string]: any }), options?: { [k: string]: any }); + + /** + * Constructs a field from a field descriptor. + * @param name Field name + * @param json Field descriptor + * @returns Created field + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IField): Field; + + /** Determines whether this field is packed. Only relevant when repeated and working with proto2. */ + public readonly packed: boolean; + + /** + * Field decorator (TypeScript). + * @param fieldId Field id + * @param fieldType Field type + * @param [fieldRule="optional"] Field rule + * @param [defaultValue] Default value + * @returns Decorator function + */ + public static d(fieldId: number, fieldType: ("double" | "float" | "int32" | "uint32" | "sint32" | "fixed32" | "sfixed32" | "int64" | "uint64" | "sint64" | "fixed64" | "sfixed64" | "string" | "bool" | "bytes" | object), fieldRule?: ("optional" | "required" | "repeated"), defaultValue?: T): FieldDecorator; + + /** + * Field decorator (TypeScript). + * @param fieldId Field id + * @param fieldType Field type + * @param [fieldRule="optional"] Field rule + * @returns Decorator function + */ + public static d>(fieldId: number, fieldType: (Constructor | string), fieldRule?: ("optional" | "required" | "repeated")): FieldDecorator; +} + +/** Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions. */ +export class FieldBase extends ReflectionObject { + + /** + * Not an actual constructor. Use {@link Field} instead. + * @param name Unique name within its namespace + * @param id Unique id within its namespace + * @param type Value type + * @param [rule="optional"] Field rule + * @param [extend] Extended type if different from parent + * @param [options] Declared options + */ + constructor(name: string, id: number, type: string, rule?: (string | { [k: string]: any }), extend?: (string | { [k: string]: any }), options?: { [k: string]: any }); + + /** Field rule, if any. */ + public rule?: string; + + /** Field type. */ + public type: string; + + /** Unique field id. */ + public id: number; + + /** Extended type if different from parent. */ + public extend?: string; + + /** Whether this field is required. */ + public required: boolean; + + /** Whether this field is optional. */ + public optional: boolean; + + /** Whether this field is repeated. */ + public repeated: boolean; + + /** Whether this field is a map or not. */ + public map: boolean; + + /** Message this field belongs to. */ + public message: (Type | null); + + /** OneOf this field belongs to, if any, */ + public partOf: (OneOf | null); + + /** The field type's default value. */ + public typeDefault: any; + + /** The field's default value on prototypes. */ + public defaultValue: any; + + /** Whether this field's value should be treated as a long. */ + public long: boolean; + + /** Whether this field's value is a buffer. */ + public bytes: boolean; + + /** Resolved type if not a basic type. */ + public resolvedType: (Type | Enum | null); + + /** Sister-field within the extended type if a declaring extension field. */ + public extensionField: (Field | null); + + /** Sister-field within the declaring namespace if an extended field. */ + public declaringField: (Field | null); + + /** + * Converts this field to a field descriptor. + * @returns Field descriptor + */ + public toJSON(): IField; + + /** + * Resolves this field's type references. + * @returns `this` + * @throws {Error} If any reference cannot be resolved + */ + public resolve(): Field; +} + +/** Field descriptor. */ +export interface IField { + + /** Field rule */ + rule?: string; + + /** Field type */ + type: string; + + /** Field id */ + id: number; + + /** Field options */ + options?: { [k: string]: any }; +} + +/** Extension field descriptor. */ +export interface IExtensionField extends IField { + + /** Extended type */ + extend: string; +} + +/** + * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript). + * @param prototype Target prototype + * @param fieldName Field name + */ +type FieldDecorator = (prototype: object, fieldName: string) => void; + +/** + * A node-style callback as used by {@link load} and {@link Root#load}. + * @param error Error, if any, otherwise `null` + * @param [root] Root, if there hasn't been an error + */ +type LoadCallback = (error: (Error | null), root?: Root) => void; + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @param filename One or multiple files to load + * @param root Root namespace, defaults to create a new one if omitted. + * @param callback Callback function + * @see {@link Root#load} + */ +export function load(filename: (string | string[]), root: Root, callback: LoadCallback): void; + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @param filename One or multiple files to load + * @param callback Callback function + * @see {@link Root#load} + */ +export function load(filename: (string | string[]), callback: LoadCallback): void; + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise. + * @param filename One or multiple files to load + * @param [root] Root namespace, defaults to create a new one if omitted. + * @returns Promise + * @see {@link Root#load} + */ +export function load(filename: (string | string[]), root?: Root): Promise; + +/** + * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only). + * @param filename One or multiple files to load + * @param [root] Root namespace, defaults to create a new one if omitted. + * @returns Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + * @see {@link Root#loadSync} + */ +export function loadSync(filename: (string | string[]), root?: Root): Root; + +/** Build type, one of `"full"`, `"light"` or `"minimal"`. */ +export const build: string; + +/** Reconfigures the library according to the environment. */ +export function configure(): void; + +/** Reflected map field. */ +export class MapField extends FieldBase { + + /** + * Constructs a new map field instance. + * @param name Unique name within its namespace + * @param id Unique id within its namespace + * @param keyType Key type + * @param type Value type + * @param [options] Declared options + */ + constructor(name: string, id: number, keyType: string, type: string, options?: { [k: string]: any }); + + /** Key type. */ + public keyType: string; + + /** Resolved key type if not a basic type. */ + public resolvedKeyType: (ReflectionObject | null); + + /** + * Constructs a map field from a map field descriptor. + * @param name Field name + * @param json Map field descriptor + * @returns Created map field + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IMapField): MapField; + + /** + * Converts this map field to a map field descriptor. + * @returns Map field descriptor + */ + public toJSON(): IMapField; + + /** + * Map field decorator (TypeScript). + * @param fieldId Field id + * @param fieldKeyType Field key type + * @param fieldValueType Field value type + * @returns Decorator function + */ + public static d }>(fieldId: number, fieldKeyType: ("int32" | "uint32" | "sint32" | "fixed32" | "sfixed32" | "int64" | "uint64" | "sint64" | "fixed64" | "sfixed64" | "bool" | "string"), fieldValueType: ("double" | "float" | "int32" | "uint32" | "sint32" | "fixed32" | "sfixed32" | "int64" | "uint64" | "sint64" | "fixed64" | "sfixed64" | "bool" | "string" | "bytes" | object | Constructor<{}>)): FieldDecorator; +} + +/** Map field descriptor. */ +export interface IMapField extends IField { + + /** Key type */ + keyType: string; +} + +/** Extension map field descriptor. */ +export interface IExtensionMapField extends IMapField { + + /** Extended type */ + extend: string; +} + +/** Abstract runtime message. */ +export class Message { + + /** + * Constructs a new message instance. + * @param [properties] Properties to set + */ + constructor(properties?: Properties); + + /** Reference to the reflected type. */ + public static readonly $type: Type; + + /** Reference to the reflected type. */ + public readonly $type: Type; + + /** + * Creates a new message of this type using the specified properties. + * @param [properties] Properties to set + * @returns Message instance + */ + public static create>(this: Constructor, properties?: { [k: string]: any }): Message; + + /** + * Encodes a message of this type. + * @param message Message to encode + * @param [writer] Writer to use + * @returns Writer + */ + public static encode>(this: Constructor, message: (T | { [k: string]: any }), writer?: Writer): Writer; + + /** + * Encodes a message of this type preceeded by its length as a varint. + * @param message Message to encode + * @param [writer] Writer to use + * @returns Writer + */ + public static encodeDelimited>(this: Constructor, message: (T | { [k: string]: any }), writer?: Writer): Writer; + + /** + * Decodes a message of this type. + * @param reader Reader or buffer to decode + * @returns Decoded message + */ + public static decode>(this: Constructor, reader: (Reader | Uint8Array)): T; + + /** + * Decodes a message of this type preceeded by its length as a varint. + * @param reader Reader or buffer to decode + * @returns Decoded message + */ + public static decodeDelimited>(this: Constructor, reader: (Reader | Uint8Array)): T; + + /** + * Verifies a message of this type. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string | null); + + /** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Message instance + */ + public static fromObject>(this: Constructor, object: { [k: string]: any }): T; + + /** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param message Message instance + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject>(this: Constructor, message: T, options?: IConversionOptions): { [k: string]: any }; + + /** + * Converts this message to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; +} + +/** Reflected service method. */ +export class Method extends ReflectionObject { + + /** + * Constructs a new service method instance. + * @param name Method name + * @param type Method type, usually `"rpc"` + * @param requestType Request message type + * @param responseType Response message type + * @param [requestStream] Whether the request is streamed + * @param [responseStream] Whether the response is streamed + * @param [options] Declared options + */ + constructor(name: string, type: (string | undefined), requestType: string, responseType: string, requestStream?: (boolean | { [k: string]: any }), responseStream?: (boolean | { [k: string]: any }), options?: { [k: string]: any }); + + /** Method type. */ + public type: string; + + /** Request type. */ + public requestType: string; + + /** Whether requests are streamed or not. */ + public requestStream?: boolean; + + /** Response type. */ + public responseType: string; + + /** Whether responses are streamed or not. */ + public responseStream?: boolean; + + /** Resolved request type. */ + public resolvedRequestType: (Type | null); + + /** Resolved response type. */ + public resolvedResponseType: (Type | null); + + /** + * Constructs a method from a method descriptor. + * @param name Method name + * @param json Method descriptor + * @returns Created method + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IMethod): Method; + + /** + * Converts this method to a method descriptor. + * @returns Method descriptor + */ + public toJSON(): IMethod; +} + +/** Method descriptor. */ +export interface IMethod { + + /** Method type */ + type?: string; + + /** Request type */ + requestType: string; + + /** Response type */ + responseType: string; + + /** Whether requests are streamed */ + requestStream?: boolean; + + /** Whether responses are streamed */ + responseStream?: boolean; + + /** Method options */ + options?: { [k: string]: any }; +} + +/** Reflected namespace. */ +export class Namespace extends NamespaceBase { + + /** + * Constructs a new namespace instance. + * @param name Namespace name + * @param [options] Declared options + */ + constructor(name: string, options?: { [k: string]: any }); + + /** + * Constructs a namespace from JSON. + * @param name Namespace name + * @param json JSON object + * @returns Created namespace + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: { [k: string]: any }): Namespace; + + /** + * Converts an array of reflection objects to JSON. + * @param array Object array + * @returns JSON object or `undefined` when array is empty + */ + public static arrayToJSON(array: ReflectionObject[]): ({ [k: string]: any } | undefined); + + /** + * Tests if the specified id is reserved. + * @param reserved Array of reserved ranges and names + * @param id Id to test + * @returns `true` if reserved, otherwise `false` + */ + public static isReservedId(reserved: ((number[] | string) [] | undefined), id: number): boolean; + + /** + * Tests if the specified name is reserved. + * @param reserved Array of reserved ranges and names + * @param name Name to test + * @returns `true` if reserved, otherwise `false` + */ + public static isReservedName(reserved: ((number[] | string) [] | undefined), name: string): boolean; +} + +/** Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions. */ +export abstract class NamespaceBase extends ReflectionObject { + + /** Nested objects by name. */ + public nested?: { [k: string]: ReflectionObject }; + + /** Nested objects of this namespace as an array for iteration. */ + public readonly nestedArray: ReflectionObject[]; + + /** + * Converts this namespace to a namespace descriptor. + * @returns Namespace descriptor + */ + public toJSON(): INamespace; + + /** + * Adds nested objects to this namespace from nested object descriptors. + * @param nestedJson Any nested object descriptors + * @returns `this` + */ + public addJSON(nestedJson: { [k: string]: AnyNestedObject }): Namespace; + + /** + * Gets the nested object of the specified name. + * @param name Nested object name + * @returns The reflection object or `null` if it doesn't exist + */ + public get(name: string): (ReflectionObject | null); + + /** + * Gets the values of the nested {@link Enum|enum} of the specified name. + * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`. + * @param name Nested enum name + * @returns Enum values + * @throws {Error} If there is no such enum + */ + public getEnum(name: string): { [k: string]: number }; + + /** + * Adds a nested object to this namespace. + * @param object Nested object to add + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name + */ + public add(object: ReflectionObject): Namespace; + + /** + * Removes a nested object from this namespace. + * @param object Nested object to remove + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this namespace + */ + public remove(object: ReflectionObject): Namespace; + + /** + * Defines additial namespaces within this one if not yet existing. + * @param path Path to create + * @param [json] Nested types to create from JSON + * @returns Pointer to the last namespace created or `this` if path is empty + */ + public define(path: (string | string[]), json?: any): Namespace; + + /** + * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost. + * @returns `this` + */ + public resolveAll(): Namespace; + + /** + * Recursively looks up the reflection object matching the specified path in the scope of this namespace. + * @param path Path to look up + * @param filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc. + * @param [parentAlreadyChecked=false] If known, whether the parent has already been checked + * @returns Looked up object or `null` if none could be found + */ + public lookup(path: (string | string[]), filterTypes: (any | any[]), parentAlreadyChecked?: boolean): (ReflectionObject | null); + + /** + * Looks up the reflection object at the specified path, relative to this namespace. + * @param path Path to look up + * @param [parentAlreadyChecked=false] Whether the parent has already been checked + * @returns Looked up object or `null` if none could be found + */ + public lookup(path: (string | string[]), parentAlreadyChecked?: boolean): (ReflectionObject | null); + + /** + * Looks up the {@link Type|type} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param path Path to look up + * @returns Looked up type + * @throws {Error} If `path` does not point to a type + */ + public lookupType(path: (string | string[])): Type; + + /** + * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param path Path to look up + * @returns Looked up enum + * @throws {Error} If `path` does not point to an enum + */ + public lookupEnum(path: (string | string[])): Enum; + + /** + * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param path Path to look up + * @returns Looked up type or enum + * @throws {Error} If `path` does not point to a type or enum + */ + public lookupTypeOrEnum(path: (string | string[])): Type; + + /** + * Looks up the {@link Service|service} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param path Path to look up + * @returns Looked up service + * @throws {Error} If `path` does not point to a service + */ + public lookupService(path: (string | string[])): Service; +} + +/** Namespace descriptor. */ +export interface INamespace { + + /** Namespace options */ + options?: { [k: string]: any }; + + /** Nested object descriptors */ + nested?: { [k: string]: AnyNestedObject }; +} + +/** Any extension field descriptor. */ +type AnyExtensionField = (IExtensionField | IExtensionMapField); + +/** Any nested object descriptor. */ +type AnyNestedObject = (IEnum | IType | IService | AnyExtensionField | INamespace); + +/** Base class of all reflection objects. */ +export abstract class ReflectionObject { + + /** Options. */ + public options?: { [k: string]: any }; + + /** Unique name within its namespace. */ + public name: string; + + /** Parent namespace. */ + public parent: (Namespace | null); + + /** Whether already resolved or not. */ + public resolved: boolean; + + /** Comment text, if any. */ + public comment: (string | null); + + /** Defining file name. */ + public filename: (string | null); + + /** Reference to the root namespace. */ + public readonly root: Root; + + /** Full name including leading dot. */ + public readonly fullName: string; + + /** + * Converts this reflection object to its descriptor representation. + * @returns Descriptor + */ + public toJSON(): { [k: string]: any }; + + /** + * Called when this object is added to a parent. + * @param parent Parent added to + */ + public onAdd(parent: ReflectionObject): void; + + /** + * Called when this object is removed from a parent. + * @param parent Parent removed from + */ + public onRemove(parent: ReflectionObject): void; + + /** + * Resolves this objects type references. + * @returns `this` + */ + public resolve(): ReflectionObject; + + /** + * Gets an option value. + * @param name Option name + * @returns Option value or `undefined` if not set + */ + public getOption(name: string): any; + + /** + * Sets an option. + * @param name Option name + * @param value Option value + * @param [ifNotSet] Sets the option only if it isn't currently set + * @returns `this` + */ + public setOption(name: string, value: any, ifNotSet?: boolean): ReflectionObject; + + /** + * Sets multiple options. + * @param options Options to set + * @param [ifNotSet] Sets an option only if it isn't currently set + * @returns `this` + */ + public setOptions(options: { [k: string]: any }, ifNotSet?: boolean): ReflectionObject; + + /** + * Converts this instance to its string representation. + * @returns Class name[, space, full name] + */ + public toString(): string; +} + +/** Reflected oneof. */ +export class OneOf extends ReflectionObject { + + /** + * Constructs a new oneof instance. + * @param name Oneof name + * @param [fieldNames] Field names + * @param [options] Declared options + */ + constructor(name: string, fieldNames?: (string[] | { [k: string]: any }), options?: { [k: string]: any }); + + /** Field names that belong to this oneof. */ + public oneof: string[]; + + /** Fields that belong to this oneof as an array for iteration. */ + public readonly fieldsArray: Field[]; + + /** + * Constructs a oneof from a oneof descriptor. + * @param name Oneof name + * @param json Oneof descriptor + * @returns Created oneof + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IOneOf): OneOf; + + /** + * Converts this oneof to a oneof descriptor. + * @returns Oneof descriptor + */ + public toJSON(): IOneOf; + + /** + * Adds a field to this oneof and removes it from its current parent, if any. + * @param field Field to add + * @returns `this` + */ + public add(field: Field): OneOf; + + /** + * Removes a field from this oneof and puts it back to the oneof's parent. + * @param field Field to remove + * @returns `this` + */ + public remove(field: Field): OneOf; + + /** + * OneOf decorator (TypeScript). + * @param fieldNames Field names + * @returns Decorator function + */ + public static d(...fieldNames: string[]): OneOfDecorator; +} + +/** Oneof descriptor. */ +export interface IOneOf { + + /** Oneof field names */ + oneof: string[]; + + /** Oneof options */ + options?: { [k: string]: any }; +} + +/** + * Decorator function as returned by {@link OneOf.d} (TypeScript). + * @param prototype Target prototype + * @param oneofName OneOf name + */ +type OneOfDecorator = (prototype: object, oneofName: string) => void; + +/** + * Parses the given .proto source and returns an object with the parsed contents. + * @param source Source contents + * @param [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns Parser result + */ +export function parse(source: string, options?: IParseOptions): IParserResult; + +/** Result object returned from {@link parse}. */ +export interface IParserResult { + + /** Package name, if declared */ + package: (string | undefined); + + /** Imports, if any */ + imports: (string[] | undefined); + + /** Weak imports, if any */ + weakImports: (string[] | undefined); + + /** Syntax, if specified (either `"proto2"` or `"proto3"`) */ + syntax: (string | undefined); + + /** Populated root instance */ + root: Root; +} + +/** Options modifying the behavior of {@link parse}. */ +export interface IParseOptions { + + /** Keeps field casing instead of converting to camel case */ + keepCase?: boolean; +} + +/** + * Parses the given .proto source and returns an object with the parsed contents. + * @param source Source contents + * @param root Root to populate + * @param [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns Parser result + */ +export function parse(source: string, root: Root, options?: IParseOptions): IParserResult; + +/** Wire format reader using `Uint8Array` if available, otherwise `Array`. */ +export class Reader { + + /** + * Constructs a new reader instance using the specified buffer. + * @param buffer Buffer to read from + */ + constructor(buffer: Uint8Array); + + /** Read buffer. */ + public buf: Uint8Array; + + /** Read buffer position. */ + public pos: number; + + /** Read buffer length. */ + public len: number; + + /** + * Creates a new reader using the specified buffer. + * @param buffer Buffer to read from + * @returns A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader} + * @throws {Error} If `buffer` is not a valid buffer + */ + public static create(buffer: (Uint8Array | Buffer)): (Reader | BufferReader); + + /** + * Reads a varint as an unsigned 32 bit value. + * @returns Value read + */ + public uint32(): number; + + /** + * Reads a varint as a signed 32 bit value. + * @returns Value read + */ + public int32(): number; + + /** + * Reads a zig-zag encoded varint as a signed 32 bit value. + * @returns Value read + */ + public sint32(): number; + + /** + * Reads a varint as a signed 64 bit value. + * @returns Value read + */ + public int64(): Long; + + /** + * Reads a varint as an unsigned 64 bit value. + * @returns Value read + */ + public uint64(): Long; + + /** + * Reads a zig-zag encoded varint as a signed 64 bit value. + * @returns Value read + */ + public sint64(): Long; + + /** + * Reads a varint as a boolean. + * @returns Value read + */ + public bool(): boolean; + + /** + * Reads fixed 32 bits as an unsigned 32 bit integer. + * @returns Value read + */ + public fixed32(): number; + + /** + * Reads fixed 32 bits as a signed 32 bit integer. + * @returns Value read + */ + public sfixed32(): number; + + /** + * Reads fixed 64 bits. + * @returns Value read + */ + public fixed64(): Long; + + /** + * Reads zig-zag encoded fixed 64 bits. + * @returns Value read + */ + public sfixed64(): Long; + + /** + * Reads a float (32 bit) as a number. + * @returns Value read + */ + public float(): number; + + /** + * Reads a double (64 bit float) as a number. + * @returns Value read + */ + public double(): number; + + /** + * Reads a sequence of bytes preceeded by its length as a varint. + * @returns Value read + */ + public bytes(): Uint8Array; + + /** + * Reads a string preceeded by its byte length as a varint. + * @returns Value read + */ + public string(): string; + + /** + * Skips the specified number of bytes if specified, otherwise skips a varint. + * @param [length] Length if known, otherwise a varint is assumed + * @returns `this` + */ + public skip(length?: number): Reader; + + /** + * Skips the next element of the specified wire type. + * @param wireType Wire type received + * @returns `this` + */ + public skipType(wireType: number): Reader; +} + +/** Wire format reader using node buffers. */ +export class BufferReader extends Reader { + + /** + * Constructs a new buffer reader instance. + * @param buffer Buffer to read from + */ + constructor(buffer: Buffer); + + /** + * Reads a sequence of bytes preceeded by its length as a varint. + * @returns Value read + */ + public bytes(): Buffer; +} + +/** Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together. */ +export class Root extends NamespaceBase { + + /** + * Constructs a new root namespace instance. + * @param [options] Top level options + */ + constructor(options?: { [k: string]: any }); + + /** Deferred extension fields. */ + public deferred: Field[]; + + /** Resolved file names of loaded files. */ + public files: string[]; + + /** + * Loads a namespace descriptor into a root namespace. + * @param json Nameespace descriptor + * @param [root] Root namespace, defaults to create a new one if omitted + * @returns Root namespace + */ + public static fromJSON(json: INamespace, root?: Root): Root; + + /** + * Resolves the path of an imported file, relative to the importing origin. + * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories. + * @param origin The file name of the importing file + * @param target The file name being imported + * @returns Resolved path to `target` or `null` to skip the file + */ + public resolvePath(origin: string, target: string): (string | null); + + /** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @param filename Names of one or multiple files to load + * @param options Parse options + * @param callback Callback function + */ + public load(filename: (string | string[]), options: IParseOptions, callback: LoadCallback): void; + + /** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @param filename Names of one or multiple files to load + * @param callback Callback function + */ + public load(filename: (string | string[]), callback: LoadCallback): void; + + /** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise. + * @param filename Names of one or multiple files to load + * @param [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns Promise + */ + public load(filename: (string | string[]), options?: IParseOptions): Promise; + + /** + * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only). + * @param filename Names of one or multiple files to load + * @param [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + */ + public loadSync(filename: (string | string[]), options?: IParseOptions): Root; +} + +/** + * Named roots. + * This is where pbjs stores generated structures (the option `-r, --root` specifies a name). + * Can also be used manually to make roots available accross modules. + */ +export let roots: { [k: string]: Root }; + +/** Streaming RPC helpers. */ +export namespace rpc { + + /** + * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. + * + * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`. + * @param error Error, if any + * @param [response] Response message + */ + type ServiceMethodCallback> = (error: (Error | null), response?: TRes) => void; + + /** + * A service method part of a {@link rpc.Service} as created by {@link Service.create}. + * @param request Request message or plain object + * @param [callback] Node-style callback called with the error, if any, and the response message + * @returns Promise if `callback` has been omitted, otherwise `undefined` + */ + type ServiceMethod, TRes extends Message> = (request: (TReq | Properties), callback?: rpc.ServiceMethodCallback) => Promise>; + + /** An RPC service as returned by {@link Service#create}. */ + class Service extends util.EventEmitter { + + /** + * Constructs a new RPC service instance. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** RPC implementation. Becomes `null` once the service is ended. */ + public rpcImpl: (RPCImpl | null); + + /** Whether requests are length-delimited. */ + public requestDelimited: boolean; + + /** Whether responses are length-delimited. */ + public responseDelimited: boolean; + + /** + * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}. + * @param method Reflected or static method + * @param requestCtor Request constructor + * @param responseCtor Response constructor + * @param request Request message or plain object + * @param callback Service callback + */ + public rpcCall, TRes extends Message>(method: (Method | rpc.ServiceMethod), requestCtor: Constructor, responseCtor: Constructor, request: (TReq | Properties), callback: rpc.ServiceMethodCallback): void; + + /** + * Ends this service and emits the `end` event. + * @param [endedByRPC=false] Whether the service has been ended by the RPC implementation. + * @returns `this` + */ + public end(endedByRPC?: boolean): rpc.Service; + } +} + +/** + * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. + * @param method Reflected or static method being called + * @param requestData Request data + * @param callback Callback function + */ +type RPCImpl = (method: (Method | rpc.ServiceMethod, Message<{}>>), requestData: Uint8Array, callback: RPCImplCallback) => void; + +/** + * Node-style callback as used by {@link RPCImpl}. + * @param error Error, if any, otherwise `null` + * @param [response] Response data or `null` to signal end of stream, if there hasn't been an error + */ +type RPCImplCallback = (error: (Error | null), response?: (Uint8Array | null)) => void; + +/** Reflected service. */ +export class Service extends NamespaceBase { + + /** + * Constructs a new service instance. + * @param name Service name + * @param [options] Service options + * @throws {TypeError} If arguments are invalid + */ + constructor(name: string, options?: { [k: string]: any }); + + /** Service methods. */ + public methods: { [k: string]: Method }; + + /** + * Constructs a service from a service descriptor. + * @param name Service name + * @param json Service descriptor + * @returns Created service + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IService): Service; + + /** + * Converts this service to a service descriptor. + * @returns Service descriptor + */ + public toJSON(): IService; + + /** Methods of this service as an array for iteration. */ + public readonly methodsArray: Method[]; + + /** + * Creates a runtime service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public create(rpcImpl: RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): rpc.Service; +} + +/** Service descriptor. */ +export interface IService extends INamespace { + + /** Method descriptors */ + methods: { [k: string]: IMethod }; +} + +/** + * Gets the next token and advances. + * @returns Next token or `null` on eof + */ +type TokenizerHandleNext = () => (string | null); + +/** + * Peeks for the next token. + * @returns Next token or `null` on eof + */ +type TokenizerHandlePeek = () => (string | null); + +/** + * Pushes a token back to the stack. + * @param token Token + */ +type TokenizerHandlePush = (token: string) => void; + +/** + * Skips the next token. + * @param expected Expected token + * @param [optional=false] If optional + * @returns Whether the token matched + * @throws {Error} If the token didn't match and is not optional + */ +type TokenizerHandleSkip = (expected: string, optional?: boolean) => boolean; + +/** + * Gets the comment on the previous line or, alternatively, the line comment on the specified line. + * @param [line] Line number + * @returns Comment text or `null` if none + */ +type TokenizerHandleCmnt = (line?: number) => (string | null); + +/** Handle object returned from {@link tokenize}. */ +export interface ITokenizerHandle { + + /** Gets the next token and advances (`null` on eof) */ + next: TokenizerHandleNext; + + /** Peeks for the next token (`null` on eof) */ + peek: TokenizerHandlePeek; + + /** Pushes a token back to the stack */ + push: TokenizerHandlePush; + + /** Skips a token, returns its presence and advances or, if non-optional and not present, throws */ + skip: TokenizerHandleSkip; + + /** Gets the comment on the previous line or the line comment on the specified line, if any */ + cmnt: TokenizerHandleCmnt; + + /** Current line number */ + line: number; +} + +/** + * Tokenizes the given .proto source and returns an object with useful utility functions. + * @param source Source contents + * @returns Tokenizer handle + */ +export function tokenize(source: string): ITokenizerHandle; + +export namespace tokenize { + + /** + * Unescapes a string. + * @param str String to unescape + * @returns Unescaped string + */ + function unescape(str: string): string; +} + +/** Reflected message type. */ +export class Type extends NamespaceBase { + + /** + * Constructs a new reflected message type instance. + * @param name Message name + * @param [options] Declared options + */ + constructor(name: string, options?: { [k: string]: any }); + + /** Message fields. */ + public fields: { [k: string]: Field }; + + /** Oneofs declared within this namespace, if any. */ + public oneofs: { [k: string]: OneOf }; + + /** Extension ranges, if any. */ + public extensions: number[][]; + + /** Reserved ranges, if any. */ + public reserved: (number[] | string) []; + + /** Message fields by id. */ + public readonly fieldsById: { [k: number]: Field }; + + /** Fields of this message as an array for iteration. */ + public readonly fieldsArray: Field[]; + + /** Oneofs of this message as an array for iteration. */ + public readonly oneofsArray: OneOf[]; + + /** + * The registered constructor, if any registered, otherwise a generic constructor. + * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor. + */ + public ctor: Constructor<{}>; + + /** + * Generates a constructor function for the specified type. + * @param mtype Message type + * @returns Codegen instance + */ + public static generateConstructor(mtype: Type): Codegen; + + /** + * Creates a message type from a message type descriptor. + * @param name Message name + * @param json Message type descriptor + * @returns Created message type + */ + public static fromJSON(name: string, json: IType): Type; + + /** + * Converts this message type to a message type descriptor. + * @returns Message type descriptor + */ + public toJSON(): IType; + + /** + * Adds a nested object to this type. + * @param object Nested object to add + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id + */ + public add(object: ReflectionObject): Type; + + /** + * Removes a nested object from this type. + * @param object Nested object to remove + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this type + */ + public remove(object: ReflectionObject): Type; + + /** + * Tests if the specified id is reserved. + * @param id Id to test + * @returns `true` if reserved, otherwise `false` + */ + public isReservedId(id: number): boolean; + + /** + * Tests if the specified name is reserved. + * @param name Name to test + * @returns `true` if reserved, otherwise `false` + */ + public isReservedName(name: string): boolean; + + /** + * Creates a new message of this type using the specified properties. + * @param [properties] Properties to set + * @returns Message instance + */ + public create(properties?: { [k: string]: any }): Message<{}>; + + /** + * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}. + * @returns `this` + */ + public setup(): Type; + + /** + * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages. + * @param message Message instance or plain object + * @param [writer] Writer to encode to + * @returns writer + */ + public encode(message: (Message<{}> | { [k: string]: any }), writer?: Writer): Writer; + + /** + * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages. + * @param message Message instance or plain object + * @param [writer] Writer to encode to + * @returns writer + */ + public encodeDelimited(message: (Message<{}> | { [k: string]: any }), writer?: Writer): Writer; + + /** + * Decodes a message of this type. + * @param reader Reader or buffer to decode from + * @param [length] Length of the message, if known beforehand + * @returns Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError<{}>} If required fields are missing + */ + public decode(reader: (Reader | Uint8Array), length?: number): Message<{}>; + + /** + * Decodes a message of this type preceeded by its byte length as a varint. + * @param reader Reader or buffer to decode from + * @returns Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError} If required fields are missing + */ + public decodeDelimited(reader: (Reader | Uint8Array)): Message<{}>; + + /** + * Verifies that field values are valid and that required fields are present. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public verify(message: { [k: string]: any }): (null | string); + + /** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param object Plain object to convert + * @returns Message instance + */ + public fromObject(object: { [k: string]: any }): Message<{}>; + + /** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param message Message instance + * @param [options] Conversion options + * @returns Plain object + */ + public toObject(message: Message<{}>, options?: IConversionOptions): { [k: string]: any }; + + /** + * Type decorator (TypeScript). + * @param [typeName] Type name, defaults to the constructor's name + * @returns Decorator function + */ + public static d>(typeName?: string): TypeDecorator; +} + +/** Message type descriptor. */ +export interface IType extends INamespace { + + /** Oneof descriptors */ + oneofs?: { [k: string]: IOneOf }; + + /** Field descriptors */ + fields: { [k: string]: IField }; + + /** Extension ranges */ + extensions?: number[][]; + + /** Reserved ranges */ + reserved?: number[][]; + + /** Whether a legacy group or not */ + group?: boolean; +} + +/** Conversion options as used by {@link Type#toObject} and {@link Message.toObject}. */ +export interface IConversionOptions { + + /** + * Long conversion type. + * Valid values are `String` and `Number` (the global types). + * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library. + */ + longs?: Function; + + /** + * Enum value conversion type. + * Only valid value is `String` (the global type). + * Defaults to copy the present value, which is the numeric id. + */ + enums?: Function; + + /** + * Bytes value conversion type. + * Valid values are `Array` and (a base64 encoded) `String` (the global types). + * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser. + */ + bytes?: Function; + + /** Also sets default values on the resulting object */ + defaults?: boolean; + + /** Sets empty arrays for missing repeated fields even if `defaults=false` */ + arrays?: boolean; + + /** Sets empty objects for missing map fields even if `defaults=false` */ + objects?: boolean; + + /** Includes virtual oneof properties set to the present field's name, if any */ + oneofs?: boolean; + + /** Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings */ + json?: boolean; +} + +/** + * Decorator function as returned by {@link Type.d} (TypeScript). + * @param target Target constructor + */ +type TypeDecorator> = (target: Constructor) => void; + +/** Common type constants. */ +export namespace types { + + /** Basic type wire types. */ + const basic: { + "double": number, + "float": number, + "int32": number, + "uint32": number, + "sint32": number, + "fixed32": number, + "sfixed32": number, + "int64": number, + "uint64": number, + "sint64": number, + "fixed64": number, + "sfixed64": number, + "bool": number, + "string": number, + "bytes": number + }; + + /** Basic type defaults. */ + const defaults: { + "double": number, + "float": number, + "int32": number, + "uint32": number, + "sint32": number, + "fixed32": number, + "sfixed32": number, + "int64": number, + "uint64": number, + "sint64": number, + "fixed64": number, + "sfixed64": number, + "bool": boolean, + "string": string, + "bytes": number[], + "message": null + }; + + /** Basic long type wire types. */ + const long: { + "int64": number, + "uint64": number, + "sint64": number, + "fixed64": number, + "sfixed64": number + }; + + /** Allowed types for map keys with their associated wire type. */ + const mapKey: { + "int32": number, + "uint32": number, + "sint32": number, + "fixed32": number, + "sfixed32": number, + "int64": number, + "uint64": number, + "sint64": number, + "fixed64": number, + "sfixed64": number, + "bool": number, + "string": number + }; + + /** Allowed types for packed repeated fields with their associated wire type. */ + const packed: { + "double": number, + "float": number, + "int32": number, + "uint32": number, + "sint32": number, + "fixed32": number, + "sfixed32": number, + "int64": number, + "uint64": number, + "sint64": number, + "fixed64": number, + "sfixed64": number, + "bool": number + }; +} + +/** Constructor type. */ +export interface Constructor extends Function { + new(...params: any[]): T; prototype: T; +} + +/** Properties type. */ +type Properties = {[P in keyof T]?: T[P]}; + +/** + * Any compatible Buffer instance. + * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings. + */ +export interface Buffer extends Uint8Array { +} + +/** + * Any compatible Long instance. + * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js. + */ +export interface Long { + + /** Low bits */ + low: number; + + /** High bits */ + high: number; + + /** Whether unsigned or not */ + unsigned: boolean; +} + +/** + * A OneOf getter as returned by {@link util.oneOfGetter}. + * @returns Set field name, if any + */ +type OneOfGetter = () => (string | undefined); + +/** + * A OneOf setter as returned by {@link util.oneOfSetter}. + * @param value Field name + */ +type OneOfSetter = (value: (string | undefined)) => void; + +/** Various utility functions. */ +export namespace util { + + /** Helper class for working with the low and high bits of a 64 bit value. */ + class LongBits { + + /** + * Constructs new long bits. + * @param lo Low 32 bits, unsigned + * @param hi High 32 bits, unsigned + */ + constructor(lo: number, hi: number); + + /** Low bits. */ + public lo: number; + + /** High bits. */ + public hi: number; + + /** Zero bits. */ + public static zero: util.LongBits; + + /** Zero hash. */ + public static zeroHash: string; + + /** + * Constructs new long bits from the specified number. + * @param value Value + * @returns Instance + */ + public static fromNumber(value: number): util.LongBits; + + /** + * Constructs new long bits from a number, long or string. + * @param value Value + * @returns Instance + */ + public static from(value: (Long | number | string)): util.LongBits; + + /** + * Converts this long bits to a possibly unsafe JavaScript number. + * @param [unsigned=false] Whether unsigned or not + * @returns Possibly unsafe number + */ + public toNumber(unsigned?: boolean): number; + + /** + * Converts this long bits to a long. + * @param [unsigned=false] Whether unsigned or not + * @returns Long + */ + public toLong(unsigned?: boolean): Long; + + /** + * Constructs new long bits from the specified 8 characters long hash. + * @param hash Hash + * @returns Bits + */ + public static fromHash(hash: string): util.LongBits; + + /** + * Converts this long bits to a 8 characters long hash. + * @returns Hash + */ + public toHash(): string; + + /** + * Zig-zag encodes this long bits. + * @returns `this` + */ + public zzEncode(): util.LongBits; + + /** + * Zig-zag decodes this long bits. + * @returns `this` + */ + public zzDecode(): util.LongBits; + + /** + * Calculates the length of this longbits when encoded as a varint. + * @returns Length + */ + public length(): number; + } + + /** An immuable empty array. */ + const emptyArray: any[]; + + /** An immutable empty object. */ + const emptyObject: object; + + /** Whether running within node or not. */ + const isNode: boolean; + + /** + * Tests if the specified value is an integer. + * @param value Value to test + * @returns `true` if the value is an integer + */ + function isInteger(value: any): boolean; + + /** + * Tests if the specified value is a string. + * @param value Value to test + * @returns `true` if the value is a string + */ + function isString(value: any): boolean; + + /** + * Tests if the specified value is a non-null object. + * @param value Value to test + * @returns `true` if the value is a non-null object + */ + function isObject(value: any): boolean; + + /** + * Checks if a property on a message is considered to be present. + * This is an alias of {@link util.isSet}. + * @param obj Plain object or message instance + * @param prop Property name + * @returns `true` if considered to be present, otherwise `false` + */ + function isset(obj: object, prop: string): boolean; + + /** + * Checks if a property on a message is considered to be present. + * @param obj Plain object or message instance + * @param prop Property name + * @returns `true` if considered to be present, otherwise `false` + */ + function isSet(obj: object, prop: string): boolean; + + /** Node's Buffer class if available. */ + let Buffer: Constructor; + + /** + * Creates a new buffer of whatever type supported by the environment. + * @param [sizeOrArray=0] Buffer size or number array + * @returns Buffer + */ + function newBuffer(sizeOrArray?: (number | number[])): (Uint8Array | Buffer); + + /** Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. */ + let Array: Constructor; + + /** Long.js's Long class if available. */ + let Long: Constructor; + + /** Regular expression used to verify 2 bit (`bool`) map keys. */ + const key2Re: RegExp; + + /** Regular expression used to verify 32 bit (`int32` etc.) map keys. */ + const key32Re: RegExp; + + /** Regular expression used to verify 64 bit (`int64` etc.) map keys. */ + const key64Re: RegExp; + + /** + * Converts a number or long to an 8 characters long hash string. + * @param value Value to convert + * @returns Hash + */ + function longToHash(value: (Long | number)): string; + + /** + * Converts an 8 characters long hash string to a long or number. + * @param hash Hash + * @param [unsigned=false] Whether unsigned or not + * @returns Original value + */ + function longFromHash(hash: string, unsigned?: boolean): (Long | number); + + /** + * Merges the properties of the source object into the destination object. + * @param dst Destination object + * @param src Source object + * @param [ifNotSet=false] Merges only if the key is not already set + * @returns Destination object + */ + function merge(dst: { [k: string]: any }, src: { [k: string]: any }, ifNotSet?: boolean): { [k: string]: any }; + + /** + * Converts the first character of a string to lower case. + * @param str String to convert + * @returns Converted string + */ + function lcFirst(str: string): string; + + /** + * Creates a custom error constructor. + * @param name Error name + * @returns Custom error constructor + */ + function newError(name: string): Constructor; + + /** Error subclass indicating a protocol specifc error. */ + class ProtocolError> extends Error { + + /** + * Constructs a new protocol error. + * @param message Error message + * @param [properties] Additional properties + */ + constructor(message: string, properties?: { [k: string]: any }); + + /** So far decoded message instance. */ + public instance: Message; + } + + /** + * Builds a getter for a oneof's present field name. + * @param fieldNames Field names + * @returns Unbound getter + */ + function oneOfGetter(fieldNames: string[]): OneOfGetter; + + /** + * Builds a setter for a oneof's present field name. + * @param fieldNames Field names + * @returns Unbound setter + */ + function oneOfSetter(fieldNames: string[]): OneOfSetter; + + /** + * Default conversion options used for {@link Message#toJSON} implementations. + * + * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely: + * + * - Longs become strings + * - Enums become string keys + * - Bytes become base64 encoded strings + * - (Sub-)Messages become plain objects + * - Maps become plain objects with all string keys + * - Repeated fields become arrays + * - NaN and Infinity for float and double fields become strings + * + * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json + */ + let toJSONOptions: IConversionOptions; + + /** Node's fs module if available. */ + let fs: { [k: string]: any }; + + /** + * Converts an object's values to an array. + * @param object Object to convert + * @returns Converted array + */ + function toArray(object: { [k: string]: any }): any[]; + + /** + * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values. + * @param array Array to convert + * @returns Converted object + */ + function toObject(array: any[]): { [k: string]: any }; + + /** + * Tests whether the specified name is a reserved word in JS. + * @param name Name to test + * @returns `true` if reserved, otherwise `false` + */ + function isReserved(name: string): boolean; + + /** + * Returns a safe property accessor for the specified property name. + * @param prop Property name + * @returns Safe accessor + */ + function safeProp(prop: string): string; + + /** + * Converts the first character of a string to upper case. + * @param str String to convert + * @returns Converted string + */ + function ucFirst(str: string): string; + + /** + * Converts a string to camel case. + * @param str String to convert + * @returns Converted string + */ + function camelCase(str: string): string; + + /** + * Compares reflected fields by id. + * @param a First field + * @param b Second field + * @returns Comparison value + */ + function compareFieldsById(a: Field, b: Field): number; + + /** + * Decorator helper for types (TypeScript). + * @param ctor Constructor function + * @param [typeName] Type name, defaults to the constructor's name + * @returns Reflected type + */ + function decorateType>(ctor: Constructor, typeName?: string): Type; + + /** + * Decorator helper for enums (TypeScript). + * @param object Enum object + * @returns Reflected enum + */ + function decorateEnum(object: object): Enum; + + /** Decorator root (TypeScript). */ + let decorateRoot: Root; + + /** + * Returns a promise from a node-style callback function. + * @param fn Function to call + * @param ctx Function context + * @param params Function arguments + * @returns Promisified function + */ + function asPromise(fn: asPromiseCallback, ctx: any, ...params: any[]): Promise; + + /** A minimal base64 implementation for number arrays. */ + namespace base64 { + + /** + * Calculates the byte length of a base64 encoded string. + * @param string Base64 encoded string + * @returns Byte length + */ + function length(string: string): number; + + /** + * Encodes a buffer to a base64 encoded string. + * @param buffer Source buffer + * @param start Source start + * @param end Source end + * @returns Base64 encoded string + */ + function encode(buffer: Uint8Array, start: number, end: number): string; + + /** + * Decodes a base64 encoded string to a buffer. + * @param string Source string + * @param buffer Destination buffer + * @param offset Destination offset + * @returns Number of bytes written + * @throws {Error} If encoding is invalid + */ + function decode(string: string, buffer: Uint8Array, offset: number): number; + + /** + * Tests if the specified string appears to be base64 encoded. + * @param string String to test + * @returns `true` if probably base64 encoded, otherwise false + */ + function test(string: string): boolean; + } + + /** + * Begins generating a function. + * @param functionParams Function parameter names + * @param [functionName] Function name if not anonymous + * @returns Appender that appends code to the function's body + */ + function codegen(functionParams: string[], functionName?: string): Codegen; + + namespace codegen { + + /** When set to `true`, codegen will log generated code to console. Useful for debugging. */ + let verbose: boolean; + } + + /** + * Begins generating a function. + * @param [functionName] Function name if not anonymous + * @returns Appender that appends code to the function's body + */ + function codegen(functionName?: string): Codegen; + + /** A minimal event emitter. */ + class EventEmitter { + + /** Constructs a new event emitter instance. */ + constructor(); + + /** + * Registers an event listener. + * @param evt Event name + * @param fn Listener + * @param [ctx] Listener context + * @returns `this` + */ + public on(evt: string, fn: EventEmitterListener, ctx?: any): this; + + /** + * Removes an event listener or any matching listeners if arguments are omitted. + * @param [evt] Event name. Removes all listeners if omitted. + * @param [fn] Listener to remove. Removes all listeners of `evt` if omitted. + * @returns `this` + */ + public off(evt?: string, fn?: EventEmitterListener): this; + + /** + * Emits an event by calling its listeners with the specified arguments. + * @param evt Event name + * @param args Arguments + * @returns `this` + */ + public emit(evt: string, ...args: any[]): this; + } + + /** Reads / writes floats / doubles from / to buffers. */ + namespace float { + + /** + * Writes a 32 bit float to a buffer using little endian byte order. + * @param val Value to write + * @param buf Target buffer + * @param pos Target buffer offset + */ + function writeFloatLE(val: number, buf: Uint8Array, pos: number): void; + + /** + * Writes a 32 bit float to a buffer using big endian byte order. + * @param val Value to write + * @param buf Target buffer + * @param pos Target buffer offset + */ + function writeFloatBE(val: number, buf: Uint8Array, pos: number): void; + + /** + * Reads a 32 bit float from a buffer using little endian byte order. + * @param buf Source buffer + * @param pos Source buffer offset + * @returns Value read + */ + function readFloatLE(buf: Uint8Array, pos: number): number; + + /** + * Reads a 32 bit float from a buffer using big endian byte order. + * @param buf Source buffer + * @param pos Source buffer offset + * @returns Value read + */ + function readFloatBE(buf: Uint8Array, pos: number): number; + + /** + * Writes a 64 bit double to a buffer using little endian byte order. + * @param val Value to write + * @param buf Target buffer + * @param pos Target buffer offset + */ + function writeDoubleLE(val: number, buf: Uint8Array, pos: number): void; + + /** + * Writes a 64 bit double to a buffer using big endian byte order. + * @param val Value to write + * @param buf Target buffer + * @param pos Target buffer offset + */ + function writeDoubleBE(val: number, buf: Uint8Array, pos: number): void; + + /** + * Reads a 64 bit double from a buffer using little endian byte order. + * @param buf Source buffer + * @param pos Source buffer offset + * @returns Value read + */ + function readDoubleLE(buf: Uint8Array, pos: number): number; + + /** + * Reads a 64 bit double from a buffer using big endian byte order. + * @param buf Source buffer + * @param pos Source buffer offset + * @returns Value read + */ + function readDoubleBE(buf: Uint8Array, pos: number): number; + } + + /** + * Fetches the contents of a file. + * @param filename File path or url + * @param options Fetch options + * @param callback Callback function + */ + function fetch(filename: string, options: IFetchOptions, callback: FetchCallback): void; + + /** + * Fetches the contents of a file. + * @param path File path or url + * @param callback Callback function + */ + function fetch(path: string, callback: FetchCallback): void; + + /** + * Fetches the contents of a file. + * @param path File path or url + * @param [options] Fetch options + * @returns Promise + */ + function fetch(path: string, options?: IFetchOptions): Promise<(string | Uint8Array)>; + + /** + * Requires a module only if available. + * @param moduleName Module to require + * @returns Required module if available and not empty, otherwise `null` + */ + function inquire(moduleName: string): object; + + /** A minimal path module to resolve Unix, Windows and URL paths alike. */ + namespace path { + + /** + * Tests if the specified path is absolute. + * @param path Path to test + * @returns `true` if path is absolute + */ + function isAbsolute(path: string): boolean; + + /** + * Normalizes the specified path. + * @param path Path to normalize + * @returns Normalized path + */ + function normalize(path: string): string; + + /** + * Resolves the specified include path against the specified origin path. + * @param originPath Path to the origin file + * @param includePath Include path relative to origin path + * @param [alreadyNormalized=false] `true` if both paths are already known to be normalized + * @returns Path to the include file + */ + function resolve(originPath: string, includePath: string, alreadyNormalized?: boolean): string; + } + + /** + * A general purpose buffer pool. + * @param alloc Allocator + * @param slice Slicer + * @param [size=8192] Slab size + * @returns Pooled allocator + */ + function pool(alloc: PoolAllocator, slice: PoolSlicer, size?: number): PoolAllocator; + + /** A minimal UTF8 implementation for number arrays. */ + namespace utf8 { + + /** + * Calculates the UTF8 byte length of a string. + * @param string String + * @returns Byte length + */ + function length(string: string): number; + + /** + * Reads UTF8 bytes as a string. + * @param buffer Source buffer + * @param start Source start + * @param end Source end + * @returns String read + */ + function read(buffer: Uint8Array, start: number, end: number): string; + + /** + * Writes a string as UTF8 bytes. + * @param string Source string + * @param buffer Destination buffer + * @param offset Destination offset + * @returns Bytes written + */ + function write(string: string, buffer: Uint8Array, offset: number): number; + } +} + +/** + * Generates a verifier specific to the specified message type. + * @param mtype Message type + * @returns Codegen instance + */ +export function verifier(mtype: Type): Codegen; + +/** Wrappers for common types. */ +export const wrappers: { [k: string]: IWrapper }; + +/** + * From object converter part of an {@link IWrapper}. + * @param object Plain object + * @returns Message instance + */ +type WrapperFromObjectConverter = (this: Type, object: { [k: string]: any }) => Message<{}>; + +/** + * To object converter part of an {@link IWrapper}. + * @param message Message instance + * @param [options] Conversion options + * @returns Plain object + */ +type WrapperToObjectConverter = (this: Type, message: Message<{}>, options?: IConversionOptions) => { [k: string]: any }; + +/** Common type wrapper part of {@link wrappers}. */ +export interface IWrapper { + + /** From object converter */ + fromObject?: WrapperFromObjectConverter; + + /** To object converter */ + toObject?: WrapperToObjectConverter; +} + +/** Wire format writer using `Uint8Array` if available, otherwise `Array`. */ +export class Writer { + + /** Constructs a new writer instance. */ + constructor(); + + /** Current length. */ + public len: number; + + /** Operations head. */ + public head: object; + + /** Operations tail */ + public tail: object; + + /** Linked forked states. */ + public states: (object | null); + + /** + * Creates a new writer. + * @returns A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} + */ + public static create(): (BufferWriter | Writer); + + /** + * Allocates a buffer of the specified size. + * @param size Buffer size + * @returns Buffer + */ + public static alloc(size: number): Uint8Array; + + /** + * Writes an unsigned 32 bit value as a varint. + * @param value Value to write + * @returns `this` + */ + public uint32(value: number): Writer; + + /** + * Writes a signed 32 bit value as a varint. + * @param value Value to write + * @returns `this` + */ + public int32(value: number): Writer; + + /** + * Writes a 32 bit value as a varint, zig-zag encoded. + * @param value Value to write + * @returns `this` + */ + public sint32(value: number): Writer; + + /** + * Writes an unsigned 64 bit value as a varint. + * @param value Value to write + * @returns `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + public uint64(value: (Long | number | string)): Writer; + + /** + * Writes a signed 64 bit value as a varint. + * @param value Value to write + * @returns `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + public int64(value: (Long | number | string)): Writer; + + /** + * Writes a signed 64 bit value as a varint, zig-zag encoded. + * @param value Value to write + * @returns `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + public sint64(value: (Long | number | string)): Writer; + + /** + * Writes a boolish value as a varint. + * @param value Value to write + * @returns `this` + */ + public bool(value: boolean): Writer; + + /** + * Writes an unsigned 32 bit value as fixed 32 bits. + * @param value Value to write + * @returns `this` + */ + public fixed32(value: number): Writer; + + /** + * Writes a signed 32 bit value as fixed 32 bits. + * @param value Value to write + * @returns `this` + */ + public sfixed32(value: number): Writer; + + /** + * Writes an unsigned 64 bit value as fixed 64 bits. + * @param value Value to write + * @returns `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + public fixed64(value: (Long | number | string)): Writer; + + /** + * Writes a signed 64 bit value as fixed 64 bits. + * @param value Value to write + * @returns `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + public sfixed64(value: (Long | number | string)): Writer; + + /** + * Writes a float (32 bit). + * @param value Value to write + * @returns `this` + */ + public float(value: number): Writer; + + /** + * Writes a double (64 bit float). + * @param value Value to write + * @returns `this` + */ + public double(value: number): Writer; + + /** + * Writes a sequence of bytes. + * @param value Buffer or base64 encoded string to write + * @returns `this` + */ + public bytes(value: (Uint8Array | string)): Writer; + + /** + * Writes a string. + * @param value Value to write + * @returns `this` + */ + public string(value: string): Writer; + + /** + * Forks this writer's state by pushing it to a stack. + * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state. + * @returns `this` + */ + public fork(): Writer; + + /** + * Resets this instance to the last state. + * @returns `this` + */ + public reset(): Writer; + + /** + * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. + * @returns `this` + */ + public ldelim(): Writer; + + /** + * Finishes the write operation. + * @returns Finished buffer + */ + public finish(): Uint8Array; +} + +/** Wire format writer using node buffers. */ +export class BufferWriter extends Writer { + + /** Constructs a new buffer writer instance. */ + constructor(); + + /** + * Finishes the write operation. + * @returns Finished buffer + */ + public finish(): Buffer; + + /** + * Allocates a buffer of the specified size. + * @param size Buffer size + * @returns Buffer + */ + public static alloc(size: number): Buffer; +} + +/** + * Callback as used by {@link util.asPromise}. + * @param error Error, if any + * @param params Additional arguments + */ +type asPromiseCallback = (error: (Error | null), ...params: any[]) => void; + +/** + * Appends code to the function's body or finishes generation. + * @param [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any + * @param [formatParams] Format parameters + * @returns Itself or the generated function if finished + * @throws {Error} If format parameter counts do not match + */ +type Codegen = (formatStringOrScope?: (string | { [k: string]: any }), ...formatParams: any[]) => (Codegen | Function); + +/** + * Event listener as used by {@link util.EventEmitter}. + * @param args Arguments + */ +type EventEmitterListener = (...args: any[]) => void; + +/** + * Node-style callback as used by {@link util.fetch}. + * @param error Error, if any, otherwise `null` + * @param [contents] File contents, if there hasn't been an error + */ +type FetchCallback = (error: Error, contents?: string) => void; + +/** Options as used by {@link util.fetch}. */ +export interface IFetchOptions { + + /** Whether expecting a binary response */ + binary?: boolean; + + /** If `true`, forces the use of XMLHttpRequest */ + xhr?: boolean; +} + +/** + * An allocator as used by {@link util.pool}. + * @param size Buffer size + * @returns Buffer + */ +type PoolAllocator = (size: number) => Uint8Array; + +/** + * A slicer as used by {@link util.pool}. + * @param start Start offset + * @param end End offset + * @returns Buffer slice + */ +type PoolSlicer = (this: Uint8Array, start: number, end: number) => Uint8Array; diff --git a/protubuf/protobuf-egret/dist/protobuf-library.js b/protubuf/protobuf-egret/dist/protobuf-library.js new file mode 100644 index 0000000..8f66595 --- /dev/null +++ b/protubuf/protobuf-egret/dist/protobuf-library.js @@ -0,0 +1,8567 @@ +/*! + * protobuf.js v6.8.4 (c) 2016, daniel wirtz + * compiled thu, 04 jan 2018 21:51:39 utc + * licensed under the bsd-3-clause license + * see: https://github.com/dcodeio/protobuf.js for details + */ +(function (global, undefined) { + "use strict"; (function prelude(modules, cache, entries) { + + // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS + // sources through a conflict-free require shim and is again wrapped within an iife that + // provides a unified `global` and a minification-friendly `undefined` var plus a global + // "use strict" directive so that minification can remove the directives of each module. + + function $require(name) { + var $module = cache[name]; + if (!$module) + modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports); + return $module.exports; + } + + // Expose globally + var protobuf = global.protobuf = $require(entries[0]); + + // Be nice to AMD + if (typeof define === "function" && define.amd) + define(["long"], function (Long) { + if (Long && Long.isLong) { + protobuf.util.Long = Long; + protobuf.configure(); + } + return protobuf; + }); + + // Be nice to CommonJS + if (typeof module === "object" && module && module.exports) + module.exports = protobuf; + + })/* end of prelude */({ + 1: [function (require, module, exports) { + "use strict"; + module.exports = asPromise; + + /** + * Callback as used by {@link util.asPromise}. + * @typedef asPromiseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {...*} params Additional arguments + * @returns {undefined} + */ + + /** + * Returns a promise from a node-style callback function. + * @memberof util + * @param {asPromiseCallback} fn Function to call + * @param {*} ctx Function context + * @param {...*} params Function arguments + * @returns {Promise<*>} Promisified function + */ + function asPromise(fn, ctx/*, varargs */) { + var params = new Array(arguments.length - 1), + offset = 0, + index = 2, + pending = true; + while (index < arguments.length) + params[offset++] = arguments[index++]; + return new Promise(function executor(resolve, reject) { + params[offset] = function callback(err/*, varargs */) { + if (pending) { + pending = false; + if (err) + reject(err); + else { + var params = new Array(arguments.length - 1), + offset = 0; + while (offset < params.length) + params[offset++] = arguments[offset]; + resolve.apply(null, params); + } + } + }; + try { + fn.apply(ctx || null, params); + } catch (err) { + if (pending) { + pending = false; + reject(err); + } + } + }); + } + + }, {}], 2: [function (require, module, exports) { + "use strict"; + + /** + * A minimal base64 implementation for number arrays. + * @memberof util + * @namespace + */ + var base64 = exports; + + /** + * Calculates the byte length of a base64 encoded string. + * @param {string} string Base64 encoded string + * @returns {number} Byte length + */ + base64.length = function length(string) { + var p = string.length; + if (!p) + return 0; + var n = 0; + while (--p % 4 > 1 && string.charAt(p) === "=") + ++n; + return Math.ceil(string.length * 3) / 4 - n; + }; + + // Base64 encoding table + var b64 = new Array(64); + + // Base64 decoding table + var s64 = new Array(123); + + // 65..90, 97..122, 48..57, 43, 47 + for (var i = 0; i < 64;) + s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; + + /** + * Encodes a buffer to a base64 encoded string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} Base64 encoded string + */ + base64.encode = function encode(buffer, start, end) { + var parts = null, + chunk = []; + var i = 0, // output index + j = 0, // goto index + t; // temporary + while (start < end) { + var b = buffer[start++]; + switch (j) { + case 0: + chunk[i++] = b64[b >> 2]; + t = (b & 3) << 4; + j = 1; + break; + case 1: + chunk[i++] = b64[t | b >> 4]; + t = (b & 15) << 2; + j = 2; + break; + case 2: + chunk[i++] = b64[t | b >> 6]; + chunk[i++] = b64[b & 63]; + j = 0; + break; + } + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (j) { + chunk[i++] = b64[t]; + chunk[i++] = 61; + if (j === 1) + chunk[i++] = 61; + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); + }; + + var invalidEncoding = "invalid encoding"; + + /** + * Decodes a base64 encoded string to a buffer. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Number of bytes written + * @throws {Error} If encoding is invalid + */ + base64.decode = function decode(string, buffer, offset) { + var start = offset; + var j = 0, // goto index + t; // temporary + for (var i = 0; i < string.length;) { + var c = string.charCodeAt(i++); + if (c === 61 && j > 1) + break; + if ((c = s64[c]) === undefined) + throw Error(invalidEncoding); + switch (j) { + case 0: + t = c; + j = 1; + break; + case 1: + buffer[offset++] = t << 2 | (c & 48) >> 4; + t = c; + j = 2; + break; + case 2: + buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; + t = c; + j = 3; + break; + case 3: + buffer[offset++] = (t & 3) << 6 | c; + j = 0; + break; + } + } + if (j === 1) + throw Error(invalidEncoding); + return offset - start; + }; + + /** + * Tests if the specified string appears to be base64 encoded. + * @param {string} string String to test + * @returns {boolean} `true` if probably base64 encoded, otherwise false + */ + base64.test = function test(string) { + return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); + }; + + }, {}], 3: [function (require, module, exports) { + "use strict"; + module.exports = codegen; + + /** + * Begins generating a function. + * @memberof util + * @param {string[]} functionParams Function parameter names + * @param {string} [functionName] Function name if not anonymous + * @returns {Codegen} Appender that appends code to the function's body + */ + function codegen(functionParams, functionName) { + + /* istanbul ignore if */ + if (typeof functionParams === "string") { + functionName = functionParams; + functionParams = undefined; + } + + var body = []; + + /** + * Appends code to the function's body or finishes generation. + * @typedef Codegen + * @type {function} + * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any + * @param {...*} [formatParams] Format parameters + * @returns {Codegen|Function} Itself or the generated function if finished + * @throws {Error} If format parameter counts do not match + */ + + function Codegen(formatStringOrScope) { + // note that explicit array handling below makes this ~50% faster + + // finish the function + if (typeof formatStringOrScope !== "string") { + var source = toString(); + if (codegen.verbose) + console.log("codegen: " + source); // eslint-disable-line no-console + source = "return " + source; + if (formatStringOrScope) { + var scopeKeys = Object.keys(formatStringOrScope), + scopeParams = new Array(scopeKeys.length + 1), + scopeValues = new Array(scopeKeys.length), + scopeOffset = 0; + while (scopeOffset < scopeKeys.length) { + scopeParams[scopeOffset] = scopeKeys[scopeOffset]; + scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]]; + } + scopeParams[scopeOffset] = source; + return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func + } + return Function(source)(); // eslint-disable-line no-new-func + } + + // otherwise append to body + var formatParams = new Array(arguments.length - 1), + formatOffset = 0; + while (formatOffset < formatParams.length) + formatParams[formatOffset] = arguments[++formatOffset]; + formatOffset = 0; + formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) { + var value = formatParams[formatOffset++]; + switch ($1) { + case "d": case "f": return String(Number(value)); + case "i": return String(Math.floor(value)); + case "j": return JSON.stringify(value); + case "s": return String(value); + } + return "%"; + }); + if (formatOffset !== formatParams.length) + throw Error("parameter count mismatch"); + body.push(formatStringOrScope); + return Codegen; + } + + function toString(functionNameOverride) { + return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}"; + } + + Codegen.toString = toString; + return Codegen; + } + + /** + * Begins generating a function. + * @memberof util + * @function codegen + * @param {string} [functionName] Function name if not anonymous + * @returns {Codegen} Appender that appends code to the function's body + * @variation 2 + */ + + /** + * When set to `true`, codegen will log generated code to console. Useful for debugging. + * @name util.codegen.verbose + * @type {boolean} + */ + codegen.verbose = false; + + }, {}], 4: [function (require, module, exports) { + "use strict"; + module.exports = EventEmitter; + + /** + * Constructs a new event emitter instance. + * @classdesc A minimal event emitter. + * @memberof util + * @constructor + */ + function EventEmitter() { + + /** + * Registered listeners. + * @type {Object.} + * @private + */ + this._listeners = {}; + } + + /** + * Registers an event listener. + * @param {string} evt Event name + * @param {function} fn Listener + * @param {*} [ctx] Listener context + * @returns {util.EventEmitter} `this` + */ + EventEmitter.prototype.on = function on(evt, fn, ctx) { + (this._listeners[evt] || (this._listeners[evt] = [])).push({ + fn: fn, + ctx: ctx || this + }); + return this; + }; + + /** + * Removes an event listener or any matching listeners if arguments are omitted. + * @param {string} [evt] Event name. Removes all listeners if omitted. + * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. + * @returns {util.EventEmitter} `this` + */ + EventEmitter.prototype.off = function off(evt, fn) { + if (evt === undefined) + this._listeners = {}; + else { + if (fn === undefined) + this._listeners[evt] = []; + else { + var listeners = this._listeners[evt]; + for (var i = 0; i < listeners.length;) + if (listeners[i].fn === fn) + listeners.splice(i, 1); + else + ++i; + } + } + return this; + }; + + /** + * Emits an event by calling its listeners with the specified arguments. + * @param {string} evt Event name + * @param {...*} args Arguments + * @returns {util.EventEmitter} `this` + */ + EventEmitter.prototype.emit = function emit(evt) { + var listeners = this._listeners[evt]; + if (listeners) { + var args = [], + i = 1; + for (; i < arguments.length;) + args.push(arguments[i++]); + for (i = 0; i < listeners.length;) + listeners[i].fn.apply(listeners[i++].ctx, args); + } + return this; + }; + + }, {}], 5: [function (require, module, exports) { + "use strict"; + module.exports = fetch; + + var asPromise = require(1), + inquire = require(7); + + var fs = inquire("fs"); + + /** + * Node-style callback as used by {@link util.fetch}. + * @typedef FetchCallback + * @type {function} + * @param {?Error} error Error, if any, otherwise `null` + * @param {string} [contents] File contents, if there hasn't been an error + * @returns {undefined} + */ + + /** + * Options as used by {@link util.fetch}. + * @typedef FetchOptions + * @type {Object} + * @property {boolean} [binary=false] Whether expecting a binary response + * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest + */ + + /** + * Fetches the contents of a file. + * @memberof util + * @param {string} filename File path or url + * @param {FetchOptions} options Fetch options + * @param {FetchCallback} callback Callback function + * @returns {undefined} + */ + function fetch(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } else if (!options) + options = {}; + + if (!callback) + return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this + + // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found. + if (!options.xhr && fs && fs.readFile) + return fs.readFile(filename, function fetchReadFileCallback(err, contents) { + return err && typeof XMLHttpRequest !== "undefined" + ? fetch.xhr(filename, options, callback) + : err + ? callback(err) + : callback(null, options.binary ? contents : contents.toString("utf8")); + }); + + // use the XHR version otherwise. + return fetch.xhr(filename, options, callback); + } + + /** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchCallback} callback Callback function + * @returns {undefined} + * @variation 2 + */ + + /** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchOptions} [options] Fetch options + * @returns {Promise} Promise + * @variation 3 + */ + + /**/ + fetch.xhr = function fetch_xhr(filename, options, callback) { + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() { + + if (xhr.readyState !== 4) + return undefined; + + // local cors security errors return status 0 / empty string, too. afaik this cannot be + // reliably distinguished from an actually empty file for security reasons. feel free + // to send a pull request if you are aware of a solution. + if (xhr.status !== 0 && xhr.status !== 200) + return callback(Error("status " + xhr.status)); + + // if binary data is expected, make sure that some sort of array is returned, even if + // ArrayBuffers are not supported. the binary string fallback, however, is unsafe. + if (options.binary) { + var buffer = xhr.response; + if (!buffer) { + buffer = []; + for (var i = 0; i < xhr.responseText.length; ++i) + buffer.push(xhr.responseText.charCodeAt(i) & 255); + } + return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer); + } + return callback(null, xhr.responseText); + }; + + if (options.binary) { + // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers + if ("overrideMimeType" in xhr) + xhr.overrideMimeType("text/plain; charset=x-user-defined"); + xhr.responseType = "arraybuffer"; + } + + xhr.open("GET", filename); + xhr.send(); + }; + + }, { "1": 1, "7": 7 }], 6: [function (require, module, exports) { + "use strict"; + + module.exports = factory(factory); + + /** + * Reads / writes floats / doubles from / to buffers. + * @name util.float + * @namespace + */ + + /** + * Writes a 32 bit float to a buffer using little endian byte order. + * @name util.float.writeFloatLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + + /** + * Writes a 32 bit float to a buffer using big endian byte order. + * @name util.float.writeFloatBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + + /** + * Reads a 32 bit float from a buffer using little endian byte order. + * @name util.float.readFloatLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + + /** + * Reads a 32 bit float from a buffer using big endian byte order. + * @name util.float.readFloatBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + + /** + * Writes a 64 bit double to a buffer using little endian byte order. + * @name util.float.writeDoubleLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + + /** + * Writes a 64 bit double to a buffer using big endian byte order. + * @name util.float.writeDoubleBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + + /** + * Reads a 64 bit double from a buffer using little endian byte order. + * @name util.float.readDoubleLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + + /** + * Reads a 64 bit double from a buffer using big endian byte order. + * @name util.float.readDoubleBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + + // Factory function for the purpose of node-based testing in modified global environments + function factory(exports) { + + // float: typed array + if (typeof Float32Array !== "undefined") (function () { + + var f32 = new Float32Array([-0]), + f8b = new Uint8Array(f32.buffer), + le = f8b[3] === 128; + + function writeFloat_f32_cpy(val, buf, pos) { + f32[0] = val; + buf[pos] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + } + + function writeFloat_f32_rev(val, buf, pos) { + f32[0] = val; + buf[pos] = f8b[3]; + buf[pos + 1] = f8b[2]; + buf[pos + 2] = f8b[1]; + buf[pos + 3] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; + /* istanbul ignore next */ + exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; + + function readFloat_f32_cpy(buf, pos) { + f8b[0] = buf[pos]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + return f32[0]; + } + + function readFloat_f32_rev(buf, pos) { + f8b[3] = buf[pos]; + f8b[2] = buf[pos + 1]; + f8b[1] = buf[pos + 2]; + f8b[0] = buf[pos + 3]; + return f32[0]; + } + + /* istanbul ignore next */ + exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; + /* istanbul ignore next */ + exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; + + // float: ieee754 + })(); else (function () { + + function writeFloat_ieee754(writeUint, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos); + else if (isNaN(val)) + writeUint(2143289344, buf, pos); + else if (val > 3.4028234663852886e+38) // +-Infinity + writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); + else if (val < 1.1754943508222875e-38) // denormal + writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos); + else { + var exponent = Math.floor(Math.log(val) / Math.LN2), + mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; + writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); + } + } + + exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); + exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); + + function readFloat_ieee754(readUint, buf, pos) { + var uint = readUint(buf, pos), + sign = (uint >> 31) * 2 + 1, + exponent = uint >>> 23 & 255, + mantissa = uint & 8388607; + return exponent === 255 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 1.401298464324817e-45 * mantissa + : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); + } + + exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); + exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); + + })(); + + // double: typed array + if (typeof Float64Array !== "undefined") (function () { + + var f64 = new Float64Array([-0]), + f8b = new Uint8Array(f64.buffer), + le = f8b[7] === 128; + + function writeDouble_f64_cpy(val, buf, pos) { + f64[0] = val; + buf[pos] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + buf[pos + 4] = f8b[4]; + buf[pos + 5] = f8b[5]; + buf[pos + 6] = f8b[6]; + buf[pos + 7] = f8b[7]; + } + + function writeDouble_f64_rev(val, buf, pos) { + f64[0] = val; + buf[pos] = f8b[7]; + buf[pos + 1] = f8b[6]; + buf[pos + 2] = f8b[5]; + buf[pos + 3] = f8b[4]; + buf[pos + 4] = f8b[3]; + buf[pos + 5] = f8b[2]; + buf[pos + 6] = f8b[1]; + buf[pos + 7] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; + /* istanbul ignore next */ + exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; + + function readDouble_f64_cpy(buf, pos) { + f8b[0] = buf[pos]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + f8b[4] = buf[pos + 4]; + f8b[5] = buf[pos + 5]; + f8b[6] = buf[pos + 6]; + f8b[7] = buf[pos + 7]; + return f64[0]; + } + + function readDouble_f64_rev(buf, pos) { + f8b[7] = buf[pos]; + f8b[6] = buf[pos + 1]; + f8b[5] = buf[pos + 2]; + f8b[4] = buf[pos + 3]; + f8b[3] = buf[pos + 4]; + f8b[2] = buf[pos + 5]; + f8b[1] = buf[pos + 6]; + f8b[0] = buf[pos + 7]; + return f64[0]; + } + + /* istanbul ignore next */ + exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; + /* istanbul ignore next */ + exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; + + // double: ieee754 + })(); else (function () { + + function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) { + writeUint(0, buf, pos + off0); + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1); + } else if (isNaN(val)) { + writeUint(0, buf, pos + off0); + writeUint(2146959360, buf, pos + off1); + } else if (val > 1.7976931348623157e+308) { // +-Infinity + writeUint(0, buf, pos + off0); + writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); + } else { + var mantissa; + if (val < 2.2250738585072014e-308) { // denormal + mantissa = val / 5e-324; + writeUint(mantissa >>> 0, buf, pos + off0); + writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); + } else { + var exponent = Math.floor(Math.log(val) / Math.LN2); + if (exponent === 1024) + exponent = 1023; + mantissa = val * Math.pow(2, -exponent); + writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); + writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); + } + } + } + + exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); + exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); + + function readDouble_ieee754(readUint, off0, off1, buf, pos) { + var lo = readUint(buf, pos + off0), + hi = readUint(buf, pos + off1); + var sign = (hi >> 31) * 2 + 1, + exponent = hi >>> 20 & 2047, + mantissa = 4294967296 * (hi & 1048575) + lo; + return exponent === 2047 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 5e-324 * mantissa + : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); + } + + exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); + exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); + + })(); + + return exports; + } + + // uint helpers + + function writeUintLE(val, buf, pos) { + buf[pos] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; + } + + function writeUintBE(val, buf, pos) { + buf[pos] = val >>> 24; + buf[pos + 1] = val >>> 16 & 255; + buf[pos + 2] = val >>> 8 & 255; + buf[pos + 3] = val & 255; + } + + function readUintLE(buf, pos) { + return (buf[pos] + | buf[pos + 1] << 8 + | buf[pos + 2] << 16 + | buf[pos + 3] << 24) >>> 0; + } + + function readUintBE(buf, pos) { + return (buf[pos] << 24 + | buf[pos + 1] << 16 + | buf[pos + 2] << 8 + | buf[pos + 3]) >>> 0; + } + + }, {}], 7: [function (require, module, exports) { + "use strict"; + module.exports = inquire; + + /** + * Requires a module only if available. + * @memberof util + * @param {string} moduleName Module to require + * @returns {?Object} Required module if available and not empty, otherwise `null` + */ + function inquire(moduleName) { + try { + var mod = eval("quire".replace(/^/, "re"))(moduleName); // eslint-disable-line no-eval + if (mod && (mod.length || Object.keys(mod).length)) + return mod; + } catch (e) { } // eslint-disable-line no-empty + return null; + } + + }, {}], 8: [function (require, module, exports) { + "use strict"; + + /** + * A minimal path module to resolve Unix, Windows and URL paths alike. + * @memberof util + * @namespace + */ + var path = exports; + + var isAbsolute = + /** + * Tests if the specified path is absolute. + * @param {string} path Path to test + * @returns {boolean} `true` if path is absolute + */ + path.isAbsolute = function isAbsolute(path) { + return /^(?:\/|\w+:)/.test(path); + }; + + var normalize = + /** + * Normalizes the specified path. + * @param {string} path Path to normalize + * @returns {string} Normalized path + */ + path.normalize = function normalize(path) { + path = path.replace(/\\/g, "/") + .replace(/\/{2,}/g, "/"); + var parts = path.split("/"), + absolute = isAbsolute(path), + prefix = ""; + if (absolute) + prefix = parts.shift() + "/"; + for (var i = 0; i < parts.length;) { + if (parts[i] === "..") { + if (i > 0 && parts[i - 1] !== "..") + parts.splice(--i, 2); + else if (absolute) + parts.splice(i, 1); + else + ++i; + } else if (parts[i] === ".") + parts.splice(i, 1); + else + ++i; + } + return prefix + parts.join("/"); + }; + + /** + * Resolves the specified include path against the specified origin path. + * @param {string} originPath Path to the origin file + * @param {string} includePath Include path relative to origin path + * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized + * @returns {string} Path to the include file + */ + path.resolve = function resolve(originPath, includePath, alreadyNormalized) { + if (!alreadyNormalized) + includePath = normalize(includePath); + if (isAbsolute(includePath)) + return includePath; + if (!alreadyNormalized) + originPath = normalize(originPath); + return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath; + }; + + }, {}], 9: [function (require, module, exports) { + "use strict"; + module.exports = pool; + + /** + * An allocator as used by {@link util.pool}. + * @typedef PoolAllocator + * @type {function} + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ + + /** + * A slicer as used by {@link util.pool}. + * @typedef PoolSlicer + * @type {function} + * @param {number} start Start offset + * @param {number} end End offset + * @returns {Uint8Array} Buffer slice + * @this {Uint8Array} + */ + + /** + * A general purpose buffer pool. + * @memberof util + * @function + * @param {PoolAllocator} alloc Allocator + * @param {PoolSlicer} slice Slicer + * @param {number} [size=8192] Slab size + * @returns {PoolAllocator} Pooled allocator + */ + function pool(alloc, slice, size) { + var SIZE = size || 8192; + var MAX = SIZE >>> 1; + var slab = null; + var offset = SIZE; + return function pool_alloc(size) { + if (size < 1 || size > MAX) + return alloc(size); + if (offset + size > SIZE) { + slab = alloc(SIZE); + offset = 0; + } + var buf = slice.call(slab, offset, offset += size); + if (offset & 7) // align to 32 bit + offset = (offset | 7) + 1; + return buf; + }; + } + + }, {}], 10: [function (require, module, exports) { + "use strict"; + + /** + * A minimal UTF8 implementation for number arrays. + * @memberof util + * @namespace + */ + var utf8 = exports; + + /** + * Calculates the UTF8 byte length of a string. + * @param {string} string String + * @returns {number} Byte length + */ + utf8.length = function utf8_length(string) { + var len = 0, + c = 0; + for (var i = 0; i < string.length; ++i) { + c = string.charCodeAt(i); + if (c < 128) + len += 1; + else if (c < 2048) + len += 2; + else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { + ++i; + len += 4; + } else + len += 3; + } + return len; + }; + + /** + * Reads UTF8 bytes as a string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} String read + */ + utf8.read = function utf8_read(buffer, start, end) { + var len = end - start; + if (len < 1) + return ""; + var parts = null, + chunk = [], + i = 0, // char offset + t; // temporary + while (start < end) { + t = buffer[start++]; + if (t < 128) + chunk[i++] = t; + else if (t > 191 && t < 224) + chunk[i++] = (t & 31) << 6 | buffer[start++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000; + chunk[i++] = 0xD800 + (t >> 10); + chunk[i++] = 0xDC00 + (t & 1023); + } else + chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); + }; + + /** + * Writes a string as UTF8 bytes. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Bytes written + */ + utf8.write = function utf8_write(string, buffer, offset) { + var start = offset, + c1, // character 1 + c2; // character 2 + for (var i = 0; i < string.length; ++i) { + c1 = string.charCodeAt(i); + if (c1 < 128) { + buffer[offset++] = c1; + } else if (c1 < 2048) { + buffer[offset++] = c1 >> 6 | 192; + buffer[offset++] = c1 & 63 | 128; + } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { + c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF); + ++i; + buffer[offset++] = c1 >> 18 | 240; + buffer[offset++] = c1 >> 12 & 63 | 128; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } else { + buffer[offset++] = c1 >> 12 | 224; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } + } + return offset - start; + }; + + }, {}], 11: [function (require, module, exports) { + "use strict"; + module.exports = common; + + var commonRe = /\/|\./; + + /** + * Provides common type definitions. + * Can also be used to provide additional google types or your own custom types. + * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name + * @param {Object.} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition + * @returns {undefined} + * @property {INamespace} google/protobuf/any.proto Any + * @property {INamespace} google/protobuf/duration.proto Duration + * @property {INamespace} google/protobuf/empty.proto Empty + * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue + * @property {INamespace} google/protobuf/timestamp.proto Timestamp + * @property {INamespace} google/protobuf/wrappers.proto Wrappers + * @example + * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension) + * protobuf.common("descriptor", descriptorJson); + * + * // manually provides a custom definition (uses my.foo namespace) + * protobuf.common("my/foo/bar.proto", myFooBarJson); + */ + function common(name, json) { + if (!commonRe.test(name)) { + name = "google/protobuf/" + name + ".proto"; + json = { nested: { google: { nested: { protobuf: { nested: json } } } } }; + } + common[name] = json; + } + + // Not provided because of limited use (feel free to discuss or to provide yourself): + // + // google/protobuf/descriptor.proto + // google/protobuf/field_mask.proto + // google/protobuf/source_context.proto + // google/protobuf/type.proto + // + // Stripped and pre-parsed versions of these non-bundled files are instead available as part of + // the repository or package within the google/protobuf directory. + + common("any", { + + /** + * Properties of a google.protobuf.Any message. + * @interface IAny + * @type {Object} + * @property {string} [typeUrl] + * @property {Uint8Array} [bytes] + * @memberof common + */ + Any: { + fields: { + type_url: { + type: "string", + id: 1 + }, + value: { + type: "bytes", + id: 2 + } + } + } + }); + + var timeType; + + common("duration", { + + /** + * Properties of a google.protobuf.Duration message. + * @interface IDuration + * @type {Object} + * @property {number|Long} [seconds] + * @property {number} [nanos] + * @memberof common + */ + Duration: timeType = { + fields: { + seconds: { + type: "int64", + id: 1 + }, + nanos: { + type: "int32", + id: 2 + } + } + } + }); + + common("timestamp", { + + /** + * Properties of a google.protobuf.Timestamp message. + * @interface ITimestamp + * @type {Object} + * @property {number|Long} [seconds] + * @property {number} [nanos] + * @memberof common + */ + Timestamp: timeType + }); + + common("empty", { + + /** + * Properties of a google.protobuf.Empty message. + * @interface IEmpty + * @memberof common + */ + Empty: { + fields: {} + } + }); + + common("struct", { + + /** + * Properties of a google.protobuf.Struct message. + * @interface IStruct + * @type {Object} + * @property {Object.} [fields] + * @memberof common + */ + Struct: { + fields: { + fields: { + keyType: "string", + type: "Value", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.Value message. + * @interface IValue + * @type {Object} + * @property {string} [kind] + * @property {0} [nullValue] + * @property {number} [numberValue] + * @property {string} [stringValue] + * @property {boolean} [boolValue] + * @property {IStruct} [structValue] + * @property {IListValue} [listValue] + * @memberof common + */ + Value: { + oneofs: { + kind: { + oneof: [ + "nullValue", + "numberValue", + "stringValue", + "boolValue", + "structValue", + "listValue" + ] + } + }, + fields: { + nullValue: { + type: "NullValue", + id: 1 + }, + numberValue: { + type: "double", + id: 2 + }, + stringValue: { + type: "string", + id: 3 + }, + boolValue: { + type: "bool", + id: 4 + }, + structValue: { + type: "Struct", + id: 5 + }, + listValue: { + type: "ListValue", + id: 6 + } + } + }, + + NullValue: { + values: { + NULL_VALUE: 0 + } + }, + + /** + * Properties of a google.protobuf.ListValue message. + * @interface IListValue + * @type {Object} + * @property {Array.} [values] + * @memberof common + */ + ListValue: { + fields: { + values: { + rule: "repeated", + type: "Value", + id: 1 + } + } + } + }); + + common("wrappers", { + + /** + * Properties of a google.protobuf.DoubleValue message. + * @interface IDoubleValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + DoubleValue: { + fields: { + value: { + type: "double", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.FloatValue message. + * @interface IFloatValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + FloatValue: { + fields: { + value: { + type: "float", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.Int64Value message. + * @interface IInt64Value + * @type {Object} + * @property {number|Long} [value] + * @memberof common + */ + Int64Value: { + fields: { + value: { + type: "int64", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.UInt64Value message. + * @interface IUInt64Value + * @type {Object} + * @property {number|Long} [value] + * @memberof common + */ + UInt64Value: { + fields: { + value: { + type: "uint64", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.Int32Value message. + * @interface IInt32Value + * @type {Object} + * @property {number} [value] + * @memberof common + */ + Int32Value: { + fields: { + value: { + type: "int32", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.UInt32Value message. + * @interface IUInt32Value + * @type {Object} + * @property {number} [value] + * @memberof common + */ + UInt32Value: { + fields: { + value: { + type: "uint32", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.BoolValue message. + * @interface IBoolValue + * @type {Object} + * @property {boolean} [value] + * @memberof common + */ + BoolValue: { + fields: { + value: { + type: "bool", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.StringValue message. + * @interface IStringValue + * @type {Object} + * @property {string} [value] + * @memberof common + */ + StringValue: { + fields: { + value: { + type: "string", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.BytesValue message. + * @interface IBytesValue + * @type {Object} + * @property {Uint8Array} [value] + * @memberof common + */ + BytesValue: { + fields: { + value: { + type: "bytes", + id: 1 + } + } + } + }); + + /** + * Gets the root definition of the specified common proto file. + * + * Bundled definitions are: + * - google/protobuf/any.proto + * - google/protobuf/duration.proto + * - google/protobuf/empty.proto + * - google/protobuf/struct.proto + * - google/protobuf/timestamp.proto + * - google/protobuf/wrappers.proto + * + * @param {string} file Proto file name + * @returns {INamespace|null} Root definition or `null` if not defined + */ + common.get = function get(file) { + return common[file] || null; + }; + + }, {}], 12: [function (require, module, exports) { + "use strict"; + /** + * Runtime message from/to plain object converters. + * @namespace + */ + var converter = exports; + + var Enum = require(15), + util = require(37); + + /** + * Generates a partial value fromObject conveter. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {number} fieldIndex Field index + * @param {string} prop Property reference + * @returns {Codegen} Codegen instance + * @ignore + */ + function genValuePartial_fromObject(gen, field, fieldIndex, prop) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { + gen + ("switch(d%s){", prop); + for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) { + if (field.repeated && values[keys[i]] === field.typeDefault) gen + ("default:"); + gen + ("case%j:", keys[i]) + ("case %i:", values[keys[i]]) + ("m%s=%j", prop, values[keys[i]]) + ("break"); + } gen + ("}"); + } else gen + ("if(typeof d%s!==\"object\")", prop) + ("throw TypeError(%j)", field.fullName + ": object expected") + ("m%s=types[%i].fromObject(d%s)", prop, fieldIndex, prop); + } else { + var isUnsigned = false; + switch (field.type) { + case "double": + case "float": gen + ("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity" + break; + case "uint32": + case "fixed32": gen + ("m%s=d%s>>>0", prop, prop); + break; + case "int32": + case "sint32": + case "sfixed32": gen + ("m%s=d%s|0", prop, prop); + break; + case "uint64": + isUnsigned = true; + // eslint-disable-line no-fallthrough + case "int64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(util.Long)") + ("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned) + ("else if(typeof d%s===\"string\")", prop) + ("m%s=parseInt(d%s,10)", prop, prop) + ("else if(typeof d%s===\"number\")", prop) + ("m%s=d%s", prop, prop) + ("else if(typeof d%s===\"object\")", prop) + ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : ""); + break; + case "bytes": gen + ("if(typeof d%s===\"string\")", prop) + ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop) + ("else if(d%s.length)", prop) + ("m%s=d%s", prop, prop); + break; + case "string": gen + ("m%s=String(d%s)", prop, prop); + break; + case "bool": gen + ("m%s=Boolean(d%s)", prop, prop); + break; + /* default: gen + ("m%s=d%s", prop, prop); + break; */ + } + } + return gen; + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ + } + + /** + * Generates a plain object to runtime message converter specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ + converter.fromObject = function fromObject(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var fields = mtype.fieldsArray; + var gen = util.codegen(["d"], mtype.name + "$fromObject") + ("if(d instanceof this.ctor)") + ("return d"); + if (!fields.length) return gen + ("return new this.ctor"); + gen + ("var m=new this.ctor"); + for (var i = 0; i < fields.length; ++i) { + var field = fields[i].resolve(), + prop = util.safeProp(field.name); + + // Map fields + if (field.map) { + gen + ("if(d%s){", prop) + ("if(typeof d%s!==\"object\")", prop) + ("throw TypeError(%j)", field.fullName + ": object expected") + ("m%s={}", prop) + ("for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true" : "", prop); + break; + case "bytes": gen + ("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop); + break; + default: gen + ("d%s=m%s", prop, prop); + break; + } + } + return gen; + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ + } + + /** + * Generates a runtime message to plain object converter specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ + converter.toObject = function toObject(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById); + if (!fields.length) + return util.codegen()("return {}"); + var gen = util.codegen(["m", "o"], mtype.name + "$toObject") + ("if(!o)") + ("o={}") + ("var d={}"); + + var repeatedFields = [], + mapFields = [], + normalFields = [], + i = 0; + for (; i < fields.length; ++i) + if (!fields[i].partOf) + (fields[i].resolve().repeated ? repeatedFields + : fields[i].map ? mapFields + : normalFields).push(fields[i]); + + if (repeatedFields.length) { + gen + ("if(o.arrays||o.defaults){"); + for (i = 0; i < repeatedFields.length; ++i) gen + ("d%s=[]", util.safeProp(repeatedFields[i].name)); + gen + ("}"); + } + + if (mapFields.length) { + gen + ("if(o.objects||o.defaults){"); + for (i = 0; i < mapFields.length; ++i) gen + ("d%s={}", util.safeProp(mapFields[i].name)); + gen + ("}"); + } + + if (normalFields.length) { + gen + ("if(o.defaults){"); + for (i = 0; i < normalFields.length; ++i) { + var field = normalFields[i], + prop = util.safeProp(field.name); + if (field.resolvedType instanceof Enum) gen + ("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault); + else if (field.long) gen + ("if(util.Long){") + ("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned) + ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop) + ("}else") + ("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber()); + else if (field.bytes) gen + ("d%s=o.bytes===String?%j:%s", prop, String.fromCharCode.apply(String, field.typeDefault), "[" + Array.prototype.slice.call(field.typeDefault).join(",") + "]"); + else gen + ("d%s=%j", prop, field.typeDefault); // also messages (=null) + } gen + ("}"); + } + var hasKs2 = false; + for (i = 0; i < fields.length; ++i) { + var field = fields[i], + index = mtype._fieldsArray.indexOf(field), + prop = util.safeProp(field.name); + if (field.map) { + if (!hasKs2) { + hasKs2 = true; gen + ("var ks2"); + } gen + ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop) + ("d%s={}", prop) + ("for(var j=0;j>>3){"); + + var i = 0; + for (; i < /* initializes */ mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), + type = field.resolvedType instanceof Enum ? "int32" : field.type, + ref = "m" + util.safeProp(field.name); gen + ("case %i:", field.id); + + // Map fields + if (field.map) { + gen + ("r.skip().pos++") // assumes id 1 + key wireType + ("if(%s===util.emptyObject)", ref) + ("%s={}", ref) + ("k=r.%s()", field.keyType) + ("r.pos++"); // assumes id 2 + value wireType + if (types.long[field.keyType] !== undefined) { + if (types.basic[type] === undefined) gen + ("%s[typeof k===\"object\"?util.longToHash(k):k]=types[%i].decode(r,r.uint32())", ref, i); // can't be groups + else gen + ("%s[typeof k===\"object\"?util.longToHash(k):k]=r.%s()", ref, type); + } else { + if (types.basic[type] === undefined) gen + ("%s[k]=types[%i].decode(r,r.uint32())", ref, i); // can't be groups + else gen + ("%s[k]=r.%s()", ref, type); + } + + // Repeated fields + } else if (field.repeated) { + gen + + ("if(!(%s&&%s.length))", ref, ref) + ("%s=[]", ref); + + // Packable (always check for forward and backward compatiblity) + if (types.packed[type] !== undefined) gen + ("if((t&7)===2){") + ("var c2=r.uint32()+r.pos") + ("while(r.pos>> 0, (field.id << 3 | 4) >>> 0) + : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0); + } + + /** + * Generates an encoder specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ + function encoder(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var gen = util.codegen(["m", "w"], mtype.name + "$encode") + ("if(!w)") + ("w=Writer.create()"); + + var i, ref; + + // "when a message is serialized its known fields should be written sequentially by field number" + var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById); + + for (var i = 0; i < fields.length; ++i) { + var field = fields[i].resolve(), + index = mtype._fieldsArray.indexOf(field), + type = field.resolvedType instanceof Enum ? "int32" : field.type, + wireType = types.basic[type]; + ref = "m" + util.safeProp(field.name); + + // Map fields + if (field.map) { + gen + ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name) // !== undefined && !== null + ("for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType); + if (wireType === undefined) gen + ("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); // can't be groups + else gen + (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref); + gen + ("}") + ("}"); + + // Repeated fields + } else if (field.repeated) { + gen + ("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null + + // Packed repeated + if (field.packed && types.packed[type] !== undefined) { + gen + + ("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0) + ("for(var i=0;i<%s.length;++i)", ref) + ("w.%s(%s[i])", type, ref) + ("w.ldelim()"); + + // Non-packed + } else { + gen + + ("for(var i=0;i<%s.length;++i)", ref); + if (wireType === undefined) + genTypePartial(gen, field, index, ref + "[i]"); + else gen + ("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref); + + } gen + ("}"); + + // Non-repeated + } else { + if (field.optional) gen + ("if(%s!=null&&m.hasOwnProperty(%j))", ref, field.name); // !== undefined && !== null + + if (wireType === undefined) + genTypePartial(gen, field, index, ref); + else gen + ("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref); + + } + } + + return gen + ("return w"); + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ + } + }, { "15": 15, "36": 36, "37": 37 }], 15: [function (require, module, exports) { + "use strict"; + module.exports = Enum; + + // extends ReflectionObject + var ReflectionObject = require(24); + ((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum"; + + var Namespace = require(23), + util = require(37); + + /** + * Constructs a new enum instance. + * @classdesc Reflected enum. + * @extends ReflectionObject + * @constructor + * @param {string} name Unique name within its namespace + * @param {Object.} [values] Enum values as an object, by name + * @param {Object.} [options] Declared options + */ + function Enum(name, values, options) { + ReflectionObject.call(this, name, options); + + if (values && typeof values !== "object") + throw TypeError("values must be an object"); + + /** + * Enum values by id. + * @type {Object.} + */ + this.valuesById = {}; + + /** + * Enum values by name. + * @type {Object.} + */ + this.values = Object.create(this.valuesById); // toJSON, marker + + /** + * Value comment texts, if any. + * @type {Object.} + */ + this.comments = {}; + + /** + * Reserved ranges, if any. + * @type {Array.} + */ + this.reserved = undefined; // toJSON + + // Note that values inherit valuesById on their prototype which makes them a TypeScript- + // compatible enum. This is used by pbts to write actual enum definitions that work for + // static and reflection code alike instead of emitting generic object definitions. + + if (values) + for (var keys = Object.keys(values), i = 0; i < keys.length; ++i) + if (typeof values[keys[i]] === "number") // use forward entries only + this.valuesById[this.values[keys[i]] = values[keys[i]]] = keys[i]; + } + + /** + * Enum descriptor. + * @interface IEnum + * @property {Object.} values Enum values + * @property {Object.} [options] Enum options + */ + + /** + * Constructs an enum from an enum descriptor. + * @param {string} name Enum name + * @param {IEnum} json Enum descriptor + * @returns {Enum} Created enum + * @throws {TypeError} If arguments are invalid + */ + Enum.fromJSON = function fromJSON(name, json) { + var enm = new Enum(name, json.values, json.options); + enm.reserved = json.reserved; + return enm; + }; + + /** + * Converts this enum to an enum descriptor. + * @returns {IEnum} Enum descriptor + */ + Enum.prototype.toJSON = function toJSON() { + return util.toObject([ + "options", this.options, + "values", this.values, + "reserved", this.reserved && this.reserved.length ? this.reserved : undefined + ]); + }; + + /** + * Adds a value to this enum. + * @param {string} name Value name + * @param {number} id Value id + * @param {string} [comment] Comment, if any + * @returns {Enum} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a value with this name or id + */ + Enum.prototype.add = function add(name, id, comment) { + // utilized by the parser but not by .fromJSON + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + if (!util.isInteger(id)) + throw TypeError("id must be an integer"); + + if (this.values[name] !== undefined) + throw Error("duplicate name '" + name + "' in " + this); + + if (this.isReservedId(id)) + throw Error("id " + id + " is reserved in " + this); + + if (this.isReservedName(name)) + throw Error("name '" + name + "' is reserved in " + this); + + if (this.valuesById[id] !== undefined) { + if (!(this.options && this.options.allow_alias)) + throw Error("duplicate id " + id + " in " + this); + this.values[name] = id; + } else + this.valuesById[this.values[name] = id] = name; + + this.comments[name] = comment || null; + return this; + }; + + /** + * Removes a value from this enum + * @param {string} name Value name + * @returns {Enum} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `name` is not a name of this enum + */ + Enum.prototype.remove = function remove(name) { + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + var val = this.values[name]; + if (val == null) + throw Error("name '" + name + "' does not exist in " + this); + + delete this.valuesById[val]; + delete this.values[name]; + delete this.comments[name]; + + return this; + }; + + /** + * Tests if the specified id is reserved. + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ + Enum.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); + }; + + /** + * Tests if the specified name is reserved. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ + Enum.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); + }; + + }, { "23": 23, "24": 24, "37": 37 }], 16: [function (require, module, exports) { + "use strict"; + module.exports = Field; + + // extends ReflectionObject + var ReflectionObject = require(24); + ((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field"; + + var Enum = require(15), + types = require(36), + util = require(37); + + var Type; // cyclic + + var ruleRe = /^required|optional|repeated$/; + + /** + * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class. + * @name Field + * @classdesc Reflected message field. + * @extends FieldBase + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} type Value type + * @param {string|Object.} [rule="optional"] Field rule + * @param {string|Object.} [extend] Extended type if different from parent + * @param {Object.} [options] Declared options + */ + + /** + * Constructs a field from a field descriptor. + * @param {string} name Field name + * @param {IField} json Field descriptor + * @returns {Field} Created field + * @throws {TypeError} If arguments are invalid + */ + Field.fromJSON = function fromJSON(name, json) { + return new Field(name, json.id, json.type, json.rule, json.extend, json.options); + }; + + /** + * Not an actual constructor. Use {@link Field} instead. + * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions. + * @exports FieldBase + * @extends ReflectionObject + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} type Value type + * @param {string|Object.} [rule="optional"] Field rule + * @param {string|Object.} [extend] Extended type if different from parent + * @param {Object.} [options] Declared options + */ + function Field(name, id, type, rule, extend, options) { + + if (util.isObject(rule)) { + options = rule; + rule = extend = undefined; + } else if (util.isObject(extend)) { + options = extend; + extend = undefined; + } + + ReflectionObject.call(this, name, options); + + if (!util.isInteger(id) || id < 0) + throw TypeError("id must be a non-negative integer"); + + if (!util.isString(type)) + throw TypeError("type must be a string"); + + if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase())) + throw TypeError("rule must be a string rule"); + + if (extend !== undefined && !util.isString(extend)) + throw TypeError("extend must be a string"); + + /** + * Field rule, if any. + * @type {string|undefined} + */ + this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON + + /** + * Field type. + * @type {string} + */ + this.type = type; // toJSON + + /** + * Unique field id. + * @type {number} + */ + this.id = id; // toJSON, marker + + /** + * Extended type if different from parent. + * @type {string|undefined} + */ + this.extend = extend || undefined; // toJSON + + /** + * Whether this field is required. + * @type {boolean} + */ + this.required = rule === "required"; + + /** + * Whether this field is optional. + * @type {boolean} + */ + this.optional = !this.required; + + /** + * Whether this field is repeated. + * @type {boolean} + */ + this.repeated = rule === "repeated"; + + /** + * Whether this field is a map or not. + * @type {boolean} + */ + this.map = false; + + /** + * Message this field belongs to. + * @type {Type|null} + */ + this.message = null; + + /** + * OneOf this field belongs to, if any, + * @type {OneOf|null} + */ + this.partOf = null; + + /** + * The field type's default value. + * @type {*} + */ + this.typeDefault = null; + + /** + * The field's default value on prototypes. + * @type {*} + */ + this.defaultValue = null; + + /** + * Whether this field's value should be treated as a long. + * @type {boolean} + */ + this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false; + + /** + * Whether this field's value is a buffer. + * @type {boolean} + */ + this.bytes = type === "bytes"; + + /** + * Resolved type if not a basic type. + * @type {Type|Enum|null} + */ + this.resolvedType = null; + + /** + * Sister-field within the extended type if a declaring extension field. + * @type {Field|null} + */ + this.extensionField = null; + + /** + * Sister-field within the declaring namespace if an extended field. + * @type {Field|null} + */ + this.declaringField = null; + + /** + * Internally remembers whether this field is packed. + * @type {boolean|null} + * @private + */ + this._packed = null; + } + + /** + * Determines whether this field is packed. Only relevant when repeated and working with proto2. + * @name Field#packed + * @type {boolean} + * @readonly + */ + Object.defineProperty(Field.prototype, "packed", { + get: function () { + // defaults to packed=true if not explicity set to false + if (this._packed === null) + this._packed = this.getOption("packed") !== false; + return this._packed; + } + }); + + /** + * @override + */ + Field.prototype.setOption = function setOption(name, value, ifNotSet) { + if (name === "packed") // clear cached before setting + this._packed = null; + return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet); + }; + + /** + * Field descriptor. + * @interface IField + * @property {string} [rule="optional"] Field rule + * @property {string} type Field type + * @property {number} id Field id + * @property {Object.} [options] Field options + */ + + /** + * Extension field descriptor. + * @interface IExtensionField + * @extends IField + * @property {string} extend Extended type + */ + + /** + * Converts this field to a field descriptor. + * @returns {IField} Field descriptor + */ + Field.prototype.toJSON = function toJSON() { + return util.toObject([ + "rule", this.rule !== "optional" && this.rule || undefined, + "type", this.type, + "id", this.id, + "extend", this.extend, + "options", this.options + ]); + }; + + /** + * Resolves this field's type references. + * @returns {Field} `this` + * @throws {Error} If any reference cannot be resolved + */ + Field.prototype.resolve = function resolve() { + + if (this.resolved) + return this; + + if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it + this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type); + if (this.resolvedType instanceof Type) + this.typeDefault = null; + else // instanceof Enum + this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values) [0]]; // first defined + } + + // use explicitly set default value if present + if (this.options && this.options["default"] != null) { + this.typeDefault = this.options["default"]; + if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string") + this.typeDefault = this.resolvedType.values[this.typeDefault]; + } + + // remove unnecessary options + if (this.options) { + if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum)) + delete this.options.packed; + if (!Object.keys(this.options).length) + this.options = undefined; + } + + // convert to internal data type if necesssary + if (this.long) { + this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u"); + + /* istanbul ignore else */ + if (Object.freeze) + Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it) + + } else if (this.bytes && typeof this.typeDefault === "string") { + var buf; + if (util.base64.test(this.typeDefault)) + util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0); + else + util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0); + this.typeDefault = buf; + } + + // take special care of maps and repeated fields + if (this.map) + this.defaultValue = util.emptyObject; + else if (this.repeated) + this.defaultValue = util.emptyArray; + else + this.defaultValue = this.typeDefault; + + // ensure proper value on prototype + if (this.parent instanceof Type) + this.parent.ctor.prototype[this.name] = this.defaultValue; + + return ReflectionObject.prototype.resolve.call(this); + }; + + /** + * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript). + * @typedef FieldDecorator + * @type {function} + * @param {Object} prototype Target prototype + * @param {string} fieldName Field name + * @returns {undefined} + */ + + /** + * Field decorator (TypeScript). + * @name Field.d + * @function + * @param {number} fieldId Field id + * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|Object} fieldType Field type + * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule + * @param {T} [defaultValue] Default value + * @returns {FieldDecorator} Decorator function + * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[] + */ + Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) { + + // submessage: decorate the submessage and use its name as the type + if (typeof fieldType === "function") + fieldType = util.decorateType(fieldType).name; + + // enum reference: create a reflected copy of the enum and keep reuseing it + else if (fieldType && typeof fieldType === "object") + fieldType = util.decorateEnum(fieldType).name; + + return function fieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor) + .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue })); + }; + }; + + /** + * Field decorator (TypeScript). + * @name Field.d + * @function + * @param {number} fieldId Field id + * @param {Constructor|string} fieldType Field type + * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule + * @returns {FieldDecorator} Decorator function + * @template T extends Message + * @variation 2 + */ + // like Field.d but without a default value + + Field._configure = function configure(Type_) { + Type = Type_; + }; + + }, { "15": 15, "24": 24, "36": 36, "37": 37 }], 17: [function (require, module, exports) { + "use strict"; + var protobuf = module.exports = require(18); + + protobuf.build = "light"; + + /** + * A node-style callback as used by {@link load} and {@link Root#load}. + * @typedef LoadCallback + * @type {function} + * @param {Error|null} error Error, if any, otherwise `null` + * @param {Root} [root] Root, if there hasn't been an error + * @returns {undefined} + */ + + /** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @param {string|string[]} filename One or multiple files to load + * @param {Root} root Root namespace, defaults to create a new one if omitted. + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @see {@link Root#load} + */ + function load(filename, root, callback) { + if (typeof root === "function") { + callback = root; + root = new protobuf.Root(); + } else if (!root) + root = new protobuf.Root(); + return root.load(filename, callback); + } + + /** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @name load + * @function + * @param {string|string[]} filename One or multiple files to load + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @see {@link Root#load} + * @variation 2 + */ + // function load(filename:string, callback:LoadCallback):undefined + + /** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise. + * @name load + * @function + * @param {string|string[]} filename One or multiple files to load + * @param {Root} [root] Root namespace, defaults to create a new one if omitted. + * @returns {Promise} Promise + * @see {@link Root#load} + * @variation 3 + */ + // function load(filename:string, [root:Root]):Promise + + protobuf.load = load; + + /** + * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only). + * @param {string|string[]} filename One or multiple files to load + * @param {Root} [root] Root namespace, defaults to create a new one if omitted. + * @returns {Root} Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + * @see {@link Root#loadSync} + */ + function loadSync(filename, root) { + if (!root) + root = new protobuf.Root(); + return root.loadSync(filename); + } + + protobuf.loadSync = loadSync; + + // Serialization + protobuf.encoder = require(14); + protobuf.decoder = require(13); + protobuf.verifier = require(40); + protobuf.converter = require(12); + + // Reflection + protobuf.ReflectionObject = require(24); + protobuf.Namespace = require(23); + protobuf.Root = require(29); + protobuf.Enum = require(15); + protobuf.Type = require(35); + protobuf.Field = require(16); + protobuf.OneOf = require(25); + protobuf.MapField = require(20); + protobuf.Service = require(33); + protobuf.Method = require(22); + + // Runtime + protobuf.Message = require(21); + protobuf.wrappers = require(41); + + // Utility + protobuf.types = require(36); + protobuf.util = require(37); + + // Configure reflection + protobuf.ReflectionObject._configure(protobuf.Root); + protobuf.Namespace._configure(protobuf.Type, protobuf.Service); + protobuf.Root._configure(protobuf.Type); + protobuf.Field._configure(protobuf.Type); + + }, { "12": 12, "13": 13, "14": 14, "15": 15, "16": 16, "18": 18, "20": 20, "21": 21, "22": 22, "23": 23, "24": 24, "25": 25, "29": 29, "33": 33, "35": 35, "36": 36, "37": 37, "40": 40, "41": 41 }], 18: [function (require, module, exports) { + "use strict"; + var protobuf = exports; + + /** + * Build type, one of `"full"`, `"light"` or `"minimal"`. + * @name build + * @type {string} + * @const + */ + protobuf.build = "minimal"; + + // Serialization + protobuf.Writer = require(42); + protobuf.BufferWriter = require(43); + protobuf.Reader = require(27); + protobuf.BufferReader = require(28); + + // Utility + protobuf.util = require(39); + protobuf.rpc = require(31); + protobuf.roots = require(30); + protobuf.configure = configure; + + /* istanbul ignore next */ + /** + * Reconfigures the library according to the environment. + * @returns {undefined} + */ + function configure() { + protobuf.Reader._configure(protobuf.BufferReader); + protobuf.util._configure(); + } + + // Configure serialization + protobuf.Writer._configure(protobuf.BufferWriter); + configure(); + + }, { "27": 27, "28": 28, "30": 30, "31": 31, "39": 39, "42": 42, "43": 43 }], 19: [function (require, module, exports) { + "use strict"; + var protobuf = module.exports = require(17); + + protobuf.build = "full"; + + // Parser + protobuf.tokenize = require(34); + protobuf.parse = require(26); + protobuf.common = require(11); + + // Configure parser + protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common); + + }, { "11": 11, "17": 17, "26": 26, "34": 34 }], 20: [function (require, module, exports) { + "use strict"; + module.exports = MapField; + + // extends Field + var Field = require(16); + ((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField"; + + var types = require(36), + util = require(37); + + /** + * Constructs a new map field instance. + * @classdesc Reflected map field. + * @extends FieldBase + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} keyType Key type + * @param {string} type Value type + * @param {Object.} [options] Declared options + */ + function MapField(name, id, keyType, type, options) { + Field.call(this, name, id, type, options); + + /* istanbul ignore if */ + if (!util.isString(keyType)) + throw TypeError("keyType must be a string"); + + /** + * Key type. + * @type {string} + */ + this.keyType = keyType; // toJSON, marker + + /** + * Resolved key type if not a basic type. + * @type {ReflectionObject|null} + */ + this.resolvedKeyType = null; + + // Overrides Field#map + this.map = true; + } + + /** + * Map field descriptor. + * @interface IMapField + * @extends {IField} + * @property {string} keyType Key type + */ + + /** + * Extension map field descriptor. + * @interface IExtensionMapField + * @extends IMapField + * @property {string} extend Extended type + */ + + /** + * Constructs a map field from a map field descriptor. + * @param {string} name Field name + * @param {IMapField} json Map field descriptor + * @returns {MapField} Created map field + * @throws {TypeError} If arguments are invalid + */ + MapField.fromJSON = function fromJSON(name, json) { + return new MapField(name, json.id, json.keyType, json.type, json.options); + }; + + /** + * Converts this map field to a map field descriptor. + * @returns {IMapField} Map field descriptor + */ + MapField.prototype.toJSON = function toJSON() { + return util.toObject([ + "keyType", this.keyType, + "type", this.type, + "id", this.id, + "extend", this.extend, + "options", this.options + ]); + }; + + /** + * @override + */ + MapField.prototype.resolve = function resolve() { + if (this.resolved) + return this; + + // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes" + if (types.mapKey[this.keyType] === undefined) + throw Error("invalid key type: " + this.keyType); + + return Field.prototype.resolve.call(this); + }; + + /** + * Map field decorator (TypeScript). + * @name MapField.d + * @function + * @param {number} fieldId Field id + * @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type + * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type + * @returns {FieldDecorator} Decorator function + * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> } + */ + MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) { + + // submessage value: decorate the submessage and use its name as the type + if (typeof fieldValueType === "function") + fieldValueType = util.decorateType(fieldValueType).name; + + // enum reference value: create a reflected copy of the enum and keep reuseing it + else if (fieldValueType && typeof fieldValueType === "object") + fieldValueType = util.decorateEnum(fieldValueType).name; + + return function mapFieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor) + .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType)); + }; + }; + + }, { "16": 16, "36": 36, "37": 37 }], 21: [function (require, module, exports) { + "use strict"; + module.exports = Message; + + var util = require(39); + + /** + * Constructs a new message instance. + * @classdesc Abstract runtime message. + * @constructor + * @param {Properties} [properties] Properties to set + * @template T extends object + */ + function Message(properties) { + // not used internally + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + this[keys[i]] = properties[keys[i]]; + } + + /** + * Reference to the reflected type. + * @name Message.$type + * @type {Type} + * @readonly + */ + + /** + * Reference to the reflected type. + * @name Message#$type + * @type {Type} + * @readonly + */ + + /*eslint-disable valid-jsdoc*/ + + /** + * Creates a new message of this type using the specified properties. + * @param {Object.} [properties] Properties to set + * @returns {Message} Message instance + * @template T extends Message + * @this Constructor + */ + Message.create = function create(properties) { + return this.$type.create(properties); + }; + + /** + * Encodes a message of this type. + * @param {T|Object.} message Message to encode + * @param {Writer} [writer] Writer to use + * @returns {Writer} Writer + * @template T extends Message + * @this Constructor + */ + Message.encode = function encode(message, writer) { + return this.$type.encode(message, writer); + }; + + /** + * Encodes a message of this type preceeded by its length as a varint. + * @param {T|Object.} message Message to encode + * @param {Writer} [writer] Writer to use + * @returns {Writer} Writer + * @template T extends Message + * @this Constructor + */ + Message.encodeDelimited = function encodeDelimited(message, writer) { + return this.$type.encodeDelimited(message, writer); + }; + + /** + * Decodes a message of this type. + * @name Message.decode + * @function + * @param {Reader|Uint8Array} reader Reader or buffer to decode + * @returns {T} Decoded message + * @template T extends Message + * @this Constructor + */ + Message.decode = function decode(reader) { + return this.$type.decode(reader); + }; + + /** + * Decodes a message of this type preceeded by its length as a varint. + * @name Message.decodeDelimited + * @function + * @param {Reader|Uint8Array} reader Reader or buffer to decode + * @returns {T} Decoded message + * @template T extends Message + * @this Constructor + */ + Message.decodeDelimited = function decodeDelimited(reader) { + return this.$type.decodeDelimited(reader); + }; + + /** + * Verifies a message of this type. + * @name Message.verify + * @function + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ + Message.verify = function verify(message) { + return this.$type.verify(message); + }; + + /** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param {Object.} object Plain object + * @returns {T} Message instance + * @template T extends Message + * @this Constructor + */ + Message.fromObject = function fromObject(object) { + return this.$type.fromObject(object); + }; + + /** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param {T} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + * @template T extends Message + * @this Constructor + */ + Message.toObject = function toObject(message, options) { + return this.$type.toObject(message, options); + }; + + /** + * Converts this message to JSON. + * @returns {Object.} JSON object + */ + Message.prototype.toJSON = function toJSON() { + return this.$type.toObject(this, util.toJSONOptions); + }; + + /*eslint-enable valid-jsdoc*/ + }, { "39": 39 }], 22: [function (require, module, exports) { + "use strict"; + module.exports = Method; + + // extends ReflectionObject + var ReflectionObject = require(24); + ((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method"; + + var util = require(37); + + /** + * Constructs a new service method instance. + * @classdesc Reflected service method. + * @extends ReflectionObject + * @constructor + * @param {string} name Method name + * @param {string|undefined} type Method type, usually `"rpc"` + * @param {string} requestType Request message type + * @param {string} responseType Response message type + * @param {boolean|Object.} [requestStream] Whether the request is streamed + * @param {boolean|Object.} [responseStream] Whether the response is streamed + * @param {Object.} [options] Declared options + */ + function Method(name, type, requestType, responseType, requestStream, responseStream, options) { + + /* istanbul ignore next */ + if (util.isObject(requestStream)) { + options = requestStream; + requestStream = responseStream = undefined; + } else if (util.isObject(responseStream)) { + options = responseStream; + responseStream = undefined; + } + + /* istanbul ignore if */ + if (!(type === undefined || util.isString(type))) + throw TypeError("type must be a string"); + + /* istanbul ignore if */ + if (!util.isString(requestType)) + throw TypeError("requestType must be a string"); + + /* istanbul ignore if */ + if (!util.isString(responseType)) + throw TypeError("responseType must be a string"); + + ReflectionObject.call(this, name, options); + + /** + * Method type. + * @type {string} + */ + this.type = type || "rpc"; // toJSON + + /** + * Request type. + * @type {string} + */ + this.requestType = requestType; // toJSON, marker + + /** + * Whether requests are streamed or not. + * @type {boolean|undefined} + */ + this.requestStream = requestStream ? true : undefined; // toJSON + + /** + * Response type. + * @type {string} + */ + this.responseType = responseType; // toJSON + + /** + * Whether responses are streamed or not. + * @type {boolean|undefined} + */ + this.responseStream = responseStream ? true : undefined; // toJSON + + /** + * Resolved request type. + * @type {Type|null} + */ + this.resolvedRequestType = null; + + /** + * Resolved response type. + * @type {Type|null} + */ + this.resolvedResponseType = null; + } + + /** + * Method descriptor. + * @interface IMethod + * @property {string} [type="rpc"] Method type + * @property {string} requestType Request type + * @property {string} responseType Response type + * @property {boolean} [requestStream=false] Whether requests are streamed + * @property {boolean} [responseStream=false] Whether responses are streamed + * @property {Object.} [options] Method options + */ + + /** + * Constructs a method from a method descriptor. + * @param {string} name Method name + * @param {IMethod} json Method descriptor + * @returns {Method} Created method + * @throws {TypeError} If arguments are invalid + */ + Method.fromJSON = function fromJSON(name, json) { + return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options); + }; + + /** + * Converts this method to a method descriptor. + * @returns {IMethod} Method descriptor + */ + Method.prototype.toJSON = function toJSON() { + return util.toObject([ + "type", this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined, + "requestType", this.requestType, + "requestStream", this.requestStream, + "responseType", this.responseType, + "responseStream", this.responseStream, + "options", this.options + ]); + }; + + /** + * @override + */ + Method.prototype.resolve = function resolve() { + + /* istanbul ignore if */ + if (this.resolved) + return this; + + this.resolvedRequestType = this.parent.lookupType(this.requestType); + this.resolvedResponseType = this.parent.lookupType(this.responseType); + + return ReflectionObject.prototype.resolve.call(this); + }; + + }, { "24": 24, "37": 37 }], 23: [function (require, module, exports) { + "use strict"; + module.exports = Namespace; + + // extends ReflectionObject + var ReflectionObject = require(24); + ((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace"; + + var Enum = require(15), + Field = require(16), + util = require(37); + + var Type, // cyclic + Service; // " + + /** + * Constructs a new namespace instance. + * @name Namespace + * @classdesc Reflected namespace. + * @extends NamespaceBase + * @constructor + * @param {string} name Namespace name + * @param {Object.} [options] Declared options + */ + + /** + * Constructs a namespace from JSON. + * @memberof Namespace + * @function + * @param {string} name Namespace name + * @param {Object.} json JSON object + * @returns {Namespace} Created namespace + * @throws {TypeError} If arguments are invalid + */ + Namespace.fromJSON = function fromJSON(name, json) { + return new Namespace(name, json.options).addJSON(json.nested); + }; + + /** + * Converts an array of reflection objects to JSON. + * @memberof Namespace + * @param {ReflectionObject[]} array Object array + * @returns {Object.|undefined} JSON object or `undefined` when array is empty + */ + function arrayToJSON(array) { + if (!(array && array.length)) + return undefined; + var obj = {}; + for (var i = 0; i < array.length; ++i) + obj[array[i].name] = array[i].toJSON(); + return obj; + } + + Namespace.arrayToJSON = arrayToJSON; + + /** + * Tests if the specified id is reserved. + * @param {Array.|undefined} reserved Array of reserved ranges and names + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ + Namespace.isReservedId = function isReservedId(reserved, id) { + if (reserved) + for (var i = 0; i < reserved.length; ++i) + if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] >= id) + return true; + return false; + }; + + /** + * Tests if the specified name is reserved. + * @param {Array.|undefined} reserved Array of reserved ranges and names + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ + Namespace.isReservedName = function isReservedName(reserved, name) { + if (reserved) + for (var i = 0; i < reserved.length; ++i) + if (reserved[i] === name) + return true; + return false; + }; + + /** + * Not an actual constructor. Use {@link Namespace} instead. + * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions. + * @exports NamespaceBase + * @extends ReflectionObject + * @abstract + * @constructor + * @param {string} name Namespace name + * @param {Object.} [options] Declared options + * @see {@link Namespace} + */ + function Namespace(name, options) { + ReflectionObject.call(this, name, options); + + /** + * Nested objects by name. + * @type {Object.|undefined} + */ + this.nested = undefined; // toJSON + + /** + * Cached nested objects as an array. + * @type {ReflectionObject[]|null} + * @private + */ + this._nestedArray = null; + } + + function clearCache(namespace) { + namespace._nestedArray = null; + return namespace; + } + + /** + * Nested objects of this namespace as an array for iteration. + * @name NamespaceBase#nestedArray + * @type {ReflectionObject[]} + * @readonly + */ + Object.defineProperty(Namespace.prototype, "nestedArray", { + get: function () { + return this._nestedArray || (this._nestedArray = util.toArray(this.nested)); + } + }); + + /** + * Namespace descriptor. + * @interface INamespace + * @property {Object.} [options] Namespace options + * @property {Object.} [nested] Nested object descriptors + */ + + /** + * Any extension field descriptor. + * @typedef AnyExtensionField + * @type {IExtensionField|IExtensionMapField} + */ + + /** + * Any nested object descriptor. + * @typedef AnyNestedObject + * @type {IEnum|IType|IService|AnyExtensionField|INamespace} + */ + // ^ BEWARE: VSCode hangs forever when using more than 5 types (that's why AnyExtensionField exists in the first place) + + /** + * Converts this namespace to a namespace descriptor. + * @returns {INamespace} Namespace descriptor + */ + Namespace.prototype.toJSON = function toJSON() { + return util.toObject([ + "options", this.options, + "nested", arrayToJSON(this.nestedArray) + ]); + }; + + /** + * Adds nested objects to this namespace from nested object descriptors. + * @param {Object.} nestedJson Any nested object descriptors + * @returns {Namespace} `this` + */ + Namespace.prototype.addJSON = function addJSON(nestedJson) { + var ns = this; + /* istanbul ignore else */ + if (nestedJson) { + for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) { + nested = nestedJson[names[i]]; + ns.add( // most to least likely + (nested.fields !== undefined + ? Type.fromJSON + : nested.values !== undefined + ? Enum.fromJSON + : nested.methods !== undefined + ? Service.fromJSON + : nested.id !== undefined + ? Field.fromJSON + : Namespace.fromJSON)(names[i], nested) + ); + } + } + return this; + }; + + /** + * Gets the nested object of the specified name. + * @param {string} name Nested object name + * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist + */ + Namespace.prototype.get = function get(name) { + return this.nested && this.nested[name] + || null; + }; + + /** + * Gets the values of the nested {@link Enum|enum} of the specified name. + * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`. + * @param {string} name Nested enum name + * @returns {Object.} Enum values + * @throws {Error} If there is no such enum + */ + Namespace.prototype.getEnum = function getEnum(name) { + if (this.nested && this.nested[name] instanceof Enum) + return this.nested[name].values; + throw Error("no such enum"); + }; + + /** + * Adds a nested object to this namespace. + * @param {ReflectionObject} object Nested object to add + * @returns {Namespace} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name + */ + Namespace.prototype.add = function add(object) { + + if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof Enum || object instanceof Service || object instanceof Namespace)) + throw TypeError("object must be a valid nested object"); + + if (!this.nested) + this.nested = {}; + else { + var prev = this.get(object.name); + if (prev) { + if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) { + // replace plain namespace but keep existing nested elements and options + var nested = prev.nestedArray; + for (var i = 0; i < nested.length; ++i) + object.add(nested[i]); + this.remove(prev); + if (!this.nested) + this.nested = {}; + object.setOptions(prev.options, true); + + } else + throw Error("duplicate name '" + object.name + "' in " + this); + } + } + this.nested[object.name] = object; + object.onAdd(this); + return clearCache(this); + }; + + /** + * Removes a nested object from this namespace. + * @param {ReflectionObject} object Nested object to remove + * @returns {Namespace} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this namespace + */ + Namespace.prototype.remove = function remove(object) { + + if (!(object instanceof ReflectionObject)) + throw TypeError("object must be a ReflectionObject"); + if (object.parent !== this) + throw Error(object + " is not a member of " + this); + + delete this.nested[object.name]; + if (!Object.keys(this.nested).length) + this.nested = undefined; + + object.onRemove(this); + return clearCache(this); + }; + + /** + * Defines additial namespaces within this one if not yet existing. + * @param {string|string[]} path Path to create + * @param {*} [json] Nested types to create from JSON + * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty + */ + Namespace.prototype.define = function define(path, json) { + + if (util.isString(path)) + path = path.split("."); + else if (!Array.isArray(path)) + throw TypeError("illegal path"); + if (path && path.length && path[0] === "") + throw Error("path must be relative"); + + var ptr = this; + while (path.length > 0) { + var part = path.shift(); + if (ptr.nested && ptr.nested[part]) { + ptr = ptr.nested[part]; + if (!(ptr instanceof Namespace)) + throw Error("path conflicts with non-namespace objects"); + } else + ptr.add(ptr = new Namespace(part)); + } + if (json) + ptr.addJSON(json); + return ptr; + }; + + /** + * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost. + * @returns {Namespace} `this` + */ + Namespace.prototype.resolveAll = function resolveAll() { + var nested = this.nestedArray, i = 0; + while (i < nested.length) + if (nested[i] instanceof Namespace) + nested[i++].resolveAll(); + else + nested[i++].resolve(); + return this.resolve(); + }; + + /** + * Recursively looks up the reflection object matching the specified path in the scope of this namespace. + * @param {string|string[]} path Path to look up + * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc. + * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + */ + Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) { + + /* istanbul ignore next */ + if (typeof filterTypes === "boolean") { + parentAlreadyChecked = filterTypes; + filterTypes = undefined; + } else if (filterTypes && !Array.isArray(filterTypes)) + filterTypes = [filterTypes]; + + if (util.isString(path) && path.length) { + if (path === ".") + return this.root; + path = path.split("."); + } else if (!path.length) + return this; + + // Start at root if path is absolute + if (path[0] === "") + return this.root.lookup(path.slice(1), filterTypes); + + // Test if the first part matches any nested object, and if so, traverse if path contains more + var found = this.get(path[0]); + if (found) { + if (path.length === 1) { + if (!filterTypes || filterTypes.indexOf(found.constructor) > -1) + return found; + } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true))) + return found; + + // Otherwise try each nested namespace + } else + for (var i = 0; i < this.nestedArray.length; ++i) + if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true))) + return found; + + // If there hasn't been a match, try again at the parent + if (this.parent === null || parentAlreadyChecked) + return null; + return this.parent.lookup(path, filterTypes); + }; + + /** + * Looks up the reflection object at the specified path, relative to this namespace. + * @name NamespaceBase#lookup + * @function + * @param {string|string[]} path Path to look up + * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + * @variation 2 + */ + // lookup(path: string, [parentAlreadyChecked: boolean]) + + /** + * Looks up the {@link Type|type} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Type} Looked up type + * @throws {Error} If `path` does not point to a type + */ + Namespace.prototype.lookupType = function lookupType(path) { + var found = this.lookup(path, [Type]); + if (!found) + throw Error("no such type"); + return found; + }; + + /** + * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Enum} Looked up enum + * @throws {Error} If `path` does not point to an enum + */ + Namespace.prototype.lookupEnum = function lookupEnum(path) { + var found = this.lookup(path, [Enum]); + if (!found) + throw Error("no such Enum '" + path + "' in " + this); + return found; + }; + + /** + * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Type} Looked up type or enum + * @throws {Error} If `path` does not point to a type or enum + */ + Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) { + var found = this.lookup(path, [Type, Enum]); + if (!found) + throw Error("no such Type or Enum '" + path + "' in " + this); + return found; + }; + + /** + * Looks up the {@link Service|service} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Service} Looked up service + * @throws {Error} If `path` does not point to a service + */ + Namespace.prototype.lookupService = function lookupService(path) { + var found = this.lookup(path, [Service]); + if (!found) + throw Error("no such Service '" + path + "' in " + this); + return found; + }; + + Namespace._configure = function (Type_, Service_) { + Type = Type_; + Service = Service_; + }; + + }, { "15": 15, "16": 16, "24": 24, "37": 37 }], 24: [function (require, module, exports) { + "use strict"; + module.exports = ReflectionObject; + + ReflectionObject.className = "ReflectionObject"; + + var util = require(37); + + var Root; // cyclic + + /** + * Constructs a new reflection object instance. + * @classdesc Base class of all reflection objects. + * @constructor + * @param {string} name Object name + * @param {Object.} [options] Declared options + * @abstract + */ + function ReflectionObject(name, options) { + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + if (options && !util.isObject(options)) + throw TypeError("options must be an object"); + + /** + * Options. + * @type {Object.|undefined} + */ + this.options = options; // toJSON + + /** + * Unique name within its namespace. + * @type {string} + */ + this.name = name; + + /** + * Parent namespace. + * @type {Namespace|null} + */ + this.parent = null; + + /** + * Whether already resolved or not. + * @type {boolean} + */ + this.resolved = false; + + /** + * Comment text, if any. + * @type {string|null} + */ + this.comment = null; + + /** + * Defining file name. + * @type {string|null} + */ + this.filename = null; + } + + Object.defineProperties(ReflectionObject.prototype, { + + /** + * Reference to the root namespace. + * @name ReflectionObject#root + * @type {Root} + * @readonly + */ + root: { + get: function () { + var ptr = this; + while (ptr.parent !== null) + ptr = ptr.parent; + return ptr; + } + }, + + /** + * Full name including leading dot. + * @name ReflectionObject#fullName + * @type {string} + * @readonly + */ + fullName: { + get: function () { + var path = [this.name], + ptr = this.parent; + while (ptr) { + path.unshift(ptr.name); + ptr = ptr.parent; + } + return path.join("."); + } + } + }); + + /** + * Converts this reflection object to its descriptor representation. + * @returns {Object.} Descriptor + * @abstract + */ + ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() { + throw Error(); // not implemented, shouldn't happen + }; + + /** + * Called when this object is added to a parent. + * @param {ReflectionObject} parent Parent added to + * @returns {undefined} + */ + ReflectionObject.prototype.onAdd = function onAdd(parent) { + if (this.parent && this.parent !== parent) + this.parent.remove(this); + this.parent = parent; + this.resolved = false; + var root = parent.root; + if (root instanceof Root) + root._handleAdd(this); + }; + + /** + * Called when this object is removed from a parent. + * @param {ReflectionObject} parent Parent removed from + * @returns {undefined} + */ + ReflectionObject.prototype.onRemove = function onRemove(parent) { + var root = parent.root; + if (root instanceof Root) + root._handleRemove(this); + this.parent = null; + this.resolved = false; + }; + + /** + * Resolves this objects type references. + * @returns {ReflectionObject} `this` + */ + ReflectionObject.prototype.resolve = function resolve() { + if (this.resolved) + return this; + if (this.root instanceof Root) + this.resolved = true; // only if part of a root + return this; + }; + + /** + * Gets an option value. + * @param {string} name Option name + * @returns {*} Option value or `undefined` if not set + */ + ReflectionObject.prototype.getOption = function getOption(name) { + if (this.options) + return this.options[name]; + return undefined; + }; + + /** + * Sets an option. + * @param {string} name Option name + * @param {*} value Option value + * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set + * @returns {ReflectionObject} `this` + */ + ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) { + if (!ifNotSet || !this.options || this.options[name] === undefined) + (this.options || (this.options = {})) [name] = value; + return this; + }; + + /** + * Sets multiple options. + * @param {Object.} options Options to set + * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set + * @returns {ReflectionObject} `this` + */ + ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) { + if (options) + for (var keys = Object.keys(options), i = 0; i < keys.length; ++i) + this.setOption(keys[i], options[keys[i]], ifNotSet); + return this; + }; + + /** + * Converts this instance to its string representation. + * @returns {string} Class name[, space, full name] + */ + ReflectionObject.prototype.toString = function toString() { + var className = this.constructor.className, + fullName = this.fullName; + if (fullName.length) + return className + " " + fullName; + return className; + }; + + ReflectionObject._configure = function (Root_) { + Root = Root_; + }; + + }, { "37": 37 }], 25: [function (require, module, exports) { + "use strict"; + module.exports = OneOf; + + // extends ReflectionObject + var ReflectionObject = require(24); + ((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf"; + + var Field = require(16), + util = require(37); + + /** + * Constructs a new oneof instance. + * @classdesc Reflected oneof. + * @extends ReflectionObject + * @constructor + * @param {string} name Oneof name + * @param {string[]|Object.} [fieldNames] Field names + * @param {Object.} [options] Declared options + */ + function OneOf(name, fieldNames, options) { + if (!Array.isArray(fieldNames)) { + options = fieldNames; + fieldNames = undefined; + } + ReflectionObject.call(this, name, options); + + /* istanbul ignore if */ + if (!(fieldNames === undefined || Array.isArray(fieldNames))) + throw TypeError("fieldNames must be an Array"); + + /** + * Field names that belong to this oneof. + * @type {string[]} + */ + this.oneof = fieldNames || []; // toJSON, marker + + /** + * Fields that belong to this oneof as an array for iteration. + * @type {Field[]} + * @readonly + */ + this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent + } + + /** + * Oneof descriptor. + * @interface IOneOf + * @property {Array.} oneof Oneof field names + * @property {Object.} [options] Oneof options + */ + + /** + * Constructs a oneof from a oneof descriptor. + * @param {string} name Oneof name + * @param {IOneOf} json Oneof descriptor + * @returns {OneOf} Created oneof + * @throws {TypeError} If arguments are invalid + */ + OneOf.fromJSON = function fromJSON(name, json) { + return new OneOf(name, json.oneof, json.options); + }; + + /** + * Converts this oneof to a oneof descriptor. + * @returns {IOneOf} Oneof descriptor + */ + OneOf.prototype.toJSON = function toJSON() { + return util.toObject([ + "options", this.options, + "oneof", this.oneof + ]); + }; + + /** + * Adds the fields of the specified oneof to the parent if not already done so. + * @param {OneOf} oneof The oneof + * @returns {undefined} + * @inner + * @ignore + */ + function addFieldsToParent(oneof) { + if (oneof.parent) + for (var i = 0; i < oneof.fieldsArray.length; ++i) + if (!oneof.fieldsArray[i].parent) + oneof.parent.add(oneof.fieldsArray[i]); + } + + /** + * Adds a field to this oneof and removes it from its current parent, if any. + * @param {Field} field Field to add + * @returns {OneOf} `this` + */ + OneOf.prototype.add = function add(field) { + + /* istanbul ignore if */ + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + + if (field.parent && field.parent !== this.parent) + field.parent.remove(field); + this.oneof.push(field.name); + this.fieldsArray.push(field); + field.partOf = this; // field.parent remains null + addFieldsToParent(this); + return this; + }; + + /** + * Removes a field from this oneof and puts it back to the oneof's parent. + * @param {Field} field Field to remove + * @returns {OneOf} `this` + */ + OneOf.prototype.remove = function remove(field) { + + /* istanbul ignore if */ + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + + var index = this.fieldsArray.indexOf(field); + + /* istanbul ignore if */ + if (index < 0) + throw Error(field + " is not a member of " + this); + + this.fieldsArray.splice(index, 1); + index = this.oneof.indexOf(field.name); + + /* istanbul ignore else */ + if (index > -1) // theoretical + this.oneof.splice(index, 1); + + field.partOf = null; + return this; + }; + + /** + * @override + */ + OneOf.prototype.onAdd = function onAdd(parent) { + ReflectionObject.prototype.onAdd.call(this, parent); + var self = this; + // Collect present fields + for (var i = 0; i < this.oneof.length; ++i) { + var field = parent.get(this.oneof[i]); + if (field && !field.partOf) { + field.partOf = self; + self.fieldsArray.push(field); + } + } + // Add not yet present fields + addFieldsToParent(this); + }; + + /** + * @override + */ + OneOf.prototype.onRemove = function onRemove(parent) { + for (var i = 0, field; i < this.fieldsArray.length; ++i) + if ((field = this.fieldsArray[i]).parent) + field.parent.remove(field); + ReflectionObject.prototype.onRemove.call(this, parent); + }; + + /** + * Decorator function as returned by {@link OneOf.d} (TypeScript). + * @typedef OneOfDecorator + * @type {function} + * @param {Object} prototype Target prototype + * @param {string} oneofName OneOf name + * @returns {undefined} + */ + + /** + * OneOf decorator (TypeScript). + * @function + * @param {...string} fieldNames Field names + * @returns {OneOfDecorator} Decorator function + * @template T extends string + */ + OneOf.d = function decorateOneOf() { + var fieldNames = new Array(arguments.length), + index = 0; + while (index < arguments.length) + fieldNames[index] = arguments[index++]; + return function oneOfDecorator(prototype, oneofName) { + util.decorateType(prototype.constructor) + .add(new OneOf(oneofName, fieldNames)); + Object.defineProperty(prototype, oneofName, { + get: util.oneOfGetter(fieldNames), + set: util.oneOfSetter(fieldNames) + }); + }; + }; + + }, { "16": 16, "24": 24, "37": 37 }], 26: [function (require, module, exports) { + "use strict"; + module.exports = parse; + + parse.filename = null; + parse.defaults = { keepCase: false }; + + var tokenize = require(34), + Root = require(29), + Type = require(35), + Field = require(16), + MapField = require(20), + OneOf = require(25), + Enum = require(15), + Service = require(33), + Method = require(22), + types = require(36), + util = require(37); + + var base10Re = /^[1-9][0-9]*$/, + base10NegRe = /^-?[1-9][0-9]*$/, + base16Re = /^0[x][0-9a-fA-F]+$/, + base16NegRe = /^-?0[x][0-9a-fA-F]+$/, + base8Re = /^0[0-7]+$/, + base8NegRe = /^-?0[0-7]+$/, + numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/, + nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/, + typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)+$/, + fqTypeRefRe = /^(?:\.[a-zA-Z][a-zA-Z_0-9]*)+$/; + + /** + * Result object returned from {@link parse}. + * @interface IParserResult + * @property {string|undefined} package Package name, if declared + * @property {string[]|undefined} imports Imports, if any + * @property {string[]|undefined} weakImports Weak imports, if any + * @property {string|undefined} syntax Syntax, if specified (either `"proto2"` or `"proto3"`) + * @property {Root} root Populated root instance + */ + + /** + * Options modifying the behavior of {@link parse}. + * @interface IParseOptions + * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case + */ + + /** + * Parses the given .proto source and returns an object with the parsed contents. + * @param {string} source Source contents + * @param {Root} root Root to populate + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {IParserResult} Parser result + * @property {string} filename=null Currently processing file name for error reporting, if known + * @property {IParseOptions} defaults Default {@link IParseOptions} + */ + function parse(source, root, options) { + /* eslint-disable callback-return */ + if (!(root instanceof Root)) { + options = root; + root = new Root(); + } + if (!options) + options = parse.defaults; + + var tn = tokenize(source), + next = tn.next, + push = tn.push, + peek = tn.peek, + skip = tn.skip, + cmnt = tn.cmnt; + + var head = true, + pkg, + imports, + weakImports, + syntax, + isProto3 = false; + + var ptr = root; + + var applyCase = options.keepCase ? function (name) { return name; } : util.camelCase; + + /* istanbul ignore next */ + function illegal(token, name, insideTryCatch) { + var filename = parse.filename; + if (!insideTryCatch) + parse.filename = null; + return Error("illegal " + (name || "token") + " '" + token + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")"); + } + + function readString() { + var values = [], + token; + do { + /* istanbul ignore if */ + if ((token = next()) !== "\"" && token !== "'") + throw illegal(token); + + values.push(next()); + skip(token); + token = peek(); + } while (token === "\"" || token === "'"); + return values.join(""); + } + + function readValue(acceptTypeRef) { + var token = next(); + switch (token) { + case "'": + case "\"": + push(token); + return readString(); + case "true": case "TRUE": + return true; + case "false": case "FALSE": + return false; + } + try { + return parseNumber(token, /* insideTryCatch */ true); + } catch (e) { + + /* istanbul ignore else */ + if (acceptTypeRef && typeRefRe.test(token)) + return token; + + /* istanbul ignore next */ + throw illegal(token, "value"); + } + } + + function readRanges(target, acceptStrings) { + var token, start; + do { + if (acceptStrings && ((token = peek()) === "\"" || token === "'")) + target.push(readString()); + else + target.push([start = parseId(next()), skip("to", true) ? parseId(next()) : start]); + } while (skip(",", true)); + skip(";"); + } + + function parseNumber(token, insideTryCatch) { + var sign = 1; + if (token.charAt(0) === "-") { + sign = -1; + token = token.substring(1); + } + switch (token) { + case "inf": case "INF": case "Inf": + return sign * Infinity; + case "nan": case "NAN": case "Nan": case "NaN": + return NaN; + case "0": + return 0; + } + if (base10Re.test(token)) + return sign * parseInt(token, 10); + if (base16Re.test(token)) + return sign * parseInt(token, 16); + if (base8Re.test(token)) + return sign * parseInt(token, 8); + + /* istanbul ignore else */ + if (numberRe.test(token)) + return sign * parseFloat(token); + + /* istanbul ignore next */ + throw illegal(token, "number", insideTryCatch); + } + + function parseId(token, acceptNegative) { + switch (token) { + case "max": case "MAX": case "Max": + return 536870911; + case "0": + return 0; + } + + /* istanbul ignore if */ + if (!acceptNegative && token.charAt(0) === "-") + throw illegal(token, "id"); + + if (base10NegRe.test(token)) + return parseInt(token, 10); + if (base16NegRe.test(token)) + return parseInt(token, 16); + + /* istanbul ignore else */ + if (base8NegRe.test(token)) + return parseInt(token, 8); + + /* istanbul ignore next */ + throw illegal(token, "id"); + } + + function parsePackage() { + + /* istanbul ignore if */ + if (pkg !== undefined) + throw illegal("package"); + + pkg = next(); + + /* istanbul ignore if */ + if (!typeRefRe.test(pkg)) + throw illegal(pkg, "name"); + + ptr = ptr.define(pkg); + skip(";"); + } + + function parseImport() { + var token = peek(); + var whichImports; + switch (token) { + case "weak": + whichImports = weakImports || (weakImports = []); + next(); + break; + case "public": + next(); + // eslint-disable-line no-fallthrough + default: + whichImports = imports || (imports = []); + break; + } + token = readString(); + skip(";"); + whichImports.push(token); + } + + function parseSyntax() { + skip("="); + syntax = readString(); + isProto3 = syntax === "proto3"; + + /* istanbul ignore if */ + if (!isProto3 && syntax !== "proto2") + throw illegal(syntax, "syntax"); + + skip(";"); + } + + function parseCommon(parent, token) { + switch (token) { + + case "option": + parseOption(parent, token); + skip(";"); + return true; + + case "message": + parseType(parent, token); + return true; + + case "enum": + parseEnum(parent, token); + return true; + + case "service": + parseService(parent, token); + return true; + + case "extend": + parseExtension(parent, token); + return true; + } + return false; + } + + function ifBlock(obj, fnIf, fnElse) { + var trailingLine = tn.line; + if (obj) { + obj.comment = cmnt(); // try block-type comment + obj.filename = parse.filename; + } + if (skip("{", true)) { + var token; + while ((token = next()) !== "}") + fnIf(token); + skip(";", true); + } else { + if (fnElse) + fnElse(); + skip(";"); + if (obj && typeof obj.comment !== "string") + obj.comment = cmnt(trailingLine); // try line-type comment if no block + } + } + + function parseType(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "type name"); + + var type = new Type(token); + ifBlock(type, function parseType_block(token) { + if (parseCommon(type, token)) + return; + + switch (token) { + + case "map": + parseMapField(type, token); + break; + + case "required": + case "optional": + case "repeated": + parseField(type, token); + break; + + case "oneof": + parseOneOf(type, token); + break; + + case "extensions": + readRanges(type.extensions || (type.extensions = [])); + break; + + case "reserved": + readRanges(type.reserved || (type.reserved = []), true); + break; + + default: + /* istanbul ignore if */ + if (!isProto3 || !typeRefRe.test(token)) + throw illegal(token); + + push(token); + parseField(type, "optional"); + break; + } + }); + parent.add(type); + } + + function parseField(parent, rule, extend) { + var type = next(); + if (type === "group") { + parseGroup(parent, rule); + return; + } + + /* istanbul ignore if */ + if (!typeRefRe.test(type)) + throw illegal(type, "type"); + + var name = next(); + + /* istanbul ignore if */ + if (!nameRe.test(name)) + throw illegal(name, "name"); + + name = applyCase(name); + skip("="); + + var field = new Field(name, parseId(next()), type, rule, extend); + ifBlock(field, function parseField_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(field, token); + skip(";"); + } else + throw illegal(token); + + }, function parseField_line() { + parseInlineOptions(field); + }); + parent.add(field); + + // JSON defaults to packed=true if not set so we have to set packed=false explicity when + // parsing proto2 descriptors without the option, where applicable. This must be done for + // all known packable types and anything that could be an enum (= is not a basic type). + if (!isProto3 && field.repeated && (types.packed[type] !== undefined || types.basic[type] === undefined)) + field.setOption("packed", false, /* ifNotSet */ true); + } + + function parseGroup(parent, rule) { + var name = next(); + + /* istanbul ignore if */ + if (!nameRe.test(name)) + throw illegal(name, "name"); + + var fieldName = util.lcFirst(name); + if (name === fieldName) + name = util.ucFirst(name); + skip("="); + var id = parseId(next()); + var type = new Type(name); + type.group = true; + var field = new Field(fieldName, id, name, rule); + field.filename = parse.filename; + ifBlock(type, function parseGroup_block(token) { + switch (token) { + + case "option": + parseOption(type, token); + skip(";"); + break; + + case "required": + case "optional": + case "repeated": + parseField(type, token); + break; + + /* istanbul ignore next */ + default: + throw illegal(token); // there are no groups with proto3 semantics + } + }); + parent.add(type) + .add(field); + } + + function parseMapField(parent) { + skip("<"); + var keyType = next(); + + /* istanbul ignore if */ + if (types.mapKey[keyType] === undefined) + throw illegal(keyType, "type"); + + skip(","); + var valueType = next(); + + /* istanbul ignore if */ + if (!typeRefRe.test(valueType)) + throw illegal(valueType, "type"); + + skip(">"); + var name = next(); + + /* istanbul ignore if */ + if (!nameRe.test(name)) + throw illegal(name, "name"); + + skip("="); + var field = new MapField(applyCase(name), parseId(next()), keyType, valueType); + ifBlock(field, function parseMapField_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(field, token); + skip(";"); + } else + throw illegal(token); + + }, function parseMapField_line() { + parseInlineOptions(field); + }); + parent.add(field); + } + + function parseOneOf(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "name"); + + var oneof = new OneOf(applyCase(token)); + ifBlock(oneof, function parseOneOf_block(token) { + if (token === "option") { + parseOption(oneof, token); + skip(";"); + } else { + push(token); + parseField(oneof, "optional"); + } + }); + parent.add(oneof); + } + + function parseEnum(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "name"); + + var enm = new Enum(token); + ifBlock(enm, function parseEnum_block(token) { + switch (token) { + case "option": + parseOption(enm, token); + skip(";"); + break; + + case "reserved": + readRanges(enm.reserved || (enm.reserved = []), true); + break; + + default: + parseEnumValue(enm, token); + } + }); + parent.add(enm); + } + + function parseEnumValue(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token)) + throw illegal(token, "name"); + + skip("="); + var value = parseId(next(), true), + dummy = {}; + ifBlock(dummy, function parseEnumValue_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(dummy, token); // skip + skip(";"); + } else + throw illegal(token); + + }, function parseEnumValue_line() { + parseInlineOptions(dummy); // skip + }); + parent.add(token, value, dummy.comment); + } + + function parseOption(parent, token) { + var isCustom = skip("(", true); + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token, "name"); + + var name = token; + if (isCustom) { + skip(")"); + name = "(" + name + ")"; + token = peek(); + if (fqTypeRefRe.test(token)) { + name += token; + next(); + } + } + skip("="); + parseOptionValue(parent, name); + } + + function parseOptionValue(parent, name) { + if (skip("{", true)) { // { a: "foo" b { c: "bar" } } + do { + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "name"); + + if (peek() === "{") + parseOptionValue(parent, name + "." + token); + else { + skip(":"); + if (peek() === "{") + parseOptionValue(parent, name + "." + token); + else + setOption(parent, name + "." + token, readValue(true)); + } + } while (!skip("}", true)); + } else + setOption(parent, name, readValue(true)); + // Does not enforce a delimiter to be universal + } + + function setOption(parent, name, value) { + if (parent.setOption) + parent.setOption(name, value); + } + + function parseInlineOptions(parent) { + if (skip("[", true)) { + do { + parseOption(parent, "option"); + } while (skip(",", true)); + skip("]"); + } + return parent; + } + + function parseService(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "service name"); + + var service = new Service(token); + ifBlock(service, function parseService_block(token) { + if (parseCommon(service, token)) + return; + + /* istanbul ignore else */ + if (token === "rpc") + parseMethod(service, token); + else + throw illegal(token); + }); + parent.add(service); + } + + function parseMethod(parent, token) { + var type = token; + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "name"); + + var name = token, + requestType, requestStream, + responseType, responseStream; + + skip("("); + if (skip("stream", true)) + requestStream = true; + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token); + + requestType = token; + skip(")"); skip("returns"); skip("("); + if (skip("stream", true)) + responseStream = true; + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token); + + responseType = token; + skip(")"); + + var method = new Method(name, type, requestType, responseType, requestStream, responseStream); + ifBlock(method, function parseMethod_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(method, token); + skip(";"); + } else + throw illegal(token); + + }); + parent.add(method); + } + + function parseExtension(parent, token) { + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token, "reference"); + + var reference = token; + ifBlock(null, function parseExtension_block(token) { + switch (token) { + + case "required": + case "repeated": + case "optional": + parseField(parent, token, reference); + break; + + default: + /* istanbul ignore if */ + if (!isProto3 || !typeRefRe.test(token)) + throw illegal(token); + push(token); + parseField(parent, "optional", reference); + break; + } + }); + } + + var token; + while ((token = next()) !== null) { + switch (token) { + + case "package": + + /* istanbul ignore if */ + if (!head) + throw illegal(token); + + parsePackage(); + break; + + case "import": + + /* istanbul ignore if */ + if (!head) + throw illegal(token); + + parseImport(); + break; + + case "syntax": + + /* istanbul ignore if */ + if (!head) + throw illegal(token); + + parseSyntax(); + break; + + case "option": + + /* istanbul ignore if */ + if (!head) + throw illegal(token); + + parseOption(ptr, token); + skip(";"); + break; + + default: + + /* istanbul ignore else */ + if (parseCommon(ptr, token)) { + head = false; + continue; + } + + /* istanbul ignore next */ + throw illegal(token); + } + } + + parse.filename = null; + return { + "package": pkg, + "imports": imports, + weakImports: weakImports, + syntax: syntax, + root: root + }; + } + + /** + * Parses the given .proto source and returns an object with the parsed contents. + * @name parse + * @function + * @param {string} source Source contents + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {IParserResult} Parser result + * @property {string} filename=null Currently processing file name for error reporting, if known + * @property {IParseOptions} defaults Default {@link IParseOptions} + * @variation 2 + */ + + }, { "15": 15, "16": 16, "20": 20, "22": 22, "25": 25, "29": 29, "33": 33, "34": 34, "35": 35, "36": 36, "37": 37 }], 27: [function (require, module, exports) { + "use strict"; + module.exports = Reader; + + var util = require(39); + + var BufferReader; // cyclic + + var LongBits = util.LongBits, + utf8 = util.utf8; + + /* istanbul ignore next */ + function indexOutOfRange(reader, writeLength) { + return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); + } + + /** + * Constructs a new reader instance using the specified buffer. + * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`. + * @constructor + * @param {Uint8Array} buffer Buffer to read from + */ + function Reader(buffer) { + + /** + * Read buffer. + * @type {Uint8Array} + */ + this.buf = buffer; + + /** + * Read buffer position. + * @type {number} + */ + this.pos = 0; + + /** + * Read buffer length. + * @type {number} + */ + this.len = buffer.length; + } + + var create_array = typeof Uint8Array !== "undefined" + ? function create_typed_array(buffer) { + if (buffer instanceof Uint8Array || Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + } + /* istanbul ignore next */ + : function create_array(buffer) { + if (Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + }; + + /** + * Creates a new reader using the specified buffer. + * @function + * @param {Uint8Array|Buffer} buffer Buffer to read from + * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader} + * @throws {Error} If `buffer` is not a valid buffer + */ + Reader.create = util.Buffer + ? function create_buffer_setup(buffer) { + return (Reader.create = function create_buffer(buffer) { + return util.Buffer.isBuffer(buffer) + ? new BufferReader(buffer) + /* istanbul ignore next */ + : create_array(buffer); + })(buffer); + } + /* istanbul ignore next */ + : create_array; + + Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice; + + /** + * Reads a varint as an unsigned 32 bit value. + * @function + * @returns {number} Value read + */ + Reader.prototype.uint32 = (function read_uint32_setup() { + var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!) + return function read_uint32() { + value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value; + + /* istanbul ignore if */ + if ((this.pos += 5) > this.len) { + this.pos = this.len; + throw indexOutOfRange(this, 10); + } + return value; + }; + })(); + + /** + * Reads a varint as a signed 32 bit value. + * @returns {number} Value read + */ + Reader.prototype.int32 = function read_int32() { + return this.uint32() | 0; + }; + + /** + * Reads a zig-zag encoded varint as a signed 32 bit value. + * @returns {number} Value read + */ + Reader.prototype.sint32 = function read_sint32() { + var value = this.uint32(); + return value >>> 1 ^ -(value & 1) | 0; + }; + + /* eslint-disable no-invalid-this */ + + function readLongVarint() { + // tends to deopt with local vars for octet etc. + var bits = new LongBits(0, 0); + var i = 0; + if (this.len - this.pos > 4) { // fast route (lo) + for (; i < 4; ++i) { + // 1st..4th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 5th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; + bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + i = 0; + } else { + for (; i < 3; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 1st..3th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 4th + bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; + return bits; + } + if (this.len - this.pos > 4) { // fast route (hi) + for (; i < 5; ++i) { + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } else { + for (; i < 5; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } + /* istanbul ignore next */ + throw Error("invalid varint encoding"); + } + + /* eslint-enable no-invalid-this */ + + /** + * Reads a varint as a signed 64 bit value. + * @name Reader#int64 + * @function + * @returns {Long} Value read + */ + + /** + * Reads a varint as an unsigned 64 bit value. + * @name Reader#uint64 + * @function + * @returns {Long} Value read + */ + + /** + * Reads a zig-zag encoded varint as a signed 64 bit value. + * @name Reader#sint64 + * @function + * @returns {Long} Value read + */ + + /** + * Reads a varint as a boolean. + * @returns {boolean} Value read + */ + Reader.prototype.bool = function read_bool() { + return this.uint32() !== 0; + }; + + function readFixed32_end(buf, end) { // note that this uses `end`, not `pos` + return (buf[end - 4] + | buf[end - 3] << 8 + | buf[end - 2] << 16 + | buf[end - 1] << 24) >>> 0; + } + + /** + * Reads fixed 32 bits as an unsigned 32 bit integer. + * @returns {number} Value read + */ + Reader.prototype.fixed32 = function read_fixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4); + }; + + /** + * Reads fixed 32 bits as a signed 32 bit integer. + * @returns {number} Value read + */ + Reader.prototype.sfixed32 = function read_sfixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4) | 0; + }; + + /* eslint-disable no-invalid-this */ + + function readFixed64(/* this: Reader */) { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 8); + + return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); + } + + /* eslint-enable no-invalid-this */ + + /** + * Reads fixed 64 bits. + * @name Reader#fixed64 + * @function + * @returns {Long} Value read + */ + + /** + * Reads zig-zag encoded fixed 64 bits. + * @name Reader#sfixed64 + * @function + * @returns {Long} Value read + */ + + /** + * Reads a float (32 bit) as a number. + * @function + * @returns {number} Value read + */ + Reader.prototype.float = function read_float() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readFloatLE(this.buf, this.pos); + this.pos += 4; + return value; + }; + + /** + * Reads a double (64 bit float) as a number. + * @function + * @returns {number} Value read + */ + Reader.prototype.double = function read_double() { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readDoubleLE(this.buf, this.pos); + this.pos += 8; + return value; + }; + + /** + * Reads a sequence of bytes preceeded by its length as a varint. + * @returns {Uint8Array} Value read + */ + Reader.prototype.bytes = function read_bytes() { + var length = this.uint32(), + start = this.pos, + end = this.pos + length; + + /* istanbul ignore if */ + if (end > this.len) + throw indexOutOfRange(this, length); + + this.pos += length; + if (Array.isArray(this.buf)) // plain array + return this.buf.slice(start, end); + return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1 + ? new this.buf.constructor(0) + : this._slice.call(this.buf, start, end); + }; + + /** + * Reads a string preceeded by its byte length as a varint. + * @returns {string} Value read + */ + Reader.prototype.string = function read_string() { + var bytes = this.bytes(); + return utf8.read(bytes, 0, bytes.length); + }; + + /** + * Skips the specified number of bytes if specified, otherwise skips a varint. + * @param {number} [length] Length if known, otherwise a varint is assumed + * @returns {Reader} `this` + */ + Reader.prototype.skip = function skip(length) { + if (typeof length === "number") { + /* istanbul ignore if */ + if (this.pos + length > this.len) + throw indexOutOfRange(this, length); + this.pos += length; + } else { + do { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + } while (this.buf[this.pos++] & 128); + } + return this; + }; + + /** + * Skips the next element of the specified wire type. + * @param {number} wireType Wire type received + * @returns {Reader} `this` + */ + Reader.prototype.skipType = function (wireType) { + switch (wireType) { + case 0: + this.skip(); + break; + case 1: + this.skip(8); + break; + case 2: + this.skip(this.uint32()); + break; + case 3: + do { // eslint-disable-line no-constant-condition + if ((wireType = this.uint32() & 7) === 4) + break; + this.skipType(wireType); + } while (true); + break; + case 5: + this.skip(4); + break; + + /* istanbul ignore next */ + default: + throw Error("invalid wire type " + wireType + " at offset " + this.pos); + } + return this; + }; + + Reader._configure = function (BufferReader_) { + BufferReader = BufferReader_; + + var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber"; + util.merge(Reader.prototype, { + + int64: function read_int64() { + return readLongVarint.call(this) [fn](false); + }, + + uint64: function read_uint64() { + return readLongVarint.call(this) [fn](true); + }, + + sint64: function read_sint64() { + return readLongVarint.call(this).zzDecode() [fn](false); + }, + + fixed64: function read_fixed64() { + return readFixed64.call(this) [fn](true); + }, + + sfixed64: function read_sfixed64() { + return readFixed64.call(this) [fn](false); + } + + }); + }; + + }, { "39": 39 }], 28: [function (require, module, exports) { + "use strict"; + module.exports = BufferReader; + + // extends Reader + var Reader = require(27); + (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; + + var util = require(39); + + /** + * Constructs a new buffer reader instance. + * @classdesc Wire format reader using node buffers. + * @extends Reader + * @constructor + * @param {Buffer} buffer Buffer to read from + */ + function BufferReader(buffer) { + Reader.call(this, buffer); + + /** + * Read buffer. + * @name BufferReader#buf + * @type {Buffer} + */ + } + + /* istanbul ignore else */ + if (util.Buffer) + BufferReader.prototype._slice = util.Buffer.prototype.slice; + + /** + * @override + */ + BufferReader.prototype.string = function read_string_buffer() { + var len = this.uint32(); // modifies pos + return this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)); + }; + + /** + * Reads a sequence of bytes preceeded by its length as a varint. + * @name BufferReader#bytes + * @function + * @returns {Buffer} Value read + */ + + }, { "27": 27, "39": 39 }], 29: [function (require, module, exports) { + "use strict"; + module.exports = Root; + + // extends Namespace + var Namespace = require(23); + ((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root"; + + var Field = require(16), + Enum = require(15), + OneOf = require(25), + util = require(37); + + var Type, // cyclic + parse, // might be excluded + common; // " + + /** + * Constructs a new root namespace instance. + * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together. + * @extends NamespaceBase + * @constructor + * @param {Object.} [options] Top level options + */ + function Root(options) { + Namespace.call(this, "", options); + + /** + * Deferred extension fields. + * @type {Field[]} + */ + this.deferred = []; + + /** + * Resolved file names of loaded files. + * @type {string[]} + */ + this.files = []; + } + + /** + * Loads a namespace descriptor into a root namespace. + * @param {INamespace} json Nameespace descriptor + * @param {Root} [root] Root namespace, defaults to create a new one if omitted + * @returns {Root} Root namespace + */ + Root.fromJSON = function fromJSON(json, root) { + if (!root) + root = new Root(); + if (json.options) + root.setOptions(json.options); + return root.addJSON(json.nested); + }; + + /** + * Resolves the path of an imported file, relative to the importing origin. + * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories. + * @function + * @param {string} origin The file name of the importing file + * @param {string} target The file name being imported + * @returns {string|null} Resolved path to `target` or `null` to skip the file + */ + Root.prototype.resolvePath = util.path.resolve; + + // A symbol-like function to safely signal synchronous loading + /* istanbul ignore next */ + function SYNC() { } // eslint-disable-line no-empty-function + + /** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} options Parse options + * @param {LoadCallback} callback Callback function + * @returns {undefined} + */ + Root.prototype.load = function load(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = undefined; + } + var self = this; + if (!callback) + return util.asPromise(load, self, filename, options); + + var sync = callback === SYNC; // undocumented + + // Finishes loading by calling the callback (exactly once) + function finish(err, root) { + /* istanbul ignore if */ + if (!callback) + return; + var cb = callback; + callback = null; + if (sync) + throw err; + cb(err, root); + } + + // Processes a single file + function process(filename, source) { + try { + if (util.isString(source) && source.charAt(0) === "{") + source = JSON.parse(source); + if (!util.isString(source)) + self.setOptions(source.options).addJSON(source.nested); + else { + parse.filename = filename; + var parsed = parse(source, self, options), + resolved, + i = 0; + if (parsed.imports) + for (; i < parsed.imports.length; ++i) + if (resolved = self.resolvePath(filename, parsed.imports[i])) + fetch(resolved); + if (parsed.weakImports) + for (i = 0; i < parsed.weakImports.length; ++i) + if (resolved = self.resolvePath(filename, parsed.weakImports[i])) + fetch(resolved, true); + } + } catch (err) { + finish(err); + } + if (!sync && !queued) + finish(null, self); // only once anyway + } + + // Fetches a single file + function fetch(filename, weak) { + + // Strip path if this file references a bundled definition + var idx = filename.lastIndexOf("google/protobuf/"); + if (idx > -1) { + var altname = filename.substring(idx); + if (altname in common) + filename = altname; + } + + // Skip if already loaded / attempted + if (self.files.indexOf(filename) > -1) + return; + self.files.push(filename); + + // Shortcut bundled definitions + if (filename in common) { + if (sync) + process(filename, common[filename]); + else { + ++queued; + setTimeout(function () { + --queued; + process(filename, common[filename]); + }); + } + return; + } + + // Otherwise fetch from disk or network + if (sync) { + var source; + try { + source = util.fs.readFileSync(filename).toString("utf8"); + } catch (err) { + if (!weak) + finish(err); + return; + } + process(filename, source); + } else { + ++queued; + util.fetch(filename, function (err, source) { + --queued; + /* istanbul ignore if */ + if (!callback) + return; // terminated meanwhile + if (err) { + /* istanbul ignore else */ + if (!weak) + finish(err); + else if (!queued) // can't be covered reliably + finish(null, self); + return; + } + process(filename, source); + }); + } + } + var queued = 0; + + // Assembling the root namespace doesn't require working type + // references anymore, so we can load everything in parallel + if (util.isString(filename)) + filename = [filename]; + for (var i = 0, resolved; i < filename.length; ++i) + if (resolved = self.resolvePath("", filename[i])) + fetch(resolved); + + if (sync) + return self; + if (!queued) + finish(null, self); + return undefined; + }; + // function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined + + /** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @function Root#load + * @param {string|string[]} filename Names of one or multiple files to load + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @variation 2 + */ + // function load(filename:string, callback:LoadCallback):undefined + + /** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise. + * @function Root#load + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {Promise} Promise + * @variation 3 + */ + // function load(filename:string, [options:IParseOptions]):Promise + + /** + * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only). + * @function Root#loadSync + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {Root} Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + */ + Root.prototype.loadSync = function loadSync(filename, options) { + if (!util.isNode) + throw Error("not supported"); + return this.load(filename, options, SYNC); + }; + + /** + * @override + */ + Root.prototype.resolveAll = function resolveAll() { + if (this.deferred.length) + throw Error("unresolvable extensions: " + this.deferred.map(function (field) { + return "'extend " + field.extend + "' in " + field.parent.fullName; + }).join(", ")); + return Namespace.prototype.resolveAll.call(this); + }; + + // only uppercased (and thus conflict-free) children are exposed, see below + var exposeRe = /^[A-Z]/; + + /** + * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type. + * @param {Root} root Root instance + * @param {Field} field Declaring extension field witin the declaring type + * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise + * @inner + * @ignore + */ + function tryHandleExtension(root, field) { + var extendedType = field.parent.lookup(field.extend); + if (extendedType) { + var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options); + sisterField.declaringField = field; + field.extensionField = sisterField; + extendedType.add(sisterField); + return true; + } + return false; + } + + /** + * Called when any object is added to this root or its sub-namespaces. + * @param {ReflectionObject} object Object added + * @returns {undefined} + * @private + */ + Root.prototype._handleAdd = function _handleAdd(object) { + if (object instanceof Field) { + + if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField) + if (!tryHandleExtension(this, object)) + this.deferred.push(object); + + } else if (object instanceof Enum) { + + if (exposeRe.test(object.name)) + object.parent[object.name] = object.values; // expose enum values as property of its parent + + } else if (!(object instanceof OneOf)) /* everything else is a namespace */ { + + if (object instanceof Type) // Try to handle any deferred extensions + for (var i = 0; i < this.deferred.length;) + if (tryHandleExtension(this, this.deferred[i])) + this.deferred.splice(i, 1); + else + ++i; + for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace + this._handleAdd(object._nestedArray[j]); + if (exposeRe.test(object.name)) + object.parent[object.name] = object; // expose namespace as property of its parent + } + + // The above also adds uppercased (and thus conflict-free) nested types, services and enums as + // properties of namespaces just like static code does. This allows using a .d.ts generated for + // a static module with reflection-based solutions where the condition is met. + }; + + /** + * Called when any object is removed from this root or its sub-namespaces. + * @param {ReflectionObject} object Object removed + * @returns {undefined} + * @private + */ + Root.prototype._handleRemove = function _handleRemove(object) { + if (object instanceof Field) { + + if (/* an extension field */ object.extend !== undefined) { + if (/* already handled */ object.extensionField) { // remove its sister field + object.extensionField.parent.remove(object.extensionField); + object.extensionField = null; + } else { // cancel the extension + var index = this.deferred.indexOf(object); + /* istanbul ignore else */ + if (index > -1) + this.deferred.splice(index, 1); + } + } + + } else if (object instanceof Enum) { + + if (exposeRe.test(object.name)) + delete object.parent[object.name]; // unexpose enum values + + } else if (object instanceof Namespace) { + + for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace + this._handleRemove(object._nestedArray[i]); + + if (exposeRe.test(object.name)) + delete object.parent[object.name]; // unexpose namespaces + + } + }; + + Root._configure = function (Type_, parse_, common_) { + Type = Type_; + parse = parse_; + common = common_; + }; + + }, { "15": 15, "16": 16, "23": 23, "25": 25, "37": 37 }], 30: [function (require, module, exports) { + "use strict"; + module.exports = {}; + + /** + * Named roots. + * This is where pbjs stores generated structures (the option `-r, --root` specifies a name). + * Can also be used manually to make roots available accross modules. + * @name roots + * @type {Object.} + * @example + * // pbjs -r myroot -o compiled.js ... + * + * // in another module: + * require("./compiled.js"); + * + * // in any subsequent module: + * var root = protobuf.roots["myroot"]; + */ + + }, {}], 31: [function (require, module, exports) { + "use strict"; + + /** + * Streaming RPC helpers. + * @namespace + */ + var rpc = exports; + + /** + * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. + * @typedef RPCImpl + * @type {function} + * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called + * @param {Uint8Array} requestData Request data + * @param {RPCImplCallback} callback Callback function + * @returns {undefined} + * @example + * function rpcImpl(method, requestData, callback) { + * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code + * throw Error("no such method"); + * asynchronouslyObtainAResponse(requestData, function(err, responseData) { + * callback(err, responseData); + * }); + * } + */ + + /** + * Node-style callback as used by {@link RPCImpl}. + * @typedef RPCImplCallback + * @type {function} + * @param {Error|null} error Error, if any, otherwise `null` + * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error + * @returns {undefined} + */ + + rpc.Service = require(32); + + }, { "32": 32 }], 32: [function (require, module, exports) { + "use strict"; + module.exports = Service; + + var util = require(39); + + // Extends EventEmitter + (Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; + + /** + * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. + * + * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`. + * @typedef rpc.ServiceMethodCallback + * @template TRes extends Message + * @type {function} + * @param {Error|null} error Error, if any + * @param {TRes} [response] Response message + * @returns {undefined} + */ + + /** + * A service method part of a {@link rpc.Service} as created by {@link Service.create}. + * @typedef rpc.ServiceMethod + * @template TReq extends Message + * @template TRes extends Message + * @type {function} + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message + * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined` + */ + + /** + * Constructs a new RPC service instance. + * @classdesc An RPC service as returned by {@link Service#create}. + * @exports rpc.Service + * @extends util.EventEmitter + * @constructor + * @param {RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ + function Service(rpcImpl, requestDelimited, responseDelimited) { + + if (typeof rpcImpl !== "function") + throw TypeError("rpcImpl must be a function"); + + util.EventEmitter.call(this); + + /** + * RPC implementation. Becomes `null` once the service is ended. + * @type {RPCImpl|null} + */ + this.rpcImpl = rpcImpl; + + /** + * Whether requests are length-delimited. + * @type {boolean} + */ + this.requestDelimited = Boolean(requestDelimited); + + /** + * Whether responses are length-delimited. + * @type {boolean} + */ + this.responseDelimited = Boolean(responseDelimited); + } + + /** + * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}. + * @param {Method|rpc.ServiceMethod} method Reflected or static method + * @param {Constructor} requestCtor Request constructor + * @param {Constructor} responseCtor Response constructor + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} callback Service callback + * @returns {undefined} + * @template TReq extends Message + * @template TRes extends Message + */ + Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { + + if (!request) + throw TypeError("request must be specified"); + + var self = this; + if (!callback) + return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request); + + if (!self.rpcImpl) { + setTimeout(function () { callback(Error("already ended")); }, 0); + return undefined; + } + + try { + return self.rpcImpl( + method, + requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), + function rpcCallback(err, response) { + + if (err) { + self.emit("error", err, method); + return callback(err); + } + + if (response === null) { + self.end(/* endedByRPC */ true); + return undefined; + } + + if (!(response instanceof responseCtor)) { + try { + response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response); + } catch (err) { + self.emit("error", err, method); + return callback(err); + } + } + + self.emit("data", response, method); + return callback(null, response); + } + ); + } catch (err) { + self.emit("error", err, method); + setTimeout(function () { callback(err); }, 0); + return undefined; + } + }; + + /** + * Ends this service and emits the `end` event. + * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation. + * @returns {rpc.Service} `this` + */ + Service.prototype.end = function end(endedByRPC) { + if (this.rpcImpl) { + if (!endedByRPC) // signal end to rpcImpl + this.rpcImpl(null, null, null); + this.rpcImpl = null; + this.emit("end").off(); + } + return this; + }; + + }, { "39": 39 }], 33: [function (require, module, exports) { + "use strict"; + module.exports = Service; + + // extends Namespace + var Namespace = require(23); + ((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service"; + + var Method = require(22), + util = require(37), + rpc = require(31); + + /** + * Constructs a new service instance. + * @classdesc Reflected service. + * @extends NamespaceBase + * @constructor + * @param {string} name Service name + * @param {Object.} [options] Service options + * @throws {TypeError} If arguments are invalid + */ + function Service(name, options) { + Namespace.call(this, name, options); + + /** + * Service methods. + * @type {Object.} + */ + this.methods = {}; // toJSON, marker + + /** + * Cached methods as an array. + * @type {Method[]|null} + * @private + */ + this._methodsArray = null; + } + + /** + * Service descriptor. + * @interface IService + * @extends INamespace + * @property {Object.} methods Method descriptors + */ + + /** + * Constructs a service from a service descriptor. + * @param {string} name Service name + * @param {IService} json Service descriptor + * @returns {Service} Created service + * @throws {TypeError} If arguments are invalid + */ + Service.fromJSON = function fromJSON(name, json) { + var service = new Service(name, json.options); + /* istanbul ignore else */ + if (json.methods) + for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i) + service.add(Method.fromJSON(names[i], json.methods[names[i]])); + if (json.nested) + service.addJSON(json.nested); + return service; + }; + + /** + * Converts this service to a service descriptor. + * @returns {IService} Service descriptor + */ + Service.prototype.toJSON = function toJSON() { + var inherited = Namespace.prototype.toJSON.call(this); + return util.toObject([ + "options", inherited && inherited.options || undefined, + "methods", Namespace.arrayToJSON(this.methodsArray) || /* istanbul ignore next */ {}, + "nested", inherited && inherited.nested || undefined + ]); + }; + + /** + * Methods of this service as an array for iteration. + * @name Service#methodsArray + * @type {Method[]} + * @readonly + */ + Object.defineProperty(Service.prototype, "methodsArray", { + get: function () { + return this._methodsArray || (this._methodsArray = util.toArray(this.methods)); + } + }); + + function clearCache(service) { + service._methodsArray = null; + return service; + } + + /** + * @override + */ + Service.prototype.get = function get(name) { + return this.methods[name] + || Namespace.prototype.get.call(this, name); + }; + + /** + * @override + */ + Service.prototype.resolveAll = function resolveAll() { + var methods = this.methodsArray; + for (var i = 0; i < methods.length; ++i) + methods[i].resolve(); + return Namespace.prototype.resolve.call(this); + }; + + /** + * @override + */ + Service.prototype.add = function add(object) { + + /* istanbul ignore if */ + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + + if (object instanceof Method) { + this.methods[object.name] = object; + object.parent = this; + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); + }; + + /** + * @override + */ + Service.prototype.remove = function remove(object) { + if (object instanceof Method) { + + /* istanbul ignore if */ + if (this.methods[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.methods[object.name]; + object.parent = null; + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); + }; + + /** + * Creates a runtime service using the specified rpc implementation. + * @param {RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed. + */ + Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) { + var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited); + for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) { + var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, ""); + rpcService[methodName] = util.codegen(["r", "c"], util.isReserved(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({ + m: method, + q: method.resolvedRequestType.ctor, + s: method.resolvedResponseType.ctor + }); + } + return rpcService; + }; + + }, { "22": 22, "23": 23, "31": 31, "37": 37 }], 34: [function (require, module, exports) { + "use strict"; + module.exports = tokenize; + + var delimRe = /[\s{}=;:[\],'"()<>]/g, + stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g, + stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g; + + var setCommentRe = /^ *[*/]+ */, + setCommentSplitRe = /\n/g, + whitespaceRe = /\s/, + unescapeRe = /\\(.?)/g; + + var unescapeMap = { + "0": "\0", + "r": "\r", + "n": "\n", + "t": "\t" + }; + + /** + * Unescapes a string. + * @param {string} str String to unescape + * @returns {string} Unescaped string + * @property {Object.} map Special characters map + * @memberof tokenize + */ + function unescape(str) { + return str.replace(unescapeRe, function ($0, $1) { + switch ($1) { + case "\\": + case "": + return $1; + default: + return unescapeMap[$1] || ""; + } + }); + } + + tokenize.unescape = unescape; + + /** + * Gets the next token and advances. + * @typedef TokenizerHandleNext + * @type {function} + * @returns {string|null} Next token or `null` on eof + */ + + /** + * Peeks for the next token. + * @typedef TokenizerHandlePeek + * @type {function} + * @returns {string|null} Next token or `null` on eof + */ + + /** + * Pushes a token back to the stack. + * @typedef TokenizerHandlePush + * @type {function} + * @param {string} token Token + * @returns {undefined} + */ + + /** + * Skips the next token. + * @typedef TokenizerHandleSkip + * @type {function} + * @param {string} expected Expected token + * @param {boolean} [optional=false] If optional + * @returns {boolean} Whether the token matched + * @throws {Error} If the token didn't match and is not optional + */ + + /** + * Gets the comment on the previous line or, alternatively, the line comment on the specified line. + * @typedef TokenizerHandleCmnt + * @type {function} + * @param {number} [line] Line number + * @returns {string|null} Comment text or `null` if none + */ + + /** + * Handle object returned from {@link tokenize}. + * @interface ITokenizerHandle + * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof) + * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof) + * @property {TokenizerHandlePush} push Pushes a token back to the stack + * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws + * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any + * @property {number} line Current line number + */ + + /** + * Tokenizes the given .proto source and returns an object with useful utility functions. + * @param {string} source Source contents + * @returns {ITokenizerHandle} Tokenizer handle + */ + function tokenize(source) { + /* eslint-disable callback-return */ + source = source.toString(); + + var offset = 0, + length = source.length, + line = 1, + commentType = null, + commentText = null, + commentLine = 0, + commentLineEmpty = false; + + var stack = []; + + var stringDelim = null; + + /* istanbul ignore next */ + /** + * Creates an error for illegal syntax. + * @param {string} subject Subject + * @returns {Error} Error created + * @inner + */ + function illegal(subject) { + return Error("illegal " + subject + " (line " + line + ")"); + } + + /** + * Reads a string till its end. + * @returns {string} String read + * @inner + */ + function readString() { + var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe; + re.lastIndex = offset - 1; + var match = re.exec(source); + if (!match) + throw illegal("string"); + offset = re.lastIndex; + push(stringDelim); + stringDelim = null; + return unescape(match[1]); + } + + /** + * Gets the character at `pos` within the source. + * @param {number} pos Position + * @returns {string} Character + * @inner + */ + function charAt(pos) { + return source.charAt(pos); + } + + /** + * Sets the current comment text. + * @param {number} start Start offset + * @param {number} end End offset + * @returns {undefined} + * @inner + */ + function setComment(start, end) { + commentType = source.charAt(start++); + commentLine = line; + commentLineEmpty = false; + var offset = start - 3, // "///" or "/**" + c; + do { + if (--offset < 0 || (c = source.charAt(offset)) === "\n") { + commentLineEmpty = true; + break; + } + } while (c === " " || c === "\t"); + var lines = source + .substring(start, end) + .split(setCommentSplitRe); + for (var i = 0; i < lines.length; ++i) + lines[i] = lines[i].replace(setCommentRe, "").trim(); + commentText = lines + .join("\n") + .trim(); + } + + /** + * Obtains the next token. + * @returns {string|null} Next token or `null` on eof + * @inner + */ + function next() { + if (stack.length > 0) + return stack.shift(); + if (stringDelim) + return readString(); + var repeat, + prev, + curr, + start, + isDoc; + do { + if (offset === length) + return null; + repeat = false; + while (whitespaceRe.test(curr = charAt(offset))) { + if (curr === "\n") + ++line; + if (++offset === length) + return null; + } + if (charAt(offset) === "/") { + if (++offset === length) + throw illegal("comment"); + if (charAt(offset) === "/") { // Line + isDoc = charAt(start = offset + 1) === "/"; + while (charAt(++offset) !== "\n") + if (offset === length) + return null; + ++offset; + if (isDoc) /// Comment + setComment(start, offset - 1); + ++line; + repeat = true; + } else if ((curr = charAt(offset)) === "*") { /* Block */ + isDoc = charAt(start = offset + 1) === "*"; + do { + if (curr === "\n") + ++line; + if (++offset === length) + throw illegal("comment"); + prev = curr; + curr = charAt(offset); + } while (prev !== "*" || curr !== "/"); + ++offset; + if (isDoc) /** Comment */ + setComment(start, offset - 2); + repeat = true; + } else + return "/"; + } + } while (repeat); + + // offset !== length if we got here + + var end = offset; + delimRe.lastIndex = 0; + var delim = delimRe.test(charAt(end++)); + if (!delim) + while (end < length && !delimRe.test(charAt(end))) + ++end; + var token = source.substring(offset, offset = end); + if (token === "\"" || token === "'") + stringDelim = token; + return token; + } + + /** + * Pushes a token back to the stack. + * @param {string} token Token + * @returns {undefined} + * @inner + */ + function push(token) { + stack.push(token); + } + + /** + * Peeks for the next token. + * @returns {string|null} Token or `null` on eof + * @inner + */ + function peek() { + if (!stack.length) { + var token = next(); + if (token === null) + return null; + push(token); + } + return stack[0]; + } + + /** + * Skips a token. + * @param {string} expected Expected token + * @param {boolean} [optional=false] Whether the token is optional + * @returns {boolean} `true` when skipped, `false` if not + * @throws {Error} When a required token is not present + * @inner + */ + function skip(expected, optional) { + var actual = peek(), + equals = actual === expected; + if (equals) { + next(); + return true; + } + if (!optional) + throw illegal("token '" + actual + "', '" + expected + "' expected"); + return false; + } + + /** + * Gets a comment. + * @param {number} [trailingLine] Line number if looking for a trailing comment + * @returns {string|null} Comment text + * @inner + */ + function cmnt(trailingLine) { + var ret = null; + if (trailingLine === undefined) { + if (commentLine === line - 1 && (commentType === "*" || commentLineEmpty)) + ret = commentText; + } else { + /* istanbul ignore else */ + if (commentLine < trailingLine) + peek(); + if (commentLine === trailingLine && !commentLineEmpty && commentType === "/") + ret = commentText; + } + return ret; + } + + return Object.defineProperty({ + next: next, + peek: peek, + push: push, + skip: skip, + cmnt: cmnt + }, "line", { + get: function () { return line; } + }); + /* eslint-enable callback-return */ + } + + }, {}], 35: [function (require, module, exports) { + "use strict"; + module.exports = Type; + + // extends Namespace + var Namespace = require(23); + ((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type"; + + var Enum = require(15), + OneOf = require(25), + Field = require(16), + MapField = require(20), + Service = require(33), + Message = require(21), + Reader = require(27), + Writer = require(42), + util = require(37), + encoder = require(14), + decoder = require(13), + verifier = require(40), + converter = require(12), + wrappers = require(41); + + /** + * Constructs a new reflected message type instance. + * @classdesc Reflected message type. + * @extends NamespaceBase + * @constructor + * @param {string} name Message name + * @param {Object.} [options] Declared options + */ + function Type(name, options) { + Namespace.call(this, name, options); + + /** + * Message fields. + * @type {Object.} + */ + this.fields = {}; // toJSON, marker + + /** + * Oneofs declared within this namespace, if any. + * @type {Object.} + */ + this.oneofs = undefined; // toJSON + + /** + * Extension ranges, if any. + * @type {number[][]} + */ + this.extensions = undefined; // toJSON + + /** + * Reserved ranges, if any. + * @type {Array.} + */ + this.reserved = undefined; // toJSON + + /*? + * Whether this type is a legacy group. + * @type {boolean|undefined} + */ + this.group = undefined; // toJSON + + /** + * Cached fields by id. + * @type {Object.|null} + * @private + */ + this._fieldsById = null; + + /** + * Cached fields as an array. + * @type {Field[]|null} + * @private + */ + this._fieldsArray = null; + + /** + * Cached oneofs as an array. + * @type {OneOf[]|null} + * @private + */ + this._oneofsArray = null; + + /** + * Cached constructor. + * @type {Constructor<{}>} + * @private + */ + this._ctor = null; + } + + Object.defineProperties(Type.prototype, { + + /** + * Message fields by id. + * @name Type#fieldsById + * @type {Object.} + * @readonly + */ + fieldsById: { + get: function () { + + /* istanbul ignore if */ + if (this._fieldsById) + return this._fieldsById; + + this._fieldsById = {}; + for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) { + var field = this.fields[names[i]], + id = field.id; + + /* istanbul ignore if */ + if (this._fieldsById[id]) + throw Error("duplicate id " + id + " in " + this); + + this._fieldsById[id] = field; + } + return this._fieldsById; + } + }, + + /** + * Fields of this message as an array for iteration. + * @name Type#fieldsArray + * @type {Field[]} + * @readonly + */ + fieldsArray: { + get: function () { + return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)); + } + }, + + /** + * Oneofs of this message as an array for iteration. + * @name Type#oneofsArray + * @type {OneOf[]} + * @readonly + */ + oneofsArray: { + get: function () { + return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)); + } + }, + + /** + * The registered constructor, if any registered, otherwise a generic constructor. + * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor. + * @name Type#ctor + * @type {Constructor<{}>} + */ + ctor: { + get: function () { + return this._ctor || (this.ctor = Type.generateConstructor(this)()); + }, + set: function (ctor) { + + // Ensure proper prototype + var prototype = ctor.prototype; + if (!(prototype instanceof Message)) { + (ctor.prototype = new Message()).constructor = ctor; + util.merge(ctor.prototype, prototype); + } + + // Classes and messages reference their reflected type + ctor.$type = ctor.prototype.$type = this; + + // Mix in static methods + util.merge(ctor, Message, true); + + this._ctor = ctor; + + // Messages have non-enumerable default values on their prototype + var i = 0; + for (; i < /* initializes */ this.fieldsArray.length; ++i) + this._fieldsArray[i].resolve(); // ensures a proper value + + // Messages have non-enumerable getters and setters for each virtual oneof field + var ctorProperties = {}; + for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i) + ctorProperties[this._oneofsArray[i].resolve().name] = { + get: util.oneOfGetter(this._oneofsArray[i].oneof), + set: util.oneOfSetter(this._oneofsArray[i].oneof) + }; + if (i) + Object.defineProperties(ctor.prototype, ctorProperties); + } + } + }); + + /** + * Generates a constructor function for the specified type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ + Type.generateConstructor = function generateConstructor(mtype) { + /* eslint-disable no-unexpected-multiline */ + var gen = util.codegen(["p"], mtype.name); + // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype + for (var i = 0, field; i < mtype.fieldsArray.length; ++i) + if ((field = mtype._fieldsArray[i]).map) gen + ("this%s={}", util.safeProp(field.name)); + else if (field.repeated) gen + ("this%s=[]", util.safeProp(field.name)); + return gen + ("if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors + * @property {Object.} fields Field descriptors + * @property {number[][]} [extensions] Extension ranges + * @property {number[][]} [reserved] Reserved ranges + * @property {boolean} [group=false] Whether a legacy group or not + */ + + /** + * Creates a message type from a message type descriptor. + * @param {string} name Message name + * @param {IType} json Message type descriptor + * @returns {Type} Created message type + */ + Type.fromJSON = function fromJSON(name, json) { + var type = new Type(name, json.options); + type.extensions = json.extensions; + type.reserved = json.reserved; + var names = Object.keys(json.fields), + i = 0; + for (; i < names.length; ++i) + type.add( + (typeof json.fields[names[i]].keyType !== "undefined" + ? MapField.fromJSON + : Field.fromJSON)(names[i], json.fields[names[i]]) + ); + if (json.oneofs) + for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i) + type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]])); + if (json.nested) + for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) { + var nested = json.nested[names[i]]; + type.add( // most to least likely + (nested.id !== undefined + ? Field.fromJSON + : nested.fields !== undefined + ? Type.fromJSON + : nested.values !== undefined + ? Enum.fromJSON + : nested.methods !== undefined + ? Service.fromJSON + : Namespace.fromJSON)(names[i], nested) + ); + } + if (json.extensions && json.extensions.length) + type.extensions = json.extensions; + if (json.reserved && json.reserved.length) + type.reserved = json.reserved; + if (json.group) + type.group = true; + return type; + }; + + /** + * Converts this message type to a message type descriptor. + * @returns {IType} Message type descriptor + */ + Type.prototype.toJSON = function toJSON() { + var inherited = Namespace.prototype.toJSON.call(this); + return util.toObject([ + "options", inherited && inherited.options || undefined, + "oneofs", Namespace.arrayToJSON(this.oneofsArray), + "fields", Namespace.arrayToJSON(this.fieldsArray.filter(function (obj) { return !obj.declaringField; })) || {}, + "extensions", this.extensions && this.extensions.length ? this.extensions : undefined, + "reserved", this.reserved && this.reserved.length ? this.reserved : undefined, + "group", this.group || undefined, + "nested", inherited && inherited.nested || undefined + ]); + }; + + /** + * @override + */ + Type.prototype.resolveAll = function resolveAll() { + var fields = this.fieldsArray, i = 0; + while (i < fields.length) + fields[i++].resolve(); + var oneofs = this.oneofsArray; i = 0; + while (i < oneofs.length) + oneofs[i++].resolve(); + return Namespace.prototype.resolveAll.call(this); + }; + + /** + * @override + */ + Type.prototype.get = function get(name) { + return this.fields[name] + || this.oneofs && this.oneofs[name] + || this.nested && this.nested[name] + || null; + }; + + /** + * Adds a nested object to this type. + * @param {ReflectionObject} object Nested object to add + * @returns {Type} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id + */ + Type.prototype.add = function add(object) { + + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + + if (object instanceof Field && object.extend === undefined) { + // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects. + // The root object takes care of adding distinct sister-fields to the respective extended + // type instead. + + // avoids calling the getter if not absolutely necessary because it's called quite frequently + if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id]) + throw Error("duplicate id " + object.id + " in " + this); + if (this.isReservedId(object.id)) + throw Error("id " + object.id + " is reserved in " + this); + if (this.isReservedName(object.name)) + throw Error("name '" + object.name + "' is reserved in " + this); + + if (object.parent) + object.parent.remove(object); + this.fields[object.name] = object; + object.message = this; + object.onAdd(this); + return clearCache(this); + } + if (object instanceof OneOf) { + if (!this.oneofs) + this.oneofs = {}; + this.oneofs[object.name] = object; + object.onAdd(this); + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); + }; + + /** + * Removes a nested object from this type. + * @param {ReflectionObject} object Nested object to remove + * @returns {Type} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this type + */ + Type.prototype.remove = function remove(object) { + if (object instanceof Field && object.extend === undefined) { + // See Type#add for the reason why extension fields are excluded here. + + /* istanbul ignore if */ + if (!this.fields || this.fields[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.fields[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + if (object instanceof OneOf) { + + /* istanbul ignore if */ + if (!this.oneofs || this.oneofs[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.oneofs[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); + }; + + /** + * Tests if the specified id is reserved. + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ + Type.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); + }; + + /** + * Tests if the specified name is reserved. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ + Type.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); + }; + + /** + * Creates a new message of this type using the specified properties. + * @param {Object.} [properties] Properties to set + * @returns {Message<{}>} Message instance + */ + Type.prototype.create = function create(properties) { + return new this.ctor(properties); + }; + + /** + * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}. + * @returns {Type} `this` + */ + Type.prototype.setup = function setup() { + // Sets up everything at once so that the prototype chain does not have to be re-evaluated + // multiple times (V8, soft-deopt prototype-check). + + var fullName = this.fullName, + types = []; + for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i) + types.push(this._fieldsArray[i].resolve().resolvedType); + + // Replace setup methods with type-specific generated functions + this.encode = encoder(this)({ + Writer: Writer, + types: types, + util: util + }); + this.decode = decoder(this)({ + Reader: Reader, + types: types, + util: util + }); + this.verify = verifier(this)({ + types: types, + util: util + }); + this.fromObject = converter.fromObject(this)({ + types: types, + util: util + }); + this.toObject = converter.toObject(this)({ + types: types, + util: util + }); + + // Inject custom wrappers for common types + var wrapper = wrappers[fullName]; + if (wrapper) { + var originalThis = Object.create(this); + // if (wrapper.fromObject) { + originalThis.fromObject = this.fromObject; + this.fromObject = wrapper.fromObject.bind(originalThis); + // } + // if (wrapper.toObject) { + originalThis.toObject = this.toObject; + this.toObject = wrapper.toObject.bind(originalThis); + // } + } + + return this; + }; + + /** + * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages. + * @param {Message<{}>|Object.} message Message instance or plain object + * @param {Writer} [writer] Writer to encode to + * @returns {Writer} writer + */ + Type.prototype.encode = function encode_setup(message, writer) { + return this.setup().encode(message, writer); // overrides this method + }; + + /** + * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages. + * @param {Message<{}>|Object.} message Message instance or plain object + * @param {Writer} [writer] Writer to encode to + * @returns {Writer} writer + */ + Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim(); + }; + + /** + * Decodes a message of this type. + * @param {Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Length of the message, if known beforehand + * @returns {Message<{}>} Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError<{}>} If required fields are missing + */ + Type.prototype.decode = function decode_setup(reader, length) { + return this.setup().decode(reader, length); // overrides this method + }; + + /** + * Decodes a message of this type preceeded by its byte length as a varint. + * @param {Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {Message<{}>} Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError} If required fields are missing + */ + Type.prototype.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof Reader)) + reader = Reader.create(reader); + return this.decode(reader, reader.uint32()); + }; + + /** + * Verifies that field values are valid and that required fields are present. + * @param {Object.} message Plain object to verify + * @returns {null|string} `null` if valid, otherwise the reason why it is not + */ + Type.prototype.verify = function verify_setup(message) { + return this.setup().verify(message); // overrides this method + }; + + /** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param {Object.} object Plain object to convert + * @returns {Message<{}>} Message instance + */ + Type.prototype.fromObject = function fromObject(object) { + return this.setup().fromObject(object); + }; + + /** + * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}. + * @interface IConversionOptions + * @property {Function} [longs] Long conversion type. + * Valid values are `String` and `Number` (the global types). + * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library. + * @property {Function} [enums] Enum value conversion type. + * Only valid value is `String` (the global type). + * Defaults to copy the present value, which is the numeric id. + * @property {Function} [bytes] Bytes value conversion type. + * Valid values are `Array` and (a base64 encoded) `String` (the global types). + * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser. + * @property {boolean} [defaults=false] Also sets default values on the resulting object + * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false` + * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false` + * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any + * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings + */ + + /** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param {Message<{}>} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ + Type.prototype.toObject = function toObject(message, options) { + return this.setup().toObject(message, options); + }; + + /** + * Decorator function as returned by {@link Type.d} (TypeScript). + * @typedef TypeDecorator + * @type {function} + * @param {Constructor} target Target constructor + * @returns {undefined} + * @template T extends Message + */ + + /** + * Type decorator (TypeScript). + * @param {string} [typeName] Type name, defaults to the constructor's name + * @returns {TypeDecorator} Decorator function + * @template T extends Message + */ + Type.d = function decorateType(typeName) { + return function typeDecorator(target) { + util.decorateType(target, typeName); + }; + }; + + }, { "12": 12, "13": 13, "14": 14, "15": 15, "16": 16, "20": 20, "21": 21, "23": 23, "25": 25, "27": 27, "33": 33, "37": 37, "40": 40, "41": 41, "42": 42 }], 36: [function (require, module, exports) { + "use strict"; + + /** + * Common type constants. + * @namespace + */ + var types = exports; + + var util = require(37); + + var s = [ + "double", // 0 + "float", // 1 + "int32", // 2 + "uint32", // 3 + "sint32", // 4 + "fixed32", // 5 + "sfixed32", // 6 + "int64", // 7 + "uint64", // 8 + "sint64", // 9 + "fixed64", // 10 + "sfixed64", // 11 + "bool", // 12 + "string", // 13 + "bytes" // 14 + ]; + + function bake(values, offset) { + var i = 0, o = {}; + offset |= 0; + while (i < values.length) o[s[i + offset]] = values[i++]; + return o; + } + + /** + * Basic type wire types. + * @type {Object.} + * @const + * @property {number} double=1 Fixed64 wire type + * @property {number} float=5 Fixed32 wire type + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + * @property {number} string=2 Ldelim wire type + * @property {number} bytes=2 Ldelim wire type + */ + types.basic = bake([ + /* double */ 1, + /* float */ 5, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0, + /* string */ 2, + /* bytes */ 2 + ]); + + /** + * Basic type defaults. + * @type {Object.} + * @const + * @property {number} double=0 Double default + * @property {number} float=0 Float default + * @property {number} int32=0 Int32 default + * @property {number} uint32=0 Uint32 default + * @property {number} sint32=0 Sint32 default + * @property {number} fixed32=0 Fixed32 default + * @property {number} sfixed32=0 Sfixed32 default + * @property {number} int64=0 Int64 default + * @property {number} uint64=0 Uint64 default + * @property {number} sint64=0 Sint32 default + * @property {number} fixed64=0 Fixed64 default + * @property {number} sfixed64=0 Sfixed64 default + * @property {boolean} bool=false Bool default + * @property {string} string="" String default + * @property {Array.} bytes=Array(0) Bytes default + * @property {null} message=null Message default + */ + types.defaults = bake([ + /* double */ 0, + /* float */ 0, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 0, + /* sfixed32 */ 0, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 0, + /* sfixed64 */ 0, + /* bool */ false, + /* string */ "", + /* bytes */ util.emptyArray, + /* message */ null + ]); + + /** + * Basic long type wire types. + * @type {Object.} + * @const + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + */ + types.long = bake([ + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1 + ], 7); + + /** + * Allowed types for map keys with their associated wire type. + * @type {Object.} + * @const + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + * @property {number} string=2 Ldelim wire type + */ + types.mapKey = bake([ + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0, + /* string */ 2 + ], 2); + + /** + * Allowed types for packed repeated fields with their associated wire type. + * @type {Object.} + * @const + * @property {number} double=1 Fixed64 wire type + * @property {number} float=5 Fixed32 wire type + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + */ + types.packed = bake([ + /* double */ 1, + /* float */ 5, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0 + ]); + + }, { "37": 37 }], 37: [function (require, module, exports) { + "use strict"; + + /** + * Various utility functions. + * @namespace + */ + var util = module.exports = require(39); + + var roots = require(30); + + var Type, // cyclic + Enum; + + util.codegen = require(3); + util.fetch = require(5); + util.path = require(8); + + /** + * Node's fs module if available. + * @type {Object.} + */ + util.fs = util.inquire("fs"); + + /** + * Converts an object's values to an array. + * @param {Object.} object Object to convert + * @returns {Array.<*>} Converted array + */ + util.toArray = function toArray(object) { + if (object) { + var keys = Object.keys(object), + array = new Array(keys.length), + index = 0; + while (index < keys.length) + array[index] = object[keys[index++]]; + return array; + } + return []; + }; + + /** + * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values. + * @param {Array.<*>} array Array to convert + * @returns {Object.} Converted object + */ + util.toObject = function toObject(array) { + var object = {}, + index = 0; + while (index < array.length) { + var key = array[index++], + val = array[index++]; + if (val !== undefined) + object[key] = val; + } + return object; + }; + + var safePropBackslashRe = /\\/g, + safePropQuoteRe = /"/g; + + /** + * Tests whether the specified name is a reserved word in JS. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ + util.isReserved = function isReserved(name) { + return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name); + }; + + /** + * Returns a safe property accessor for the specified property name. + * @param {string} prop Property name + * @returns {string} Safe accessor + */ + util.safeProp = function safeProp(prop) { + if (!/^[$\w_]+$/.test(prop) || util.isReserved(prop)) + return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]"; + return "." + prop; + }; + + /** + * Converts the first character of a string to upper case. + * @param {string} str String to convert + * @returns {string} Converted string + */ + util.ucFirst = function ucFirst(str) { + return str.charAt(0).toUpperCase() + str.substring(1); + }; + + var camelCaseRe = /_([a-z])/g; + + /** + * Converts a string to camel case. + * @param {string} str String to convert + * @returns {string} Converted string + */ + util.camelCase = function camelCase(str) { + return str.substring(0, 1) + + str.substring(1) + .replace(camelCaseRe, function ($0, $1) { return $1.toUpperCase(); }); + }; + + /** + * Compares reflected fields by id. + * @param {Field} a First field + * @param {Field} b Second field + * @returns {number} Comparison value + */ + util.compareFieldsById = function compareFieldsById(a, b) { + return a.id - b.id; + }; + + /** + * Decorator helper for types (TypeScript). + * @param {Constructor} ctor Constructor function + * @param {string} [typeName] Type name, defaults to the constructor's name + * @returns {Type} Reflected type + * @template T extends Message + * @property {Root} root Decorators root + */ + util.decorateType = function decorateType(ctor, typeName) { + + /* istanbul ignore if */ + if (ctor.$type) { + if (typeName && ctor.$type.name !== typeName) { + util.decorateRoot.remove(ctor.$type); + ctor.$type.name = typeName; + util.decorateRoot.add(ctor.$type); + } + return ctor.$type; + } + + /* istanbul ignore next */ + if (!Type) + Type = require(35); + + var type = new Type(typeName || ctor.name); + util.decorateRoot.add(type); + type.ctor = ctor; // sets up .encode, .decode etc. + Object.defineProperty(ctor, "$type", { value: type, enumerable: false }); + Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false }); + return type; + }; + + var decorateEnumIndex = 0; + + /** + * Decorator helper for enums (TypeScript). + * @param {Object} object Enum object + * @returns {Enum} Reflected enum + */ + util.decorateEnum = function decorateEnum(object) { + + /* istanbul ignore if */ + if (object.$type) + return object.$type; + + /* istanbul ignore next */ + if (!Enum) + Enum = require(15); + + var enm = new Enum("Enum" + decorateEnumIndex++, object); + util.decorateRoot.add(enm); + Object.defineProperty(object, "$type", { value: enm, enumerable: false }); + return enm; + }; + + /** + * Decorator root (TypeScript). + * @name util.decorateRoot + * @type {Root} + * @readonly + */ + Object.defineProperty(util, "decorateRoot", { + get: function () { + return roots["decorated"] || (roots["decorated"] = new (require(29))()); + } + }); + + }, { "15": 15, "29": 29, "3": 3, "30": 30, "35": 35, "39": 39, "5": 5, "8": 8 }], 38: [function (require, module, exports) { + "use strict"; + module.exports = LongBits; + + var util = require(39); + + /** + * Constructs new long bits. + * @classdesc Helper class for working with the low and high bits of a 64 bit value. + * @memberof util + * @constructor + * @param {number} lo Low 32 bits, unsigned + * @param {number} hi High 32 bits, unsigned + */ + function LongBits(lo, hi) { + + // note that the casts below are theoretically unnecessary as of today, but older statically + // generated converter code might still call the ctor with signed 32bits. kept for compat. + + /** + * Low bits. + * @type {number} + */ + this.lo = lo >>> 0; + + /** + * High bits. + * @type {number} + */ + this.hi = hi >>> 0; + } + + /** + * Zero bits. + * @memberof util.LongBits + * @type {util.LongBits} + */ + var zero = LongBits.zero = new LongBits(0, 0); + + zero.toNumber = function () { return 0; }; + zero.zzEncode = zero.zzDecode = function () { return this; }; + zero.length = function () { return 1; }; + + /** + * Zero hash. + * @memberof util.LongBits + * @type {string} + */ + var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; + + /** + * Constructs new long bits from the specified number. + * @param {number} value Value + * @returns {util.LongBits} Instance + */ + LongBits.fromNumber = function fromNumber(value) { + if (value === 0) + return zero; + var sign = value < 0; + if (sign) + value = -value; + var lo = value >>> 0, + hi = (value - lo) / 4294967296 >>> 0; + if (sign) { + hi = ~hi >>> 0; + lo = ~lo >>> 0; + if (++lo > 4294967295) { + lo = 0; + if (++hi > 4294967295) + hi = 0; + } + } + return new LongBits(lo, hi); + }; + + /** + * Constructs new long bits from a number, long or string. + * @param {Long|number|string} value Value + * @returns {util.LongBits} Instance + */ + LongBits.from = function from(value) { + if (typeof value === "number") + return LongBits.fromNumber(value); + if (util.isString(value)) { + /* istanbul ignore else */ + if (util.Long) + value = util.Long.fromString(value); + else + return LongBits.fromNumber(parseInt(value, 10)); + } + return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; + }; + + /** + * Converts this long bits to a possibly unsafe JavaScript number. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {number} Possibly unsafe number + */ + LongBits.prototype.toNumber = function toNumber(unsigned) { + if (!unsigned && this.hi >>> 31) { + var lo = ~this.lo + 1 >>> 0, + hi = ~this.hi >>> 0; + if (!lo) + hi = hi + 1 >>> 0; + return -(lo + hi * 4294967296); + } + return this.lo + this.hi * 4294967296; + }; + + /** + * Converts this long bits to a long. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long} Long + */ + LongBits.prototype.toLong = function toLong(unsigned) { + return util.Long + ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) + /* istanbul ignore next */ + : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; + }; + + var charCodeAt = String.prototype.charCodeAt; + + /** + * Constructs new long bits from the specified 8 characters long hash. + * @param {string} hash Hash + * @returns {util.LongBits} Bits + */ + LongBits.fromHash = function fromHash(hash) { + if (hash === zeroHash) + return zero; + return new LongBits( + (charCodeAt.call(hash, 0) + | charCodeAt.call(hash, 1) << 8 + | charCodeAt.call(hash, 2) << 16 + | charCodeAt.call(hash, 3) << 24) >>> 0 + , + (charCodeAt.call(hash, 4) + | charCodeAt.call(hash, 5) << 8 + | charCodeAt.call(hash, 6) << 16 + | charCodeAt.call(hash, 7) << 24) >>> 0 + ); + }; + + /** + * Converts this long bits to a 8 characters long hash. + * @returns {string} Hash + */ + LongBits.prototype.toHash = function toHash() { + return String.fromCharCode( + this.lo & 255, + this.lo >>> 8 & 255, + this.lo >>> 16 & 255, + this.lo >>> 24, + this.hi & 255, + this.hi >>> 8 & 255, + this.hi >>> 16 & 255, + this.hi >>> 24 + ); + }; + + /** + * Zig-zag encodes this long bits. + * @returns {util.LongBits} `this` + */ + LongBits.prototype.zzEncode = function zzEncode() { + var mask = this.hi >> 31; + this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; + this.lo = (this.lo << 1 ^ mask) >>> 0; + return this; + }; + + /** + * Zig-zag decodes this long bits. + * @returns {util.LongBits} `this` + */ + LongBits.prototype.zzDecode = function zzDecode() { + var mask = -(this.lo & 1); + this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; + this.hi = (this.hi >>> 1 ^ mask) >>> 0; + return this; + }; + + /** + * Calculates the length of this longbits when encoded as a varint. + * @returns {number} Length + */ + LongBits.prototype.length = function length() { + var part0 = this.lo, + part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, + part2 = this.hi >>> 24; + return part2 === 0 + ? part1 === 0 + ? part0 < 16384 + ? part0 < 128 ? 1 : 2 + : part0 < 2097152 ? 3 : 4 + : part1 < 16384 + ? part1 < 128 ? 5 : 6 + : part1 < 2097152 ? 7 : 8 + : part2 < 128 ? 9 : 10; + }; + + }, { "39": 39 }], 39: [function (require, module, exports) { + "use strict"; + var util = exports; + + // used to return a Promise where callback is omitted + util.asPromise = require(1); + + // converts to / from base64 encoded strings + util.base64 = require(2); + + // base class of rpc.Service + util.EventEmitter = require(4); + + // float handling accross browsers + util.float = require(6); + + // requires modules optionally and hides the call from bundlers + util.inquire = require(7); + + // converts to / from utf8 encoded strings + util.utf8 = require(10); + + // provides a node-like buffer pool in the browser + util.pool = require(9); + + // utility to work with the low and high bits of a 64 bit value + util.LongBits = require(38); + + /** + * An immuable empty array. + * @memberof util + * @type {Array.<*>} + * @const + */ + util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */[]; // used on prototypes + + /** + * An immutable empty object. + * @type {Object} + * @const + */ + util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes + + /** + * Whether running within node or not. + * @memberof util + * @type {boolean} + * @const + */ + util.isNode = Boolean(global.process && global.process.versions && global.process.versions.node); + + /** + * Tests if the specified value is an integer. + * @function + * @param {*} value Value to test + * @returns {boolean} `true` if the value is an integer + */ + util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) { + return typeof value === "number" && isFinite(value) && Math.floor(value) === value; + }; + + /** + * Tests if the specified value is a string. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a string + */ + util.isString = function isString(value) { + return typeof value === "string" || value instanceof String; + }; + + /** + * Tests if the specified value is a non-null object. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a non-null object + */ + util.isObject = function isObject(value) { + return value && typeof value === "object"; + }; + + /** + * Checks if a property on a message is considered to be present. + * This is an alias of {@link util.isSet}. + * @function + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ + util.isset = + + /** + * Checks if a property on a message is considered to be present. + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ + util.isSet = function isSet(obj, prop) { + var value = obj[prop]; + if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins + return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; + return false; + }; + + /** + * Any compatible Buffer instance. + * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings. + * @interface Buffer + * @extends Uint8Array + */ + + /** + * Node's Buffer class if available. + * @type {Constructor} + */ + util.Buffer = (function () { + try { + var Buffer = util.inquire("buffer").Buffer; + // refuse to use non-node buffers if not explicitly assigned (perf reasons): + return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null; + } catch (e) { + /* istanbul ignore next */ + return null; + } + })(); + + // Internal alias of or polyfull for Buffer.from. + util._Buffer_from = null; + + // Internal alias of or polyfill for Buffer.allocUnsafe. + util._Buffer_allocUnsafe = null; + + /** + * Creates a new buffer of whatever type supported by the environment. + * @param {number|number[]} [sizeOrArray=0] Buffer size or number array + * @returns {Uint8Array|Buffer} Buffer + */ + util.newBuffer = function newBuffer(sizeOrArray) { + /* istanbul ignore next */ + return typeof sizeOrArray === "number" + ? util.Buffer + ? util._Buffer_allocUnsafe(sizeOrArray) + : new util.Array(sizeOrArray) + : util.Buffer + ? util._Buffer_from(sizeOrArray) + : typeof Uint8Array === "undefined" + ? sizeOrArray + : new Uint8Array(sizeOrArray); + }; + + /** + * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. + * @type {Constructor} + */ + util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array; + + /** + * Any compatible Long instance. + * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js. + * @interface Long + * @property {number} low Low bits + * @property {number} high High bits + * @property {boolean} unsigned Whether unsigned or not + */ + + /** + * Long.js's Long class if available. + * @type {Constructor} + */ + util.Long = /* istanbul ignore next */ global.dcodeIO && /* istanbul ignore next */ global.dcodeIO.Long || util.inquire("long"); + + /** + * Regular expression used to verify 2 bit (`bool`) map keys. + * @type {RegExp} + * @const + */ + util.key2Re = /^true|false|0|1$/; + + /** + * Regular expression used to verify 32 bit (`int32` etc.) map keys. + * @type {RegExp} + * @const + */ + util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; + + /** + * Regular expression used to verify 64 bit (`int64` etc.) map keys. + * @type {RegExp} + * @const + */ + util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; + + /** + * Converts a number or long to an 8 characters long hash string. + * @param {Long|number} value Value to convert + * @returns {string} Hash + */ + util.longToHash = function longToHash(value) { + return value + ? util.LongBits.from(value).toHash() + : util.LongBits.zeroHash; + }; + + /** + * Converts an 8 characters long hash string to a long or number. + * @param {string} hash Hash + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long|number} Original value + */ + util.longFromHash = function longFromHash(hash, unsigned) { + var bits = util.LongBits.fromHash(hash); + if (util.Long) + return util.Long.fromBits(bits.lo, bits.hi, unsigned); + return bits.toNumber(Boolean(unsigned)); + }; + + /** + * Merges the properties of the source object into the destination object. + * @memberof util + * @param {Object.} dst Destination object + * @param {Object.} src Source object + * @param {boolean} [ifNotSet=false] Merges only if the key is not already set + * @returns {Object.} Destination object + */ + function merge(dst, src, ifNotSet) { // used by converters + for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) + if (dst[keys[i]] === undefined || !ifNotSet) + dst[keys[i]] = src[keys[i]]; + return dst; + } + + util.merge = merge; + + /** + * Converts the first character of a string to lower case. + * @param {string} str String to convert + * @returns {string} Converted string + */ + util.lcFirst = function lcFirst(str) { + return str.charAt(0).toLowerCase() + str.substring(1); + }; + + /** + * Creates a custom error constructor. + * @memberof util + * @param {string} name Error name + * @returns {Constructor} Custom error constructor + */ + function newError(name) { + + function CustomError(message, properties) { + + if (!(this instanceof CustomError)) + return new CustomError(message, properties); + + // Error.call(this, message); + // ^ just returns a new error instance because the ctor can be called as a function + + Object.defineProperty(this, "message", { get: function () { return message; } }); + + /* istanbul ignore next */ + if (Error.captureStackTrace) // node + Error.captureStackTrace(this, CustomError); + else + Object.defineProperty(this, "stack", { value: (new Error()).stack || "" }); + + if (properties) + merge(this, properties); + } + + (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError; + + Object.defineProperty(CustomError.prototype, "name", { get: function () { return name; } }); + + CustomError.prototype.toString = function toString() { + return this.name + ": " + this.message; + }; + + return CustomError; + } + + util.newError = newError; + + /** + * Constructs a new protocol error. + * @classdesc Error subclass indicating a protocol specifc error. + * @memberof util + * @extends Error + * @template T extends Message + * @constructor + * @param {string} message Error message + * @param {Object.} [properties] Additional properties + * @example + * try { + * MyMessage.decode(someBuffer); // throws if required fields are missing + * } catch (e) { + * if (e instanceof ProtocolError && e.instance) + * console.log("decoded so far: " + JSON.stringify(e.instance)); + * } + */ + util.ProtocolError = newError("ProtocolError"); + + /** + * So far decoded message instance. + * @name util.ProtocolError#instance + * @type {Message} + */ + + /** + * A OneOf getter as returned by {@link util.oneOfGetter}. + * @typedef OneOfGetter + * @type {function} + * @returns {string|undefined} Set field name, if any + */ + + /** + * Builds a getter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfGetter} Unbound getter + */ + util.oneOfGetter = function getOneOf(fieldNames) { + var fieldMap = {}; + for (var i = 0; i < fieldNames.length; ++i) + fieldMap[fieldNames[i]] = 1; + + /** + * @returns {string|undefined} Set field name, if any + * @this Object + * @ignore + */ + return function () { // eslint-disable-line consistent-return + for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i) + if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) + return keys[i]; + }; + }; + + /** + * A OneOf setter as returned by {@link util.oneOfSetter}. + * @typedef OneOfSetter + * @type {function} + * @param {string|undefined} value Field name + * @returns {undefined} + */ + + /** + * Builds a setter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfSetter} Unbound setter + */ + util.oneOfSetter = function setOneOf(fieldNames) { + + /** + * @param {string} name Field name + * @returns {undefined} + * @this Object + * @ignore + */ + return function (name) { + for (var i = 0; i < fieldNames.length; ++i) + if (fieldNames[i] !== name) + delete this[fieldNames[i]]; + }; + }; + + /** + * Default conversion options used for {@link Message#toJSON} implementations. + * + * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely: + * + * - Longs become strings + * - Enums become string keys + * - Bytes become base64 encoded strings + * - (Sub-)Messages become plain objects + * - Maps become plain objects with all string keys + * - Repeated fields become arrays + * - NaN and Infinity for float and double fields become strings + * + * @type {IConversionOptions} + * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json + */ + util.toJSONOptions = { + longs: String, + enums: String, + bytes: String, + json: true + }; + + util._configure = function () { + var Buffer = util.Buffer; + /* istanbul ignore if */ + if (!Buffer) { + util._Buffer_from = util._Buffer_allocUnsafe = null; + return; + } + // because node 4.x buffers are incompatible & immutable + // see: https://github.com/dcodeIO/protobuf.js/pull/665 + util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from || + /* istanbul ignore next */ + function Buffer_from(value, encoding) { + return new Buffer(value, encoding); + }; + util._Buffer_allocUnsafe = Buffer.allocUnsafe || + /* istanbul ignore next */ + function Buffer_allocUnsafe(size) { + return new Buffer(size); + }; + }; + + }, { "1": 1, "10": 10, "2": 2, "38": 38, "4": 4, "6": 6, "7": 7, "9": 9 }], 40: [function (require, module, exports) { + "use strict"; + module.exports = verifier; + + var Enum = require(15), + util = require(37); + + function invalid(field, expected) { + return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:" + field.keyType + "}" : "") + " expected"; + } + + /** + * Generates a partial value verifier. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {number} fieldIndex Field index + * @param {string} ref Variable reference + * @returns {Codegen} Codegen instance + * @ignore + */ + function genVerifyValue(gen, field, fieldIndex, ref) { + /* eslint-disable no-unexpected-multiline */ + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { + gen + ("switch(%s){", ref) + ("default:") + ("return%j", invalid(field, "enum value")); + for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen + ("case %i:", field.resolvedType.values[keys[j]]); + gen + ("break") + ("}"); + } else { + gen + ("{") + ("var e=types[%i].verify(%s);", fieldIndex, ref) + ("if(e)") + ("return%j+e", field.name + ".") + ("}"); + } + } else { + switch (field.type) { + case "int32": + case "uint32": + case "sint32": + case "fixed32": + case "sfixed32": gen + ("if(!util.isInteger(%s))", ref) + ("return%j", invalid(field, "integer")); + break; + case "int64": + case "uint64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref) + ("return%j", invalid(field, "integer|Long")); + break; + case "float": + case "double": gen + ("if(typeof %s!==\"number\")", ref) + ("return%j", invalid(field, "number")); + break; + case "bool": gen + ("if(typeof %s!==\"boolean\")", ref) + ("return%j", invalid(field, "boolean")); + break; + case "string": gen + ("if(!util.isString(%s))", ref) + ("return%j", invalid(field, "string")); + break; + case "bytes": gen + ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref) + ("return%j", invalid(field, "buffer")); + break; + } + } + return gen; + /* eslint-enable no-unexpected-multiline */ + } + + /** + * Generates a partial key verifier. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {string} ref Variable reference + * @returns {Codegen} Codegen instance + * @ignore + */ + function genVerifyKey(gen, field, ref) { + /* eslint-disable no-unexpected-multiline */ + switch (field.keyType) { + case "int32": + case "uint32": + case "sint32": + case "fixed32": + case "sfixed32": gen + ("if(!util.key32Re.test(%s))", ref) + ("return%j", invalid(field, "integer key")); + break; + case "int64": + case "uint64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(!util.key64Re.test(%s))", ref) // see comment above: x is ok, d is not + ("return%j", invalid(field, "integer|Long key")); + break; + case "bool": gen + ("if(!util.key2Re.test(%s))", ref) + ("return%j", invalid(field, "boolean key")); + break; + } + return gen; + /* eslint-enable no-unexpected-multiline */ + } + + /** + * Generates a verifier specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ + function verifier(mtype) { + /* eslint-disable no-unexpected-multiline */ + + var gen = util.codegen(["m"], mtype.name + "$verify") + ("if(typeof m!==\"object\"||m===null)") + ("return%j", "object expected"); + var oneofs = mtype.oneofsArray, + seenFirstField = {}; + if (oneofs.length) gen + ("var p={}"); + + for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), + ref = "m" + util.safeProp(field.name); + + if (field.optional) gen + ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); // !== undefined && !== null + + // map fields + if (field.map) { + gen + ("if(!util.isObject(%s))", ref) + ("return%j", invalid(field, "object")) + ("var k=Object.keys(%s)", ref) + ("for(var i=0;i} + * @const + */ + var wrappers = exports; + + var Message = require(21); + + /** + * From object converter part of an {@link IWrapper}. + * @typedef WrapperFromObjectConverter + * @type {function} + * @param {Object.} object Plain object + * @returns {Message<{}>} Message instance + * @this Type + */ + + /** + * To object converter part of an {@link IWrapper}. + * @typedef WrapperToObjectConverter + * @type {function} + * @param {Message<{}>} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + * @this Type + */ + + /** + * Common type wrapper part of {@link wrappers}. + * @interface IWrapper + * @property {WrapperFromObjectConverter} [fromObject] From object converter + * @property {WrapperToObjectConverter} [toObject] To object converter + */ + + // Custom wrapper for Any + wrappers[".google.protobuf.Any"] = { + + fromObject: function (object) { + + // unwrap value type if mapped + if (object && object["@type"]) { + var type = this.lookup(object["@type"]); + /* istanbul ignore else */ + if (type) { + // type_url does not accept leading "." + var type_url = object["@type"].charAt(0) === "." ? + object["@type"].substr(1) : object["@type"]; + // type_url prefix is optional, but path seperator is required + return this.create({ + type_url: "/" + type_url, + value: type.encode(type.fromObject(object)).finish() + }); + } + } + + return this.fromObject(object); + }, + + toObject: function (message, options) { + + // decode value if requested and unmapped + if (options && options.json && message.type_url && message.value) { + // Only use fully qualified type name after the last '/' + var name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1); + var type = this.lookup(name); + /* istanbul ignore else */ + if (type) + message = type.decode(message.value); + } + + // wrap value if unmapped + if (!(message instanceof this.ctor) && message instanceof Message) { + var object = message.$type.toObject(message, options); + object["@type"] = message.$type.fullName; + return object; + } + + return this.toObject(message, options); + } + }; + + }, { "21": 21 }], 42: [function (require, module, exports) { + "use strict"; + module.exports = Writer; + + var util = require(39); + + var BufferWriter; // cyclic + + var LongBits = util.LongBits, + base64 = util.base64, + utf8 = util.utf8; + + /** + * Constructs a new writer operation instance. + * @classdesc Scheduled writer operation. + * @constructor + * @param {function(*, Uint8Array, number)} fn Function to call + * @param {number} len Value byte length + * @param {*} val Value to write + * @ignore + */ + function Op(fn, len, val) { + + /** + * Function to call. + * @type {function(Uint8Array, number, *)} + */ + this.fn = fn; + + /** + * Value byte length. + * @type {number} + */ + this.len = len; + + /** + * Next operation. + * @type {Writer.Op|undefined} + */ + this.next = undefined; + + /** + * Value to write. + * @type {*} + */ + this.val = val; // type varies + } + + /* istanbul ignore next */ + function noop() { } // eslint-disable-line no-empty-function + + /** + * Constructs a new writer state instance. + * @classdesc Copied writer state. + * @memberof Writer + * @constructor + * @param {Writer} writer Writer to copy state from + * @ignore + */ + function State(writer) { + + /** + * Current head. + * @type {Writer.Op} + */ + this.head = writer.head; + + /** + * Current tail. + * @type {Writer.Op} + */ + this.tail = writer.tail; + + /** + * Current buffer length. + * @type {number} + */ + this.len = writer.len; + + /** + * Next state. + * @type {State|null} + */ + this.next = writer.states; + } + + /** + * Constructs a new writer instance. + * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`. + * @constructor + */ + function Writer() { + + /** + * Current length. + * @type {number} + */ + this.len = 0; + + /** + * Operations head. + * @type {Object} + */ + this.head = new Op(noop, 0, 0); + + /** + * Operations tail + * @type {Object} + */ + this.tail = this.head; + + /** + * Linked forked states. + * @type {Object|null} + */ + this.states = null; + + // When a value is written, the writer calculates its byte length and puts it into a linked + // list of operations to perform when finish() is called. This both allows us to allocate + // buffers of the exact required size and reduces the amount of work we have to do compared + // to first calculating over objects and then encoding over objects. In our case, the encoding + // part is just a linked list walk calling operations with already prepared values. + } + + /** + * Creates a new writer. + * @function + * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} + */ + Writer.create = util.Buffer + ? function create_buffer_setup() { + return (Writer.create = function create_buffer() { + return new BufferWriter(); + })(); + } + /* istanbul ignore next */ + : function create_array() { + return new Writer(); + }; + + /** + * Allocates a buffer of the specified size. + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ + Writer.alloc = function alloc(size) { + return new util.Array(size); + }; + + // Use Uint8Array buffer pool in the browser, just like node does with buffers + /* istanbul ignore else */ + if (util.Array !== Array) + Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); + + /** + * Pushes a new operation to the queue. + * @param {function(Uint8Array, number, *)} fn Function to call + * @param {number} len Value byte length + * @param {number} val Value to write + * @returns {Writer} `this` + * @private + */ + Writer.prototype._push = function push(fn, len, val) { + this.tail = this.tail.next = new Op(fn, len, val); + this.len += len; + return this; + }; + + function writeByte(val, buf, pos) { + buf[pos] = val & 255; + } + + function writeVarint32(val, buf, pos) { + while (val > 127) { + buf[pos++] = val & 127 | 128; + val >>>= 7; + } + buf[pos] = val; + } + + /** + * Constructs a new varint writer operation instance. + * @classdesc Scheduled varint writer operation. + * @extends Op + * @constructor + * @param {number} len Value byte length + * @param {number} val Value to write + * @ignore + */ + function VarintOp(len, val) { + this.len = len; + this.next = undefined; + this.val = val; + } + + VarintOp.prototype = Object.create(Op.prototype); + VarintOp.prototype.fn = writeVarint32; + + /** + * Writes an unsigned 32 bit value as a varint. + * @param {number} value Value to write + * @returns {Writer} `this` + */ + Writer.prototype.uint32 = function write_uint32(value) { + // here, the call to this.push has been inlined and a varint specific Op subclass is used. + // uint32 is by far the most frequently used operation and benefits significantly from this. + this.len += (this.tail = this.tail.next = new VarintOp( + (value = value >>> 0) + < 128 ? 1 + : value < 16384 ? 2 + : value < 2097152 ? 3 + : value < 268435456 ? 4 + : 5, + value)).len; + return this; + }; + + /** + * Writes a signed 32 bit value as a varint. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ + Writer.prototype.int32 = function write_int32(value) { + return value < 0 + ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec + : this.uint32(value); + }; + + /** + * Writes a 32 bit value as a varint, zig-zag encoded. + * @param {number} value Value to write + * @returns {Writer} `this` + */ + Writer.prototype.sint32 = function write_sint32(value) { + return this.uint32((value << 1 ^ value >> 31) >>> 0); + }; + + function writeVarint64(val, buf, pos) { + while (val.hi) { + buf[pos++] = val.lo & 127 | 128; + val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; + val.hi >>>= 7; + } + while (val.lo > 127) { + buf[pos++] = val.lo & 127 | 128; + val.lo = val.lo >>> 7; + } + buf[pos++] = val.lo; + } + + /** + * Writes an unsigned 64 bit value as a varint. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + Writer.prototype.uint64 = function write_uint64(value) { + var bits = LongBits.from(value); + return this._push(writeVarint64, bits.length(), bits); + }; + + /** + * Writes a signed 64 bit value as a varint. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + Writer.prototype.int64 = Writer.prototype.uint64; + + /** + * Writes a signed 64 bit value as a varint, zig-zag encoded. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + Writer.prototype.sint64 = function write_sint64(value) { + var bits = LongBits.from(value).zzEncode(); + return this._push(writeVarint64, bits.length(), bits); + }; + + /** + * Writes a boolish value as a varint. + * @param {boolean} value Value to write + * @returns {Writer} `this` + */ + Writer.prototype.bool = function write_bool(value) { + return this._push(writeByte, 1, value ? 1 : 0); + }; + + function writeFixed32(val, buf, pos) { + buf[pos] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; + } + + /** + * Writes an unsigned 32 bit value as fixed 32 bits. + * @param {number} value Value to write + * @returns {Writer} `this` + */ + Writer.prototype.fixed32 = function write_fixed32(value) { + return this._push(writeFixed32, 4, value >>> 0); + }; + + /** + * Writes a signed 32 bit value as fixed 32 bits. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ + Writer.prototype.sfixed32 = Writer.prototype.fixed32; + + /** + * Writes an unsigned 64 bit value as fixed 64 bits. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + Writer.prototype.fixed64 = function write_fixed64(value) { + var bits = LongBits.from(value); + return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); + }; + + /** + * Writes a signed 64 bit value as fixed 64 bits. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + Writer.prototype.sfixed64 = Writer.prototype.fixed64; + + /** + * Writes a float (32 bit). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ + Writer.prototype.float = function write_float(value) { + return this._push(util.float.writeFloatLE, 4, value); + }; + + /** + * Writes a double (64 bit float). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ + Writer.prototype.double = function write_double(value) { + return this._push(util.float.writeDoubleLE, 8, value); + }; + + var writeBytes = util.Array.prototype.set + ? function writeBytes_set(val, buf, pos) { + buf.set(val, pos); // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytes_for(val, buf, pos) { + for (var i = 0; i < val.length; ++i) + buf[pos + i] = val[i]; + }; + + /** + * Writes a sequence of bytes. + * @param {Uint8Array|string} value Buffer or base64 encoded string to write + * @returns {Writer} `this` + */ + Writer.prototype.bytes = function write_bytes(value) { + var len = value.length >>> 0; + if (!len) + return this._push(writeByte, 1, 0); + if (util.isString(value)) { + var buf = Writer.alloc(len = base64.length(value)); + base64.decode(value, buf, 0); + value = buf; + } + return this.uint32(len)._push(writeBytes, len, value); + }; + + /** + * Writes a string. + * @param {string} value Value to write + * @returns {Writer} `this` + */ + Writer.prototype.string = function write_string(value) { + var len = utf8.length(value); + return len + ? this.uint32(len)._push(utf8.write, len, value) + : this._push(writeByte, 1, 0); + }; + + /** + * Forks this writer's state by pushing it to a stack. + * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state. + * @returns {Writer} `this` + */ + Writer.prototype.fork = function fork() { + this.states = new State(this); + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + return this; + }; + + /** + * Resets this instance to the last state. + * @returns {Writer} `this` + */ + Writer.prototype.reset = function reset() { + if (this.states) { + this.head = this.states.head; + this.tail = this.states.tail; + this.len = this.states.len; + this.states = this.states.next; + } else { + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + } + return this; + }; + + /** + * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. + * @returns {Writer} `this` + */ + Writer.prototype.ldelim = function ldelim() { + var head = this.head, + tail = this.tail, + len = this.len; + this.reset().uint32(len); + if (len) { + this.tail.next = head.next; // skip noop + this.tail = tail; + this.len += len; + } + return this; + }; + + /** + * Finishes the write operation. + * @returns {Uint8Array} Finished buffer + */ + Writer.prototype.finish = function finish() { + var head = this.head.next, // skip noop + buf = this.constructor.alloc(this.len), + pos = 0; + while (head) { + head.fn(head.val, buf, pos); + pos += head.len; + head = head.next; + } + // this.head = this.tail = null; + return buf; + }; + + Writer._configure = function (BufferWriter_) { + BufferWriter = BufferWriter_; + }; + + }, { "39": 39 }], 43: [function (require, module, exports) { + "use strict"; + module.exports = BufferWriter; + + // extends Writer + var Writer = require(42); + (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; + + var util = require(39); + + var Buffer = util.Buffer; + + /** + * Constructs a new buffer writer instance. + * @classdesc Wire format writer using node buffers. + * @extends Writer + * @constructor + */ + function BufferWriter() { + Writer.call(this); + } + + /** + * Allocates a buffer of the specified size. + * @param {number} size Buffer size + * @returns {Buffer} Buffer + */ + BufferWriter.alloc = function alloc_buffer(size) { + return (BufferWriter.alloc = util._Buffer_allocUnsafe)(size); + }; + + var writeBytesBuffer = Buffer && Buffer.prototype instanceof Uint8Array && Buffer.prototype.set.name === "set" + ? function writeBytesBuffer_set(val, buf, pos) { + buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited) + // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytesBuffer_copy(val, buf, pos) { + if (val.copy) // Buffer values + val.copy(buf, pos, 0, val.length); + else for (var i = 0; i < val.length;) // plain array values + buf[pos++] = val[i++]; + }; + + /** + * @override + */ + BufferWriter.prototype.bytes = function write_bytes_buffer(value) { + if (util.isString(value)) + value = util._Buffer_from(value, "base64"); + var len = value.length >>> 0; + this.uint32(len); + if (len) + this._push(writeBytesBuffer, len, value); + return this; + }; + + function writeStringBuffer(val, buf, pos) { + if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions) + util.utf8.write(val, buf, pos); + else + buf.utf8Write(val, pos); + } + + /** + * @override + */ + BufferWriter.prototype.string = function write_string_buffer(value) { + var len = Buffer.byteLength(value); + this.uint32(len); + if (len) + this._push(writeStringBuffer, len, value); + return this; + }; + + + /** + * Finishes the write operation. + * @name BufferWriter#finish + * @function + * @returns {Buffer} Finished buffer + */ + + }, { "39": 39, "42": 42 }] + }, {}, [19]) + +})(typeof window === "object" && window || typeof self === "object" && self || this); \ No newline at end of file diff --git a/protubuf/protobuf-egret/dist/protobuf-library.min.js b/protubuf/protobuf-egret/dist/protobuf-library.min.js new file mode 100644 index 0000000..91ba8a9 --- /dev/null +++ b/protubuf/protobuf-egret/dist/protobuf-library.min.js @@ -0,0 +1 @@ +(function(global,undefined){"use strict";(function prelude(modules,cache,entries){function $require(name){var $module=cache[name];if(!$module)modules[name][0].call($module=cache[name]={exports:{}},$require,$module,$module.exports);return $module.exports}var protobuf=global.protobuf=$require(entries[0]);if(typeof define==="function"&&define.amd)define(["long"],function(Long){if(Long&&Long.isLong){protobuf.util.Long=Long;protobuf.configure()}return protobuf});if(typeof module==="object"&&module&&module.exports)module.exports=protobuf})({1:[function(require,module,exports){"use strict";module.exports=asPromise;function asPromise(fn,ctx){var params=new Array(arguments.length-1),offset=0,index=2,pending=true;while(index1&&string.charAt(p)==="=")++n;return Math.ceil(string.length*3)/4-n};var b64=new Array(64);var s64=new Array(123);for(var i=0;i<64;)s64[b64[i]=i<26?i+65:i<52?i+71:i<62?i-4:i-59|43]=i++;base64.encode=function encode(buffer,start,end){var parts=null,chunk=[];var i=0,j=0,t;while(start>2];t=(b&3)<<4;j=1;break;case 1:chunk[i++]=b64[t|b>>4];t=(b&15)<<2;j=2;break;case 2:chunk[i++]=b64[t|b>>6];chunk[i++]=b64[b&63];j=0;break}if(i>8191){(parts||(parts=[])).push(String.fromCharCode.apply(String,chunk));i=0}}if(j){chunk[i++]=b64[t];chunk[i++]=61;if(j===1)chunk[i++]=61}if(parts){if(i)parts.push(String.fromCharCode.apply(String,chunk.slice(0,i)));return parts.join("")}return String.fromCharCode.apply(String,chunk.slice(0,i))};var invalidEncoding="invalid encoding";base64.decode=function decode(string,buffer,offset){var start=offset;var j=0,t;for(var i=0;i1)break;if((c=s64[c])===undefined)throw Error(invalidEncoding);switch(j){case 0:t=c;j=1;break;case 1:buffer[offset++]=t<<2|(c&48)>>4;t=c;j=2;break;case 2:buffer[offset++]=(t&15)<<4|(c&60)>>2;t=c;j=3;break;case 3:buffer[offset++]=(t&3)<<6|c;j=0;break}}if(j===1)throw Error(invalidEncoding);return offset-start};base64.test=function test(string){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string)}},{}],3:[function(require,module,exports){"use strict";module.exports=codegen;function codegen(functionParams,functionName){if(typeof functionParams==="string"){functionName=functionParams;functionParams=undefined}var body=[];function Codegen(formatStringOrScope){if(typeof formatStringOrScope!=="string"){var source=toString();if(codegen.verbose)console.log("codegen: "+source);source="return "+source;if(formatStringOrScope){var scopeKeys=Object.keys(formatStringOrScope),scopeParams=new Array(scopeKeys.length+1),scopeValues=new Array(scopeKeys.length),scopeOffset=0;while(scopeOffset0?0:2147483648,buf,pos);else if(isNaN(val))writeUint(2143289344,buf,pos);else if(val>3.4028234663852886e38)writeUint((sign<<31|2139095040)>>>0,buf,pos);else if(val<1.1754943508222875e-38)writeUint((sign<<31|Math.round(val/1.401298464324817e-45))>>>0,buf,pos);else{var exponent=Math.floor(Math.log(val)/Math.LN2),mantissa=Math.round(val*Math.pow(2,-exponent)*8388608)&8388607;writeUint((sign<<31|exponent+127<<23|mantissa)>>>0,buf,pos)}}exports.writeFloatLE=writeFloat_ieee754.bind(null,writeUintLE);exports.writeFloatBE=writeFloat_ieee754.bind(null,writeUintBE);function readFloat_ieee754(readUint,buf,pos){var uint=readUint(buf,pos),sign=(uint>>31)*2+1,exponent=uint>>>23&255,mantissa=uint&8388607;return exponent===255?mantissa?NaN:sign*Infinity:exponent===0?sign*1.401298464324817e-45*mantissa:sign*Math.pow(2,exponent-150)*(mantissa+8388608)}exports.readFloatLE=readFloat_ieee754.bind(null,readUintLE);exports.readFloatBE=readFloat_ieee754.bind(null,readUintBE)})();if(typeof Float64Array!=="undefined")(function(){var f64=new Float64Array([-0]),f8b=new Uint8Array(f64.buffer),le=f8b[7]===128;function writeDouble_f64_cpy(val,buf,pos){f64[0]=val;buf[pos]=f8b[0];buf[pos+1]=f8b[1];buf[pos+2]=f8b[2];buf[pos+3]=f8b[3];buf[pos+4]=f8b[4];buf[pos+5]=f8b[5];buf[pos+6]=f8b[6];buf[pos+7]=f8b[7]}function writeDouble_f64_rev(val,buf,pos){f64[0]=val;buf[pos]=f8b[7];buf[pos+1]=f8b[6];buf[pos+2]=f8b[5];buf[pos+3]=f8b[4];buf[pos+4]=f8b[3];buf[pos+5]=f8b[2];buf[pos+6]=f8b[1];buf[pos+7]=f8b[0]}exports.writeDoubleLE=le?writeDouble_f64_cpy:writeDouble_f64_rev;exports.writeDoubleBE=le?writeDouble_f64_rev:writeDouble_f64_cpy;function readDouble_f64_cpy(buf,pos){f8b[0]=buf[pos];f8b[1]=buf[pos+1];f8b[2]=buf[pos+2];f8b[3]=buf[pos+3];f8b[4]=buf[pos+4];f8b[5]=buf[pos+5];f8b[6]=buf[pos+6];f8b[7]=buf[pos+7];return f64[0]}function readDouble_f64_rev(buf,pos){f8b[7]=buf[pos];f8b[6]=buf[pos+1];f8b[5]=buf[pos+2];f8b[4]=buf[pos+3];f8b[3]=buf[pos+4];f8b[2]=buf[pos+5];f8b[1]=buf[pos+6];f8b[0]=buf[pos+7];return f64[0]}exports.readDoubleLE=le?readDouble_f64_cpy:readDouble_f64_rev;exports.readDoubleBE=le?readDouble_f64_rev:readDouble_f64_cpy})();else(function(){function writeDouble_ieee754(writeUint,off0,off1,val,buf,pos){var sign=val<0?1:0;if(sign)val=-val;if(val===0){writeUint(0,buf,pos+off0);writeUint(1/val>0?0:2147483648,buf,pos+off1)}else if(isNaN(val)){writeUint(0,buf,pos+off0);writeUint(2146959360,buf,pos+off1)}else if(val>1.7976931348623157e308){writeUint(0,buf,pos+off0);writeUint((sign<<31|2146435072)>>>0,buf,pos+off1)}else{var mantissa;if(val<2.2250738585072014e-308){mantissa=val/5e-324;writeUint(mantissa>>>0,buf,pos+off0);writeUint((sign<<31|mantissa/4294967296)>>>0,buf,pos+off1)}else{var exponent=Math.floor(Math.log(val)/Math.LN2);if(exponent===1024)exponent=1023;mantissa=val*Math.pow(2,-exponent);writeUint(mantissa*4503599627370496>>>0,buf,pos+off0);writeUint((sign<<31|exponent+1023<<20|mantissa*1048576&1048575)>>>0,buf,pos+off1)}}}exports.writeDoubleLE=writeDouble_ieee754.bind(null,writeUintLE,0,4);exports.writeDoubleBE=writeDouble_ieee754.bind(null,writeUintBE,4,0);function readDouble_ieee754(readUint,off0,off1,buf,pos){var lo=readUint(buf,pos+off0),hi=readUint(buf,pos+off1);var sign=(hi>>31)*2+1,exponent=hi>>>20&2047,mantissa=4294967296*(hi&1048575)+lo;return exponent===2047?mantissa?NaN:sign*Infinity:exponent===0?sign*5e-324*mantissa:sign*Math.pow(2,exponent-1075)*(mantissa+4503599627370496)}exports.readDoubleLE=readDouble_ieee754.bind(null,readUintLE,0,4);exports.readDoubleBE=readDouble_ieee754.bind(null,readUintBE,4,0)})();return exports}function writeUintLE(val,buf,pos){buf[pos]=val&255;buf[pos+1]=val>>>8&255;buf[pos+2]=val>>>16&255;buf[pos+3]=val>>>24}function writeUintBE(val,buf,pos){buf[pos]=val>>>24;buf[pos+1]=val>>>16&255;buf[pos+2]=val>>>8&255;buf[pos+3]=val&255}function readUintLE(buf,pos){return(buf[pos]|buf[pos+1]<<8|buf[pos+2]<<16|buf[pos+3]<<24)>>>0}function readUintBE(buf,pos){return(buf[pos]<<24|buf[pos+1]<<16|buf[pos+2]<<8|buf[pos+3])>>>0}},{}],7:[function(require,module,exports){"use strict";module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}},{}],8:[function(require,module,exports){"use strict";var path=exports;var isAbsolute=path.isAbsolute=function isAbsolute(path){return/^(?:\/|\w+:)/.test(path)};var normalize=path.normalize=function normalize(path){path=path.replace(/\\/g,"/").replace(/\/{2,}/g,"/");var parts=path.split("/"),absolute=isAbsolute(path),prefix="";if(absolute)prefix=parts.shift()+"/";for(var i=0;i0&&parts[i-1]!=="..")parts.splice(--i,2);else if(absolute)parts.splice(i,1);else++i}else if(parts[i]===".")parts.splice(i,1);else++i}return prefix+parts.join("/")};path.resolve=function resolve(originPath,includePath,alreadyNormalized){if(!alreadyNormalized)includePath=normalize(includePath);if(isAbsolute(includePath))return includePath;if(!alreadyNormalized)originPath=normalize(originPath);return(originPath=originPath.replace(/(?:\/|^)[^/]+$/,"")).length?normalize(originPath+"/"+includePath):includePath}},{}],9:[function(require,module,exports){"use strict";module.exports=pool;function pool(alloc,slice,size){var SIZE=size||8192;var MAX=SIZE>>>1;var slab=null;var offset=SIZE;return function pool_alloc(size){if(size<1||size>MAX)return alloc(size);if(offset+size>SIZE){slab=alloc(SIZE);offset=0}var buf=slice.call(slab,offset,offset+=size);if(offset&7)offset=(offset|7)+1;return buf}}},{}],10:[function(require,module,exports){"use strict";var utf8=exports;utf8.length=function utf8_length(string){var len=0,c=0;for(var i=0;i191&&t<224)chunk[i++]=(t&31)<<6|buffer[start++]&63;else if(t>239&&t<365){t=((t&7)<<18|(buffer[start++]&63)<<12|(buffer[start++]&63)<<6|buffer[start++]&63)-65536;chunk[i++]=55296+(t>>10);chunk[i++]=56320+(t&1023)}else chunk[i++]=(t&15)<<12|(buffer[start++]&63)<<6|buffer[start++]&63;if(i>8191){(parts||(parts=[])).push(String.fromCharCode.apply(String,chunk));i=0}}if(parts){if(i)parts.push(String.fromCharCode.apply(String,chunk.slice(0,i)));return parts.join("")}return String.fromCharCode.apply(String,chunk.slice(0,i))};utf8.write=function utf8_write(string,buffer,offset){var start=offset,c1,c2;for(var i=0;i>6|192;buffer[offset++]=c1&63|128}else if((c1&64512)===55296&&((c2=string.charCodeAt(i+1))&64512)===56320){c1=65536+((c1&1023)<<10)+(c2&1023);++i;buffer[offset++]=c1>>18|240;buffer[offset++]=c1>>12&63|128;buffer[offset++]=c1>>6&63|128;buffer[offset++]=c1&63|128}else{buffer[offset++]=c1>>12|224;buffer[offset++]=c1>>6&63|128;buffer[offset++]=c1&63|128}}return offset-start}},{}],11:[function(require,module,exports){"use strict";module.exports=common;var commonRe=/\/|\./;function common(name,json){if(!commonRe.test(name)){name="google/protobuf/"+name+".proto";json={nested:{google:{nested:{protobuf:{nested:json}}}}}}common[name]=json}common("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var timeType;common("duration",{Duration:timeType={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}});common("timestamp",{Timestamp:timeType});common("empty",{Empty:{fields:{}}});common("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}});common("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}});common.get=function get(file){return common[file]||null}},{}],12:[function(require,module,exports){"use strict";var converter=exports;var Enum=require(15),util=require(37);function genValuePartial_fromObject(gen,field,fieldIndex,prop){if(field.resolvedType){if(field.resolvedType instanceof Enum){gen("switch(d%s){",prop);for(var values=field.resolvedType.values,keys=Object.keys(values),i=0;i>>0",prop,prop);break;case"int32":case"sint32":case"sfixed32":gen("m%s=d%s|0",prop,prop);break;case"uint64":isUnsigned=true;case"int64":case"sint64":case"fixed64":case"sfixed64":gen("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",prop,prop,isUnsigned)('else if(typeof d%s==="string")',prop)("m%s=parseInt(d%s,10)",prop,prop)('else if(typeof d%s==="number")',prop)("m%s=d%s",prop,prop)('else if(typeof d%s==="object")',prop)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",prop,prop,prop,isUnsigned?"true":"");break;case"bytes":gen('if(typeof d%s==="string")',prop)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",prop,prop,prop)("else if(d%s.length)",prop)("m%s=d%s",prop,prop);break;case"string":gen("m%s=String(d%s)",prop,prop);break;case"bool":gen("m%s=Boolean(d%s)",prop,prop);break}}return gen}converter.fromObject=function fromObject(mtype){var fields=mtype.fieldsArray;var gen=util.codegen(["d"],mtype.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!fields.length)return gen("return new this.ctor");gen("var m=new this.ctor");for(var i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s",prop,prop,prop,prop,isUnsigned?"true":"",prop);break;case"bytes":gen("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",prop,prop,prop,prop,prop);break;default:gen("d%s=m%s",prop,prop);break}}return gen}converter.toObject=function toObject(mtype){var fields=mtype.fieldsArray.slice().sort(util.compareFieldsById);if(!fields.length)return util.codegen()("return {}");var gen=util.codegen(["m","o"],mtype.name+"$toObject")("if(!o)")("o={}")("var d={}");var repeatedFields=[],mapFields=[],normalFields=[],i=0;for(;i>>3){");var i=0;for(;i>>0,(field.id<<3|4)>>>0):gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",fieldIndex,ref,(field.id<<3|2)>>>0)}function encoder(mtype){var gen=util.codegen(["m","w"],mtype.name+"$encode")("if(!w)")("w=Writer.create()");var i,ref;var fields=mtype.fieldsArray.slice().sort(util.compareFieldsById);for(var i=0;i>>0,8|types.mapKey[field.keyType],field.keyType);if(wireType===undefined)gen("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",index,ref);else gen(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|wireType,type,ref);gen("}")("}")}else if(field.repeated){gen("if(%s!=null&&%s.length){",ref,ref);if(field.packed&&types.packed[type]!==undefined){gen("w.uint32(%i).fork()",(field.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",ref)("w.%s(%s[i])",type,ref)("w.ldelim()")}else{gen("for(var i=0;i<%s.length;++i)",ref);if(wireType===undefined)genTypePartial(gen,field,index,ref+"[i]");else gen("w.uint32(%i).%s(%s[i])",(field.id<<3|wireType)>>>0,type,ref)}gen("}")}else{if(field.optional)gen("if(%s!=null&&m.hasOwnProperty(%j))",ref,field.name);if(wireType===undefined)genTypePartial(gen,field,index,ref);else gen("w.uint32(%i).%s(%s)",(field.id<<3|wireType)>>>0,type,ref)}}return gen("return w")}},{15:15,36:36,37:37}],15:[function(require,module,exports){"use strict";module.exports=Enum;var ReflectionObject=require(24);((Enum.prototype=Object.create(ReflectionObject.prototype)).constructor=Enum).className="Enum";var Namespace=require(23),util=require(37);function Enum(name,values,options){ReflectionObject.call(this,name,options);if(values&&typeof values!=="object")throw TypeError("values must be an object");this.valuesById={};this.values=Object.create(this.valuesById);this.comments={};this.reserved=undefined;if(values)for(var keys=Object.keys(values),i=0;i=id)return true;return false};Namespace.isReservedName=function isReservedName(reserved,name){if(reserved)for(var i=0;i0){var part=path.shift();if(ptr.nested&&ptr.nested[part]){ptr=ptr.nested[part];if(!(ptr instanceof Namespace))throw Error("path conflicts with non-namespace objects")}else ptr.add(ptr=new Namespace(part))}if(json)ptr.addJSON(json);return ptr};Namespace.prototype.resolveAll=function resolveAll(){var nested=this.nestedArray,i=0;while(i-1)return found}else if(found instanceof Namespace&&(found=found.lookup(path.slice(1),filterTypes,true)))return found}else for(var i=0;i-1)this.oneof.splice(index,1);field.partOf=null;return this};OneOf.prototype.onAdd=function onAdd(parent){ReflectionObject.prototype.onAdd.call(this,parent);var self=this;for(var i=0;i");var name=next();if(!nameRe.test(name))throw illegal(name,"name");skip("=");var field=new MapField(applyCase(name),parseId(next()),keyType,valueType);ifBlock(field,function parseMapField_block(token){if(token==="option"){parseOption(field,token);skip(";")}else throw illegal(token)},function parseMapField_line(){parseInlineOptions(field)});parent.add(field)}function parseOneOf(parent,token){if(!nameRe.test(token=next()))throw illegal(token,"name");var oneof=new OneOf(applyCase(token));ifBlock(oneof,function parseOneOf_block(token){if(token==="option"){parseOption(oneof,token);skip(";")}else{push(token);parseField(oneof,"optional")}});parent.add(oneof)}function parseEnum(parent,token){if(!nameRe.test(token=next()))throw illegal(token,"name");var enm=new Enum(token);ifBlock(enm,function parseEnum_block(token){switch(token){case"option":parseOption(enm,token);skip(";");break;case"reserved":readRanges(enm.reserved||(enm.reserved=[]),true);break;default:parseEnumValue(enm,token)}});parent.add(enm)}function parseEnumValue(parent,token){if(!nameRe.test(token))throw illegal(token,"name");skip("=");var value=parseId(next(),true),dummy={};ifBlock(dummy,function parseEnumValue_block(token){if(token==="option"){parseOption(dummy,token);skip(";")}else throw illegal(token)},function parseEnumValue_line(){parseInlineOptions(dummy)});parent.add(token,value,dummy.comment)}function parseOption(parent,token){var isCustom=skip("(",true);if(!typeRefRe.test(token=next()))throw illegal(token,"name");var name=token;if(isCustom){skip(")");name="("+name+")";token=peek();if(fqTypeRefRe.test(token)){name+=token;next()}}skip("=");parseOptionValue(parent,name)}function parseOptionValue(parent,name){if(skip("{",true)){do{if(!nameRe.test(token=next()))throw illegal(token,"name");if(peek()==="{")parseOptionValue(parent,name+"."+token);else{skip(":");if(peek()==="{")parseOptionValue(parent,name+"."+token);else setOption(parent,name+"."+token,readValue(true))}}while(!skip("}",true))}else setOption(parent,name,readValue(true))}function setOption(parent,name,value){if(parent.setOption)parent.setOption(name,value)}function parseInlineOptions(parent){if(skip("[",true)){do{parseOption(parent,"option")}while(skip(",",true));skip("]")}return parent}function parseService(parent,token){if(!nameRe.test(token=next()))throw illegal(token,"service name");var service=new Service(token);ifBlock(service,function parseService_block(token){if(parseCommon(service,token))return;if(token==="rpc")parseMethod(service,token);else throw illegal(token)});parent.add(service)}function parseMethod(parent,token){var type=token;if(!nameRe.test(token=next()))throw illegal(token,"name");var name=token,requestType,requestStream,responseType,responseStream;skip("(");if(skip("stream",true))requestStream=true;if(!typeRefRe.test(token=next()))throw illegal(token);requestType=token;skip(")");skip("returns");skip("(");if(skip("stream",true))responseStream=true;if(!typeRefRe.test(token=next()))throw illegal(token);responseType=token;skip(")");var method=new Method(name,type,requestType,responseType,requestStream,responseStream);ifBlock(method,function parseMethod_block(token){if(token==="option"){parseOption(method,token);skip(";")}else throw illegal(token)});parent.add(method)}function parseExtension(parent,token){if(!typeRefRe.test(token=next()))throw illegal(token,"reference");var reference=token;ifBlock(null,function parseExtension_block(token){switch(token){case"required":case"repeated":case"optional":parseField(parent,token,reference);break;default:if(!isProto3||!typeRefRe.test(token))throw illegal(token);push(token);parseField(parent,"optional",reference);break}})}var token;while((token=next())!==null){switch(token){case"package":if(!head)throw illegal(token);parsePackage();break;case"import":if(!head)throw illegal(token);parseImport();break;case"syntax":if(!head)throw illegal(token);parseSyntax();break;case"option":if(!head)throw illegal(token);parseOption(ptr,token);skip(";");break;default:if(parseCommon(ptr,token)){head=false;continue}throw illegal(token)}}parse.filename=null;return{package:pkg,imports:imports,weakImports:weakImports,syntax:syntax,root:root}}},{15:15,16:16,20:20,22:22,25:25,29:29,33:33,34:34,35:35,36:36,37:37}],27:[function(require,module,exports){"use strict";module.exports=Reader;var util=require(39);var BufferReader;var LongBits=util.LongBits,utf8=util.utf8;function indexOutOfRange(reader,writeLength){return RangeError("index out of range: "+reader.pos+" + "+(writeLength||1)+" > "+reader.len)}function Reader(buffer){this.buf=buffer;this.pos=0;this.len=buffer.length}var create_array=typeof Uint8Array!=="undefined"?function create_typed_array(buffer){if(buffer instanceof Uint8Array||Array.isArray(buffer))return new Reader(buffer);throw Error("illegal buffer")}:function create_array(buffer){if(Array.isArray(buffer))return new Reader(buffer);throw Error("illegal buffer")};Reader.create=util.Buffer?function create_buffer_setup(buffer){return(Reader.create=function create_buffer(buffer){return util.Buffer.isBuffer(buffer)?new BufferReader(buffer):create_array(buffer)})(buffer)}:create_array;Reader.prototype._slice=util.Array.prototype.subarray||util.Array.prototype.slice;Reader.prototype.uint32=function read_uint32_setup(){var value=4294967295;return function read_uint32(){value=(this.buf[this.pos]&127)>>>0;if(this.buf[this.pos++]<128)return value;value=(value|(this.buf[this.pos]&127)<<7)>>>0;if(this.buf[this.pos++]<128)return value;value=(value|(this.buf[this.pos]&127)<<14)>>>0;if(this.buf[this.pos++]<128)return value;value=(value|(this.buf[this.pos]&127)<<21)>>>0;if(this.buf[this.pos++]<128)return value;value=(value|(this.buf[this.pos]&15)<<28)>>>0;if(this.buf[this.pos++]<128)return value;if((this.pos+=5)>this.len){this.pos=this.len;throw indexOutOfRange(this,10)}return value}}();Reader.prototype.int32=function read_int32(){return this.uint32()|0};Reader.prototype.sint32=function read_sint32(){var value=this.uint32();return value>>>1^-(value&1)|0};function readLongVarint(){var bits=new LongBits(0,0);var i=0;if(this.len-this.pos>4){for(;i<4;++i){bits.lo=(bits.lo|(this.buf[this.pos]&127)<>>0;if(this.buf[this.pos++]<128)return bits}bits.lo=(bits.lo|(this.buf[this.pos]&127)<<28)>>>0;bits.hi=(bits.hi|(this.buf[this.pos]&127)>>4)>>>0;if(this.buf[this.pos++]<128)return bits;i=0}else{for(;i<3;++i){if(this.pos>=this.len)throw indexOutOfRange(this);bits.lo=(bits.lo|(this.buf[this.pos]&127)<>>0;if(this.buf[this.pos++]<128)return bits}bits.lo=(bits.lo|(this.buf[this.pos++]&127)<>>0;return bits}if(this.len-this.pos>4){for(;i<5;++i){bits.hi=(bits.hi|(this.buf[this.pos]&127)<>>0;if(this.buf[this.pos++]<128)return bits}}else{for(;i<5;++i){if(this.pos>=this.len)throw indexOutOfRange(this);bits.hi=(bits.hi|(this.buf[this.pos]&127)<>>0;if(this.buf[this.pos++]<128)return bits}}throw Error("invalid varint encoding")}Reader.prototype.bool=function read_bool(){return this.uint32()!==0};function readFixed32_end(buf,end){return(buf[end-4]|buf[end-3]<<8|buf[end-2]<<16|buf[end-1]<<24)>>>0}Reader.prototype.fixed32=function read_fixed32(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)};Reader.prototype.sfixed32=function read_sfixed32(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)|0};function readFixed64(){if(this.pos+8>this.len)throw indexOutOfRange(this,8);return new LongBits(readFixed32_end(this.buf,this.pos+=4),readFixed32_end(this.buf,this.pos+=4))}Reader.prototype.float=function read_float(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);var value=util.float.readFloatLE(this.buf,this.pos);this.pos+=4;return value};Reader.prototype.double=function read_double(){if(this.pos+8>this.len)throw indexOutOfRange(this,4);var value=util.float.readDoubleLE(this.buf,this.pos);this.pos+=8;return value};Reader.prototype.bytes=function read_bytes(){var length=this.uint32(),start=this.pos,end=this.pos+length;if(end>this.len)throw indexOutOfRange(this,length);this.pos+=length;if(Array.isArray(this.buf))return this.buf.slice(start,end);return start===end?new this.buf.constructor(0):this._slice.call(this.buf,start,end)};Reader.prototype.string=function read_string(){var bytes=this.bytes();return utf8.read(bytes,0,bytes.length)};Reader.prototype.skip=function skip(length){if(typeof length==="number"){if(this.pos+length>this.len)throw indexOutOfRange(this,length);this.pos+=length}else{do{if(this.pos>=this.len)throw indexOutOfRange(this)}while(this.buf[this.pos++]&128)}return this};Reader.prototype.skipType=function(wireType){switch(wireType){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:do{if((wireType=this.uint32()&7)===4)break;this.skipType(wireType)}while(true);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+wireType+" at offset "+this.pos)}return this};Reader._configure=function(BufferReader_){BufferReader=BufferReader_;var fn=util.Long?"toLong":"toNumber";util.merge(Reader.prototype,{int64:function read_int64(){return readLongVarint.call(this)[fn](false)},uint64:function read_uint64(){return readLongVarint.call(this)[fn](true)},sint64:function read_sint64(){return readLongVarint.call(this).zzDecode()[fn](false)},fixed64:function read_fixed64(){return readFixed64.call(this)[fn](true)},sfixed64:function read_sfixed64(){return readFixed64.call(this)[fn](false)}})}},{39:39}],28:[function(require,module,exports){"use strict";module.exports=BufferReader;var Reader=require(27);(BufferReader.prototype=Object.create(Reader.prototype)).constructor=BufferReader;var util=require(39);function BufferReader(buffer){Reader.call(this,buffer)}if(util.Buffer)BufferReader.prototype._slice=util.Buffer.prototype.slice;BufferReader.prototype.string=function read_string_buffer(){var len=this.uint32();return this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+len,this.len))}},{27:27,39:39}],29:[function(require,module,exports){"use strict";module.exports=Root;var Namespace=require(23);((Root.prototype=Object.create(Namespace.prototype)).constructor=Root).className="Root";var Field=require(16),Enum=require(15),OneOf=require(25),util=require(37);var Type,parse,common;function Root(options){Namespace.call(this,"",options);this.deferred=[];this.files=[]}Root.fromJSON=function fromJSON(json,root){if(!root)root=new Root;if(json.options)root.setOptions(json.options);return root.addJSON(json.nested)};Root.prototype.resolvePath=util.path.resolve;function SYNC(){}Root.prototype.load=function load(filename,options,callback){if(typeof options==="function"){callback=options;options=undefined}var self=this;if(!callback)return util.asPromise(load,self,filename,options);var sync=callback===SYNC;function finish(err,root){if(!callback)return;var cb=callback;callback=null;if(sync)throw err;cb(err,root)}function process(filename,source){try{if(util.isString(source)&&source.charAt(0)==="{")source=JSON.parse(source);if(!util.isString(source))self.setOptions(source.options).addJSON(source.nested);else{parse.filename=filename;var parsed=parse(source,self,options),resolved,i=0;if(parsed.imports)for(;i-1){var altname=filename.substring(idx);if(altname in common)filename=altname}if(self.files.indexOf(filename)>-1)return;self.files.push(filename);if(filename in common){if(sync)process(filename,common[filename]);else{++queued;setTimeout(function(){--queued;process(filename,common[filename])})}return}if(sync){var source;try{source=util.fs.readFileSync(filename).toString("utf8")}catch(err){if(!weak)finish(err);return}process(filename,source)}else{++queued;util.fetch(filename,function(err,source){--queued;if(!callback)return;if(err){if(!weak)finish(err);else if(!queued)finish(null,self);return}process(filename,source)})}}var queued=0;if(util.isString(filename))filename=[filename];for(var i=0,resolved;i-1)this.deferred.splice(index,1)}}}else if(object instanceof Enum){if(exposeRe.test(object.name))delete object.parent[object.name]}else if(object instanceof Namespace){for(var i=0;i]/g,stringDoubleRe=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,stringSingleRe=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g;var setCommentRe=/^ *[*/]+ */,setCommentSplitRe=/\n/g,whitespaceRe=/\s/,unescapeRe=/\\(.?)/g;var unescapeMap={0:"\0",r:"\r",n:"\n",t:"\t"};function unescape(str){return str.replace(unescapeRe,function($0,$1){switch($1){case"\\":case"":return $1;default:return unescapeMap[$1]||""}})}tokenize.unescape=unescape;function tokenize(source){source=source.toString();var offset=0,length=source.length,line=1,commentType=null,commentText=null,commentLine=0,commentLineEmpty=false;var stack=[];var stringDelim=null;function illegal(subject){return Error("illegal "+subject+" (line "+line+")")}function readString(){var re=stringDelim==="'"?stringSingleRe:stringDoubleRe;re.lastIndex=offset-1;var match=re.exec(source);if(!match)throw illegal("string");offset=re.lastIndex;push(stringDelim);stringDelim=null;return unescape(match[1])}function charAt(pos){return source.charAt(pos)}function setComment(start,end){commentType=source.charAt(start++);commentLine=line;commentLineEmpty=false;var offset=start-3,c;do{if(--offset<0||(c=source.charAt(offset))==="\n"){commentLineEmpty=true;break}}while(c===" "||c==="\t");var lines=source.substring(start,end).split(setCommentSplitRe);for(var i=0;i0)return stack.shift();if(stringDelim)return readString();var repeat,prev,curr,start,isDoc;do{if(offset===length)return null;repeat=false;while(whitespaceRe.test(curr=charAt(offset))){if(curr==="\n")++line;if(++offset===length)return null}if(charAt(offset)==="/"){if(++offset===length)throw illegal("comment");if(charAt(offset)==="/"){isDoc=charAt(start=offset+1)==="/";while(charAt(++offset)!=="\n")if(offset===length)return null;++offset;if(isDoc)setComment(start,offset-1);++line;repeat=true}else if((curr=charAt(offset))==="*"){isDoc=charAt(start=offset+1)==="*";do{if(curr==="\n")++line;if(++offset===length)throw illegal("comment");prev=curr;curr=charAt(offset)}while(prev!=="*"||curr!=="/");++offset;if(isDoc)setComment(start,offset-2);repeat=true}else return"/"}}while(repeat);var end=offset;delimRe.lastIndex=0;var delim=delimRe.test(charAt(end++));if(!delim)while(end>>0;this.hi=hi>>>0}var zero=LongBits.zero=new LongBits(0,0);zero.toNumber=function(){return 0};zero.zzEncode=zero.zzDecode=function(){return this};zero.length=function(){return 1};var zeroHash=LongBits.zeroHash="\0\0\0\0\0\0\0\0";LongBits.fromNumber=function fromNumber(value){if(value===0)return zero;var sign=value<0;if(sign)value=-value;var lo=value>>>0,hi=(value-lo)/4294967296>>>0;if(sign){hi=~hi>>>0;lo=~lo>>>0;if(++lo>4294967295){lo=0;if(++hi>4294967295)hi=0}}return new LongBits(lo,hi)};LongBits.from=function from(value){if(typeof value==="number")return LongBits.fromNumber(value);if(util.isString(value)){if(util.Long)value=util.Long.fromString(value);else return LongBits.fromNumber(parseInt(value,10))}return value.low||value.high?new LongBits(value.low>>>0,value.high>>>0):zero};LongBits.prototype.toNumber=function toNumber(unsigned){if(!unsigned&&this.hi>>>31){var lo=~this.lo+1>>>0,hi=~this.hi>>>0;if(!lo)hi=hi+1>>>0;return-(lo+hi*4294967296)}return this.lo+this.hi*4294967296};LongBits.prototype.toLong=function toLong(unsigned){return util.Long?new util.Long(this.lo|0,this.hi|0,Boolean(unsigned)):{low:this.lo|0,high:this.hi|0,unsigned:Boolean(unsigned)}};var charCodeAt=String.prototype.charCodeAt;LongBits.fromHash=function fromHash(hash){if(hash===zeroHash)return zero;return new LongBits((charCodeAt.call(hash,0)|charCodeAt.call(hash,1)<<8|charCodeAt.call(hash,2)<<16|charCodeAt.call(hash,3)<<24)>>>0,(charCodeAt.call(hash,4)|charCodeAt.call(hash,5)<<8|charCodeAt.call(hash,6)<<16|charCodeAt.call(hash,7)<<24)>>>0)};LongBits.prototype.toHash=function toHash(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)};LongBits.prototype.zzEncode=function zzEncode(){var mask=this.hi>>31;this.hi=((this.hi<<1|this.lo>>>31)^mask)>>>0;this.lo=(this.lo<<1^mask)>>>0;return this};LongBits.prototype.zzDecode=function zzDecode(){var mask=-(this.lo&1);this.lo=((this.lo>>>1|this.hi<<31)^mask)>>>0;this.hi=(this.hi>>>1^mask)>>>0;return this};LongBits.prototype.length=function length(){var part0=this.lo,part1=(this.lo>>>28|this.hi<<4)>>>0,part2=this.hi>>>24;return part2===0?part1===0?part0<16384?part0<128?1:2:part0<2097152?3:4:part1<16384?part1<128?5:6:part1<2097152?7:8:part2<128?9:10}},{39:39}],39:[function(require,module,exports){"use strict";var util=exports;util.asPromise=require(1);util.base64=require(2);util.EventEmitter=require(4);util.float=require(6);util.inquire=require(7);util.utf8=require(10);util.pool=require(9);util.LongBits=require(38);util.emptyArray=Object.freeze?Object.freeze([]):[];util.emptyObject=Object.freeze?Object.freeze({}):{};util.isNode=Boolean(global.process&&global.process.versions&&global.process.versions.node);util.isInteger=Number.isInteger||function isInteger(value){return typeof value==="number"&&isFinite(value)&&Math.floor(value)===value};util.isString=function isString(value){return typeof value==="string"||value instanceof String};util.isObject=function isObject(value){return value&&typeof value==="object"};util.isset=util.isSet=function isSet(obj,prop){var value=obj[prop];if(value!=null&&obj.hasOwnProperty(prop))return typeof value!=="object"||(Array.isArray(value)?value.length:Object.keys(value).length)>0;return false};util.Buffer=function(){try{var Buffer=util.inquire("buffer").Buffer;return Buffer.prototype.utf8Write?Buffer:null}catch(e){return null}}();util._Buffer_from=null;util._Buffer_allocUnsafe=null;util.newBuffer=function newBuffer(sizeOrArray){return typeof sizeOrArray==="number"?util.Buffer?util._Buffer_allocUnsafe(sizeOrArray):new util.Array(sizeOrArray):util.Buffer?util._Buffer_from(sizeOrArray):typeof Uint8Array==="undefined"?sizeOrArray:new Uint8Array(sizeOrArray)};util.Array=typeof Uint8Array!=="undefined"?Uint8Array:Array;util.Long=global.dcodeIO&&global.dcodeIO.Long||util.inquire("long");util.key2Re=/^true|false|0|1$/;util.key32Re=/^-?(?:0|[1-9][0-9]*)$/;util.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;util.longToHash=function longToHash(value){return value?util.LongBits.from(value).toHash():util.LongBits.zeroHash};util.longFromHash=function longFromHash(hash,unsigned){var bits=util.LongBits.fromHash(hash);if(util.Long)return util.Long.fromBits(bits.lo,bits.hi,unsigned);return bits.toNumber(Boolean(unsigned))};function merge(dst,src,ifNotSet){for(var keys=Object.keys(src),i=0;i-1;--i)if(fieldMap[keys[i]]===1&&this[keys[i]]!==undefined&&this[keys[i]]!==null)return keys[i]}};util.oneOfSetter=function setOneOf(fieldNames){return function(name){for(var i=0;i127){buf[pos++]=val&127|128;val>>>=7}buf[pos]=val}function VarintOp(len,val){this.len=len;this.next=undefined;this.val=val}VarintOp.prototype=Object.create(Op.prototype);VarintOp.prototype.fn=writeVarint32;Writer.prototype.uint32=function write_uint32(value){this.len+=(this.tail=this.tail.next=new VarintOp((value=value>>>0)<128?1:value<16384?2:value<2097152?3:value<268435456?4:5,value)).len;return this};Writer.prototype.int32=function write_int32(value){return value<0?this._push(writeVarint64,10,LongBits.fromNumber(value)):this.uint32(value)};Writer.prototype.sint32=function write_sint32(value){return this.uint32((value<<1^value>>31)>>>0)};function writeVarint64(val,buf,pos){while(val.hi){buf[pos++]=val.lo&127|128;val.lo=(val.lo>>>7|val.hi<<25)>>>0;val.hi>>>=7}while(val.lo>127){buf[pos++]=val.lo&127|128;val.lo=val.lo>>>7}buf[pos++]=val.lo}Writer.prototype.uint64=function write_uint64(value){var bits=LongBits.from(value);return this._push(writeVarint64,bits.length(),bits)};Writer.prototype.int64=Writer.prototype.uint64;Writer.prototype.sint64=function write_sint64(value){var bits=LongBits.from(value).zzEncode();return this._push(writeVarint64,bits.length(),bits)};Writer.prototype.bool=function write_bool(value){return this._push(writeByte,1,value?1:0)};function writeFixed32(val,buf,pos){buf[pos]=val&255;buf[pos+1]=val>>>8&255;buf[pos+2]=val>>>16&255;buf[pos+3]=val>>>24}Writer.prototype.fixed32=function write_fixed32(value){return this._push(writeFixed32,4,value>>>0)};Writer.prototype.sfixed32=Writer.prototype.fixed32;Writer.prototype.fixed64=function write_fixed64(value){var bits=LongBits.from(value);return this._push(writeFixed32,4,bits.lo)._push(writeFixed32,4,bits.hi)};Writer.prototype.sfixed64=Writer.prototype.fixed64;Writer.prototype.float=function write_float(value){return this._push(util.float.writeFloatLE,4,value)};Writer.prototype.double=function write_double(value){return this._push(util.float.writeDoubleLE,8,value)};var writeBytes=util.Array.prototype.set?function writeBytes_set(val,buf,pos){buf.set(val,pos)}:function writeBytes_for(val,buf,pos){for(var i=0;i>>0;if(!len)return this._push(writeByte,1,0);if(util.isString(value)){var buf=Writer.alloc(len=base64.length(value));base64.decode(value,buf,0);value=buf}return this.uint32(len)._push(writeBytes,len,value)};Writer.prototype.string=function write_string(value){var len=utf8.length(value);return len?this.uint32(len)._push(utf8.write,len,value):this._push(writeByte,1,0)};Writer.prototype.fork=function fork(){this.states=new State(this);this.head=this.tail=new Op(noop,0,0);this.len=0;return this};Writer.prototype.reset=function reset(){if(this.states){this.head=this.states.head;this.tail=this.states.tail;this.len=this.states.len;this.states=this.states.next}else{this.head=this.tail=new Op(noop,0,0);this.len=0}return this};Writer.prototype.ldelim=function ldelim(){var head=this.head,tail=this.tail,len=this.len;this.reset().uint32(len);if(len){this.tail.next=head.next;this.tail=tail;this.len+=len}return this};Writer.prototype.finish=function finish(){var head=this.head.next,buf=this.constructor.alloc(this.len),pos=0;while(head){head.fn(head.val,buf,pos);pos+=head.len;head=head.next}return buf};Writer._configure=function(BufferWriter_){BufferWriter=BufferWriter_}},{39:39}],43:[function(require,module,exports){"use strict";module.exports=BufferWriter;var Writer=require(42);(BufferWriter.prototype=Object.create(Writer.prototype)).constructor=BufferWriter;var util=require(39);var Buffer=util.Buffer;function BufferWriter(){Writer.call(this)}BufferWriter.alloc=function alloc_buffer(size){return(BufferWriter.alloc=util._Buffer_allocUnsafe)(size)};var writeBytesBuffer=Buffer&&Buffer.prototype instanceof Uint8Array&&Buffer.prototype.set.name==="set"?function writeBytesBuffer_set(val,buf,pos){buf.set(val,pos)}:function writeBytesBuffer_copy(val,buf,pos){if(val.copy)val.copy(buf,pos,0,val.length);else for(var i=0;i>>0;this.uint32(len);if(len)this._push(writeBytesBuffer,len,value);return this};function writeStringBuffer(val,buf,pos){if(val.length<40)util.utf8.write(val,buf,pos);else buf.utf8Write(val,pos)}BufferWriter.prototype.string=function write_string_buffer(value){var len=Buffer.byteLength(value);this.uint32(len);if(len)this._push(writeStringBuffer,len,value);return this}},{39:39,42:42}]},{},[19])})(typeof window==="object"&&window||typeof self==="object"&&self||this); \ No newline at end of file diff --git a/protubuf/protobuf-egret/egret-project/egretProperties.json b/protubuf/protobuf-egret/egret-project/egretProperties.json new file mode 100644 index 0000000..7dd69a8 --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/egretProperties.json @@ -0,0 +1,41 @@ +{ + "engineVersion": "5.1.2", + "compilerVersion": "5.1.2", + "template": {}, + "target": { + "current": "web" + }, + "modules": [ + { + "name": "egret" + }, + { + "name": "game" + }, + { + "name": "tween" + }, + { + "name": "assetsmanager" + }, + { + "name": "promise" + }, + { + "name": "protobuf-library", + "path": "protobuf/library" + }, + { + "name": "protobuf-bundles", + "path": "protobuf/bundles" + }, + { + "name": "protobuf-library", + "path": "protobuf/library" + }, + { + "name": "protobuf-bundles", + "path": "protobuf/bundles" + } + ] +} \ No newline at end of file diff --git a/protubuf/protobuf-egret/egret-project/favicon.ico b/protubuf/protobuf-egret/egret-project/favicon.ico new file mode 100644 index 0000000..e4ec42c Binary files /dev/null and b/protubuf/protobuf-egret/egret-project/favicon.ico differ diff --git a/protubuf/protobuf-egret/egret-project/index.html b/protubuf/protobuf-egret/egret-project/index.html new file mode 100644 index 0000000..73f7bb1 --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/index.html @@ -0,0 +1,96 @@ + + + + + + Egret + + + + + + + + + + +
+
+ + + + \ No newline at end of file diff --git a/protubuf/protobuf-egret/egret-project/manifest.json b/protubuf/protobuf-egret/egret-project/manifest.json new file mode 100644 index 0000000..210518f --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/manifest.json @@ -0,0 +1,17 @@ +{ + "initial": [ + "libs/modules/egret/egret.js", + "libs/modules/egret/egret.web.js", + "libs/modules/game/game.js", + "libs/modules/tween/tween.js", + "libs/modules/assetsmanager/assetsmanager.js", + "libs/modules/promise/promise.js", + "protobuf/library/protobuf-library.js", + "protobuf/bundles/protobuf-bundles.js" + ], + "game": [ + "bin-debug/LoadingUI.js", + "bin-debug/Main.js", + "bin-debug/Platform.js" + ] +} \ No newline at end of file diff --git a/protubuf/protobuf-egret/egret-project/resource/assets/bg.jpg b/protubuf/protobuf-egret/egret-project/resource/assets/bg.jpg new file mode 100644 index 0000000..a61ee5b Binary files /dev/null and b/protubuf/protobuf-egret/egret-project/resource/assets/bg.jpg differ diff --git a/protubuf/protobuf-egret/egret-project/resource/assets/egret_icon.png b/protubuf/protobuf-egret/egret-project/resource/assets/egret_icon.png new file mode 100644 index 0000000..28042eb Binary files /dev/null and b/protubuf/protobuf-egret/egret-project/resource/assets/egret_icon.png differ diff --git a/protubuf/protobuf-egret/egret-project/resource/config/description.json b/protubuf/protobuf-egret/egret-project/resource/config/description.json new file mode 100644 index 0000000..9f06a30 --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/resource/config/description.json @@ -0,0 +1,5 @@ +[ + "Open-source,Free,Multi-platform", + "Push Game Forward", + "HTML5 Game Engine" +] \ No newline at end of file diff --git a/protubuf/protobuf-egret/egret-project/resource/default.res.json b/protubuf/protobuf-egret/egret-project/resource/default.res.json new file mode 100644 index 0000000..51dbe95 --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/resource/default.res.json @@ -0,0 +1,23 @@ +{ + "groups":[ + { + "keys":"bg_jpg,egret_icon_png,description_json", + "name":"preload" + }], + "resources":[ + { + "name":"bg_jpg", + "type":"image", + "url":"assets/bg.jpg" + }, + { + "name":"egret_icon_png", + "type":"image", + "url":"assets/egret_icon.png" + }, + { + "name":"description_json", + "type":"json", + "url":"config/description.json" + }] +} \ No newline at end of file diff --git a/protubuf/protobuf-egret/egret-project/scripts/api.d.ts b/protubuf/protobuf-egret/egret-project/scripts/api.d.ts new file mode 100644 index 0000000..3a85bf5 --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/scripts/api.d.ts @@ -0,0 +1,310 @@ + +/** + * ResourceManager 配置文件 + */ +type ResourceManagerConfig = { + /** + * 配置文件生成路径 + */ + configPath: string, + /** + * 资源根目录路径 + */ + resourceRoot: () => string, + /** + * 构建与发布配置 + */ + buildConfig: (param: BuildConfigParam) => UserConfig, + /** + * 设置资源类型 + */ + typeSelector: (path: string) => (string | null | undefined) + /** + * 设置资源的合并策略 + */ + mergeSelector?: (path: string) => (string | null | undefined), + /** + * 设置资源的命名策略 + * beta 功能,请勿随意使用 + */ + nameSelector?: (path: string) => (string | null | undefined) +} +/** + * 构建配置 + */ +type UserConfig = { + /** + * 输出路径 + */ + outputDir: string, + /** + * 插件 + */ + commands: (string | plugins.Command) [] +} + +type BuildConfigParam = { + + + /** + * 当前命令,build 或者 command + */ + readonly command: string; + + /** + * 发布平台 + */ + readonly target: string; + + /** + * 开发者指定的版本号 + */ + readonly version: string; + + /** + * 项目名称 + */ + readonly projectName: string; + + /** + * 项目路径 + */ + readonly projectRoot: string; +} + + +declare namespace plugins { + + interface CommandContext { + + /** + * 可以用此接口进行文件创建 + */ + createFile(relativeFilePath: string, contents: Buffer); + + /** + * 构建配置 + */ + buildConfig: BuildConfigParam; + + /** + * 项目绝对路径 + */ + projectRoot: string; + + /** + * 项目输出绝对路径 + */ + outputDir: string; + + } + + /** + * 构建管线命令 + */ + interface Command { + + /** + * 项目中的每个文件都会执行此函数,返回 file 表示保留此文件,返回 null 表示将此文件从构建管线中删除,即不会发布 + */ + onFile?(file: File): Promise + + /** + * 项目中所有文件均执行完后,最终会执行此函数。 + * 这个函数主要被用于创建新文件 + */ + onFinish?(pluginContext?: CommandContext): Promise + + [options: string]: any; + } + + interface File { + + /** + * 文件内容的二进制流,如果开发者需要修改文件内容,请修改此属性 + */ + contents: Buffer; + + + /** + * 文件绝对路径,如果开发者需要对文件进行重命名,请修改此属性 + */ + path: string; + + /** + * 文件所在的项目的项目路径 + */ + readonly base: string; + + /** + * 文件的相对于 base 属性的相对路径 + */ + readonly relative: string; + + + /** + * 文件变更历史,history[0] 即 origin 属性 + */ + readonly history: ReadonlyArray; + + + /** + * 文件所在的文件夹的绝对路径 + */ + readonly dirname: string; + + /** + * 文件的文件名 + */ + readonly basename: string; + + + /** + * 文件的扩展名 + */ + readonly extname: string; + + /** + * 文件的初始文件名 + */ + readonly origin: string; + + /** + * 其他自定义属性 + */ + [customProperty: string]: any; + + } + +} + + + + + + + + + + +declare module 'built-in' { + + /** + * 混淆插件参数,设置源代码和目标代码 + */ + type UglifyPluginOption = { sources: string[], target: string }; + + type UglifyPluginOptions = UglifyPluginOption[]; + + /** + * 混淆插件 + */ + export class UglifyPlugin implements plugins.Command { + + constructor(mergeSelector: UglifyPluginOptions); + + } + + + type LibraryType = "debug" | "release"; + + type CompilePluginOptions = { libraryType: LibraryType }; + /** + * 编译命令 + */ + export class CompilePlugin implements plugins.Command { + + constructor(options: CompilePluginOptions); + } + + /** + * EXML 插件,用于发布 EXML 文件 + */ + export class ExmlPlugin implements plugins.Command { + + constructor(publishPolicy: EXML_Publish_Policy); + + } + + /** + * 发布策略 + * * default : 使用 egretProperties.json 中的 exmlPublishPolicy 中的策略 + * * debug : 默认策略,用于开发环境 + * * contents : 将 EXML 的内容写入到主题文件中 + * * gjs : 将生成的JS文件写入到主题文件中 + * * commonjs : 将EXML合并为一个 CommonJS 风格的文件 + */ + type EXML_Publish_Policy = "default" | "debug" | "contents" | "gjs" | "commonjs" + + + + + /** + * 生成 manifest 文件,这个文件会被用于记录 JavaScript 文件的版本号 + */ + export class ManifestPlugin implements plugins.Command { + constructor(options?: ManifestPluginOptions) + } + + /** + * 生成文件的文件名 + * 支持 json 与 js 两种格式 + */ + type ManifestPluginOptions = { + + output: string, + + hash?: "crc32", + + /** + * 是否输出转换过程 + */ + verbose?: boolean + + + } + + /** + * EmitResConfigFilePlugin 的参数 + * * output: 生成路径,可以指定生成为 *.res.js 文件或者 *.res.json 文件 + * * typeSelector: 根据文件路径决定文件类型 + * * nameSelector: 根据文件路径决定文件的资源名 + * * groupSelector: 根据文件路径决定资源所述的资源组 + */ + type EmitResConfigFilePluginOptions = { + output: string, + typeSelector: (path: string) => string | null | undefined, + nameSelector: (path: string) => string | null | undefined, + groupSelector: (path: string) => string | null | undefined, + } + + + /** + * 生成 res.json 文件或者 res.js 文件 + */ + export class EmitResConfigFilePlugin implements plugins.Command { + + constructor(options: EmitResConfigFilePluginOptions) + + } + + + /** + * 增量编译 + * 这个插件生成的 JavaScript 代码不会被添加到构建管线中,后续其他插件无法获取生成的 js 文件 + * 这个功能将会在未来被 watch 模式代替掉 + */ + export class IncrementCompilePlugin implements plugins.Command { + + } + + /** + * 使用 TextureMerger 实现纹理自动合并,依赖 TextureMerger 1.7 以上的版本 + */ + export class TextureMergerPlugin implements plugins.Command { + + constructor(); + + } + +} \ No newline at end of file diff --git a/protubuf/protobuf-egret/egret-project/scripts/bricks/bricks.ts b/protubuf/protobuf-egret/egret-project/scripts/bricks/bricks.ts new file mode 100644 index 0000000..e40b563 --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/scripts/bricks/bricks.ts @@ -0,0 +1,44 @@ +import * as fs from 'fs'; +import * as path from 'path'; + + +type ManifestConfig = { + + initial: string[], + + game: string[] + +} + +export class BricksPlugin implements plugins.Command { + + constructor() { + } + async onFile(file: plugins.File) { + const filename = file.origin; + if (filename == 'manifest.json') { + const contents = file.contents.toString(); + const jsonData: ManifestConfig = JSON.parse(contents); + + let content = ''; + + for (let item of jsonData.initial) { + if (item != 'js/promise.js' && item != 'js/promise.min.js') { + content += `BK.Script.loadlib("GameRes://${item}");\n` + } + if (item == "js/egret.js" || item == 'js/egret.min.js') { + content += `BK.Script.loadlib("GameRes://egret.bricks.js");\n` + } + } + for (let item of jsonData.game) { + content += `BK.Script.loadlib("GameRes://${item}");\n` + } + file.path = file.dirname + '/manifest.js' + file.contents = new Buffer(content); + } + return file; + } + async onFinish(pluginContext) { + + } +} \ No newline at end of file diff --git a/protubuf/protobuf-egret/egret-project/scripts/config.ts b/protubuf/protobuf-egret/egret-project/scripts/config.ts new file mode 100644 index 0000000..99b8e17 --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/scripts/config.ts @@ -0,0 +1,127 @@ +/// 阅读 api.d.ts 查看文档 +/// + +import * as path from 'path'; +import { UglifyPlugin, IncrementCompilePlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin } from 'built-in'; +import { WxgamePlugin } from './wxgame/wxgame'; +import { BricksPlugin } from './bricks/bricks'; +import { CustomPlugin } from './myplugin'; + +const config: ResourceManagerConfig = { + + configPath: 'config.res.js', + + resourceRoot: () => "resource", + + buildConfig: (params) => { + + + + const { target, command, projectName, version } = params; + + if (target == 'wxgame') { + const outputDir = `../${projectName}_wxgame`; + return { + outputDir, + commands: [ + new CompilePlugin({ libraryType: "release" }), + new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置 + new WxgamePlugin(), + new UglifyPlugin([{ + sources: ["main.js"], + target: "main.min.js" + } + ]), + new ManifestPlugin({ output: 'manifest.js' }) + ] + } + } + + + if (target == 'bricks') { + const outputDir = `../${projectName}_bricks/PublicBrickEngineGame/Res`; + return { + outputDir, + commands: [ + new CompilePlugin({ libraryType: "debug" }), + new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置 + new ManifestPlugin({ output: 'manifest.json' }), + new BricksPlugin() + ] + } + } + + if (command == 'build') { + const outputDir = '.'; + return { + outputDir, + commands: [ + // new EmitResConfigFilePlugin({ + // output: "resource/default.res.json", + // typeSelector: config.typeSelector, + // nameSelector: p => path.basename(p).replace(/\./gi, "_"), + // groupSelector: p => "preload" + // }), + new ExmlPlugin('debug'), // 非 EUI 项目关闭此设置 + new IncrementCompilePlugin(), + ] + } + } + else if (command == 'publish') { + const outputDir = `bin-release/web/${version}`; + return { + outputDir, + commands: [ + new CustomPlugin(), + new CompilePlugin({ libraryType: "release" }), + new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置 + new UglifyPlugin([{ + sources: ["main.js"], + target: "main.min.js" + }]), + new ManifestPlugin({ output: "manifest.json", hash: "crc32" }) + ] + } + } + else { + throw `unknown command : ${params.command}` + } + }, + + mergeSelector: (path) => { + if (path.indexOf("assets/bitmap/") >= 0) { + return "assets/bitmap/sheet.sheet" + } + else if (path.indexOf("armature") >= 0 && path.indexOf(".json") >= 0) { + return "assets/armature/1.zip"; + } + }, + + typeSelector: (path) => { + const ext = path.substr(path.lastIndexOf(".") + 1); + const typeMap = { + "jpg": "image", + "png": "image", + "webp": "image", + "json": "json", + "fnt": "font", + "pvr": "pvr", + "mp3": "sound", + "zip": "zip", + "sheet": "sheet", + "exml": "text" + } + let type = typeMap[ext]; + if (type == "json") { + if (path.indexOf("sheet") >= 0) { + type = "sheet"; + } else if (path.indexOf("movieclip") >= 0) { + type = "movieclip"; + }; + } + return type; + } +} + + +export = config; diff --git a/protubuf/protobuf-egret/egret-project/scripts/myplugin.ts b/protubuf/protobuf-egret/egret-project/scripts/myplugin.ts new file mode 100644 index 0000000..f425f3a --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/scripts/myplugin.ts @@ -0,0 +1,17 @@ +/** + * 示例自定义插件,您可以查阅 http://developer.egret.com/cn/2d/projectConfig/cmdExtensionPluginin/ + * 了解如何开发一个自定义插件 + */ +export class CustomPlugin implements plugins.Command { + + constructor() { + } + + async onFile(file: plugins.File) { + return file; + } + + async onFinish(commandContext: plugins.CommandContext) { + + } +} \ No newline at end of file diff --git a/protubuf/protobuf-egret/egret-project/scripts/node.d.ts b/protubuf/protobuf-egret/egret-project/scripts/node.d.ts new file mode 100644 index 0000000..239fd38 --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/scripts/node.d.ts @@ -0,0 +1,4209 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/a4a912a0cd1849fa7df0e5d909c8625fba04e49d/node/index.d.ts +interface Console { + Console: NodeJS.ConsoleConstructor; + assert(value: any, message?: string, ...optionalParams: any[]): void; + dir(obj: any, options?: {showHidden?: boolean, depth?: number, colors?: boolean}): void; + error(message?: any, ...optionalParams: any[]): void; + info(message?: any, ...optionalParams: any[]): void; + log(message?: any, ...optionalParams: any[]): void; + time(label: string): void; + timeEnd(label: string): void; + trace(message?: any, ...optionalParams: any[]): void; + warn(message?: any, ...optionalParams: any[]): void; +} + +interface Error { + stack?: string; +} + +interface ErrorConstructor { + captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + stackTraceLimit: number; +} + +// compat for TypeScript 1.8 +// if you use with --target es3 or --target es5 and use below definitions, +// use the lib.es6.d.ts that is bundled with TypeScript 1.8. +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } + +// Forward-declare needed types from lib.es2015.d.ts (in case users are using `--lib es5`) +interface Iterable {} +interface Iterator { + next(value?: any): IteratorResult; +} +interface IteratorResult {} +interface SymbolConstructor { + readonly iterator: symbol; +} +declare var Symbol: SymbolConstructor; + +/************************************************ +* * +* GLOBAL * +* * +************************************************/ +declare var process: NodeJS.Process; +declare var global: NodeJS.Global; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare function clearTimeout(timeoutId: NodeJS.Timer): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare function clearInterval(intervalId: NodeJS.Timer): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; +declare function clearImmediate(immediateId: any): void; + +interface NodeRequireFunction { + (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { + resolve(id: string): string; + cache: any; + extensions: any; + main: NodeModule | undefined; +} + +declare var require: NodeRequire; + +interface NodeModule { + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: NodeModule | null; + children: NodeModule[]; +} + +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; +declare var SlowBuffer: { + new (str: string, encoding?: string): Buffer; + new (size: number): Buffer; + new (size: Uint8Array): Buffer; + new (array: any[]): Buffer; + prototype: Buffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: Buffer[], totalLength?: number): Buffer; +}; + + +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "binary" | "hex"; +interface Buffer extends NodeBuffer { } + +/** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + */ +declare var Buffer: { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + new (str: string, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + new (size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + new (array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + new (arrayBuffer: ArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + new (array: any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + new (buffer: Buffer): Buffer; + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafeSlow(size: number): Buffer; +}; + +/************************************************ +* * +* GLOBAL INTERFACES * +* * +************************************************/ +declare namespace NodeJS { + export interface ConsoleConstructor { + prototype: Console; + new(stdout: WritableStream, stderr?: WritableStream): Console; + } + + export interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + export class EventEmitter { + addListener(event: string | symbol, listener: Function): this; + on(event: string | symbol, listener: Function): this; + once(event: string | symbol, listener: Function): this; + removeListener(event: string | symbol, listener: Function): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + listenerCount(type: string | symbol): number; + // Added in Node 6... + prependListener(event: string | symbol, listener: Function): this; + prependOnceListener(event: string | symbol, listener: Function): this; + eventNames(): (string | symbol)[]; + } + + export interface ReadableStream extends EventEmitter { + readable: boolean; + isTTY?: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string | null): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): this; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): ReadableStream; + } + + export interface WritableStream extends EventEmitter { + writable: boolean; + isTTY?: boolean; + write(buffer: Buffer | string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export interface ReadWriteStream extends ReadableStream, WritableStream { } + + export interface Events extends EventEmitter { } + + export interface Domain extends Events { + run(fn: Function): void; + add(emitter: Events): void; + remove(emitter: Events): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; + + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + } + + export interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + } + + export interface CpuUsage { + user: number; + system: number; + } + + export interface ProcessVersions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + + type Platform = 'aix' + | 'android' + | 'darwin' + | 'freebsd' + | 'linux' + | 'openbsd' + | 'sunos' + | 'win32'; + + export interface Process extends EventEmitter { + stdout: WritableStream; + stderr: WritableStream; + stdin: ReadableStream; + argv: string[]; + argv0: string; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + env: any; + exit(code?: number): void; + exitCode: number; + getgid(): number; + setgid(id: number): void; + setgid(id: string): void; + getuid(): number; + setuid(id: number): void; + setuid(id: string): void; + version: string; + versions: ProcessVersions; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string | number): void; + pid: number; + title: string; + arch: string; + platform: Platform; + mainModule?: NodeModule; + memoryUsage(): MemoryUsage; + cpuUsage(previousValue?: CpuUsage): CpuUsage; + nextTick(callback: Function, ...args: any[]): void; + umask(mask?: number): number; + uptime(): number; + hrtime(time?: [number, number]): [number, number]; + domain: Domain; + + // Worker + send?(message: any, sendHandle?: any): void; + disconnect(): void; + connected: boolean; + } + + export interface Global { + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + GLOBAL: Global; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: Function; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: any) => void; + clearInterval: (intervalId: NodeJS.Timer) => void; + clearTimeout: (timeoutId: NodeJS.Timer) => void; + console: typeof console; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + process: Process; + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } + + export interface Timer { + ref(): void; + unref(): void; + } +} + +interface IterableIterator { } + +/** + * @deprecated + */ +interface NodeBuffer extends Uint8Array { + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + keys(): IterableIterator; + values(): IterableIterator; +} + +/************************************************ +* * +* MODULES * +* * +************************************************/ +declare module "buffer" { + export var INSPECT_MAX_BYTES: number; + var BuffType: typeof Buffer; + var SlowBuffType: typeof SlowBuffer; + export { BuffType as Buffer, SlowBuffType as SlowBuffer }; +} + +declare module "querystring" { + export interface StringifyOptions { + encodeURIComponent?: Function; + } + + export interface ParseOptions { + maxKeys?: number; + decodeURIComponent?: Function; + } + + export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; + export function escape(str: string): string; + export function unescape(str: string): string; +} + +declare module "events" { + class internal extends NodeJS.EventEmitter { } + + namespace internal { + export class EventEmitter extends internal { + static listenerCount(emitter: EventEmitter, event: string | symbol): number; // deprecated + static defaultMaxListeners: number; + + addListener(event: string | symbol, listener: Function): this; + on(event: string | symbol, listener: Function): this; + once(event: string | symbol, listener: Function): this; + prependListener(event: string | symbol, listener: Function): this; + prependOnceListener(event: string | symbol, listener: Function): this; + removeListener(event: string | symbol, listener: Function): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + eventNames(): (string | symbol)[]; + listenerCount(type: string | symbol): number; + } + } + + export = internal; +} + +declare module "http" { + import * as events from "events"; + import * as net from "net"; + import * as stream from "stream"; + + export interface RequestOptions { + protocol?: string; + host?: string; + hostname?: string; + family?: number; + port?: number; + localAddress?: string; + socketPath?: string; + method?: string; + path?: string; + headers?: { [key: string]: any }; + auth?: string; + agent?: Agent | boolean; + timeout?: number; + } + + export interface Server extends net.Server { + setTimeout(msecs: number, callback: Function): void; + maxHeadersCount: number; + timeout: number; + listening: boolean; + } + /** + * @deprecated Use IncomingMessage + */ + export interface ServerRequest extends IncomingMessage { + connection: net.Socket; + } + export interface ServerResponse extends stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + writeContinue(): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; + writeHead(statusCode: number, headers?: any): void; + statusCode: number; + statusMessage: string; + headersSent: boolean; + setHeader(name: string, value: string | string[]): void; + setTimeout(msecs: number, callback: Function): ServerResponse; + sendDate: boolean; + getHeader(name: string): string; + removeHeader(name: string): void; + write(chunk: any, encoding?: string): any; + addTrailers(headers: any): void; + finished: boolean; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + export interface ClientRequest extends stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + write(chunk: any, encoding?: string): void; + abort(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + + setHeader(name: string, value: string | string[]): void; + getHeader(name: string): string; + removeHeader(name: string): void; + addTrailers(headers: any): void; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + export interface IncomingMessage extends stream.Readable { + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + connection: net.Socket; + headers: any; + rawHeaders: string[]; + trailers: any; + rawTrailers: any; + setTimeout(msecs: number, callback: Function): NodeJS.Timer; + /** + * Only valid for request obtained from http.Server. + */ + method?: string; + /** + * Only valid for request obtained from http.Server. + */ + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: net.Socket; + destroy(error?: Error): void; + } + /** + * @deprecated Use IncomingMessage + */ + export interface ClientResponse extends IncomingMessage { } + + export interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + } + + export class Agent { + maxSockets: number; + sockets: any; + requests: any; + + constructor(opts?: AgentOptions); + + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } + + export var METHODS: string[]; + + export var STATUS_CODES: { + [errorCode: number]: string; + [errorCode: string]: string; + }; + export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; + export function createClient(port?: number, host?: string): any; + export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; + export var globalAgent: Agent; +} + +declare module "cluster" { + import * as child from "child_process"; + import * as events from "events"; + import * as net from "net"; + + // interfaces + export interface ClusterSettings { + execArgv?: string[]; // default: process.execArgv + exec?: string; + args?: string[]; + silent?: boolean; + stdio?: any[]; + uid?: number; + gid?: number; + } + + export interface ClusterSetupMasterSettings { + exec?: string; // default: process.argv[1] + args?: string[]; // default: process.argv.slice(2) + silent?: boolean; // default: false + stdio?: any[]; + } + + export interface Address { + address: string; + port: number; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" + } + + export class Worker extends events.EventEmitter { + id: string; + process: child.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any): boolean; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + isConnected(): boolean; + isDead(): boolean; + exitedAfterDisconnect: boolean; + + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: Function): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (code: number, signal: string) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + + emit(event: string, listener: Function): boolean + emit(event: "disconnect", listener: () => void): boolean + emit(event: "error", listener: (code: number, signal: string) => void): boolean + emit(event: "exit", listener: (code: number, signal: string) => void): boolean + emit(event: "listening", listener: (address: Address) => void): boolean + emit(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): boolean + emit(event: "online", listener: () => void): boolean + + on(event: string, listener: Function): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (code: number, signal: string) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (code: number, signal: string) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (code: number, signal: string) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + + export interface Cluster extends events.EventEmitter { + Worker: Worker; + disconnect(callback?: Function): void; + fork(env?: any): Worker; + isMaster: boolean; + isWorker: boolean; + // TODO: cluster.schedulingPolicy + settings: ClusterSettings; + setupMaster(settings?: ClusterSetupMasterSettings): void; + worker: Worker; + workers: { + [index: string]: Worker + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: Function): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: any) => void): this; + + emit(event: string, listener: Function): boolean; + emit(event: "disconnect", listener: (worker: Worker) => void): boolean; + emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; + emit(event: "fork", listener: (worker: Worker) => void): boolean; + emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; + emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; + emit(event: "online", listener: (worker: Worker) => void): boolean; + emit(event: "setup", listener: (settings: any) => void): boolean; + + on(event: string, listener: Function): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: any) => void): this; + + once(event: string, listener: Function): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: any) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: any) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: any) => void): this; + + } + + export function disconnect(callback?: Function): void; + export function fork(env?: any): Worker; + export var isMaster: boolean; + export var isWorker: boolean; + // TODO: cluster.schedulingPolicy + export var settings: ClusterSettings; + export function setupMaster(settings?: ClusterSetupMasterSettings): void; + export var worker: Worker; + export var workers: { + [index: string]: Worker + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + export function addListener(event: string, listener: Function): Cluster; + export function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function addListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function emit(event: string, listener: Function): boolean; + export function emit(event: "disconnect", listener: (worker: Worker) => void): boolean; + export function emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; + export function emit(event: "fork", listener: (worker: Worker) => void): boolean; + export function emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; + export function emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; + export function emit(event: "online", listener: (worker: Worker) => void): boolean; + export function emit(event: "setup", listener: (settings: any) => void): boolean; + + export function on(event: string, listener: Function): Cluster; + export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function on(event: "fork", listener: (worker: Worker) => void): Cluster; + export function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function on(event: "online", listener: (worker: Worker) => void): Cluster; + export function on(event: "setup", listener: (settings: any) => void): Cluster; + + export function once(event: string, listener: Function): Cluster; + export function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function once(event: "fork", listener: (worker: Worker) => void): Cluster; + export function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function once(event: "online", listener: (worker: Worker) => void): Cluster; + export function once(event: "setup", listener: (settings: any) => void): Cluster; + + export function removeListener(event: string, listener: Function): Cluster; + export function removeAllListeners(event?: string): Cluster; + export function setMaxListeners(n: number): Cluster; + export function getMaxListeners(): number; + export function listeners(event: string): Function[]; + export function listenerCount(type: string): number; + + export function prependListener(event: string, listener: Function): Cluster; + export function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function prependOnceListener(event: string, listener: Function): Cluster; + export function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function eventNames(): string[]; +} + +declare module "zlib" { + import * as stream from "stream"; + + export interface ZlibOptions { + flush?: number; // default: zlib.constants.Z_NO_FLUSH + finishFlush?: number; // default: zlib.constants.Z_FINISH + chunkSize?: number; // default: 16*1024 + windowBits?: number; + level?: number; // compression only + memLevel?: number; // compression only + strategy?: number; // compression only + dictionary?: any; // deflate/inflate only, empty dictionary by default + } + + export interface Gzip extends stream.Transform { } + export interface Gunzip extends stream.Transform { } + export interface Deflate extends stream.Transform { } + export interface Inflate extends stream.Transform { } + export interface DeflateRaw extends stream.Transform { } + export interface InflateRaw extends stream.Transform { } + export interface Unzip extends stream.Transform { } + + export function createGzip(options?: ZlibOptions): Gzip; + export function createGunzip(options?: ZlibOptions): Gunzip; + export function createDeflate(options?: ZlibOptions): Deflate; + export function createInflate(options?: ZlibOptions): Inflate; + export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + export function createInflateRaw(options?: ZlibOptions): InflateRaw; + export function createUnzip(options?: ZlibOptions): Unzip; + + export function deflate(buf: Buffer | string, callback: (error: Error, result: Buffer) => void): void; + export function deflateSync(buf: Buffer | string, options?: ZlibOptions): Buffer; + export function deflateRaw(buf: Buffer | string, callback: (error: Error, result: Buffer) => void): void; + export function deflateRawSync(buf: Buffer | string, options?: ZlibOptions): Buffer; + export function gzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function gzipSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function gunzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function gunzipSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function inflate(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function inflateSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function inflateRaw(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function inflateRawSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function unzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function unzipSync(buf: Buffer, options?: ZlibOptions): Buffer; + + export namespace constants { + // Allowed flush values. + + export const Z_NO_FLUSH: number; + export const Z_PARTIAL_FLUSH: number; + export const Z_SYNC_FLUSH: number; + export const Z_FULL_FLUSH: number; + export const Z_FINISH: number; + export const Z_BLOCK: number; + export const Z_TREES: number; + + // Return codes for the compression/decompression functions. Negative values are errors, positive values are used for special but normal events. + + export const Z_OK: number; + export const Z_STREAM_END: number; + export const Z_NEED_DICT: number; + export const Z_ERRNO: number; + export const Z_STREAM_ERROR: number; + export const Z_DATA_ERROR: number; + export const Z_MEM_ERROR: number; + export const Z_BUF_ERROR: number; + export const Z_VERSION_ERROR: number; + + // Compression levels. + + export const Z_NO_COMPRESSION: number; + export const Z_BEST_SPEED: number; + export const Z_BEST_COMPRESSION: number; + export const Z_DEFAULT_COMPRESSION: number; + + // Compression strategy. + + export const Z_FILTERED: number; + export const Z_HUFFMAN_ONLY: number; + export const Z_RLE: number; + export const Z_FIXED: number; + export const Z_DEFAULT_STRATEGY: number; + } + + // Constants + export var Z_NO_FLUSH: number; + export var Z_PARTIAL_FLUSH: number; + export var Z_SYNC_FLUSH: number; + export var Z_FULL_FLUSH: number; + export var Z_FINISH: number; + export var Z_BLOCK: number; + export var Z_TREES: number; + export var Z_OK: number; + export var Z_STREAM_END: number; + export var Z_NEED_DICT: number; + export var Z_ERRNO: number; + export var Z_STREAM_ERROR: number; + export var Z_DATA_ERROR: number; + export var Z_MEM_ERROR: number; + export var Z_BUF_ERROR: number; + export var Z_VERSION_ERROR: number; + export var Z_NO_COMPRESSION: number; + export var Z_BEST_SPEED: number; + export var Z_BEST_COMPRESSION: number; + export var Z_DEFAULT_COMPRESSION: number; + export var Z_FILTERED: number; + export var Z_HUFFMAN_ONLY: number; + export var Z_RLE: number; + export var Z_FIXED: number; + export var Z_DEFAULT_STRATEGY: number; + export var Z_BINARY: number; + export var Z_TEXT: number; + export var Z_ASCII: number; + export var Z_UNKNOWN: number; + export var Z_DEFLATED: number; +} + +declare module "os" { + export interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + + export interface NetworkInterfaceInfo { + address: string; + netmask: string; + family: string; + mac: string; + internal: boolean; + } + + export function hostname(): string; + export function loadavg(): number[]; + export function uptime(): number; + export function freemem(): number; + export function totalmem(): number; + export function cpus(): CpuInfo[]; + export function type(): string; + export function release(): string; + export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; + export function homedir(): string; + export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string } + export var constants: { + UV_UDP_REUSEADDR: number, + errno: { + 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; + SIGTTIN: number; + SIGTTOU: number; + SIGURG: number; + SIGXCPU: number; + SIGXFSZ: number; + SIGVTALRM: number; + SIGPROF: number; + SIGWINCH: number; + SIGIO: number; + SIGPOLL: number; + SIGPWR: number; + SIGSYS: number; + SIGUNUSED: number; + }, + signals: { + 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; + }, + }; + export function arch(): string; + export function platform(): NodeJS.Platform; + export function tmpdir(): string; + export var EOL: string; + export function endianness(): "BE" | "LE"; +} + +declare module "https" { + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; + + export interface ServerOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + crl?: any; + ciphers?: string; + honorCipherOrder?: boolean; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; + SNICallback?: (servername: string, cb: (err: Error, ctx: tls.SecureContext) => any) => any; + } + + export interface RequestOptions extends http.RequestOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: string; + rejectUnauthorized?: boolean; + secureProtocol?: string; + } + + export interface Agent extends http.Agent { } + + export interface AgentOptions extends http.AgentOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: string; + rejectUnauthorized?: boolean; + secureProtocol?: string; + maxCachedSessions?: number; + } + + export var Agent: { + new (options?: AgentOptions): Agent; + }; + export interface Server extends tls.Server { } + export function createServer(options: ServerOptions, requestListener?: Function): Server; + export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export var globalAgent: Agent; +} + +declare module "punycode" { + export function decode(string: string): string; + export function encode(string: string): string; + export function toUnicode(domain: string): string; + export function toASCII(domain: string): string; + export var ucs2: ucs2; + interface ucs2 { + decode(string: string): number[]; + encode(codePoints: number[]): string; + } + export var version: any; +} + +declare module "repl" { + import * as stream from "stream"; + import * as readline from "readline"; + + export interface ReplOptions { + prompt?: string; + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + terminal?: boolean; + eval?: Function; + useColors?: boolean; + useGlobal?: boolean; + ignoreUndefined?: boolean; + writer?: Function; + completer?: Function; + replMode?: any; + breakEvalOnSigint?: any; + } + + export interface REPLServer extends readline.ReadLine { + defineCommand(keyword: string, cmd: Function | { help: string, action: Function }): void; + displayPrompt(preserveCursor?: boolean): void; + + /** + * events.EventEmitter + * 1. exit + * 2. reset + **/ + + addListener(event: string, listener: Function): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: Function): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: any): boolean; + + on(event: string, listener: Function): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: Function): this; + + once(event: string, listener: Function): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: Function): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: Function): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: Function): this; + } + + export function start(options: ReplOptions): REPLServer; +} + +declare module "readline" { + import * as events from "events"; + import * as stream from "stream"; + + export interface Key { + sequence?: string; + name?: string; + ctrl?: boolean; + meta?: boolean; + shift?: boolean; + } + + export interface ReadLine extends events.EventEmitter { + setPrompt(prompt: string): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: (answer: string) => void): void; + pause(): ReadLine; + resume(): ReadLine; + 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: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: any) => 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, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: any): 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: Function): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: any) => 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: Function): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: any) => 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: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: any) => 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: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: any) => 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; + } + + type Completer = (line: string) => CompleterResult; + type AsyncCompleter = (line: string, callback: (err: any, result: CompleterResult) => void) => any; + + export type CompleterResult = [string[], string]; + + export interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + completer?: Completer | AsyncCompleter; + terminal?: boolean; + historySize?: number; + } + + export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): ReadLine; + export function createInterface(options: ReadLineOptions): ReadLine; + + export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; + export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; + export function clearLine(stream: NodeJS.WritableStream, dir: number): void; + export function clearScreenDown(stream: NodeJS.WritableStream): void; +} + +declare module "vm" { + export interface Context { } + export interface ScriptOptions { + filename?: string; + lineOffset?: number; + columnOffset?: number; + displayErrors?: boolean; + timeout?: number; + cachedData?: Buffer; + produceCachedData?: boolean; + } + export interface RunningScriptOptions { + filename?: string; + lineOffset?: number; + columnOffset?: number; + displayErrors?: boolean; + timeout?: number; + } + export class Script { + constructor(code: string, options?: ScriptOptions); + runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; + runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; + runInThisContext(options?: RunningScriptOptions): any; + } + export function createContext(sandbox?: Context): Context; + export function isContext(sandbox: Context): boolean; + export function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions): any; + export function runInDebugContext(code: string): any; + export function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions): any; + export function runInThisContext(code: string, options?: RunningScriptOptions): any; +} + +declare module "child_process" { + import * as events from "events"; + import * as stream from "stream"; + import * as net from "net"; + + export interface ChildProcess extends events.EventEmitter { + stdin: stream.Writable; + stdout: stream.Readable; + stderr: stream.Readable; + stdio: [stream.Writable, stream.Readable, stream.Readable]; + pid: number; + kill(signal?: string): void; + send(message: any, sendHandle?: any): boolean; + connected: boolean; + disconnect(): void; + unref(): void; + ref(): void; + + /** + * events.EventEmitter + * 1. close + * 2. disconnet + * 3. error + * 4. exit + * 5. message + **/ + + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: (code: number, signal: string) => void): this; + addListener(event: "disconnet", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close", code: number, signal: string): boolean; + emit(event: "disconnet"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "message", message: any, sendHandle: net.Socket | net.Server): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: (code: number, signal: string) => void): this; + on(event: "disconnet", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: (code: number, signal: string) => void): this; + once(event: "disconnet", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: (code: number, signal: string) => void): this; + prependListener(event: "disconnet", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "disconnet", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + } + + export interface SpawnOptions { + cwd?: string; + env?: any; + stdio?: any; + detached?: boolean; + uid?: number; + gid?: number; + shell?: boolean | string; + } + export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + + export interface ExecOptions { + cwd?: string; + env?: any; + shell?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + } + export interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + export interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: string; // specify `null`. + } + export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, options: ExecOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + // usage. child_process.exec("tsc", {encoding: null as string}, (err, stdout, stderr) => {}); + export function exec(command: string, options: ExecOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + + export interface ExecFileOptions { + cwd?: string; + env?: any; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + } + export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: string; // specify `null`. + } + export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + // usage. child_process.execFile("file.sh", {encoding: null as string}, (err, stdout, stderr) => {}); + export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + // usage. child_process.execFile("file.sh", ["foo"], {encoding: null as string}, (err, stdout, stderr) => {}); + export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + + export interface ForkOptions { + cwd?: string; + env?: any; + execPath?: string; + execArgv?: string[]; + silent?: boolean; + uid?: number; + gid?: number; + } + export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; + + export interface SpawnSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: string; + shell?: boolean | string; + } + export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + export interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding: string; // specify `null`. + } + export interface SpawnSyncReturns { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number; + signal: string; + error: Error; + } + export function spawnSync(command: string): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns; + + export interface ExecSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + shell?: string; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: string; + } + export interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + export interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding: string; // specify `null`. + } + export function execSync(command: string): Buffer; + export function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; + export function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; + export function execSync(command: string, options?: ExecSyncOptions): Buffer; + + export interface ExecFileSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: string; + } + export interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + export interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding: string; // specify `null`. + } + export function execFileSync(command: string): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; + export function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithStringEncoding): string; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer; +} + +declare module "url" { + export interface Url { + href?: string; + protocol?: string; + auth?: string; + hostname?: string; + port?: string; + host?: string; + pathname?: string; + search?: string; + query?: string | any; + slashes?: boolean; + hash?: string; + path?: string; + } + + export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; + export function format(url: Url): string; + export function resolve(from: string, to: string): string; + + export class URLSearchParams implements Iterable { + constructor(init?: URLSearchParams | string); + append(name: string, value: string): void; + delete(name: string): void; + entries(): Iterator; + forEach(callback: (value: string, name: string) => void): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + keys(): Iterator; + set(name: string, value: string): void; + sort(): void; + toString(): string; + values(): Iterator; + [Symbol.iterator](): Iterator; + } + + export 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; + } +} + +declare module "dns" { + export interface MxRecord { + exchange: string, + priority: number + } + + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; + export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: MxRecord[]) => void): string[]; + export function resolveTxt(domain: string, callback: (err: Error, addresses: string[][]) => void): string[][]; + export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; + export function setServers(servers: string[]): void; + + //Error codes + export var NODATA: string; + export var FORMERR: string; + export var SERVFAIL: string; + export var NOTFOUND: string; + export var NOTIMP: string; + export var REFUSED: string; + export var BADQUERY: string; + export var BADNAME: string; + export var BADFAMILY: string; + export var BADRESP: string; + export var CONNREFUSED: string; + export var TIMEOUT: string; + export var EOF: string; + export var FILE: string; + export var NOMEM: string; + export var DESTRUCTION: string; + export var BADSTR: string; + export var BADFLAGS: string; + export var NONAME: string; + export var BADHINTS: string; + export var NOTINITIALIZED: string; + export var LOADIPHLPAPI: string; + export var ADDRGETNETWORKPARAMS: string; + export var CANCELLED: string; +} + +declare module "net" { + import * as stream from "stream"; + import * as events from "events"; + + export interface Socket extends stream.Duplex { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + connect(port: number, host?: string, connectionListener?: Function): void; + connect(path: string, connectionListener?: Function): void; + bufferSize: number; + setEncoding(encoding?: string): this; + write(data: any, encoding?: string, callback?: Function): void; + destroy(err?: any): void; + pause(): this; + resume(): this; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setKeepAlive(enable?: boolean, initialDelay?: number): void; + address(): { port: number; family: string; address: string; }; + unref(): void; + ref(): void; + + remoteAddress: string; + remoteFamily: string; + remotePort: number; + localAddress: string; + localPort: number; + bytesRead: number; + bytesWritten: number; + destroyed: boolean; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: (had_error: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + addListener(event: "timeout", listener: () => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close", had_error: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "timeout"): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: (had_error: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + on(event: "timeout", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: (had_error: boolean) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: (had_error: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + + export var Socket: { + new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; + }; + + export interface ListenOptions { + port?: number; + host?: string; + backlog?: number; + path?: string; + exclusive?: boolean; + } + + export interface Server extends events.EventEmitter { + listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): Server; + listen(port: number, hostname?: string, listeningListener?: Function): Server; + listen(port: number, backlog?: number, listeningListener?: Function): Server; + listen(port: number, listeningListener?: Function): Server; + listen(path: string, backlog?: number, listeningListener?: Function): Server; + listen(path: string, listeningListener?: Function): Server; + listen(options: ListenOptions, listeningListener?: Function): Server; + listen(handle: any, backlog?: number, listeningListener?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + close(callback?: Function): Server; + address(): { port: number; family: string; address: string; }; + getConnections(cb: (error: Error, count: number) => void): void; + ref(): Server; + unref(): Server; + maxConnections: number; + connections: number; + listening: boolean; + + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + } + export function createServer(connectionListener?: (socket: Socket) => void): Server; + export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server; + export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function connect(port: number, host?: string, connectionListener?: Function): Socket; + export function connect(path: string, connectionListener?: Function): Socket; + export function createConnection(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; + export function createConnection(path: string, connectionListener?: Function): Socket; + export function isIP(input: string): number; + export function isIPv4(input: string): boolean; + export function isIPv6(input: string): boolean; +} + +declare module "dgram" { + import * as events from "events"; + + interface RemoteInfo { + address: string; + family: string; + port: number; + } + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + interface BindOptions { + port: number; + address?: string; + exclusive?: boolean; + } + + interface SocketOptions { + type: "udp4" | "udp6"; + reuseAddr?: boolean; + } + + export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + + export interface Socket extends events.EventEmitter { + send(msg: Buffer | String | any[], port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + send(msg: Buffer | String | any[], offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + bind(port?: number, address?: string, callback?: () => void): void; + bind(options: BindOptions, callback?: Function): void; + close(callback?: () => void): void; + address(): AddressInfo; + setBroadcast(flag: boolean): void; + setTTL(ttl: number): void; + setMulticastTTL(ttl: number): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + ref(): this; + unref(): this; + + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + **/ + addListener(event: string, listener: Function): 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: AddressInfo) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: AddressInfo): boolean; + + on(event: string, listener: Function): 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: AddressInfo) => void): this; + + once(event: string, listener: Function): 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: AddressInfo) => void): this; + + prependListener(event: string, listener: Function): 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: AddressInfo) => void): this; + + prependOnceListener(event: string, listener: Function): 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: AddressInfo) => void): this; + } +} + +declare module "fs" { + import * as stream from "stream"; + import * as events from "events"; + + interface Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + interface FSWatcher extends events.EventEmitter { + close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: Function): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (code: number, signal: string) => void): this; + + on(event: string, listener: Function): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (code: number, signal: string) => void): this; + + once(event: string, listener: Function): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (code: number, signal: string) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (code: number, signal: string) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; + } + + export interface ReadStream extends stream.Readable { + close(): void; + destroy(): void; + bytesRead: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: Function): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + export interface WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: Function): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + /** + * Asynchronous rename. + * @param oldPath + * @param newPath + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /** + * Synchronous rename + * @param oldPath + * @param newPath + */ + export function renameSync(oldPath: string, newPath: string): void; + export function truncate(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncate(path: string | Buffer, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncateSync(path: string | Buffer, len?: number): void; + export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncateSync(fd: number, len?: number): void; + export function chown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chownSync(path: string | Buffer, uid: number, gid: number): void; + export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchownSync(fd: number, uid: number, gid: number): void; + export function lchown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchownSync(path: string | Buffer, uid: number, gid: number): void; + export function chmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmodSync(path: string | Buffer, mode: number): void; + export function chmodSync(path: string | Buffer, mode: string): void; + export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmodSync(fd: number, mode: number): void; + export function fchmodSync(fd: number, mode: string): void; + export function lchmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmodSync(path: string | Buffer, mode: number): void; + export function lchmodSync(path: string | Buffer, mode: string): void; + export function stat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function lstat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function statSync(path: string | Buffer): Stats; + export function lstatSync(path: string | Buffer): Stats; + export function fstatSync(fd: number): Stats; + export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function linkSync(srcpath: string | Buffer, dstpath: string | Buffer): void; + export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function symlinkSync(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): void; + export function readlink(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; + export function readlinkSync(path: string | Buffer): string; + export function realpath(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpathSync(path: string | Buffer, cache?: { [path: string]: string }): string; + /** + * Asynchronous unlink - deletes the file specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function unlink(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + /** + * Synchronous unlink - deletes the file specified in {path} + * + * @param path + */ + export function unlinkSync(path: string | Buffer): void; + /** + * Asynchronous rmdir - removes the directory specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function rmdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + /** + * Synchronous rmdir - removes the directory specified in {path} + * + * @param path + */ + export function rmdirSync(path: string | Buffer): void; + /** + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + /** + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdir(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + /** + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdir(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /** + * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdirSync(path: string | Buffer, mode?: number): void; + /** + * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdirSync(path: string | Buffer, mode?: string): void; + /** + * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * @param prefix + * @param callback The created folder path is passed as a string to the callback's second parameter. + */ + export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; + /** + * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * @param prefix + * @returns Returns the created folder path. + */ + export function mkdtempSync(prefix: string): string; + export function readdir(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; + export function readdirSync(path: string | Buffer): string[]; + export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function closeSync(fd: number): void; + export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + export function openSync(path: string | Buffer, flags: string | number, mode?: number): number; + export function utimes(path: string | Buffer, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimesSync(path: string | Buffer, atime: number, mtime: number): void; + export function utimesSync(path: string | Buffer, atime: Date, mtime: Date): void; + export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimesSync(fd: number, atime: number, mtime: number): void; + export function futimesSync(fd: number, atime: Date, mtime: Date): void; + export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fsyncSync(fd: number): void; + export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function write(fd: number, buffer: Buffer, offset: number, length: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function write(fd: number, data: any, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function write(fd: number, data: any, offset: number, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number; + export function writeSync(fd: number, data: any, position?: number, enconding?: string): number; + export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; + export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + /** + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param encoding + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + /** + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + /** + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /** + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /** + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param encoding + */ + export function readFileSync(filename: string, encoding: string): string; + /** + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. + */ + export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; + /** + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. + */ + export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; + export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; + export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; + export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; + export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; + export function watch(filename: string, encoding: string, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; + export function watch(filename: string, options: { persistent?: boolean; recursive?: boolean; encoding?: string }, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; + export function exists(path: string | Buffer, callback?: (exists: boolean) => void): void; + export function existsSync(path: string | Buffer): boolean; + + export namespace constants { + // File Access Constants + + /** Constant for fs.access(). File is visible to the calling process. */ + export const F_OK: number; + + /** Constant for fs.access(). File can be read by the calling process. */ + export const R_OK: number; + + /** Constant for fs.access(). File can be written by the calling process. */ + export const W_OK: number; + + /** Constant for fs.access(). File can be executed by the calling process. */ + export const X_OK: number; + + // File Open Constants + + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + export const O_RDONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + export const O_WRONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + export const O_RDWR: number; + + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + export const O_CREAT: number; + + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + export const O_EXCL: number; + + /** Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one). */ + export const O_NOCTTY: number; + + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + export const O_TRUNC: number; + + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + export const O_APPEND: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + export const O_DIRECTORY: number; + + /** Constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only. */ + export const O_NOATIME: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + export const O_NOFOLLOW: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + export const O_SYNC: number; + + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + export const O_SYMLINK: number; + + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + export const O_DIRECT: number; + + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + export const O_NONBLOCK: number; + + // File Type Constants + + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + export const S_IFMT: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + export const S_IFREG: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + export const S_IFDIR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + export const S_IFCHR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + export const S_IFBLK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + export const S_IFIFO: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + export const S_IFLNK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + export const S_IFSOCK: number; + + // File Mode Constants + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + export const S_IRWXU: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + export const S_IRUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + export const S_IWUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + export const S_IXUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + export const S_IRWXG: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + export const S_IRGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + export const S_IWGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + export const S_IXGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + export const S_IRWXO: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + export const S_IROTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + export const S_IWOTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + export const S_IXOTH: number; + } + + /** Tests a user's permissions for the file specified by path. */ + export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; + export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; + /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ + export function accessSync(path: string | Buffer, mode?: number): void; + export function createReadStream(path: string | Buffer, options?: { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + end?: number; + }): ReadStream; + export function createWriteStream(path: string | Buffer, options?: { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + }): WriteStream; + export function fdatasync(fd: number, callback: Function): void; + export function fdatasyncSync(fd: number): void; +} + +declare module "path" { + + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + export 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; + } + + /** + * 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. + */ + export 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. + */ + export function join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} paramter, 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. + */ + export function resolve(...pathSegments: any[]): 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. + */ + export 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. + * + * @param from + * @param to + */ + export 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. + */ + export 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. + */ + export 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. + */ + export function extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + export var sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + export var delimiter: string; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + export function parse(pathString: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + export function format(pathObject: ParsedPath): string; + + export module posix { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } + + export module win32 { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } +} + +declare module "string_decoder" { + export interface NodeStringDecoder { + write(buffer: Buffer): string; + end(buffer?: Buffer): string; + } + export var StringDecoder: { + new (encoding?: string): NodeStringDecoder; + }; +} + +declare module "tls" { + import * as crypto from "crypto"; + import * as net from "net"; + import * as stream from "stream"; + + var CLIENT_RENEG_LIMIT: number; + var CLIENT_RENEG_WINDOW: number; + + export interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + + export interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + } + + export class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket:net.Socket, options?: { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext, + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean, + /** + * An optional net.Server instance. + */ + server?: net.Server, + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean, + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. Defaults to false. + */ + rejectUnauthorized?: boolean, + /** + * An array of strings or a Buffer naming possible NPN protocols. + * (Protocols should be ordered by their priority.) + */ + NPNProtocols?: string[] | Buffer, + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) When the server + * receives both NPN and ALPN extensions from the client, ALPN takes + * precedence over NPN and the server does not send an NPN extension + * to the client. + */ + ALPNProtocols?: string[] | Buffer, + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: Function, + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer, + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean + }); + /** + * Returns the bound address, the address family name and port of the underlying socket as reported by + * the operating system. + * @returns {any} - An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. + */ + address(): { port: number; family: string; address: string }; + /** + * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. + */ + authorized: boolean; + /** + * The reason why the peer's certificate has not been verified. + * This property becomes available only when tlsSocket.authorized === false. + */ + authorizationError: Error; + /** + * Static boolean value, always true. + * May be used to distinguish TLS sockets from regular ones. + */ + encrypted: boolean; + /** + * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. + * @returns {CipherNameAndProtocol} - Returns an object representing the cipher name + * and the SSL/TLS protocol version of the current connection. + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the peer's certificate. + * The returned object has some properties corresponding to the field of the certificate. + * If detailed argument is true the full chain with issuer property will be returned, + * if false only the top certificate without issuer property. + * If the peer does not provide a certificate, it returns null or an empty object. + * @param {boolean} detailed - If true; the full chain with issuer property will be returned. + * @returns {any} - An object representing the peer's certificate. + */ + getPeerCertificate(detailed?: boolean): { + subject: Certificate; + issuerInfo: Certificate; + issuer: Certificate; + raw: any; + valid_from: string; + valid_to: string; + fingerprint: string; + serialNumber: string; + }; + /** + * Could be used to speed up handshake establishment when reconnecting to the server. + * @returns {any} - ASN.1 encoded TLS session or undefined if none was negotiated. + */ + getSession(): any; + /** + * NOTE: Works only with client TLS sockets. + * Useful only for debugging, for session reuse provide session option to tls.connect(). + * @returns {any} - TLS session ticket or undefined if none was negotiated. + */ + getTLSTicket(): any; + /** + * The string representation of the local IP address. + */ + localAddress: string; + /** + * The numeric representation of the local port. + */ + localPort: number; + /** + * The string representation of the remote IP address. + * For example, '74.125.127.100' or '2001:4860:a005::68'. + */ + remoteAddress: string; + /** + * The string representation of the remote IP family. 'IPv4' or 'IPv6'. + */ + remoteFamily: string; + /** + * The numeric representation of the remote port. For example, 443. + */ + remotePort: number; + /** + * Initiate TLS renegotiation process. + * + * NOTE: Can be used to request peer's certificate after the secure connection has been established. + * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. + * @param {TlsOptions} options - The options may contain the following fields: rejectUnauthorized, + * requestCert (See tls.createServer() for details). + * @param {Function} callback - callback(err) will be executed with null as err, once the renegotiation + * is successfully completed. + */ + renegotiate(options: TlsOptions, callback: (err: Error) => any): any; + /** + * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by + * the TLS layer until the entire fragment is received and its integrity is verified; + * large fragments can span multiple roundtrips, and their processing can be delayed due to packet + * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, + * which may decrease overall server throughput. + * @param {number} size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns {boolean} - Returns true on success, false otherwise. + */ + setMaxSendFragment(size: number): boolean; + + /** + * events.EventEmitter + * 1. OCSPResponse + * 2. secureConnect + **/ + addListener(event: string, listener: Function): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + + on(event: string, listener: Function): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + } + + export interface TlsOptions { + host?: string; + port?: number; + pfx?: string | Buffer[]; + key?: string | string[] | Buffer | any[]; + passphrase?: string; + cert?: string | string[] | Buffer | Buffer[]; + ca?: string | string[] | Buffer | Buffer[]; + crl?: string | string[]; + ciphers?: string; + honorCipherOrder?: boolean; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: string[] | Buffer; + SNICallback?: (servername: string, cb: (err: Error, ctx: SecureContext) => any) => any; + ecdhCurve?: string; + dhparam?: string | Buffer; + handshakeTimeout?: number; + ALPNProtocols?: string[] | Buffer; + sessionTimeout?: number; + ticketKeys?: any; + sessionIdContext?: string; + secureProtocol?: string; + } + + export interface ConnectionOptions { + host?: string; + port?: number; + socket?: net.Socket; + pfx?: string | Buffer + key?: string | string[] | Buffer | Buffer[]; + passphrase?: string; + cert?: string | string[] | Buffer | Buffer[]; + ca?: string | Buffer | (string | Buffer)[]; + rejectUnauthorized?: boolean; + NPNProtocols?: (string | Buffer)[]; + servername?: string; + path?: string; + ALPNProtocols?: (string | Buffer)[]; + checkServerIdentity?: (servername: string, cert: string | Buffer | (string | Buffer)[]) => any; + secureProtocol?: string; + secureContext?: Object; + session?: Buffer; + minDHSize?: number; + } + + export interface Server extends net.Server { + close(callback?: Function): Server; + address(): { port: number; family: string; address: string; }; + addContext(hostName: string, credentials: { + key: string; + cert: string; + ca: string; + }): void; + maxConnections: number; + connections: number; + + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + **/ + addListener(event: string, listener: Function): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + addListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: Function): boolean; + emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + + on(event: string, listener: Function): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + once(event: string, listener: Function): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependOnceListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + } + + export interface ClearTextStream extends stream.Duplex { + authorized: boolean; + authorizationError: Error; + getPeerCertificate(): any; + getCipher: { + name: string; + version: string; + }; + address: { + port: number; + family: string; + address: string; + }; + remoteAddress: string; + remotePort: number; + } + + export interface SecurePair { + encrypted: any; + cleartext: any; + } + + export interface SecureContextOptions { + pfx?: string | Buffer; + key?: string | Buffer; + passphrase?: string; + cert?: string | Buffer; + ca?: string | Buffer; + crl?: string | string[] + ciphers?: string; + honorCipherOrder?: boolean; + } + + export interface SecureContext { + context: any; + } + + export function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): TLSSocket; + export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + export function createSecureContext(details: SecureContextOptions): SecureContext; +} + +declare module "crypto" { + export interface Certificate { + exportChallenge(spkac: string | Buffer): Buffer; + exportPublicKey(spkac: string | Buffer): Buffer; + verifySpkac(spkac: Buffer): boolean; + } + export var Certificate: { + new (): Certificate; + (): Certificate; + } + + export var fips: boolean; + + export interface CredentialDetails { + pfx: string; + key: string; + passphrase: string; + cert: string; + ca: string | string[]; + crl: string | string[]; + ciphers: string; + } + export interface Credentials { context?: any; } + export function createCredentials(details: CredentialDetails): Credentials; + export function createHash(algorithm: string): Hash; + export function createHmac(algorithm: string, key: string | Buffer): Hmac; + + type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; + type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; + type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; + type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + + export interface Hash extends NodeJS.ReadWriteStream { + update(data: string | Buffer): Hash; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hash; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + export interface Hmac extends NodeJS.ReadWriteStream { + update(data: string | Buffer): Hmac; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hmac; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + export function createCipher(algorithm: string, password: any): Cipher; + export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; + export interface Cipher extends NodeJS.ReadWriteStream { + update(data: Buffer): Buffer; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): void; + getAuthTag(): Buffer; + setAAD(buffer: Buffer): void; + } + export function createDecipher(algorithm: string, password: any): Decipher; + export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; + export interface Decipher extends NodeJS.ReadWriteStream { + update(data: Buffer): Buffer; + update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; + update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): void; + setAuthTag(tag: Buffer): void; + setAAD(buffer: Buffer): void; + } + export function createSign(algorithm: string): Signer; + export interface Signer extends NodeJS.WritableStream { + update(data: string | Buffer): Signer; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Signer; + sign(private_key: string | { key: string; passphrase: string }): Buffer; + sign(private_key: string | { key: string; passphrase: string }, output_format: HexBase64Latin1Encoding): string; + } + export function createVerify(algorith: string): Verify; + export interface Verify extends NodeJS.WritableStream { + update(data: string | Buffer): Verify; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Verify; + verify(object: string, signature: Buffer): boolean; + verify(object: string, signature: string, signature_format: HexBase64Latin1Encoding): boolean; + } + export function createDiffieHellman(prime_length: number, generator?: number): DiffieHellman; + export function createDiffieHellman(prime: Buffer): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Buffer): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; + export interface DiffieHellman { + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: Buffer): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrime(): Buffer; + getPrime(encoding: HexBase64Latin1Encoding): string; + getGenerator(): Buffer; + getGenerator(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + setPublicKey(public_key: Buffer): void; + setPublicKey(public_key: string, encoding: string): void; + setPrivateKey(private_key: Buffer): void; + setPrivateKey(private_key: string, encoding: string): void; + verifyError: number; + } + export function getDiffieHellman(group_name: string): DiffieHellman; + export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer; + export function randomBytes(size: number): Buffer; + export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; + export function pseudoRandomBytes(size: number): Buffer; + export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; + export interface RsaPublicKey { + key: string; + padding?: number; + } + export interface RsaPrivateKey { + key: string; + passphrase?: string, + padding?: number; + } + export function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer + export function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer + export function privateEncrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer + export function publicDecrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer + export function getCiphers(): string[]; + export function getCurves(): string[]; + export function getHashes(): string[]; + export interface ECDH { + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding): string; + generateKeys(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; + computeSecret(other_public_key: Buffer): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding): string; + getPublicKey(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; + setPrivateKey(private_key: Buffer): void; + setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; + } + export function createECDH(curve_name: string): ECDH; + export function timingSafeEqual(a: Buffer, b: Buffer): boolean; + export var DEFAULT_ENCODING: string; +} + +declare module "stream" { + import * as events from "events"; + + class internal extends events.EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } + namespace internal { + + export class Stream extends internal { } + + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?: (size?: number) => any; + } + + export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { + readable: boolean; + constructor(opts?: ReadableOptions); + protected _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): this; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. readable + * 5. error + **/ + addListener(event: string, listener: Function): this; + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + + removeListener(event: string, listener: Function): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + } + + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; + writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; + } + + export class Writable extends events.EventEmitter implements NodeJS.WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + protected _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + **/ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "drain", chunk: Buffer | string): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + + removeListener(event: string, listener: Function): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + } + + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writableObjectMode?: boolean; + } + + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements NodeJS.ReadWriteStream { + // Readable + pause(): this; + resume(): this; + // Writeable + writable: boolean; + constructor(opts?: DuplexOptions); + protected _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export interface TransformOptions extends DuplexOptions { + transform?: (chunk: string | Buffer, encoding: string, callback: Function) => any; + flush?: (callback: Function) => any; + } + + // Note: Transform lacks the _read and _write methods of Readable/Writable. + export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { + readable: boolean; + writable: boolean; + constructor(opts?: TransformOptions); + protected _transform(chunk: any, encoding: string, callback: Function): void; + protected _flush(callback: Function): void; + read(size?: number): any; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): this; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export class PassThrough extends Transform { } + } + + export = internal; +} + +declare module "util" { + export interface InspectOptions { + showHidden?: boolean; + depth?: number; + colors?: boolean; + customInspect?: boolean; + } + + export function format(format: any, ...param: any[]): string; + export function debug(string: string): void; + export function error(...param: any[]): void; + export function puts(...param: any[]): void; + export function print(...param: any[]): void; + export function log(string: string): void; + export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; + export function inspect(object: any, options: InspectOptions): string; + export function isArray(object: any): boolean; + export function isRegExp(object: any): boolean; + export function isDate(object: any): boolean; + export function isError(object: any): boolean; + export function inherits(constructor: any, superConstructor: any): void; + export function debuglog(key: string): (msg: string, ...param: any[]) => void; + export function isBoolean(object: any): boolean; + export function isBuffer(object: any): boolean; + export function isFunction(object: any): boolean; + export function isNull(object: any): boolean; + export function isNullOrUndefined(object: any): boolean; + export function isNumber(object: any): boolean; + export function isObject(object: any): boolean; + export function isPrimitive(object: any): boolean; + export function isString(object: any): boolean; + export function isSymbol(object: any): boolean; + export function isUndefined(object: any): boolean; + export function deprecate(fn: Function, message: string): Function; +} + +declare module "assert" { + function internal(value: any, message?: string): void; + namespace internal { + export class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; + + constructor(options?: { + message?: string; actual?: any; expected?: any; + operator?: string; stackStartFunction?: Function + }); + } + + export function fail(actual: any, expected: any, message: string, operator: string): void; + export function ok(value: any, message?: string): void; + export function equal(actual: any, expected: any, message?: string): void; + export function notEqual(actual: any, expected: any, message?: string): void; + export function deepEqual(actual: any, expected: any, message?: string): void; + export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function strictEqual(actual: any, expected: any, message?: string): void; + export function notStrictEqual(actual: any, expected: any, message?: string): void; + export function deepStrictEqual(actual: any, expected: any, message?: string): void; + export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; + export var throws: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export var doesNotThrow: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export function ifError(value: any): void; + } + + export = internal; +} + +declare module "tty" { + import * as net from "net"; + + export function isatty(fd: number): boolean; + export interface ReadStream extends net.Socket { + isRaw: boolean; + setRawMode(mode: boolean): void; + isTTY: boolean; + } + export interface WriteStream extends net.Socket { + columns: number; + rows: number; + isTTY: boolean; + } +} + +declare module "domain" { + import * as events from "events"; + + export class Domain extends events.EventEmitter implements NodeJS.Domain { + run(fn: Function): void; + add(emitter: events.EventEmitter): void; + remove(emitter: events.EventEmitter): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; + members: any[]; + enter(): void; + exit(): void; + } + + export function create(): Domain; +} + +declare module "constants" { + export var E2BIG: number; + export var EACCES: number; + export var EADDRINUSE: number; + export var EADDRNOTAVAIL: number; + export var EAFNOSUPPORT: number; + export var EAGAIN: number; + export var EALREADY: number; + export var EBADF: number; + export var EBADMSG: number; + export var EBUSY: number; + export var ECANCELED: number; + export var ECHILD: number; + export var ECONNABORTED: number; + export var ECONNREFUSED: number; + export var ECONNRESET: number; + export var EDEADLK: number; + export var EDESTADDRREQ: number; + export var EDOM: number; + export var EEXIST: number; + export var EFAULT: number; + export var EFBIG: number; + export var EHOSTUNREACH: number; + export var EIDRM: number; + export var EILSEQ: number; + export var EINPROGRESS: number; + export var EINTR: number; + export var EINVAL: number; + export var EIO: number; + export var EISCONN: number; + export var EISDIR: number; + export var ELOOP: number; + export var EMFILE: number; + export var EMLINK: number; + export var EMSGSIZE: number; + export var ENAMETOOLONG: number; + export var ENETDOWN: number; + export var ENETRESET: number; + export var ENETUNREACH: number; + export var ENFILE: number; + export var ENOBUFS: number; + export var ENODATA: number; + export var ENODEV: number; + export var ENOENT: number; + export var ENOEXEC: number; + export var ENOLCK: number; + export var ENOLINK: number; + export var ENOMEM: number; + export var ENOMSG: number; + export var ENOPROTOOPT: number; + export var ENOSPC: number; + export var ENOSR: number; + export var ENOSTR: number; + export var ENOSYS: number; + export var ENOTCONN: number; + export var ENOTDIR: number; + export var ENOTEMPTY: number; + export var ENOTSOCK: number; + export var ENOTSUP: number; + export var ENOTTY: number; + export var ENXIO: number; + export var EOPNOTSUPP: number; + export var EOVERFLOW: number; + export var EPERM: number; + export var EPIPE: number; + export var EPROTO: number; + export var EPROTONOSUPPORT: number; + export var EPROTOTYPE: number; + export var ERANGE: number; + export var EROFS: number; + export var ESPIPE: number; + export var ESRCH: number; + export var ETIME: number; + export var ETIMEDOUT: number; + export var ETXTBSY: number; + export var EWOULDBLOCK: number; + export var EXDEV: number; + export var WSAEINTR: number; + export var WSAEBADF: number; + export var WSAEACCES: number; + export var WSAEFAULT: number; + export var WSAEINVAL: number; + export var WSAEMFILE: number; + export var WSAEWOULDBLOCK: number; + export var WSAEINPROGRESS: number; + export var WSAEALREADY: number; + export var WSAENOTSOCK: number; + export var WSAEDESTADDRREQ: number; + export var WSAEMSGSIZE: number; + export var WSAEPROTOTYPE: number; + export var WSAENOPROTOOPT: number; + export var WSAEPROTONOSUPPORT: number; + export var WSAESOCKTNOSUPPORT: number; + export var WSAEOPNOTSUPP: number; + export var WSAEPFNOSUPPORT: number; + export var WSAEAFNOSUPPORT: number; + export var WSAEADDRINUSE: number; + export var WSAEADDRNOTAVAIL: number; + export var WSAENETDOWN: number; + export var WSAENETUNREACH: number; + export var WSAENETRESET: number; + export var WSAECONNABORTED: number; + export var WSAECONNRESET: number; + export var WSAENOBUFS: number; + export var WSAEISCONN: number; + export var WSAENOTCONN: number; + export var WSAESHUTDOWN: number; + export var WSAETOOMANYREFS: number; + export var WSAETIMEDOUT: number; + export var WSAECONNREFUSED: number; + export var WSAELOOP: number; + export var WSAENAMETOOLONG: number; + export var WSAEHOSTDOWN: number; + export var WSAEHOSTUNREACH: number; + export var WSAENOTEMPTY: number; + export var WSAEPROCLIM: number; + export var WSAEUSERS: number; + export var WSAEDQUOT: number; + export var WSAESTALE: number; + export var WSAEREMOTE: number; + export var WSASYSNOTREADY: number; + export var WSAVERNOTSUPPORTED: number; + export var WSANOTINITIALISED: number; + export var WSAEDISCON: number; + export var WSAENOMORE: number; + export var WSAECANCELLED: number; + export var WSAEINVALIDPROCTABLE: number; + export var WSAEINVALIDPROVIDER: number; + export var WSAEPROVIDERFAILEDINIT: number; + export var WSASYSCALLFAILURE: number; + export var WSASERVICE_NOT_FOUND: number; + export var WSATYPE_NOT_FOUND: number; + export var WSA_E_NO_MORE: number; + export var WSA_E_CANCELLED: number; + export var WSAEREFUSED: number; + export var SIGHUP: number; + export var SIGINT: number; + export var SIGILL: number; + export var SIGABRT: number; + export var SIGFPE: number; + export var SIGKILL: number; + export var SIGSEGV: number; + export var SIGTERM: number; + export var SIGBREAK: number; + export var SIGWINCH: number; + export var SSL_OP_ALL: number; + export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; + export var SSL_OP_CISCO_ANYCONNECT: number; + export var SSL_OP_COOKIE_EXCHANGE: number; + export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + export var SSL_OP_EPHEMERAL_RSA: number; + export var SSL_OP_LEGACY_SERVER_CONNECT: number; + export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; + export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + export var SSL_OP_NETSCAPE_CA_DN_BUG: number; + export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NO_COMPRESSION: number; + export var SSL_OP_NO_QUERY_MTU: number; + export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + export var SSL_OP_NO_SSLv2: number; + export var SSL_OP_NO_SSLv3: number; + export var SSL_OP_NO_TICKET: number; + export var SSL_OP_NO_TLSv1: number; + export var SSL_OP_NO_TLSv1_1: number; + export var SSL_OP_NO_TLSv1_2: number; + export var SSL_OP_PKCS1_CHECK_1: number; + export var SSL_OP_PKCS1_CHECK_2: number; + export var SSL_OP_SINGLE_DH_USE: number; + export var SSL_OP_SINGLE_ECDH_USE: number; + export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; + export var SSL_OP_TLS_D5_BUG: number; + export var SSL_OP_TLS_ROLLBACK_BUG: number; + export var ENGINE_METHOD_DSA: number; + export var ENGINE_METHOD_DH: number; + export var ENGINE_METHOD_RAND: number; + export var ENGINE_METHOD_ECDH: number; + export var ENGINE_METHOD_ECDSA: number; + export var ENGINE_METHOD_CIPHERS: number; + export var ENGINE_METHOD_DIGESTS: number; + export var ENGINE_METHOD_STORE: number; + export var ENGINE_METHOD_PKEY_METHS: number; + export var ENGINE_METHOD_PKEY_ASN1_METHS: number; + export var ENGINE_METHOD_ALL: number; + export var ENGINE_METHOD_NONE: number; + export var DH_CHECK_P_NOT_SAFE_PRIME: number; + export var DH_CHECK_P_NOT_PRIME: number; + export var DH_UNABLE_TO_CHECK_GENERATOR: number; + export var DH_NOT_SUITABLE_GENERATOR: number; + export var NPN_ENABLED: number; + export var RSA_PKCS1_PADDING: number; + export var RSA_SSLV23_PADDING: number; + export var RSA_NO_PADDING: number; + export var RSA_PKCS1_OAEP_PADDING: number; + export var RSA_X931_PADDING: number; + export var RSA_PKCS1_PSS_PADDING: number; + export var POINT_CONVERSION_COMPRESSED: number; + export var POINT_CONVERSION_UNCOMPRESSED: number; + export var POINT_CONVERSION_HYBRID: number; + export var O_RDONLY: number; + export var O_WRONLY: number; + export var O_RDWR: number; + export var S_IFMT: number; + export var S_IFREG: number; + export var S_IFDIR: number; + export var S_IFCHR: number; + export var S_IFBLK: number; + export var S_IFIFO: number; + export var S_IFSOCK: number; + export var S_IRWXU: number; + export var S_IRUSR: number; + export var S_IWUSR: number; + export var S_IXUSR: number; + export var S_IRWXG: number; + export var S_IRGRP: number; + export var S_IWGRP: number; + export var S_IXGRP: number; + export var S_IRWXO: number; + export var S_IROTH: number; + export var S_IWOTH: number; + export var S_IXOTH: number; + export var S_IFLNK: number; + export var O_CREAT: number; + export var O_EXCL: number; + export var O_NOCTTY: number; + export var O_DIRECTORY: number; + export var O_NOATIME: number; + export var O_NOFOLLOW: number; + export var O_SYNC: number; + export var O_SYMLINK: number; + export var O_DIRECT: number; + export var O_NONBLOCK: number; + export var O_TRUNC: number; + export var O_APPEND: number; + export var F_OK: number; + export var R_OK: number; + export var W_OK: number; + export var X_OK: number; + export var UV_UDP_REUSEADDR: number; + export var SIGQUIT: number; + export var SIGTRAP: number; + export var SIGIOT: number; + export var SIGBUS: number; + export var SIGUSR1: number; + export var SIGUSR2: number; + export var SIGPIPE: number; + export var SIGALRM: number; + export var SIGCHLD: number; + export var SIGSTKFLT: number; + export var SIGCONT: number; + export var SIGSTOP: number; + export var SIGTSTP: number; + export var SIGTTIN: number; + export var SIGTTOU: number; + export var SIGURG: number; + export var SIGXCPU: number; + export var SIGXFSZ: number; + export var SIGVTALRM: number; + export var SIGPROF: number; + export var SIGIO: number; + export var SIGPOLL: number; + export var SIGPWR: number; + export var SIGSYS: number; + export var SIGUNUSED: number; + export var defaultCoreCipherList: string; + export var defaultCipherList: string; + export var ENGINE_METHOD_RSA: number; + export var ALPN_ENABLED: number; +} + +declare module "process" { + export = process; +} + +declare module "v8" { + 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; + } + + export function getHeapStatistics(): HeapInfo; + export function getHeapSpaceStatistics(): HeapSpaceInfo[]; + export function setFlagsFromString(flags: string): void; +} + +declare module "timers" { + export function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + export function clearTimeout(timeoutId: NodeJS.Timer): void; + export function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + export function clearInterval(intervalId: NodeJS.Timer): void; + export function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; + export function clearImmediate(immediateId: any): void; +} + +declare module "console" { + export = console; +} + +/** + * _debugger module is not documented. + * Source code is at https://github.com/nodejs/node/blob/master/lib/_debugger.js + */ +declare module "_debugger" { + export interface Packet { + raw: string; + headers: string[]; + body: Message; + } + + export interface Message { + seq: number; + type: string; + } + + export interface RequestInfo { + command: string; + arguments: any; + } + + export interface Request extends Message, RequestInfo { + } + + export interface Event extends Message { + event: string; + body?: any; + } + + export interface Response extends Message { + request_seq: number; + success: boolean; + /** Contains error message if success === false. */ + message?: string; + /** Contains message body if success === true. */ + body?: any; + } + + export interface BreakpointMessageBody { + type: string; + target: number; + line: number; + } + + export class Protocol { + res: Packet; + state: string; + execute(data: string): void; + serialize(rq: Request): string; + onResponse: (pkt: Packet) => void; + } + + export var NO_FRAME: number; + export var port: number; + + export interface ScriptDesc { + name: string; + id: number; + isNative?: boolean; + handle?: number; + type: string; + lineOffset?: number; + columnOffset?: number; + lineCount?: number; + } + + export interface Breakpoint { + id: number; + scriptId: number; + script: ScriptDesc; + line: number; + condition?: string; + scriptReq?: string; + } + + export interface RequestHandler { + (err: boolean, body: Message, res: Packet): void; + request_seq?: number; + } + + export interface ResponseBodyHandler { + (err: boolean, body?: any): void; + request_seq?: number; + } + + export interface ExceptionInfo { + text: string; + } + + export interface BreakResponse { + script?: ScriptDesc; + exception?: ExceptionInfo; + sourceLine: number; + sourceLineText: string; + sourceColumn: number; + } + + export function SourceInfo(body: BreakResponse): string; + + export interface ClientInstance extends NodeJS.EventEmitter { + protocol: Protocol; + scripts: ScriptDesc[]; + handles: ScriptDesc[]; + breakpoints: Breakpoint[]; + currentSourceLine: number; + currentSourceColumn: number; + currentSourceLineText: string; + currentFrame: number; + currentScript: string; + + connect(port: number, host: string): void; + req(req: any, cb: RequestHandler): void; + reqFrameEval(code: string, frame: number, cb: RequestHandler): void; + mirrorObject(obj: any, depth: number, cb: ResponseBodyHandler): void; + setBreakpoint(rq: BreakpointMessageBody, cb: RequestHandler): void; + clearBreakpoint(rq: Request, cb: RequestHandler): void; + listbreakpoints(cb: RequestHandler): void; + reqSource(from: number, to: number, cb: RequestHandler): void; + reqScripts(cb: any): void; + reqContinue(cb: RequestHandler): void; + } + + export var Client : { + new (): ClientInstance + } +} diff --git a/protubuf/protobuf-egret/egret-project/scripts/tsconfig.json b/protubuf/protobuf-egret/egret-project/scripts/tsconfig.json new file mode 100644 index 0000000..1868374 --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/scripts/tsconfig.json @@ -0,0 +1,50 @@ +{ + "compilerOptions": { + /* Basic Options */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */ + "module": "commonjs", /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */ + "lib": [ + "es5", + "es2015.promise" + ], /* Specify library files to be included in the compilation: */ + "allowJs": true, /* Allow javascript files to be compiled. */ + // "checkJs": true, /* Report errors in .js files. */ + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ + // "declaration": true, /* Generates corresponding '.d.ts' file. */ + // "sourceMap": true, /* Generates corresponding '.map' file. */ + // "outFile": "./", /* Concatenate and emit output to single file. */ + // "outDir": "./", /* Redirect output structure to the directory. */ + // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ + // "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + /* Strict Type-Checking Options */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": false /* Raise error on expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* Enable strict null checks. */ + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ + /* Additional Checks */ + // "noUnusedLocals": true, /* Report errors on unused locals. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + /* Module Resolution Options */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + // "types": [], /* Type declaration files to be included in compilation. */ + // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + /* Source Map Options */ + // "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + /* Experimental Options */ + // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + } +} \ No newline at end of file diff --git a/protubuf/protobuf-egret/egret-project/scripts/wxgame/wxgame.ts b/protubuf/protobuf-egret/egret-project/scripts/wxgame/wxgame.ts new file mode 100644 index 0000000..e16c08e --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/scripts/wxgame/wxgame.ts @@ -0,0 +1,47 @@ +import * as fs from 'fs'; +import * as path from 'path'; +export class WxgamePlugin implements plugins.Command { + + constructor() { + } + async onFile(file: plugins.File) { + if (file.extname == '.js') { + const filename = file.origin; + if (filename == "libs/modules/promise/promise.js" || filename == 'libs/modules/promise/promise.min.js') { + return null; + } + if (filename == 'libs/modules/egret/egret.js' || filename == 'libs/modules/egret/egret.min.js') { + let content = file.contents.toString(); + content += `;window.egret = egret;`; + content = content.replace(/definition = __global/, "definition = window"); + file.contents = new Buffer(content); + } + else { + let content = file.contents.toString(); + if ( + filename == "libs/modules/res/res.js" || + filename == 'libs/modules/res/res.min.js' || + filename == 'libs/modules/assetsmanager/assetsmanager.min.js' || + filename == 'libs/modules/assetsmanager/assetsmanager.js' + ) { + content += ";window.RES = RES;" + } + if (filename == "libs/modules/eui/eui.js" || filename == 'libs/modules/eui/eui.min.js') { + content += ";window.eui = eui;" + } + if (filename == 'libs/modules/dragonBones/dragonBones.js' || filename == 'libs/modules/dragonBones/dragonBones.min.js') { + content += ';window.dragonBones = dragonBones'; + } + content = "var egret = window.egret;" + content; + if (filename == 'main.js') { + content += ";window.Main = Main;" + } + file.contents = new Buffer(content); + } + } + return file; + } + async onFinish(pluginContext) { + + } +} \ No newline at end of file diff --git a/protubuf/protobuf-egret/egret-project/src/LoadingUI.ts b/protubuf/protobuf-egret/egret-project/src/LoadingUI.ts new file mode 100644 index 0000000..e611046 --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/src/LoadingUI.ts @@ -0,0 +1,51 @@ +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +class LoadingUI extends egret.Sprite implements RES.PromiseTaskReporter { + + public constructor() { + super(); + this.createView(); + } + + private textField: egret.TextField; + + private createView(): void { + this.textField = new egret.TextField(); + this.addChild(this.textField); + this.textField.y = 300; + this.textField.width = 480; + this.textField.height = 100; + this.textField.textAlign = "center"; + } + + public onProgress(current: number, total: number): void { + this.textField.text = `Loading...${current}/${total}`; + } +} diff --git a/protubuf/protobuf-egret/egret-project/src/Main.ts b/protubuf/protobuf-egret/egret-project/src/Main.ts new file mode 100644 index 0000000..ecd027c --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/src/Main.ts @@ -0,0 +1,238 @@ +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +class Main extends egret.DisplayObjectContainer { + + + + public constructor() { + super(); + this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this); + } + + private onAddToStage(event: egret.Event) { + + + // awesomepackage.AwesomeMessage. + // let root = protobuf.Root.fromJSON(data); + + // // Obtain a message type + // var AwesomeMessage = root.lookupType("awesomepackage.AwesomeMessage"); + + // Exemplary payload + var payload = { awesomeField: "AwesomeString" }; + + // Verify the payload if necessary (i.e. when possibly incomplete or invalid) + var errMsg = awesomepackage.AwesomeMessage.verify(payload); + if (errMsg) + throw Error(errMsg); + // Create a new message + var message = awesomepackage.AwesomeMessage.create(payload); // or use .fromObject if conversion is necessary + console.log('message', message) + // Encode a message to an Uint8Array (browser) or Buffer (node) + var buffer = awesomepackage.AwesomeMessage.encode(message).finish(); + // ... do something with buffer + console.log('buffer', buffer) + // Decode an Uint8Array (browser) or Buffer (node) to a message + var message = awesomepackage.AwesomeMessage.decode(buffer); + + console.log('message', message) + // ... do something with message + // If the application uses length-delimited buffers, there is also encodeDelimited and decodeDelimited. + + // Maybe convert the message back to a plain object + var object = awesomepackage.AwesomeMessage.toObject(message, { + longs: String, + enums: String, + bytes: String, + // see ConversionOptions + }); + + console.log('object', object) + + + // protobuf.load("awesome.proto", function (err, root) { + + + + + // }); + + + + + egret.lifecycle.addLifecycleListener((context) => { + // custom lifecycle plugin + + context.onUpdate = () => { + + } + }) + + egret.lifecycle.onPause = () => { + egret.ticker.pause(); + } + + egret.lifecycle.onResume = () => { + egret.ticker.resume(); + } + + this.runGame().catch(e => { + console.log(e); + }) + + + + } + + private async runGame() { + await this.loadResource() + this.createGameScene(); + const result = await RES.getResAsync("description_json") + this.startAnimation(result); + await platform.login(); + const userInfo = await platform.getUserInfo(); + console.log(userInfo); + + } + + private async loadResource() { + try { + const loadingView = new LoadingUI(); + this.stage.addChild(loadingView); + await RES.loadConfig("resource/default.res.json", "resource/"); + await RES.loadGroup("preload", 0, loadingView); + this.stage.removeChild(loadingView); + } + catch (e) { + console.error(e); + } + } + + private textfield: egret.TextField; + + /** + * 创建游戏场景 + * Create a game scene + */ + private createGameScene() { + let sky = this.createBitmapByName("bg_jpg"); + this.addChild(sky); + let stageW = this.stage.stageWidth; + let stageH = this.stage.stageHeight; + sky.width = stageW; + sky.height = stageH; + + let topMask = new egret.Shape(); + topMask.graphics.beginFill(0x000000, 0.5); + topMask.graphics.drawRect(0, 0, stageW, 172); + topMask.graphics.endFill(); + topMask.y = 33; + this.addChild(topMask); + + let icon = this.createBitmapByName("egret_icon_png"); + this.addChild(icon); + icon.x = 26; + icon.y = 33; + + let line = new egret.Shape(); + line.graphics.lineStyle(2, 0xffffff); + line.graphics.moveTo(0, 0); + line.graphics.lineTo(0, 117); + line.graphics.endFill(); + line.x = 172; + line.y = 61; + this.addChild(line); + + + let colorLabel = new egret.TextField(); + colorLabel.textColor = 0xffffff; + colorLabel.width = stageW - 172; + colorLabel.textAlign = "center"; + colorLabel.text = "Hello Egret"; + colorLabel.size = 24; + colorLabel.x = 172; + colorLabel.y = 80; + this.addChild(colorLabel); + + let textfield = new egret.TextField(); + this.addChild(textfield); + textfield.alpha = 0; + textfield.width = stageW - 172; + textfield.textAlign = egret.HorizontalAlign.CENTER; + textfield.size = 24; + textfield.textColor = 0xffffff; + textfield.x = 172; + textfield.y = 135; + this.textfield = textfield; + + + } + + /** + * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。 + * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json. + */ + private createBitmapByName(name: string) { + let result = new egret.Bitmap(); + let texture: egret.Texture = RES.getRes(name); + result.texture = texture; + return result; + } + + /** + * 描述文件加载成功,开始播放动画 + * Description file loading is successful, start to play the animation + */ + private startAnimation(result: string[]) { + let parser = new egret.HtmlTextParser(); + + let textflowArr = result.map(text => parser.parse(text)); + let textfield = this.textfield; + let count = -1; + let change = () => { + count++; + if (count >= textflowArr.length) { + count = 0; + } + let textFlow = textflowArr[count]; + + // 切换描述内容 + // Switch to described content + textfield.textFlow = textFlow; + let tw = egret.Tween.get(textfield); + tw.to({ "alpha": 1 }, 200); + tw.wait(2000); + tw.to({ "alpha": 0 }, 200); + tw.call(change, this); + }; + + change(); + } +} \ No newline at end of file diff --git a/protubuf/protobuf-egret/egret-project/src/Platform.ts b/protubuf/protobuf-egret/egret-project/src/Platform.ts new file mode 100644 index 0000000..639c878 --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/src/Platform.ts @@ -0,0 +1,40 @@ +/** + * 平台数据接口。 + * 由于每款游戏通常需要发布到多个平台上,所以提取出一个统一的接口用于开发者获取平台数据信息 + * 推荐开发者通过这种方式封装平台逻辑,以保证整体结构的稳定 + * 由于不同平台的接口形式各有不同,白鹭推荐开发者将所有接口封装为基于 Promise 的异步形式 + */ +declare interface Platform { + + getUserInfo(): Promise; + + login(): Promise; +} + +class DebugPlatform implements Platform { + async getUserInfo() { + return { nickName: "username" } + } + async login() { + + } +} + + +if (!window.platform) { + window.platform = new DebugPlatform(); +} + + + +declare let platform: Platform; + +declare interface Window { + + platform: Platform +} + + + + + diff --git a/protubuf/protobuf-egret/egret-project/template/runtime/native_loader.js b/protubuf/protobuf-egret/egret-project/template/runtime/native_loader.js new file mode 100644 index 0000000..ad94285 --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/template/runtime/native_loader.js @@ -0,0 +1,8 @@ +require("launcher/native_require.js"); + +egret_native.egtMain = function () { + egret_native.nativeType = "native"; + + egret_native.egretInit(); + egret_native.egretStart(); +}; diff --git a/protubuf/protobuf-egret/egret-project/template/runtime/native_require.js b/protubuf/protobuf-egret/egret-project/template/runtime/native_require.js new file mode 100644 index 0000000..3b7e504 --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/template/runtime/native_require.js @@ -0,0 +1,53 @@ +var manifest = JSON.parse(egret_native.readFileSync("manifest.json")); +var game_file_list = manifest.initial.concat(manifest.game); + +var window = this; + +egret_native.setSearchPaths([""]); + +egret_native.requireFiles = function () { + for (var key in game_file_list) { + var src = game_file_list[key]; + require(src); + } +}; + +egret_native.egretInit = function () { + if(egret_native.featureEnable) { + //控制一些优化方案是否开启 + //Control whether some optimization options are open + var result = egret_native.featureEnable({ + + }); + } + egret_native.requireFiles(); + egret.dom = {}; + egret.dom.drawAsCanvas = function () { + }; +}; + +egret_native.egretStart = function () { + var option = { + //以下为自动修改,请勿修改 + //The following is automatically modified, please do not modify + //----auto option start---- + entryClassName: "Main", + frameRate: 30, + scaleMode: "showAll", + contentWidth: 640, + contentHeight: 1136, + showPaintRect: false, + showFPS: false, + fpsStyles: "x:0,y:0,size:12,textColor:0xffffff,bgAlpha:0.9", + showLog: false, + logFilter: "", + maxTouches: 2, + textureScaleFactor: 1 + //----auto option end---- + }; + + egret.native.NativePlayer.option = option; + egret.runEgret(); + egret_native.Label.createLabel("/system/fonts/DroidSansFallback.ttf", 20, "", 0); + egret_native.EGTView.preSetOffScreenBufferEnable(true); +}; \ No newline at end of file diff --git a/protubuf/protobuf-egret/egret-project/template/runtime/runtime_loader.js b/protubuf/protobuf-egret/egret-project/template/runtime/runtime_loader.js new file mode 100644 index 0000000..5b5f76b --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/template/runtime/runtime_loader.js @@ -0,0 +1,8 @@ +require("launcher/native_require.js"); + +egret_native.egtMain = function () { + egret_native.nativeType = "runtime"; + + egret_native.egretInit(); + egret_native.egretStart(); +}; \ No newline at end of file diff --git a/protubuf/protobuf-egret/egret-project/template/web/index.html b/protubuf/protobuf-egret/egret-project/template/web/index.html new file mode 100644 index 0000000..73f7bb1 --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/template/web/index.html @@ -0,0 +1,96 @@ + + + + + + Egret + + + + + + + + + + +
+
+ + + + \ No newline at end of file diff --git a/protubuf/protobuf-egret/egret-project/tsconfig.json b/protubuf/protobuf-egret/egret-project/tsconfig.json new file mode 100644 index 0000000..483f9e4 --- /dev/null +++ b/protubuf/protobuf-egret/egret-project/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "es5", + "outDir": "bin-debug", + "experimentalDecorators": true, + "lib": [ + "es5", + "dom", + "es2015.promise" + ], + "types": [] + }, + "include": [ + "src", + "libs", + "protobuf/**/*.d.ts" + ] +} \ No newline at end of file diff --git a/protubuf/protobuf-egret/egret-project_wxgame/.DS_Store b/protubuf/protobuf-egret/egret-project_wxgame/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/protubuf/protobuf-egret/egret-project_wxgame/.DS_Store differ diff --git a/protubuf/protobuf-egret/egret-project_wxgame/egret.wxgame.js b/protubuf/protobuf-egret/egret-project_wxgame/egret.wxgame.js new file mode 100644 index 0000000..46c21c7 --- /dev/null +++ b/protubuf/protobuf-egret/egret-project_wxgame/egret.wxgame.js @@ -0,0 +1,7773 @@ +var __reflect = (this && this.__reflect) || function (p, c, t) { + p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t; +}; +var __extends = this && this.__extends || function __extends(t, e) { + function r() { + this.constructor = t; +} +for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]); +r.prototype = e.prototype, t.prototype = new r(); +}; +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var wxapp; + (function (wxapp) { + /** + * @private + */ + var WebFps = (function (_super) { + __extends(WebFps, _super); + function WebFps(stage, showFPS, showLog, logFilter, styles) { + var _this = _super.call(this) || this; + _this.showPanle = true; + _this.fpsHeight = 0; + _this.WIDTH = 101; + _this.HEIGHT = 20; + _this.bgCanvasColor = "#18304b"; + _this.fpsFrontColor = "#18fefe"; + _this.WIDTH_COST = 50; + _this.cost1Color = "#18fefe"; + // private cost2Color = "#ffff00"; + _this.cost3Color = "#ff0000"; + _this.arrFps = []; + _this.arrCost = []; + _this.arrLog = []; + if (showFPS || showLog) { + if (egret.Capabilities.renderMode == 'canvas') { + _this.renderMode = "Canvas"; + } + else { + _this.renderMode = "WebGL"; + } + _this.panelX = styles["x"] === undefined ? 0 : parseInt(styles['x']); + _this.panelY = styles["y"] === undefined ? 0 : parseInt(styles['y']); + _this.fontColor = styles["textColor"] === undefined ? '#ffffff' : styles['textColor'].replace("0x", "#"); + _this.fontSize = styles["size"] === undefined ? 12 : parseInt(styles['size']); + if (egret.Capabilities.isMobile) { + _this.fontSize -= 2; + } + var all = document.createElement('div'); + all.style.position = 'absolute'; + all.style.background = "rgba(0,0,0," + styles['bgAlpha'] + ")"; + all.style.left = _this.panelX + 'px'; + all.style.top = _this.panelY + 'px'; + all.style.pointerEvents = 'none'; + document.body.appendChild(all); + var container = document.createElement('div'); + container.style.color = _this.fontColor; + container.style.fontSize = _this.fontSize + 'px'; + container.style.lineHeight = _this.fontSize + 'px'; + container.style.margin = '4px 4px 4px 4px'; + _this.container = container; + all.appendChild(container); + if (showFPS) + _this.addFps(); + if (showLog) + _this.addLog(); + } + return _this; + } + WebFps.prototype.addFps = function () { + var div = document.createElement('div'); + div.style.display = 'inline-block'; + this.containerFps = div; + this.container.appendChild(div); + var fps = document.createElement('div'); + fps.style.paddingBottom = '2px'; + this.fps = fps; + this.containerFps.appendChild(fps); + fps.innerHTML = "0 FPS " + this.renderMode + "
min0 max0 avg0"; + var canvas = document.createElement('canvas'); + this.containerFps.appendChild(canvas); + canvas.width = this.WIDTH; + canvas.height = this.HEIGHT; + this.canvasFps = canvas; + var context = canvas.getContext('2d'); + this.contextFps = context; + context.fillStyle = this.bgCanvasColor; + context.fillRect(0, 0, this.WIDTH, this.HEIGHT); + var divDatas = document.createElement('div'); + this.divDatas = divDatas; + this.containerFps.appendChild(divDatas); + var left = document.createElement('div'); + left.style['float'] = 'left'; + left.innerHTML = "Draw
Cost"; + divDatas.appendChild(left); + var right = document.createElement('div'); + right.style.paddingLeft = left.offsetWidth + 20 + "px"; + divDatas.appendChild(right); + var draw = document.createElement('div'); + this.divDraw = draw; + draw.innerHTML = "0
"; + right.appendChild(draw); + var cost = document.createElement('div'); + this.divCost = cost; + cost.innerHTML = "0 0"; + right.appendChild(cost); + canvas = document.createElement('canvas'); + this.canvasCost = canvas; + this.containerFps.appendChild(canvas); + canvas.width = this.WIDTH; + canvas.height = this.HEIGHT; + context = canvas.getContext('2d'); + this.contextCost = context; + context.fillStyle = this.bgCanvasColor; + context.fillRect(0, 0, this.WIDTH, this.HEIGHT); + context.fillStyle = "#000000"; + context.fillRect(this.WIDTH_COST, 0, 1, this.HEIGHT); + this.fpsHeight = this.container.offsetHeight; + }; + WebFps.prototype.addLog = function () { + var log = document.createElement('div'); + log.style.maxWidth = document.body.clientWidth - 8 - this.panelX + 'px'; + log.style.wordWrap = "break-word"; + this.log = log; + this.container.appendChild(log); + }; + WebFps.prototype.update = function (datas, showLastData) { + if (showLastData === void 0) { showLastData = false; } + var numFps; + var numCostTicker; + var numCostRender; + if (!showLastData) { + numFps = datas.fps; + numCostTicker = datas.costTicker; + numCostRender = datas.costRender; + this.lastNumDraw = datas.draw; + this.arrFps.push(numFps); + this.arrCost.push([numCostTicker, numCostRender]); + } + else { + numFps = this.arrFps[this.arrFps.length - 1]; + numCostTicker = this.arrCost[this.arrCost.length - 1][0]; + numCostRender = this.arrCost[this.arrCost.length - 1][1]; + } + var fpsTotal = 0; + var lenFps = this.arrFps.length; + if (lenFps > 101) { + lenFps = 101; + this.arrFps.shift(); + this.arrCost.shift(); + } + var fpsMin = this.arrFps[0]; + var fpsMax = this.arrFps[0]; + for (var i = 0; i < lenFps; i++) { + var num = this.arrFps[i]; + fpsTotal += num; + if (num < fpsMin) + fpsMin = num; + else if (num > fpsMax) + fpsMax = num; + } + var WIDTH = this.WIDTH; + var HEIGHT = this.HEIGHT; + var context = this.contextFps; + context.drawImage(this.canvasFps, 1, 0, WIDTH - 1, HEIGHT, 0, 0, WIDTH - 1, HEIGHT); + context.fillStyle = this.bgCanvasColor; + context.fillRect(WIDTH - 1, 0, 1, HEIGHT); + var lastHeight = Math.floor(numFps / 60 * 20); + if (lastHeight < 1) + lastHeight = 1; + context.fillStyle = this.fpsFrontColor; + context.fillRect(WIDTH - 1, 20 - lastHeight, 1, lastHeight); + var WIDTH_COST = this.WIDTH_COST; + context = this.contextCost; + context.drawImage(this.canvasCost, 1, 0, WIDTH_COST - 1, HEIGHT, 0, 0, WIDTH_COST - 1, HEIGHT); + context.drawImage(this.canvasCost, WIDTH_COST + 2, 0, WIDTH_COST - 1, HEIGHT, WIDTH_COST + 1, 0, WIDTH_COST - 1, HEIGHT); + var c1Height = Math.floor(numCostTicker / 2); + if (c1Height < 1) + c1Height = 1; + else if (c1Height > 20) + c1Height = 20; + //todo lcj + var c2Height = Math.floor(numCostRender / 2); + if (c2Height < 1) + c2Height = 1; + else if (c2Height > 20) + c2Height = 20; + context.fillStyle = this.bgCanvasColor; + context.fillRect(WIDTH_COST - 1, 0, 1, HEIGHT); + context.fillRect(WIDTH_COST * 2, 0, 1, HEIGHT); + context.fillRect(WIDTH_COST * 3 + 1, 0, 1, HEIGHT); + context.fillStyle = this.cost1Color; + context.fillRect(WIDTH_COST - 1, 20 - c1Height, 1, c1Height); + context.fillStyle = this.cost3Color; + context.fillRect(WIDTH_COST * 2, 20 - c2Height, 1, c2Height); + var fpsAvg = Math.floor(fpsTotal / lenFps); + var fpsOutput = numFps + " FPS " + this.renderMode; + if (this.showPanle) { + fpsOutput += "
min" + fpsMin + " max" + fpsMax + " avg" + fpsAvg; + this.divDraw.innerHTML = this.lastNumDraw + "
"; + this.divCost.innerHTML = "" + numCostTicker + " " + numCostRender + ""; + } + this.fps.innerHTML = fpsOutput; + }; + ; + WebFps.prototype.updateInfo = function (info) { + this.arrLog.push(info); + this.log.innerHTML = this.arrLog.join('
'); + while (document.body.clientHeight < (this.log.offsetHeight + this.fpsHeight + this.panelY + this.fontSize * 2)) { + this.arrLog.shift(); + this.log.innerHTML = this.arrLog.join('
'); + } + }; + WebFps.prototype.updateWarn = function (info) { + }; + WebFps.prototype.updateError = function (info) { + }; + return WebFps; + }(egret.DisplayObject)); + wxapp.WebFps = WebFps; + __reflect(WebFps.prototype, "egret.wxapp.WebFps", ["egret.FPSDisplay", "egret.DisplayObject"]); + egret.FPSDisplay = WebFps; + })(wxapp = egret.wxapp || (egret.wxapp = {})); +})(egret || (egret = {})); +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// +if (window['HTMLDivElement'] == undefined) { + window['HTMLDivElement'] = HTMLElement; +} +// There is no HTMLDivElement in webkit for air +if (window['HTMLVideoElement'] == undefined) { + window['HTMLVideoElement'] = HTMLDivElement; +} + +(function (egret) { + var wxapp; + (function (wxapp) { + var className = "egret.BitmapData"; + egret.registerClass(HTMLImageElement, className); + egret.registerClass(HTMLCanvasElement, className); + egret.registerClass(HTMLVideoElement, className); + })(wxapp = egret.wxapp || (egret.wxapp = {})); +})(egret || (egret = {})); +(function (egret) { + /** + * 转换 Image,Canvas,Video 为 Egret 框架内使用的 BitmapData 对象。 + * @param data 需要转换的对象,包括HTMLImageElement|HTMLCanvasElement|HTMLVideoElement + * @deprecated + */ + function $toBitmapData(data) { + data["hashCode"] = data["$hashCode"] = egret.$hashCount++; + return data; + } + egret.$toBitmapData = $toBitmapData; +})(egret || (egret = {})); +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var localStorage; + (function (localStorage) { + var wxapp; + (function (wxapp) { + /** + * @private + * + * @param key + * @returns + */ + function getItem(key) { + return window.localStorage.getItem(key); + } + /** + * @private + * + * @param key + * @param value + * @returns + */ + function setItem(key, value) { + try { + window.localStorage.setItem(key, value); + return true; + } + catch (e) { + egret.$warn(1047, key, value); + return false; + } + } + /** + * @private + * + * @param key + */ + function removeItem(key) { + window.localStorage.removeItem(key); + } + /** + * @private + * + */ + function clear() { + window.localStorage.clear(); + } + localStorage.getItem = getItem; + localStorage.setItem = setItem; + localStorage.removeItem = removeItem; + localStorage.clear = clear; + })(wxapp = localStorage.wxapp || (localStorage.wxapp = {})); + })(localStorage = egret.localStorage || (egret.localStorage = {})); +})(egret || (egret = {})); +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var wxapp; + (function (wxapp) { + /** + * @private + * @inheritDoc + */ + var HtmlSound = (function (_super) { + __extends(HtmlSound, _super); + /** + * @private + * @inheritDoc + */ + function HtmlSound() { + var _this = _super.call(this) || this; + /** + * @private + */ + _this.loaded = false; + return _this; + } + Object.defineProperty(HtmlSound.prototype, "length", { + get: function () { + if (this.originAudio) { + return this.originAudio.duration; + } + throw new Error("sound not loaded!"); + //return 0; + }, + enumerable: true, + configurable: true + }); + /** + * @inheritDoc + */ + HtmlSound.prototype.load = function (url) { + var self = this; + this.url = url; + if (true && !url) { + egret.$error(3002); + } + var audio = new Audio(url); + audio.addEventListener("canplaythrough", onAudioLoaded); + audio.addEventListener("error", onAudioError); + var ua = navigator.userAgent.toLowerCase(); + if (ua.indexOf("firefox") >= 0) { + audio.autoplay = !0; + audio.muted = true; + } + // audio.load(); wxapp没有此接口 + this.originAudio = audio; + if (HtmlSound.clearAudios[this.url]) { + delete HtmlSound.clearAudios[this.url]; + } + HtmlSound.$recycle(this.url, audio); + function onAudioLoaded() { + removeListeners(); + if (ua.indexOf("firefox") >= 0) { + audio.pause(); + audio.muted = false; + } + self.loaded = true; + self.dispatchEventWith(egret.Event.COMPLETE); + } + function onAudioError() { + removeListeners(); + self.dispatchEventWith(egret.IOErrorEvent.IO_ERROR); + } + function removeListeners() { + audio.removeEventListener("canplaythrough", onAudioLoaded); + audio.removeEventListener("error", onAudioError); + } + }; + /** + * @inheritDoc + */ + HtmlSound.prototype.play = function (startTime, loops) { + startTime = +startTime || 0; + loops = +loops || 0; + if (true && this.loaded == false) { + egret.$error(1049); + } + var audio = HtmlSound.$pop(this.url); + if (audio == null) { + audio = this.originAudio.cloneNode(); + } + else { + //audio.load(); + } + audio.autoplay = true; + var channel = new wxapp.HtmlSoundChannel(audio); + channel.$url = this.url; + channel.$loops = loops; + channel.$startTime = startTime; + channel.$play(); + egret.sys.$pushSoundChannel(channel); + return channel; + }; + /** + * @inheritDoc + */ + HtmlSound.prototype.close = function () { + if (this.loaded == false && this.originAudio) + this.originAudio.src = ""; + if (this.originAudio) + this.originAudio = null; + HtmlSound.$clear(this.url); + }; + HtmlSound.$clear = function (url) { + HtmlSound.clearAudios[url] = true; + var array = HtmlSound.audios[url]; + if (array) { + array.length = 0; + } + }; + HtmlSound.$pop = function (url) { + var array = HtmlSound.audios[url]; + if (array && array.length > 0) { + return array.pop(); + } + return null; + }; + HtmlSound.$recycle = function (url, audio) { + if (HtmlSound.clearAudios[url]) { + return; + } + var array = HtmlSound.audios[url]; + if (HtmlSound.audios[url] == null) { + array = HtmlSound.audios[url] = []; + } + array.push(audio); + }; + /** + * Background music + * @version Egret 2.4 + * @platform Web,Native + * @language en_US + */ + /** + * 背景音乐 + * @version Egret 2.4 + * @platform Web,Native + * @language zh_CN + */ + HtmlSound.MUSIC = "music"; + /** + * EFFECT + * @version Egret 2.4 + * @platform Web,Native + * @language en_US + */ + /** + * 音效 + * @version Egret 2.4 + * @platform Web,Native + * @language zh_CN + */ + HtmlSound.EFFECT = "effect"; + /** + * @private + */ + HtmlSound.audios = {}; + HtmlSound.clearAudios = {}; + return HtmlSound; + }(egret.EventDispatcher)); + wxapp.HtmlSound = HtmlSound; + __reflect(HtmlSound.prototype, "egret.wxapp.HtmlSound", ["egret.Sound"]); + })(wxapp = egret.wxapp || (egret.wxapp = {})); +})(egret || (egret = {})); +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var wxapp; + (function (wxapp) { + /** + * @private + * @inheritDoc + */ + var HtmlSoundChannel = (function (_super) { + __extends(HtmlSoundChannel, _super); + /** + * @private + */ + function HtmlSoundChannel(audio) { + var _this = _super.call(this) || this; + /** + * @private + */ + _this.$startTime = 0; + /** + * @private + */ + _this.audio = null; + //声音是否已经播放完成 + _this.isStopped = false; + _this.canPlay = function () { + _this.audio.removeEventListener("canplay", _this.canPlay); + try { + _this.audio.currentTime = _this.$startTime; + } + catch (e) { + } + finally { + _this.audio.play(); + } + }; + /** + * @private + */ + _this.onPlayEnd = function () { + if (_this.$loops == 1) { + _this.stop(); + _this.dispatchEventWith(egret.Event.SOUND_COMPLETE); + return; + } + if (_this.$loops > 0) { + _this.$loops--; + } + ///////////// + //this.audio.load(); + _this.$play(); + }; + /** + * @private + */ + _this._volume = 1; + audio.addEventListener("ended", _this.onPlayEnd); + _this.audio = audio; + return _this; + } + HtmlSoundChannel.prototype.$play = function () { + if (this.isStopped) { + egret.$error(1036); + return; + } + try { + //this.audio.pause(); + this.audio.volume = this._volume; + this.audio.currentTime = this.$startTime; + } + catch (e) { + this.audio.addEventListener("canplay", this.canPlay); + return; + } + this.audio.play(); + }; + /** + * @private + * @inheritDoc + */ + HtmlSoundChannel.prototype.stop = function () { + if (!this.audio) + return; + if (!this.isStopped) { + egret.sys.$popSoundChannel(this); + } + this.isStopped = true; + var audio = this.audio; + audio.removeEventListener("ended", this.onPlayEnd); + audio.volume = 0; + this._volume = 0; + this.audio = null; + var url = this.$url; + //延迟一定时间再停止,规避chrome报错 + window.setTimeout(function () { + audio.pause(); + wxapp.HtmlSound.$recycle(url, audio); + }, 200); + }; + Object.defineProperty(HtmlSoundChannel.prototype, "volume", { + /** + * @private + * @inheritDoc + */ + get: function () { + return this._volume; + }, + /** + * @inheritDoc + */ + set: function (value) { + if (this.isStopped) { + egret.$error(1036); + return; + } + this._volume = value; + if (!this.audio) + return; + this.audio.volume = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(HtmlSoundChannel.prototype, "position", { + /** + * @private + * @inheritDoc + */ + get: function () { + if (!this.audio) + return 0; + return this.audio.currentTime; + }, + enumerable: true, + configurable: true + }); + return HtmlSoundChannel; + }(egret.EventDispatcher)); + wxapp.HtmlSoundChannel = HtmlSoundChannel; + __reflect(HtmlSoundChannel.prototype, "egret.wxapp.HtmlSoundChannel", ["egret.SoundChannel", "egret.IEventDispatcher"]); + })(wxapp = egret.wxapp || (egret.wxapp = {})); +})(egret || (egret = {})); +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var wxapp; + (function (wxapp) { + /** + * @private + */ + var WebAudioDecode = (function () { + function WebAudioDecode() { + } + /** + * @private + * + */ + WebAudioDecode.decodeAudios = function () { + if (WebAudioDecode.decodeArr.length <= 0) { + return; + } + if (WebAudioDecode.isDecoding) { + return; + } + WebAudioDecode.isDecoding = true; + var decodeInfo = WebAudioDecode.decodeArr.shift(); + WebAudioDecode.ctx.decodeAudioData(decodeInfo["buffer"], function (audioBuffer) { + decodeInfo["self"].audioBuffer = audioBuffer; + if (decodeInfo["success"]) { + decodeInfo["success"](); + } + WebAudioDecode.isDecoding = false; + WebAudioDecode.decodeAudios(); + }, function () { + alert("sound decode error: " + decodeInfo["url"] + "!\nsee http://edn.egret.com/cn/docs/page/156"); + if (decodeInfo["fail"]) { + decodeInfo["fail"](); + } + WebAudioDecode.isDecoding = false; + WebAudioDecode.decodeAudios(); + }); + }; + /** + * @private + */ + WebAudioDecode.decodeArr = []; + /** + * @private + */ + WebAudioDecode.isDecoding = false; + return WebAudioDecode; + }()); + wxapp.WebAudioDecode = WebAudioDecode; + __reflect(WebAudioDecode.prototype, "egret.wxapp.WebAudioDecode"); + /** + * @private + * @inheritDoc + */ + var WebAudioSound = (function (_super) { + __extends(WebAudioSound, _super); + /** + * @private + * @inheritDoc + */ + function WebAudioSound() { + var _this = _super.call(this) || this; + /** + * @private + */ + _this.loaded = false; + return _this; + } + Object.defineProperty(WebAudioSound.prototype, "length", { + get: function () { + if (this.audioBuffer) { + return this.audioBuffer.duration; + } + throw new Error("sound not loaded!"); + //return 0; + }, + enumerable: true, + configurable: true + }); + /** + * @inheritDoc + */ + WebAudioSound.prototype.load = function (url) { + var self = this; + this.url = url; + if (true && !url) { + egret.$error(3002); + } + var request = new XMLHttpRequest(); + request.open("GET", url, true); + request.responseType = "arraybuffer"; + request.onreadystatechange = function () { + if (request.readyState == 4) { + var ioError = (request.status >= 400 || request.status == 0); + if (ioError) { + self.dispatchEventWith(egret.IOErrorEvent.IO_ERROR); + } + else { + WebAudioDecode.decodeArr.push({ + "buffer": request.response, + "success": onAudioLoaded, + "fail": onAudioError, + "self": self, + "url": self.url + }); + WebAudioDecode.decodeAudios(); + } + } + }; + request.send(); + function onAudioLoaded() { + self.loaded = true; + self.dispatchEventWith(egret.Event.COMPLETE); + } + function onAudioError() { + self.dispatchEventWith(egret.IOErrorEvent.IO_ERROR); + } + }; + /** + * @inheritDoc + */ + WebAudioSound.prototype.play = function (startTime, loops) { + startTime = +startTime || 0; + loops = +loops || 0; + if (true && this.loaded == false) { + egret.$error(1049); + } + var channel = new wxapp.WebAudioSoundChannel(); + channel.$url = this.url; + channel.$loops = loops; + channel.$audioBuffer = this.audioBuffer; + channel.$startTime = startTime; + channel.$play(); + egret.sys.$pushSoundChannel(channel); + return channel; + }; + /** + * @inheritDoc + */ + WebAudioSound.prototype.close = function () { + }; + /** + * Background music + * @version Egret 2.4 + * @platform Web,Native + * @language en_US + */ + /** + * 背景音乐 + * @version Egret 2.4 + * @platform Web,Native + * @language zh_CN + */ + WebAudioSound.MUSIC = "music"; + /** + * EFFECT + * @version Egret 2.4 + * @platform Web,Native + * @language en_US + */ + /** + * 音效 + * @version Egret 2.4 + * @platform Web,Native + * @language zh_CN + */ + WebAudioSound.EFFECT = "effect"; + return WebAudioSound; + }(egret.EventDispatcher)); + wxapp.WebAudioSound = WebAudioSound; + __reflect(WebAudioSound.prototype, "egret.wxapp.WebAudioSound", ["egret.Sound"]); + })(wxapp = egret.wxapp || (egret.wxapp = {})); +})(egret || (egret = {})); +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var wxapp; + (function (wxapp) { + /** + * @private + * @inheritDoc + */ + var WebAudioSoundChannel = (function (_super) { + __extends(WebAudioSoundChannel, _super); + /** + * @private + */ + function WebAudioSoundChannel() { + var _this = _super.call(this) || this; + /** + * @private + */ + _this.$startTime = 0; + /** + * @private + */ + _this.bufferSource = null; + /** + * @private + */ + _this.context = wxapp.WebAudioDecode.ctx; + //声音是否已经播放完成 + _this.isStopped = false; + /** + * @private + */ + _this._currentTime = 0; + /** + * @private + */ + _this._volume = 1; + /** + * @private + */ + _this.onPlayEnd = function () { + if (_this.$loops == 1) { + _this.stop(); + _this.dispatchEventWith(egret.Event.SOUND_COMPLETE); + return; + } + if (_this.$loops > 0) { + _this.$loops--; + } + ///////////// + _this.$play(); + }; + /** + * @private + */ + _this._startTime = 0; + if (_this.context["createGain"]) { + _this.gain = _this.context["createGain"](); + } + else { + _this.gain = _this.context["createGainNode"](); + } + return _this; + } + WebAudioSoundChannel.prototype.$play = function () { + if (this.isStopped) { + egret.$error(1036); + return; + } + if (this.bufferSource) { + this.bufferSource.onended = null; + this.bufferSource = null; + } + var context = this.context; + var gain = this.gain; + var bufferSource = context.createBufferSource(); + this.bufferSource = bufferSource; + bufferSource.buffer = this.$audioBuffer; + bufferSource.connect(gain); + gain.connect(context.destination); + bufferSource.onended = this.onPlayEnd; + this._startTime = Date.now(); + this.gain.gain.value = this._volume; + bufferSource.start(0, this.$startTime); + this._currentTime = 0; + }; + WebAudioSoundChannel.prototype.stop = function () { + if (this.bufferSource) { + var sourceNode = this.bufferSource; + if (sourceNode.stop) { + sourceNode.stop(0); + } + else { + sourceNode.noteOff(0); + } + sourceNode.onended = null; + sourceNode.disconnect(); + this.bufferSource = null; + this.$audioBuffer = null; + } + if (!this.isStopped) { + egret.sys.$popSoundChannel(this); + } + this.isStopped = true; + }; + Object.defineProperty(WebAudioSoundChannel.prototype, "volume", { + /** + * @private + * @inheritDoc + */ + get: function () { + return this._volume; + }, + /** + * @inheritDoc + */ + set: function (value) { + if (this.isStopped) { + egret.$error(1036); + return; + } + this._volume = value; + this.gain.gain.value = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WebAudioSoundChannel.prototype, "position", { + /** + * @private + * @inheritDoc + */ + get: function () { + if (this.bufferSource) { + return (Date.now() - this._startTime) / 1000 + this.$startTime; + } + return 0; + }, + enumerable: true, + configurable: true + }); + return WebAudioSoundChannel; + }(egret.EventDispatcher)); + wxapp.WebAudioSoundChannel = WebAudioSoundChannel; + __reflect(WebAudioSoundChannel.prototype, "egret.wxapp.WebAudioSoundChannel", ["egret.SoundChannel", "egret.IEventDispatcher"]); + })(wxapp = egret.wxapp || (egret.wxapp = {})); +})(egret || (egret = {})); +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var wxapp; + (function (wxapp) { + /** + * @private + * @inheritDoc + */ + var WebVideo = (function (_super) { + __extends(WebVideo, _super); + /** + * @inheritDoc + */ + function WebVideo(url, cache) { + if (cache === void 0) { cache = true; } + var _this = _super.call(this) || this; + /** + * @private + */ + _this.loaded = false; + /** + * @private + */ + _this.closed = false; + /** + * @private + */ + _this.heightSet = NaN; + /** + * @private + */ + _this.widthSet = NaN; + /** + * @private + * pc上视频卡住的时候不能暂停 + */ + _this.waiting = false; + /** + * @private + * 用户是否设置了 pause + */ + _this.userPause = false; + /** + * @private + * 用户是否设置了 play + */ + _this.userPlay = false; + _this.isPlayed = false; + _this.screenChanged = function (e) { + var isfullscreen = document.fullscreenEnabled || document.webkitIsFullScreen; + if (!isfullscreen) { + _this.checkFullScreen(false); + if (!egret.Capabilities.isMobile) { + _this._fullscreen = isfullscreen; + } + } + }; + _this._fullscreen = true; + /** + * @private + * + */ + _this.onVideoLoaded = function () { + _this.video.removeEventListener("canplay", _this.onVideoLoaded); + var video = _this.video; + _this.loaded = true; + //video.pause(); + if (_this.posterData) { + _this.posterData.width = _this.getPlayWidth(); + _this.posterData.height = _this.getPlayHeight(); + } + video.width = video.videoWidth; + video.height = video.videoHeight; + window.setTimeout(function () { + _this.dispatchEventWith(egret.Event.COMPLETE); + }, 200); + }; + _this.$renderNode = new egret.sys.BitmapNode(); + _this.src = url; + _this.once(egret.Event.ADDED_TO_STAGE, _this.loadPoster, _this); + if (url) { + _this.load(); + } + return _this; + } + /** + * @inheritDoc + */ + WebVideo.prototype.load = function (url, cache) { + var _this = this; + if (cache === void 0) { cache = true; } + url = url || this.src; + this.src = url; + if (true && !url) { + egret.$error(3002); + } + if (this.video && this.video.src == url) { + return; + } + var video; + if (!this.video || egret.Capabilities.isMobile) { + video = document.createElement("video"); + this.video = video; + video.controls = null; + } + else { + video = this.video; + } + video.src = url; + video.setAttribute("autoplay", "autoplay"); + video.setAttribute("webkit-playsinline", "true"); + video.addEventListener("canplay", this.onVideoLoaded); + video.addEventListener("error", function () { return _this.onVideoError(); }); + video.addEventListener("ended", function () { return _this.onVideoEnded(); }); + var firstPause = false; + video.addEventListener("canplay", function () { + _this.waiting = false; + if (!firstPause) { + firstPause = true; + video.pause(); + } + else { + if (_this.userPause) { + _this.pause(); + } + else if (_this.userPlay) { + _this.play(); + } + } + }); + video.addEventListener("waiting", function () { + _this.waiting = true; + }); + video.load(); + this.videoPlay(); + video.style.position = "absolute"; + video.style.top = "0px"; + video.style.zIndex = "-88888"; + video.style.left = "0px"; + video.height = 1; + video.width = 1; + }; + /** + * @inheritDoc + */ + WebVideo.prototype.play = function (startTime, loop) { + var _this = this; + if (loop === void 0) { loop = false; } + if (this.loaded == false) { + this.load(this.src); + this.once(egret.Event.COMPLETE, function (e) { return _this.play(startTime, loop); }, this); + return; + } + this.isPlayed = true; + var video = this.video; + if (startTime != undefined) + video.currentTime = +startTime || 0; + video.loop = !!loop; + if (egret.Capabilities.isMobile) { + video.style.zIndex = "-88888"; //移动端,就算设置成最小,只要全屏,都会在最上层,而且在自动退出去后,不担心挡住canvas + } + else { + video.style.zIndex = "9999"; + } + video.style.position = "absolute"; + video.style.top = "0px"; + video.style.left = "0px"; + video.height = video.videoHeight; + video.width = video.videoWidth; + if (egret.Capabilities.os != "Windows PC" && egret.Capabilities.os != "Mac OS") { + window.setTimeout(function () { + video.width = 0; + }, 1000); + } + this.checkFullScreen(this._fullscreen); + }; + WebVideo.prototype.videoPlay = function () { + this.userPause = false; + if (this.waiting) { + this.userPlay = true; + return; + } + this.userPlay = false; + this.video.play(); + }; + WebVideo.prototype.checkFullScreen = function (playFullScreen) { + var video = this.video; + if (playFullScreen) { + if (video.parentElement == null) { + video.removeAttribute("webkit-playsinline"); + document.body.appendChild(video); + } + egret.stopTick(this.markDirty, this); + this.goFullscreen(); + } + else { + if (video.parentElement != null) { + video.parentElement.removeChild(video); + } + video.setAttribute("webkit-playsinline", "true"); + this.setFullScreenMonitor(false); + egret.startTick(this.markDirty, this); + if (egret.Capabilities.isMobile) { + this.video.currentTime = 0; + this.onVideoEnded(); + return; + } + } + this.videoPlay(); + }; + WebVideo.prototype.goFullscreen = function () { + var video = this.video; + var fullscreenType; + fullscreenType = wxapp.getPrefixStyleName('requestFullscreen', video); + if (!video[fullscreenType]) { + fullscreenType = wxapp.getPrefixStyleName('requestFullScreen', video); + if (!video[fullscreenType]) { + return true; + } + } + video.removeAttribute("webkit-playsinline"); + video[fullscreenType](); + this.setFullScreenMonitor(true); + return true; + }; + WebVideo.prototype.setFullScreenMonitor = function (use) { + var video = this.video; + if (use) { + video.addEventListener("mozfullscreenchange", this.screenChanged); + video.addEventListener("webkitfullscreenchange", this.screenChanged); + video.addEventListener("mozfullscreenerror", this.screenError); + video.addEventListener("webkitfullscreenerror", this.screenError); + } + else { + video.removeEventListener("mozfullscreenchange", this.screenChanged); + video.removeEventListener("webkitfullscreenchange", this.screenChanged); + video.removeEventListener("mozfullscreenerror", this.screenError); + video.removeEventListener("webkitfullscreenerror", this.screenError); + } + }; + WebVideo.prototype.screenError = function () { + egret.$error(3014); + }; + WebVideo.prototype.exitFullscreen = function () { + //退出全屏 + if (document['exitFullscreen']) { + document['exitFullscreen'](); + } + else if (document['msExitFullscreen']) { + document['msExitFullscreen'](); + } + else if (document['mozCancelFullScreen']) { + document['mozCancelFullScreen'](); + } + else if (document['oCancelFullScreen']) { + document['oCancelFullScreen'](); + } + else if (document['webkitExitFullscreen']) { + document['webkitExitFullscreen'](); + } + else { + } + }; + /** + * @private + * + */ + WebVideo.prototype.onVideoEnded = function () { + this.pause(); + this.isPlayed = false; + this.dispatchEventWith(egret.Event.ENDED); + }; + /** + * @private + * + */ + WebVideo.prototype.onVideoError = function () { + this.dispatchEventWith(egret.IOErrorEvent.IO_ERROR); + }; + /** + * @inheritDoc + */ + WebVideo.prototype.close = function () { + var _this = this; + this.closed = true; + this.video.removeEventListener("canplay", this.onVideoLoaded); + this.video.removeEventListener("error", function () { return _this.onVideoError(); }); + this.video.removeEventListener("ended", function () { return _this.onVideoEnded(); }); + this.pause(); + if (this.loaded == false && this.video) + this.video.src = ""; + if (this.video && this.video.parentElement) { + this.video.parentElement.removeChild(this.video); + this.video = null; + } + this.loaded = false; + }; + /** + * @inheritDoc + */ + WebVideo.prototype.pause = function () { + this.userPlay = false; + if (this.waiting) { + this.userPause = true; + return; + } + this.userPause = false; + egret.stopTick(this.markDirty, this); + }; + Object.defineProperty(WebVideo.prototype, "volume", { + /** + * @inheritDoc + */ + get: function () { + if (!this.video) + return 1; + return this.video.volume; + }, + /** + * @inheritDoc + */ + set: function (value) { + if (!this.video) + return; + this.video.volume = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WebVideo.prototype, "position", { + /** + * @inheritDoc + */ + get: function () { + if (!this.video) + return 0; + return this.video.currentTime; + }, + /** + * @inheritDoc + */ + set: function (value) { + if (!this.video) + return; + this.video.currentTime = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WebVideo.prototype, "fullscreen", { + /** + * @inheritDoc + */ + get: function () { + return this._fullscreen; + }, + /** + * @inheritDoc + */ + set: function (value) { + if (egret.Capabilities.isMobile) { + return; + } + this._fullscreen = !!value; + if (this.video && this.video.paused == false) { + this.checkFullScreen(this._fullscreen); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WebVideo.prototype, "bitmapData", { + /** + * @inheritDoc + */ + get: function () { + if (!this.video || !this.loaded) + return null; + if (!this._bitmapData) { + this.video.width = this.video.videoWidth; + this.video.height = this.video.videoHeight; + this._bitmapData = new egret.BitmapData(this.video); + this._bitmapData.$deleteSource = false; + } + return this._bitmapData; + }, + enumerable: true, + configurable: true + }); + WebVideo.prototype.loadPoster = function () { + var _this = this; + var poster = this.poster; + if (!poster) + return; + var imageLoader = new egret.ImageLoader(); + imageLoader.once(egret.Event.COMPLETE, function (e) { + var posterData = imageLoader.data; + _this.posterData = imageLoader.data; + _this.posterData.width = _this.getPlayWidth(); + _this.posterData.height = _this.getPlayHeight(); + }, this); + imageLoader.load(poster); + }; + /** + * @private + */ + WebVideo.prototype.$measureContentBounds = function (bounds) { + var bitmapData = this.bitmapData; + var posterData = this.posterData; + if (bitmapData) { + bounds.setTo(0, 0, this.getPlayWidth(), this.getPlayHeight()); + } + else if (posterData) { + bounds.setTo(0, 0, this.getPlayWidth(), this.getPlayHeight()); + } + else { + bounds.setEmpty(); + } + }; + WebVideo.prototype.getPlayWidth = function () { + if (!isNaN(this.widthSet)) { + return this.widthSet; + } + if (this.bitmapData) { + return this.bitmapData.width; + } + if (this.posterData) { + return this.posterData.width; + } + return NaN; + }; + WebVideo.prototype.getPlayHeight = function () { + if (!isNaN(this.heightSet)) { + return this.heightSet; + } + if (this.bitmapData) { + return this.bitmapData.height; + } + if (this.posterData) { + return this.posterData.height; + } + return NaN; + }; + /** + * @private + */ + WebVideo.prototype.$updateRenderNode = function () { + var node = this.$renderNode; + var bitmapData = this.bitmapData; + var posterData = this.posterData; + var width = this.getPlayWidth(); + var height = this.getPlayHeight(); + if ((!this.isPlayed || egret.Capabilities.isMobile) && posterData) { + node.image = posterData; + node.imageWidth = width; + node.imageHeight = height; + node.drawImage(0, 0, posterData.width, posterData.height, 0, 0, width, height); + } + else if (this.isPlayed && bitmapData) { + node.image = bitmapData; + node.imageWidth = bitmapData.width; + node.imageHeight = bitmapData.height; + egret.WebGLUtils.deleteWebGLTexture(bitmapData.webGLTexture); + bitmapData.webGLTexture = null; + node.drawImage(0, 0, bitmapData.width, bitmapData.height, 0, 0, width, height); + } + }; + WebVideo.prototype.markDirty = function () { + this.$renderDirty = true; + return true; + }; + /** + * @private + * 设置显示高度 + */ + WebVideo.prototype.$setHeight = function (value) { + this.heightSet = +value || 0; + _super.prototype.$setHeight.call(this, value); + }; + /** + * @private + * 设置显示宽度 + */ + WebVideo.prototype.$setWidth = function (value) { + this.widthSet = +value || 0; + _super.prototype.$setWidth.call(this, value); + }; + Object.defineProperty(WebVideo.prototype, "paused", { + get: function () { + if (this.video) { + return this.video.paused; + } + return true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WebVideo.prototype, "length", { + /** + * @inheritDoc + */ + get: function () { + if (this.video) { + return this.video.duration; + } + throw new Error("Video not loaded!"); + }, + enumerable: true, + configurable: true + }); + return WebVideo; + }(egret.DisplayObject)); + wxapp.WebVideo = WebVideo; + __reflect(WebVideo.prototype, "egret.wxapp.WebVideo", ["egret.Video", "egret.DisplayObject"]); + egret.Video = WebVideo; + })(wxapp = egret.wxapp || (egret.wxapp = {})); +})(egret || (egret = {})); +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var wxapp; + (function (wxapp) { + /** + * @private + */ + var WebHttpRequest = (function (_super) { + __extends(WebHttpRequest, _super); + /** + * @private + */ + function WebHttpRequest() { + var _this = _super.call(this) || this; + /** + * @private + */ + _this._url = ""; + _this._method = ""; + return _this; + } + Object.defineProperty(WebHttpRequest.prototype, "response", { + /** + * @private + * 本次请求返回的数据,数据类型根据responseType设置的值确定。 + */ + get: function () { + if (this._response) { + return this._response; + } + if (!this._xhr) { + return null; + } + if (this._xhr.response != undefined) { + return this._xhr.response; + } + if (this._responseType == "text") { + return this._xhr.responseText; + } + if (this._responseType == "arraybuffer" && /msie 9.0/i.test(navigator.userAgent)) { + var w = window; + return w.convertResponseBodyToText(this._xhr["responseBody"]); + } + if (this._responseType == "document") { + return this._xhr.responseXML; + } + /*if (this._xhr.responseXML) { + return this._xhr.responseXML; + } + if (this._xhr.responseText != undefined) { + return this._xhr.responseText; + }*/ + return null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WebHttpRequest.prototype, "responseType", { + /** + * @private + * 设置返回的数据格式,请使用 HttpResponseType 里定义的枚举值。设置非法的值或不设置,都将使用HttpResponseType.TEXT。 + */ + get: function () { + return this._responseType; + }, + set: function (value) { + this._responseType = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WebHttpRequest.prototype, "withCredentials", { + /** + * @private + * 表明在进行跨站(cross-site)的访问控制(Access-Control)请求时,是否使用认证信息(例如cookie或授权的header)。 默认为 false。(这个标志不会影响同站的请求) + */ + get: function () { + return this._withCredentials; + }, + set: function (value) { + this._withCredentials = value; + }, + enumerable: true, + configurable: true + }); + /** + * @private + * 初始化一个请求.注意,若在已经发出请求的对象上调用此方法,相当于立即调用abort(). + * @param url 该请求所要访问的URL该请求所要访问的URL + * @param method 请求所使用的HTTP方法, 请使用 HttpMethod 定义的枚举值. + */ + WebHttpRequest.prototype.open = function (url, method) { + if (method === void 0) { method = "GET"; } + this._url = url; + this._method = method; + if (this._xhr) { + this._xhr.abort(); + this._xhr = null; + } + this._xhr = new XMLHttpRequest(); + this._xhr.onreadystatechange = this.onReadyStateChange.bind(this); + this._xhr.onprogress = this.updateProgress.bind(this); + this._xhr.open(this._method, this._url, true); + }; + WebHttpRequest.prototype.readFileAsync = function () { + var self = this; + var onSuccessFunc = function (content) { + self._response = content; + self.dispatchEventWith(egret.Event.COMPLETE); + }; + var onErrorFunc = function () { + self.dispatchEventWith(egret.IOErrorEvent.IO_ERROR); + }; + var fs = wx.getFileSystemManager(); + if (self.responseType == "arraybuffer") { + //不传 encoding 默认返回二进制格式,传了 encoding:binary 反而返回 string 格式 + fs.readFile({ + filePath: self._url, + success: function (_a) { + var data = _a.data; + onSuccessFunc(data); + }, + fail: function () { + onErrorFunc(); + } + }); + } + else { + fs.readFile({ + filePath: self._url, + encoding: 'utf8', + success: function (_a) { + var data = _a.data; + onSuccessFunc(data); + }, + fail: function () { + onErrorFunc(); + } + }); + } + }; + /** + * @private + * 发送请求. + * @param data 需要发送的数据 + */ + WebHttpRequest.prototype.send = function (data) { + this._response = undefined; + if (!this.isNetUrl(this._url)) { + this.readFileAsync(); + } + else { + if (this._responseType != null) { + this._xhr.responseType = this._responseType; + } + if (this._withCredentials != null) { + this._xhr.withCredentials = this._withCredentials; + } + if (this.headerObj) { + for (var key in this.headerObj) { + this._xhr.setRequestHeader(key, this.headerObj[key]); + } + } + this._xhr.send(data); + } + }; + /** + * 是否是网络地址 + * @param url + * @returns {boolean} + */ + WebHttpRequest.prototype.isNetUrl = function (url) { + return url.indexOf("http://") != -1 || url.indexOf("HTTP://") != -1 || url.indexOf("https://") != -1 || url.indexOf("HTTPS://") != -1; + }; + /** + * @private + * 如果请求已经被发送,则立刻中止请求. + */ + WebHttpRequest.prototype.abort = function () { + if (this._xhr) { + this._xhr.abort(); + } + }; + /** + * @private + * 返回所有响应头信息(响应头名和值), 如果响应头还没接受,则返回"". + */ + WebHttpRequest.prototype.getAllResponseHeaders = function () { + if (!this._xhr) { + return null; + } + var result = this._xhr.getAllResponseHeaders(); + return result ? result : ""; + }; + /** + * @private + * 给指定的HTTP请求头赋值.在这之前,您必须确认已经调用 open() 方法打开了一个url. + * @param header 将要被赋值的请求头名称. + * @param value 给指定的请求头赋的值. + */ + WebHttpRequest.prototype.setRequestHeader = function (header, value) { + if (!this.headerObj) { + this.headerObj = {}; + } + this.headerObj[header] = value; + }; + /** + * @private + * 返回指定的响应头的值, 如果响应头还没被接受,或该响应头不存在,则返回"". + * @param header 要返回的响应头名称 + */ + WebHttpRequest.prototype.getResponseHeader = function (header) { + if (!this._xhr) { + return null; + } + var result = this._xhr.getResponseHeader(header); + return result ? result : ""; + }; + /** + * @private + */ + WebHttpRequest.prototype.onReadyStateChange = function () { + var xhr = this._xhr; + if (xhr.readyState == 4) { + var ioError_1 = (xhr.status >= 400 || xhr.status == 0); + var url_1 = this._url; + var self_1 = this; + window.setTimeout(function () { + if (ioError_1) { + if (true && !self_1.hasEventListener(egret.IOErrorEvent.IO_ERROR)) { + egret.$error(1011, url_1); + } + self_1.dispatchEventWith(egret.IOErrorEvent.IO_ERROR); + } + else { + self_1.dispatchEventWith(egret.Event.COMPLETE); + } + }, 0); + } + }; + /** + * @private + */ + WebHttpRequest.prototype.updateProgress = function (event) { + if (event.lengthComputable) { + egret.ProgressEvent.dispatchProgressEvent(this, egret.ProgressEvent.PROGRESS, event.loaded, event.total); + } + }; + return WebHttpRequest; + }(egret.EventDispatcher)); + wxapp.WebHttpRequest = WebHttpRequest; + __reflect(WebHttpRequest.prototype, "egret.wxapp.WebHttpRequest", ["egret.HttpRequest"]); + egret.HttpRequest = WebHttpRequest; + })(wxapp = egret.wxapp || (egret.wxapp = {})); +})(egret || (egret = {})); +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var wxapp; + (function (wxapp) { + var winURL = window["URL"] || window["webkitURL"]; + /** + * @private + * ImageLoader 类可用于加载图像(JPG、PNG 或 GIF)文件。使用 load() 方法来启动加载。被加载的图像对象数据将存储在 ImageLoader.data 属性上 。 + */ + var WebImageLoader = (function (_super) { + __extends(WebImageLoader, _super); + function WebImageLoader() { + var _this = _super !== null && _super.apply(this, arguments) || this; + /** + * @private + * 使用 load() 方法加载成功的 BitmapData 图像数据。 + */ + _this.data = null; + /** + * @private + * 当从其他站点加载一个图片时,指定是否启用跨域资源共享(CORS),默认值为null。 + * 可以设置为"anonymous","use-credentials"或null,设置为其他值将等同于"anonymous"。 + */ + _this._crossOrigin = null; + /** + * @private + * 标记crossOrigin有没有被设置过,设置过之后使用设置的属性 + */ + _this._hasCrossOriginSet = false; + /** + * @private + */ + _this.currentImage = null; + /** + * @private + */ + _this.request = null; + return _this; + } + Object.defineProperty(WebImageLoader.prototype, "crossOrigin", { + get: function () { + return this._crossOrigin; + }, + set: function (value) { + this._hasCrossOriginSet = true; + this._crossOrigin = value; + }, + enumerable: true, + configurable: true + }); + /** + * @private + * 启动一次图像加载。注意:若之前已经调用过加载请求,重新调用 load() 将终止先前的请求,并开始新的加载。 + * @param url 要加载的图像文件的地址。 + */ + WebImageLoader.prototype.load = function (url) { + this.loadImage(url); + }; + /** + * @private + */ + WebImageLoader.prototype.loadImage = function (src) { + var image = new Image(); + this.data = null; + this.currentImage = image; + if (this._hasCrossOriginSet) { + if (this._crossOrigin) { + image.crossOrigin = this._crossOrigin; + } + } + else { + if (WebImageLoader.crossOrigin) { + image.crossOrigin = WebImageLoader.crossOrigin; + } + } + /*else { + if (image.hasAttribute("crossOrigin")) {//兼容猎豹 + image.removeAttribute("crossOrigin"); + } + }*/ + image.onload = this.onImageComplete.bind(this); + image.onerror = this.onLoadError.bind(this); + image.src = src; + }; + /** + * @private + */ + WebImageLoader.prototype.onImageComplete = function (event) { + var image = this.getImage(event); + if (!image) { + return; + } + this.data = new egret.BitmapData(image); + var self = this; + window.setTimeout(function () { + self.dispatchEventWith(egret.Event.COMPLETE); + }, 0); + }; + /** + * @private + */ + WebImageLoader.prototype.onLoadError = function (event) { + var image = this.getImage(event); + if (!image) { + return; + } + this.dispatchIOError(image.src); + }; + WebImageLoader.prototype.dispatchIOError = function (url) { + var self = this; + window.setTimeout(function () { + if (true && !self.hasEventListener(egret.IOErrorEvent.IO_ERROR)) { + egret.$error(1011, url); + } + self.dispatchEventWith(egret.IOErrorEvent.IO_ERROR); + }, 0); + }; + /** + * @private + */ + WebImageLoader.prototype.getImage = function (event) { + var image = event.target; + var url = image.src; + image.onerror = null; + image.onload = null; + if (this.currentImage !== image) { + return null; + } + this.currentImage = null; + return image; + }; + /** + * @private + * 指定是否启用跨域资源共享,如果ImageLoader实例有设置过crossOrigin属性将使用设置的属性 + */ + WebImageLoader.crossOrigin = null; + return WebImageLoader; + }(egret.EventDispatcher)); + wxapp.WebImageLoader = WebImageLoader; + __reflect(WebImageLoader.prototype, "egret.wxapp.WebImageLoader", ["egret.ImageLoader"]); + egret.ImageLoader = WebImageLoader; + })(wxapp = egret.wxapp || (egret.wxapp = {})); +})(egret || (egret = {})); +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var wxapp; + (function (wxapp) { + /** + * @classdesc + * @extends egret.StageText + * @private + */ + var HTML5StageText = (function (_super) { + __extends(HTML5StageText, _super); + /** + * @private + */ + function HTML5StageText() { + var _this = _super.call(this) || this; + /** + * @private + */ + _this.textValue = ""; + _this.onKeyboardComplete = _this.onKeyboardComplete.bind(_this); + _this.onKeyboardInput = _this.onKeyboardInput.bind(_this); + return _this; + } + /** + * @private + * + * @param textfield + */ + HTML5StageText.prototype.$setTextField = function (textfield) { + this.$textfield = textfield; + return true; + }; + /** + * @private + * + */ + HTML5StageText.prototype.$addToStage = function () { + }; + /** + * @private + * + */ + HTML5StageText.prototype.$show = function () { + var info = { + defaultValue: this.$textfield.text, + multiple: this.$textfield.multiline, + confirmHold: true, + confirmType: 'done', + fail: function (res) { + console.log(res.errMsg); + } + }; + if (this.$textfield.maxChars) { + info.maxLength = this.$textfield.maxChars; + } + wx.showKeyboard(info); + wx.onKeyboardConfirm(this.onKeyboardComplete); + wx.onKeyboardComplete(this.onKeyboardComplete); + wx.onKeyboardInput(this.onKeyboardInput); + this.dispatchEvent(new egret.Event("focus")); + }; + HTML5StageText.prototype.onKeyboardInput = function (data) { + this.textValue = data.value; + egret.Event.dispatchEvent(this, "updateText", false); + }; + HTML5StageText.prototype.onKeyboardComplete = function (res) { + this.$textfield.text = res.value; + this.$hide(); + }; + /** + * @private + */ + HTML5StageText.prototype.$hide = function () { + wx.offKeyboardComplete(); + wx.offKeyboardConfirm(); + wx.offKeyboardInput(); + wx.hideKeyboard({}); + this.dispatchEvent(new egret.Event("blur")); + }; + /** + * @private + * + * @returns + */ + HTML5StageText.prototype.$getText = function () { + if (!this.textValue) { + this.textValue = ""; + } + return this.textValue; + }; + /** + * @private + * + * @param value + */ + HTML5StageText.prototype.$setText = function (value) { + this.textValue = value; + // this.resetText(); + return true; + }; + /** + * @private + */ + HTML5StageText.prototype.$setColor = function (value) { + return true; + }; + HTML5StageText.prototype.$onBlur = function () { + }; + /** + * @private + * + */ + HTML5StageText.prototype.$removeFromStage = function () { + }; + /** + * 修改位置 + * @private + */ + HTML5StageText.prototype.$resetStageText = function () { + }; + return HTML5StageText; + }(egret.EventDispatcher)); + wxapp.HTML5StageText = HTML5StageText; + __reflect(HTML5StageText.prototype, "egret.wxapp.HTML5StageText", ["egret.StageText"]); + egret.StageText = HTML5StageText; + })(wxapp = egret.wxapp || (egret.wxapp = {})); +})(egret || (egret = {})); +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var wxapp; + (function (wxapp) { + /** + * @private + */ + var context = null; + /** + * @private + */ + var fontCache = {}; + /** + * 测量文本在指定样式下的宽度。 + * @param text 要测量的文本内容。 + * @param fontFamily 字体名称 + * @param fontSize 字体大小 + * @param bold 是否粗体 + * @param italic 是否斜体 + */ + function measureText(text, fontFamily, fontSize, bold, italic) { + if (!context) { + createContext(); + } + var font = ""; + if (italic) + font += "italic "; + if (bold) + font += "bold "; + font += (fontSize || 12) + "px "; + font += (fontFamily || "Arial"); + context.font = font; + return context.measureText(text).width; + } + /** + * @private + */ + function createContext() { + context = egret.sys.canvasHitTestBuffer.context; + context.textAlign = "left"; + context.textBaseline = "middle"; + } + egret.sys.measureText = measureText; + })(wxapp = egret.wxapp || (egret.wxapp = {})); +})(egret || (egret = {})); +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var wxapp; + (function (wxapp) { + /** + * 创建一个canvas。 + */ + function createCanvas(width, height) { + var canvas = document.createElement("canvas"); + if (!isNaN(width) && !isNaN(height)) { + canvas.width = width; + canvas.height = height; + } + var context = canvas.getContext("2d"); + if (context["imageSmoothingEnabled"] === undefined) { + var keys = ["webkitImageSmoothingEnabled", "mozImageSmoothingEnabled", "msImageSmoothingEnabled"]; + var key_1; + for (var i = keys.length - 1; i >= 0; i--) { + key_1 = keys[i]; + if (context[key_1] !== void 0) { + break; + } + } + try { + Object.defineProperty(context, "imageSmoothingEnabled", { + get: function () { + return this[key_1]; + }, + set: function (value) { + this[key_1] = value; + } + }); + } + catch (e) { + context["imageSmoothingEnabled"] = context[key_1]; + } + } + return canvas; + } + var sharedCanvas; + /** + * @private + * Canvas2D渲染缓冲 + */ + var CanvasRenderBuffer = (function () { + function CanvasRenderBuffer(width, height, root) { + if (root) { + if (egret.wxgame.isSubContext) { + this.surface = window["sharedCanvas"]; + } + else { + this.surface = window["canvas"]; + } + } + else { + this.surface = createCanvas(width, height); + } + this.context = this.surface.getContext("2d"); + if (this.context) { + this.context.$offsetX = 0; + this.context.$offsetY = 0; + } + } + Object.defineProperty(CanvasRenderBuffer.prototype, "width", { + /** + * 渲染缓冲的宽度,以像素为单位。 + * @readOnly + */ + get: function () { + return this.surface.width; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CanvasRenderBuffer.prototype, "height", { + /** + * 渲染缓冲的高度,以像素为单位。 + * @readOnly + */ + get: function () { + return this.surface.height; + }, + enumerable: true, + configurable: true + }); + /** + * 改变渲染缓冲的大小并清空缓冲区 + * @param width 改变后的宽 + * @param height 改变后的高 + * @param useMaxSize 若传入true,则将改变后的尺寸与已有尺寸对比,保留较大的尺寸。 + */ + CanvasRenderBuffer.prototype.resize = function (width, height, useMaxSize) { + var surface = this.surface; + if (surface == window["sharedCanvas"]) { + return; + } + if (useMaxSize) { + var change = false; + if (surface.width < width) { + surface.width = width; + change = true; + } + if (surface.height < height) { + surface.height = height; + change = true; + } + //尺寸没有变化时,将绘制属性重置 + if (!change) { + this.context.globalCompositeOperation = "source-over"; + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.globalAlpha = 1; + } + } + else { + if (surface.width != width) { + surface.width = width; + } + if (surface.height != height) { + surface.height = height; + } + } + this.clear(); + }; + /** + * 获取指定区域的像素 + */ + CanvasRenderBuffer.prototype.getPixels = function (x, y, width, height) { + if (width === void 0) { width = 1; } + if (height === void 0) { height = 1; } + return this.context.getImageData(x, y, width, height).data; + }; + /** + * 转换成base64字符串,如果图片(或者包含的图片)跨域,则返回null + * @param type 转换的类型,如: "image/png","image/jpeg" + */ + CanvasRenderBuffer.prototype.toDataURL = function (type, encoderOptions) { + return this.surface.toDataURL(type, encoderOptions); + }; + /** + * 清空缓冲区数据 + */ + CanvasRenderBuffer.prototype.clear = function () { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.surface.width, this.surface.height); + }; + /** + * 销毁绘制对象 + */ + CanvasRenderBuffer.prototype.destroy = function () { + this.surface.width = this.surface.height = 0; + }; + return CanvasRenderBuffer; + }()); + wxapp.CanvasRenderBuffer = CanvasRenderBuffer; + __reflect(CanvasRenderBuffer.prototype, "egret.wxapp.CanvasRenderBuffer", ["egret.sys.RenderBuffer"]); + })(wxapp = egret.wxapp || (egret.wxapp = {})); +})(egret || (egret = {})); +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided this the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var wxapp; + (function (wxapp) { + /** + * @private + */ + var WebTouchHandler = (function (_super) { + __extends(WebTouchHandler, _super); + /** + * @private + */ + function WebTouchHandler(stage, canvas) { + var _this = _super.call(this) || this; + /** + * @private + */ + _this.onTouchBegin = function (event) { + var location = _this.getLocation(event); + _this.touch.onTouchBegin(location.x, location.y, event.identifier); + }; + /** + * @private + */ + _this.onTouchMove = function (event) { + var location = _this.getLocation(event); + _this.touch.onTouchMove(location.x, location.y, event.identifier); + }; + /** + * @private + */ + _this.onTouchEnd = function (event) { + var location = _this.getLocation(event); + _this.touch.onTouchEnd(location.x, location.y, event.identifier); + }; + /** + * @private + */ + _this.scaleX = 1; + /** + * @private + */ + _this.scaleY = 1; + /** + * @private + */ + _this.rotation = 0; + _this.canvas = canvas; + _this.touch = new egret.sys.TouchHandler(stage); + _this.addTouchListener(); + return _this; + } + /** + * @private + * + */ + WebTouchHandler.prototype.addTouchListener = function () { + var self = this; + if (egret.wxgame.isSubContext) { + wx.onTouchStart(function (event) { + var l = event.changedTouches.length; + for (var i = 0; i < l; i++) { + self.onTouchBegin(event.changedTouches[i]); + } + }); + wx.onTouchMove(function (event) { + var l = event.changedTouches.length; + for (var i = 0; i < l; i++) { + self.onTouchMove(event.changedTouches[i]); + } + }); + wx.onTouchEnd(function (event) { + var l = event.changedTouches.length; + for (var i = 0; i < l; i++) { + self.onTouchEnd(event.changedTouches[i]); + } + }); + wx.onTouchCancel(function (event) { + var l = event.changedTouches.length; + for (var i = 0; i < l; i++) { + self.onTouchEnd(event.changedTouches[i]); + } + }); + } + else { + self.canvas.addEventListener("touchstart", function (event) { + var l = event.changedTouches.length; + for (var i = 0; i < l; i++) { + self.onTouchBegin(event.changedTouches[i]); + } + self.prevent(event); + }, false); + self.canvas.addEventListener("touchmove", function (event) { + var l = event.changedTouches.length; + for (var i = 0; i < l; i++) { + self.onTouchMove(event.changedTouches[i]); + } + self.prevent(event); + }, false); + self.canvas.addEventListener("touchend", function (event) { + var l = event.changedTouches.length; + for (var i = 0; i < l; i++) { + self.onTouchEnd(event.changedTouches[i]); + } + self.prevent(event); + }, false); + self.canvas.addEventListener("touchcancel", function (event) { + var l = event.changedTouches.length; + for (var i = 0; i < l; i++) { + self.onTouchEnd(event.changedTouches[i]); + } + self.prevent(event); + }, false); + } + }; + /** + * @private + */ + WebTouchHandler.prototype.prevent = function (event) { + event.stopPropagation(); + if (event["isScroll"] != true && !this.canvas['userTyping']) { + event.preventDefault(); + } + }; + /** + * @private + */ + WebTouchHandler.prototype.getLocation = function (event) { + // event.identifier = +event.identifier || 0; wxapp 内核该属性只读 + var doc = document.documentElement; + var box = this.canvas.getBoundingClientRect(); + var left = box.left; + var top = box.top; + var x = event.pageX - left, newx = x; + var y = event.pageY - top, newy = y; + if (this.rotation == 90) { + newx = y; + newy = box.width - x; + } + else if (this.rotation == -90) { + newx = box.height - y; + newy = x; + } + newx = newx / this.scaleX; + newy = newy / this.scaleY; + return egret.$TempPoint.setTo(Math.round(newx), Math.round(newy)); + }; + /** + * @private + * 更新屏幕当前的缩放比例,用于计算准确的点击位置。 + * @param scaleX 水平方向的缩放比例。 + * @param scaleY 垂直方向的缩放比例。 + */ + WebTouchHandler.prototype.updateScaleMode = function (scaleX, scaleY, rotation) { + this.scaleX = scaleX; + this.scaleY = scaleY; + this.rotation = rotation; + }; + /** + * @private + * 更新同时触摸点的数量 + */ + WebTouchHandler.prototype.$updateMaxTouches = function () { + this.touch.$initMaxTouches(); + }; + return WebTouchHandler; + }(egret.HashObject)); + wxapp.WebTouchHandler = WebTouchHandler; + __reflect(WebTouchHandler.prototype, "egret.wxapp.WebTouchHandler"); + })(wxapp = egret.wxapp || (egret.wxapp = {})); +})(egret || (egret = {})); +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var wxapp; + (function (wxapp) { + /** + * @private + */ + wxapp.WebLifeCycleHandler = function (context) { + var handleVisibilityChange = function () { + if (!document[hidden]) { + context.resume(); + } + else { + context.pause(); + } + }; + window.addEventListener("focus", context.resume, false); + window.addEventListener("blur", context.pause, false); + var hidden, visibilityChange; + if (typeof document.hidden !== "undefined") { + hidden = "hidden"; + visibilityChange = "visibilitychange"; + } + else if (typeof document["mozHidden"] !== "undefined") { + hidden = "mozHidden"; + visibilityChange = "mozvisibilitychange"; + } + else if (typeof document["msHidden"] !== "undefined") { + hidden = "msHidden"; + visibilityChange = "msvisibilitychange"; + } + else if (typeof document["webkitHidden"] !== "undefined") { + hidden = "webkitHidden"; + visibilityChange = "webkitvisibilitychange"; + } + else if (typeof document["oHidden"] !== "undefined") { + hidden = "oHidden"; + visibilityChange = "ovisibilitychange"; + } + if ("onpageshow" in window && "onpagehide" in window) { + window.addEventListener("pageshow", context.resume, false); + window.addEventListener("pagehide", context.pause, false); + } + if (hidden && visibilityChange) { + document.addEventListener(visibilityChange, handleVisibilityChange, false); + } + var ua = navigator.userAgent; + var isWX = /micromessenger/gi.test(ua); + var isQQBrowser = /mqq/ig.test(ua); + var isQQ = /mobile.*qq/gi.test(ua); + if (isQQ || isWX) { + isQQBrowser = false; + } + if (isQQBrowser) { + var browser = window["browser"] || {}; + browser.execWebFn = browser.execWebFn || {}; + browser.execWebFn.postX5GamePlayerMessage = function (event) { + var eventType = event.type; + if (eventType == "app_enter_background") { + context.pause(); + } + else if (eventType == "app_enter_foreground") { + context.resume(); + } + }; + window["browser"] = browser; + } + }; + })(wxapp = egret.wxapp || (egret.wxapp = {})); +})(egret || (egret = {})); +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var wxapp; + (function (wxapp) { + /** + * @private + */ + var AudioType = (function () { + function AudioType() { + } + /** + * @private + */ + AudioType.WEB_AUDIO = 2; + /** + * @private + */ + AudioType.HTML5_AUDIO = 3; + return AudioType; + }()); + wxapp.AudioType = AudioType; + __reflect(AudioType.prototype, "egret.wxapp.AudioType"); + /** + * @private + */ + var SystemOSType = (function () { + function SystemOSType() { + } + /** + * @private + */ + SystemOSType.WPHONE = 1; + /** + * @private + */ + SystemOSType.IOS = 2; + /** + * @private + */ + SystemOSType.ADNROID = 3; + return SystemOSType; + }()); + wxapp.SystemOSType = SystemOSType; + __reflect(SystemOSType.prototype, "egret.wxapp.SystemOSType"); + /** + * html5兼容性配置 + * @private + */ + var Html5Capatibility = (function (_super) { + __extends(Html5Capatibility, _super); + /** + * @private + */ + function Html5Capatibility() { + return _super.call(this) || this; + } + /** + * @private + * + */ + Html5Capatibility.$init = function () { + var ua = navigator.userAgent.toLowerCase(); + Html5Capatibility.ua = ua; + egret.Capabilities.$isMobile = (ua.indexOf('mobile') != -1 || ua.indexOf('android') != -1); + Html5Capatibility._canUseBlob = false; + var canUseWebAudio = window["AudioContext"] || window["webkitAudioContext"] || window["mozAudioContext"]; + if (canUseWebAudio) { + try { + //防止某些chrome版本创建异常问题 + wxapp.WebAudioDecode.ctx = new (window["AudioContext"] || window["webkitAudioContext"] || window["mozAudioContext"])(); + } + catch (e) { + canUseWebAudio = false; + } + } + var audioType = Html5Capatibility._audioType; + var checkAudioType; + if ((audioType == AudioType.WEB_AUDIO && canUseWebAudio) || audioType == AudioType.HTML5_AUDIO) { + checkAudioType = false; + Html5Capatibility.setAudioType(audioType); + } + else { + checkAudioType = true; + Html5Capatibility.setAudioType(AudioType.HTML5_AUDIO); + } + if (ua.indexOf("windows phone") >= 0) { + Html5Capatibility._System_OS = SystemOSType.WPHONE; + egret.Capabilities.$os = "Windows Phone"; + } + else if (ua.indexOf("android") >= 0) { + egret.Capabilities.$os = "Android"; + Html5Capatibility._System_OS = SystemOSType.ADNROID; + if (checkAudioType && canUseWebAudio) { + Html5Capatibility.setAudioType(AudioType.WEB_AUDIO); + } + } + else if (ua.indexOf("iphone") >= 0 || ua.indexOf("ipad") >= 0 || ua.indexOf("ipod") >= 0) { + egret.Capabilities.$os = "iOS"; + Html5Capatibility._System_OS = SystemOSType.IOS; + if (Html5Capatibility.getIOSVersion() >= 7) { + Html5Capatibility._canUseBlob = true; + if (checkAudioType && canUseWebAudio) { + Html5Capatibility.setAudioType(AudioType.WEB_AUDIO); + } + } + } + else { + if (ua.indexOf("windows nt") != -1) { + egret.Capabilities.$os = "Windows PC"; + } + else if (ua.indexOf("mac os") != -1) { + egret.Capabilities.$os = "Mac OS"; + } + } + var winURL = window["URL"] || window["webkitURL"]; + if (!winURL) { + Html5Capatibility._canUseBlob = false; + } + if (ua.indexOf("egretnative") >= 0) { + Html5Capatibility.setAudioType(AudioType.HTML5_AUDIO); + Html5Capatibility._canUseBlob = true; + } + egret.Sound = Html5Capatibility._AudioClass; + }; + Html5Capatibility.setAudioType = function (type) { + Html5Capatibility._audioType = type; + switch (type) { + case AudioType.WEB_AUDIO: + Html5Capatibility._AudioClass = egret.wxapp.WebAudioSound; + break; + case AudioType.HTML5_AUDIO: + Html5Capatibility._AudioClass = egret.wxapp.HtmlSound; + break; + } + }; + /** + * @private + * 获取ios版本 + * @returns {string} + */ + Html5Capatibility.getIOSVersion = function () { + var value = Html5Capatibility.ua.toLowerCase().match(/cpu [^\d]*\d.*like mac os x/)[0]; + return parseInt(value.match(/\d+(_\d)*/)[0]) || 0; + }; + /** + * @private + * + */ + Html5Capatibility.checkHtml5Support = function () { + var language = (navigator.language || navigator["browserLanguage"]).toLowerCase(); + var strings = language.split("-"); + if (strings.length > 1) { + strings[1] = strings[1].toUpperCase(); + } + egret.Capabilities.$language = strings.join("-"); + }; + //当前浏览器版本是否支持blob + Html5Capatibility._canUseBlob = false; + //当前浏览器版本是否支持webaudio + Html5Capatibility._audioType = 0; + /** + * @private + */ + Html5Capatibility._System_OS = 0; + /** + * @private + */ + Html5Capatibility.ua = ""; + return Html5Capatibility; + }(egret.HashObject)); + wxapp.Html5Capatibility = Html5Capatibility; + __reflect(Html5Capatibility.prototype, "egret.wxapp.Html5Capatibility"); + /** + * @private + */ + var currentPrefix = null; + /** + * @private + */ + function getPrefixStyleName(name, element) { + var header = ""; + if (element != null) { + header = getPrefix(name, element); + } + else { + if (currentPrefix == null) { + var tempStyle = document.createElement('div').style; + currentPrefix = getPrefix("transform", tempStyle); + } + header = currentPrefix; + } + if (header == "") { + return name; + } + return header + name.charAt(0).toUpperCase() + name.substring(1, name.length); + } + wxapp.getPrefixStyleName = getPrefixStyleName; + /** + * @private + */ + function getPrefix(name, element) { + if (name in element) { + return ""; + } + name = name.charAt(0).toUpperCase() + name.substring(1, name.length); + var transArr = ["webkit", "ms", "Moz", "O"]; + for (var i = 0; i < transArr.length; i++) { + var tempStyle = transArr[i] + name; + if (tempStyle in element) { + return transArr[i]; + } + } + return ""; + } + wxapp.getPrefix = getPrefix; + })(wxapp = egret.wxapp || (egret.wxapp = {})); +})(egret || (egret = {})); +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var wxgame; + (function (wxgame) { + /** + * 微信小游戏支持库版本号 + */ + wxgame.version = "1.0.10"; + /** + * 运行环境是否为子域 + */ + wxgame.isSubContext = false; + })(wxgame = egret.wxgame || (egret.wxgame = {})); +})(egret || (egret = {})); +(function (egret) { + var wxapp; + (function (wxapp) { + /** + * @private + * 刷新所有Egret播放器的显示区域尺寸。仅当使用外部JavaScript代码动态修改了Egret容器大小时,需要手动调用此方法刷新显示区域。 + * 当网页尺寸发生改变时此方法会自动被调用。 + */ + function updateAllScreens() { + if (!isRunning) { + return; + } + // let containerList = document.querySelectorAll(".egret-player"); + // let length = containerList.length; + // for (let i = 0; i < length; i++) { + // let container = containerList[i]; + // let player = container["egret-player"]; + window['player'].updateScreenSize(); + // } + } + var isRunning = false; + /** + * @private + * 网页加载完成,实例化页面中定义的Egret标签 + */ + function runEgret(options) { + if (isRunning) { + return; + } + isRunning = true; + if (!options) { + options = {}; + } + wxapp.Html5Capatibility._audioType = options.audioType; + wxapp.Html5Capatibility.$init(); + // WebGL上下文参数自定义 + if (options.renderMode == "webgl") { + // WebGL抗锯齿默认关闭,提升PC及某些平台性能 + var antialias = options.antialias; + wxapp.WebGLRenderContext.antialias = !!antialias; + // WebGLRenderContext.antialias = (typeof antialias == undefined) ? true : antialias; + } + egret.sys.CanvasRenderBuffer = wxapp.CanvasRenderBuffer; + setRenderMode(options.renderMode); + var canvasScaleFactor; + if (options.canvasScaleFactor) { + canvasScaleFactor = options.canvasScaleFactor; + } + else if (options.calculateCanvasScaleFactor) { + canvasScaleFactor = options.calculateCanvasScaleFactor(egret.sys.canvasHitTestBuffer.context); + } + else { + //based on : https://github.com/jondavidjohn/hidpi-canvas-polyfill + var context = egret.sys.canvasHitTestBuffer.context; + var backingStore = context.backingStorePixelRatio || + context.webkitBackingStorePixelRatio || + context.mozBackingStorePixelRatio || + context.msBackingStorePixelRatio || + context.oBackingStorePixelRatio || + context.backingStorePixelRatio || 1; + canvasScaleFactor = (window.devicePixelRatio || 1) / backingStore; + } + egret.sys.DisplayList.$canvasScaleFactor = canvasScaleFactor; + var ticker = egret.ticker; + startTicker(ticker); + if (options.screenAdapter) { + egret.sys.screenAdapter = options.screenAdapter; + } + else if (!egret.sys.screenAdapter) { + egret.sys.screenAdapter = new egret.sys.DefaultScreenAdapter(); + } + // let list = document.querySelectorAll(".egret-player"); + // let length = list.length; + // for (let i = 0; i < length; i++) { + // let container = list[i]; + // let player = new WebPlayer(container, options); + // container["egret-player"] = player; + // } + var container = {}; + var player = new wxapp.WebPlayer(container, options); + window['player'] = player; + window.addEventListener("resize", function () { + if (isNaN(resizeTimer)) { + resizeTimer = window.setTimeout(doResize, 300); + } + }); + } + /** + * 设置渲染模式。"auto","webgl","canvas" + * @param renderMode + */ + function setRenderMode(renderMode) { + if (!egret.wxgame.isSubContext) { + egret.Capabilities.$renderMode = "webgl"; + egret.sys.RenderBuffer = wxapp.WebGLRenderBuffer; + egret.sys.systemRenderer = new wxapp.WebGLRenderer(); + egret.sys.canvasRenderer = new egret.CanvasRenderer(); + egret.sys.customHitTestBuffer = new wxapp.WebGLRenderBuffer(3, 3); + egret.sys.canvasHitTestBuffer = new wxapp.CanvasRenderBuffer(3, 3); + } + else { + egret.Capabilities.$renderMode = "canvas"; + egret.sys.RenderBuffer = wxapp.CanvasRenderBuffer; + egret.sys.systemRenderer = new egret.CanvasRenderer(); + egret.sys.canvasRenderer = egret.sys.systemRenderer; + egret.sys.customHitTestBuffer = new wxapp.CanvasRenderBuffer(3, 3); + egret.sys.canvasHitTestBuffer = egret.sys.customHitTestBuffer; + } + } + /** + * @private + * 启动心跳计时器。 + */ + function startTicker(ticker) { + var requestAnimationFrame = window["requestAnimationFrame"] || + window["webkitRequestAnimationFrame"] || + window["mozRequestAnimationFrame"] || + window["oRequestAnimationFrame"] || + window["msRequestAnimationFrame"]; + if (!requestAnimationFrame) { + requestAnimationFrame = function (callback) { + return window.setTimeout(callback, 1000 / 60); + }; + } + requestAnimationFrame(onTick); + function onTick() { + ticker.update(); + requestAnimationFrame(onTick); + } + } + //覆盖原生的isNaN()方法实现,在不同浏览器上有2~10倍性能提升。 + window["isNaN"] = function (value) { + value = +value; + return value !== value; + }; + egret.runEgret = runEgret; + egret.updateAllScreens = updateAllScreens; + var resizeTimer = NaN; + function doResize() { + resizeTimer = NaN; + egret.updateAllScreens(); + } + })(wxapp = egret.wxapp || (egret.wxapp = {})); +})(egret || (egret = {})); +if (true) { + var language = navigator.language || navigator["browserLanguage"] || "en_US"; + language = language.replace("-", "_"); + if (language in egret.$locale_strings) + egret.$language = language; +} +////////////////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2014-present, Egret Technology. +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the Egret nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS +// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +////////////////////////////////////////////////////////////////////////////////////// + +(function (egret) { + var wxapp; + (function (wxapp) { + /** + * @private + */ + var WebCapability = (function () { + function WebCapability() { + } + /** + * @private + * 检测系统属性 + */ + WebCapability.detect = function () { + var capabilities = egret.Capabilities; + var ua = navigator.userAgent.toLowerCase(); + capabilities.$isMobile = (ua.indexOf('mobile') != -1 || ua.indexOf('android') != -1); + if (capabilities.$isMobile) { + if (ua.indexOf("windows") < 0 && (ua.indexOf("iphone") != -1 || ua.indexOf("ipad") != -1 || ua.indexOf("ipod") != -1)) { + capabilities.$os = "iOS"; + } + else if (ua.indexOf("android") != -1 && ua.indexOf("linux") != -1) { + capabilities.$os = "Android"; + } + else if (ua.indexOf("windows") != -1) { + capabilities.$os = "Windows Phone"; + } + } + else { + if (ua.indexOf("windows nt") != -1) { + capabilities.$os = "Windows PC"; + } + else if (ua.indexOf("mac os") != -1) { + capabilities.$os = "Mac OS"; + } + } + var language = (navigator.language || navigator["browserLanguage"]).toLowerCase(); + var strings = language.split("-"); + if (strings.length > 1) { + strings[1] = strings[1].toUpperCase(); + } + capabilities.$language = strings.join("-"); + WebCapability.injectUIntFixOnIE9(); + }; + WebCapability.injectUIntFixOnIE9 = function () { + if (/msie 9.0/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) { + var IEBinaryToArray_ByteStr_Script = "\r\n" + + "