diff --git a/3d-bin-packing/3d-bin-packing-tests.ts b/3d-bin-packing/3d-bin-packing-tests.ts new file mode 100644 index 0000000000..4562c26ce9 --- /dev/null +++ b/3d-bin-packing/3d-bin-packing-tests.ts @@ -0,0 +1,52 @@ +/// + +import packer = require("3d-bin-packing"); +import samchon = require("samchon-framework"); + +function main(): void +{ + /////////////////////////// + // CONSTRUCT OBJECTS + /////////////////////////// + let wrapperArray: bws.packer.WrapperArray = new packer.WrapperArray(); + let instanceArray: bws.packer.InstanceArray = new packer.InstanceArray(); + + // Wrappers + wrapperArray.push + ( + new packer.Wrapper("Large", 1000, 40, 40, 15, 0), + new packer.Wrapper("Medium", 700, 20, 20, 10, 0), + new packer.Wrapper("Small", 500, 15, 15, 8, 0) + ); + + /////// + // Each Instance is repeated #15 + /////// + instanceArray.insert(instanceArray.end(), 15, new packer.Product("Eraser", 1, 2, 5)); + instanceArray.insert(instanceArray.end(), 15, new packer.Product("Book", 15, 30, 3)); + instanceArray.insert(instanceArray.end(), 15, new packer.Product("Drink", 3, 3, 10)); + instanceArray.insert(instanceArray.end(), 15, new packer.Product("Umbrella", 5, 5, 20)); + + // Wrappers also can be packed into another Wrapper. + instanceArray.insert(instanceArray.end(), 15, new packer.Wrapper("Notebook-Box", 2000, 30, 40, 4, 2)); + instanceArray.insert(instanceArray.end(), 15, new packer.Wrapper("Tablet-Box", 2500, 20, 28, 2, 0)); + + /////////////////////////// + // BEGINS PACKING + /////////////////////////// + // CONSTRUCT PACKER + let my_packer: bws.packer.Packer = new packer.Packer(wrapperArray, instanceArray); + + /////// + // PACK (OPTIMIZE) + let result: bws.packer.WrapperArray = my_packer.optimize(); + /////// + + /////////////////////////// + // TRACE PACKING RESULT + /////////////////////////// + let xml: samchon.library.XML = result.toXML(); + console.log(xml.toString()); +} + +main(); \ No newline at end of file diff --git a/3d-bin-packing/3d-bin-packing.d.ts b/3d-bin-packing/3d-bin-packing.d.ts new file mode 100644 index 0000000000..afd3af6050 --- /dev/null +++ b/3d-bin-packing/3d-bin-packing.d.ts @@ -0,0 +1,1500 @@ +// Type definitions for 3d-bin-packing +// Project: https://github.com/betterwaysystems/packer +// Definitions by: Jeongho Nam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// +/// +/// + +declare module "3d-bin-packing" +{ + export = bws.packer; +} +declare var ReactDataGrid: typeof AdazzleReactDataGrid.ReactDataGrid; +declare namespace boxologic { + /** + *

An abstract instance of boxologic.

+ * + *

{@link st_Instance} represents a physical, tangible instance of 3-dimension.

+ * + * @author Jeongho Nam + */ + abstract class Instance { + /** + * Width of the tangible instance, length on the X-axis in 3D. + */ + width: number; + /** + * Height of the tangible instance, length on the Y-axis in 3D. + */ + height: number; + /** + * Length of the tangible instance, length on the Z-axis in 3D. + */ + length: number; + /** + * Width considering layout placement. + */ + layout_width: number; + /** + * Height considering layout placement. + */ + layout_height: number; + /** + * Length considering layout placement. + */ + layout_length: number; + /** + * Volume, Width x Height x Length. + */ + volume: number; + /** + * Construct from size members. + * + * @param width Width, length on the X-axis in 3D. + * @param height Height, length on the Y-axis in 3D. + * @param length Length, length on the Z-axis in 3D. + */ + constructor(width: number, height: number, length: number); + } +} +declare namespace bws.packer { + /** + * @brief Packer, a solver of 3d bin packing with multiple wrappers. + * + * @details + *

Packer is a facade class supporting packing operations in user side. You can solve a packing problem + * by constructing Packer class with {@link WrapperArray wrappers} and {@link InstanceArray instances} to + * pack and executing {@link optimize Packer.optimize()} method.

+ * + *

In background side, deducting packing solution, those algorithms are used.

+ * + * + * @author Jeongho Nam + */ + class Packer extends samchon.protocol.Entity { + /** + * Candidate wrappers who can contain instances. + */ + protected wrapperArray: WrapperArray; + /** + * Instances trying to pack into the wrapper. + */ + protected instanceArray: InstanceArray; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from members. + * + * @param wrapperArray Candidate wrappers who can contain instances. + * @param instanceArray Instances to be packed into some wrappers. + */ + constructor(wrapperArray: WrapperArray, instanceArray: InstanceArray); + /** + * @inheritdoc + */ + construct(xml: samchon.library.XML): void; + /** + * Get wrapperArray. + */ + getWrapperArray(): WrapperArray; + /** + * Get instanceArray. + */ + getInstanceArray(): InstanceArray; + /** + *

Deduct + * + */ + optimize(): WrapperArray; + /** + * @brief Initialize sequence list (gene_array). + * + * @details + *

Deducts initial sequence list by such assumption:

+ * + *
    + *
  • Cost of larger wrapper is less than smaller one, within framework of price per volume unit.
  • + *
      + *
    • Wrapper Larger: (price: $1,000, volume: 100cm^3 -> price per volume unit: $10 / cm^3)
    • + *
    • Wrapper Smaller: (price: $700, volume: 50cm^3 -> price per volume unit: $14 / cm^3)
    • + *
    • Larger's cost is less than Smaller, within framework of price per volume unit
    • + *
    + *
+ * + *

Method {@link initGenes initGenes()} constructs {@link WrapperGroup WrapperGroups} corresponding + * with the {@link wrapperArray} and allocates {@link instanceArray instances} to a {@link WrapperGroup}, + * has the smallest cost between containbles.

+ * + *

After executing packing solution by {@link WrapperGroup.optimize WrapperGroup.optimize()}, trying to + * {@link repack re-pack} each {@link WrapperGroup} to another type of {@link Wrapper}, deducts the best + * solution between them. It's the initial sequence list of genetic algorithm.

+ * + * @return Initial sequence list. + */ + protected initGenes(): GAWrapperArray; + /** + * Try to repack each wrappers to another type. + * + * @param $wrappers Wrappers to repack. + * @return Re-packed wrappers. + */ + protected repack($wrappers: WrapperArray): WrapperArray; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + toXML(): samchon.library.XML; + } +} +declare namespace flex { + class TabNavigator extends React.Component { + render(): JSX.Element; + private handle_change(index, event); + } + class NavigatorContent extends React.Component { + render(): JSX.Element; + } + interface TabNavigatorProps extends React.Props { + selectedIndex?: number; + style?: React.CSSProperties; + } + interface NavigatorContentProps extends React.Props { + label: string; + } +} +declare namespace boxologic { + /** + * A box, trying to pack into a {@link Pallet}. + * + * @author Bill Knechtel,
+ * Migrated and Refactored by Jeongho Nam + */ + class Box extends Instance { + /** + * Coordinate-X of the box placement in a {@link Pallet}. + */ + cox: number; + /** + * Coordinate-Y of the box placement in a {@link Pallet}. + */ + coy: number; + /** + * Coordinate-Z of the box placement in a {@link Pallet}. + */ + coz: number; + /** + * Whether the {@link Box} is packed into a {@link Pallet}. + */ + is_packed: boolean; + overlapped_boxes: std.HashSet; + /** + * Construct from an instance. + * + * @param instance An instance adapts with. + */ + constructor(instance: bws.packer.Instance); + hit_test(obj: Box): boolean; + private hit_test_single(obj); + private hit_test_point(x, y, z); + } +} +/** + *

A set of programs that calculate the best fit for boxes on a pallet migrated from language C.

+ * + *
    + *
  • Original Boxologic: https://github.com/exad/boxologic
  • + *
+ * + * @author Bill Knechtel,
+ * Migrated and Refactored by Jeongho Nam + */ +declare namespace boxologic { + /** + *

A facade class of boxologic.

+ * + *

The Boxologic class dudcts the best solution of packing boxes to a pallet.

+ * + *
    + *
  • Reference: https://github.com/exad/boxologic
  • + *
+ * + * @author Bill Knechtel,
+ * Migrated and Refactored by Jeongho Nam + */ + class Boxologic { + /** + * A Wrapper to pack instances. + */ + private wrapper; + /** + * Instances trying to put into the wrapper. + */ + private instanceArray; + /** + * Instances failed to pack by overloading. + */ + private leftInstances; + /** + * A pallet containing {@link Box boxes}. + * + * @see Wrapper + */ + private pallet; + /** + * Boxes, trying to pack into the {@link pallet}. + */ + private box_array; + /** + * Sum of all boxes' volume. + */ + private total_box_volume; + /** + *

All different lengths of {@link box_array all box} dimensions along with evaluation values.

+ * + *

In other word, the layer_map stores those entries; each {@link Boxbox}'s length on each + * axis as a key (width, height or length) and evaluation value as a value. The evaluation + * value means sum of minimum gaps between the key and other {@link Box boxes}' width, height and length + *

+ * + * + FOR i := 0 to box_array.size() + WHILE key IN width, length and height in box_array[i] + BEGIN + value := 0 + FOR j to box_array.size() + value += min + ( + abs(key - box_array[j].width), + abs(key - box_array[j].height), + abs(key - box_array[j].length) + ) + layer_map.insert({key, value}); + END + * + * + *
    + *
  • key: A dimension value
  • + *
  • value: Evaluation weight value for the corresponding key.
  • + *
+ */ + private layer_map; + /** + * {@link List} of {@link Scrapped} instances, edges of layers under construction. + * + * @see Scrapped + * @see scrap_min_z + */ + private scrap_list; + /** + * The topology {@link Scrapped}, the edge of the current layer under construction. + * + * @see Scrapped + * @see scrap_list + */ + private scrap_min_z; + /** + * Index of the current {@link box}. + */ + private cboxi; + /** + * Candidate {@link Box.layout_width layout_width} of the {@link cboxi current box}. + */ + private cbox_layout_width; + /** + * Candidate {@link Box.layout_height layout_height} of the {@link cboxi current box}. + */ + private cbox_layout_height; + /** + * Candidate {@link Box.layout_length layout_length} of the {@link cboxi current box}. + */ + private cbox_layout_length; + /** + * Current layer's key on iteration. + */ + private layer_thickness; + /** + * Previous layer's key had iterated. + */ + private pre_layer; + /** + * Key of the unevened layer in the current packing layer. + */ + private layer_in_layer; + /** + * Little Z, gotten from {@link Scrapped.cumz cumz} in {@link min_scrap_z} + */ + private lilz; + /** + * Remained (unfilled) {@link Pallet.layout_height layout_height} of the {@link pallet}. + */ + private remain_layout_height; + /** + * Remained (unfilled) {@link Pallet.layout_length layout_length} of the {@link pallet}. + */ + private remain_layout_length; + /** + * Packed (filled) {@link Pallet.layout_height layout_height} of the {@link pallet}. + */ + private packed_layout_height; + /** + * Packed {@link Pallet.vo1lume volume} of the {@lnk pallet}. + */ + private packed_volume; + private boxi; + private bboxi; + private boxx; + private boxy; + private boxz; + private bboxx; + private bboxy; + private bboxz; + private bfx; + private bfy; + private bfz; + private bbfx; + private bbfy; + private bbfz; + /** + *

Whether the packing is on progress.

+ * + *

The {@link packing} is a flag variable for terminating iterations in + * {@link iterate_orientations iterate_orientations()}, who deducts the best packing solution.

+ */ + private packing; + /** + * Whether packing a layer is done. + */ + private layer_done; + /** + * Whether the current packing layer is evened. + */ + private evened; + /** + * Whether the best solution is deducted. + */ + private packing_best; + /** + * Whether the utilization degree of pallet space is 100%. + */ + private hundred_percent; + /** + * The best orientation of the pallet, which can deduct the {@link best_solution_volume}. + */ + private best_orientation; + /** + * The best layer, which can deduct the {@link best_solution_volume}. + */ + private best_layer; + /** + * The best volume, fit the best utilization degree of the pallet space. + */ + private best_solution_volume; + /** + * Construct from a wrapper and instances. + * + * @param wrapper A Wrapper to pack instances. + * @param instanceArray Instances trying to put into the wrapper. + */ + constructor(wrapper: bws.packer.Wrapper, instanceArray: bws.packer.InstanceArray); + /** + *

Encode data

+ * + *

Encodes {@link bws.packer Packer}'s data to be suitable for the + * {@link boxologic Boxologic}'s parametric data.

+ */ + private encode(); + /** + *

Decode data

+ * + *

Decodes the Boxologic's optimization result data to be suitable for the Packer's own.

+ */ + private decode(); + private inspect_validity(); + /** + *

Pack instances to the {@link wrapper}.

+ * + *

The {@link Boxologic.pack} is an adaptor method between {@link bws.packer Packer} and + * {@link boxologic}. It encodes data from {@link bws.packer Packer}, deducts the best packing + * solution decodes the optimization result and returns it.

+ * + *

The optimization result is returned as a {@link Pair} like below:

+ *
    + *
  • first: The {@link wrapper} with packed instances.
  • + *
  • second: {@link leftInstances Left instances failed to pack} by overloading.
  • + *
+ * + * @return A pair of {@link wrapper} with packed instances and + * {@link leftInstances instances failed to pack} by overloading. + */ + pack(): std.Pair; + /** + *

Execute iterations by calling proper functions.

+ * + *

Iterations are done and parameters of the best solution are found.

+ */ + private iterate_orientations(); + /** + * Iterate a layer. + * + * @param thickness Thickness of the iterating layer. + */ + private iterate_layer(thickness); + /** + *

Construct layers.

+ * + *

Creates all possible layer heights by giving a weight value to each of them.

+ */ + private construct_layers(); + /** + *

Packs the boxes found and arranges all variables and records properly.

+ * + *

Update the linked list and the Boxlist[] array as a box is packed.

+ */ + private pack_layer(); + /** + * Find the most proper layer height by looking at the unpacked boxes and + * the remaining empty space available. + */ + private find_layer(thickness); + /** + *

Determine the gap with the samllest z value in the current layer.

+ * + *

Find the most proper boxes by looking at all six possible orientations, + * empty space given, adjacent boxes, and pallet limits.

+ * + * @param hmx Maximum available x-dimension of the current gap to be filled. + * @param hy Current layer thickness value. + * @param hmy Current layer thickness value. + * @param hz Z-dimension of the current gap to be filled. + * @param hmz Maximum available z-dimension to the current gap to be filled. + */ + private find_box(hmx, hy, hmy, hz, hmz); + /** + *

Analyzes each unpacked {@link Box box} to find the best fitting one to the empty space.

+ * + *

Used by {@link find_box find_box()} to analyze box dimensions.

+ * + * @param x index of a {@link Box box} in the {@link box_array}. + * + * @param hmx Maximum available x-dimension of the current gap to be filled. + * @param hy Current layer thickness value. + * @param hmy Current layer thickness value. + * @param hz Z-dimension of the current gap to be filled. + * @param hmz Maximum available z-dimension to the current gap to be filled. + * + * @param dim1 X-dimension of the orientation of the box being examined. + * @param dim2 Y-dimension of the orientation of the box being examined. + * @param dim3 Z-dimension of the orientation of the box being examined. + */ + private analyze_box(index, hmx, hy, hmy, hz, hmz, dim1, dim2, dim3); + /** + * After finding each box, the candidate boxes and the condition of the layer are examined. + */ + private check_found(); + /** + * After packing of each box, 100% packing condition is checked. + */ + private volume_check(); + /** + *

Find the first to be packed gap in the layer edge.

+ * + *

Determine the gap with the {@link scrap_min_z smallest z} value in the current layer.

+ */ + private find_smallest_z(); + /** + *

Determine {@link box_arrray boxes}.

+ * + *

Using the parameters found, packs the best solution found and reports.

+ */ + private report_results(); + /** + *

Determine a {@link Box}.

+ * + *

Transforms the found co-ordinate system to the one entered by the user and write them to the + * report.

+ */ + private write_box_file(); + } +} +declare namespace boxologic { + /** + * A pallet containing boxes. + * + * @author Bill Knechtel,
+ * Migrated and Refactored by Jeongho Nam + */ + class Pallet extends Instance { + /** + * Construct from a wrapper. + * + * @param wrapper A wrapper wrapping instances. + */ + constructor(wrapper: bws.packer.Wrapper); + /** + * Set placement orientation. + */ + set_orientation(orientation: number): void; + } +} +declare namespace boxologic { + /** + *

Cumulated lengths of current layer.

+ * + *

{@link Scrapped} represents an edge of the current layer under construction.

+ * + * @author Bill Knechtel,
+ * Migrated and Refactored by Jeongho Nam + */ + class Scrap { + /** + * Cumulated length on the X-axis in 3D. + */ + cumx: number; + /** + * Cumulated length on the Z-axis in 3D. + */ + cumz: number; + /** + * Default Constructor. + */ + constructor(); + /** + * Initialization Constructor. + * + * @param cumx Cumulated length on the x-axis. + * @param cumz Cumulated length on the z-axis. + */ + constructor(cumx: number, cumz: number); + } +} +declare namespace bws.packer { + /** + * Bridge of {@link Packer} for {@link InstanceForm repeated instances}. + * + * @author Jeongho Nam + */ + class PackerForm extends samchon.protocol.Entity { + /** + * Form of Instances to pack. + */ + private instanceFormArray; + /** + * Type of Wrappers to be used. + */ + private wrapperArray; + /** + * Default Constructor. + */ + constructor(); + /** + * Initializer Constructor. + * + * @param instanceFormArray Form of Instances to pack. + * @param wrapperArray Type of Wrappers to be used. + */ + constructor(instanceFormArray: InstanceFormArray, wrapperArray: WrapperArray); + construct(xml: samchon.library.XML): void; + optimize(): WrapperArray; + getInstanceFormArray(): InstanceFormArray; + getWrapperArray(): WrapperArray; + TAG(): string; + toXML(): samchon.library.XML; + toPacker(): Packer; + } + /** + * An array of {@link InstanceForm} objects. + * + * @author Jeongho Nam + */ + class InstanceFormArray extends samchon.protocol.EntityArrayCollection { + /** + * Default Constructor. + */ + constructor(); + createChild(xml: samchon.library.XML): InstanceForm; + TAG(): string; + CHILD_TAG(): string; + /** + * Convert {@link InstanceForm} objects to {@link InstanceArray}. + * + * @return An array of instance containing repeated instances in {@link InstanceForm} objects. + */ + toInstanceArray(): InstanceArray; + } + /** + *

A repeated Instance.

+ * + *

InstanceForm is an utility class for repeated {@link Instance}. It is designed for shrinking + * volume of network message I/O by storing {@link count repeated count}.

+ * + * @author Jeongho Nam + */ + class InstanceForm extends samchon.protocol.Entity { + /** + * A duplicated Instance. + */ + private instance; + /** + * Repeated count of the {@link instance}. + */ + private count; + /** + * Default Constructor. + */ + constructor(instance?: Instance, count?: number); + /** + * @inheritdoc + */ + construct(xml: samchon.library.XML): void; + private createInstance(xml); + key(): any; + getInstance(): Instance; + getCount(): number; + setCount(val: number): void; + $name: string; + $width: string; + $height: string; + $length: string; + $count: string; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + toXML(): samchon.library.XML; + /** + *

Repeated {@link instance} to {@link InstanceArray}. + * + * @details + *

Contains the {@link instance repeated instance} to an {@link InstanceArray} to make + * {@link instance} to participate in the packing process. The returned {@link InstanceArray} will be + * registered on {@link Packer.instanceArray}. + * + * @return An array of instance containing repeated {@link instance}. + */ + toInstanceArray(): InstanceArray; + } +} +declare namespace bws.packer { + class WrapperArray extends samchon.protocol.EntityArrayCollection { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + createChild(xml: samchon.library.XML): Wrapper; + /** + * Get (calculate) price. + */ + getPrice(): number; + /** + * Get (calculate) utilization rate. + */ + getUtilization(): number; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + CHILD_TAG(): string; + } +} +declare namespace bws.packer { + class GAWrapperArray extends WrapperArray { + protected instanceArray: InstanceArray; + protected result: std.HashMap; + private price; + /** + * @brief Validity of this sequence list. + */ + private valid; + /** + * Construct from instances. + * + * @param instanceArray Instances to be wrapped. + */ + constructor(instanceArray: InstanceArray); + /** + * @brief Copy Constructor. + */ + constructor(genes: GAWrapperArray); + private constructResult(); + /** + * @brief Get optimization result. + * + * @return result map. + */ + getResult(): std.HashMap; + less(obj: GAWrapperArray): boolean; + } +} +declare namespace bws.packer { + /** + * An interface of physical 3D-instances. + * + * @author Jeongho Nam + */ + interface Instance extends samchon.protocol.IEntity { + /** + * Get name. + */ + getName(): string; + /** + * Get width, length on the X-axis in 3D. + */ + getWidth(): number; + /** + * Get height, length on the Y-axis in 3D. + */ + getHeight(): number; + /** + * Get length, length on the Z-axis in 3D. + */ + getLength(): number; + /** + * Get (calculate) volume. + * + * @return width x height x length + */ + getVolume(): number; + /** + * Set name. + */ + setName(val: string): void; + /** + * Set width, length on the X-axis in 3D. + */ + setWidth(val: number): void; + /** + * Set height, length on the Y-axis in 3D. + */ + setHeight(val: number): void; + /** + * Set length, length on the Z-axis in 3D. + */ + setLength(val: number): void; + /** + *

A type, identifier of derived class.

+ * + *

Derived types

+ *
    + *
  • {@link Product product}
  • + *
  • {@link Wrapper wrapper}
  • + *
      + */ + TYPE(): string; + } +} +declare namespace bws.packer { + /** + * An array of Instance objects. + * + * @author Jeongho Nam + */ + class InstanceArray extends samchon.protocol.EntityArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + createChild(xml: samchon.library.XML): Instance; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + CHILD_TAG(): string; + } +} +declare namespace bws.packer { + /** + * A product. + * + * @author Jeongho Nam + */ + class Product extends samchon.protocol.Entity implements Instance { + /** + *

      Name, key of the Product.

      + * + *

      The name must be unique because a name identifies a {@link Product}.

      + */ + protected name: string; + /** + * Width of the Product, length on the X-axis in 3D. + */ + protected width: number; + /** + * Height of the Product, length on the Y-axis in 3D. + */ + protected height: number; + /** + * Length of the Product, length on the Z-axis in 3D. + */ + protected length: number; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from members. + * + * @param name Name, identifier of the Product. + * @param width Width, length on the X-axis in 3D. + * @param height Height, length on the Y-axis in 3D. + * @param length Length, length on the Z-axis in 3D. + */ + constructor(name: string, width: number, height: number, length: number); + /** + * Key of a Product is its name. + */ + key(): any; + /** + * @inheritdoc + */ + getName(): string; + /** + * @inheritdoc + */ + getWidth(): number; + /** + * @inheritdoc + */ + getHeight(): number; + /** + * @inheritdoc + */ + getLength(): number; + /** + * @inheritdoc + */ + getVolume(): number; + /** + * @inheritdoc + */ + setName(val: string): void; + /** + * @inheritdoc + */ + setWidth(val: number): void; + /** + * @inheritdoc + */ + setHeight(val: number): void; + /** + * @inheritdoc + */ + setLength(val: number): void; + /** + * @inheritdoc + */ + TYPE(): string; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + toXML(): samchon.library.XML; + } +} +declare namespace bws.packer { + /** + *

      Wrap represents an act wrap(ping).

      + * + *

      {@link Wrap} is a class represents an act wrapping an {@link Instance} to an {@link Wrapper}. + * To represent the relationship, Wrap uses Bridge and Capsular patterns to links and intermediates + * relationship between Wrapper and Instance.

      + * + *

      Wrap also helps packing optimization and 3d-visualization with its own members + * {@link orientation} and position variables {@link x}, {@link y} and {@link z}.

      + * + * @author Jeongho Nam + */ + class Wrap extends samchon.protocol.Entity { + /** + * A wrapper wrapping the {@link instance}. + */ + protected wrapper: Wrapper; + /** + * An instance wrapped into the {@link wrapper}. + */ + protected instance: Instance; + /** + * Coordinate-X of the instance placement in the wrapper. + */ + protected x: number; + /** + * Coordinate-Y of the instance placement in the wrapper. + */ + protected y: number; + /** + * Coordinate-Z of the instance placement in the wrapper. + */ + protected z: number; + /** + * Placement orientation of wrapped {@link instance}. + */ + protected orientation: number; + /** + * + */ + protected color: number; + /** + * Construct from a Wrapper. + * + * @param wrapper A wrapper who will contain an instance. + */ + constructor(wrapper: Wrapper); + /** + * Construct from a Wrapper and Instance with its position and default orientation 1. + * + * @param wrapper A wrapper who contains the instance. + * @param instance An instance contained into the wrapper. + * @param x Coordinate-X of the {@link instance} placement in the {@link wrapper}. + * @param y Coordinate-Y of the {@link instance} placement in the {@link wrapper}. + * @param z Coordinate-Z of the {@link instance} placement in the {@link wrapper}. + */ + constructor(wrapper: Wrapper, instance: Instance, x: number, y: number, z: number); + /** + * Construct from a Wrapper and Instance with its position and orientation. + * + * @param wrapper A wrapper who contains the instance. + * @param instance An instance contained into the wrapper. + * @param x Coordinate-X of the {@link instance} placement in the {@link wrapper}. + * @param y Coordinate-Y of the {@link instance} placement in the {@link wrapper}. + * @param z Coordinate-Z of the {@link instance} placement in the {@link wrapper}. + * @param orientation Placement orientation of wrapped {@link instance}. + */ + constructor(wrapper: Wrapper, instance: Instance, x: number, y: number, z: number, orientation: number); + /** + * @inheritdoc + */ + construct(xml: samchon.library.XML): void; + /** + * Factory method of wrapped Instance. + * + * @param type Type of contained Instance's type. + */ + protected createInstance(type: string): Instance; + /** + * Set orientation. + * + * @param orientation Orientation code (1 to 6). + */ + setOrientation(orientation: number): void; + /** + * Set position. + * + * @param x Coordinate-X of the instance placement in the wrapper. + * @param y Coordinate-Y of the instance placement in the wrapper. + * @param z Coordinate-Z of the instance placement in the wrapper. + */ + setPosition(x: number, y: number, z: number): void; + /** + * @brief Estimate orientation by given size. + * + * @param width Width by placement. + * @param height Height by placement. + * @param length Length by placement. + */ + estimateOrientation(width: number, height: number, length: number): void; + /** + * @brief Orientation change is occured in level of the packer. + * + * @details orientation Packer's new orientation. + */ + changeWrapperOrientation(orientation: number): void; + /** + * Get wrapper. + */ + getWrapper(): Wrapper; + /** + * Get instance. + */ + getInstance(): Instance; + /** + * Get x. + */ + getX(): number; + /** + * Get y. + */ + getY(): number; + /** + * Get z. + */ + getZ(): number; + /** + * Get orientation. + */ + getOrientation(): number; + /** + * Get width. + */ + getWidth(): number; + /** + * Get height. + */ + getHeight(): number; + /** + * Get length. + */ + getLength(): number; + /** + * Get volume. + */ + getVolume(): number; + $instanceName: string; + $layoutScale: string; + $position: string; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + toXML(): samchon.library.XML; + /** + * Thickness of boundary lines of a shape represents the {@link instance}. + */ + private static BOUNDARY_THICKNESS; + /** + * + * + * @param geometry + * + * @return A shape and its boundary lines as 3D-objects. + */ + toDisplayObjects(geometry: THREE.Geometry): std.Vector; + } +} +declare namespace bws.packer { + /** + * A wrapper wrapping instances. + * + * @author Jeongho Nam + */ + class Wrapper extends samchon.protocol.EntityDeque implements Instance { + /** + *

      Name, key of the Wrapper.

      + * + *

      The name represents a type of Wrapper and identifies the Wrapper.

      + */ + protected name: string; + /** + * Price, cost of using an Wrapper. + */ + protected price: number; + /** + * Width of the Wrapper, length on the X-axis in 3D. + */ + protected width: number; + /** + * Height of the Wrapper, length on the Y-axis in 3D. + */ + protected height: number; + /** + * Length of the Wrapper, length on the Z-axis in 3D. + */ + protected length: number; + /** + *

      Thickness, margin of a Wrapper causes shrinkness of containable volume.

      + * + *

      The thickness reduces each dimension's containable size (dimension - 2*thickness), + * so finally, it reduces total containable volume (-8 * thickness^3).

      + */ + protected thickness: number; + /** + * Default Constructor. + */ + constructor(); + /** + * Copy Constructor. + */ + constructor(wrapper: Wrapper); + /** + * Construct from members. + * + * @param name Name, identifier of a Wrapper. + * @param price Price, issued cost for a type of the Wrapper. + * @param width Width, dimensional length on the X-axis in 3D. + * @param height Height, dimensional length on the Y-axis in 3D. + * @param length Length, dimensional length on the Z-axis in 3D. + * @param thickness A thickness causes shrinkness on containable volume. + */ + constructor(name: string, price: number, width: number, height: number, length: number, thickness: number); + construct(xml: samchon.library.XML): void; + /** + * @inheritdoc + */ + createChild(xml: samchon.library.XML): Wrap; + /** + * Key of a Wrapper is its name. + */ + key(): any; + /** + * Get name. + */ + getName(): string; + /** + * Get price. + */ + getPrice(): number; + /** + * Get width, length on X-axis in 3D. + */ + getWidth(): number; + /** + * Get height, length on Y-axis in 3D. + */ + getHeight(): number; + /** + * Get length, length on Z-axis in 3D. + */ + getLength(): number; + /** + * Get thickness. + */ + getThickness(): number; + /** + *

      Get (calculate) containable width, length on the X-axis in 3D.

      + * + *

      Calculates containable width considering the {@link thickness}.

      + * + * @return width - (2 x thickness) + */ + getContainableWidth(): number; + /** + *

      Get (calculate) containable height, length on the Y-axis in 3D.

      + * + *

      Calculates containable height considering the {@link thickness}.

      + * + * @return height - (2 x thickness) + */ + getContainableHeight(): number; + /** + *

      Get (calculate) containable length, length on the Z-axis in 3D.

      + * + *

      Calculates containable length considering the {@link thickness}.

      + * + * @return length - (2 x thickness) + */ + getContainableLength(): number; + /** + *

      Get (calculate) volume.

      + * + *

      Notice

      + *

      If {@link thickness} of the Wrapper is not 0, the volume does not mean containable volume. + * In that case, use {@link containableVolume} instead.

      + * + * @return width x height x length + */ + getVolume(): number; + /** + *

      Get (calculate) containable volume.

      + * + *

      Calculates containable volume considering the {@link thickness}.

      + * + * @return volume - {(2 x thickness) ^ 3} + */ + getContainableVolume(): number; + /** + * Get utilization ratio of containable volume. + * + * @return utilization ratio. + */ + getUtilization(): number; + equal_to(obj: Wrapper): boolean; + /** + *

      Wrapper is enough greater?

      + * + *

      Test whether the Wrapper is enough greater than an Instance to contain.

      + * + * @param instance An Instance to test. + * @return Enough greater or not. + */ + containable(instance: Instance): boolean; + /** + * @inheritdoc + */ + setName(val: string): void; + /** + * Set price. + */ + setPrice(val: number): void; + /** + * @inheritdoc + */ + setWidth(val: number): void; + /** + * @inheritdoc + */ + setHeight(val: number): void; + /** + * @inheritdoc + */ + setLength(val: number): void; + /** + * Set thickness. + */ + setThickness(val: number): void; + $name: string; + $price: string; + $width: string; + $height: string; + $length: string; + $thickness: string; + $scale: string; + $spaceUtilization: string; + /** + * @inheritdoc + */ + TYPE(): string; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): samchon.library.XML; + private static scene; + private static renderer; + private static camera; + private static trackball; + private static mouse; + private static BOUNDARY_THICKNESS; + /** + *

      Convert to a canvas containing 3D elements.

      + * + * @param endIndex + * + * @return A 3D-canvans printing the Wrapper and its children {@link Wrap wrapped} + * {@link Instance instances} with those boundary lines. + */ + toCanvas(endIndex?: number): HTMLCanvasElement; + private static handleMouseMove(event); + private static animate(); + private static render(); + } +} +declare namespace bws.packer { + /** + * A group of {@link Wrapper Wrappers} with same type. + * + * @author Jeongho Nam + */ + class WrapperGroup extends WrapperArray { + /** + *

      A sample, standard of the WrapperGroup.

      + * + *

      The sample represents what type of Wrappers are grouped into the WrapperGroup.

      + */ + protected sample: Wrapper; + /** + * Allocated instances. + */ + protected allocatedInstanceArray: InstanceArray; + /** + * Default Constructor. + */ + constructor(); + /** + * Copy Constructor. + */ + constructor(wrapperGroup: WrapperGroup); + /** + * Construct from a sample. + * + * @param sample A sample, standard of the WrapperGroup. + */ + constructor(sample: Wrapper); + /** + * Construct from members of the {@link sample}. + * + * @param name Name, identifier of the sample. + * @param price Price, issued cost for a type of the sample. + * @param width Width, dimensional length on the X-axis in 3D, of the sample. + * @param height Height, dimensional length on the Y-axis in 3D, of the sample. + * @param length Length, dimensional length on the Z-axis in 3D, of the sample. + * @param thickness A thickness, causes shrinkness on containable volume, of the sample. + */ + constructor(name: string, price: number, width: number, height: number, length: number, thickness: number); + /** + * Key of a WrapperGroup is dependent on its sample. + */ + key(): any; + /** + * Get sample. + */ + getSample(): Wrapper; + /** + * Get allocated instances. + */ + getAllocatedInstanceArray(): InstanceArray; + /** + * Get (calculate) price. + * + * @return (Price of the sample) x (numbers of children Wrappers) + */ + getPrice(): number; + /** + * @inheritdoc + */ + getUtilization(): number; + /** + *

      Allocate instance(s) to the WrapperGroup.

      + * + *

      Inspect the instance is enough small to be wrapped into an empty wrapper. If the instance + * is enough small, registers the instance (or repeated instances) to the {@link reserveds} and + * returns true. If the instance is too large to be capsuled, returns false.

      + * + *

      Note

      + *

      The word the instance is enough small to be wrapped into the empty wrapper means + * the instance can be contained into an empty, a new wrapper contaning nothing literally.

      + * + *

      In the method allocate(), it doesn't consider how many instances are wrapped into ordinary + * wrapper and how much volumes are consumed.

      + * + * @param instance An Instance to allocate. + * @param n Repeating number of the instance. + * + * @return Whether the instance is enough small to be wrapped into a (new) wrapper + * of same type with the sample. + */ + allocate(instance: Instance, n?: number): boolean; + /** + *

      Run optimization in level of the group.

      + * + *

      The optimization routine begins by creating a {@link Wrapper} like the {@link sample}. Then + * try to pack {@link allocatedInstanceArray allocated instances} to the {@link Wrapper} as a lot as + * possible. If there're some {@link Wrappers} can't be packed by overloading, then create a new + * {@link Wrapper} again and try to pack {@link allocatedInstanceArray instances} again, too.

      + * + *

      Repeats those steps until all {@link alloctedInstanceArray instances} are {@link Wrap packed} + * so that there's not any {@link Instance instance} left.

      + * + *

      Warning

      + *

      When call this {@link optimize optimize()} method, ordinary children {@link Wrapper} objects + * in the {@link WrapperGroup} will be substituted with the newly optimized {@link Wrapper} objects.

      + */ + optimize(): void; + /** + *

      Wrap allocated instances into a new {@link Wrapper}.

      + * + *

      {@link Wrap Wraps} instances to a new Wrapper which is copied from the sample.

      + *

      After the wrapping is done, the new {@link Wrapper} is registered to the {@link WrapperGroup} + * as a child and instances failed to wrap by overloading is returned.

      + * + * @param instanceArray instances to {@link Wrap wrap} into a new {@link Wrapper}. + * + * @return Instances failed to {@link Wrap wrap} by overloading. + * @see boxologic + */ + private pack(instanceArray); + /** + * @inheritdoc + */ + TAG(): string; + } +} +declare namespace bws.packer { + abstract class Editor extends React.Component<{ + dataProvider: samchon.protocol.EntityArrayCollection; + }, {}> { + private columns; + private selected_index; + /** + * Default Constructor. + */ + constructor(); + protected abstract createColumns(): AdazzleReactDataGrid.Column[]; + private get_row(index); + private insert_instance(event); + private erase_instances(event); + private handle_data_change(event); + private handle_row_change(event); + private handle_select(event); + render(): JSX.Element; + } +} +declare namespace bws.packer { + interface ItemEditorProps extends React.Props { + application: PackerApplication; + instances: InstanceFormArray; + wrappers: WrapperArray; + } + class ItemEditor extends React.Component { + private clear(event); + private open(event); + private save(event); + private pack(event); + render(): JSX.Element; + } + class InstanceEditor extends Editor { + protected createColumns(): AdazzleReactDataGrid.Column[]; + } + class WrapperEditor extends Editor { + protected createColumns(): AdazzleReactDataGrid.Column[]; + } +} +declare namespace bws.packer { + class PackerApplication extends React.Component<{}, {}> { + private instances; + private wrappers; + private result; + /** + * Default Constructor. + */ + constructor(); + pack(): void; + drawWrapper(wrapper: Wrapper, index?: number): void; + render(): JSX.Element; + static main(): void; + } +} +declare namespace bws.packer { + class ResultViewer extends React.Component { + drawWrapper(wrapper: Wrapper, index?: number): void; + private clear(event); + private open(event); + private save(event); + refresh(): void; + render(): JSX.Element; + } + interface WrapperViewerProps extends React.Props { + application: PackerApplication; + wrappers: WrapperArray; + } +} diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 4317128869..44f0d8e9a0 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -401,6 +401,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](egg.js/egg.js.d.ts) [Egg.js](https://github.com/mikeflynn/egg.js) by [Markus Peloso](https://github.com/ToastHawaii) * [:link:](ejs-locals/ejs-locals.d.ts) [ejs-locals](https://github.com/randometc/ejs-locals) by [jt000](https://github.com/jt000) * [:link:](ejs/ejs.d.ts) [ejs.js](http://ejs.co) by [Ben Liddicott](https://github.com/benliddicott/DefinitelyTyped) +* [:link:](elasticsearch/elasticsearch.d.ts) [elasticsearch](https://www.elastic.co) by [Casper Skydt](https://github.com/CasperSkydt/DefinitelyTyped), [Blake Smith](https://github.com/bfsmith/DefinitelyTyped) * [:link:](jquery.elang/jquery.elang.d.ts) [eLang](https://github.com/sumegizoltan/ELang) by [Zoltan Sumegi](https://github.com/sumegizoltan) * [:link:](github-electron/github-electron.d.ts) [Electron](http://electron.atom.io) by [jedmao](https://github.com/jedmao), [rhysd](https://rhysd.github.io), [Milan Burda](https://github.com/miniak) * [:link:](electron-builder/electron-builder.d.ts) [electron-builder](https://github.com/loopline-systems/electron-builder) by [Maxime LUCE](https://github.com/SomaticIT) @@ -1123,10 +1124,11 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](moment/moment.d.ts) [Moment.js](https://github.com/timrwood/moment) by [Michael Lakerveld](https://github.com/Lakerfield), [Aaron King](https://github.com/kingdango), [Hiroki Horiuchi](https://github.com/horiuchi), [Dick van den Brink](https://github.com/DickvdBrink), [Adi Dahiya](https://github.com/adidahiya), [Matt Brooks](https://github.com/EnableSoftware) * [:link:](moment-range/moment-range.d.ts) [Moment.js](https://github.com/gf3/moment-range) by [Bart van den Burg](https://github.com/Burgov), [Wilgert Velinga](https://github.com/wilgert) * [:link:](mongodb/mongodb.d.ts) [MongoDB](https://github.com/mongodb/node-mongodb-native/tree/2.1) by [Federico Caselli](https://github.com/CaselIT) -* [:link:](mongoose/mongoose.d.ts) [Mongoose](http://mongoosejs.com) by [horiuchi](https://github.com/horiuchi) +* [:link:](mongoose/mongoose.d.ts) [Mongoose](http://mongoosejs.com) by [simonxca](https://github.com/simonxca), [horiuchi](https://github.com/horiuchi) * [:link:](mongoose-auto-increment/mongoose-auto-increment.d.ts) [mongoose-auto-increment](https://github.com/codetunnel/mongoose-auto-increment) by [Aya Morisawa](https://github.com/AyaMorisawa) * [:link:](mongoose-deep-populate/mongoose-deep-populate.d.ts) [mongoose-deep-populate](https://github.com/buunguyen/mongoose-deep-populate) by [Aya Morisawa](https://github.com/AyaMorisawa) * [:link:](mongoose-mock/mongoose-mock.d.ts) [mongoose-mock](https://github.com/JohanObrink/mongoose-mock) by [jt000](https://github.com/jt000) +* [:link:](mongoose-promise/mongoose-promise.d.ts) [mongoose-promise](http://mongoosejs.com/docs/api.html#promise-js) by [simonxca](https://github.com/simonxca) * [:link:](morgan/morgan.d.ts) [morgan](https://github.com/expressjs/morgan) by [James Roland Cabresos](https://github.com/staticfunction) * [:link:](mousetrap/mousetrap-global-bind.d.ts) [Mousetrap 1.4.6's global-bind extension](http://craig.is/killing/mice#extensions.global) by [Andrew Bradley](https://github.com/cspotcode) * [:link:](mousetrap/mousetrap.d.ts) [Mousetrap 1.5.x](http://craig.is/killing/mice) by [Dániel Tar](https://github.com/qcz) diff --git a/ace/ace.d.ts b/ace/ace.d.ts index 6a09235977..1ac19c7c63 100644 --- a/ace/ace.d.ts +++ b/ace/ace.d.ts @@ -77,9 +77,6 @@ declare namespace AceAjax { onTextInput(text: any): void; } - var KeyBinding: { - new(editor: Editor): KeyBinding; - } export interface TextMode { diff --git a/acl/acl.d.ts b/acl/acl.d.ts index 06defa2449..d222f9ebb6 100644 --- a/acl/acl.d.ts +++ b/acl/acl.d.ts @@ -3,7 +3,7 @@ // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// /// diff --git a/adal-angular/adal-tests.ts b/adal-angular/adal-tests.ts index 3b9e46c961..db984d95ba 100644 --- a/adal-angular/adal-tests.ts +++ b/adal-angular/adal-tests.ts @@ -20,4 +20,6 @@ Logging.level = 4; auth.info("Logging message"); -var userName: string = auth.getCachedUser().userName; \ No newline at end of file +var userName: string = auth.getCachedUser().userName; +var postLogoutRedirectUrl = auth.config.postLogoutRedirectUri; +var isValidRequest = auth.getRequestInfo('hash').valid; \ No newline at end of file diff --git a/adal-angular/adal.d.ts b/adal-angular/adal.d.ts index 76b86e7150..a896d687ec 100644 --- a/adal-angular/adal.d.ts +++ b/adal-angular/adal.d.ts @@ -13,29 +13,30 @@ declare module 'adal' { declare namespace adal { interface Config { - tenant?: string, - clientId: string, - redirectUri?: string, - cacheLocation?: string, - displayCall?: (urlNavigate: string) => any, - correlationId?: string, - loginResource?: string, - resource?: string - endpoints?: any // If you need to send CORS api requests. - extraQueryParameter?: string + tenant?: string; + clientId: string; + redirectUri?: string; + cacheLocation?: string; + displayCall?: (urlNavigate: string) => any; + correlationId?: string; + loginResource?: string; + resource?: string; + endpoints?: any; // If you need to send CORS api requests. + extraQueryParameter?: string; + postLogoutRedirectUri?: string; // redirect url after succesful logout operation } interface User { - userName: string, - profile: any + userName: string; + profile: any; } interface RequestInfo { - valid: boolean, - parameters: any, - stateMatch: boolean, - stateResponse: string, - requestType: string + valid: boolean; + parameters: any; + stateMatch: boolean; + stateResponse: string; + requestType: string; } interface Logging { @@ -64,6 +65,10 @@ declare namespace adal { * Saves the resulting Idtoken in localStorage. */ login(): void; + + /** + * Indicates whether login is in progress now or not. + */ loginInProgress(): boolean; /** @@ -131,9 +136,9 @@ declare namespace adal { /** * Gets requestInfo from given hash. - * @returns {string} error message related to login + * @returns {RequestInfo} for appropriate hash. */ - getRequestInfo(hash: string): string; + getRequestInfo(hash: string): RequestInfo; /** * Saves token from hash that is received from redirect. @@ -147,6 +152,11 @@ declare namespace adal { */ getResourceForEndpoint(endpoint: string): string; + /** + * Handles redirection after login operation. + * Gets access token from url and saves token to the (local/session) storage + * or saves error in case unsuccessful login. + */ handleWindowCallback(): void; log(level: number, message: string, error: any): void; diff --git a/agenda/agenda.d.ts b/agenda/agenda.d.ts index 463ba43d2e..8dd58fdd80 100644 --- a/agenda/agenda.d.ts +++ b/agenda/agenda.d.ts @@ -319,6 +319,11 @@ declare module "agenda" { * The date/time the job last failed. */ failedAt: Date; + + /** + * Job's state + */ + disabled: boolean } /** @@ -409,6 +414,11 @@ declare module "agenda" { * @param cb Called after the job has been saved to the database. */ touch(cb?: Callback): void; + + /** + * Calculates next time the job should run + */ + computeNextRunAt(): Job; } interface JobOptions { diff --git a/ajv/ajv-tests.ts b/ajv/ajv-tests.ts new file mode 100644 index 0000000000..e6413fd824 --- /dev/null +++ b/ajv/ajv-tests.ts @@ -0,0 +1,74 @@ +/// + +import * as Ajv from 'ajv'; +var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true} +var validate = ajv.compile({}); +var valid = validate({}); +if (!valid) console.log(validate.errors); + +var valid = ajv.validate({}, {}); +if (!valid) console.log(ajv.errors); + +ajv.addSchema({}, 'mySchema'); +var valid = ajv.validate('mySchema', {}); +if (!valid) console.log(ajv.errorsText()); + +ajv.addKeyword('range', { + type: 'number', compile: function (sch, parentSchema) { + var min: any = sch[0]; + var max: any = sch[1]; + + return parentSchema.exclusiveRange === true + ? function (data) { return data > min && data < max; } + : function (data) { return data >= min && data <= max; } + } +}); + +var schema = { "range": [2, 4], "exclusiveRange": true }; +var validate = ajv.compile(schema); +console.log(validate(2.01)); // true +console.log(validate(3.99)); // true +console.log(validate(2)); // false +console.log(validate(4)); // false + +declare var request: any; +function loadSchema(uri: any, callback: any) { + request.json(uri, function (err: any, res: any, body: any) { + if (err || res.statusCode >= 400) + callback(err || new Error('Loading error: ' + res.statusCode)); + else + callback(null, body); + }); +} +var ajv = new Ajv({ loadSchema: loadSchema }); + +ajv.compileAsync(schema, function (err, validate) { + if (err) return; + var valid = validate({}); +}); + +declare var knex: any; +function checkIdExists(schema: any, data: any) { + return knex(schema.table) + .select('id') + .where('id', data) + .then(function (rows: any) { + return true; + }); +} + +var validate = ajv.compile(schema); + +(validate({ userId: 1, postId: 19 }) as PromiseLike) + .then(function (valid) { + // "valid" is always true here + console.log('Data is valid'); + }, function (err) { + if (!(err instanceof Ajv.ValidationError)) throw err; + // data is invalid + console.log('Validation errors:', err.errors); + }); + +var ajv = new Ajv({ /* async: 'es7', */ transpile: 'nodent' }); +var validate = ajv.compile(schema); // transpiled es7 async function +(validate({}) as PromiseLike).then(() => { }, () => { }); diff --git a/ajv/ajv.d.ts b/ajv/ajv.d.ts new file mode 100644 index 0000000000..d8bfd56ef3 --- /dev/null +++ b/ajv/ajv.d.ts @@ -0,0 +1,112 @@ +// Type definitions for ajv +// Project: https://github.com/epoberezkin/ajv +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "ajv" { + class Ajv { + /** + * Create Ajv instance. + */ + constructor(options?: Ajv.AjvOptions); + /** + * Generate validating function and cache the compiled schema for future use. + */ + compile(schema: any): Ajv.AjvValidate; + /** + * Asyncronous version of compile method that loads missing remote schemas using asynchronous function in options.loadSchema. + */ + compileAsync(schema: any, callback: (error: Error, validate: Ajv.AjvValidate) => void): void; + /** + * Validate data using passed schema (it will be compiled and cached). + */ + validate(schema: any, data: any): boolean | PromiseLike; + errors: Ajv.ValidationError[]; + /** + * Add schema(s) to validator instance. + */ + addSchema(schema: any, key: string): void; + /** + * Adds meta schema(s) that can be used to validate other schemas. + * That function should be used instead of addSchema because there may be instance options that would compile a meta schema incorrectly (at the moment it is removeAdditional option). + */ + addMetaSchema(schema: any, key: string): void; + /** + * Validates schema. + * This method should be used to validate schemas rather than validate due to the inconsistency of uri format in JSON-Schema standard. + */ + validateSchema(schema: any): Boolean; + /** + * Retrieve compiled schema previously added with addSchema by the key passed to addSchema or by its full reference (id). + * Returned validating function has schema property with the reference to the original schema. + */ + getSchema(key: string): Ajv.AjvValidate; + /** + * Remove added/cached schema. + * Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references. + */ + removeSchema(schema: any): void; + /** + * Add custom format to validate strings. It can also be used to replace pre-defined formats for Ajv instance. + */ + addFormat(name: string, format: any): void; + /** + * Add custom validation keyword to Ajv instance. + */ + addKeyword(keyword: string, definition: Ajv.AjxKeywordDefinition): void; + errorsText(): any; + static ValidationError: Function; + } + namespace Ajv { + type AjvOptions = { + v5?: boolean; + allErrors?: boolean; + verbose?: boolean; + jsonPointers?: boolean; + uniqueItems?: boolean; + unicode?: boolean; + format?: string; + formats?: any; + schemas?: any; + missingRefs?: boolean; + loadSchema?(uri: string, callback: (error: Error, body: any) => void): void; + removeAdditional?: boolean; + useDefaults?: boolean; + coerceTypes?: boolean; + async?: any; + transpile?: string; + meta?: boolean; + validateSchema?: boolean; + addUsedSchema?: boolean; + inlineRefs?: boolean; + passContext?: boolean; + loopRequired?: number; + ownProperties?: boolean; + multipleOfPrecision?: boolean; + errorDataPath?: string, + messages?: boolean; + beautify?: boolean; + cache?: any; + } + type AjvValidate = ((data: any) => boolean | PromiseLike) & { + errors: ValidationError[]; + } + type AjxKeywordDefinition = { + async?: boolean; + type: string; + compile?: (schema: any, parentsSchema: any) => ((data: any) => boolean | PromiseLike); + validate?: (schema: any, data: any) => boolean; + } + type ValidationError = { + keyword: string; + dataPath: string; + schemaPath: string; + params: any; + message: string; + schema: any; + parentSchema: any; + data: any; + } + } + export = Ajv; +} diff --git a/alexa-sdk/alexa-sdk-tests.ts b/alexa-sdk/alexa-sdk-tests.ts new file mode 100644 index 0000000000..e161c5bf38 --- /dev/null +++ b/alexa-sdk/alexa-sdk-tests.ts @@ -0,0 +1,25 @@ +/// +/// + +import * as Alexa from "alexa-sdk"; + +exports.handler = function(event: Alexa.RequestBody, context: Alexa.Context, callback: Function) { + let alexa = Alexa.handler(event, context); + alexa.registerHandlers(handlers); + alexa.execute(); +}; + +let handlers: Alexa.Handlers = { + 'LaunchRequest': function () { + var self: Alexa.Handler = this; + self.emit('SayHello'); + }, + 'HelloWorldIntent': function () { + var self: Alexa.Handler = this; + self.emit('SayHello'); + }, + 'SayHello': function () { + var self: Alexa.Handler = this; + self.emit(':tell', 'Hello World!'); + } +}; diff --git a/alexa-sdk/alexa-sdk.d.ts b/alexa-sdk/alexa-sdk.d.ts new file mode 100644 index 0000000000..5866d8c4ee --- /dev/null +++ b/alexa-sdk/alexa-sdk.d.ts @@ -0,0 +1,132 @@ +// Type definitions for Alexa SDK for Node.js v1.0.3 +// Project: https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs +// Definitions by: Pete Beegle +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'alexa-sdk' { + export function handler(event: RequestBody, context: Context, callback?: Function): AlexaObject; + export function CreateStateHandler(state: string, obj: any): any; + export var StateString: string; + + interface AlexaObject { + _event: any; + _context: any; + _callback: any; + state: any; + appId: any; + response: any; + dynamoDBTableName: any; + saveBeforeResponse: boolean; + registerHandlers: (...handlers: Handlers[]) => any; + execute: () => void; + } + + interface Handlers { + [intent: string]: () => void; + } + + interface Handler { + on: any; + emit(event: string, ...args: any[]): boolean; + emitWithState: any; + state: any; + handler: any; + event: RequestBody; + attributes: any; + context: any; + name: any; + isOverriden: any; + } + + interface Context { + callbackWaitsForEmptyEventLoop: boolean; + logGroupName: string; + logStreamName: string; + functionName: string; + memoryLimitInMB: string; + functionVersion: string; + invokeid: string; + awsRequestId: string; + } + + interface RequestBody { + version: string; + session: Session; + request: LaunchRequest | IntentRequest | SessionEndedRequest; + } + + interface Session { + new: boolean; + sessionId: string; + attributes: any; + application: SessionApplication; + user: SessionUser; + } + + interface SessionApplication { + applicationId: string; + } + + interface SessionUser { + userId: string; + accessToken: string; + } + + interface LaunchRequest extends IRequest {} + + interface IntentRequest extends IRequest { + intent: Intent; + } + + interface Intent { + name: string; + slots: any; + } + + interface SessionEndedRequest extends IRequest{ + reason: string; + } + + interface IRequest { + type: "LaunchRequest" | "IntentRequest" | "SessionEndedRequest"; + requestId: string; + timeStamp: string; + } + + interface ResponseBody { + version: string; + sessionAttributes?: any; + response: Response; + } + + interface Response { + outputSpeech?: OutputSpeech; + card?: Card; + reprompt?: Reprompt; + shouldEndSession: boolean; + } + + interface OutputSpeech { + type: "PlainText" | "SSML"; + text?: string; + ssml?: string; + } + + interface Card { + type: "Simple" | "Standard" | "LinkAccount"; + title?: string; + content?: string; + text?: string; + image?: Image; + } + + interface Image { + smallImageUrl: string; + largeImageUrl: string; + } + + interface Reprompt { + outputSpeech: OutputSpeech; + } +} + diff --git a/alt/alt.d.ts b/alt/alt.d.ts index 20da159f35..575d476451 100644 --- a/alt/alt.d.ts +++ b/alt/alt.d.ts @@ -53,8 +53,8 @@ declare namespace AltJS { export type Source = {[name:string]: () => SourceModel}; export interface SourceModel { - local(state:any):any; - remote(state:any):Promise; + local(state:any, ...args: any[]):any; + remote(state:any, ...args: any[]):Promise; shouldFetch?(fetchFn:(...args:Array) => boolean):void; loading?:(args:any) => void; success?:(state:S) => void; diff --git a/amcharts/AmCharts.d.ts b/amcharts/AmCharts.d.ts index 543467feac..4f5dbe90f7 100644 --- a/amcharts/AmCharts.d.ts +++ b/amcharts/AmCharts.d.ts @@ -26,6 +26,22 @@ declare namespace AmCharts { /** Clears all the charts on page, removes listeners and intervals. */ function clear(); + + /** Handle ready event */ + function ready(Function): void; + + /** Create chart by params. */ + function makeChart(selector: string, params: any, delay?: number): AmChart; + + /** Set a method to be called before initializing the chart. + * When the method is called, the chart instance is passed as an attribute. + * You can use this feature to preprocess chart data or do some other things you need + * before initializing the chart. + * @param {Function} handler - The method to be called. + * @param {string[]} types - Which chart types should call this method. Defaults to all + * if none is passed. + */ + function addInitHandler(handler: Function, types: string[]); /** AmPieChart class creates pie/donut chart. In order to display pie chart you need to set at least three properties - dataProvider, titleField and valueField. @example @@ -948,6 +964,10 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val @Default 150 */ hideBalloonTime: number; + /** Allows changing language easily. + * Note, you should include the language.js file from amcharts/lang or ammap/lang folder and then use variable name used in this file, like chart.language = "de"; + * Note, for maps this works differently - you use language only for country names, as there are no other strings in the maps application. */ + language: string; /** Legend of a chart. */ legend: AmLegend; /** Reference to the div of the legend. */ @@ -976,6 +996,8 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val prefixesOfBigNumbers: any[]; /** Prefixes which are used to make small numbers shorter: 2μ instead of 0.000002, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e-24, prefix:"y"},{number:1e-21, prefix:"z"},{number:1e-18, prefix:"a"},{number:1e-15, prefix:"f"},{number:1e-12, prefix:"p"},{number:1e-9, prefix:"n"},{number:1e-6, prefix:"μ"},{number:1e-3, prefix:"m"}] */ prefixesOfSmallNumbers: any[]; + /** A config object for Responsive plugin. */ + responsive: any; /** Theme of a chart. Config files of themes can be found in amcharts/themes/ folder. More info about using themes. */ theme: string; /** Thousands separator. @@ -1003,7 +1025,7 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val bold - specifies if text is bold (true/false), url - url */ - addLabel(x: number, y: number, text: string, align: string, size: number, color: string, rotation: number, alpha: number, bold: boolean, url: string); + addLabel(x: number|string, y: number|string, text: string, align: string, size?: number, color?: string, rotation?: number, alpha?: number, bold?: boolean, url?: string); /** Adds a legend to the chart. By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter. (NOTE: This method will not work on StockPanel.) diff --git a/amplitude-js/v2/amplitude-js-tests.ts b/amplitude-js/v2/amplitude-js-tests.ts new file mode 100644 index 0000000000..3e69d7c867 --- /dev/null +++ b/amplitude-js/v2/amplitude-js-tests.ts @@ -0,0 +1,87 @@ +// Tests for Amplitude SDK TypeScript definitions + +/// + +module Amplitude.Tests { + function all() { + amplitude.init('YOUR_API_KEY_HERE', null, { + // optional configuration options + saveEvents: true, + includeUtm: true, + includeReferrer: true, + batchEvents: true, + eventUploadThreshold: 50 + }); + amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE', null, () => {}); + + amplitude.logEvent('EVENT_IDENTIFIER_HERE'); + amplitude.setUserId('USER_ID_HERE'); + amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE'); + amplitude.setUserId(null); // not string 'null' + amplitude.setVersionName('VERSION_NAME_HERE'); + + amplitude.regenerateDeviceId(); + amplitude.setDeviceId('CUSTOM_DEVICE_ID'); + + amplitude.logEvent('EVENT_IDENTIFIER_HERE', { + 'color': 'blue', + 'age': 20, + 'key': 'value' + }); + amplitude.logEvent("EVENT_IDENTIFIER_HERE", null, (httpCode, response) => { }); + + let identify = new amplitude.Identify().set('gender', 'female').set('age', 20); + amplitude.identify(identify); + + identify = new amplitude.Identify().setOnce('sign_up_date', '08/24/2015'); + amplitude.identify(identify); + + identify = new amplitude.Identify().setOnce('sign_up_date', '09/14/2015'); + amplitude.identify(identify); + + identify = new amplitude.Identify().unset('gender').unset('age'); + amplitude.identify(identify); + + identify = new amplitude.Identify().add('karma', 1).add('friends', 1); + amplitude.identify(identify); + + identify = new amplitude.Identify().append('ab-tests', 'new-user-test').append('some_list', [1, 2, 3, 4, 'values']); + amplitude.identify(identify); + + identify = new amplitude.Identify().prepend('ab-tests', 'new-user-test').prepend('some_list', [1, 2, 3, 4, 'values']); + amplitude.identify(identify); + + identify = new amplitude.Identify() + .set('karma', 10) + .add('karma', 1) + .unset('karma'); + amplitude.identify(identify); + + identify = new amplitude.Identify() + .set('colors', ['rose', 'gold']) + .append('ab-tests', 'campaign_a') + .append('existing_list', [4, 5]); + amplitude.identify(identify); + + amplitude.setUserProperties({ + gender: 'female', + age: 20 + }); + + amplitude.clearUserProperties(); + + amplitude.setOptOut(true); + amplitude.setOptOut(false); + + amplitude.setGroup('orgId', '15'); + amplitude.setGroup('sport', ['soccer', 'tennis']); + + // TODO: Implement those. + /* + var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3); + amplitude.logRevenueV2(revenue); + + amplitude.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' }); + */ + } +} diff --git a/amplitude-js/v2/amplitude-js.d.ts b/amplitude-js/v2/amplitude-js.d.ts new file mode 100644 index 0000000000..613f5ad5d8 --- /dev/null +++ b/amplitude-js/v2/amplitude-js.d.ts @@ -0,0 +1,61 @@ +// Type definitions for Amplitude SDK 2.12.1 +// Project: https://github.com/amplitude/Amplitude-Javascript +// Definitions by: Arvydas Sidorenko +// Definitions: https://github.com/Asido/DefinitelyTyped + +declare module amplitude { + interface Config { + batchEvents?: boolean; + cookieExpiration?: number; + cookieName?: string; + deviceId?: string; + domain?: string; + eventUploadPeriodMillis?: number; + eventUploadThreshold?: number; + includeReferrer?: boolean; + includeUtm?: boolean; + language?: string; + optOut?: boolean; + platform?: string; + saveEvents?: boolean; + savedMaxCount?: number; + sessionTimeout?: number; + uploadBatchSize?: number; + } + + export class Identify { + set(key: string, value: any): Identify; + setOnce(key: string, value: any): Identify; + add(key: string, value: number): Identify; + append(key: string, value: any): Identify; + prepend(key: string, value: any): Identify; + + unset(key: string): Identify; + } + + export function init(apiKey: string): void; + export function init(apiKey: string, userId: string): void; + export function init(apiKey: string, userId: string, options: Config): void; + export function init(apiKey: string, userId: string, options: Config, callback: () => void): void; + + export function setVersionName(version: string): void; + export function setUserId(userId: string): void; + + export function setDeviceId(id: string): void; + export function regenerateDeviceId(): void; + + export function identify(identify: Identify): void; + + export function setUserProperties(properties: Object): void; + export function clearUserProperties(): void; + + export function setOptOut(optOut: boolean): void; + + export function setGroup(groupType: string, groupName: string | string[]): void; + + export function logEvent(event: string): void; + export function logEvent(event: string, data: Object): void; + export function logEvent(event: string, data: Object, callback: (httpCode: number, response: any) => void): void; + + export var options: Config; +} diff --git a/angular-environment/angular-environment.d.ts b/angular-environment/angular-environment.d.ts index 483474410c..94972d1383 100644 --- a/angular-environment/angular-environment.d.ts +++ b/angular-environment/angular-environment.d.ts @@ -14,6 +14,11 @@ declare namespace angular.environment { * loads the correct environment variables. */ check: () => void; + /** + * Retrieves the correct version of a + * variable for the current environment. + */ + read: (key: string) => any; } interface Service { /** diff --git a/angular-es/angular-es-tests.ts b/angular-es/angular-es-tests.ts new file mode 100644 index 0000000000..2e44d5d0a8 --- /dev/null +++ b/angular-es/angular-es-tests.ts @@ -0,0 +1,157 @@ +/// + +// +// @Component +// +import { Component } from 'angular-es'; +@Component({ + selector: '', + template: '' +}) +class MyComponentController { + +} + +// +// @Config +// +import { Config } from 'angular-es'; + +@Config() +class MyConfig { + +} + +// +// @Constant +// +import { Constant } from 'angular-es'; + +@Constant('MyConstant') +class MyConstant { + foo = 'foo'; + bar = 'bar'; +} + +// +// @Controller +// +import { Controller } from 'angular-es'; + +@Controller('MyController') +class MyController { + +} + +// +// @Decorator +// +import { Decorator } from 'angular-es'; + +@Decorator('MyServiceDecorator') +class MyServiceDecorator { + +} + +// +// @Directive +// +import { Directive } from 'angular-es'; + +@Directive('MyDirective') +class MyDirective { + +} + +// +// @Factory +// +import { Factory } from 'angular-es'; + +@Factory('MyFactory') +class MyFactory { +} + +// +// @Filter +// +import { Filter } from 'angular-es'; + +@Filter('MyFilter') +class MyFilter { +} + +// +// @Inject +// +import { Inject } from 'angular-es'; + +@Inject('fooBar') +class MyFooService { + + @Inject('bazBar') + myMethod(bazBar: Object) { + } + + constructor(fooBar: Object) { + } +} + +// +// @InjectAsProperty +// +import { InjectAsProperty } from 'angular-es'; + +@InjectAsProperty('fooBar') +class MyFooBarService { + fooBar: Object; + + myMethod() { + this.fooBar !== undefined; + } +} + +// +// @Module +// +import { Module } from 'angular-es'; + +@Module('my.module') +@Service('MyModuleService') +class MyModuleService { +} + +// +// @Provider +// +import { Provider } from 'angular-es'; + +@Provider('MyProvider') +class MyProvider { +} + +// +// @Run +// +import { Run } from 'angular-es'; + +@Run() +class MyRunBlock { +} + +// +// @Service +// +import { Service } from 'angular-es'; + +@Service('MyService') +class MyService { +} +// +// @Value +// +import { Value } from 'angular-es'; + +@Value('MyValue') +class MyValue { +} diff --git a/angular-es/angular-es.d.ts b/angular-es/angular-es.d.ts new file mode 100644 index 0000000000..0972b42da0 --- /dev/null +++ b/angular-es/angular-es.d.ts @@ -0,0 +1,187 @@ +// Type definitions for angular-es v0.0.3 +// Project: https://github.com/mbutsykin/angular-es +// Definitions by: mbutsykin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'angular-es' { + + interface ClassDecorator { + (target: TFunction): TFunction|void; + } + + interface MethodDecorator { + (target: Object, propertyKey: string|symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor|void; + } + + /** + * Decorated target + */ + interface ngESDecorator extends ClassDecorator, MethodDecorator { + (target: Object|Function, + ngName?: string, + ngArguments?: Array, + ngType?: string, + injectAsProperty?: Array): void; + } + + /** + * Component interface + * @see https://docs.angularjs.org/guide/component + */ + interface iComponent { + template: string, + selector: string, + controllerAs?: string, + require?: string, + templateUrl?: string, + transclude?: string, + bindings?: Object + } + + /** + * Register component + * + * @param {Object} component - component config + * + * @returns {ngESDecorator} - decorated class + */ + function Component(component: iComponent): ngESDecorator; + + /** + * Register config block + */ + function Config(): ngESDecorator; + + /** + * Register constant + * + * @param {string} name - constant name + * + * @returns {ngESDecorator} - decorated class + */ + function Constant(name: string): ngESDecorator; + + /** + * Register controller + * + * @param {string} name - controller name + * + * @returns {ngESDecorator} - decorated class + */ + function Controller(name: string): ngESDecorator; + + /** + * Register decorator + * + * @param {string} name - provider name to decorate + * + * @returns {ngESDecorator} - decorated class + */ + function Decorator(name: string): ngESDecorator; + + /** + * Register directive + * + * @param {string} name - directive selector, can be in hyphen-case + * + * @returns {ngESDecorator} - decorated class + */ + function Directive(name: string): ngESDecorator; + + /** + * Register factory + * + * @param {string} name - factory name + * + * @returns {ngESDecorator} - decorated class + */ + function Factory(name: string): ngESDecorator; + + /** + * Register filter + * + * @param {string} name - filter name + * + * @returns {ngESDecorator} - decorated class + */ + function Filter(name: string): ngESDecorator; + + /** + * Add $inject property to target + * + * @param {Array} dependencies - dependencies to inject + * + * @returns {ngESDecorator} - decorated class + */ + function Inject(...dependencies: Array): ngESDecorator; + + /** + * Inject dependencies as properties to target + * + * @param {Array} dependencies - dependencies to inject + * + * @returns {ngESDecorator} - decorated class + */ + function InjectAsProperty(...dependencies: Array): ngESDecorator; + + /** + * Attach target to the specified module + * + * @param {string} name - module name + * + * @returns {ngESDecorator} - decorated class + */ + function Module(name: string): ngESDecorator; + + /** + * Register provider + * + * @param {string} name - provider name + * + * @returns {ngESDecorator} - decorated class + */ + function Provider(name: string): ngESDecorator; + + /** + * Register run block + * + * @returns {ngESDecorator} - decorated class + */ + function Run(): ngESDecorator; + + /** + * Register service + * + * @param {string} name - service name + * + * @returns {ngESDecorator} - decorated class + */ + function Service(name: string): ngESDecorator; + + /** + * Register value + * + * @param {string} name - value name + * + * @returns {ngESDecorator} - decorated class + */ + function Value(name: string): ngESDecorator; + + export { + Component, + Config, + Constant, + Controller, + Decorator, + Directive, + Factory, + Filter, + Inject, + InjectAsProperty, + Module, + Provider, + Run, + Service, + Value, + } +} diff --git a/angular-feature-flags/angular-feature-flags-tests.ts b/angular-feature-flags/angular-feature-flags-tests.ts new file mode 100644 index 0000000000..a36eaba3d0 --- /dev/null +++ b/angular-feature-flags/angular-feature-flags-tests.ts @@ -0,0 +1,31 @@ +/// + +let myApp = angular.module('myApp', ['feature-flags']); + +const flagsData: Array = [ + { + key: '1', + active: true, + name: 'flag1', + description: 'This is the first flag' + }, + { + key: '2', + active: false, + name: 'flag2', + description: 'This is the second flag' + } +]; + +myApp.config(function (featureFlagsProvider: angular.featureflags.FeatureFlagsProvider) { + featureFlagsProvider.setInitialFlags(flagsData); +}); + +myApp.run(function ($q: angular.IQService, $http: angular.IHttpService, featureFlags: angular.featureflags.FeatureFlagsService) { + let deferred = $q.defer(); + deferred.resolve(flagsData); + + featureFlags.set(deferred.promise); + + featureFlags.set($http.get('/data/flags.json')); +}); \ No newline at end of file diff --git a/angular-feature-flags/angular-feature-flags.d.ts b/angular-feature-flags/angular-feature-flags.d.ts new file mode 100644 index 0000000000..99ef300976 --- /dev/null +++ b/angular-feature-flags/angular-feature-flags.d.ts @@ -0,0 +1,38 @@ +// Type definitions for angular-feature-flags 1.4.0 +// Project: https://github.com/mjt01/angular-feature-flags +// Definitions by: Borislav Zhivkov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.featureflags { + export interface FlagData { + /** + * Unique key that is used from the markup to resolve whether a flag is active or not. + */ + key: string; + + /** + * Boolean value for enabling/disabling the feature + */ + active: boolean; + + /** + * A short name of the flag (only visible in the list of flags) + */ + name: string; + + /** + * A long description of the flag to further explain the feature being toggled (only visible in the list of flags) + */ + description: string; + } + + export interface FeatureFlagsProvider { + setInitialFlags(flags: Array): void; + } + + export interface FeatureFlagsService { + set(flagsPromise: angular.IPromise | angular.IHttpPromise): void; + } +} \ No newline at end of file diff --git a/angular-gettext/angular-gettext.d.ts b/angular-gettext/angular-gettext.d.ts index 48734d4433..84721d8dc0 100644 --- a/angular-gettext/angular-gettext.d.ts +++ b/angular-gettext/angular-gettext.d.ts @@ -51,12 +51,12 @@ declare namespace angular.gettext { /** Get the correct pluralized (but untranslated) string for the value of n. */ getStringForm(string: string, n: number): string; - /** Translate a string with the given context. Uses Angular.JS interpolation, so something like this will do what you expect: + /** Translate a string with the given scope. Uses Angular.JS interpolation, so something like this will do what you expect: * var hello = gettextCatalog.getString("Hello {{name}}!", { name: "Ruben" }); * // var hello will be "Hallo Ruben!" in Dutch. - * The context parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster. + * The scope parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster. */ - getString(string: string, context?: any): string; + getString(string: string, scope?: any, context?: string): string; /** Translate a plural string with the given context. */ getPlural(n: number, string: string, stringPlural: string, context?: any): string; diff --git a/angular-jwt/angular-jwt-tests.ts b/angular-jwt/angular-jwt-tests.ts index 3a6b7d6bf1..818899e829 100644 --- a/angular-jwt/angular-jwt-tests.ts +++ b/angular-jwt/angular-jwt-tests.ts @@ -15,3 +15,18 @@ var $jwtInterceptor: ng.jwt.IJwtInterceptor; $jwtInterceptor.tokenGetter = () => { return expToken; } + + +var authManager: ng.jwt.IAuthManagerServiceProvider; + +// Indicate the user is authenticated +authManager.authenticate(); + +// Indicate the user is unauthenticated +authManager.unauthenticate(); + +// Keep the user authenticated +authManager.checkAuthOnRefresh(); + +// Redirect the user on unauthorized requests +authManager.redirectWhenUnauthenticated(); \ No newline at end of file diff --git a/angular-jwt/angular-jwt.d.ts b/angular-jwt/angular-jwt.d.ts index eb02cf24df..d1f9eb085f 100644 --- a/angular-jwt/angular-jwt.d.ts +++ b/angular-jwt/angular-jwt.d.ts @@ -27,4 +27,11 @@ declare namespace angular.jwt { interface IJwtInterceptor { tokenGetter(...params : any[]): string; } + + interface IAuthManagerServiceProvider { + authenticate(): void; + unauthenticate(): void; + checkAuthOnRefresh(): void; + redirectWhenUnauthenticated(): void; + } } diff --git a/angular-material/angular-material-tests.ts b/angular-material/angular-material-tests.ts index 8e2bdfdf43..552ba7a95e 100644 --- a/angular-material/angular-material-tests.ts +++ b/angular-material/angular-material-tests.ts @@ -30,7 +30,11 @@ myApp.config(( myApp.controller('BottomSheetController', ($scope: ng.IScope, $mdBottomSheet: ng.material.IBottomSheetService) => { $scope['openBottomSheet'] = () => { $mdBottomSheet.show({ - template: 'Hello!' + template: 'Hello!', + clickOutsideToClose: true, + disableBackdrop: true, + disableParentScroll: false, + parent: () => {} }); }; $scope['hideBottomSheet'] = $mdBottomSheet.hide.bind($mdBottomSheet, 'hide'); @@ -115,15 +119,41 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia $scope['close'] = () => $mdSidenav(componentId).close(); $scope['isOpen'] = $mdSidenav(componentId).isOpen(); $scope['isLockedOpen'] = $mdSidenav(componentId).isLockedOpen(); + + $scope['asyncLookup'] = $mdSidenav(componentId, true).then((instance) => { + instance.toggle(); + instance.open(); + instance.close(); + instance.isOpen(); + instance.isLockedOpen(); + }); + + $scope['onClose'] = $mdSidenav(componentId).onClose(() => {}); }); myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => { - $scope['openToast'] = () => $mdToast.show($mdToast.simple().textContent('Hello!')); + $scope['openToast'] = () => { + $mdToast.show($mdToast.simple().textContent('Hello!')); + $mdToast.updateTextContent('New Content'); + } + + $scope['customToast'] = () => { + var options = { + hideDelay: 3000, + position: 'top right', + controller : 'ToastCtrl', + templateUrl : 'toast-template.html', + toastClass: 'my-class' + }; + + $mdToast.show(options); + } }); myApp.controller('PanelController', ($scope: ng.IScope, $mdPanel: ng.material.IPanelService) => { $scope['createPanel'] = () => { var config = { + id: 'myPanel', template: '

      Hello!

      ', hasBackdrop: true, disableParentScroll: true, diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index 2769945a7b..3fa0290904 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular Material 1.0.0-rc5+ (angular.material module) +// Type definitions for Angular Material 1.1.0-rc5+ (angular.material module) // Project: https://github.com/angular/material // Definitions by: Alex Staroselsky , Blake Bigelow , Peter Hajdu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -19,11 +19,12 @@ declare namespace angular.material { preserveScope?: boolean; // default: false controller?: string|Function; locals?: {[index: string]: any}; - targetEvent?: MouseEvent; - resolve?: {[index: string]: angular.IPromise} + clickOutsideToClose?: boolean; + disableBackdrop?: boolean; + escapeToClose?: boolean; + resolve?: {[index: string]: () => angular.IPromise}; controllerAs?: string; - bindToController?: boolean; - parent?: string|Element|JQuery; // default: root node + parent?: Function|string|Object; // default: root node disableParentScroll?: boolean; // default: true } @@ -52,7 +53,7 @@ declare namespace angular.material { controller(controller?: string|Function): T; locals(locals?: {[index: string]: any}): T; bindToController(bindToController?: boolean): T; // default: false - resolve(resolve?: {[index: string]: angular.IPromise}): T; + resolve(resolve?: {[index: string]: () => angular.IPromise}): T; controllerAs(controllerAs?: string): T; parent(parent?: string|Element|JQuery): T; // default: root node onComplete(onComplete?: Function): T; @@ -90,7 +91,7 @@ declare namespace angular.material { controller?: string|Function; locals?: {[index: string]: any}; bindToController?: boolean; // default: false - resolve?: {[index: string]: angular.IPromise} + resolve?: {[index: string]: () => angular.IPromise} controllerAs?: string; parent?: string|Element|JQuery; // default: root node onShowing?: Function; @@ -131,9 +132,11 @@ declare namespace angular.material { close(): angular.IPromise; isOpen(): boolean; isLockedOpen(): boolean; + onClose(onClose: Function): void; } interface ISidenavService { + (component: string, enableWait: boolean): angular.IPromise; (component: string): ISidenavObject; } @@ -160,10 +163,11 @@ declare namespace angular.material { preserveScope?: boolean; // default: false hideDelay?: number; // default (ms): 3000 position?: string; // any combination of 'bottom'/'left'/'top'/'right'/'fit'; default: 'bottom left' + toastClass?: string; controller?: string|Function; locals?: {[index: string]: any}; bindToController?: boolean; // default: false - resolve?: {[index: string]: angular.IPromise} + resolve?: {[index: string]: () => angular.IPromise} controllerAs?: string; parent?: string|Element|JQuery; // default: root node } @@ -173,7 +177,8 @@ declare namespace angular.material { showSimple(content: string): angular.IPromise; simple(): ISimpleToastPreset; build(): IToastPreset; - updateContent(): void; + updateContent(newContent: string): void; + updateTextContent(newContent: string): void hide(response?: any): void; cancel(response?: any): void; } @@ -245,6 +250,7 @@ declare namespace angular.material { extendPalette(name: string, palette: IPalette): IPalette; setDefaultTheme(theme: string): void; alwaysWatchTheme(alwaysWatch: boolean): void; + setNonce(nonce: string): void; } interface IDateLocaleProvider { @@ -288,14 +294,16 @@ declare namespace angular.material { } interface IPanelConfig { + id?: string; template?: string; templateUrl?: string; controller?: string|Function; controllerAs?: string; bindToController?: boolean; // default: true locals?: {[index: string]: any}; - resolve?: {[index: string]: angular.IPromise} + resolve?: {[index: string]: () => angular.IPromise} attachTo?: string|JQuery|Element; + propagateContainerEvents?: boolean; panelClass?: string; zIndex?: number; // default: 80 position?: IPanelPosition; @@ -328,16 +336,18 @@ declare namespace angular.material { addClass(newClass: string): void; removeClass(oldClass: string): void; toggleClass(toggleClass: string): void; - focusOnOpen(): void; + updatePosition(position: IPanelPosition): void; } interface IPanelPosition { absolute(): IPanelPosition; relativeTo(someElement: string|JQuery|Element): IPanelPosition; - top(opt_top: string): IPanelPosition; // default: '0' - bottom(opt_bottom: string): IPanelPosition; // default: '0' - left(opt_left: string): IPanelPosition; // default: '0' - right(opt_right: string): IPanelPosition; // default: '0' + top(top?: string): IPanelPosition; // default: '0' + bottom(bottom?: string): IPanelPosition; // default: '0' + start(start?: string): IPanelPosition; // default: '0' + end(end?: string): IPanelPosition; // default: '0' + left(left?: string): IPanelPosition; // default: '0' + right(right?: string): IPanelPosition; // default: '0' centerHorizontally(): IPanelPosition; centerVertically(): IPanelPosition; center(): IPanelPosition; @@ -357,5 +367,24 @@ declare namespace angular.material { open(opt_config: IPanelConfig): angular.IPromise; newPanelPosition(): IPanelPosition; newPanelAnimation(): IPanelAnimation; + xPosition: { + CENTER: string, + ALIGN_START: string, + ALIGN_END: string, + OFFSET_START: string, + OFFSET_END: string, + }; + yPosition: { + CENTER: string, + ALIGN_TOPS: string, + ALIGN_BOTTOMS: string, + ABOVE: string, + BELOW: string, + }; + animation: { + SLIDE: string, + SCALE: string, + FADE: string, + }; } } diff --git a/angular-permission/angular-permission-tests.ts b/angular-permission/angular-permission-tests.ts index cc9cd7c367..c6d5b91a8d 100644 --- a/angular-permission/angular-permission-tests.ts +++ b/angular-permission/angular-permission-tests.ts @@ -1,10 +1,11 @@ /// -import permission = angular.permission; +import permissionNamespace = angular.permission; +import { permission, ngPermission, uiPermission } from "angular-permission"; angular - .module('fooModule', ['permission', 'user']) - .run(function (PermissionStore: permission.PermissionStore, User: any) { + .module('fooModule', [permission, ngPermission, uiPermission, 'user']) + .run(function (PermissionStore: permissionNamespace.PermissionStore, User: any) { // Define anonymous permission PermissionStore .definePermission('anonymous', function (stateParams) { @@ -22,8 +23,8 @@ angular hasPermissionDefinition(permission: string) : angular.IPromise; } - angular.module('barModule', ['permission', 'user']) - .run(function (PermissionStore: permission.PermissionStore, User: BackendUserService, $q: angular.IQService) { + angular.module('barModule', [permission, 'user']) + .run(function (PermissionStore: permissionNamespace.PermissionStore, User: BackendUserService, $q: angular.IQService) { PermissionStore // Define user permission calling back-end .definePermission('user', function (stateParams) { @@ -64,14 +65,14 @@ angular PermissionStore.removePermissionDefinition('user'); - let permissions: Array = PermissionStore.getStore(); + let permissions: Array = PermissionStore.getStore(); }); angular - .module('fooModule', ['permission', 'user']) - .run(function (RoleStore: permission.RoleStore, User: any) { + .module('fooModule', [permission, 'user']) + .run(function (RoleStore: permissionNamespace.RoleStore, User: any) { RoleStore // Permission array validated role // Library will internally validate if 'user' and 'editor' permissions are valid when checking if role is valid @@ -88,5 +89,5 @@ angular RoleStore.removeRoleDefinition('user'); - let roles: Array = RoleStore.getStore(); + let roles: Array = RoleStore.getStore(); }); diff --git a/angular-permission/angular-permission.d.ts b/angular-permission/angular-permission.d.ts index fecbafb29b..138c8892ce 100644 --- a/angular-permission/angular-permission.d.ts +++ b/angular-permission/angular-permission.d.ts @@ -173,3 +173,9 @@ declare namespace angular.permission { options?: angular.ui.IStateOptions; } } + +declare module "angular-permission" { + export var permission: string; + export var ngPermission: string; + export var uiPermission: string; +} diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 51946281ce..0187e33cab 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -13,7 +13,7 @@ declare module "angular-translate" { declare namespace angular.translate { interface ITranslationTable { - [key: string]: any; + [key: string]: string | ITranslationTable; } interface ILanguageKeyAlias { @@ -95,8 +95,9 @@ declare namespace angular.translate { use(key: string): ITranslateProvider; storageKey(): string; storageKey(key: string): void; // JeroMiya - the library should probably return ITranslateProvider but it doesn't here + uniformLanguageTag(options: string | Object): ITranslateProvider; useUrlLoader(url: string): ITranslateProvider; - useStaticFilesLoader(options: IStaticFilesLoaderOptions): ITranslateProvider; + useStaticFilesLoader(options: IStaticFilesLoaderOptions | { files: IStaticFilesLoaderOptions[] }): ITranslateProvider; useLoader(loaderFactory: string, options?: any): ITranslateProvider; useLocalStorage(): ITranslateProvider; useCookieStorage(): ITranslateProvider; diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index 38a1c321bd..d6c389146b 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -393,6 +393,24 @@ declare namespace angular.ui.bootstrap { */ windowTopClass?: string; + + /** + * Appends the modal to a specific element. + * + * @default 'body' + */ + appendTo?: angular.IAugmentedJQuery; + + /** + * A string reference to the component to be rendered that is registered with Angular's compiler. If using a directive, the directive must have `restrict: 'E'` and a template or templateUrl set. + * + * It supports these bindings: + * - `close` - A method that can be used to close a modal, passing a result. The result must be passed in this format: `{$value: myResult}` + * - `dismiss` - A method that can be used to dismiss a modal, passing a result. The result must be passed in this format: `{$value: myRejectedResult}` + * - `modalInstance` - The modal instance. This is the same `$uibModalInstance` injectable found when using `controller`. + * - `resolve` - An object of the modal resolve values. See [UI Router resolves] for details. + */ + component?: string; } interface IModalStackService { diff --git a/angular-ui-notification/angular-ui-notification-tests.ts b/angular-ui-notification/angular-ui-notification-tests.ts new file mode 100644 index 0000000000..3039a74c9e --- /dev/null +++ b/angular-ui-notification/angular-ui-notification-tests.ts @@ -0,0 +1,30 @@ +/// + +function TestNotifications(NotificationProvider: angular.uiNotification.INotificationProvider, Notification: angular.uiNotification.INotificationService) { + NotificationProvider.setOptions({ + delay: 10000, + startTop: 20, + startRight: 10, + verticalSpacing: 20, + horizontalSpacing: 20, + positionX: 'left', + positionY: 'bottom' + }); + + Notification.primary('Primary notification'); + Notification('Primary notification'); + + Notification.success('Success notification'); + + Notification({message: 'Warning notification'}, 'warning'); + + Notification({message: 'Primary notification', title: 'Primary notification'}); + + Notification.error({message: 'Error notification 1s', delay: 1000}); + + Notification.success({message: 'Success notification
      Some other content
      This is a link
      ', title: 'Html content'}); + + Notification.error({message: 'Error Bottom Right', positionY: 'bottom', positionX: 'right'}); + + Notification.error({message: 'Error notification 1s', replaceMessage: true}); +} \ No newline at end of file diff --git a/angular-ui-notification/angular-ui-notification.d.ts b/angular-ui-notification/angular-ui-notification.d.ts new file mode 100644 index 0000000000..48215e6d42 --- /dev/null +++ b/angular-ui-notification/angular-ui-notification.d.ts @@ -0,0 +1,82 @@ +// Type definitions for angular-ui-notification +// Project: https://github.com/alexcrack/angular-ui-notification +// Definitions by: Kamil Rojewski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace angular.uiNotification { + // Taken from angular to avoid dependency + interface IPromise { + /** + * Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected. + * The successCallBack may return IPromise for when a $q.reject() needs to be returned + * This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method. + */ + then(successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + + /** + * Shorthand for promise.then(null, errorCallback) + */ + catch(onRejected: (reason: any) => IPromise|TResult): IPromise; + + /** + * Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information. + * + * Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible. + */ + finally(finallyCallback: () => any): IPromise; + } + + type XPosition = 'right'|'left'|'center'; + type YPosition = 'top'|'bottom'; + + type MessageType = 'primary'|'info'|'success'|'warning'|'error'; + + interface IGlobalMessageOptions { + delay?: number; + startTop?: number; + startRight?: number; + verticalSpacing?: number; + horizontalSpacing?: number; + positionX?: XPosition; + positionY?: YPosition; + replaceMessage?: boolean; + templateUrl?: string; + onClose?: (element: any) => any; + closeOnClick?: boolean; + maxCount?: number; + } + + interface IMessageOptions { + title?: string; + message?: string; + templateUrl?: string; + delay?: number; + type?: MessageType; + positionX?: XPosition; + positionY?: YPosition; + replaceMessage?: boolean; + closeOnClick?: boolean; + } + + interface INotificationScope { + kill(isHard: boolean): void; + } + + interface INotificationProvider { + setOptions(options: IGlobalMessageOptions): void; + } + + type Message = string|IMessageOptions; + + interface INotificationService { + primary(message: Message): IPromise; + info(message: Message): IPromise; + success(message: Message): IPromise; + warning(message: Message): IPromise; + error(message: Message): IPromise; + + clearAll(): void; + + (message: Message, type?: MessageType): IPromise; + } +} diff --git a/angular-ui-router/angular-ui-router-tests.ts b/angular-ui-router/angular-ui-router-tests.ts index 9c5db1754a..a588faa448 100644 --- a/angular-ui-router/angular-ui-router-tests.ts +++ b/angular-ui-router/angular-ui-router-tests.ts @@ -1,6 +1,7 @@ /// -var myApp = angular.module('testModule'); +import uiRouterModule from "angular-ui-router"; +var myApp = angular.module("testModule", [uiRouterModule]); interface MyAppScope extends ng.IScope { items: string[]; @@ -141,7 +142,7 @@ class UrlLocatorTestService implements IUrlLocatorTestService { private $state: ng.ui.IStateService ) { $rootScope.$on("$locationChangeSuccess", (event: ng.IAngularEvent) => this.onLocationChangeSuccess(event)); - $rootScope.$on('$stateNotFound', (event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) => + $rootScope.$on('$stateNotFound', (event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) => this.onStateNotFound(event, unfoundState, fromState, fromParams)); } @@ -164,14 +165,14 @@ class UrlLocatorTestService implements IUrlLocatorTestService { }); } } - + private onStateNotFound(event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) { var unfoundTo: string = unfoundState.to; var unfoundToParams: {} = unfoundState.toParams; - var unfoundOptions: ng.ui.IStateOptions = unfoundState.options + var unfoundOptions: ng.ui.IStateOptions = unfoundState.options } private stateServiceTest() { diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index 88f00c9b5d..7e4f097c8c 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -7,13 +7,7 @@ // Support for AMD require and CommonJS declare module 'angular-ui-router' { - // Since angular-ui-router adds providers for a bunch of - // injectable dependencies, it doesn't really return any - // actual data except the plain string 'ui.router'. - // - // As such, I don't think anybody will ever use the actual - // default value of the module. So I've only included the - // the types. (@xogeny) + export default "ui.router"; export type IState = angular.ui.IState; export type IStateProvider = angular.ui.IStateProvider; export type IUrlMatcher = angular.ui.IUrlMatcher; @@ -44,6 +38,10 @@ declare namespace angular.ui { * Function, returns HTML content string */ templateProvider?: Function | Array; + /** + * String, component name + */ + component?: string; /** * A controller paired to the state. Function, annotated array or name as String */ @@ -105,7 +103,7 @@ declare namespace angular.ui { toParams: {}, options: IStateOptions } - + interface IStateProvider extends angular.IServiceProvider { state(name:string, config:IState): IStateProvider; state(config:IState): IStateProvider; diff --git a/angular-ui-scroll/angular-ui-scroll.d.ts b/angular-ui-scroll/angular-ui-scroll.d.ts index 168c6ba271..5f24c8ec38 100644 --- a/angular-ui-scroll/angular-ui-scroll.d.ts +++ b/angular-ui-scroll/angular-ui-scroll.d.ts @@ -42,9 +42,10 @@ declare namespace angular.ui { */ topVisibleScope: ng.IRepeatScope; /** - * calling this method reinitializes and reloads the scroller content. + * calling this method reinitializes and reloads the scroller content. + * @param startIndex is an integer indicating what item index the scroller will use to start the load process. */ - reload(): void; + reload(startIndex?: number): void; /** * Replaces the item in the buffer at the given index with the new items. * diff --git a/angular-websocket/angular-websocket-tests.ts b/angular-websocket/angular-websocket-tests.ts index 980e2001d3..e7cb30fe49 100644 --- a/angular-websocket/angular-websocket-tests.ts +++ b/angular-websocket/angular-websocket-tests.ts @@ -2,11 +2,35 @@ let dummySocket: ng.websocket.IWebSocket; let dummyPromise: ng.IPromise; +let dummyScope: ng.IScope; -let provider: ng.websocket.IWebSocketProvider = (url: string) => { +let provider: ng.websocket.IWebSocketProvider = (url: string, protocols?:string[] | ng.websocket.IWebSocketConfigOptions, options?: ng.websocket.IWebSocketConfigOptions) => { return dummySocket; } +let socketWithProtocol = provider("wss://localhost", "protocol"); +let socketWithProtocols = provider("wss://localhost", ["protocol-a", "protocol-b"]); + +let socketWithOptions = provider("wss://localhost", { + scope: dummyScope, + rootScopeFailOver: true, + useApplyAsync: true, + initialTimeout: 100, + maxTimeout: 300000, + reconnectIfNotNormalClose: true, + binaryType: "blob" +}); + +let socketWithProtocolAndOptions = provider("wss://localhost", "protocol", { + scope: dummyScope, + rootScopeFailOver: true, + useApplyAsync: true, + initialTimeout: 100, + maxTimeout: 300000, + reconnectIfNotNormalClose: true, + binaryType: "blob" +}); + let socket = provider("wss://localhost"); socket.onOpen((event) => {}) diff --git a/angular-websocket/angular-websocket.d.ts b/angular-websocket/angular-websocket.d.ts index a01e5eab3e..6929561f9c 100644 --- a/angular-websocket/angular-websocket.d.ts +++ b/angular-websocket/angular-websocket.d.ts @@ -7,6 +7,18 @@ declare namespace angular.websocket { + /** + * Options available to be specified for IWebSocketProvider. + */ + type IWebSocketConfigOptions = { + scope?: ng.IScope; + rootScopeFailOver?: boolean; + useApplyAsync?: boolean; + initialTimeout?: number; + maxTimeout?: number; + binaryType?: "blob" | "arraybuffer"; + reconnectIfNotNormalClose?: boolean; + } interface IWebSocketProvider { /** * Creates and opens an IWebSocket instance. @@ -14,7 +26,7 @@ declare namespace angular.websocket { * @param url url to connect to * @return websocket instance */ - (url: string): IWebSocket; + (url: string, protocols?: string | string[] | IWebSocketConfigOptions, options?: IWebSocketConfigOptions): IWebSocket; } /** Options available to be specified for IWebSocket.onMessage */ diff --git a/angular-xeditable/angular-xeditable-tests.ts b/angular-xeditable/angular-xeditable-tests.ts new file mode 100644 index 0000000000..9264c47f41 --- /dev/null +++ b/angular-xeditable/angular-xeditable-tests.ts @@ -0,0 +1,15 @@ +/// + +var myApp = angular.module('testModule', ['xeditable']); + +myApp.run(["editableOptions", (editableOptions: angular.xeditable.IEditableOptions) => { + + editableOptions.activate = "select"; + editableOptions.activationEvent = "click"; + editableOptions.blurElem = "ignore"; + editableOptions.blurForm = "submit"; + editableOptions.buttons = "no"; + editableOptions.icon_set = "font-awesome"; + editableOptions.isDisabled = true; + editableOptions.theme = "bs3"; +}]); \ No newline at end of file diff --git a/angular-xeditable/angular-xeditable.d.ts b/angular-xeditable/angular-xeditable.d.ts new file mode 100644 index 0000000000..026fc5d2fb --- /dev/null +++ b/angular-xeditable/angular-xeditable.d.ts @@ -0,0 +1,98 @@ +// Type definitions for Angular xEditable 0.2.0 (angular.xeditable module) +// Project: https://vitalets.github.io/angular-xeditable/ +// Definitions by: Joao Monteiro +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.xeditable { + + interface IEditableOptions { + + /** + * Theme. Possible values `bs3`, `bs2`, `default` + */ + theme: string; + + /** + * Icon Set. Possible values `font-awesome`, `default`. + */ + icon_set: string; + + /** + * Whether to show buttons for single editalbe element. + * Possible values `right` (default), `no`. + */ + buttons: string; + + /** + * Default value for `blur` attribute of single editable element. + * Can be `cancel|submit|ignore`. + */ + blurElem: string; + + /** + * Default value for `blur` attribute of editable form. + * Can be `cancel|submit|ignore`. + */ + blurForm: string; + + /** + * How input elements get activated. Possible values: `focus|select|none`. + */ + activate: string; + + /** + * Whether to disable x-editable. Can be overloaded on each element. + */ + isDisabled: boolean; + + /* + * Event, on which the edit mode gets activated. + * Can be any event. + */ + activationEvent: string; + } + + interface IEditableFormController extends angular.IFormController { + + /** + * Shows form with editable controls. + */ + $show(): void; + + /** + * Hides form with editable controls without saving. + */ + $hide(): void; + + /** + * Sets focus on form field specified by `name`.
      + * When trying to set the focus on a form field of a new row in the editable table, the `$activate` call needs to be wrapped in a `$timeout` call so that the form is rendered before the `$activate` function is called. + * + * @param name name of field + */ + $activate(name: string): void; + + /** + * Triggers `oncancel` event and calls `$hide()`. + */ + $cancel(): void; + + $setWaiting(value: boolean): void; + + /** + * Shows error message for particular field. + * + * @param name name of field + * @param msg error message + */ + $setError(name: string, msg: string): void; + + $submit(): void; + + $save(): void; + + } + +} diff --git a/angularjs/angular-animate.d.ts b/angularjs/angular-animate.d.ts index daae229f56..2451976bf5 100644 --- a/angularjs/angular-animate.d.ts +++ b/angularjs/angular-animate.d.ts @@ -69,8 +69,8 @@ declare namespace angular.animate { * @param value If provided then set the animation on or off. * @returns current animation state */ + enabled(value?: boolean): boolean; enabled(element: JQuery, value?: boolean): boolean; - enabled(value: boolean): boolean; /** * Cancels the provided animation. diff --git a/angularjs/angular-component-router.d.ts b/angularjs/angular-component-router.d.ts index 3b037b58b1..94d7dd7359 100644 --- a/angularjs/angular-component-router.d.ts +++ b/angularjs/angular-component-router.d.ts @@ -476,7 +476,7 @@ declare namespace angular { // Supplement IComponentOptions from angular.d.ts with router-specific // fields. interface IComponentOptions { - $canActivate?: () => boolean; + $canActivate?: (...args: any[]) => boolean | angular.IPromise; $routeConfig?: RouteDefinition[]; } } diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index 441a7e1d3d..f7e803c1c8 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -42,15 +42,20 @@ declare namespace angular.resource { (url: string, paramDefaults?: any, /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): IResourceClass>; + actions?: IActionHash, options?: IResourceOptions): IResourceClass>; (url: string, paramDefaults?: any, /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): U; + actions?: IActionHash, options?: IResourceOptions): U; (url: string, paramDefaults?: any, /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): IResourceClass; + actions?: IActionHash, options?: IResourceOptions): IResourceClass; + } + + // Hash of action descriptors allows custom action names + interface IActionHash { + [action: string]: IActionDescriptor } // Just a reference to facilitate describing new actions @@ -186,6 +191,12 @@ declare namespace angular { /** creating a resource service factory */ factory(name: string, resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction): IModule; } + + namespace auto { + interface IInjectorService { + get(name: '$resource'): ng.resource.IResourceService; + } + } } interface Array diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 7eaf0be763..07f67a7375 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -867,6 +867,26 @@ angular.module('docsTabsExample', []) }; }); +angular.module('multiSlotTranscludeExample', []) + .directive('dropDownMenu', function() { + return { + transclude: { + button: 'button', + list: 'ul', + }, + link: function(scope, element, attrs, ctrl, transclude) { + // without scope + transclude().appendTo(element); + transclude(clone => clone.appendTo(element)); + + // with scope + transclude(scope, clone => clone.appendTo(element)); + transclude(scope, clone => clone.appendTo(element), element, 'button'); + transclude(scope, null, element, 'list').addClass('drop-down-list').appendTo(element); + } + }; + }); + angular.module('componentExample', []) .component('counter', { require: {'ctrl': '^ctrl'}, @@ -1098,6 +1118,12 @@ function parseTyping() { } } +function parseWithParams() { + var $parse: angular.IParseService; + var compiledExp = $parse('a.b.c', () => null); + var compiledExp = $parse('a.b.c', null, false); +} + function doBootstrap(element: Element | JQuery, mode: string): ng.auto.IInjectorService { if (mode === 'debug') { return angular.bootstrap(element, ['main', function($provide: ng.auto.IProvideService) { @@ -1105,11 +1131,11 @@ function doBootstrap(element: Element | JQuery, mode: string): ng.auto.IInjector $delegate['debug'] = true; }); }, 'debug-helpers'], { - debugInfoEnabled: true + strictDi: true }); } return angular.bootstrap(element, ['main'], { - debugInfoEnabled: false + strictDi: false }); } diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 15e9ec2043..c9e95bcc98 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular JS 1.5 // Project: http://angularjs.org -// Definitions by: Diego Vilar +// Definitions by: Diego Vilar , Georgii Dolzhykov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -41,7 +41,6 @@ declare namespace angular { interface IAngularBootstrapConfig { strictDi?: boolean; - debugInfoEnabled?: boolean; } /////////////////////////////////////////////////////////////////////////// @@ -119,14 +118,15 @@ declare namespace angular { fromJson(json: string): any; identity(arg?: T): T; injector(modules?: any[], strictDi?: boolean): auto.IInjectorService; - isArray(value: any): boolean; - isDate(value: any): boolean; + isArray(value: any): value is Array; + isDate(value: any): value is Date; isDefined(value: any): boolean; isElement(value: any): boolean; - isFunction(value: any): boolean; - isNumber(value: any): boolean; - isObject(value: any): boolean; - isString(value: any): boolean; + isFunction(value: any): value is Function; + isNumber(value: any): value is number; + isObject(value: any): value is Object; + isObject(value: any): value is T; + isString(value: any): value is string; isUndefined(value: any): boolean; lowercase(str: string): string; @@ -388,6 +388,7 @@ declare namespace angular { $invalid: boolean; $submitted: boolean; $error: any; + $name: string; $pending: any; $addControl(control: INgModelController | IFormController): void; $removeControl(control: INgModelController | IFormController): void; @@ -874,7 +875,7 @@ declare namespace angular { // see http://docs.angularjs.org/api/ng.$parseProvider /////////////////////////////////////////////////////////////////////////// interface IParseService { - (expression: string): ICompiledExpression; + (expression: string, interceptorFn?: (value: any, scope: IScope, locals: any) => any, expensiveChecks?: boolean): ICompiledExpression; } interface IParseProvider { @@ -986,7 +987,10 @@ declare namespace angular { // DocumentService // see http://docs.angularjs.org/api/ng.$document /////////////////////////////////////////////////////////////////////////// - interface IDocumentService extends JQuery {} + interface IDocumentService extends JQuery { + // Must return intersection type for index signature compatibility with JQuery + [index: number]: HTMLElement & Document; + } /////////////////////////////////////////////////////////////////////////// // ExceptionHandlerService @@ -1255,7 +1259,7 @@ declare namespace angular { // This corresponds to $transclude (and also the transclude function passed to link). interface ITranscludeFunction { // If the scope is provided, then the cloneAttachFn must be as well. - (scope: IScope, cloneAttachFn: ICloneAttachFunction): JQuery; + (scope: IScope, cloneAttachFn: ICloneAttachFunction, futureParentElement?: JQuery, slotName?: string): JQuery; // If one argument is provided, then it's assumed to be the cloneAttachFn. (cloneAttachFn?: ICloneAttachFunction): JQuery; } @@ -1408,6 +1412,16 @@ declare namespace angular { * Absolute or relative URL of the resource that is being requested. */ url: string; + /** + * Event listeners to be bound to the XMLHttpRequest object. + * To bind events to the XMLHttpRequest upload object, use uploadEventHandlers. The handler will be called in the context of a $apply block. + */ + eventHandlers?: { [type: string]: EventListenerOrEventListenerObject }; + /** + * Event listeners to be bound to the XMLHttpRequest upload object. + * To bind events to the XMLHttpRequest object, use eventHandlers. The handler will be called in the context of a $apply block. + */ + uploadEventHandlers?: { [type: string]: EventListenerOrEventListenerObject }; } interface IHttpHeadersGetter { @@ -1716,13 +1730,19 @@ declare namespace angular { * Whether transclusion is enabled. Enabled by default. */ transclude?: boolean | string | {[slot: string]: string}; + /** + * Requires the controllers of other directives and binds them to this component's controller. + * The object keys specify the property names under which the required controllers (object values) will be bound. + * Note that the required controllers will not be available during the instantiation of the controller, + * but they are guaranteed to be available just before the $onInit method is executed! + */ require?: {[controller: string]: string}; } interface IComponentTemplateFn { ( $element?: JQuery, $attrs?: IAttributes ): string; } - + /** * Components have a well-defined lifecycle Each component can implement "lifecycle hooks". These are methods that * will be called at certain points in the life of the component. @@ -1736,12 +1756,12 @@ declare namespace angular { */ $onInit?(): void; /** - * Called whenever one-way bindings are updated. The changesObj is a hash whose keys are the names of the bound - * properties that have changed, and the values are an {@link IChangesObject} object of the form + * Called whenever one-way bindings are updated. The onChangesObj is a hash whose keys are the names of the bound + * properties that have changed, and the values are an {@link IChangesObject} object of the form * { currentValue, previousValue, isFirstChange() }. Use this hook to trigger updates within a component such as * cloning the bound value to prevent accidental mutation of the outer value. */ - $onChanges?(changesObj: {[property:string]: IChangesObject}): void; + $onChanges?(onChangesObj: IOnChangesObject): void; /** * Called on a controller when its containing scope is destroyed. Use this hook for releasing external resources, * watches and event handlers. @@ -1757,6 +1777,10 @@ declare namespace angular { */ $postLink?(): void; } + + interface IOnChangesObject { + [property: string]: IChangesObject; + } interface IChangesObject { currentValue: any; @@ -1816,7 +1840,7 @@ declare namespace angular { bindToController?: boolean | Object; link?: IDirectiveLinkFn | IDirectivePrePost; multiElement?: boolean; - name?: string; + directiveName?: string; priority?: number; /** * @deprecated diff --git a/angularjs/legacy/angular-1.4.d.ts b/angularjs/legacy/angular-1.4.d.ts index 22c504712e..2cb129dca1 100644 --- a/angularjs/legacy/angular-1.4.d.ts +++ b/angularjs/legacy/angular-1.4.d.ts @@ -886,7 +886,7 @@ declare namespace angular { // see http://docs.angularjs.org/api/ng.$parseProvider /////////////////////////////////////////////////////////////////////////// interface IParseService { - (expression: string): ICompiledExpression; + (expression: string, interceptorFn?: (value: any, scope: IScope, locals: any) => any, expensiveChecks?: boolean): ICompiledExpression; } interface IParseProvider { diff --git a/anydb-sql-migrations/anydb-sql-migrations.d.ts b/anydb-sql-migrations/anydb-sql-migrations.d.ts index 9ab421c3ac..98961266a9 100644 --- a/anydb-sql-migrations/anydb-sql-migrations.d.ts +++ b/anydb-sql-migrations/anydb-sql-migrations.d.ts @@ -3,7 +3,7 @@ // Definitions by: Gorgi Kosev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// declare module "anydb-sql-migrations" { @@ -31,4 +31,4 @@ declare module "anydb-sql-migrations" { items: MigrationTask[]; }) => any) => Promise; }; -} \ No newline at end of file +} diff --git a/aphrodite/aphrodite-tests.tsx b/aphrodite/aphrodite-tests.tsx new file mode 100644 index 0000000000..76d28ca43f --- /dev/null +++ b/aphrodite/aphrodite-tests.tsx @@ -0,0 +1,82 @@ +/// +/// + +import * as React from "react"; +import { StyleSheet, css, StyleSheetServer, StyleSheetTestUtils } from "aphrodite"; + +const styles = StyleSheet.create({ + red: { + backgroundColor: 'red' + }, + blue: { + backgroundColor: 'blue' + }, + hover: { + ':hover': { + backgroundColor: 'red' + } + }, + small: { + '@media (max-width: 600px)': { + backgroundColor: 'red', + } + } +}); + +const coolFont = { + fontFamily: "CoolFont", + fontStyle: "normal", + fontWeight: "normal", + src: "url('coolfont.woff2') format('woff2')" +}; + +const withFont = StyleSheet.create({ + headingText: { + fontFamily: coolFont, + fontSize: 20 + }, + bodyText: { + fontFamily: [coolFont, "sans-serif"], + fontSize: 12 + } +}); + + +class App extends React.Component<{}, {}> { + render() { + return
      + + This is red. + + + This turns red on hover. + + + This turns red when the browser is less than 600px width. + + + This is blue. + + + This is blue and turns red when the browser is less than + 600px width. + + + With font + +
      ; + } +} + +const output = StyleSheetServer.renderStatic(() => { + return "test"; +}); + +output.css.content; +output.css.renderedClassNames; +output.html; + +StyleSheet.rehydrate(output.css.renderedClassNames); + +StyleSheetTestUtils.suppressStyleInjection(); +StyleSheetTestUtils.clearBufferAndResumeStyleInjection(); diff --git a/aphrodite/aphrodite.d.ts b/aphrodite/aphrodite.d.ts new file mode 100644 index 0000000000..89d8646e54 --- /dev/null +++ b/aphrodite/aphrodite.d.ts @@ -0,0 +1,76 @@ +// Type definitions for Aphrodite 0.5.0 +// Project: https://github.com/Khan/aphrodite +// Definitions by: Alexey Svetliakov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "aphrodite" { + import * as React from "react"; + + /** + * Aphrodite style declaration + */ + export interface StyleDeclaration { + [key: string]: React.CSSProperties; + } + + interface StyleSheetStatic { + /** + * Create style sheet + */ + create(styles: T): T; + /** + * Rehydrate class names from server renderer + */ + rehydrate(renderedClassNames: string[]): void; + } + + export var StyleSheet: StyleSheetStatic; + /** + * Get class names from passed styles + */ + export function css(...styles: any[]): string; + + interface StaticRendererResult { + html: string; + css: { + content: string; + renderedClassNames: string[]; + } + } + + /** + * Utilities for using Aphrodite server-side. + */ + interface StyleSheetServerStatic { + renderStatic(renderFunc: () => string): StaticRendererResult; + } + + export var StyleSheetServer: StyleSheetServerStatic; + + interface StyleSheetTestUtilsStatic { + /** + * Prevent styles from being injected into the DOM. + * + * This is useful in situations where you'd like to test rendering UI + * components which use Aphrodite without any of the side-effects of + * Aphrodite happening. Particularly useful for testing the output of + * components when you have no DOM, e.g. testing in Node without a fake DOM. + * + * Should be paired with a subsequent call to + * clearBufferAndResumeStyleInjection. + */ + suppressStyleInjection(): void; + /** + * Opposite method of preventStyleInject. + */ + clearBufferAndResumeStyleInjection(): void; + } + + export var StyleSheetTestUtils: StyleSheetTestUtilsStatic; +} + +declare module "aphrodite/no-important" { + export * from "aphrodite"; +} diff --git a/apigee-access/apigee-access-tests.ts b/apigee-access/apigee-access-tests.ts new file mode 100644 index 0000000000..99baec8021 --- /dev/null +++ b/apigee-access/apigee-access-tests.ts @@ -0,0 +1,67 @@ +/// +import apigee from "apigee-access"; + +//Sample code from +// https://www.npmjs.com/package/apigee-access + +var request: any = null; + +// Variables +var val1 = apigee.getVariable(request, 'TestVariable'); + +apigee.setIntVariable(request, 'TestVariable', '123'); +apigee.setIntVariable(request, 'TestVariable2', 42); + +apigee.deleteVariable(request, 'TestVariable'); + +// Mode +console.log('The deployment mode is ' + apigee.getMode()); + +// Cache +var cache = apigee.getCache('cache'); +var customCache = apigee.getCache('MyCustomCache', + { resource: 'MyCustomrResource' }); +cache.put('key2', 'Hello, World!', 120); +cache.put('key4', 'Hello, World!', function (err: any) { +}); + +cache.get('key', function (err: any, data: any) { +}); + +cache.remove('key'); + +// Secure Vault +var orgVault = apigee.getVault('vault1', 'organization'); +orgVault.get('key1', function (err: any, secretValue: any) { +}); + +// Quota Service +var quota = apigee.getQuota(); +quota.apply({ identifier: 'Foo', allow: 10, timeUnit: 'hour' }, + function (err: any, result: any) { + console.log('Quota applied: %j', result); + }); + +quota.apply({ + identifier: 'Foo', + timeUnit: 'hour', + allow: 100 +}, quotaResult); + +quota.apply({ + identifier: 'Bar', + timeUnit: 'minute', + interval: 5, + allow: 500 +}, quotaResult); + +quota.apply({ + identifier: 'Foo', + timeUnit: 'hour', + allow: 100, + weight: 10 +}, quotaResult); + +function quotaResult(err: any, r: any) { + if (err) { console.error('Quota failed'); } +} \ No newline at end of file diff --git a/apigee-access/apigee-access.d.ts b/apigee-access/apigee-access.d.ts new file mode 100644 index 0000000000..af34724023 --- /dev/null +++ b/apigee-access/apigee-access.d.ts @@ -0,0 +1,58 @@ +// Type definitions for apigee-access +// Project: https://www.npmjs.com/package/apigee-access +// Definitions by: Casper Skydt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module ApigeeAccess { + + function getVariable(request: any, name: string): string | number | boolean; + function setVariable(request: any, name: string, value: string | number | boolean ): void; + function setIntVariable(request: any, name: string, value: string | number): void; + function deleteVariable(request: any, name: string): void; + function getCache(name: string, options?: CacheOptions): any; + function getVault(name: string, scope?: "organization" | "environment"): SecureVault; + function getQuota(options?: any): QuotaService; + function getMode(): "apigee" | "standalone"; + + interface CacheOptions{ + resource?: string; + scope?: "global" | "application" | "exclusive"; + defaultTtl?: number; + timeout?: number; + } + + interface Cache{ + put(key: string, data: any, ttl?: number, callback?: (err: any) => void): void; + get(key: string, callback: (err: any, data: any) => void): void; + remove(key: string, callback?: (err: any) => void): void; + } + + interface SecureVault{ + getKeys(callback: (err: any, data: any) => void): void; + get(key: string, callback: (err: any, data: any) => void): void; + } + + interface QuotaService{ + apply(options?: QuotaServiceApplyOptions, callback?: (err: any, data: QuotaServiceApplyCallbackData) => void): void; + } + + interface QuotaServiceApplyOptions{ + identifier: string; + timeUnit: "minute" | "hour" | "day" | "week" | "month"; + allow: number; + interval?: number; + weight?: number; + } + + interface QuotaServiceApplyCallbackData{ + used: number; + allowed: number; + isAllowed: boolean; + expiryTime: number; + timestamp: number; + } +} + +declare module "apigee-access"{ + export default ApigeeAccess; +} \ No newline at end of file diff --git a/app-root-path/app-root-path-tests.ts b/app-root-path/app-root-path-tests.ts new file mode 100644 index 0000000000..64d8cdab6b --- /dev/null +++ b/app-root-path/app-root-path-tests.ts @@ -0,0 +1,10 @@ +/// +import * as root from 'app-root-path'; + +let resolvedPath: string; +resolvedPath = root.resolve('../dir'); +resolvedPath = root.path; +resolvedPath = root.toString(); +let resolvedModule: any = root.require('app-root-path'); +root.setPath('C:\\app-root'); + diff --git a/app-root-path/app-root-path.d.ts b/app-root-path/app-root-path.d.ts new file mode 100644 index 0000000000..7cccc59e01 --- /dev/null +++ b/app-root-path/app-root-path.d.ts @@ -0,0 +1,39 @@ +// Type definitions for app-root-path 1.2.1 +// Project: https://github.com/inxilpro/node-app-root-path +// Definitions by: Shant Marouti +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'app-root-path' { + interface RootPath { + + /** + * Application root directory absolute path + * @type {string} + */ + path: string; + + /** + * Resolves relative path from root to absolute path + * @param {string} pathToModule + * @returns {string} + */ + resolve(pathToModule: string): string; + + /** + * Resolve module by relative addressing from root + * @param {string} pathToModule + * @returns {*} + */ + require(pathToModule: string): any; + + /** + * Explicitly set root path + * @param {string} explicitlySetPath + */ + setPath(explicitlySetPath: string): void; + + toString(): string; + } + var RootPath: RootPath; + export = RootPath; +} \ No newline at end of file diff --git a/applicationinsights-js/applicationinsights-js.d.ts b/applicationinsights-js/applicationinsights-js.d.ts index d9ad3c1c9d..ba154e5fe6 100644 --- a/applicationinsights-js/applicationinsights-js.d.ts +++ b/applicationinsights-js/applicationinsights-js.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ApplicationInsights-JS v0.22.14 +// Type definitions for ApplicationInsights-JS v0.23.2 // Project: https://github.com/Microsoft/ApplicationInsights-JS // Definitions by: Kamil Szostak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -788,3 +788,9 @@ declare module Microsoft.ApplicationInsights { _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error): any; } } + +declare module 'applicationinsights-js' { + export let AppInsights: Microsoft.ApplicationInsights.IAppInsights; +} + +declare var appInsights: Microsoft.ApplicationInsights.IAppInsights; \ No newline at end of file diff --git a/arcgis-js-api/arcgis-js-api.d.ts b/arcgis-js-api/arcgis-js-api.d.ts index 01d8a02c12..65765fbb09 100644 --- a/arcgis-js-api/arcgis-js-api.d.ts +++ b/arcgis-js-api/arcgis-js-api.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ArcGIS API for JavaScript v3.16 +// Type definitions for ArcGIS API for JavaScript v3.17 // Project: http://js.arcgis.com // Definitions by: Esri // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -18,7 +18,6 @@ declare module "esri" { import BasemapLayer = require("esri/dijit/BasemapLayer"); import Symbol = require("esri/symbols/Symbol"); import BookmarkItem = require("esri/dijit/BookmarkItem"); - import Units = require("esri/units"); import Color = require("esri/Color"); import LocationProviderBase = require("esri/tasks/locationproviders/LocationProviderBase"); import PictureMarkerSymbol = require("esri/symbols/PictureMarkerSymbol"); @@ -45,6 +44,7 @@ declare module "esri" { import QueryTask = require("esri/tasks/QueryTask"); import TextSymbol = require("esri/symbols/TextSymbol"); import StandardGeographyQueryTask = require("esri/tasks/geoenrichment/StandardGeographyQueryTask"); + import WMSLayerInfo = require("esri/layers/WMSLayerInfo"); import WMTSLayerInfo = require("esri/layers/WMTSLayerInfo"); export interface AGSMouseEvent extends MouseEvent { @@ -354,7 +354,7 @@ declare module "esri" { /** Radius of the circle. */ radius?: number; /** Unit of the radius. */ - radiusUnit?: Units; + radiusUnit?: string; } export interface CircleOptions2 { /** The center point of the circle. */ @@ -366,7 +366,7 @@ declare module "esri" { /** The radius of the circle. */ radius?: number; /** Unit of the radius. */ - radiusUnit?: Units; + radiusUnit?: string; } export interface ClassedColorSliderOptions { /** Data map containing renderer information. */ @@ -643,6 +643,8 @@ declare module "esri" { minStops?: number; /** When true, stops on the route are re-ordered to provide an optimal route. */ optimalRoute?: boolean; + /** If specified, this specifies the portal where the produced route layers are going to be stored and accessed. */ + portalUrl?: string; /** URL link to a custom print page. */ printPage?: string; /** If available, this print task is used to display an overview map of the route on the directions print page (Added at v3.11). */ @@ -677,6 +679,8 @@ declare module "esri" { showReturnToStartOption?: boolean; /** Display the 'Show Reverse Stops' button. */ showReverseStopsButton?: boolean; + /** Applicable if the widget works with a Network Analyst Server federated with ArcGIS Online or Portal. */ + showSaveButton?: boolean; /** Highlight the route segment when a directions step is clicked. */ showSegmentHighlight?: boolean; /** Display a popup with segment details when a direction step is clicked. */ @@ -911,6 +915,8 @@ declare module "esri" { layer: FeatureLayer; } export interface FeatureTableOptions { + /** The number of features a service will try to fetch. */ + batchCount?: number; /** Object defining the date options specifically for formatting date and time editors. */ dateOptions?: any; /** Sets the editing state for the FeatureTable. */ @@ -931,12 +937,18 @@ declare module "esri" { menuFunctions?: any[]; /** Attribute fields to include in the FeatureTable. */ outFields?: string[]; + /** Displays or hides the attachment column. */ + showAttachments?: boolean; /** Displays the data type of the field right under the field label. */ showDataTypes?: boolean; + /** Displays or hides total number of features and selected number of features in the grid header. */ + showFeatureCount?: boolean; /** Displays or hides the FeatureTable header. */ showGridHeader?: boolean; /** Displays or hides 'Options' drop-down menu of the FeatureTable. */ showGridMenu?: boolean; + /** Displays or hides the 'Statistics' option in column menus for numeric fields. */ + showStatistics?: boolean; /** Enables an interaction between the map and the feature table. */ syncSelection?: boolean; /** Enables pan/zoom to selected features on the map when the table in 'sync selection' mode. */ @@ -1187,10 +1199,20 @@ declare module "esri" { gdbVersion?: string; } export interface ImageServiceMeasureOptions { + /** The angular unit in which directions of line segments will be calculated. */ + angularUnit?: string; + /** The area unit in which areas of polygons will be calculated. */ + areaUnit?: string; + /** Defines whether to show the widget result in a popup or in the widget's result area when the widget has 'toolbar' layout. */ + displayMeasureResultInPopup?: boolean; /** Symbol to be used when drawing a polygon or extent. */ fillSymbol?: SimpleFillSymbol; /** Image service layer with which the toolbar is associated. */ layer: ArcGISImageServiceLayer; + /** Defines the layout of the widget. */ + layout?: string; + /** The linear unit in which height, length, or perimeters will be calculated. */ + linearUnit?: string; /** Symbol to be used when drawing a line. */ lineSymbol?: SimpleLineSymbol; /** Map instance with which the toolbar is associate. */ @@ -1402,9 +1424,9 @@ declare module "esri" { /** Flag for showing full list of units in the Location tool. */ advancedLocationUnits?: boolean; /** The default area unit for the measure area tool. */ - defaultAreaUnit?: Units; + defaultAreaUnit?: string; /** The default length unit for the measure distance tool. */ - defaultLengthUnit?: Units; + defaultLengthUnit?: string; /** Allows the user to immediately measure previously-created geometry on dijit creation. */ geometry?: Point | Polyline | Polygon; /** Line symbol used to draw the lines for the measure line and measure distance tools. */ @@ -2190,6 +2212,28 @@ declare module "esri" { /** The well-known ID of the spatial reference used by the WFSLayer. */ wkid?: string; } + export interface WMSLayerInfoOptions { + /** All the bounding extents defined for this layer. */ + allExtents?: Extent[]; + /** A description of the WMS layer. */ + description?: string; + /** The extent of the WMS Layer. */ + extent?: Extent; + /** The URL to the legend image. */ + legendURL?: string; + /** The name of the WMS layer. */ + name: string; + /** Returns true if the layer can be queried and the service supports GetFeatureInfo with either text/html or text/plain formats. */ + queryable?: boolean; + /** Indicates if this layer should be included in the popup. */ + showPopup?: boolean; + /** All the spatial references defined for this layer. */ + spatialReferences?: SpatialReference[]; + /** WMSLayerInfos of the layer's sub layers. */ + subLayers?: WMSLayerInfo[]; + /** The title of the WMS layer. */ + title?: string; + } export interface WMSLayerOptions { /** Specify the map image format, valid options are png,jpg,bmp,gif,svg. */ format?: string; @@ -3732,6 +3776,8 @@ declare module "esri/dijit/Directions" { maxStopsReached: boolean; /** Read-only: The graphic for the calculated route. */ mergedRouteGraphic: Graphic; + /** If specified, this specifies the portal where the produced route layers are going to be stored and accessed. */ + portalUrl: string; /** Routing parameters for the widget. */ routeParams: RouteParameters; /** Routing task for the widget. */ @@ -3744,6 +3790,8 @@ declare module "esri/dijit/Directions" { showClearButton: boolean; /** If true, the toggle button group allowing user to choose between Miles and Kilometers is shown. */ showMilesKilometersOption: boolean; + /** Applicable if the widget works with a Network Analyst Server federated with ArcGIS Online or Portal. */ + showSaveButton: boolean; /** If true, and supported by the service, then two toggle button groups are shown: one to allow user to choose between driving a car, a truck, or walking, and one more group to choose between fastest or shortest routes. */ showTravelModesOption: boolean; /** An array of graphics that define the stop locations along the route. */ @@ -3792,6 +3840,11 @@ declare module "esri/dijit/Directions" { * @param index The index of the route segment to highlight. */ highlightSegment(index: number): void; + /** + * Loads a stored route layer from either ArcGIS Online or Portal + * @param itemId The itemId of the stored route layer from either ArcGIS Online or Portal. + */ + loadRoute(itemId: string): any; /** * Remove the stop at the specified index. * @param index The index of the stop to remove. @@ -3801,6 +3854,16 @@ declare module "esri/dijit/Directions" { removeStops(): any; /** Resets the directions widget removing any directions, stops and map graphics. */ reset(): any; + /** + * Specify the language used for the directions. + * @param locale The locale used for the directions. + */ + setDirectionsLanguage(locale: string): any; + /** + * Specify the length units used for the directions widget. + * @param units The length units used for the directions widget. + */ + setDirectionsLengthUnits(units: string): any; /** * If widget runs with Travel Modes enabled, call this method to switch to particular Travel mode programmatically. * @param travelModeName Travel mode. @@ -3843,10 +3906,16 @@ declare module "esri/dijit/Directions" { on(type: "directions-finish", listener: (event: { result: RouteResult; target: Directions }) => void): esri.Handle; /** Fires when the route services starts to calculate the route. */ on(type: "directions-start", listener: (event: { target: Directions }) => void): esri.Handle; + /** Fires after a user clicks the Save or Save as New button and subsequently does not have permission to create an item in ArcGIS Online or Portal. */ + on(type: "feature-collection-created", listener: (event: { target: Directions }) => void): esri.Handle; /** Fires when the directions widget has fully loaded. */ on(type: "load", listener: (event: { target: Directions }) => void): esri.Handle; /** Fires when the widget starts or stops listening for map clicks. */ on(type: "map-click-active", listener: (event: { mapClickActive: boolean; target: Directions }) => void): esri.Handle; + /** Fires after a user clicks the Save or Save as New button for the first time in order to store a new route in either ArcGIS Online or Portal. */ + on(type: "route-item-created", listener: (event: { target: Directions }) => void): esri.Handle; + /** Fires when a existing route layer item is successfully updated in ArcGIS Online or Portal after user clicks the Save button. */ + on(type: "route-item-updated", listener: (event: { target: Directions }) => void): esri.Handle; /** Fired when you hover over a route segment in the directions display. */ on(type: "segment-highlight", listener: (event: { graphic: Graphic; target: Directions }) => void): esri.Handle; /** Fires when a route segment is selected in the directions display. */ @@ -3901,6 +3970,8 @@ declare module "esri/dijit/FeatureTable" { /** Creates an instance of the FeatureTable widget within the provided DOM node. */ class FeatureTable { + /** The number of features a service will try to fetch. */ + batchCount: number; /** Read-only: A reference to the column objects and their parameters. */ columns: any[]; /** Read-only: Reference to the dataStore used by the dGrid. */ @@ -3909,6 +3980,8 @@ declare module "esri/dijit/FeatureTable" { dateOptions: any; /** Sets the editing state for the FeatureTable. */ editable: boolean; + /** Event trigger(s) used to display editing interface for an individual cell. */ + editOn: string | any; /** Read-only: Number of records displayed in FeatureTable. */ featureCount: number; /** The featureLayer that the table is associated with. */ @@ -3937,12 +4010,18 @@ declare module "esri/dijit/FeatureTable" { selectedRowIds: number[]; /** Read-only: Each element in the array is an object that contains name-value pair of fields and field values associated with the selected rows. */ selectedRows: any[]; - /** Displays the data type of the field right under the field label in the column header. */ + /** Displays or hides the attachment column. */ + showAttachments: boolean; + /** Displays or hides the data type of the field right under the field label in the column header. */ showDataTypes: boolean; + /** Displays or hides total number of features and selected number of features in the grid header. */ + showFeatureCount: boolean; /** Displays or hides the FeatureTable header. */ showGridHeader: boolean; /** Displays or hides 'Options' drop-down menu of the FeatureTable. */ showGridMenu: boolean; + /** Displays or hides the 'Statistics' option in column menus for numeric fields. */ + showStatistics: boolean; /** Enables an interaction between the map and the feature table. */ syncSelection: boolean; /** Enables pans to selected features on the map when the table in 'sync selection' mode. */ @@ -3953,6 +4032,29 @@ declare module "esri/dijit/FeatureTable" { * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ constructor(params: esri.FeatureTableOptions, srcNodeRef: Node | string); + /** Removes all current selections including subsets from filterSelectedRecords(). */ + clearSelection(): void; + /** Destroys the FeatureTable widget. */ + destroy(): void; + /** + * Allows users to see the sub-set of currently selected records (uses dGrid.query). + * @param toggle When true only a subset of currently selected features will be displayed in the FeatureTable. + */ + filterSelectedRecords(toggle: boolean): void; + /** + * Queries and gets selected features from the FeatureLayer instead of the store. + * @param id Array of row ids + */ + getFeatureDataById(id: number[]): any; + /** + * Gets row object by the row ID. + * @param id row ID + */ + getRowDataById(id: number): any; + /** Refreshes the data in the grid. */ + refresh(): void; + /** Resizes the grid's container. */ + resize(): void; /** Finalizes the creation of the widget. */ startup(): void; /** Fires when the grid column is resized. */ @@ -4286,8 +4388,13 @@ declare module "esri/dijit/ImageServiceMeasure" { /** * Creates an instance of the ImageServiceMeasure widget. * @param params An Object containing constructor options. + * @param srcNode Reference or id of the HTML element where the widget should be rendered. */ - constructor(params: esri.ImageServiceMeasureOptions); + constructor(params: esri.ImageServiceMeasureOptions, srcNode: Node | string); + /** Destroys the ImageServiceMeasure widget. */ + destroy(): void; + /** Finalizes the creation of the widget. */ + startup(): void; } export = ImageServiceMeasure; } @@ -4528,9 +4635,14 @@ declare module "esri/dijit/LayerSwipe" { declare module "esri/dijit/Legend" { import esri = require("esri"); + import Map = require("esri/map"); /** The legend dijit displays a label and symbol for some or all of the layers in the map. */ class Legend { + /** Specify a subset of the layers in the map to display in the legend. */ + layerInfos: any[]; + /** Reference to the map. */ + map: Map; /** * Creates a new Legend dijit. * @param params Parameters used to configure the dijit. @@ -4555,7 +4667,7 @@ declare module "esri/dijit/LocateButton" { import Symbol = require("esri/symbols/Symbol"); import Graphic = require("esri/graphic"); - /** LocateButton provides a simple button to locate and zoom to the users current location. */ + /** LocateButton provides a simple button to locate and zoom to the user's location. */ class LocateButton { /** Centers the map to the location when a new position is returned. */ centerAt: boolean; @@ -6767,7 +6879,7 @@ declare module "esri/dijit/editing/Add" { import esri = require("esri"); import OperationBase = require("esri/OperationBase"); - /** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */ + /** This class is used with the UndoManager to provide undo/redo functionality of Add operations when editing. */ class Add extends OperationBase { /** * Create a new Add operation. @@ -6810,7 +6922,7 @@ declare module "esri/dijit/editing/Cut" { import esri = require("esri"); import OperationBase = require("esri/OperationBase"); - /** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */ + /** This class is used with the UndoManager to provide undo/redo functionality of Cut operations when editing. */ class Cut extends OperationBase { /** * Create a new Cut operation. @@ -6829,7 +6941,7 @@ declare module "esri/dijit/editing/Delete" { import esri = require("esri"); import OperationBase = require("esri/OperationBase"); - /** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */ + /** This class is used with the UndoManager to provide undo/redo functionality of Delete operations when editing. */ class Delete extends OperationBase { /** * Create a new Delete operation. @@ -6929,7 +7041,7 @@ declare module "esri/dijit/editing/Union" { import esri = require("esri"); import OperationBase = require("esri/OperationBase"); - /** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */ + /** This class is used with the UndoManager to provide undo/redo functionality of Union operations when editing. */ class Union extends OperationBase { /** * Create a new Union operation. @@ -6948,7 +7060,7 @@ declare module "esri/dijit/editing/Update" { import esri = require("esri"); import OperationBase = require("esri/OperationBase"); - /** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */ + /** This class is used with the UndoManager to provide undo/redo functionality of Update operations when editing. */ class Update extends OperationBase { /** * Create a new Update operation. @@ -8353,8 +8465,9 @@ declare module "esri/geometry/webMercatorUtils" { /** * Converts geometry from Web Mercator units to geographic units. * @param geometry The geometry to convert. + * @param isLinear Indicates whether to work with linear values, i.e., do not normalize. */ - webMercatorToGeographic(geometry: Geometry): Geometry; + webMercatorToGeographic(geometry: Geometry, isLinear?: boolean): Geometry; /** * Translates the given Web Mercator coordinates to Longitude and Latitude. * @param x The x coordinate value to convert. @@ -10809,8 +10922,6 @@ declare module "esri/layers/VectorTileLayer" { initialExtent: Extent; /** The spatial reference of the layer. */ spatialReference: SpatialReference; - /** The style object of the service with fully qualified URLs for glyphs and sprite. */ - style: any; /** Contains information about the tiling scheme for the layer. */ tileInfo: TileInfo; /** The URL to the vector tile service or style JSON that will be used to draw the layer. */ @@ -10821,6 +10932,8 @@ declare module "esri/layers/VectorTileLayer" { * @param options Optional parameters. */ constructor(url: string | any, options?: esri.VectorTileLayerOptions); + /** Returns an object that contains the current style information for the layer. */ + getStyle(): any; /** * Changes the style properties used to render the layers. * @param styleUrl A url to a JSON file containing the stylesheet information to render the layer. @@ -10835,14 +10948,15 @@ declare module "esri/layers/VectorTileLayer" { declare module "esri/layers/WFSLayer" { import esri = require("esri"); + import GraphicsLayer = require("esri/layers/GraphicsLayer"); import Field = require("esri/layers/Field"); import Extent = require("esri/geometry/Extent"); import Graphic = require("esri/graphic"); import InfoTemplate = require("esri/InfoTemplate"); import Renderer = require("esri/renderers/Renderer"); - /** (Currently in beta) A layer for OGC Web Feature Services (WFS). */ - class WFSLayer { + /** (Currently in beta) A layer for OGC Web Feature Services (WFS). */ + class WFSLayer extends GraphicsLayer { /** An array of fields in the layer. */ fields: Field[]; /** The full extent of the layer. */ @@ -10864,17 +10978,11 @@ declare module "esri/layers/WFSLayer" { * @param options See options table below for full descriptions of the properties needed for this object. */ constructor(options: esri.WFSLayerOptions); - /** Creates the getFeature parameter based on the version, nsLayerName, nsGeometryFieldName, mode, wkid, inverseFilter, maxFeatures constructor parameters. */ - buildRequest(): string; /** - * Gets the WFS layer capabilities. - * @param callback An array of WFS layers in JSON format. + * Creates a WFSLayer using the provided JSON object. + * @param json The input JSON. */ - getCapabilities(callback?: Function): void; - /** Performs the getFeature request. */ - getFeature(): void; - /** Returns a JSON Object containing all of the WFS parameters. */ - getWFSParameters(): any; + fromJson(json: Object): void; /** Redraws all the graphics in the layer. */ redraw(): void; /** Refreshes the features in the WFS layer. */ @@ -10885,8 +10993,8 @@ declare module "esri/layers/WFSLayer" { setPointSymbol(): void; /** Sets the default polygon symbol to be used if no renderer is specified. */ setPolygonSymbol(): void; - /** Sets the WFS parameters using the provided JSON Object. */ - setWFSParameters(): void; + /** Converts the WFSLayer instance to a JSON object. */ + toJson(): any; } export = WFSLayer; } @@ -10952,6 +11060,7 @@ declare module "esri/layers/WMSLayer" { } declare module "esri/layers/WMSLayerInfo" { + import esri = require("esri"); import Extent = require("esri/geometry/Extent"); /** The WMSLayerInfo class defines and provides information about layers in a WMS service. */ @@ -10966,6 +11075,10 @@ declare module "esri/layers/WMSLayerInfo" { legendURL: string; /** The layer name. */ name: string; + /** Returns true if the layer can be queried and the service supports GetFeatureInfo with either text/html or text/plain formats */ + queryable: boolean; + /** Indicates if this layer should be included in the popup. */ + showPopup: boolean; /** An array of WKIDs of all spatial references defined for the layer. */ spatialReferences: number[]; /** WMSLayerInfos of the layer's sub layers. */ @@ -10974,9 +11087,9 @@ declare module "esri/layers/WMSLayerInfo" { title: string; /** * Creates a new WMSLayerInfo object. - * @param layer WMSLayerInfo layer object. + * @param options See options list for parameters. */ - constructor(layer: any); + constructor(options?: esri.WMSLayerInfoOptions); } export = WMSLayerInfo; } @@ -11584,7 +11697,7 @@ declare module "esri/opsdashboard/DataSourceProxy" { displayFieldName: string; /** Read-only: The collection of fields. */ fields: Field[]; - /** The geometry type. */ + /** Read-only: The geometry type. */ geometryType: string; /** Read-only: The id of the data source. */ id: string; @@ -11611,8 +11724,8 @@ declare module "esri/opsdashboard/DataSourceProxy" { executeQuery(query: Query): any; /** An object that contains service level metadata about whether or not the layer supports queries using statistics, order by fields, DISTINCT, pagination, query with distance, and returning queries with extents. */ getAdvancedQueryCapabilities(): any; - /** Retrieve the associated data source that supports selection. */ - getAssociatedSelectionDataSourceProxy(): any; + /** Retrieve the associated id of the data source that supports selection. */ + getAssociatedSelectionDataSourceId(): any; /** Get the associated popupInfo for the data source if any available. */ getPopupInfo(): any; /** Get the associated render object for the data source if any available. */ @@ -11666,12 +11779,17 @@ declare module "esri/opsdashboard/ExtensionBase" { static POLYLINE: any; /** Read-only: Indicates if the host application is the Windows Operations Dashboard. */ isNative: boolean; + /** Read Only: It will list all of the Portal helper services. */ + portalHelperServices: string; /** Read-only: The URL to the ArcGIS.com site or in-house portal that you are currently signed in to. */ portalUrl: string; /** Get the collection of data sources from the host application. */ getDataSourceProxies(): any; - /** Get the data source corresponding to the data source id from the host application. */ - getDataSourceProxy(): any; + /** + * Get the data source corresponding to the data source id from the host application. + * @param dataSourceId The data source id + */ + getDataSourceProxy(dataSourceId: string): any; /** Get the collection of map widgets from the host application. */ getMapWidgetProxies(): any; /** @@ -11791,7 +11909,7 @@ declare module "esri/opsdashboard/GraphicsLayerProxy" { minScale: number; /** Read-only: The current host graphics layer opacity ratio. */ opacity: number; - /** The current renderer used by the host graphics layer. */ + /** Read-only: The current renderer used by the host graphics layer. */ renderer: Renderer; /** Read-only: The current host graphics layer visibility. */ visible: boolean; @@ -11928,8 +12046,6 @@ declare module "esri/opsdashboard/MapWidgetProxy" { destroyGraphicsLayerProxy(graphicsLayerProxy: GraphicsLayerProxy): void; /** Gets the current host map extent. */ getMapExtent(): any; - /** Called by the host application when the extent of the host map has changed. */ - mapExtentChanged(): void; /** * Pans the map to a new location. * @param mapPoint A new location with the same spatial reference as the host map. @@ -14088,7 +14204,7 @@ declare module "esri/tasks/FindTask" { url: string; /** * Creates a new FindTask object. - * @param url URL to the ArcGIS Server REST resource that represents a layer in a service. + * @param url URL to the ArcGIS Server REST resource that represents a map service. * @param options Optional parameters. */ constructor(url: string, options?: esri.FindTaskOptions); @@ -15343,6 +15459,8 @@ declare module "esri/tasks/RouteParameters" { startTimeIsUTC: boolean; /** The set of stops loaded as network locations during analysis. */ stops: any; + /** If true , the TimeWindowStart and TimeWindowEnd attributes of a stop are in UTC time (milliseconds). */ + timeWindowsAreUTC: boolean; /** Travel modes define how a pedestrian, car, truck or other medium of transportation moves through the street network. */ travelMode: any; /** If true, the hierarchy attribute for the network should be used in analysis. */ @@ -16696,7 +16814,7 @@ declare module "esri/tasks/query" { static SPATIAL_REL_TOUCHES: any; /** The feature from feature class 1 is completely enclosed by the feature from feature class 2. */ static SPATIAL_REL_WITHIN: any; - /** Distance to buffer input geometry. */ + /** Buffer distance for input geometries. */ distance: number; /** The geometry to apply to the spatial filter. */ geometry: Geometry; @@ -16738,7 +16856,7 @@ declare module "esri/tasks/query" { text: string; /** Specify a time extent for the query. */ timeExtent: TimeExtent; - /** Distance unit. */ + /** The unit for calculating the buffer distance. */ units: string; /** A where clause for the query. */ where: string; @@ -17055,7 +17173,7 @@ declare module "esri/toolbars/navigation" { * @param symbol The SimpleFillSymbol used for the rubber band zoom. */ setZoomSymbol(symbol: Symbol): void; - /** Zoom to full extent of base layer. */ + /** Zoom to initial extent of base layer. */ zoomToFullExtent(): void; /** Zoom to next extent in extent history. */ zoomToNextExtent(): void; diff --git a/archiver/archiver.d.ts b/archiver/archiver.d.ts index d5133555a4..b31c8ad619 100644 --- a/archiver/archiver.d.ts +++ b/archiver/archiver.d.ts @@ -24,7 +24,7 @@ declare module "archiver" { interface Archiver extends STREAM.Transform { pipe(writeStream: FS.WriteStream): void; - append(readStream: FS.ReadStream, name: nameInterface): void; + append(source: FS.ReadStream | Buffer | string, name: nameInterface): void; finalize(): void; } diff --git a/asana/asana.d.ts b/asana/asana.d.ts index 61cb54d26f..8b618b81a3 100644 --- a/asana/asana.d.ts +++ b/asana/asana.d.ts @@ -3,7 +3,7 @@ // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// declare module "asana" { diff --git a/async/async-tests.ts b/async/async-tests.ts index e7af9120a1..63640cecf6 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -392,13 +392,6 @@ function (results) { ]); }); -var sys; -var iterator = async.iterator([ - function () { sys.p('one'); }, - function () { sys.p('two'); }, - function () { sys.p('three'); } -]); - async.parallel([ async.apply(fs.writeFile, 'testfile1', 'test1'), async.apply(fs.writeFile, 'testfile2', 'test2'), diff --git a/async/async.d.ts b/async/async.d.ts index 6288a269a1..96da35c1ea 100644 --- a/async/async.d.ts +++ b/async/async.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Async 1.4.2 +// Type definitions for Async 2.0.1 // Project: https://github.com/caolan/async // Definitions by: Boris Yankov , Arseniy Maximov , Joe Herman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -37,6 +37,13 @@ interface AsyncQueue { pause(): void resume(): void; kill(): void; + workersList(): { + data: T, + callback: Function + }[]; + error(error: Error, data: any): void; + unsaturated(): void; + buffer: number; } interface AsyncPriorityQueue { @@ -54,6 +61,14 @@ interface AsyncPriorityQueue { pause(): void; resume(): void; kill(): void; + workersList(): { + data: T, + priority: number, + callback: Function + }[]; + error(error: Error, data: any): void; + unsaturated(): void; + buffer: number; } interface AsyncCargo { @@ -85,6 +100,9 @@ interface Async { map(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; mapSeries(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + mapValuesLimit(obj: {[name: string]: T}, limit: number, iteratee: (value: string, key: T, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; + mapValues(obj: {[name: string]: T}, iteratee: (value: string, key: T, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; + mapValuesSeries: typeof async.mapValues; filter(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; select(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; filterSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; @@ -100,11 +118,17 @@ interface Async { reduceRight(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; foldr(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; detect(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): any; + find: typeof async.detect; detectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): any; + findSeries: typeof async.detectSeries; detectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): any; + findLimit: typeof async.detectLimit; sortBy(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; some(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; someLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; + anyLimit: typeof async.someLimit; + someSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; + anySeries: typeof async.someSeries; any(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; every(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; everyLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; @@ -134,18 +158,35 @@ interface Async { queue(worker: AsyncWorker, concurrency?: number): AsyncQueue; priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo; - auto(tasks: any, callback?: (error: Error, results: any) => void): void; + auto(tasks: any, concurrency?: number, callback?: (error: Error, results: any) => void): void; + autoInject(tasks: any, callback?: (error: Error, results: any) => void): void; retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: (error: Error, results: any) => void): void; retry(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback, results : any) => void, callback: (error: Error, results: any) => void): void; - iterator(tasks: Function[]): Function; + retryable(opts: number | {times: number, interval: number}, task: AsyncFunction): AsyncFunction; apply(fn: Function, ...arguments: any[]): AsyncFunction; - nextTick(callback: Function): void; - setImmediate(callback: Function): void; + nextTick(callback: Function, ...args: any[]): void; + setImmediate: typeof async.nextTick; + + allLimit(arr: T[], limit: number, iteratee: AsyncBooleanIterator, cb?: (result: boolean) => any) : any; + everySeries(arr: T[], iteratee: AsyncBooleanIterator, cb?: (result: boolean) => any) : any + allSeries: typeof async.everySeries; + + reflect(fn: AsyncFunction) : (callback: (err: void, result: {error?: Error, value?: T}) => void) => void; + reflectAll(tasks: AsyncFunction[]): ((callback: (err: void, result: {error?: Error, value?: T}) => void) => void)[]; + + timeout(fn: AsyncFunction, milliseconds: number, info: any): AsyncFunction; times (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; timesSeries(n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; timesLimit(n: number, limit: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + transform(arr: T[], iteratee: (acc: R[], item: T, key: string, callback: (error?: Error) => void) => void): void; + transform(arr: T[], acc: R[], iteratee: (acc: R[], item: T, key: string, callback: (error?: Error) => void) => void): void; + transform(arr: {[key: string] : T}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: Error) => void) => void): void; + transform(arr: {[key: string] : T}, acc: {[key: string] : R}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: Error) => void) => void): void; + + race(tasks: (AsyncFunction)[], callback: AsyncResultCallback) : void; + // Utils memoize(fn: Function, hasher?: Function): Function; unmemoize(fn: Function): Function; @@ -155,7 +196,6 @@ interface Async { wrapSync(fn: Function): Function; log(fn: Function, ...arguments: any[]): void; dir(fn: Function, ...arguments: any[]): void; - noConflict(): Async; } declare var async: Async; diff --git a/atom/atom.d.ts b/atom/atom.d.ts index 389d6ef16e..ac899ba5ac 100644 --- a/atom/atom.d.ts +++ b/atom/atom.d.ts @@ -946,9 +946,14 @@ declare namespace AtomCore { registry: any; repository: Object; scopeName: string; + tokenizeLines: (text: string) => any; // TBD } + + interface IGrammars { + grammarForScopeName(scope: string): IGrammar; + } interface IPane /* extends Theorist.Model */ { itemForURI: (uri:string)=>IEditor; @@ -1302,6 +1307,7 @@ declare namespace AtomCore { deserializers:IDeserializerManager; config: IConfig; commands: ICommandRegistry; + grammars: IGrammars; keymaps: IKeymapManager; keymap: IKeymapManager; packages: IPackageManager; diff --git a/auth0-js/auth0-js-tests.ts b/auth0-js/auth0-js-tests.ts new file mode 100644 index 0000000000..c92251db91 --- /dev/null +++ b/auth0-js/auth0-js-tests.ts @@ -0,0 +1,23 @@ +/// + +var auth0 = new Auth0({ + domain: 'mine.auth0.com', + clientID: 'dsa7d77dsa7d7', + callbackURL: 'http://my-app.com/callback', + callbackOnLocationHash: true +}); + +auth0.login({ + connection: 'google-oauth2', + popup: true, + popupOptions: { + width: 450, + height: 800 + } +}, (err, profile, idToken, accessToken, state) => { + if (err) { + alert("something went wrong: " + err.message); + return; + } + alert('hello ' + profile.name); + }); diff --git a/auth0-js/auth0-js.d.ts b/auth0-js/auth0-js.d.ts new file mode 100644 index 0000000000..250c7a850e --- /dev/null +++ b/auth0-js/auth0-js.d.ts @@ -0,0 +1,133 @@ +// Type definitions for Auth0.js +// Project: https://github.com/auth0/auth0.js +// Definitions by: Robert McLaws +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** Extensions to the browser Window object. */ +interface Window { + /** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */ + token: string; +} + +/** This is the interface for the main Auth0 client. */ +interface Auth0Static { + + new(options: Auth0ClientOptions): Auth0Static; + changePassword(options: any, callback?: Function): void; + decodeJwt(jwt: string): any; + login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void; + loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + logout(query: string): void; + getConnections(callback?: Function): void; + refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; + getDelegationToken(targetClientId: string, id_token: string, options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; + getProfile(id_token: string, callback?: Function): Auth0UserProfile; + getSSOData(withActiveDirectories: any, callback?: Function): void; + parseHash(hash: string): Auth0DecodedHash; + signup(options: Auth0SignupOptions, callback: Function): void; + validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void; +} + +/** Represents constructor options for the Auth0 client. */ +interface Auth0ClientOptions { + clientID: string; + callbackURL: string; + callbackOnLocationHash?: boolean; + domain: string; + forceJSONP?: boolean; +} + +/** Represents a normalized UserProfile. */ +interface Auth0UserProfile { + email: string; + email_verified: boolean; + family_name: string; + gender: string; + given_name: string; + locale: string; + name: string; + nickname: string; + picture: string; + user_id: string; + /** Represents one or more Identities that may be associated with the User. */ + identities: Auth0Identity[]; + user_metadata?: any; + app_metadata?: any; +} + +/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */ +interface MicrosoftUserProfile extends Auth0UserProfile { + emails: string[]; +} + +/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */ +interface Office365UserProfile extends Auth0UserProfile { + tenantid: string; + upn: string; +} + +/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */ +interface AdfsUserProfile extends Auth0UserProfile { + issuer: string; +} + +/** Represents multiple identities assigned to a user. */ +interface Auth0Identity { + access_token: string; + connection: string; + isSocial: boolean; + provider: string; + user_id: string; +} + +interface Auth0DecodedHash { + access_token: string; + id_token: string; + profile: Auth0UserProfile; + state: any; +} + +interface Auth0PopupOptions { + width: number; + height: number; +} + +interface Auth0LoginOptions { + auto_login?: boolean; + connection?: string; + email?: string; + username?: string; + password?: string; + popup?: boolean; + popupOptions?: Auth0PopupOptions; +} + +interface Auth0SignupOptions extends Auth0LoginOptions { + auto_login: boolean; +} + +interface Auth0Error { + code: any; + details: any; + name: string; + message: string; + status: any; +} + +/** Represents the response from an API Token Delegation request. */ +interface Auth0DelegationToken { + /** The length of time in seconds the token is valid for. */ + expires_in: string; + /** The JWT for delegated access. */ + id_token: string; + /** The type of token being returned. Possible values: "Bearer" */ + token_type: string; +} + +declare var Auth0: Auth0Static; + +declare module "auth0-js" { + export = Auth0 +} diff --git a/auth0.lock/auth0.lock-tests.ts b/auth0.lock/auth0.lock-tests.ts index fd646ee1bb..d466cf5937 100644 --- a/auth0.lock/auth0.lock-tests.ts +++ b/auth0.lock/auth0.lock-tests.ts @@ -1,13 +1,165 @@ -/// +/// /// -var lock: Auth0LockStatic = new Auth0Lock("dsa7d77dsa7d7", "mine.auth0.com"); +const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID"; +const DOMAIN = "YOUR_DOMAIN_AT.auth0.com"; -lock.showSignin({ - connections: ["facebook", "google-oauth2", "twitter", "Username-Password-Authentication"], - icon: "https://contoso.com/logo-32.png", - socialBigButtons: true - }, - () => { - // The Auth0 Widget is now loaded. +var lock: Auth0LockStatic = new Auth0Lock(CLIENT_ID, DOMAIN); + +lock.show(); +lock.hide(); +lock.logout(() => {}); + +// The examples below are lifted from auth0-lock documentation on Github + +// "on" event-driven example + +lock.on("authenticated", function(authResult : any) { + lock.getProfile(authResult.idToken, function(error, profile) { + if (error) { + // Handle error + return; + } + + localStorage.setItem("idToken", authResult.idToken); + localStorage.setItem("profile", JSON.stringify(profile)); + }); }); + + +// test theme + +var themeOptions : Auth0LockConstructorOptions = { + theme: { + logo: "https://example.com/assets/logo.png", + primaryColor: "green" + } +}; + +new Auth0Lock(CLIENT_ID, DOMAIN, themeOptions); + +// test authentication + +var authOptions : Auth0LockConstructorOptions = { + auth: { + params: { state: "foo" }, + redirect: true, + redirectUrl: "some url", + responseType: "token", + sso: true + } +}; + +new Auth0Lock(CLIENT_ID, DOMAIN, authOptions); + +// test multi-variant example + +var multiVariantOptions : Auth0LockConstructorOptions = { + container: "myContainer", + closable: false, + languageDictionary: { + signUpTerms: "I agree to the terms of service ...", + title: "My Company", + }, + autofocus: false +}; + +new Auth0Lock(CLIENT_ID, DOMAIN, multiVariantOptions); + +// test text-field additional sign up field + +var textFieldOptions : Auth0LockConstructorOptions = { + additionalSignUpFields: [{ + name: "address", + placeholder: "enter your address", + // The following properties are optional + icon: "https://example.com/assests/address_icon.png", + prefill: "street 123", + validator: function(input : string) { + return { + valid: input.length >= 10, + hint: "Must have 10 or more chars" // optional + }; + } + }] +}; + +new Auth0Lock(CLIENT_ID, DOMAIN, textFieldOptions); + +// test select-field additional sign up field + +var selectFieldOptions : Auth0LockConstructorOptions = { + additionalSignUpFields: [{ + type: "select", + name: "location", + placeholder: "choose your location", + options: [ + {value: "us", label: "United States"}, + {value: "fr", label: "France"}, + {value: "ar", label: "Argentina"} + ], + // The following properties are optional + icon: "https://example.com/assests/location_icon.png", + prefill: "us" + }] +}; + +new Auth0Lock(CLIENT_ID, DOMAIN, selectFieldOptions); + +// test select-field additional sign up field with callbacks for + +var selectFieldOptionsWithCallbacks : Auth0LockConstructorOptions = { + additionalSignUpFields: [{ + type: "select", + name: "location", + placeholder: "choose your location", + options: function(cb) { + // obtain options, in case of error you call cb with the error in the + // first arg instead of null + + let options = [ + {value: "us", label: "United States"}, + {value: "fr", label: "France"}, + {value: "ar", label: "Argentina"} + ]; + + cb(null, options); + }, + icon: "https://example.com/assests/location_icon.png", + prefill: function(cb) { + // obtain prefill, in case of error you call cb with the error in the + // first arg instead of null + + let prefill = "us"; + + cb(null, prefill); + } + }] +} + +new Auth0Lock(CLIENT_ID, DOMAIN, selectFieldOptionsWithCallbacks); + +// test Avatar options + +var avatarOptions : Auth0LockConstructorOptions = { + avatar: { + url: (email : string, cb : Auth0LockAvatarUrlCallback) => { + // obtain url for email, in case of error you call cb with the error in + // the first arg instead of null + + let url = "url"; + + cb(null, url); + }, + displayName: (email : string, cb : Auth0LockAvatarDisplayNameCallback) => { + // obtain displayName for email, in case of error you call cb with the + // error in the first arg instead of null + + let displayName = "displayName"; + + cb(null, displayName); + } + } +}; + +new Auth0Lock(CLIENT_ID, DOMAIN, avatarOptions); diff --git a/auth0.lock/auth0.lock.d.ts b/auth0.lock/auth0.lock.d.ts index 15f767984b..2d74f6e6a5 100644 --- a/auth0.lock/auth0.lock.d.ts +++ b/auth0.lock/auth0.lock.d.ts @@ -1,9 +1,69 @@ -// Type definitions for Auth0Widget.js +// Type definitions for auth0-lock v10.0.1 // Project: http://auth0.com -// Definitions by: Robert McLaws +// Definitions by: Brian Caruso // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// + +interface Auth0LockAdditionalSignUpFieldOption { + value: string; + label: string; +} + +type Auth0LockAdditionalSignUpFieldOptionsCallback = + (error: Auth0Error, options: Auth0LockAdditionalSignUpFieldOption[]) => void; + +type Auth0LockAdditionalSignUpFieldOptionsFunction = + (callback: Auth0LockAdditionalSignUpFieldOptionsCallback) => void; + +type Auth0LockAdditionalSignUpFieldPrefillCallback = + (error: Auth0Error, prefill: string) => void; + +type Auth0LockAdditionalSignUpFieldPrefillFunction = + (callback: Auth0LockAdditionalSignUpFieldPrefillCallback) => void; + +interface Auth0LockAdditionalSignUpField { + icon?: string; + name: string; + options?: Auth0LockAdditionalSignUpFieldOption[] | Auth0LockAdditionalSignUpFieldOptionsFunction; + placeholder: string; + prefill?: string | Auth0LockAdditionalSignUpFieldPrefillFunction; + type?: "select" | "text"; + validator?: (input: string) => { valid: boolean; hint?: string }; +} + +type Auth0LockAvatarUrlCallback = (error: Auth0Error, url: string) => void; +type Auth0LockAvatarDisplayNameCallback = (error: Auth0Error, displayName: string) => void; + +interface Auth0LockAvatarOptions { + url: (email: string, callback: Auth0LockAvatarUrlCallback) => void; + displayName: (email: string, callback: Auth0LockAvatarDisplayNameCallback) => void; +} + +interface Auth0LockThemeOptions { + logo?: string; + primaryColor?: string; +} + +// https://auth0.com/docs/libraries/lock/v10/sending-authentication-parameters +interface Auth0LockAuthParamsOptions { + access_token?: any; + connection_scopes?: any; + device?: any; + nonce?: any; + protocol?: any; + request_id?: any; + scope?: string; + state?: string; +} + +interface Auth0LockAuthOptions { + params?: Auth0LockAuthParamsOptions; + redirect?: boolean; + redirectUrl?: string; + responseType?: string; + sso?: boolean; +} interface Auth0LockPopupOptions { width: number; @@ -12,68 +72,51 @@ interface Auth0LockPopupOptions { top: number; } -interface Auth0LockOptions { - authParams?: any; - callbackURL?: string; - connections?: string[]; - container?: string; - closable?: boolean; - dict?: any; - defaultUserPasswordConnection?: string; - defaultADUsernameFromEmailPrefix?: boolean; - disableResetAction?: boolean; - disableSignupAction?: boolean; - focusInput?: boolean; - forceJSONP?: boolean; - gravatar?: boolean; - integratedWindowsLogin?: boolean; - icon?: string; - loginAfterSignup?: boolean; - popup?: boolean; - popupOptions?: Auth0LockPopupOptions; - rememberLastLogin?: boolean; - resetLink?: string; - responseType?: string; - signupLink?: string; - socialBigButtons?: boolean; - sso?: boolean; - theme?: string; - usernameStyle?: any; -} - interface Auth0LockConstructorOptions { - cdn?: string; + additionalSignUpFields?: Auth0LockAdditionalSignUpField[]; + allowedConnections?: string[]; + allowForgotPassword?: boolean; + allowLogin?: boolean; + allowSignUp?: boolean; assetsUrl?: string; - useCordovaSocialPlugins?: boolean; + auth?: Auth0LockAuthOptions; + autoclose?: boolean; + autofocus?: boolean; + avatar?: Auth0LockAvatarOptions; + closable?: boolean; + container?: string; + defaultADUsernameFromEmailPrefix?: string; + defaultDatabaseConnection?: string; + defaultEnterpriseConnection?: string; + forgotPasswordLink?: string; + initialScreen?: "login" | "signUp" | "forgotPassword"; + language?: string; + languageDictionary?: any; + loginAfterSignUp?: boolean; + mustAcceptTerms?: boolean; + popupOptions?: Auth0LockPopupOptions; + prefill?: { email?: string, username?: string}; + rememberLastLogin?: boolean; + signupLink?: string; + socialButtonStyle?: "big" | "small"; + theme?: Auth0LockThemeOptions; + usernameStyle?: string; } interface Auth0LockStatic { new (clientId: string, domain: string, options?: Auth0LockConstructorOptions): Auth0LockStatic; + getProfile(token: string, callback: (error: Auth0Error, profile: Auth0UserProfile) => void) : void; show(): void; - show(options: Auth0LockOptions): void; - show(callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; - show(options: Auth0LockOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; + hide(): void; + logout(query: any): void; - showSignin(): void; - showSignin(options: Auth0LockOptions): void; - showSignin(callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; - showSignin(options: Auth0LockOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; - - showSignup(): void; - showSignup(options: Auth0LockOptions): void; - showSignup(callback: (error?: Auth0Error) => void) : void; - showSignup(options: Auth0LockOptions, callback: (error?: Auth0Error) => void) : void; - - showReset(): void; - showReset(options: Auth0LockOptions): void; - showReset(callback: (error?: Auth0Error) => void) : void; - showReset(options: Auth0LockOptions, callback: (error?: Auth0Error) => void) : void; - - hide(callback: () => void): void; - logout(callback: () => void): void; - - getClient(): Auth0Static; + on(event: "show", callback: () => void) : void; + on(event: "hide", callback: () => void) : void; + on(event: "unrecoverable_error", callback: (error: Auth0Error) => void) : void; + on(event: "authorization_error", callback: (error: Auth0Error) => void) : void; + on(event: "authenticated", callback: (authResult: any) => void) : void; + on(event: string, callback: (...args: any[]) => void) : void; } declare var Auth0Lock: Auth0LockStatic; diff --git a/auth0.widget/auth0.widget-tests.ts b/auth0.widget/auth0.widget-tests.ts index 012e9b9769..f44601986e 100644 --- a/auth0.widget/auth0.widget-tests.ts +++ b/auth0.widget/auth0.widget-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// var widget: Auth0WidgetStatic = new Auth0Widget({ diff --git a/auth0.widget/auth0.widget.d.ts b/auth0.widget/auth0.widget.d.ts index 20694526c3..e36a7f868a 100644 --- a/auth0.widget/auth0.widget.d.ts +++ b/auth0.widget/auth0.widget.d.ts @@ -3,7 +3,7 @@ // Definitions by: Robert McLaws // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Auth0WidgetStatic { diff --git a/auth0/auth0-tests.ts b/auth0/auth0-tests.ts index 9cd903b306..a1357246f3 100644 --- a/auth0/auth0-tests.ts +++ b/auth0/auth0-tests.ts @@ -1,23 +1,51 @@ -/// +/// -var auth0 = new Auth0({ - domain: 'mine.auth0.com', - clientID: 'dsa7d77dsa7d7', - callbackURL: 'http://my-app.com/callback', - callbackOnLocationHash: true +import * as auth0 from 'auth0'; + +const management = new auth0.ManagementClient({ + token: '{YOUR_API_V2_TOKEN}', + domain: '{YOUR_ACCOUNT}.auth0.com' }); -auth0.login({ - connection: 'google-oauth2', - popup: true, - popupOptions: { - width: 450, - height: 800 - } -}, (err, profile, idToken, accessToken, state) => { - if (err) { - alert("something went wrong: " + err.message); - return; - } - alert('hello ' + profile.name); - }); +const auth = new auth0.AuthenticationClient({ + domain: '{YOUR_ACCOUNT}.auth0.com', + clientId: '{OPTIONAL_CLIENT_ID}' +}); + +// Using a callback. +management.getUsers((err: Error, users: auth0.User[]) => { + if (err) { + // Handle error. + } + console.log(users); +}); + +// Using a Promise. +management + .getUsers() + .then((users) => { + console.log(users); + }) + .catch((err) => { + // Handle the error. + }); + +management + .createUser({ + connection: 'My-Connection', + email: 'hi@me.co', + }).then((user) => { + console.log(user); + }).catch((err) => { + // Handle the error. + }); + +auth + .requestChangePasswordEmail({ + connection: 'My-Connection', + email: 'hi@me.co', + }).then((response) => { + console.log(response); + }).catch((err) => { + // Handle the error. + }); diff --git a/auth0/auth0.d.ts b/auth0/auth0.d.ts index 0608674ae7..e367d30411 100644 --- a/auth0/auth0.d.ts +++ b/auth0/auth0.d.ts @@ -1,131 +1,95 @@ -// Type definitions for Auth0.js -// Project: http://auth0.com -// Definitions by: Robert McLaws +// Type definitions for auth0 v2.3.1 +// Project: https://github.com/auth0/node-auth0 +// Definitions by: Seth Westphal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/** Extensions to the browser Window object. */ -interface Window { - /** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */ +/// + +declare module "auth0" { + + import * as Promise from 'bluebird'; + + export interface ManagementClientOptions { token: string; -} + domain?: string; + } -/** This is the interface for the main Auth0 client. */ -interface Auth0Static { - - new(options: Auth0ClientOptions): Auth0Static; - changePassword(options: any, callback?: Function): void; - decodeJwt(jwt: string): any; - login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void; - loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - logout(query: string): void; - getConnections(callback?: Function): void; - getDelegationToken(targetClientId: string, id_token: string, options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; - getProfile(id_token: string, callback?: Function): Auth0UserProfile; - getSSOData(withActiveDirectories: any, callback?: Function): void; - parseHash(hash: string): Auth0DecodedHash; - signup(options: Auth0SignupOptions, callback: Function): void; - validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void; -} - -/** Represents constructor options for the Auth0 client. */ -interface Auth0ClientOptions { - clientID: string; - callbackURL: string; - callbackOnLocationHash?: boolean; - domain: string; - forceJSONP?: boolean; -} - -/** Represents a normalized UserProfile. */ -interface Auth0UserProfile { - email: string; - family_name: string; - gender: string; - given_name: string; - locale: string; - name: string; - nickname: string; - picture: string; - user_id: string; - /** Represents one or more Identities that may be associated with the User. */ - identities: Auth0Identity[]; - user_metadata?: any; - app_metadata?: any; -} - -/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */ -interface MicrosoftUserProfile extends Auth0UserProfile { - emails: string[]; -} - -/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */ -interface Office365UserProfile extends Auth0UserProfile { - tenantid: string; - upn: string; -} - -/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */ -interface AdfsUserProfile extends Auth0UserProfile { - issuer: string; -} - -/** Represents multiple identities assigned to a user. */ -interface Auth0Identity { - access_token: string; + export interface UserData { connection: string; - isSocial: boolean; - provider: string; - user_id: string; -} - -interface Auth0DecodedHash { - access_token: string; - id_token: string; - profile: Auth0UserProfile; - state: any; -} - -interface Auth0PopupOptions { - width: number; - height: number; -} - -interface Auth0LoginOptions { - auto_login?: boolean; - connection?: string; email?: string; username?: string; password?: string; - popup?: boolean; - popupOptions?: Auth0PopupOptions; -} + phone_number?: string; + user_metadata?: {}; + email_verified?: boolean; + app_metadata?: {}; + } -interface Auth0SignupOptions extends Auth0LoginOptions { - auto_login: boolean; -} + export interface GetUsersData { + per_page?: number; + page?: number; + include_totals?: boolean; + sort?: string; + connection?: string; + fields?: string; + include_fields?: boolean; + q?: string; + search_engine?: string; + } -interface Auth0Error { - code: any; - details: any; - name: string; - message: string; - status: any; -} + export interface User { + email?: string; + email_verified?: boolean; + username?: string; + phone_number?: string; + phone_verified?: boolean; + user_id?: string; + created_at?: string; + updated_at?: string; + identities?: Identity[]; + app_metadata?: {}; + user_metadata?: {}; + picture?: string; + name?: string; + nickname?: string; + multifactor?: string[]; + last_ip?: string; + last_login?: string; + logins_count?: number; + blocked?: boolean; + } -/** Represents the response from an API Token Delegation request. */ -interface Auth0DelegationToken { - /** The length of time in seconds the token is valid for. */ - expires_in: string; - /** The JWT for delegated access. */ - id_token: string; - /** The type of token being returned. Possible values: "Bearer" */ - token_type: string; -} + export interface Identity { + connection: string; + user_id: string; + provider: string; + isSocial: boolean; + } -declare var Auth0: Auth0Static; + export class ManagementClient { + constructor(options: ManagementClientOptions); + + getUsers(params?: GetUsersData): Promise; + getUsers(params?: GetUsersData, cb?: (err: Error, users: User[]) => void): void; + createUser(data: UserData): Promise; + createUser(data: UserData, cb: (err: Error, data: User) => void): void; + } + + export interface AuthenticationClientOptions { + clientId?: string; + domain: string; + } + + export interface RequestChangePasswordEmailData { + connection: string; + email: string; + } + + export class AuthenticationClient { + constructor(options: AuthenticationClientOptions); + + requestChangePasswordEmail(data: RequestChangePasswordEmailData): Promise; + requestChangePasswordEmail(data: RequestChangePasswordEmailData, cb: (err: Error, message: string) => void): void; + } -declare module "auth0" { - export = Auth0 } diff --git a/autobahn/autobahn.d.ts b/autobahn/autobahn.d.ts index 97837b52d0..bb7a0c86ae 100644 --- a/autobahn/autobahn.d.ts +++ b/autobahn/autobahn.d.ts @@ -45,7 +45,7 @@ declare namespace autobahn { interface IInvocation { caller?: number; - progress?: boolean; + progress?: (args : any[], kwargs : any) => void; procedure: string; } @@ -163,6 +163,7 @@ declare namespace autobahn { } interface IPublishOptions { + acknowledge?: boolean; exclude?: number[]; eligible?: number[]; disclose_me?: Boolean; diff --git a/autobind-decorator/autobind-decorator-tests.ts b/autobind-decorator/autobind-decorator-tests.ts new file mode 100644 index 0000000000..e428604802 --- /dev/null +++ b/autobind-decorator/autobind-decorator-tests.ts @@ -0,0 +1,43 @@ +/// + +import autobind = require('autobind-decorator'); + +class Test { + public static what: string = 'static'; + + @autobind + public static test(): void { + console.log(this.what); + } + + public constructor(public what: string) { + this.what = what; + } + + @autobind + public test(): void { + console.warn(this.what); + } +} + +const tester: Test = new Test('bind'); +const { test } = tester; +tester.test(); // warns 'bind'. +test(); // warns 'bind'. +Test.test(); // logs 'static'. + +@autobind +class Component { + public constructor(private someMember: string) { + this.someMember = someMember; + } + + public someMethod(): void { + console.error(this.someMember); + } +} + +const component: Component = new Component('React vs Angular2'); +const { someMethod } = component; +component.someMethod(); // errors 'React vs Angular2' +someMethod(); // errors 'React vs Angular2' diff --git a/autobind-decorator/autobind-decorator.d.ts b/autobind-decorator/autobind-decorator.d.ts new file mode 100644 index 0000000000..51ba89c9bf --- /dev/null +++ b/autobind-decorator/autobind-decorator.d.ts @@ -0,0 +1,10 @@ +// Type definitions for autobind-decorator v1.3.3 +// Project: https://github.com/andreypopp/autobind-decorator +// Definitions by: Ivo Stratev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'autobind-decorator' { + function autobind(target: TFunction): TFunction | void; + function autobind(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void; + export = autobind; +} diff --git a/autobind-decorator/autobind-decorator.ts.tscparams b/autobind-decorator/autobind-decorator.ts.tscparams new file mode 100644 index 0000000000..1ee3d05cb6 --- /dev/null +++ b/autobind-decorator/autobind-decorator.ts.tscparams @@ -0,0 +1 @@ +--experimentalDecorators diff --git a/autosize/autosize-tests.ts b/autosize/autosize-tests.ts new file mode 100644 index 0000000000..23686fbd88 --- /dev/null +++ b/autosize/autosize-tests.ts @@ -0,0 +1,10 @@ +/// + +// from a NodeList +autosize(document.querySelectorAll('textarea')); + +// from a single Node +autosize(document.querySelector('textarea')); + +// from a single element +autosize(document.getElementById('my-textarea')); diff --git a/autosize/autosize.d.ts b/autosize/autosize.d.ts new file mode 100644 index 0000000000..0a8a696c3d --- /dev/null +++ b/autosize/autosize.d.ts @@ -0,0 +1,17 @@ +// Type definitions for jquery.autosize 3.0.7 +// Project: http://www.jacklmoore.com/autosize/ +// Definitions by: Aaron T. King +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace autosize { + interface AutosizeStatic { + (el: Element): void; + (el: NodeList): void; + } +} + +declare var autosize: autosize.AutosizeStatic; + +declare module 'autosize' { + export = autosize; +} diff --git a/avoscloud-sdk/avoscloud-sdk.d.ts b/avoscloud-sdk/avoscloud-sdk.d.ts index af904a6c8c..deb416290d 100644 --- a/avoscloud-sdk/avoscloud-sdk.d.ts +++ b/avoscloud-sdk/avoscloud-sdk.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "avoscloud-sdk" { - namespace AV{ + namespace AV { var applicationId: string; var applicationKey: string; @@ -301,6 +301,7 @@ declare module "avoscloud-sdk" { fetch(options?: Object.FetchOptions): Promise; get(attr: string): any; getACL(): ACL; + getObjectId(): string; has(attr: string): boolean; hasChanged(attr: string): boolean; increment(attr: string, amount?: number): any; @@ -529,6 +530,7 @@ declare module "avoscloud-sdk" { constructor(objectClass: any); + static and(...var_args: Query[]): Query; static or(...var_args: Query[]): Query; addAscending(key: string): Query; @@ -628,7 +630,7 @@ declare module "avoscloud-sdk" { signUp(attrs: any, options?: SuccessFailureOptions): Promise; logIn(options?: SuccessFailureOptions): Promise; fetch(options?: SuccessFailureOptions): Promise; - save(arg1: any, arg2: any, arg3: any): Promise; + save(arg1?: any, arg2?: any, arg3?: any): Promise; authenticated(): boolean; isCurrent(): boolean; diff --git a/aws-lambda/aws-lambda-tests.ts b/aws-lambda/aws-lambda-tests.ts new file mode 100644 index 0000000000..f562b59d3d --- /dev/null +++ b/aws-lambda/aws-lambda-tests.ts @@ -0,0 +1,40 @@ +/// + +import lambda = require('aws-lambda'); + +var str: string; +var date: Date; +var anyObj: any; +var num: number; +var identity: lambda.CognitoIdentity; +var error: Error; +var b: boolean; +var clientCtx: lambda.ClientContext; + +/* Context */ +var context: lambda.Context; + +b = context.callbackWaitsForEmptyEventLoop; +str = context.functionName; +str = context.functionVersion; +str = context.invokedFunctionArn; +num = context.memoryLimitInMB; +str = context.awsRequestId; +str = context.logGroupName; +str = context.logStreamName; +identity = context.identity; +clientCtx = context.clientContext; + +/* CognitoIdentity */ +var identity: lambda.CognitoIdentity; + +str = identity.cognitoIdentityId; +str = identity.cognitoIdentityPoolId; + +/* Callback */ +function callback(cb: lambda.Callback) { + cb(); + cb(null); + cb(error); + cb(null, anyObj); +} \ No newline at end of file diff --git a/aws-lambda/aws-lambda.d.ts b/aws-lambda/aws-lambda.d.ts new file mode 100644 index 0000000000..c9a66a3783 --- /dev/null +++ b/aws-lambda/aws-lambda.d.ts @@ -0,0 +1,68 @@ +// Type definitions for AWS Lambda +// Project: http://docs.aws.amazon.com/lambda +// Definitions by: James Darbyshire , Michael Skarum , Stef Heyenrath +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "aws-lambda" { + // Context + // http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html + interface Context { + // Properties + callbackWaitsForEmptyEventLoop: boolean; + functionName: string; + functionVersion: string; + invokedFunctionArn: string; + memoryLimitInMB: number; + awsRequestId: string; + logGroupName: string; + logStreamName: string; + identity?: CognitoIdentity; + clientContext?: ClientContext; + + // Functions + getRemainingTimeInMillis(): number; + + // Functions for compatibility with earlier Node.js Runtime v0.10.42 + log(message: string, object: any): void; + fail(message: string): void; + succeed(message: string): void; + succeed(object: any): void; + succeed(message: string, object: any): void; + } + + interface CognitoIdentity { + cognitoIdentityId: string; + cognitoIdentityPoolId: string; + } + + interface ClientContext { + client: ClientContextClient; + Custom?: any; + env: ClientContextEnv; + } + + interface ClientContextClient { + installationId: string; + appTitle: string; + appVersionName: string; + appVersionCode: string; + appPackageName: string; + } + + interface ClientContextEnv { + platformVersion: string; + platform: string; + make: string; + model: string; + locale: string; + } + + /** + * Optional callback parameter. + * http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html + * + * @param error – an optional parameter that you can use to provide results of the failed Lambda function execution. + * @param result – an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible. + */ + export type Callback = (error?: Error, result?: any) => void; +} \ No newline at end of file diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index 94e13c93d2..869f61071b 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -9,1465 +9,2263 @@ declare module "aws-sdk" { - export var config: ClientConfig; + export var config: ClientConfig; - export function Config(json: any): void; + export function Config(json: any): void; - export class Credentials { - constructor(accessKeyId: string, secretAccessKey: string, sessionToken?: string); - accessKeyId: string; - } + export class Credentials { + constructor(accessKeyId: string, secretAccessKey: string, sessionToken?: string); + accessKeyId: string; + } - export class EnvironmentCredentials extends Credentials { - constructor(profile: string); - } + export class EnvironmentCredentials extends Credentials { + constructor(profile: string); + } - export interface Logger { - write?: (chunk: any, encoding?: string, callback?: () => void) => void; - log?: (...messages: any[]) => void; - } + export interface Logger { + write?: (chunk: any, encoding?: string, callback?: () => void) => void; + log?: (...messages: any[]) => void; + } - export interface HttpOptions { - proxy?: string; - agent?: any; - timeout?: number; - xhrAsync?: boolean; - xhrWithCredentials?: boolean; - } - - export class Endpoint { - constructor(endpoint:string); - - host:string; - hostname:string; - href:string; - port:number; - protocol:string; - } + export interface HttpOptions { + proxy?: string; + agent?: any; + timeout?: number; + xhrAsync?: boolean; + xhrWithCredentials?: boolean; + } - export interface Services { - autoscaling?: any; - cloudformation?: any; - cloudfront?: any; - cloudsearch?: any; - cloudsearchdomain?: any; - cloudtrail?: any; - cloudwatch?: any; - cloudwatchlogs?: any; - cognitoidentity?: any; - cognitosync?: any; - datapipeline?: any; - directconnect?: any; - dynamodb?: any; - ec2?: any; - ecs?: any; - elasticache?: any; - elasticbeanstalk?: any; - elastictranscoder?: any; - elb?: any; - emr?: any; - glacier?: any; - httpOptions?: HttpOptions; - iam?: any; - importexport?: any; - kinesis?: any; - opsworks?: any; - rds?: any; - redshift?: any; - route53?: any; - route53domains?: any; - s3?: any; - ses?: any; - simpledb?: any; - sns?: any; - sqs?: any; - storagegateway?: any; - sts?: any; - support?: any; - swf?: any; - } + export class Endpoint { + constructor(endpoint: string); - export interface ClientConfigPartial extends Services { - credentials?: Credentials; - region?: string; - accessKeyId: string; - secretAccessKey: string; - computeChecksums?: boolean; - convertResponseTypes?: boolean; - logger?: Logger; - maxRedirects?: number; - maxRetries?: number; - paramValidation?: boolean; - s3ForcePathStyle?: boolean; - apiVersion?: any; - apiVersions?: Services; - signatureVersion?: string; - sslEnabled?: boolean; - systemClockOffset?: number; - } + host: string; + hostname: string; + href: string; + port: number; + protocol: string; + } - export interface ClientConfig extends ClientConfigPartial { - update?: (options: ClientConfigPartial, allUnknownKeys?: boolean) => void; - getCredentials?: (callback: (err?: any) => void) => void ; - loadFromPath?: (path: string) => void; - credentials: Credentials; - region: string; - } + interface AwsError extends Error { + stack: string; + } - export class SQS { - constructor(options?: any); - endpoint:Endpoint; - - addPermission(params: SQS.AddPermissionParams, callback: (err:Error, data:any) => void): void; - changeMessageVisibility(params: SQS.ChangeMessageVisibilityParams, callback: (err:Error, data:any) => void): void; - changeMessageVisibilityBatch(params: SQS.ChangeMessageVisibilityBatchParams, callback: (err:Error, data:SQS.ChangeMessageVisibilityBatchResponse) => void): void; - createQueue(params: SQS.CreateQueueParams, callback: (err: Error, data: SQS.CreateQueueResult) => void): void; - deleteMessage(params: SQS.DeleteMessageParams, callback: (err: Error, data: any) => void): void; - deleteMessageBatch(params: SQS.DeleteMessageBatchParams, callback: (err: Error, data: SQS.DeleteMessageBatchResult) => void): void; - deleteQueue(params: { QueueUrl: string; }, callback: (err: Error, data: any) => void): void; - getQueueAttributes(params: SQS.GetQueueAttributesParams, callback: (err: Error, data: SQS.GetQueueAttributesResult) => void): void; - getQueueUrl(params: SQS.GetQueueUrlParams, callback: (err: Error, data: { QueueUrl: string; }) => void): void; - listDeadLetterSourceQueues(params: {QueueUrl:string}, callback: (err: Error, data: {queueUrls: string[]}) => void): void; - listQueues(params: {QueueNamePrefix?:string}, callback: (err: Error, data: {QueueUrls: string[]}) => void): void; - purgeQueue(params: {QueueUrl: string}, callback: (err: Error, data: any) => void): void; - receiveMessage(params: SQS.ReceiveMessageParams, callback: (err: Error, data: SQS.ReceiveMessageResult) => void): void; - removePermission(params: {QueueUrl: string, Label: string}, callback: (err: Error, data: any) => void): void; - sendMessage(params: SQS.SendMessageParams, callback: (err: Error, data: SQS.SendMessageResult) => void): void; - sendMessageBatch(params: SQS.SendMessageBatchParams, callback: (err: Error, data: SQS.SendMessageBatchResult) => void): void; - setQueueAttributes(params: SQS.SetQueueAttributesParams, callback: (err: Error, data: any) => void): void; - } + export interface RetryDelayOption { + base?: number; + customBackoff?: (retryCount: number) => number; + } - export class SES { - constructor(options?: any); - public client: Ses.Client; - } + export interface Ebs { + SnapshotId?: string; + VolumeSize?: number; + VolumeType?: string; + DeleteOnTermination?: boolean; + Iops?: number; + Encrypted?: boolean; + } - export class SNS { - constructor(options?: any); - publish(request: Sns.PublishRequest, callback: (err: any, data: any) => void): void; - } - - export class SimpleWorkflow { - constructor(options?: any); - public client: Swf.Client; - } + export interface BlockDeviceMapping { + VirtualName?: string; + DeviceName: string; + Ebs?: Ebs; + NoDevice?: boolean; + } - export class S3 { - constructor(options?: any); - putObject(params: s3.PutObjectRequest, callback: (err: any, data: any) => void): void; - getObject(params: s3.GetObjectRequest, callback: (err: any, data: any) => void): void; - } + export interface InstanceMonitoring { + SpotPrice?: string; + Enabled?: boolean; + } - export class STS{ - constructor(options?: any); + export interface Filter { + Name?: string; + Values?: boolean; + } + + export interface StepAdjustment { + scalingAdjustment: number; + metricIntervalLowerBound?: number; + metricIntervalUpperBound?: number; + } + + export interface Tags { + resourceId?: string; + resourceType?: string; + key: string; + value?: string; + propagateAtLaunch?: boolean; + } + + export interface Services { + autoscaling?: any; + cloudformation?: any; + cloudfront?: any; + cloudsearch?: any; + cloudsearchdomain?: any; + cloudtrail?: any; + cloudwatch?: any; + cloudwatchlogs?: any; + cognitoidentity?: any; + cognitosync?: any; + datapipeline?: any; + directconnect?: any; + dynamodb?: any; + ec2?: any; + ecs?: any; + elasticache?: any; + elasticbeanstalk?: any; + elastictranscoder?: any; + elb?: any; + emr?: any; + glacier?: any; + httpOptions?: HttpOptions; + iam?: any; + importexport?: any; + kinesis?: any; + opsworks?: any; + rds?: any; + redshift?: any; + route53?: any; + route53domains?: any; + s3?: any; + ses?: any; + simpledb?: any; + sns?: any; + sqs?: any; + storagegateway?: any; + sts?: any; + support?: any; + swf?: any; + } + + export interface ClientConfigPartial extends Services { + credentials?: Credentials; + region?: string; + accessKeyId?: string; + secretAccessKey?: string; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + logger?: Logger; + maxRedirects?: number; + maxRetries?: number; + paramValidation?: boolean; + s3ForcePathStyle?: boolean; + apiVersion?: any; + apiVersions?: Services; + signatureVersion?: string; + sslEnabled?: boolean; + systemClockOffset?: number; + } + + export interface ClientConfig extends ClientConfigPartial { + update?: (options: ClientConfigPartial, allUnknownKeys?: boolean) => void; + getCredentials?: (callback: (err?: any) => void) => void; + loadFromPath?: (path: string) => void; + credentials: Credentials; + region: string; + } + + export class Lambda { + constructor(options?: any); + endpoint: Endpoint; + + addPermission(params: Lambda.AddPermissionParams, callback: (err: AwsError, data: any) => void): void; + createAlias(params: Lambda.CreateAliasParams, callback: (err: AwsError, data: any) => void): void; + createEventSourceMapping(params: Lambda.CreateEventSourceMappingParams, callback: (err: AwsError, data: any) => void): void; + createFunction(params: Lambda.CreateFunctionParams, callback: (err: AwsError, data: any) => void): void; + deleteAlias(params: Lambda.DeleteAliasParams, callback: (err: AwsError, data: any) => void): void; + deleteEventSourceMapping(params: Lambda.DeleteEventSourceMappingParams, callback: (err: AwsError, data: any) => void): void; + deleteFunction(params: Lambda.DeleteFunctionParams, callback: (err: AwsError, data: any) => void): void; + getAlias(params: Lambda.GetAliasParams, callback: (err: AwsError, data: any) => void): void; + getEventSourceMapping(params: Lambda.GetEventSourceMappingParams, callback: (err: AwsError, data: any) => void): void; + getFunction(params: Lambda.GetFunctionParams, callback: (err: AwsError, data: any) => void): void; + getFunctionConfiguration(params: Lambda.GetFunctionConfigurationParams, callback: (err: AwsError, data: any) => void): void; + getPolicy(params: Lambda.GetPolicyParams, callback: (err: AwsError, data: any) => void): void; + invoke(params: Lambda.InvokeParams, callback: (err: AwsError, data: any) => void): void; + listAliases(params: Lambda.ListAliasesParams, callback: (err: AwsError, data: any) => void): void; + listEventSourceMappings(params: Lambda.ListEventSourceMappingsParams, callback: (err: AwsError, data: any) => void): void; + listFunctions(params: Lambda.ListFunctionsParams, callback: (err: AwsError, data: any) => void): void; + listVersionsByFunction(params: Lambda.ListVersionsByFunctionParams, callback: (err: AwsError, data: any) => void): void; + publishVersion(params: Lambda.PublishVersionParams, callback: (err: AwsError, data: any) => void): void; + removePermission(params: Lambda.RemovePermissionParams, callback: (err: AwsError, data: any) => void): void; + updateAlias(params: Lambda.UpdateAliasParams, callback: (err: AwsError, data: any) => void): void; + updateEventSourceMapping(params: Lambda.UpdateEventSourceMappingParams, callback: (err: AwsError, data: any) => void): void; + updateFunctionCode(params: Lambda.UpdateFunctionCodeParams, callback: (err: AwsError, data: any) => void): void; + updateFunctionConfiguration(params: Lambda.UpdateFunctionConfigurationParams, callback: (err: AwsError, data: any) => void): void; + } + + export class AutoScaling { + constructor(options?: any); + endpoint: Endpoint; + + attachInstances(params: AutoScaling.AttachInstancesParams, callback: (err: AwsError, data: any) => void): void; + attachLoadBalancers(params: AutoScaling.AttachLoadBalancersParams, callback: (err: AwsError, data: any) => void): void; + attachLoadBalancerTargetGroups(param: AutoScaling.AttachLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void; + completeLifecycleAction(param: AutoScaling.CompleteLifecycleActionParams, callback: (err: AwsError, data: any) => void): void; + createAutoScalingGroup(param: AutoScaling.CreateAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void; + createLaunchConfiguration(param: AutoScaling.CreateLaunchConfigurationParams, callback: (err: AwsError, data: any) => void): void; + createOrUpdateTags(param: AutoScaling.CreateOrUpdateTagsParams, callback: (err: AwsError, data: any) => void): void; + deleteAutoScalingGroup(param: AutoScaling.DeleteAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void; + deleteLaunchConfiguration(param: AutoScaling.DeleteLaunchConfigurationParams, callback: (err: AwsError, data: any) => void): void; + deleteLifecycleHook(param: AutoScaling.DeleteLifecycleHookParams, callback: (err: AwsError, data: any) => void): void; + deleteNotificationConfiguration(param: AutoScaling.DeleteNotificationConfigurationParams, callback: (err: AwsError, data: any) => void): void; + deletePolicy(param: AutoScaling.DeletePolicyParams, callback: (err: AwsError, data: any) => void): void; + deleteScheduledAction(param: AutoScaling.DeleteScheduledActionParams, callback: (err: AwsError, data: any) => void): void; + deleteTags(param: AutoScaling.DeleteTagsParams, callback: (err: AwsError, data: any) => void): void; + describeAccountLimits(callback: (err: AwsError, data: any) => void): void; + describeAdjustmentTypes(callback: (err: AwsError, data: any) => void): void; + describeAutoScalingGroups(param: AutoScaling.DescribeAutoScalingGroupsParams, callback: (err: AwsError, data: any) => void): void; + describeAutoScalingInstances(param: AutoScaling.DescribeAutoScalingInstancesParams, callback: (err: AwsError, data: any) => void): void; + describeAutoScalingNotificationTypes(callback: (err: AwsError, data: any) => void): void; + describeLaunchConfigurations(param: AutoScaling.DescribeLaunchConfigurationsParams, callback: (err: AwsError, data: any) => void): void; + describeLifecycleHooks(param: AutoScaling.DescribeLifecycleHooksParams, callback: (err: AwsError, data: any) => void): void; + describeLifecycleHookTypes(callback: (err: AwsError, data: any) => void): void; + describeLoadBalancers(param: AutoScaling.DescribeLoadBalancersParams, callback: (err: AwsError, data: any) => void): void; + describeLoadBalancerTargetGroups(param: AutoScaling.DescribeLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void; + describeMetricCollectionTypes(callback: (err: AwsError, data: any) => void): void; + describeNotificationConfigurations(param: AutoScaling.DescribeNotificationConfigurationsParams, callback: (err: AwsError, data: any) => void): void; + describePolicies(param: AutoScaling.DescribePoliciesParams, callback: (err: AwsError, data: any) => void): void; + describeScalingActivities(param: AutoScaling.DescribeScalingActivitiesParams, callback: (err: AwsError, data: any) => void): void; + describeScalingProcessTypes(callback: (err: AwsError, data: any) => void): void; + describeScheduledActions(param: AutoScaling.DescribeScheduledActionsParams, callback: (err: AwsError, data: any) => void): void; + describeTags(param: AutoScaling.DescribeTagsParams, callback: (err: AwsError, data: any) => void): void; + describeTerminationPolicyTypes(callback: (err: AwsError, data: any) => void): void; + detachInstances(param: AutoScaling.DetachInstancesParams, callback: (err: AwsError, data: any) => void): void; + detachLoadBalancers(param: AutoScaling.DetachLoadBalancersParams, callback: (err: AwsError, data: any) => void): void; + detachLoadBalancerTargetGroups(param: AutoScaling.DetachLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void; + disableMetricsCollection(param: AutoScaling.DisableMetricsCollectionParams, callback: (err: AwsError, data: any) => void): void; + enableMetricsCollection(param: AutoScaling.EnableMetricsCollectionParams, callback: (err: AwsError, data: any) => void): void; + enterStandby(param: AutoScaling.EnterStandbyParams, callback: (err: AwsError, data: any) => void): void; + executePolicy(param: AutoScaling.ExecutePolicyParams, callback: (err: AwsError, data: any) => void): void; + exitStandby(param: AutoScaling.ExitStandbyParams, callback: (err: AwsError, data: any) => void): void; + putLifecycleHook(param: AutoScaling.PutLifecycleHookParams, callback: (err: AwsError, data: any) => void): void; + putNotificationConfiguration(param: AutoScaling.PutNotificationConfigurationParams, callback: (err: AwsError, data: any) => void): void; + putScalingPolicy(param: AutoScaling.PutScalingPolicyParams, callback: (err: AwsError, data: any) => void): void; + putScheduledUpdateGroupAction(param: AutoScaling.PutScheduledUpdateGroupActionParams, callback: (err: AwsError, data: any) => void): void; + recordLifecycleActionHeartbeat(params: AutoScaling.RecordLifecycleActionHeartbeatParams, callback: (err: AwsError, data: any) => void): void; + resumeProcesses(params: AutoScaling.ResumeProcessesParams, callback: (err: AwsError, data: any) => void): void; + setDesiredCapacity(params: AutoScaling.SetDesiredCapacityParams, callback: (err: AwsError, data: any) => void): void; + setInstanceHealth(params: AutoScaling.SetInstanceHealthParams, callback: (err: AwsError, data: any) => void): void; + setInstanceProtection(params: AutoScaling.SetInstanceProtectionParams, callback: (err: AwsError, data: any) => void): void; + suspendProcesses(params: AutoScaling.SuspendProcessesParams, callback: (err: AwsError, data: any) => void): void; + terminateInstanceInAutoScalingGroup(params: AutoScaling.TerminateInstanceInAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void; + updateAutoScalingGroup(params: AutoScaling.UpdateAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void; + } + + export class SQS { + constructor(options?: any); + endpoint: Endpoint; + + addPermission(params: SQS.AddPermissionParams, callback: (err: AwsError, data: any) => void): void; + changeMessageVisibility(params: SQS.ChangeMessageVisibilityParams, callback: (err: AwsError, data: any) => void): void; + changeMessageVisibilityBatch(params: SQS.ChangeMessageVisibilityBatchParams, callback: (err: AwsError, data: SQS.ChangeMessageVisibilityBatchResponse) => void): void; + createQueue(params: SQS.CreateQueueParams, callback: (err: AwsError, data: SQS.CreateQueueResult) => void): void; + deleteMessage(params: SQS.DeleteMessageParams, callback: (err: AwsError, data: any) => void): void; + deleteMessageBatch(params: SQS.DeleteMessageBatchParams, callback: (err: AwsError, data: SQS.DeleteMessageBatchResult) => void): void; + deleteQueue(params: { QueueUrl: string; }, callback: (err: AwsError, data: any) => void): void; + getQueueAttributes(params: SQS.GetQueueAttributesParams, callback: (err: AwsError, data: SQS.GetQueueAttributesResult) => void): void; + getQueueUrl(params: SQS.GetQueueUrlParams, callback: (err: AwsError, data: { QueueUrl: string; }) => void): void; + listDeadLetterSourceQueues(params: { QueueUrl: string }, callback: (err: AwsError, data: { queueUrls: string[] }) => void): void; + listQueues(params: { QueueNamePrefix?: string }, callback: (err: AwsError, data: { QueueUrls: string[] }) => void): void; + purgeQueue(params: { QueueUrl: string }, callback: (err: AwsError, data: any) => void): void; + receiveMessage(params: SQS.ReceiveMessageParams, callback: (err: AwsError, data: SQS.ReceiveMessageResult) => void): void; + removePermission(params: { QueueUrl: string, Label: string }, callback: (err: AwsError, data: any) => void): void; + sendMessage(params: SQS.SendMessageParams, callback: (err: AwsError, data: SQS.SendMessageResult) => void): void; + sendMessageBatch(params: SQS.SendMessageBatchParams, callback: (err: AwsError, data: SQS.SendMessageBatchResult) => void): void; + setQueueAttributes(params: SQS.SetQueueAttributesParams, callback: (err: AwsError, data: any) => void): void; + } + + export class SES { + constructor(options?: any); + endpoint: Endpoint; + + sendEmail(params: any, callback: (err: any, data: SES.SendEmailResult) => void): void; + } + + export class SNS { + constructor(options?: any); + endpoint: Endpoint; + + publish(request: Sns.PublishRequest, callback: (err: any, data: any) => void): void; + } + + export class SWF { + constructor(options?: any); + endpoint: Endpoint; + + countClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + countOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + countPendingActivityTasks(params: any, callback: (err: any, data: any) => void): void; + countPendingDecisionTasks(params: any, callback: (err: any, data: any) => void): void; + deprecateActivityType(params: any, callback: (err: any, data: any) => void): void; + deprecateDomain(params: any, callback: (err: any, data: any) => void): void; + deprecateWorkflowType(params: any, callback: (err: any, data: any) => void): void; + describeActivityType(params: any, callback: (err: any, data: any) => void): void; + describeDomain(params: any, callback: (err: any, data: any) => void): void; + describeWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + describeWorkflowType(params: any, callback: (err: any, data: any) => void): void; + getWorkflowExecutionHistory(params: any, callback: (err: any, data: any) => void): void; + listActivityTypes(params: any, callback: (err: any, data: any) => void): void; + listClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + listDomains(params: any, callback: (err: any, data: any) => void): void; + listOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + listWorkflowTypes(params: any, callback: (err: any, data: any) => void): void; + pollForActivityTask(params: any, callback: (err: any, data: Swf.ActivityTask) => void): void; + pollForDecisionTask(params: any, callback: (err: any, data: Swf.DecisionTask) => void): void; + recordActivityTaskHeartbeat(params: any, callback: (err: any, data: any) => void): void; + registerActivityType(params: any, callback: (err: any, data: any) => void): void; + registerDomain(params: any, callback: (err: any, data: any) => void): void; + registerWorkflowType(params: any, callback: (err: any, data: any) => void): void; + requestCancelWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + respondActivityTaskCanceled(params: Swf.RespondActivityTaskCanceledRequest, callback: (err: any, data: any) => void): void; + respondActivityTaskCompleted(params: Swf.RespondActivityTaskCompletedRequest, callback: (err: any, data: any) => void): void; + respondActivityTaskFailed(params: Swf.RespondActivityTaskFailedRequest, callback: (err: any, data: any) => void): void; + respondDecisionTaskCompleted(params: Swf.RespondDecisionTaskCompletedRequest, callback: (err: any, data: any) => void): void; + signalWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + startWorkflowExecution(params: any, callback: (err: any, data: Swf.StartWorkflowExecutionResult) => void): void; + terminateWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + + } + + export class S3 { + constructor(options?: any); + endpoint: Endpoint; + + getObject(params: s3.GetObjectRequest, callback?: (err: Error, data: any) => void): any; + putObject(params: s3.PutObjectRequest, callback: (err: Error, data: any) => void): void; + deleteObject(params: s3.DeleteObjectRequest, callback: (err: Error, data: any) => void): void; + headObject(params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void; + getSignedUrl(operation: string, params: any): string; + getSignedUrl(operation: string, params: any, callback: (err: Error, url: string) => void): void; + upload(params?: s3.PutObjectRequest, options?: s3.UploadOptions, callback?: (err: Error, data: any) => void): void; + listObjects(params: s3.ListObjectRequest, callback: (err: Error, data: s3.ListObjectResponse) => void): void; + listObjectsV2(params: s3.ListObjectV2Request, callback: (err: Error, data: s3.ListObjectV2Response) => void): void; + waitFor(state: string, params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void; + + createMultipartUpload(params: any, callback: (err: Error, data: any) => void): void; + uploadPart(params: any, callback: (err: Error, data: any) => void): void; + listParts(params: any, callback: (err: Error, data: any) => void): void; + completeMultipartUpload(params: any, callback: (err: Error, data: any) => void): void; + } + + export class STS { + constructor(options?: any); + endpoint: Endpoint; /** * Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) that you can use to access AWS resources that you might not normally have access to. */ - assumeRole(params: sts.AssumeRoleParams, callback: (err: any, data: sts.AssumeRoleCallbackData) => void): void; + assumeRole(params: sts.AssumeRoleParams, callback: (err: any, data: sts.AssumeRoleCallbackData) => void): void; /** - * Returns a set of temporary security credentials for users who have been authenticated via a SAML authentication response. + * Returns a set of temporary security credentials for users who have been authenticated via a SAML authentication response. */ - assumeRoleWithSAML(params: sts.AssumeRoleWithSAMLParams, callback: (err: any, data: any) => void): void; + assumeRoleWithSAML(params: sts.AssumeRoleWithSAMLParams, callback: (err: any, data: any) => void): void; /** * Returns a set of temporary security credentials for users who have been authenticated in a mobile or web application with a web identity provider, such as Amazon Cognito, Login with Amazon, Facebook, Google, or any OpenID Connect-compatible identity provider. */ - assumeRoleWithWebIdentity(params: sts.AssumeRoleWithWebIdentityParams, callback: (err: any, data: any) => void): void; + assumeRoleWithWebIdentity(params: sts.AssumeRoleWithWebIdentityParams, callback: (err: any, data: any) => void): void; /** * Creates a credentials object from STS response data containing credentials information. */ - credentialsFrom(params: sts.CredentialsFromParams, callback: (err: any, data: any) => void): void; + credentialsFrom(params: sts.CredentialsFromParams, callback: (err: any, data: any) => void): void; /** * Decodes additional information about the authorization status of a request from an encoded message returned in response to an AWS request. */ - decodeAuthorizationMessage(params: sts.DecodeAuthorizationMessageParams, callback: (err: any, data: any) => void): void; + decodeAuthorizationMessage(params: sts.DecodeAuthorizationMessageParams, callback: (err: any, data: any) => void): void; /** * Returns details about the IAM identity whose credentials are used to call the API. */ - getCallerIdentity(params: {}, callback: (err: any, data: any) => void): void; + getCallerIdentity(params: {}, callback: (err: any, data: any) => void): void; /** * Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) for a federated user. */ - getFederationToken(params: sts.GetFederationTokenParams, callback: (err: any, data: any) => void): void; + getFederationToken(params: sts.GetFederationTokenParams, callback: (err: any, data: any) => void): void; /** * Returns a set of temporary credentials for an AWS account or IAM user. */ - getSessionToken(params: sts.GetSessionTokenParams, callback: (err: any, data: any) => void): void; + getSessionToken(params: sts.GetSessionTokenParams, callback: (err: any, data: any) => void): void; - } + } - export class ECS { - constructor(options?: any); - /** - * Runs and maintains a desired number of tasks from a specified task definition. If the number of tasks running in a service drops below desiredCount, Amazon ECS spawns another instantiation of the task in the specified cluster. To update an existing service, see UpdateService. - */ - createService(params: ecs.CreateServicesParams, callback: (err: any, data: any) => void): void; + export class ECS { + constructor(options?: any); + endpoint: Endpoint; + /** + * Runs and maintains a desired number of tasks from a specified task definition. If the number of tasks running in a service drops below desiredCount, Amazon ECS spawns another instantiation of the task in the specified cluster. To update an existing service, see UpdateService. + */ + createService(params: ecs.CreateServicesParams, callback: (err: any, data: any) => void): void; /** * Describes one or more of your clusters. */ - describeClusters(params: ecs.DescribeClustersParams, callback: (err: any, data: any) => void): void; + describeClusters(params: ecs.DescribeClustersParams, callback: (err: any, data: any) => void): void; /** * Describes the specified services running in your cluster. */ - describeServices(params: ecs.DescribeServicesParams, callback: (err: any, data: any) => void): void; + describeServices(params: ecs.DescribeServicesParams, callback: (err: any, data: any) => void): void; /** * Describes a specified task or tasks. */ - describeTasks(params: ecs.DescribeTasksParams, callback: (err: any, data: any) => void): void; + describeTasks(params: ecs.DescribeTasksParams, callback: (err: any, data: any) => void): void; /** * Describes a task definition. You can specify a family and revision to find information about a specific task definition, or you can simply specify the family to find the latest ACTIVE revision in that family. */ - describeTaskDefinition(params: ecs.DescribeTaskDefinitionParams, callback: (err: any, data: any) => void): void; + describeTaskDefinition(params: ecs.DescribeTaskDefinitionParams, callback: (err: any, data: any) => void): void; /** * Registers a new task definition from the supplied family and containerDefinitions. Optionally, you can add data volumes to your containers with the volumes parameter. For more information about task definition parameters and defaults, see Amazon ECS Task Definitions in the Amazon EC2 Container Service Developer Guide. */ - registerTaskDefinition(params: ecs.RegisterTaskDefinitionParams, callback: (err: any, data: any) => void): void; + registerTaskDefinition(params: ecs.RegisterTaskDefinitionParams, callback: (err: any, data: any) => void): void; /** * Modifies the desired count, deployment configuration, or task definition used in a service. */ - updateService(params: ecs.UpdateServiceParams, callback: (err: any, data: any) => void): void; - } - - export class DynamoDB { - constructor(options?: any); - } - - // ========================================================== - - export module DynamoDB { - - interface _DDBDC_Generic { - TableName: string; - ExpressionAttributeNames?: string[]; - ReturnConsumedCapacity?: "INDEXES" | "TOTAL" | "NONE"; - } - - type _DDBDC_ComparisonOperator = "EQ" | "NE" | "IN" | "LE" | "LT" | "GE" | "GT" | "BETWEEN" | "NOT_NULL" | "NULL" | "CONTAINS" | "NOT_CONTAINS" | "BEGINS_WITH" - type _DDBDC_Keys = { [someKey: string]: any }; - type _DDBDC_KeyComparison = { - [someKey: string]: { - AttributeValueList: any[]; - ComparisonOperator: _DDBDC_ComparisonOperator; - } - }; - - interface _DDBDC_Reader extends _DDBDC_Generic { - ConsistentRead?: boolean; - ProjectionExpression?: string; - AttributesToGet?: string[]; - } - - interface _DDBDC_Writer extends _DDBDC_Generic { - ExpressionAttributeValues?: _DDBDC_Keys; - ReturnItemCollectionMetrics?: "SIZE" | "NONE"; - ReturnValues?: "NONE" | "ALL_OLD" | "UPDATED_OLD" | "ALL_NEW" | "UPDATED_NEW"; - ConditionExpression?: string; - ConditionalOperator?: "AND" | "OR"; - Expected?: { - [someKey: string]: { - AttributeValueList: any[]; - ComparisonOperator: _DDBDC_ComparisonOperator; - Exists: boolean; - Value: any; - } - } - } - - interface UpdateParam extends _DDBDC_Writer { - Key: _DDBDC_Keys; - AttributeUpdates: { - [someKey: string]: { - Action: "PUT" | "ADD" | "DELETE"; - Value: any - } - } - } - - interface QueryParam extends _DDBDC_Reader { - ConditionalOperator?: "AND" | "OR"; - ExclusiveStartKey?: _DDBDC_Keys; - ExpressionAttributeValues?: _DDBDC_Keys; - FilterExpression?: string; - IndexName?: string; - KeyConditionExpression?: string; - KeyConditions?: _DDBDC_KeyComparison; - Limit?: number; - QueryFilter?: _DDBDC_KeyComparison; - ScanIndexForward?: boolean; - Select?: "ALL_ATTRIBUTES" | "ALL_PROJECTED_ATTRIBUTES" | "SPECIFIC_ATTRIBUTES" | "COUNT"; - } - - interface ScanParam extends QueryParam { - Segment?: number; - ScanFilter?: _DDBDC_KeyComparison; - TotalSegments?: number; - } - - interface GetParam extends _DDBDC_Reader { - Key: _DDBDC_Keys; - } - - interface PutParam extends _DDBDC_Writer { - Item: _DDBDC_Keys; - } - - interface DeleteParam extends _DDBDC_Writer { - Key: _DDBDC_Keys; - } - - export class DocumentClient { - constructor(options?: any); - get(params: GetParam, next: (err: any, data: any) => void): void; - put(params: PutParam, next: (err: any, data: any) => void): void; - delete(params: DeleteParam, next: (err: any, data: any) => void): void; - query(params: QueryParam, next: (err: any, data: any) => void): void; - scan(params: ScanParam, next: (err: any, data: any) => void): void; - update(params: UpdateParam, next: (err: any, data: any) => void): void; - createSet(list: any[], options?: { validate?: boolean }): { values: any[], type: string }; - batchGet(params: any, next: (err: any, data: any) => void): void; - batchWrite(params: any, next: (err: any, data: any) => void): void; - } - - } - -// =========================================================== - - export module SQS { - - export interface SqsOptions { - params?: any; - endpoint?: string; - accessKeyId?: string; - secretAccessKey?: string; - sessionToken?: Credentials; - credentials?: Credentials; - credentialProvider?: any; - region?: string; - maxRetries?: number; - maxRedirects?: number; - sslEnabled?: boolean; - paramValidation?: boolean; - computeChecksums?: boolean; - convertResponseTypes?: boolean; - correctClockSkew?: boolean; - s3ForcePathStyle?: boolean; - s3BucketEndpoint?: boolean; - httpOptions?: HttpOptions; - apiVersion?: string; - apiVersions?: { [serviceName:string]: string}; - logger?: Logger; - systemClockOffset?: number; - signatureVersion?: string; - signatureCache?: boolean; - } - - export interface AddPermissionParams { - QueueUrl: string; - Label: string; - AWSAccountIds:string[]; - Actions:string[]; - } - - export interface ChangeMessageVisibilityParams { - QueueUrl: string, - ReceiptHandle: string, - VisibilityTimeout: number - } - - export interface ChangeMessageVisibilityBatchParams { - QueueUrl: string, - Entries: { Id: string; ReceiptHandle: string; VisibilityTimeout?: number; }[] - } - - export interface ChangeMessageVisibilityBatchResponse { - Successful: { Id:string }[]; - Failed: BatchResultErrorEntry[]; - } - - export interface SendMessageParams { - QueueUrl: string; - MessageBody: string; - DelaySeconds?: number; - MessageAttributes?: { [name:string]: MessageAttribute; } - } - - export interface ReceiveMessageParams { - QueueUrl: string; - MaxNumberOfMessages?: number; - VisibilityTimeout?: number; - AttributeNames?: string[]; - MessageAttributeNames?: string[]; - WaitTimeSeconds?:number; - } - - export interface DeleteMessageBatchParams { - QueueUrl: string; - Entries: DeleteMessageBatchRequestEntry[]; - } - - export interface DeleteMessageBatchRequestEntry { - Id: string; - ReceiptHandle: string; - } - - export interface DeleteMessageParams { - QueueUrl: string; - ReceiptHandle: string; - } - - export interface SendMessageBatchParams { - QueueUrl: string; - Entries: SendMessageBatchRequestEntry[]; - } - - export interface SendMessageBatchRequestEntry { - Id: string; - MessageBody: string; - DelaySeconds?: number; - MessageAttributes?: { [name:string]: MessageAttribute; } - } - - export interface CreateQueueParams { - QueueName: string; - Attributes: QueueAttributes; - } - - export interface QueueAttributes { - [name:string]: any; - DelaySeconds?: number; - MaximumMessageSize?: number; - MessageRetentionPeriod?: number; - Policy?: any; - ReceiveMessageWaitTimeSeconds?: number; - VisibilityTimeout?: number; - RedrivePolicy?: any; - } - - export interface GetQueueAttributesParams { - QueueUrl: string; - AttributeNames: string[]; - } - - export interface GetQueueAttributesResult { - Attributes: {[name:string]: string}; - } - - export interface GetQueueUrlParams { - QueueName: string; - QueueOwnerAWSAccountId?: string; - } - - export interface SendMessageResult { - MessageId: string; - MD5OfMessageBody: string; - MD5OfMessageAttributes: string; - } - - export interface ReceiveMessageResult { - Messages: Message[]; - } - - export interface Message { - MessageId: string; - ReceiptHandle: string; - MD5OfBody: string; - Body: string; - Attributes: { [name:string]:any }; - MD5OfMessageAttributes:string; - MessageAttributes: { [name:string]: MessageAttribute; } - } - - export interface MessageAttribute { - StringValue?: string; - BinaryValue?: any; //(Buffer, Typed Array, Blob, String) - StringListValues?: string[]; - BinaryListValues?: any[]; - DataType: string; - } - - export interface DeleteMessageBatchResult { - Successful: DeleteMessageBatchResultEntry[]; - Failed: BatchResultErrorEntry[]; - } - - export interface DeleteMessageBatchResultEntry { - Id: string; - } - - export interface BatchResultErrorEntry { - Id: string; - Code: string; - Message?: string; - SenderFault: boolean; - } - - export interface SendMessageBatchResult { - Successful: SendMessageBatchResultEntry[]; - Failed: BatchResultErrorEntry[]; - } - - export interface SendMessageBatchResultEntry { - Id: string; - MessageId: string; - MD5OfMessageBody: string; - MD5OfMessageAttributes:string; - } - - export interface CreateQueueResult { - QueueUrl: string; - } - - export interface SetQueueAttributesParams { - QueueUrl: string; - Attributes: QueueAttributes; - } - - } - - export module Ses { - - export interface Client { - config: ClientConfig; - - sendEmail(params: any, callback: (err: any, data: SendEmailResult) => void): void; - } - - export interface SendEmailRequest { - Source: string; - Destination: Destination; - Message: Message; - ReplyToAddresses: string[]; - ReturnPath: string; - } - - export class Destination { - ToAddresses: string[]; - CcAddresses: string[]; - BccAddresses: string[]; - } - - export class Message { - Subject: Content; - Body: Body; - } - - export class Content { - Data: string; - Charset: string; - } - - export class Body { - Text: Content; - Html: Content; - } - - export class SendEmailResult { - MessageId: string; - } - - } - - export module Swf { - - export class Client { - //constructor(options?: any); - public config: ClientConfig; - - countClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; - countOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; - countPendingActivityTasks(params: any, callback: (err: any, data: any) => void): void; - countPendingDecisionTasks(params: any, callback: (err: any, data: any) => void): void; - deprecateActivityType(params: any, callback: (err: any, data: any) => void): void; - deprecateDomain(params: any, callback: (err: any, data: any) => void): void; - deprecateWorkflowType(params: any, callback: (err: any, data: any) => void): void; - describeActivityType(params: any, callback: (err: any, data: any) => void): void; - describeDomain(params: any, callback: (err: any, data: any) => void): void; - describeWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; - describeWorkflowType(params: any, callback: (err: any, data: any) => void): void; - getWorkflowExecutionHistory(params: any, callback: (err: any, data: any) => void): void; - listActivityTypes(params: any, callback: (err: any, data: any) => void): void; - listClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; - listDomains(params: any, callback: (err: any, data: any) => void): void; - listOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; - listWorkflowTypes(params: any, callback: (err: any, data: any) => void): void; - pollForActivityTask(params: any, callback: (err: any, data: ActivityTask) => void): void; - pollForDecisionTask(params: any, callback: (err: any, data: DecisionTask) => void): void; - recordActivityTaskHeartbeat(params: any, callback: (err: any, data: any) => void): void; - registerActivityType(params: any, callback: (err: any, data: any) => void): void; - registerDomain(params: any, callback: (err: any, data: any) => void): void; - registerWorkflowType(params: any, callback: (err: any, data: any) => void): void; - requestCancelWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; - respondActivityTaskCanceled(params: RespondActivityTaskCanceledRequest, callback: (err: any, data: any) => void): void; - respondActivityTaskCompleted(params: RespondActivityTaskCompletedRequest, callback: (err: any, data: any) => void): void; - respondActivityTaskFailed(params: RespondActivityTaskFailedRequest, callback: (err: any, data: any) => void): void; - respondDecisionTaskCompleted(params: RespondDecisionTaskCompletedRequest, callback: (err: any, data: any) => void): void; - signalWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; - startWorkflowExecution(params: any, callback: (err: any, data: StartWorkflowExecutionResult) => void): void; - terminateWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; - } - - export interface PollForActivityTaskRequest { - domain?: string; - taskList?: TaskList; - identity?: string; - } - - export interface TaskList { - name?: string; - } - - export interface PollForDecisionTaskRequest { - domain?: string; - taskList?: TaskList; - identity?: string; - nextPageToken?: string; - maximumPageSize?: number; - reverseOrder?: Boolean; - } - - export interface StartWorkflowExecutionRequest { - domain?: string; - workflowId?: string; - workflowType?: WorkflowType; - taskList?: TaskList; - input?: string; - executionStartToCloseTimeout?: string; - tagList?: string[]; - taskStartToCloseTimeout?: string; - childPolicy?: string; - } - - export interface WorkflowType { - name?: string; - version?: string; - } - - export interface RespondDecisionTaskCompletedRequest { - taskToken?: string; - decisions?: Decision[]; - executionContext?: string; - } - - export interface Decision { - decisionType?: string; - scheduleActivityTaskDecisionAttributes?: ScheduleActivityTaskDecisionAttributes; - requestCancelActivityTaskDecisionAttributes?: RequestCancelActivityTaskDecisionAttributes; - completeWorkflowExecutionDecisionAttributes?: CompleteWorkflowExecutionDecisionAttributes; - failWorkflowExecutionDecisionAttributes?: FailWorkflowExecutionDecisionAttributes; - cancelWorkflowExecutionDecisionAttributes?: CancelWorkflowExecutionDecisionAttributes; - continueAsNewWorkflowExecutionDecisionAttributes?: ContinueAsNewWorkflowExecutionDecisionAttributes; - recordMarkerDecisionAttributes?: RecordMarkerDecisionAttributes; - startTimerDecisionAttributes?: StartTimerDecisionAttributes; - cancelTimerDecisionAttributes?: CancelTimerDecisionAttributes; - signalExternalWorkflowExecutionDecisionAttributes?: SignalExternalWorkflowExecutionDecisionAttributes; - requestCancelExternalWorkflowExecutionDecisionAttributes?: RequestCancelExternalWorkflowExecutionDecisionAttributes; - startChildWorkflowExecutionDecisionAttributes?: StartChildWorkflowExecutionDecisionAttributes; - } - - export interface ScheduleActivityTaskDecisionAttributes { - activityType?: ActivityType; - activityId?: string; - control?: string; - input?: string; - scheduleToCloseTimeout?: string; - taskList?: TaskList; - scheduleToStartTimeout?: string; - startToCloseTimeout?: string; - heartbeatTimeout?: string; - } - - export interface ActivityType { - name?: string; - version?: string; - } - - export interface RequestCancelActivityTaskDecisionAttributes { - activityId?: string; - } - - export interface CompleteWorkflowExecutionDecisionAttributes { - result?: string; - } - - export interface FailWorkflowExecutionDecisionAttributes { - reason?: string; - details?: string; - } - - export interface CancelWorkflowExecutionDecisionAttributes { - details?: string; - } - - export interface ContinueAsNewWorkflowExecutionDecisionAttributes { - input?: string; - executionStartToCloseTimeout?: string; - taskList?: TaskList; - taskStartToCloseTimeout?: string; - childPolicy?: string; - tagList?: string[]; - workflowTypeVersion?: string; - } - - export interface RecordMarkerDecisionAttributes { - markerName?: string; - details?: string; - } - - export interface StartTimerDecisionAttributes { - timerId?: string; - control?: string; - startToFireTimeout?: string; - } - - export interface CancelTimerDecisionAttributes { - timerId?: string; - } - - export interface SignalExternalWorkflowExecutionDecisionAttributes { - workflowId?: string; - runId?: string; - signalName?: string; - input?: string; - control?: string; - } - - export interface RequestCancelExternalWorkflowExecutionDecisionAttributes { - workflowId?: string; - runId?: string; - control?: string; - } - - export interface StartChildWorkflowExecutionDecisionAttributes { - workflowType?: WorkflowType; - workflowId?: string; - control?: string; - input?: string; - executionStartToCloseTimeout?: string; - taskList?: TaskList; - taskStartToCloseTimeout?: string; - childPolicy?: string; - tagList?: string[]; - } - - export interface RespondActivityTaskCompletedRequest { - taskToken?: string; - result?: string; - } - - export interface RespondActivityTaskFailedRequest { - taskToken?: string; - reason?: string; - details?: string; - } - - export interface RespondActivityTaskCanceledRequest { - taskToken?: string; - details?: string; - } - - export interface DecisionTask { - taskToken?: string; - startedEventId?: number; - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - events?: HistoryEvent[]; - nextPageToken?: string; - previousStartedEventId?: number; - } - - export interface WorkflowExecution { - workflowId?: string; - runId?: string; - } - - export interface HistoryEvent { - eventTimestamp?: any; - eventType?: string; - eventId?: number; - workflowExecutionStartedEventAttributes?: WorkflowExecutionStartedEventAttributes; - workflowExecutionCompletedEventAttributes?: WorkflowExecutionCompletedEventAttributes; - completeWorkflowExecutionFailedEventAttributes?: CompleteWorkflowExecutionFailedEventAttributes; - workflowExecutionFailedEventAttributes?: WorkflowExecutionFailedEventAttributes; - failWorkflowExecutionFailedEventAttributes?: FailWorkflowExecutionFailedEventAttributes; - workflowExecutionTimedOutEventAttributes?: WorkflowExecutionTimedOutEventAttributes; - workflowExecutionCanceledEventAttributes?: WorkflowExecutionCanceledEventAttributes; - cancelWorkflowExecutionFailedEventAttributes?: CancelWorkflowExecutionFailedEventAttributes; - workflowExecutionContinuedAsNewEventAttributes?: WorkflowExecutionContinuedAsNewEventAttributes; - continueAsNewWorkflowExecutionFailedEventAttributes?: ContinueAsNewWorkflowExecutionFailedEventAttributes; - workflowExecutionTerminatedEventAttributes?: WorkflowExecutionTerminatedEventAttributes; - workflowExecutionCancelRequestedEventAttributes?: WorkflowExecutionCancelRequestedEventAttributes; - decisionTaskScheduledEventAttributes?: DecisionTaskScheduledEventAttributes; - decisionTaskStartedEventAttributes?: DecisionTaskStartedEventAttributes; - decisionTaskCompletedEventAttributes?: DecisionTaskCompletedEventAttributes; - decisionTaskTimedOutEventAttributes?: DecisionTaskTimedOutEventAttributes; - activityTaskScheduledEventAttributes?: ActivityTaskScheduledEventAttributes; - activityTaskStartedEventAttributes?: ActivityTaskStartedEventAttributes; - activityTaskCompletedEventAttributes?: ActivityTaskCompletedEventAttributes; - activityTaskFailedEventAttributes?: ActivityTaskFailedEventAttributes; - activityTaskTimedOutEventAttributes?: ActivityTaskTimedOutEventAttributes; - activityTaskCanceledEventAttributes?: ActivityTaskCanceledEventAttributes; - activityTaskCancelRequestedEventAttributes?: ActivityTaskCancelRequestedEventAttributes; - workflowExecutionSignaledEventAttributes?: WorkflowExecutionSignaledEventAttributes; - markerRecordedEventAttributes?: MarkerRecordedEventAttributes; - timerStartedEventAttributes?: TimerStartedEventAttributes; - timerFiredEventAttributes?: TimerFiredEventAttributes; - timerCanceledEventAttributes?: TimerCanceledEventAttributes; - startChildWorkflowExecutionInitiatedEventAttributes?: StartChildWorkflowExecutionInitiatedEventAttributes; - childWorkflowExecutionStartedEventAttributes?: ChildWorkflowExecutionStartedEventAttributes; - childWorkflowExecutionCompletedEventAttributes?: ChildWorkflowExecutionCompletedEventAttributes; - childWorkflowExecutionFailedEventAttributes?: ChildWorkflowExecutionFailedEventAttributes; - childWorkflowExecutionTimedOutEventAttributes?: ChildWorkflowExecutionTimedOutEventAttributes; - childWorkflowExecutionCanceledEventAttributes?: ChildWorkflowExecutionCanceledEventAttributes; - childWorkflowExecutionTerminatedEventAttributes?: ChildWorkflowExecutionTerminatedEventAttributes; - signalExternalWorkflowExecutionInitiatedEventAttributes?: SignalExternalWorkflowExecutionInitiatedEventAttributes; - externalWorkflowExecutionSignaledEventAttributes?: ExternalWorkflowExecutionSignaledEventAttributes; - signalExternalWorkflowExecutionFailedEventAttributes?: SignalExternalWorkflowExecutionFailedEventAttributes; - externalWorkflowExecutionCancelRequestedEventAttributes?: ExternalWorkflowExecutionCancelRequestedEventAttributes; - requestCancelExternalWorkflowExecutionInitiatedEventAttributes?: RequestCancelExternalWorkflowExecutionInitiatedEventAttributes; - requestCancelExternalWorkflowExecutionFailedEventAttributes?: RequestCancelExternalWorkflowExecutionFailedEventAttributes; - scheduleActivityTaskFailedEventAttributes?: ScheduleActivityTaskFailedEventAttributes; - requestCancelActivityTaskFailedEventAttributes?: RequestCancelActivityTaskFailedEventAttributes; - startTimerFailedEventAttributes?: StartTimerFailedEventAttributes; - cancelTimerFailedEventAttributes?: CancelTimerFailedEventAttributes; - startChildWorkflowExecutionFailedEventAttributes?: StartChildWorkflowExecutionFailedEventAttributes; - } - - export interface WorkflowExecutionStartedEventAttributes { - input?: string; - executionStartToCloseTimeout?: string; - taskStartToCloseTimeout?: string; - childPolicy?: string; - taskList?: TaskList; - workflowType?: WorkflowType; - tagList?: string[]; - continuedExecutionRunId?: string; - parentWorkflowExecution?: WorkflowExecution; - parentInitiatedEventId?: number; - } - - export interface WorkflowExecutionCompletedEventAttributes { - result?: string; - decisionTaskCompletedEventId?: number; - } - - export interface CompleteWorkflowExecutionFailedEventAttributes { - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface WorkflowExecutionFailedEventAttributes { - reason?: string; - details?: string; - decisionTaskCompletedEventId?: number; - } - - export interface FailWorkflowExecutionFailedEventAttributes { - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface WorkflowExecutionTimedOutEventAttributes { - timeoutType?: string; - childPolicy?: string; - } - - export interface WorkflowExecutionCanceledEventAttributes { - details?: string; - decisionTaskCompletedEventId?: number; - } - - export interface CancelWorkflowExecutionFailedEventAttributes { - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface WorkflowExecutionContinuedAsNewEventAttributes { - input?: string; - decisionTaskCompletedEventId?: number; - newExecutionRunId?: string; - executionStartToCloseTimeout?: string; - taskList?: TaskList; - taskStartToCloseTimeout?: string; - childPolicy?: string; - tagList?: string[]; - workflowType?: WorkflowType; - } - - export interface ContinueAsNewWorkflowExecutionFailedEventAttributes { - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface WorkflowExecutionTerminatedEventAttributes { - reason?: string; - details?: string; - childPolicy?: string; - cause?: string; - } - - export interface WorkflowExecutionCancelRequestedEventAttributes { - externalWorkflowExecution?: WorkflowExecution; - externalInitiatedEventId?: number; - cause?: string; - } - - export interface DecisionTaskScheduledEventAttributes { - taskList?: TaskList; - startToCloseTimeout?: string; - } - - export interface DecisionTaskStartedEventAttributes { - identity?: string; - scheduledEventId?: number; - } - - export interface DecisionTaskCompletedEventAttributes { - executionContext?: string; - scheduledEventId?: number; - startedEventId?: number; - } - - export interface DecisionTaskTimedOutEventAttributes { - timeoutType?: string; - scheduledEventId?: number; - startedEventId?: number; - } - - export interface ActivityTaskScheduledEventAttributes { - activityType?: ActivityType; - activityId?: string; - input?: string; - control?: string; - scheduleToStartTimeout?: string; - scheduleToCloseTimeout?: string; - startToCloseTimeout?: string; - taskList?: TaskList; - decisionTaskCompletedEventId?: number; - heartbeatTimeout?: string; - } - - export interface ActivityTaskStartedEventAttributes { - identity?: string; - scheduledEventId?: number; - } - - export interface ActivityTaskCompletedEventAttributes { - result?: string; - scheduledEventId?: number; - startedEventId?: number; - } - - export interface ActivityTaskFailedEventAttributes { - reason?: string; - details?: string; - scheduledEventId?: number; - startedEventId?: number; - } - - export interface ActivityTaskTimedOutEventAttributes { - timeoutType?: string; - scheduledEventId?: number; - startedEventId?: number; - details?: string; - } - - export interface ActivityTaskCanceledEventAttributes { - details?: string; - scheduledEventId?: number; - startedEventId?: number; - latestCancelRequestedEventId?: number; - } - - export interface ActivityTaskCancelRequestedEventAttributes { - decisionTaskCompletedEventId?: number; - activityId?: string; - } - - export interface WorkflowExecutionSignaledEventAttributes { - signalName?: string; - input?: string; - externalWorkflowExecution?: WorkflowExecution; - externalInitiatedEventId?: number; - } - - export interface MarkerRecordedEventAttributes { - markerName?: string; - details?: string; - decisionTaskCompletedEventId?: number; - } - - export interface TimerStartedEventAttributes { - timerId?: string; - control?: string; - startToFireTimeout?: string; - decisionTaskCompletedEventId?: number; - } - - export interface TimerFiredEventAttributes { - timerId?: string; - startedEventId?: number; - } - - export interface TimerCanceledEventAttributes { - timerId?: string; - startedEventId?: number; - decisionTaskCompletedEventId?: number; - } - - export interface StartChildWorkflowExecutionInitiatedEventAttributes { - workflowId?: string; - workflowType?: WorkflowType; - control?: string; - input?: string; - executionStartToCloseTimeout?: string; - taskList?: TaskList; - decisionTaskCompletedEventId?: number; - childPolicy?: string; - taskStartToCloseTimeout?: string; - tagList?: string[]; - } - - export interface ChildWorkflowExecutionStartedEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - initiatedEventId?: number; - } - - export interface ChildWorkflowExecutionCompletedEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - result?: string; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface ChildWorkflowExecutionFailedEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - reason?: string; - details?: string; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface ChildWorkflowExecutionTimedOutEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - timeoutType?: string; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface ChildWorkflowExecutionCanceledEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - details?: string; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface ChildWorkflowExecutionTerminatedEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface SignalExternalWorkflowExecutionInitiatedEventAttributes { - workflowId?: string; - runId?: string; - signalName?: string; - input?: string; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface ExternalWorkflowExecutionSignaledEventAttributes { - workflowExecution?: WorkflowExecution; - initiatedEventId?: number; - } - - export interface SignalExternalWorkflowExecutionFailedEventAttributes { - workflowId?: string; - runId?: string; - cause?: string; - initiatedEventId?: number; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface ExternalWorkflowExecutionCancelRequestedEventAttributes { - workflowExecution?: WorkflowExecution; - initiatedEventId?: number; - } - - export interface RequestCancelExternalWorkflowExecutionInitiatedEventAttributes { - workflowId?: string; - runId?: string; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface RequestCancelExternalWorkflowExecutionFailedEventAttributes { - workflowId?: string; - runId?: string; - cause?: string; - initiatedEventId?: number; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface ScheduleActivityTaskFailedEventAttributes { - activityType?: ActivityType; - activityId?: string; - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface RequestCancelActivityTaskFailedEventAttributes { - activityId?: string; - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface StartTimerFailedEventAttributes { - timerId?: string; - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface CancelTimerFailedEventAttributes { - timerId?: string; - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface StartChildWorkflowExecutionFailedEventAttributes { - workflowType?: WorkflowType; - cause?: string; - workflowId?: string; - initiatedEventId?: number; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface ActivityTask { - taskToken?: string; - activityId?: string; - startedEventId?: number; - workflowExecution?: WorkflowExecution; - activityType?: ActivityType; - input?: string; - } - - export interface PollForActivityTaskResult { - activityTask?: ActivityTask; - } - - export interface PollForDecisionTaskResult { - decisionTask?: DecisionTask; - } - - export interface StartWorkflowExecutionResult { - run?: Run; - } - - export interface Run { - runId?: string; - } - - } - - export module Sns { - - export interface Client { - config: ClientConfig; - - publish(params: PublishRequest, callback: (err: any, data: PublishResult) => void): void; - createTopic(params: CreateTopicRequest, callback: (err: any, data: CreateTopicResult) => void): void; - deleteTopic(params: DeleteTopicRequest, callback: (err: any, data: any) => void): void; - } - - export interface PublishRequest { - TopicArn?: string; - TargetArn?: string; - MessageAttributes?: { [name: string]: MessageAttribute; }; - Message?: string; - MessageStructure?: string; - Subject?: string; - } - - export interface MessageAttribute { - DataType: string; - StringValue?: string; - BinaryValue: any; // (Buffer, Typed Array, Blob, String) - } - - export interface PublishResult { - MessageId?: string; - } - - export interface CreateTopicRequest { - Name?: string; - } - - export interface CreateTopicResult { - TopicArn?: string; - } - - export interface DeleteTopicRequest { - TopicArn?: string; - } - - } - - export module s3 { - - export interface PutObjectRequest { - ACL?: string; - Body?: any; - Bucket: string; - CacheControl?: string; - ContentDisposition?: string; - ContentEncoding?: string; - ContentLanguage?: string; - ContentLength?: string; - ContentMD5?: string; - ContentType?: string; - Expires?: any; - GrantFullControl?: string; - GrantRead?: string; - GrantReadACP?: string; - GrantWriteACP?: string; - Key: string; - Metadata?: { [key: string]:string; }; - ServerSideEncryption?: string; - StorageClass?: string; - WebsiteRedirectLocation?: string; - } - - export interface GetObjectRequest { - Bucket: string; - IfMatch?: string; - IfModifiedSince?: any; - IfNoneMatch?: string; - IfUnmodifiedSince?: any; - Key: string; - Range?: string; - ResponseCacheControl?: string; - ResponseContentDisposition?: string; - ResponseContentEncoding?: string; - ResponseContentLanguage?: string; - ResponseContentType?: string; - ResponseExpires?: any; - VersionId?: string; - } - - } - - export module ecs { - export interface CreateServicesParams { - desiredCount: number; - serviceName: string; - taskDefinition: string; - clientToken?: string; - cluster?: string; - deploymentConfiguration?: { - maximumPercent?: number; - minimumHealthyPercent?: number; - }; - loadBalancers?: { - containerName?: string; - containerPort?: number; - loadBalancerName?: string; - }[]; - role?: string; - } - - export interface DescribeServicesParams { + updateService(params: ecs.UpdateServiceParams, callback: (err: any, data: any) => void): void; + } + + export class DynamoDB { + constructor(options?: any); + endpoint: Endpoint; + createTable(params: any, next: (err: any, data: any) => void): void; + deleteTable(params: any, next: (err: any, data: any) => void): void; + } + + // ========================================================== + + export module DynamoDB { + + interface _DDBDC_Generic { + TableName: string; + ExpressionAttributeNames?: { [someKey: string]: string }; + ReturnConsumedCapacity?: "INDEXES" | "TOTAL" | "NONE"; + } + + type _DDBDC_ComparisonOperator = "EQ" | "NE" | "IN" | "LE" | "LT" | "GE" | "GT" | "BETWEEN" | "NOT_NULL" | "NULL" | "CONTAINS" | "NOT_CONTAINS" | "BEGINS_WITH" + type _DDBDC_Keys = { [someKey: string]: any }; + type _DDBDC_KeyComparison = { + [someKey: string]: { + AttributeValueList: any[]; + ComparisonOperator: _DDBDC_ComparisonOperator; + } + }; + + interface _DDBDC_Reader extends _DDBDC_Generic { + ConsistentRead?: boolean; + ProjectionExpression?: string; + AttributesToGet?: string[]; + } + + interface _DDBDC_Writer extends _DDBDC_Generic { + ExpressionAttributeValues?: _DDBDC_Keys; + ReturnItemCollectionMetrics?: "SIZE" | "NONE"; + ReturnValues?: "NONE" | "ALL_OLD" | "UPDATED_OLD" | "ALL_NEW" | "UPDATED_NEW"; + ConditionExpression?: string; + ConditionalOperator?: "AND" | "OR"; + Expected?: { + [someKey: string]: { + AttributeValueList?: any[]; + ComparisonOperator?: _DDBDC_ComparisonOperator; + Exists: boolean; + Value?: any; + } + } + } + + interface UpdateParam extends _DDBDC_Writer { + Key: _DDBDC_Keys; + AttributeUpdates: { + [someKey: string]: { + Action: "PUT" | "ADD" | "DELETE"; + Value: any + } + } + } + + interface QueryParam extends _DDBDC_Reader { + ConditionalOperator?: "AND" | "OR"; + ExclusiveStartKey?: _DDBDC_Keys; + ExpressionAttributeValues?: _DDBDC_Keys; + FilterExpression?: string; + IndexName?: string; + KeyConditionExpression?: string; + KeyConditions?: _DDBDC_KeyComparison; + Limit?: number; + QueryFilter?: _DDBDC_KeyComparison; + ScanIndexForward?: boolean; + Select?: "ALL_ATTRIBUTES" | "ALL_PROJECTED_ATTRIBUTES" | "SPECIFIC_ATTRIBUTES" | "COUNT"; + } + + interface ScanParam extends QueryParam { + Segment?: number; + ScanFilter?: _DDBDC_KeyComparison; + TotalSegments?: number; + } + + interface GetParam extends _DDBDC_Reader { + Key: _DDBDC_Keys; + } + + interface PutParam extends _DDBDC_Writer { + Item: _DDBDC_Keys; + } + + interface DeleteParam extends _DDBDC_Writer { + Key: _DDBDC_Keys; + } + + export class DocumentClient { + constructor(options?: any); + get(params: GetParam, next: (err: any, data: any) => void): void; + put(params: PutParam, next: (err: any, data: any) => void): void; + delete(params: DeleteParam, next: (err: any, data: any) => void): void; + query(params: QueryParam, next: (err: any, data: any) => void): void; + scan(params: ScanParam, next: (err: any, data: any) => void): void; + update(params: UpdateParam, next: (err: any, data: any) => void): void; + createSet(list: any[], options?: { validate?: boolean }): { values: any[], type: string }; + batchGet(params: any, next: (err: any, data: any) => void): void; + batchWrite(params: any, next: (err: any, data: any) => void): void; + } + + } + + // =========================================================== + + export module Lambda { + + export interface AddPermissionParams { + Action: string; + FunctionName: string; + Principal: string; + StatementId: string; + Qualifier?: string; + SourceAccount?: string; + SourceArn?: string; + } + + export interface CreateAliasParams { + FunctionName: string; + FunctionVersion: string; + Name: string; + Description?: string; + } + + export interface CreateEventSourceMappingParams { + EventSourceArn: string; + FunctionName: string; + StartingPosition: string; /* TRIM_HORIZON | LATEST */ + BatchSize?: number; + Enabled?: boolean + } + + export interface CreateFunctionParams { + Code: { + S3Bucket?: string; + S3Key?: string; + S3ObjectVersion?: string; + ZipFile?: any; // new Buffer('...') || string; + }, + FunctionName: string; + Handler: string; + Role: string; + Runtime: string; /* 'nodejs | java8 | python2.7', */ + Description?: string; + MemorySize?: number; + Publish?: boolean; + Timeout?: number; + VpcConfig?: { + SecurityGroupIds?: string[]; + SubnetIds?: string[]; + } + } + + export interface DeleteAliasParams { + FunctionName: string; + Name: string; + } + + export interface DeleteEventSourceMappingParams { + UUID: string; + } + + export interface DeleteFunctionParams { + FunctionName: string; + Qualifier?: string; + } + export interface GetAliasParams { + FunctionName: string; + Name: string; + } + + export interface GetEventSourceMappingParams { + UUID: string; + } + + export interface GetFunctionParams { + FunctionName: string; + Qualifier?: string; + } + + export interface GetFunctionConfigurationParams { + FunctionName: string; + Qualifier?: string; + } + + export interface GetPolicyParams { + FunctionName: string; + Qualifier?: string; + } + + export interface InvokeParams { + FunctionName: string; + ClientContext?: string; + InvocationType?: string;/* 'Event | RequestResponse | DryRun' */ + LogType?: string; /* 'None | Tail' */ + Payload?: any; /* new Buffer('...') || string */ + Qualifier?: string; + } + + export interface ListAliasesParams { + FunctionName: string; + FunctionVersion?: string; + Marker?: string; + MaxItems?: number + } + + export interface ListEventSourceMappingsParams { + EventSourceArn?: string; + FunctionName?: string; + Marker?: string; + MaxItems?: number + } + + export interface ListFunctionsParams { + Marker?: string; + MaxItems?: number + } + + export interface ListVersionsByFunctionParams { + FunctionName: string; + Marker?: string; + MaxItems?: number + } + + export interface PublishVersionParams { + FunctionName: string; + CodeSha256?: string; + Description?: string; + } + + export interface RemovePermissionParams { + FunctionName: string; + StatementId: string; + Qualifier?: string; + } + + export interface UpdateAliasParams { + FunctionName: string; + Name: string; + Description?: string; + FunctionVersion?: string; + } + + export interface UpdateEventSourceMappingParams { + UUID: string; + BatchSize?: number; + Enabled?: boolean; + FunctionName?: string; + } + + export interface UpdateFunctionCodeParams { + FunctionName: string; + Publish?: boolean; + S3Bucket?: string; + S3Key?: string; + S3ObjectVersion?: string; + ZipFile?: any; /* new Buffer('...') || string; */ + + } + + export interface UpdateFunctionConfigurationParams { + FunctionName: string; + Description?: string; + Handler?: string; + MemorySize?: number; + Role?: string; + Timeout?: number; + VpcConfig?: { + SecurityGroupIds?: string[]; + SubnetIds?: string[]; + } + } + } + + export module AutoScaling { + export interface AutoScalingOptions { + params?: any; + endpoint?: string; + accessKeyId?: string; + secretAccessKey?: string; + sessionToken?: Credentials; + credentials?: Credentials; + credentialProvider?: any; + region?: string; + maxRetries?: number; + maxRedirects?: number; + sslEnabled?: boolean; + paramValidation?: boolean; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + correctClockSkew?: boolean; + s3ForcePathStyle?: boolean; + s3BucketEndpoint?: boolean; + s3DisableBodySigning?: boolean; + retryDelayOptions?: RetryDelayOption; + httpOptions?: HttpOptions; + apiVersion?: string; + apiVersions?: { [serviceName: string]: string }; + logger?: Logger; + systemClockOffset?: number; + signatureVersion?: string; + signatureCache?: boolean; + } + + export interface AttachInstancesParams { + AutoScalingGroupName: string; + InstanceIds: string[]; + } + + export interface AttachLoadBalancersParams { + AutoScalingGroupName: string; + LoadBalancerNames: string[]; + } + + export interface AttachLoadBalancerTargetGroupsParams { + AutoScalingGroupName: string; + TargetGroupARNs: string[]; + } + + export interface CompleteLifecycleActionParams { + AutoScalingGroupName: string; + LifecycleActionResult: string; + LifecycleHookName: string; + lifecycleActionToken?: string; + InstanceId?: string; + } + + export interface CreateAutoScalingGroupParams { + AutoScalingGroupName: string; + MinSize: number; + MaxSize: number; + LaunchConfigurationName?: string; + InstanceId?: string; + DesiredCapacity?: number; + DefaultCooldown?: number; + AvailabilityZones?: string[]; + LoadBalancerNames?: string[]; + TargetGroupARNs?: string[]; + HealthCheckType?: string; + HealthCheckGracePeriod?: number; + PlacementGroup?: string; + VPCZoneIdentifier?: string; + TerminationPolicies?: string; + NewInstancesProtectedFromScaleIn?: boolean; + Tags?: Tags; + } + + export interface CreateLaunchConfigurationParams { + LaunchConfigurationName: string; + AssociatePublicIpAddress?: boolean; + ImageId?: string; + KeyName?: string; + SecurityGroups?: string[]; + ClassicLinkVPCId?: string; + ClassicLinkVPCSecurityGroups?: string[]; + UserData?: string; + InstanceId?: string; + InstanceType?: string; + KernelId?: string; + RamdiskId?: string; + BlockDeviceMappings?: BlockDeviceMapping[]; + InstanceMonitoring?: InstanceMonitoring; + SpotPrice?: string; + IamInstanceProfile?: string; + EbsOptimized?: boolean; + PlacementTenancy?: string; + } + + export interface CreateOrUpdateTagsParams { + Tags: Tags[]; + } + + export interface DeleteAutoScalingGroupParams { + AutoScalingGroupName: string; + ForceDelete?: boolean; + } + + export interface DeleteLaunchConfigurationParams { + LaunchConfigurationName: string; + } + + export interface DeleteLifecycleHookParams { + AutoScalingGroupName: string; + LifecycleHookName: string; + } + + export interface DeleteNotificationConfigurationParams { + AutoScalingGroupName: string; + TopicARN: string; + } + + export interface DeletePolicyParams { + PolicyName: string; + AutoScalingGroupName?: string; + } + + export interface DeleteScheduledActionParams { + AutoScalingGroupName: string; + ScheduledActionName: string; + } + + export interface DeleteTagsParams { + Tags: Tags[]; + } + + export interface DescribeAutoScalingGroupsParams { + AutoScalingGroupName?: string; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeAutoScalingInstancesParams { + InstanceIds?: string[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeLaunchConfigurationsParams { + LaunchConfigurationNames?: string[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeLifecycleHooksParams { + AutoScalingGroupName: string; + LifecycleHookNames?: string[]; + } + + export interface DescribeLoadBalancersParams { + AutoScalingGroupName: string; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeLoadBalancerTargetGroupsParams { + AutoScalingGroupName: string; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeNotificationConfigurationsParams { + AutoScalingGroupName?: string; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribePoliciesParams { + AutoScalingGroupName?: string; + PolicyNames?: string[]; + PolicyTypes?: string[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeScalingActivitiesParams { + AutoScalingGroupName?: string; + ActivityIds?: string[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeScheduledActionsParams { + AutoScalingGroupName?: string; + ScheduledActionNames?: string[]; + StartTime?: Date; + EndTime?: Date; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeTagsParams { + Filters?: Filter[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DetachInstancesParams { + AutoScalingGroupName: string; + ShouldDecrementDesiredCapacity: boolean; + InstanceIds?: string[]; + } + + export interface DetachLoadBalancersParams { + AutoScalingGroupName: string; + LoadBalancerNames: string; + } + + export interface DetachLoadBalancerTargetGroupsParams { + AutoScalingGroupName: string; + TargetGroupARNs: string[]; + } + + export interface DisableMetricsCollectionParams { + AutoScalingGroupName: string; + Metrics?: string[]; + } + + export interface EnableMetricsCollectionParams { + AutoScalingGroupName: string; + Granularity: string; + Metrics?: string[]; + } + + export interface EnterStandbyParams { + AutoScalingGroupName: string; + ShouldDecrementDesiredCapacity: boolean; + InstanceIds?: string[]; + } + + export interface ExecutePolicyParams { + PolicyName: string; + AutoScalingGroupName?: string; + HonorCooldown?: boolean; + MetricValue?: number; + BreachThreshold?: number; + } + + export interface ExitStandbyParams { + AutoScalingGroupName: string; + InstanceIds?: string[]; + } + + export interface PutLifecycleHookParams { + AutoScalingGroupName: string; + LifecycleHookName: string; + LifecycleTransition?: string; + RoleARN?: string; + NotificationTargetARN?: string; + NotificationMetadata?: string; + HeartbeatTimeout?: number; + DefaultResult?: string; + } + + export interface PutNotificationConfigurationParams { + AutoScalingGroupName: string; + NotificationTypes: string[]; + TopicARN: string; + } + + export interface PutScalingPolicyParams { + AutoScalingGroupName: string; + AdjustmentType: string; + PolicyName: string; + PolicyType?: string; + MinAdjustmentStep?: number; + MinAdjustmentMagnitude?: number; + ScalingAdjustment?: number; + Cooldown?: number; + MetricAggregationType?: string; + StepAdjustments?: StepAdjustment[]; + EstimatedInstanceWarmup: number; + } + + export interface PutScheduledUpdateGroupActionParams { + AutoScalingGroupName: string; + ScheduledActionName: string; + Time?: Date; + StartTime?: Date; + EndTime?: Date; + Recurrence?: string; + MinSize?: number; + MaxSize?: number; + DesiredCapacity?: number; + } + + export interface RecordLifecycleActionHeartbeatParams { + AutoScalingGroupName: string; + LifecycleHookName: string; + LifecycleActionToken?: string; + InstanceId?: string; + } + + export interface ResumeProcessesParams { + AutoScalingGroupName: string; + ScalingProcesses?: string[]; + } + + export interface SetDesiredCapacityParams { + AutoScalingGroupName: string; + DesiredCapacity: number; + HonorCooldown?: boolean; + } + + export interface SetInstanceHealthParams { + HealthStatus: string; + InstanceId: string; + ShouldRespectGracePeriod?: boolean; + } + + export interface SetInstanceProtectionParams { + AutoScalingGroupName: string; + InstanceIds: string[]; + ProtectedFromScaleIn: boolean; + } + + export interface SuspendProcessesParams { + AutoScalingGroupName: string; + ScalingProcesses?: string[]; + } + + export interface TerminateInstanceInAutoScalingGroupParams { + InstanceId: string; + ShouldDecrementDesiredCapacity: boolean; + } + + export interface UpdateAutoScalingGroupParams { + AutoScalingGroupName: string; + LaunchConfigurationName: string; + MinSize: number; + MaxSize: number; + DesiredCapacity: number; + DefaultCooldown: number; + AvailabilityZones: string[]; + HealthCheckType: string; + HealthCheckGracePeriod: number; + PlacementGroup: string; + VPCZoneIdentifier: string; + TerminationPolicies: string[]; + NewInstancesProtectedFromScaleIn?: boolean; + } + } + + + export module SQS { + + export interface SqsOptions { + params?: any; + endpoint?: string; + accessKeyId?: string; + secretAccessKey?: string; + sessionToken?: Credentials; + credentials?: Credentials; + credentialProvider?: any; + region?: string; + maxRetries?: number; + maxRedirects?: number; + sslEnabled?: boolean; + paramValidation?: boolean; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + correctClockSkew?: boolean; + s3ForcePathStyle?: boolean; + s3BucketEndpoint?: boolean; + httpOptions?: HttpOptions; + apiVersion?: string; + apiVersions?: { [serviceName: string]: string }; + logger?: Logger; + systemClockOffset?: number; + signatureVersion?: string; + signatureCache?: boolean; + } + + export interface AddPermissionParams { + QueueUrl: string; + Label: string; + AWSAccountIds: string[]; + Actions: string[]; + } + + export interface ChangeMessageVisibilityParams { + QueueUrl: string, + ReceiptHandle: string, + VisibilityTimeout: number + } + + export interface ChangeMessageVisibilityBatchParams { + QueueUrl: string, + Entries: { Id: string; ReceiptHandle: string; VisibilityTimeout?: number; }[] + } + + export interface ChangeMessageVisibilityBatchResponse { + Successful: { Id: string }[]; + Failed: BatchResultErrorEntry[]; + } + + export interface SendMessageParams { + QueueUrl?: string; + MessageBody: string; + DelaySeconds?: number; + MessageAttributes?: { [name: string]: MessageAttribute; } + } + + export interface ReceiveMessageParams { + QueueUrl: string; + MaxNumberOfMessages?: number; + VisibilityTimeout?: number; + AttributeNames?: string[]; + MessageAttributeNames?: string[]; + WaitTimeSeconds?: number; + } + + export interface DeleteMessageBatchParams { + QueueUrl: string; + Entries: DeleteMessageBatchRequestEntry[]; + } + + export interface DeleteMessageBatchRequestEntry { + Id: string; + ReceiptHandle: string; + } + + export interface DeleteMessageParams { + QueueUrl: string; + ReceiptHandle: string; + } + + export interface SendMessageBatchParams { + QueueUrl: string; + Entries: SendMessageBatchRequestEntry[]; + } + + export interface SendMessageBatchRequestEntry { + Id: string; + MessageBody: string; + DelaySeconds?: number; + MessageAttributes?: { [name: string]: MessageAttribute; } + } + + export interface CreateQueueParams { + QueueName: string; + Attributes: QueueAttributes; + } + + export interface QueueAttributes { + [name: string]: any; + DelaySeconds?: number; + MaximumMessageSize?: number; + MessageRetentionPeriod?: number; + Policy?: any; + ReceiveMessageWaitTimeSeconds?: number; + VisibilityTimeout?: number; + RedrivePolicy?: any; + } + + export interface GetQueueAttributesParams { + QueueUrl: string; + AttributeNames: string[]; + } + + export interface GetQueueAttributesResult { + Attributes: { [name: string]: string }; + } + + export interface GetQueueUrlParams { + QueueName: string; + QueueOwnerAWSAccountId?: string; + } + + export interface SendMessageResult { + MessageId: string; + MD5OfMessageBody: string; + MD5OfMessageAttributes: string; + } + + export interface ReceiveMessageResult { + Messages: Message[]; + } + + export interface Message { + MessageId: string; + ReceiptHandle: string; + MD5OfBody: string; + Body: string; + Attributes: { [name: string]: any }; + MD5OfMessageAttributes: string; + MessageAttributes: { [name: string]: MessageAttribute; } + } + + export interface MessageAttribute { + StringValue?: string; + BinaryValue?: any; //(Buffer, Typed Array, Blob, String) + StringListValues?: string[]; + BinaryListValues?: any[]; + DataType: string; + } + + export interface DeleteMessageBatchResult { + Successful: DeleteMessageBatchResultEntry[]; + Failed: BatchResultErrorEntry[]; + } + + export interface DeleteMessageBatchResultEntry { + Id: string; + } + + export interface BatchResultErrorEntry { + Id: string; + Code: string; + Message?: string; + SenderFault: boolean; + } + + export interface SendMessageBatchResult { + Successful: SendMessageBatchResultEntry[]; + Failed: BatchResultErrorEntry[]; + } + + export interface SendMessageBatchResultEntry { + Id: string; + MessageId: string; + MD5OfMessageBody: string; + MD5OfMessageAttributes: string; + } + + export interface CreateQueueResult { + QueueUrl: string; + } + + export interface SetQueueAttributesParams { + QueueUrl: string; + Attributes: QueueAttributes; + } + + } + + export module SES { + + export interface Client { + config: ClientConfig; + + sendEmail(params: any, callback: (err: any, data: SendEmailResult) => void): void; + } + + export interface SendEmailRequest { + Source: string; + Destination: Destination; + Message: Message; + ReplyToAddresses: string[]; + ReturnPath: string; + } + + export class Destination { + ToAddresses: string[]; + CcAddresses: string[]; + BccAddresses: string[]; + } + + export class Message { + Subject: Content; + Body: Body; + } + + export class Content { + Data: string; + Charset: string; + } + + export class Body { + Text: Content; + Html: Content; + } + + export class SendEmailResult { + MessageId: string; + } + + } + + export module Swf { + + export interface Client { + //constructor(options?: any); + config: ClientConfig; + + countClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + countOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + countPendingActivityTasks(params: any, callback: (err: any, data: any) => void): void; + countPendingDecisionTasks(params: any, callback: (err: any, data: any) => void): void; + deprecateActivityType(params: any, callback: (err: any, data: any) => void): void; + deprecateDomain(params: any, callback: (err: any, data: any) => void): void; + deprecateWorkflowType(params: any, callback: (err: any, data: any) => void): void; + describeActivityType(params: any, callback: (err: any, data: any) => void): void; + describeDomain(params: any, callback: (err: any, data: any) => void): void; + describeWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + describeWorkflowType(params: any, callback: (err: any, data: any) => void): void; + getWorkflowExecutionHistory(params: any, callback: (err: any, data: any) => void): void; + listActivityTypes(params: any, callback: (err: any, data: any) => void): void; + listClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + listDomains(params: any, callback: (err: any, data: any) => void): void; + listOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + listWorkflowTypes(params: any, callback: (err: any, data: any) => void): void; + pollForActivityTask(params: any, callback: (err: any, data: ActivityTask) => void): void; + pollForDecisionTask(params: any, callback: (err: any, data: DecisionTask) => void): void; + recordActivityTaskHeartbeat(params: any, callback: (err: any, data: any) => void): void; + registerActivityType(params: any, callback: (err: any, data: any) => void): void; + registerDomain(params: any, callback: (err: any, data: any) => void): void; + registerWorkflowType(params: any, callback: (err: any, data: any) => void): void; + requestCancelWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + respondActivityTaskCanceled(params: RespondActivityTaskCanceledRequest, callback: (err: any, data: any) => void): void; + respondActivityTaskCompleted(params: RespondActivityTaskCompletedRequest, callback: (err: any, data: any) => void): void; + respondActivityTaskFailed(params: RespondActivityTaskFailedRequest, callback: (err: any, data: any) => void): void; + respondDecisionTaskCompleted(params: RespondDecisionTaskCompletedRequest, callback: (err: any, data: any) => void): void; + signalWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + startWorkflowExecution(params: any, callback: (err: any, data: StartWorkflowExecutionResult) => void): void; + terminateWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + } + + export interface PollForActivityTaskRequest { + domain?: string; + taskList?: TaskList; + identity?: string; + } + + export interface TaskList { + name?: string; + } + + export interface PollForDecisionTaskRequest { + domain?: string; + taskList?: TaskList; + identity?: string; + nextPageToken?: string; + maximumPageSize?: number; + reverseOrder?: Boolean; + } + + export interface StartWorkflowExecutionRequest { + domain?: string; + workflowId?: string; + workflowType?: WorkflowType; + taskList?: TaskList; + input?: string; + executionStartToCloseTimeout?: string; + tagList?: string[]; + taskStartToCloseTimeout?: string; + childPolicy?: string; + } + + export interface WorkflowType { + name?: string; + version?: string; + } + + export interface RespondDecisionTaskCompletedRequest { + taskToken?: string; + decisions?: Decision[]; + executionContext?: string; + } + + export interface Decision { + decisionType?: string; + scheduleActivityTaskDecisionAttributes?: ScheduleActivityTaskDecisionAttributes; + requestCancelActivityTaskDecisionAttributes?: RequestCancelActivityTaskDecisionAttributes; + completeWorkflowExecutionDecisionAttributes?: CompleteWorkflowExecutionDecisionAttributes; + failWorkflowExecutionDecisionAttributes?: FailWorkflowExecutionDecisionAttributes; + cancelWorkflowExecutionDecisionAttributes?: CancelWorkflowExecutionDecisionAttributes; + continueAsNewWorkflowExecutionDecisionAttributes?: ContinueAsNewWorkflowExecutionDecisionAttributes; + recordMarkerDecisionAttributes?: RecordMarkerDecisionAttributes; + startTimerDecisionAttributes?: StartTimerDecisionAttributes; + cancelTimerDecisionAttributes?: CancelTimerDecisionAttributes; + signalExternalWorkflowExecutionDecisionAttributes?: SignalExternalWorkflowExecutionDecisionAttributes; + requestCancelExternalWorkflowExecutionDecisionAttributes?: RequestCancelExternalWorkflowExecutionDecisionAttributes; + startChildWorkflowExecutionDecisionAttributes?: StartChildWorkflowExecutionDecisionAttributes; + } + + export interface ScheduleActivityTaskDecisionAttributes { + activityType?: ActivityType; + activityId?: string; + control?: string; + input?: string; + scheduleToCloseTimeout?: string; + taskList?: TaskList; + scheduleToStartTimeout?: string; + startToCloseTimeout?: string; + heartbeatTimeout?: string; + } + + export interface ActivityType { + name?: string; + version?: string; + } + + export interface RequestCancelActivityTaskDecisionAttributes { + activityId?: string; + } + + export interface CompleteWorkflowExecutionDecisionAttributes { + result?: string; + } + + export interface FailWorkflowExecutionDecisionAttributes { + reason?: string; + details?: string; + } + + export interface CancelWorkflowExecutionDecisionAttributes { + details?: string; + } + + export interface ContinueAsNewWorkflowExecutionDecisionAttributes { + input?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + taskStartToCloseTimeout?: string; + childPolicy?: string; + tagList?: string[]; + workflowTypeVersion?: string; + } + + export interface RecordMarkerDecisionAttributes { + markerName?: string; + details?: string; + } + + export interface StartTimerDecisionAttributes { + timerId?: string; + control?: string; + startToFireTimeout?: string; + } + + export interface CancelTimerDecisionAttributes { + timerId?: string; + } + + export interface SignalExternalWorkflowExecutionDecisionAttributes { + workflowId?: string; + runId?: string; + signalName?: string; + input?: string; + control?: string; + } + + export interface RequestCancelExternalWorkflowExecutionDecisionAttributes { + workflowId?: string; + runId?: string; + control?: string; + } + + export interface StartChildWorkflowExecutionDecisionAttributes { + workflowType?: WorkflowType; + workflowId?: string; + control?: string; + input?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + taskStartToCloseTimeout?: string; + childPolicy?: string; + tagList?: string[]; + } + + export interface RespondActivityTaskCompletedRequest { + taskToken?: string; + result?: string; + } + + export interface RespondActivityTaskFailedRequest { + taskToken?: string; + reason?: string; + details?: string; + } + + export interface RespondActivityTaskCanceledRequest { + taskToken?: string; + details?: string; + } + + export interface DecisionTask { + taskToken?: string; + startedEventId?: number; + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + events?: HistoryEvent[]; + nextPageToken?: string; + previousStartedEventId?: number; + } + + export interface WorkflowExecution { + workflowId?: string; + runId?: string; + } + + export interface HistoryEvent { + eventTimestamp?: any; + eventType?: string; + eventId?: number; + workflowExecutionStartedEventAttributes?: WorkflowExecutionStartedEventAttributes; + workflowExecutionCompletedEventAttributes?: WorkflowExecutionCompletedEventAttributes; + completeWorkflowExecutionFailedEventAttributes?: CompleteWorkflowExecutionFailedEventAttributes; + workflowExecutionFailedEventAttributes?: WorkflowExecutionFailedEventAttributes; + failWorkflowExecutionFailedEventAttributes?: FailWorkflowExecutionFailedEventAttributes; + workflowExecutionTimedOutEventAttributes?: WorkflowExecutionTimedOutEventAttributes; + workflowExecutionCanceledEventAttributes?: WorkflowExecutionCanceledEventAttributes; + cancelWorkflowExecutionFailedEventAttributes?: CancelWorkflowExecutionFailedEventAttributes; + workflowExecutionContinuedAsNewEventAttributes?: WorkflowExecutionContinuedAsNewEventAttributes; + continueAsNewWorkflowExecutionFailedEventAttributes?: ContinueAsNewWorkflowExecutionFailedEventAttributes; + workflowExecutionTerminatedEventAttributes?: WorkflowExecutionTerminatedEventAttributes; + workflowExecutionCancelRequestedEventAttributes?: WorkflowExecutionCancelRequestedEventAttributes; + decisionTaskScheduledEventAttributes?: DecisionTaskScheduledEventAttributes; + decisionTaskStartedEventAttributes?: DecisionTaskStartedEventAttributes; + decisionTaskCompletedEventAttributes?: DecisionTaskCompletedEventAttributes; + decisionTaskTimedOutEventAttributes?: DecisionTaskTimedOutEventAttributes; + activityTaskScheduledEventAttributes?: ActivityTaskScheduledEventAttributes; + activityTaskStartedEventAttributes?: ActivityTaskStartedEventAttributes; + activityTaskCompletedEventAttributes?: ActivityTaskCompletedEventAttributes; + activityTaskFailedEventAttributes?: ActivityTaskFailedEventAttributes; + activityTaskTimedOutEventAttributes?: ActivityTaskTimedOutEventAttributes; + activityTaskCanceledEventAttributes?: ActivityTaskCanceledEventAttributes; + activityTaskCancelRequestedEventAttributes?: ActivityTaskCancelRequestedEventAttributes; + workflowExecutionSignaledEventAttributes?: WorkflowExecutionSignaledEventAttributes; + markerRecordedEventAttributes?: MarkerRecordedEventAttributes; + timerStartedEventAttributes?: TimerStartedEventAttributes; + timerFiredEventAttributes?: TimerFiredEventAttributes; + timerCanceledEventAttributes?: TimerCanceledEventAttributes; + startChildWorkflowExecutionInitiatedEventAttributes?: StartChildWorkflowExecutionInitiatedEventAttributes; + childWorkflowExecutionStartedEventAttributes?: ChildWorkflowExecutionStartedEventAttributes; + childWorkflowExecutionCompletedEventAttributes?: ChildWorkflowExecutionCompletedEventAttributes; + childWorkflowExecutionFailedEventAttributes?: ChildWorkflowExecutionFailedEventAttributes; + childWorkflowExecutionTimedOutEventAttributes?: ChildWorkflowExecutionTimedOutEventAttributes; + childWorkflowExecutionCanceledEventAttributes?: ChildWorkflowExecutionCanceledEventAttributes; + childWorkflowExecutionTerminatedEventAttributes?: ChildWorkflowExecutionTerminatedEventAttributes; + signalExternalWorkflowExecutionInitiatedEventAttributes?: SignalExternalWorkflowExecutionInitiatedEventAttributes; + externalWorkflowExecutionSignaledEventAttributes?: ExternalWorkflowExecutionSignaledEventAttributes; + signalExternalWorkflowExecutionFailedEventAttributes?: SignalExternalWorkflowExecutionFailedEventAttributes; + externalWorkflowExecutionCancelRequestedEventAttributes?: ExternalWorkflowExecutionCancelRequestedEventAttributes; + requestCancelExternalWorkflowExecutionInitiatedEventAttributes?: RequestCancelExternalWorkflowExecutionInitiatedEventAttributes; + requestCancelExternalWorkflowExecutionFailedEventAttributes?: RequestCancelExternalWorkflowExecutionFailedEventAttributes; + scheduleActivityTaskFailedEventAttributes?: ScheduleActivityTaskFailedEventAttributes; + requestCancelActivityTaskFailedEventAttributes?: RequestCancelActivityTaskFailedEventAttributes; + startTimerFailedEventAttributes?: StartTimerFailedEventAttributes; + cancelTimerFailedEventAttributes?: CancelTimerFailedEventAttributes; + startChildWorkflowExecutionFailedEventAttributes?: StartChildWorkflowExecutionFailedEventAttributes; + } + + export interface WorkflowExecutionStartedEventAttributes { + input?: string; + executionStartToCloseTimeout?: string; + taskStartToCloseTimeout?: string; + childPolicy?: string; + taskList?: TaskList; + workflowType?: WorkflowType; + tagList?: string[]; + continuedExecutionRunId?: string; + parentWorkflowExecution?: WorkflowExecution; + parentInitiatedEventId?: number; + } + + export interface WorkflowExecutionCompletedEventAttributes { + result?: string; + decisionTaskCompletedEventId?: number; + } + + export interface CompleteWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionFailedEventAttributes { + reason?: string; + details?: string; + decisionTaskCompletedEventId?: number; + } + + export interface FailWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionTimedOutEventAttributes { + timeoutType?: string; + childPolicy?: string; + } + + export interface WorkflowExecutionCanceledEventAttributes { + details?: string; + decisionTaskCompletedEventId?: number; + } + + export interface CancelWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionContinuedAsNewEventAttributes { + input?: string; + decisionTaskCompletedEventId?: number; + newExecutionRunId?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + taskStartToCloseTimeout?: string; + childPolicy?: string; + tagList?: string[]; + workflowType?: WorkflowType; + } + + export interface ContinueAsNewWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionTerminatedEventAttributes { + reason?: string; + details?: string; + childPolicy?: string; + cause?: string; + } + + export interface WorkflowExecutionCancelRequestedEventAttributes { + externalWorkflowExecution?: WorkflowExecution; + externalInitiatedEventId?: number; + cause?: string; + } + + export interface DecisionTaskScheduledEventAttributes { + taskList?: TaskList; + startToCloseTimeout?: string; + } + + export interface DecisionTaskStartedEventAttributes { + identity?: string; + scheduledEventId?: number; + } + + export interface DecisionTaskCompletedEventAttributes { + executionContext?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface DecisionTaskTimedOutEventAttributes { + timeoutType?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface ActivityTaskScheduledEventAttributes { + activityType?: ActivityType; + activityId?: string; + input?: string; + control?: string; + scheduleToStartTimeout?: string; + scheduleToCloseTimeout?: string; + startToCloseTimeout?: string; + taskList?: TaskList; + decisionTaskCompletedEventId?: number; + heartbeatTimeout?: string; + } + + export interface ActivityTaskStartedEventAttributes { + identity?: string; + scheduledEventId?: number; + } + + export interface ActivityTaskCompletedEventAttributes { + result?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface ActivityTaskFailedEventAttributes { + reason?: string; + details?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface ActivityTaskTimedOutEventAttributes { + timeoutType?: string; + scheduledEventId?: number; + startedEventId?: number; + details?: string; + } + + export interface ActivityTaskCanceledEventAttributes { + details?: string; + scheduledEventId?: number; + startedEventId?: number; + latestCancelRequestedEventId?: number; + } + + export interface ActivityTaskCancelRequestedEventAttributes { + decisionTaskCompletedEventId?: number; + activityId?: string; + } + + export interface WorkflowExecutionSignaledEventAttributes { + signalName?: string; + input?: string; + externalWorkflowExecution?: WorkflowExecution; + externalInitiatedEventId?: number; + } + + export interface MarkerRecordedEventAttributes { + markerName?: string; + details?: string; + decisionTaskCompletedEventId?: number; + } + + export interface TimerStartedEventAttributes { + timerId?: string; + control?: string; + startToFireTimeout?: string; + decisionTaskCompletedEventId?: number; + } + + export interface TimerFiredEventAttributes { + timerId?: string; + startedEventId?: number; + } + + export interface TimerCanceledEventAttributes { + timerId?: string; + startedEventId?: number; + decisionTaskCompletedEventId?: number; + } + + export interface StartChildWorkflowExecutionInitiatedEventAttributes { + workflowId?: string; + workflowType?: WorkflowType; + control?: string; + input?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + decisionTaskCompletedEventId?: number; + childPolicy?: string; + taskStartToCloseTimeout?: string; + tagList?: string[]; + } + + export interface ChildWorkflowExecutionStartedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + initiatedEventId?: number; + } + + export interface ChildWorkflowExecutionCompletedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + result?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionFailedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + reason?: string; + details?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionTimedOutEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + timeoutType?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionCanceledEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + details?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionTerminatedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface SignalExternalWorkflowExecutionInitiatedEventAttributes { + workflowId?: string; + runId?: string; + signalName?: string; + input?: string; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ExternalWorkflowExecutionSignaledEventAttributes { + workflowExecution?: WorkflowExecution; + initiatedEventId?: number; + } + + export interface SignalExternalWorkflowExecutionFailedEventAttributes { + workflowId?: string; + runId?: string; + cause?: string; + initiatedEventId?: number; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ExternalWorkflowExecutionCancelRequestedEventAttributes { + workflowExecution?: WorkflowExecution; + initiatedEventId?: number; + } + + export interface RequestCancelExternalWorkflowExecutionInitiatedEventAttributes { + workflowId?: string; + runId?: string; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface RequestCancelExternalWorkflowExecutionFailedEventAttributes { + workflowId?: string; + runId?: string; + cause?: string; + initiatedEventId?: number; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ScheduleActivityTaskFailedEventAttributes { + activityType?: ActivityType; + activityId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface RequestCancelActivityTaskFailedEventAttributes { + activityId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface StartTimerFailedEventAttributes { + timerId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface CancelTimerFailedEventAttributes { + timerId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface StartChildWorkflowExecutionFailedEventAttributes { + workflowType?: WorkflowType; + cause?: string; + workflowId?: string; + initiatedEventId?: number; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ActivityTask { + taskToken?: string; + activityId?: string; + startedEventId?: number; + workflowExecution?: WorkflowExecution; + activityType?: ActivityType; + input?: string; + } + + export interface PollForActivityTaskResult { + activityTask?: ActivityTask; + } + + export interface PollForDecisionTaskResult { + decisionTask?: DecisionTask; + } + + export interface StartWorkflowExecutionResult { + run?: Run; + } + + export interface Run { + runId?: string; + } + + } + + export module Sns { + + export interface Client { + config: ClientConfig; + + publish(params: PublishRequest, callback: (err: any, data: PublishResult) => void): void; + createTopic(params: CreateTopicRequest, callback: (err: any, data: CreateTopicResult) => void): void; + deleteTopic(params: DeleteTopicRequest, callback: (err: any, data: any) => void): void; + } + + export interface PublishRequest { + TopicArn?: string; + TargetArn?: string; + MessageAttributes?: { [name: string]: MessageAttribute; }; + Message?: string; + MessageStructure?: string; + Subject?: string; + } + + export interface MessageAttribute { + DataType: string; + StringValue?: string; + BinaryValue: any; // (Buffer, Typed Array, Blob, String) + } + + export interface PublishResult { + MessageId?: string; + } + + export interface CreateTopicRequest { + Name?: string; + } + + export interface CreateTopicResult { + TopicArn?: string; + } + + export interface DeleteTopicRequest { + TopicArn?: string; + } + + } + + export module s3 { + interface Owner { + DisplayName: string; + ID: string; + } + + interface ObjectKeyPrefix { + Prefix: string; + } + + export interface ListObjectContent { + Key: string; + LastModified: Date; + ETag: string; + Size: number; + StorageClass: "STANDARD" | "REDUCED_REDUNDANCY" | "GLACIER"; + Owner?: Owner + } + + // This private interface contains the common parts between v1 and v2 of the API Request and is exposed via V1 and V2 subclasses + interface ListObjectRequestBase { + Bucket: string; + Delimiter?: string; + EncodingType?: 'url'; + MaxKeys?: number; + Prefix?: string; + } + + // This private interface contains the common parts between v1 and v2 of the API Response and is exposed via V1 and V2 subclasses + interface ListObjectResponseBase { + IsTruncated: boolean; + Contents: ListObjectContent[]; + Name: string; + Prefix?: string; + Delimiter?: string; + MaxKeys: number; + CommonPrefixes?: ObjectKeyPrefix[]; + EncodingType?: "url"; + } + + export interface PutObjectRequest { + ACL?: string; + Body?: any; + Bucket: string; + CacheControl?: string; + ContentDisposition?: string; + ContentEncoding?: string; + ContentLanguage?: string; + ContentLength?: string; + ContentMD5?: string; + ContentType?: string; + Expires?: any; + GrantFullControl?: string; + GrantRead?: string; + GrantReadACP?: string; + GrantWriteACP?: string; + Key: string; + Metadata?: { [key: string]: string; }; + ServerSideEncryption?: string; + StorageClass?: string; + WebsiteRedirectLocation?: string; + } + + export interface GetObjectRequest { + Bucket: string; + IfMatch?: string; + IfModifiedSince?: any; + IfNoneMatch?: string; + IfUnmodifiedSince?: any; + Key: string; + Range?: string; + ResponseCacheControl?: string; + ResponseContentDisposition?: string; + ResponseContentEncoding?: string; + ResponseContentLanguage?: string; + ResponseContentType?: string; + ResponseExpires?: any; + VersionId?: string; + } + + export interface DeleteObjectRequest { + Bucket: string; + Key: string; + MFA?: string; + RequestPayer?: string; + VersionId?: string; + } + + export interface HeadObjectRequest { + Bucket: string; + Key: string; + IfMatch?: string; + IfModifiedSince?: Date; + IfNoneMatch?: string; + IfUnmodifiedSince?: Date; + Range?: string; + RequestPayer?: string; + SSECustomerAlgorithm?: string; + SSECustomerKey?: Buffer | string; + SSECustomerKeyMD5?: string; + VersionId?: string; + } + + export interface UploadOptions { + partSize?: number; + queueSize?: number; + } + + export interface ListObjectRequest extends ListObjectRequestBase { + Marker?: string; + } + + export interface ListObjectV2Request extends ListObjectRequestBase { + ContinuationToken?: string; + FetchOwner?: boolean; + StartAfter?: string; + } + + export interface ListObjectResponse extends ListObjectResponseBase { + Marker?: string; + NextMarker?: string; + } + + export interface ListObjectV2Response extends ListObjectResponseBase { + KeyCount: number; + ContinuationToken?: string; + NextContinuationToken?: string; + StartAfter?: string; + } + } + + export module ecs { + export interface CreateServicesParams { + desiredCount: number; + serviceName: string; + taskDefinition: string; + clientToken?: string; + cluster?: string; + deploymentConfiguration?: { + maximumPercent?: number; + minimumHealthyPercent?: number; + }; + loadBalancers?: { + containerName?: string; + containerPort?: number; + loadBalancerName?: string; + }[]; + role?: string; + } + + export interface DescribeServicesParams { /** * A list of services to describe. */ - services: string[]; + services: string[]; /** * The name of the cluster that hosts the service to describe. If you do not specify a cluster, the default cluster is assumed. */ - cluster?: string; - } + cluster?: string; + } - export interface DescribeClustersParams { + export interface DescribeClustersParams { /** * A space-separated list of cluster names or full cluster Amazon Resource Name (ARN) entries. If you do not specify a cluster, the default cluster is assumed. */ - clusters?: string[]; - } + clusters?: string[]; + } - export interface DescribeTasksParams { + export interface DescribeTasksParams { /** * A space-separated list of task IDs or full Amazon Resource Name (ARN) entries. */ - tasks: string[]; + tasks: string[]; /** * The short name or full Amazon Resource Name (ARN) of the cluster that hosts the task to describe. If you do not specify a cluster, the default cluster is assumed. */ - cluster?: string; - } + cluster?: string; + } - export interface DescribeTaskDefinitionParams { + export interface DescribeTaskDefinitionParams { /** * The `family` for the latest `ACTIVE` revision, `family` and `revision` (`family:revision`) for a specific revision in the family, or full Amazon Resource Name (ARN) of the task definition to describe. */ - taskDefinition: string; - } + taskDefinition: string; + } - export interface RegisterTaskDefinitionParams { - containerDefinitions: { - command?: string[], - cpu?: number, - disableNetworking?: boolean, - dnsSearchDomains?: string[], - dnsServers?: string[], - dockerLabels?: any, - dockerSecurityOptions?: string[], - entryPoint?: string[], - environment?: any[], - essential?: boolean, - extraHosts?: { - hostName: string, - ipAddress: string - }[]; - hostname?: string, - image?: string, - links?: string[], - logConfiguration?: { - logDriver: string, - options: any - }[], - memory?: number, - mountPoints?: { - containerPath: string, - readOnly: boolean, - sourceVolume: string - }[]; - name?: string, - portMappings?: { - containerPort?: number, - hostPort?: number, - protocol: string - }[]; - privileged?: boolean, - readonlyRootFilesystem?: boolean, - ulimits?: { - hardLimit: number, - name: string, - softLimit: number - }[]; - user?: string, - volumesFrom?: { - readOnly?: boolean, - sourceContainer?: string - }[], - workingDirectory?: string - }[]; - family: string; - volumes?: { - host: { - sourcePath: string - }, - name: string - }[]; - } + export interface RegisterTaskDefinitionParams { + containerDefinitions: { + command?: string[], + cpu?: number, + disableNetworking?: boolean, + dnsSearchDomains?: string[], + dnsServers?: string[], + dockerLabels?: any, + dockerSecurityOptions?: string[], + entryPoint?: string[], + environment?: any[], + essential?: boolean, + extraHosts?: { + hostName: string, + ipAddress: string + }[]; + hostname?: string, + image?: string, + links?: string[], + logConfiguration?: { + logDriver: string, + options: any + }[], + memory?: number, + mountPoints?: { + containerPath: string, + readOnly: boolean, + sourceVolume: string + }[]; + name?: string, + portMappings?: { + containerPort?: number, + hostPort?: number, + protocol: string + }[]; + privileged?: boolean, + readonlyRootFilesystem?: boolean, + ulimits?: { + hardLimit: number, + name: string, + softLimit: number + }[]; + user?: string, + volumesFrom?: { + readOnly?: boolean, + sourceContainer?: string + }[], + workingDirectory?: string + }[]; + family: string; + volumes?: { + host: { + sourcePath: string + }, + name: string + }[]; + } - export interface UpdateServiceParams { - service: string; - cluster?: string; - deploymentConfiguration?: { - maximumPercent: number; - minimumHealthyPercent: number; - }; - desiredCount?: number; - taskDefinition: string; - } - } + export interface UpdateServiceParams { + service: string; + cluster?: string; + deploymentConfiguration?: { + maximumPercent: number; + minimumHealthyPercent: number; + }; + desiredCount?: number; + taskDefinition: string; + } + } - export module sts { - export interface AssumeRoleParams { - RoleArn: string; - RoleSessionName: string; - DurationSeconds?: number; - ExternalId?: string; - Policy?: string; - SerialNumber?: string; - TokenCode?: string; - } + export module sts { + export interface AssumeRoleParams { + RoleArn: string; + RoleSessionName: string; + DurationSeconds?: number; + ExternalId?: string; + Policy?: string; + SerialNumber?: string; + TokenCode?: string; + } - export interface AssumeRoleCallbackData{ - Credentials: TemporaryCredentials; - AssumedRoleUser: AssumedRoleUser; - PackedPolicySize: number; - } + export interface AssumeRoleCallbackData { + Credentials: TemporaryCredentials; + AssumedRoleUser: AssumedRoleUser; + PackedPolicySize: number; + } - export interface TemporaryCredentials{ - AccessKeyId: string; - SecretAccessKey: string; - SessionToken: string; - Expiration: Date; - } + export interface TemporaryCredentials { + AccessKeyId: string; + SecretAccessKey: string; + SessionToken: string; + Expiration: Date; + } - export interface AssumedRoleUser{ - AssumedRoleId: string; - Arn: string; - } + export interface AssumedRoleUser { + AssumedRoleId: string; + Arn: string; + } - export interface AssumeRoleWithSAMLParams { - PrincipalArn: string; - RoleArn: string; - SAMLAssertion: string; - DurationSeconds?: number; - Policy?: string; - } + export interface AssumeRoleWithSAMLParams { + PrincipalArn: string; + RoleArn: string; + SAMLAssertion: string; + DurationSeconds?: number; + Policy?: string; + } - export interface AssumeRoleWithWebIdentityParams { - RoleArn: string; - RoleSessionName: string; - WebIdentityToken: string; - DurationSeconds?: number; - Policy?: string; - ProviderId?: string; - } + export interface AssumeRoleWithWebIdentityParams { + RoleArn: string; + RoleSessionName: string; + WebIdentityToken: string; + DurationSeconds?: number; + Policy?: string; + ProviderId?: string; + } - export interface CredentialsFromParams { + export interface CredentialsFromParams { /** * Data retrieved from a call to AWS.STS.getFederatedToken, getSessionToken(), assumeRole(), or assumeRoleWithWebIdentity(). */ - Data: any; + Data: any; /** * An optional credentials object to fill instead of creating a new object. Useful when modifying an existing credentials object from a refresh call. */ - Credentials?: Credentials - } + Credentials?: Credentials + } - export interface DecodeAuthorizationMessageParams { - EncodedMessage: string; - } + export interface DecodeAuthorizationMessageParams { + EncodedMessage: string; + } - export interface GetFederationTokenParams { - Name: string; - DurationSeconds?: number, - Policy?: string - } + export interface GetFederationTokenParams { + Name: string; + DurationSeconds?: number, + Policy?: string + } - export interface GetSessionTokenParams { - DurationSeconds: number, - SerialNumber: string; - TokenCode: string; - } - } + export interface GetSessionTokenParams { + DurationSeconds: number, + SerialNumber: string; + TokenCode: string; + } + } } diff --git a/axe-core/axe-core-tests.ts b/axe-core/axe-core-tests.ts new file mode 100644 index 0000000000..7decb865c2 --- /dev/null +++ b/axe-core/axe-core-tests.ts @@ -0,0 +1,91 @@ +/// + +var context:any = document +var $fixture:any = {} + +// axe.a11yCheck config +axe.a11yCheck(context, {}, (results) => { + // axe's results object + console.log(results.passes.length) + console.log(results.violations.length) +}); +// axe.a11yCheck include/exclude +axe.a11yCheck({include: [['#id1'], ['#id2']]}, {}, (results) => { + console.log(results) +}) +axe.a11yCheck({exclude: [$fixture[0]]}, {}, (results) => { + console.log(results) +}) +var tagConfigRunOnly: axe.RunOnly = { + type: 'tag', + values: ['wcag2a'] +} +var tagConfig = { + runOnly: tagConfigRunOnly +} +axe.a11yCheck(context, tagConfig, (results) => { + console.log(results) +}) +var includeExcludeTagsRunOnly: axe.RunOnly = { + type: 'tags', + value: { + include: ['wcag2a', 'wcag2aa'], + exclude: ['experimental'] + } +} +var includeExcludeTagsConfig = { + runOnly: includeExcludeTagsRunOnly +} +axe.a11yCheck(context, includeExcludeTagsConfig, (results) => { + console.log(results) +}) +var someRulesConfig = { + rules: { + "color-contrast": {enabled: 'false'}, + "heading-order": {enabled: 'true'} + } +} +axe.a11yCheck(context, someRulesConfig, (results) => { + console.log(results) +}) + +// axe.configure +var spec: axe.Spec = { + branding: { + brand: 'foo', + application: 'bar' + }, + reporter: 'v1', + checks: [{ + id: 'custom-check', + evaluate: function() { + return true + } + }], + rules: [{ + id: 'custom-rule', + any: ['custom-check'] + }] +} +axe.configure(spec) + +axe.reset() + +axe.getRules(['wcag2aa']) +typeof axe.getRules() === 'object' + +// Plugins +var pluginSrc: axe.AxePlugin = { + id: 'doStuff', + run: (data:any, callback:Function) => { + callback() + }, + commands: [{ + id: 'run-doStuff', + callback: (data:any, callback:Function) => { + axe.plugins['doStuff'].run(data, callback) + } + }] +} +axe.registerPlugin(pluginSrc) +axe.cleanup() diff --git a/axe-core/axe-core.d.ts b/axe-core/axe-core.d.ts new file mode 100644 index 0000000000..98818e75cc --- /dev/null +++ b/axe-core/axe-core.d.ts @@ -0,0 +1,159 @@ +// Type definitions for axe-core 2.0.5 +// Project: https://github.com/dequelabs/axe-core +// Definitions by: Marcy Sutton +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace axe { + + export type ImpactValue = "minor" | "moderate" | "serious" | "critical"; + + export type TagValue = "wcag2a" | "wcag2aa" | "section508" | "best-practice"; + + export type ReporterVersion = "v1" | "v2"; + + export type RunOnlyType = "rule" | "rules" | "tag" | "tags"; + + export interface ElementContext { + node?: Object, + selector?: string, + include?: any[], + exclude?: any[] + } + export interface RunOnly { + type: RunOnlyType, + value?: { + include?: string[], + exclude?: string[] + } + values?: TagValue[] + } + export interface AxeResults { + url: string, + timestamp: string, + passes: Pass[], + violations: Violation[] + } + export interface Pass { + description: string, + help: string, + helpUrl: string, + id: string, + impact: ImpactValue, + tags: TagValue[], + nodes: NodeResult[] + } + export interface Violation { + description: string, + help: string, + helpUrl: string, + id: string, + impact: ImpactValue, + tags: TagValue[], + nodes: NodeResult[] + } + export interface NodeResult { + html: string, + impact: ImpactValue, + target: string[], + any: CheckResult[], + all: CheckResult[], + none: CheckResult[] + } + export interface CheckResult { + id: string, + impact: string, + message: string, + data: any, + relatedNodes?: RelatedNode[] + } + export interface RelatedNode { + target: string[], + html: string + } + export interface Spec { + branding?: { + brand: string, + application: string + }, + reporter?: ReporterVersion, + checks?: Check[], + rules?: Rule[] + } + export interface Check { + id: string, + evaluate: Function, + after?: Function, + options?: any, + matches?: string, + enabled?: boolean + } + export interface Rule { + id: string, + selector?: string, + excludeHidden?: boolean, + enabled?: boolean, + pageLevel?: boolean, + any?: string[], + all?: string[], + none?: string[], + tags?: string[], + matches?: string + } + export interface AxePlugin { + id: string, + run(...args:any[]): any, + commands: { + id: string, + callback(...args:any[]): void + }[], + cleanup?(callback:Function): void + } + + export let plugins: any + + /** + * Starts analysis on the current document and its subframes + * + * @param {Object} context The `Context` specification object @see Context + * @param {Array} options Options passed into rules or checks, temporarily modifyint them. + * @param {Function} callback The function to invoke when analysis is complete. + * @returns {Object} results The aXe results object + */ + export function a11yCheck(context: ElementContext, options: {runOnly?: RunOnly, rules?: Object}, callback: (results:AxeResults) => void): AxeResults + + /** + * Method for configuring the data format used by aXe. Helpful for adding new + * rules, which must be registered with the library to execute. + * @param {Spec} Spec Object with valid `branding`, `reporter`, `checks` and `rules` data + */ + export function configure(spec: Spec): void + + /** + * Searches and returns rules that contain a tag in the list of tags. + * @param {Array} tags Optional array of tags + * @return {Array} Array of rules + */ + export function getRules(tags?: string[]): Object[] + + /** + * Restores the default axe configuration + */ + export function reset(): void + + /** + * Function to register a plugin configuration in document and its subframes + * @param {Object} plugin A plugin configuration object + */ + export function registerPlugin(plugin: AxePlugin): void + + /** + * Function to clean up plugin configuration in document and its subframes + */ + export function cleanup(): void + +} + +// axe is also available as a module +declare module "axe-core" { + export = axe; +} diff --git a/azure-mobile-apps/azure-mobile-apps-tests.ts b/azure-mobile-apps/azure-mobile-apps-tests.ts index 093932c2fb..302f732889 100644 --- a/azure-mobile-apps/azure-mobile-apps-tests.ts +++ b/azure-mobile-apps/azure-mobile-apps-tests.ts @@ -72,6 +72,13 @@ table.read.use([function () {}, function () {}]); table.read.use(function () {}, function () {}); table.use(function () {}).use(function () {}).read(function () {}).use(function () {}) +table.access = undefined; +table.access = 'authenticated'; +table.read.access = 'anonymous'; +table.update.access = 'disabled'; +table.delete.access = 'authenticated'; +table.insert.access = 'authenticated'; + // Express.Table, instantiated from the static require('azure-mobile-apps').table() // This is going to be interesting if we ever support more than one provider var table2 = mobileApps.table(); @@ -84,4 +91,14 @@ mobileApps.logger.debug('a debug message') // Query queries.create('table').where({ x: 10 }).select('col1,col2'); -mobileApps.query.create('table'); \ No newline at end of file +mobileApps.query.create('table'); + +// custom sql query +mobileApp.api.add('query', { authorize: true, get: (req, res, next) => { + req.azureMobile.data.execute({ + sql: "SELECT * FROM TODOITEM WHERE COMPLETE = :complete", + parameters: [ + { name: 'complete', value: 1 } + ] + }).then(x => {}); +}, delete: function () {} }); diff --git a/azure-mobile-apps/azure-mobile-apps.d.ts b/azure-mobile-apps/azure-mobile-apps.d.ts index 0a42fa9ecf..a17e41e2d6 100644 --- a/azure-mobile-apps/azure-mobile-apps.d.ts +++ b/azure-mobile-apps/azure-mobile-apps.d.ts @@ -47,6 +47,7 @@ declare namespace Azure.MobileApps { interface Table { authorize?: boolean; + access?: AccessType; autoIncrement?: boolean; dynamicSchema?: boolean; name: string; @@ -66,8 +67,11 @@ declare namespace Azure.MobileApps { (operationHandler: (context: Context) => void): Table; use(...middleware: Middleware[]): Table; use(middleware: Middleware[]): Table; + access: AccessType; } + type AccessType = 'anonymous' | 'authenticated' | 'disabled'; + interface Tables { configuration: Configuration; add(name: string, definition?: Table | TableDefinition): void; @@ -215,7 +219,7 @@ declare namespace Azure.MobileApps { item: any; req: Express.Request; res: Express.Response; - data: (table: TableDefinition) => Data.Table; + data: ContextData; tables: (tableName: string) => Data.Table; user: User; push: typeof nh; @@ -223,6 +227,21 @@ declare namespace Azure.MobileApps { execute(): Thenable; } + interface ContextData { + (table: TableDefinition): Data.Table; + execute(q: SqlQueryDefinition): Thenable; + } + + interface SqlQueryDefinition { + sql: string; + parameters?: SqlParameterDefinition[]; + } + + interface SqlParameterDefinition { + name: string; + value: any; + } + interface TableDefinition { authorize?: boolean; autoIncrement?: boolean; diff --git a/azure-mobile-services-client/AzureMobileServicesClient.d.ts b/azure-mobile-services-client/AzureMobileServicesClient.d.ts index afd6014598..6fa0f9c475 100644 --- a/azure-mobile-services-client/AzureMobileServicesClient.d.ts +++ b/azure-mobile-services-client/AzureMobileServicesClient.d.ts @@ -17,7 +17,7 @@ declare namespace Microsoft.WindowsAzure { login(provider: string, token: string): asyncPromise; login(provider: string, callback: (error: any, user: User) => void ): void; login(provider: string): asyncPromise; - logout(): void; + logout(): asyncPromise; getTable(tableName: string): MobileServiceTable; withFilter(serviceFilter: (request: any, next: (request: any, callback: (error: any, response: any) => void) => void, callback: (error: any, response: any) => void) => void): MobileServiceClient; /** diff --git a/backbone/backbone-global.d.ts b/backbone/backbone-global.d.ts index d86305ee3d..3dca269eb0 100644 --- a/backbone/backbone-global.d.ts +++ b/backbone/backbone-global.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Backbone 1.0.0 +// Type definitions for Backbone 1.3.3 // Project: http://backbonejs.org/ // Definitions by: Boris Yankov , Natan Vivo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -109,9 +109,15 @@ declare namespace Backbone { attributes: any; changed: any[]; + cidPrefix: string; cid: string; collection: Collection; + private _changing: boolean; + private _previousAttributes : any; + private _pending: boolean; + + /** * Default attributes for the model. It can be an object hash or a method returning an object hash. * For assigning an object hash, do it like this: this.defaults = { attribute: value, ... }; @@ -147,7 +153,14 @@ declare namespace Backbone { /*private*/ set(attributeName: string, value: any, options?: ModelSetOptions): Model; set(obj: any, options?: ModelSetOptions): Model; - changedAttributes(attributes?: any): any[]; + /** + * Return an object containing all the attributes that have changed, or + * false if there are no changed attributes. Useful for determining what + * parts of a view need to be updated and/or what attributes need to be + * persisted to the server. Unset attributes will be set to undefined. + * You can also pass an attributes object to diff against the model, + * determining if there *would be* a change. */ + changedAttributes(attributes?: any): any; clear(options?: Silenceable): any; clone(): Model; destroy(options?: ModelDestroyOptions): any; @@ -178,6 +191,7 @@ declare namespace Backbone { omit(fn: (value: any, key: any, object: any) => any): any; chain(): any; isEmpty(): boolean; + matches(attrs: any): boolean; } class Collection extends ModelBase { @@ -208,6 +222,7 @@ declare namespace Backbone { * Get a model from a collection, specified by an id, a cid, or by passing in a model. **/ get(id: number|string|Model): TModel; + has(key: number|string|Model): boolean; create(attributes: any, options?: ModelSaveOptions): TModel; pluck(attribute: string): any[]; push(model: TModel, options?: AddOptions): TModel; @@ -221,10 +236,12 @@ declare namespace Backbone { unshift(model: TModel, options?: AddOptions): TModel; where(properties: any): TModel[]; findWhere(properties: any): TModel; + modelId(attrs: any) : any private _prepareModel(attributes?: any, options?: any): any; private _removeReference(model: TModel): void; private _onModelEvent(event: string, model: TModel, collection: Collection, options: any): void; + private _isModel(obj: any) : obj is Model; /** * Return a shallow copy of this collection's models, using the same options as native Array#slice. @@ -314,6 +331,8 @@ declare namespace Backbone { navigate(fragment: string, options?: NavigateOptions): Router; navigate(fragment: string, trigger?: boolean): Router; + execute(callback: Function, args: any[], name: string) : void; + private _bindRoutes(): void; private _routeToRegExp(route: string): RegExp; private _extractParameters(route: RegExp, fragment: string): string[]; @@ -330,9 +349,14 @@ declare namespace Backbone { getHash(window?: Window): string; getFragment(fragment?: string): string; + decodeFragment(fragment: string): string; + getSearch(): string; stop(): void; route(route: string, callback: Function): number; checkUrl(e?: any): void; + getPath(): string; + matchRoot(): boolean; + atRoot(): boolean; loadUrl(fragmentOverride?: string): boolean; navigate(fragment: string, options?: any): boolean; static started: boolean; diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 65e273a61f..d3887b4176 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Backbone 1.0.0 +// Type definitions for Backbone 1.3.3 // Project: http://backbonejs.org/ // Definitions by: Boris Yankov , Natan Vivo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/backlog-js/backlog-js-tests.ts b/backlog-js/backlog-js-tests.ts new file mode 100644 index 0000000000..979eb57ca4 --- /dev/null +++ b/backlog-js/backlog-js-tests.ts @@ -0,0 +1,88 @@ +/// + +import * as backlogjs from 'backlog-js'; + +const host = 'example.backlog.jp'; +const apiKey = 'apiKey'; +const clientId = 'clientId'; +const clientSecret = 'clientSecret'; +const redirectUri = 'redirectUri'; +const state = 'state'; +const code = 'code'; +const refreshToken = 'refreshToken'; +const configure = { host, apiKey } +const credentials = { clientId, clientSecret } + +const oauth2 = new backlogjs.OAuth2(credentials); +oauth2.getAuthorizationURL({ host, redirectUri, state }); +oauth2.getAccessToken({ host, code, redirectUri }).then(data => {}).catch(err => {}); +oauth2.refreshAccessToken({ host, refreshToken }).then(data => {}).catch(err => {}); + +const backlog = new backlogjs.Backlog(configure); +backlog.getSpace().then(data => { }).catch(err => { }); +backlog.getSpaceActivities({ + activityTypeId: [ + backlogjs.Option.ActivityType.IssueCreated, + backlogjs.Option.ActivityType.IssueUpdated + ], + minId: 1, + maxId: 2, + count: 3, + order: "asc" +}).then(data => { }).catch(err => { }); +backlog.getSpaceDiskUsage().then(data => { }).catch(err => { }); +backlog.getSpaceIcon().then(data => { }).catch(err => { }); +backlog.postSpaceAttachment(new FormData()).then(data => { }).catch(err => { }); +backlog.getUsers().then(data => { }).catch(err => { }); +backlog.getUser(1).then(data => { }).catch(err => { }); +backlog.postUser({ + userId: 'string', + password: 'string', + name: 'string', + mailAddress: 'string', + roleType: backlogjs.Option.User.RoleType.Admin +}).then(data => { }).catch(err => { }); +backlog.patchUser(1, { + password: 'string', + name: 'string', + mailAddress: 'string', + roleType: backlogjs.Option.User.RoleType.Admin +}).then(data => { }).catch(err => { }); +backlog.deleteUser(1).then(data => { }).catch(err => { }); +backlog.getMyself().then(data => { }).catch(err => { }); +backlog.getUserActivities(1, { + activityTypeId: [ + backlogjs.Option.ActivityType.IssueCreated, + backlogjs.Option.ActivityType.IssueUpdated + ], + minId: 1, + maxId: 2, + count: 3, + order: "asc" +}).then(data => { }).catch(err => { }); +backlog.getUserStars(1, { + minId: 1, + maxId: 2, + count: 3, + order: "asc" +}).then(data => { }).catch(err => { }); +backlog.getUserStarsCount(1, { + since: 'YYYY-MM-DD', + until: 'YYYY-MM-DD' +}).then(data => { }).catch(err => { }); +backlog.getRecentlyViewedIssues({ + order: 'asc', + offset: 1, + count: 2 +}).then(data => { }).catch(err => { }); +backlog.getRecentlyViewedProjects({ + order: 'asc', + offset: 1, + count: 2 +}).then(data => { }).catch(err => { }); +backlog.getRecentlyViewedWikis({ + order: 'asc', + offset: 1, + count: 2 +}).then(data => { }).catch(err => { }); +backlog.getUserIcon(1).then(data => {}).catch(err => {}); diff --git a/backlog-js/backlog-js.d.ts b/backlog-js/backlog-js.d.ts new file mode 100644 index 0000000000..353e7e90cd --- /dev/null +++ b/backlog-js/backlog-js.d.ts @@ -0,0 +1,695 @@ +// Type definitions for backlog-js 0.9.0 +// Project: https://github.com/nulab/backlog-js +// Definitions by: Yuichi Watanabe +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// + +declare module 'backlog-js' { + + class Request { + private configure; + constructor(configure: { + host: string; + apiKey?: string; + accessToken?: string; + timeout?: number; + }); + get(path: string, params?: any): Promise; + post(path: string, params?: any): Promise; + put(path: string, params: any): Promise; + patch(path: string, params: any): Promise; + delete(path: string, params?: any): Promise; + request(options: { + method: string; + path: string; + params?: Params | FormData; + }): Promise; + checkStatus(response: IResponse): Promise; + parseJSON(response: IResponse): Promise; + private toFormData(params); + private toQueryString(params); + webAppBaseURL: string; + restBaseURL: string; + } + + type Params = { + [index: string]: number | string | number[] | string[]; + }; + + export class Backlog extends Request { + constructor(configure: { + host: string; + apiKey?: string; + accessToken?: string; + timeout?: number; + }); + getSpace(): Promise; + getSpaceActivities(params: Option.Space.GetActivitiesParams): Promise; + getSpaceNotification(): Promise; + putSpaceNotification(params: Option.Space.PutSpaceNotificationParams): Promise; + getSpaceDiskUsage(): Promise; + getSpaceIcon(): Promise; + postSpaceAttachment(form: FormData): Promise; + getUsers(): Promise; + getUser(userId: number): Promise; + postUser(params: Option.User.PostUserParams): Promise; + patchUser(userId: number, params: Option.User.PatchUserParams): Promise; + deleteUser(userId: number): Promise; + getMyself(): Promise; + getUserActivities(userId: number, params: Option.User.GetUserActivitiesParams): Promise; + getUserStars(userId: number, params: Option.User.GetUserStarsParams): Promise; + getUserStarsCount(userId: number, params: Option.User.GetUserStarsCountParams): Promise; + getRecentlyViewedIssues(params: Option.User.GetRecentlyViewedParams): Promise; + getRecentlyViewedProjects(params: Option.User.GetRecentlyViewedParams): Promise; + getRecentlyViewedWikis(params: Option.User.GetRecentlyViewedParams): Promise; + getUserIcon(userId: number): Promise; + getGroups(params: Option.Group.GetGroupsParams): Promise; + postGroups(params: Option.Group.PostGroupsParams): Promise; + getGroup(groupId: number): Promise; + patchGroup(groupId: number, params: Option.Group.PatchGroupParams): Promise; + deleteGroup(groupId: number): Promise; + getStatuses(): Promise; + getResolutions(): Promise; + getPriorities(): Promise; + postProject(params: Option.Project.PostProjectParams): Promise; + getProjects(params?: Option.Project.GetProjectsParams): Promise; + getProject(projectIdOrKey: string): Promise; + patchProject(projectIdOrKey: string, params: Option.Project.PatchProjectParams): Promise; + deleteProject(projectIdOrKey: string): Promise; + getProjectActivities(projectIdOrKey: string, params: Option.Space.GetActivitiesParams): Promise; + getProjectUsers(projectIdOrKey: string): Promise; + deleteProjectUsers(projectIdOrKey: string, params: Option.Project.DeleteProjectUsersParams): Promise; + postProjectAdministrators(projectIdOrKey: string, params: Option.Project.PostProjectAdministrators): Promise; + getProjectAdministrators(projectIdOrKey: string): Promise; + deleteProjectAdministrators(projectIdOrKey: string, params: Option.Project.DeleteProjectAdministrators): Promise; + getIssueTypes(projectIdOrKey: string): Promise; + postIssueType(projectIdOrKey: string, params: Option.Project.PostIssueTypeParams): Promise; + patchIssueType(projectIdOrKey: string, id: number, params: Option.Project.PatchIssueTypeParams): Promise; + deleteIssueType(projectIdOrKey: string, id: number, params: Option.Project.DeleteIssueTypeParams): Promise; + getCategories(projectIdOrKey: string): Promise; + postCategories(projectIdOrKey: string, params: Option.Project.PostCategoriesParams): Promise; + patchCategories(projectIdOrKey: string, id: number, params: Option.Project.PatchCategoriesParams): Promise; + deleteCategories(projectIdOrKey: string, id: number): Promise; + getVersions(projectIdOrKey: string): Promise; + postVersions(projectIdOrKey: string, params: Option.Project.PostVersionsParams): Promise; + patchVersions(projectIdOrKey: string, id: number, params: Option.Project.PatchVersionsParams): Promise; + deleteVersions(projectIdOrKey: string, id: number): Promise; + getCustomFields(projectIdOrKey: string): Promise; + postCustomField(projectIdOrKey: string, params: Option.Project.PostCustomFieldParams | Option.Project.PostCustomFieldWithNumericParams | Option.Project.PostCustomFieldWithDateParams | Option.Project.PostCustomFieldWithListParams): Promise; + patchCustomField(projectIdOrKey: string, id: number, params: Option.Project.PatchCustomFieldParams | Option.Project.PatchCustomFieldWithNumericParams | Option.Project.PatchCustomFieldWithDateParams | Option.Project.PatchCustomFieldWithListParams): Promise; + deleteCustomField(projectIdOrKey: string, id: number): Promise; + postCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise; + patchCustomFieldItem(projectIdOrKey: string, id: number, itemId: number, params: Option.Project.PatchCustomFieldItemParams): Promise; + deleteCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise; + getSharedFiles(projectIdOrKey: string, path: string, params: Option.Project.GetSharedFilesParams): Promise; + getProjectsDiskUsage(projectIdOrKey: string): Promise; + getWebhooks(projectIdOrKey: string): Promise; + postWebhook(projectIdOrKey: string, params: Option.Project.PostWebhookParams): Promise; + getWebhook(projectIdOrKey: string, webhookId: string): Promise; + patchWebhook(projectIdOrKey: string, webhookId: string, params: Option.Project.PatchWebhookParams): Promise; + deleteWebhook(projectIdOrKey: string, webhookId: string): Promise; + postIssue(params: Option.Issue.PostIssueParams): Promise; + patchIssue(issueIdOrKey: string, params: Option.Issue.PatchIssueParams): Promise; + getIssues(params?: Option.Issue.GetIssuesParams): Promise; + getIssue(issueIdOrKey: string): Promise; + getIssuesCount(params?: Option.Issue.GetIssuesParams): Promise; + deleteIssuesCount(issueIdOrKey: string): Promise; + getIssueComments(issueIdOrKey: string, params: Option.Issue.GetIssueCommentsParams): Promise; + postIssueComments(issueIdOrKey: string, params: Option.Issue.PostIssueCommentsParams): Promise; + getIssueCommentsCount(issueIdOrKey: string): Promise; + getIssueComment(issueIdOrKey: string, commentId: number): Promise; + patchIssueComment(issueIdOrKey: string, commentId: number, params: Option.Issue.PatchIssueCommentParams): Promise; + getIssueCommentNotifications(issueIdOrKey: string, commentId: number): Promise; + postIssueCommentNotifications(issueIdOrKey: string, commentId: number, prams: Option.Issue.IssueCommentNotifications): Promise; + getIssueAttachments(issueIdOrKey: string): Promise; + deleteIssueAttachment(issueIdOrKey: string, attachmentId: string): Promise; + getIssueSharedFiles(issueIdOrKey: string): Promise; + linkIssueSharedFiles(issueIdOrKey: string, params: Option.Issue.LinkIssueSharedFilesParams): Promise; + unlinkIssueSharedFile(issueIdOrKey: string, id: number): Promise; + getWikis(projectIdOrKey: number): Promise; + getWikisCount(projectIdOrKey: number): Promise; + getWikisTags(projectIdOrKey: number): Promise; + postWiki(params: Option.Wiki.PostWikiParams): Promise; + getWiki(wikiId: number): Promise; + patchWiki(wikiId: number, params: Option.Wiki.PatchWikiParams): Promise; + deleteWiki(wikiId: number, mailNotify: boolean): Promise; + getWikisAttachments(wikiId: number): Promise; + postWikisAttachments(wikiId: number, attachmentId: number[]): Promise; + deleteWikisAttachments(wikiId: number, attachmentId: number): Promise; + getWikisSharedFiles(wikiId: number): Promise; + linkWikisSharedFiles(wikiId: number, fileId: number[]): Promise; + unlinkWikisSharedFiles(wikiId: number, id: number): Promise; + getWikisHistory(wikiId: number, params: Option.Wiki.GetWikisHistoryParams): Promise; + getWikisStars(wikiId: number): Promise; + postStar(params: Option.Project.PostStarParams): Promise; + getNotifications(params: Option.Notification.GetNotificationsParams): Promise; + getNotificationsCount(params: Option.Notification.GetNotificationsCountParams): Promise; + resetNotificationsMarkAsRead(): Promise; + markAsReadNotification(id: number): Promise; + getGitRepositories(projectIdOrKey: string): Promise; + getGitRepository(projectIdOrKey: string, repoIdOrName: string): Promise; + getPullRequests(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise; + getPullRequestsCount(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise; + postPullRequest(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.PostPullRequestParams): Promise; + getPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number): Promise; + patchPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PatchPullRequestParams): Promise; + getPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.GetPullRequestCommentsParams): Promise; + postPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PostPullRequestCommentsParams): Promise; + getPullRequestCommentsCount(projectIdOrKey: string, repoIdOrName: string, number: number): Promise; + patchPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, commentId: number, params: Option.PullRequest.PatchPullRequestCommentsParams): Promise; + getPullRequestAttachments(projectIdOrKey: string, repoIdOrName: string, number: number): Promise; + deletePullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise; + getProjectIcon(projectIdOrKey: string): Promise; + getSharedFile(projectIdOrKey: string, sharedFileId: number): Promise; + getIssueAttachment(issueIdOrKey: string, attachmentId: number): Promise; + getWikiAttachment(wikiId: number, attachmentId: number): Promise; + getPullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise; + private download(path); + private upload(path, params); + private parseFileData(response); + } + + export class OAuth2 { + private credentials; + private timeout; + constructor(credentials: Option.OAuth2.Credentials, timeout?: number); + getAuthorizationURL(options: { + host: string; + redirectUri?: string; + state?: string; + }): string; + getAccessToken(options: { + host: string; + code: string; + redirectUri?: string; + }): Promise; + refreshAccessToken(options: { + host: string; + refreshToken: string; + }): Promise; + } + + import { PassThrough } from 'stream'; + export namespace Entity { + export namespace File { + export type FileData = NodeFileData | BrowserFileData; + export interface NodeFileData { + body: PassThrough; + url: string; + filename: string; + } + export interface BrowserFileData { + body: any; + url: string; + blob?: () => Promise; + } + } + export namespace OAuth2 { + export interface AccessToken { + access_token: string; + token_type: string; + expires_in: number; + refresh_token: string; + } + } + } + + + export namespace Option { + export type Order = "asc" | "desc"; + export enum ActivityType { + Undefined = -1, + IssueCreated = 1, + IssueUpdated = 2, + IssueCommented = 3, + IssueDeleted = 4, + WikiCreated = 5, + WikiUpdated = 6, + WikiDeleted = 7, + FileAdded = 8, + FileUpdated = 9, + FileDeleted = 10, + SvnCommitted = 11, + GitPushed = 12, + GitRepositoryCreated = 13, + IssueMultiUpdated = 14, + ProjectUserAdded = 15, + ProjectUserRemoved = 16, + NotifyAdded = 17, + PullRequestAdded = 18, + PullRequestUpdated = 19, + PullRequestCommented = 20, + PullRequestMerged = 21, + } + export namespace Notification { + export interface GetNotificationsParams { + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface GetNotificationsCountParams { + alreadyRead: boolean; + resourceAlreadyRead: boolean; + } + } + export namespace Space { + export interface GetActivitiesParams { + activityTypeId?: ActivityType[]; + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface PutSpaceNotificationParams { + content: string; + } + } + export namespace User { + export interface PostUserParams { + userId: string; + password: string; + name: string; + mailAddress: string; + roleType: RoleType; + } + export interface PatchUserParams { + password?: string; + name?: string; + mailAddress?: string; + roleType?: RoleType; + } + export enum RoleType { + Admin = 1, + User = 2, + Reporter = 3, + Viewer = 4, + GuestReporter = 5, + GuestViewer = 6, + } + export interface GetUserActivitiesParams { + activityTypeId?: ActivityType[]; + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface GetUserStarsParams { + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface GetUserStarsCountParams { + since?: string; + until?: string; + } + export interface GetRecentlyViewedParams { + order?: Order; + offset?: number; + count?: number; + } + } + export namespace Group { + export interface GetGroupsParams { + order?: Order; + offset?: number; + count?: number; + } + export interface PostGroupsParams { + name: string; + members?: string[]; + } + export interface PatchGroupParams { + name?: string; + members?: string[]; + } + } + export namespace Project { + export type TextFormattingRule = "backlog" | "markdown"; + export interface PostProjectParams { + name: string; + key: string; + chartEnabled: boolean; + projectLeaderCanEditProjectLeader?: boolean; + subtaskingEnabled: boolean; + textFormattingRule: TextFormattingRule; + } + export interface PatchProjectParams { + name?: string; + key?: string; + chartEnabled?: boolean; + subtaskingEnabled?: boolean; + projectLeaderCanEditProjectLeader?: boolean; + textFormattingRule?: TextFormattingRule; + archived?: boolean; + } + export interface GetProjectsParams { + archived?: boolean; + all?: boolean; + } + export interface DeleteProjectUsersParams { + userId: number; + } + export interface PostProjectAdministrators { + userId: number; + } + export interface DeleteProjectAdministrators { + userId: number; + } + export type IssueTypeColor = "#e30000" | "#990000" | "#934981" | "#814fbc" | "#2779ca" | "#007e9a" | "#7ea800" | "#ff9200" | "#ff3265" | "#666665"; + export interface PostIssueTypeParams { + name: string; + color: IssueTypeColor; + } + export interface PatchIssueTypeParams { + name?: string; + color?: IssueTypeColor; + } + export interface DeleteIssueTypeParams { + substituteIssueTypeId: number; + } + export interface PostCategoriesParams { + name: string; + } + export interface PatchCategoriesParams { + name: string; + } + export interface PostVersionsParams { + name: string; + description: string; + startDate: string; + releaseDueDate: string; + } + export interface PatchVersionsParams { + name: string; + description?: string; + startDate?: string; + releaseDueDate?: string; + archived?: boolean; + } + export interface PostCustomFieldParams { + typeId: FieldType; + name: string; + applicableIssueTypes?: number[]; + description?: string; + required?: boolean; + } + export interface PostCustomFieldWithNumericParams extends PostCustomFieldParams { + min?: number; + max?: number; + initialValue?: number; + unit?: string; + } + export interface PostCustomFieldWithDateParams extends PostCustomFieldParams { + min?: string; + max?: string; + initialValueType?: number; + initialDate?: string; + initialShift?: number; + } + export interface PostCustomFieldWithListParams extends PostCustomFieldParams { + items?: string[]; + allowInput?: boolean; + allowAddItem?: boolean; + } + export interface PatchCustomFieldParams { + name?: string; + applicableIssueTypes?: number[]; + description?: string; + required?: boolean; + } + export interface PatchCustomFieldWithNumericParams extends PatchCustomFieldParams { + min?: number; + max?: number; + initialValue?: number; + unit?: string; + } + export interface PatchCustomFieldWithDateParams extends PatchCustomFieldParams { + min?: string; + max?: string; + initialValueType?: number; + initialDate?: string; + initialShift?: number; + } + export interface PatchCustomFieldWithListParams extends PatchCustomFieldParams { + items?: string[]; + allowInput?: boolean; + allowAddItem?: boolean; + } + export interface PostCustomFieldItemParams { + name: string; + } + export interface PatchCustomFieldItemParams { + name: string; + } + export interface GetSharedFilesParams { + order?: Order; + offset?: number; + count?: number; + } + export interface PostWebhookParams { + name?: string; + description?: string; + hookUrl?: string; + allEvent?: boolean; + activityTypeIds?: number[]; + } + export interface PatchWebhookParams { + name?: string; + description?: string; + hookUrl?: string; + allEvent?: boolean; + activityTypeIds?: number[]; + } + export enum FieldType { + Text = 1, + TextArea = 2, + Numeric = 3, + Date = 4, + SingleList = 5, + MultipleList = 6, + CheckBox = 7, + Radio = 8, + } + export interface PostStarParams { + issueId?: number; + commentId?: number; + wikiId?: number; + pullRequestId?: number; + pullRequestCommentId?: number; + } + } + export namespace Issue { + export interface PostIssueParams { + projectId: number; + summary: string; + priorityId: number; + issueTypeId: number; + parentIssueId?: number; + description?: string; + startDate?: string; + dueDate?: string; + estimatedHours?: number; + actualHours?: number; + categoryId?: number[]; + versionId?: number[]; + milestoneId?: number[]; + assigneeId?: number; + notifiedUserId?: number[]; + attachmentId?: number[]; + [customField_: string]: any; + } + export interface PatchIssueParams { + summary?: string; + parentIssueId?: number; + description?: string; + statusId?: number; + resolutionId?: number; + startDate?: string; + dueDate?: string; + estimatedHours?: number; + actualHours?: number; + issueTypeId?: number; + categoryId?: number[]; + versionId?: number[]; + milestoneId?: number[]; + priorityId?: number; + assigneeId?: number; + notifiedUserId?: number[]; + attachmentId?: number[]; + comment?: string; + [customField_: string]: any; + } + export interface GetIssuesParams { + projectId?: number[]; + issueTypeId?: number[]; + categoryId?: number[]; + versionId?: number[]; + milestoneId?: number[]; + statusId?: number[]; + priorityId?: number[]; + assigneeId?: number[]; + createdUserId?: number[]; + resolutionId?: number[]; + parentChild?: ParentChildType; + attachment?: boolean; + sharedFile?: boolean; + sort?: SortKey; + order?: Order; + offset?: number; + count?: number; + createdSince?: string; + createdUntil?: string; + updatedSince?: string; + updatedUntil?: string; + startDateSince?: string; + startDateUntil?: string; + dueDateSince?: string; + dueDateUntil?: string; + id?: number[]; + parentIssueId?: number[]; + keyword: string; + [customField_: string]: any; + } + export enum ParentChildType { + All = 0, + NotChild = 1, + Child = 2, + NotChildNotParent = 3, + Parent = 4, + } + export type SortKey = "issueType" | "category" | "version" | "milestone" | "summary" | "status" | "priority" | "attachment" | "sharedFile" | "created" | "createdUser" | "updated" | "updatedUser" | "assignee" | "startDate" | "dueDate" | "estimatedHours" | "actualHours" | "childIssue"; + export interface GetIssueCommentsParams { + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface PostIssueCommentsParams { + content: string; + notifiedUserId?: number[]; + attachmentId?: number[]; + } + export interface PatchIssueCommentParams { + content: string; + } + export interface IssueCommentNotifications { + notifiedUserId: number[]; + } + export interface LinkIssueSharedFilesParams { + fileId: number[]; + } + } + export namespace PullRequest { + export interface GetPullRequestsParams { + statusId?: number[]; + assigneeId?: number[]; + issueId?: number[]; + createdUserId?: number[]; + offset?: number; + count?: number; + } + export interface PostPullRequestParams { + summary: string; + description: string; + base: string; + branch: string; + issueId?: number; + assigneeId?: number; + notifiedUserId?: number[]; + attachmentId?: number[]; + } + export interface PatchPullRequestParams { + summary?: string; + description?: string; + issueId?: number; + assigneeId?: number; + notifiedUserId?: number[]; + comment?: string[]; + } + export interface GetPullRequestCommentsParams { + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface PostPullRequestCommentsParams { + content: string; + notifiedUserId?: number[]; + } + export interface PatchPullRequestCommentsParams { + content: string; + } + } + export namespace Wiki { + export interface PostWikiParams { + projectId: number; + name: string; + content: string; + mailNotify?: boolean; + } + export interface PatchWikiParams { + name?: string; + content?: string; + mailNotify?: boolean; + } + export interface GetWikisHistoryParams { + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + } + export namespace OAuth2 { + export interface Credentials { + clientId: string; + clientSecret: string; + } + } + } + + export namespace Error { + export class BacklogError extends global.Error { + private _name; + private _url; + private _status; + private _body; + private _response; + constructor(name: BacklogErrorNameType, response: IResponse, body?: { + errors: BacklogErrorMessage[]; + }); + name: BacklogErrorNameType; + url: string; + status: number; + body: { + errors: BacklogErrorMessage[]; + }; + response: IResponse; + } + export class BacklogApiError extends BacklogError { + constructor(response: IResponse, body?: { + errors: BacklogErrorMessage[]; + }); + } + export class BacklogAuthError extends BacklogError { + constructor(response: IResponse, body?: { + errors: BacklogErrorMessage[]; + }); + } + export class UnexpectedError extends BacklogError { + constructor(response: IResponse); + } + export interface BacklogErrorMessage { + message: string; + code: number; + errorInfo: string; + moreInfo: string; + } + export type BacklogErrorNameType = 'BacklogApiError' | 'BacklogAuthError' | 'UnexpectedError'; + } + +} diff --git a/base16/base16-tests.ts b/base16/base16-tests.ts new file mode 100644 index 0000000000..e4cf78d559 --- /dev/null +++ b/base16/base16-tests.ts @@ -0,0 +1,24 @@ +/// + +import * as base16 from 'base16'; + +const colorScheme: base16.ColorScheme = base16.solarized + +const scheme: string = colorScheme.scheme +const author: string = colorScheme.author +const base00: string = colorScheme.base00 +const base01: string = colorScheme.base01 +const base02: string = colorScheme.base02 +const base03: string = colorScheme.base03 +const base04: string = colorScheme.base04 +const base05: string = colorScheme.base05 +const base06: string = colorScheme.base06 +const base07: string = colorScheme.base07 +const base08: string = colorScheme.base08 +const base09: string = colorScheme.base09 +const base0A: string = colorScheme.base0A +const base0B: string = colorScheme.base0B +const base0C: string = colorScheme.base0C +const base0D: string = colorScheme.base0D +const base0E: string = colorScheme.base0E +const base0F: string = colorScheme.base0F diff --git a/base16/base16.d.ts b/base16/base16.d.ts new file mode 100644 index 0000000000..32717e99f2 --- /dev/null +++ b/base16/base16.d.ts @@ -0,0 +1,70 @@ +// Type definitions for base16-js 1.0.0 +// Project: https://github.com/gaearon/base16-js +// Definitions by: Alec Hill +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'base16' { + + /** + * Type describing a syntax highlighting scheme as a JS object, as used in redux dev tools + * Based on https://github.com/chriskempson/base16 + */ + export interface ColorScheme { + scheme: string + author: string + base00: string + base01: string + base02: string + base03: string + base04: string + base05: string + base06: string + base07: string + base08: string + base09: string + base0A: string + base0B: string + base0C: string + base0D: string + base0E: string + base0F: string + } + + // predefined schemes... + export var threezerotwofour: ColorScheme + export var apathy: ColorScheme + export var ashes: ColorScheme + export var atelierDune: ColorScheme + export var atelierForest: ColorScheme + export var atelierHeath: ColorScheme + export var atelierLakeside: ColorScheme + export var atelierSeaside: ColorScheme + export var bespin: ColorScheme + export var brewer: ColorScheme + export var bright: ColorScheme + export var chalk: ColorScheme + export var codeschool: ColorScheme + export var colors: ColorScheme + export var eighties: ColorScheme + export var embers: ColorScheme + export var flat: ColorScheme + export var google: ColorScheme + export var grayscale: ColorScheme + export var greenscreen: ColorScheme + export var harmonic: ColorScheme + export var hopscotch: ColorScheme + export var isotope: ColorScheme + export var marrakesh: ColorScheme + export var monokai: ColorScheme + export var ocean: ColorScheme + export var paraiso: ColorScheme + export var pop: ColorScheme + export var railscasts: ColorScheme + export var shapeshifter: ColorScheme + export var solarized: ColorScheme + export var summerfruit: ColorScheme + export var tomorrow: ColorScheme + export var tube: ColorScheme + export var twilight: ColorScheme + +} diff --git a/base64url/base64url.d.ts b/base64url/base64url.d.ts new file mode 100644 index 0000000000..42dbe4cca5 --- /dev/null +++ b/base64url/base64url.d.ts @@ -0,0 +1,74 @@ +// Type definitions for base64url v2.0.0 +// Project: https://github.com/brianloveswords/base64url +// Definitions by: Stepan Miroshin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/** + * For encoding and decoding base64url! + * v2.0.0 + */ + +/** + * Encoding type + */ +declare type Encoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "utf16le" | "base64" | "binary" | "hex" + +interface IBase64Url { + /** + * Encode input to base64url + * @param {string} input Incoming input + * @param {Encoding} encoding Default 'utf8' + * @return {string} + */ + (input: string, encoding?: Encoding): string; + /** + * Encode input to base64url + * @param {Buffer} input Incoming value + */ + (inout: Buffer): string; + /** + * Encode input to base64url + * + * @param {string} input Incoming input + * @param {Encoding} encoding Default 'utf8' + * @returns {string} + */ + encode(input: string, encoding?: Encoding): string; + /** + * Encode input to base64url + * @param {Buffer} input Incoming value + */ + encode(input: Buffer): string; + /** + * Convert a base64url encoded string into a raw string. + * @param {string} base64url base64url encoded string + * @param {Encoding} encoding Encoding defaults to 'utf8' + * @returns {string} + */ + decode(base64url: string, encoding?: string): string; + /** + * Convert a base64url encoded string to a base64 encoded string + * @param {string | Buffer} base64url base64url encoded value + * @returns {string} + */ + toBase64(base64url: string | Buffer): string; + /** + * Convert a base64 encoded string to a base64url encoded string + * @param {string} base64 encoded string + * @returns {string} + */ + fromBase64(base64: string): string; + /** + * Convert a base64url encoded string to a Buffer + * @param {string} base64url encoded string + * @returns {Buffer} + */ + toBuffer(base64url: string): Buffer; +} + +declare module "base64url" { + const base64url: IBase64Url; + export = base64url; +} diff --git a/base64url/base64url.test.ts b/base64url/base64url.test.ts new file mode 100644 index 0000000000..01b3934bc9 --- /dev/null +++ b/base64url/base64url.test.ts @@ -0,0 +1,26 @@ +/// + +import * as base64url from "base64url"; + +// default +let str = base64url("some value"); +str = base64url("some value", "hex"); +str = base64url(new Buffer("some value")); + +// encode +str = base64url.encode("some value"); +str = base64url.encode("some value", "hex"); +str = base64url.encode(new Buffer("some value")); + +// decode +str = base64url.decode("ADA="); +str = base64url.decode("ADA=", "binary"); + +// toBase64 +str = base64url.toBase64("ADA="); +str = base64url.toBase64(new Buffer("ADA=", "base64")); + +// fromBase64 +str = base64url.fromBase64("ADA="); + +let buf = base64url.toBase64("ADA="); \ No newline at end of file diff --git a/bazinga-translator/bazinga-translator-tests.ts b/bazinga-translator/bazinga-translator-tests.ts new file mode 100644 index 0000000000..2401641815 --- /dev/null +++ b/bazinga-translator/bazinga-translator-tests.ts @@ -0,0 +1,12 @@ +/// + +Translator.fallback = 'en'; +Translator.defaultDomain = 'messages'; + +Translator.add("test", "it work", "frontend", "en"); + +Translator.trans('key', {}, 'frontend'); +Translator.trans('key', {"foo": "bar"}, 'DOMAIN_NAME'); + +Translator.transChoice('key', 1, {}, 'frontend'); +Translator.transChoice('key', 123, {"foo": "bar"}, 'DOMAIN_NAME'); \ No newline at end of file diff --git a/bazinga-translator/bazinga-translator.d.ts b/bazinga-translator/bazinga-translator.d.ts new file mode 100644 index 0000000000..5467fbfd85 --- /dev/null +++ b/bazinga-translator/bazinga-translator.d.ts @@ -0,0 +1,99 @@ +// Type definitions for Translator +// Project: https://github.com/willdurand/BazingaJsTranslationBundle +// Definitions by: Alex +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface BazingaTranslator { + /** + * The current locale. + * + * @type {String} + */ + locale: string; + + /** + * Fallback locale. + * + * @type {String} + */ + fallback: string; + + /** + * Placeholder prefix. + * + * @type {String} + */ + placeHolderPrefix: string; + + /** + * Placeholder suffix. + * + * @type {String} + */ + placeHolderSuffix: string; + + /** + * Default domain. + * + * @type {String} + */ + defaultDomain: string; + + /** + * Plural separator. + * + * @type {String} + */ + pluralSeparator: string; + + /** + * Adds a translation entry. + * + * @param {String} id The message id + * @param {String} message The message to register for the given id + * @param {String} [domain] The domain for the message or null to use the default + * @param {String} [locale] The locale or null to use the default + * + * @return {Object} Translator + */ + add(id: string, message: string, domain: string, locale: string): BazingaTranslator; + + + /** + * Translates the given message. + * + * @param {String} id The message id + * @param {Object} [parameters] An array of parameters for the message + * @param {String} [domain] The domain for the message or null to guess it + * @param {String} [locale] The locale or null to use the default + * + * @return {String} The translated string + */ + trans(id: string, parameters: any, domain: string, locale?: string): string; + + /** + * Translates the given choice message by choosing a translation according to a number. + * + * @param {String} id The message id + * @param {Number} number The number to use to find the indice of the message + * @param {Object} [parameters] An array of parameters for the message + * @param {String} [domain] The domain for the message or null to guess it + * @param {String} [locale] The locale or null to use the default + * + * @return {String} The translated string + */ + transChoice(id: string, number: number, parameters: any, domain: string, locale?: string): string, + + /** + * Loads translations from JSON. + * + * @param {String} data A JSON string or object literal + * + * @return {Object} Translator + */ + fromJSON(data: string): BazingaTranslator; + + reset(): void; +} + +declare var Translator: BazingaTranslator; \ No newline at end of file diff --git a/bezier-js/bezier-js-tests.ts b/bezier-js/bezier-js-tests.ts index 54c629d11b..2f9f2685a2 100644 --- a/bezier-js/bezier-js-tests.ts +++ b/bezier-js/bezier-js-tests.ts @@ -1,27 +1,29 @@ /// function test() { - + var bezierjs: typeof BezierJs; - - var bezier = new bezierjs.Bezier([1,2,3,4]); + + var bezier = new bezierjs.Bezier([1, 2, 3, 4]); var cap = new bezierjs.BezierCap([]); var point: BezierJs.Point = { x: 0, y: 0 }; var utils = bezier.getUtils(); - var line: BezierJs.Line = { p1: { x:0, y: 0}, p2: {x:1, y: 1}}; + var line: BezierJs.Line = { p1: { x: 0, y: 0 }, p2: { x: 1, y: 1 } }; var abc: BezierJs.ABC = { A: null, B: null, C: null }; var arc: BezierJs.Arc = { e: 0, s: 0, x: 0, y: 0, r: 1 }; var bbox: BezierJs.BBox = bezier.bbox(); - var closest: BezierJs.Closest = { mdist: 1, mpos: 0 }; - var inflection: BezierJs.Inflection = { values: null, x: [0], y: [0], z:[0] }; + var closest: BezierJs.Closest = { mdist: 1, mpos: 0 }; + var inflection: BezierJs.Inflection = { values: null, x: [0], y: [0], z: [0] }; var minmax: BezierJs.MinMax = { min: 0, max: 0 }; var offset: BezierJs.Offset = { x: 0, y: 0, c: point, n: point }; var pair: BezierJs.Pair = { left: bezier, right: bezier }; var poly: BezierJs.PolyBezier = bezier.outline(1); var projection: BezierJs.Projection = { x: 0, y: 0, t: 9, d: 4 }; - var shape: BezierJs.Shape = { startcap: cap, endcap: cap, forward: bezier, back: bezier, bbox: bbox }; + var shape: BezierJs.Shape = { + startcap: cap, endcap: cap, forward: bezier, back: bezier, bbox: bbox, intersections: function (shape) { return [[0]]; } + }; var split: BezierJs.Split = { left: bezier, right: bezier, span: [point] }; - + bezier.arcs(); bezier.clockwise; bezier.compute(.5); @@ -36,10 +38,10 @@ function test() { bezier.length(); bezier.lineIntersects(line); bezier.normal(0); - bezier.offset(1,2); + bezier.offset(1, 2); bezier.on(point, 0); bezier.order = 5; - bezier.outlineshapes(1,3); + bezier.outlineshapes(1, 3); bezier.overlaps(bezier); bezier.point(9); bezier.project(point); @@ -52,9 +54,9 @@ function test() { bezier.split(0.5).left; bezier.toSVG(); bezier.update(); - + cap.virtual = true; - + poly.addCurve(bezier); poly.bbox(); poly.curve(7); @@ -62,12 +64,12 @@ function test() { poly.length(); poly.offset(9).points[0].y; poly.points[0]; - + utils.abcratio(0, 1); utils.align([point], line); utils.angle(point, point, point); utils.approximately(5, 7, .001); - utils.arcfn(1, function(){}); + utils.arcfn(1, function () { }); utils.bboxoverlap(bbox, bbox); utils.between(0, 0, 1); utils.closest([point], point); @@ -78,7 +80,7 @@ function test() { utils.findbbox([bezier]); utils.getccenter(point, point, point); utils.getminmax(bezier, 'x', [0]); - utils.length(function(){}); + utils.length(function () { }); utils.lerp(1, point, point); utils.lli(offset, offset); utils.lli4(point, point, point, point); @@ -92,5 +94,5 @@ function test() { utils.roots([point], line); utils.round(.999, .001); utils.shapeintersections(shape, bbox, shape, bbox); - + } \ No newline at end of file diff --git a/bezier-js/bezier-js.d.ts b/bezier-js/bezier-js.d.ts index 8256f4ce99..8ee85790b1 100644 --- a/bezier-js/bezier-js.d.ts +++ b/bezier-js/bezier-js.d.ts @@ -57,6 +57,7 @@ declare module BezierJs { back: Bezier; endcap: BezierCap; bbox: BBox; + intersections: (shape: Shape) => string[][] | number[][]; } interface ABC { A: Point; @@ -76,8 +77,8 @@ declare module BezierJs { * */ class Bezier { - clockwise: boolean; private _linear; + clockwise: boolean; _3d: boolean; _t1: number; _t2: number; @@ -124,16 +125,16 @@ declare module BezierJs { overlaps(curve: Bezier): boolean; offset(t: number, d?: number): Offset | Bezier[]; simple(): boolean; - reduce(): any[]; + reduce(): Bezier[]; scale(d: Function): Bezier; scale(d: number): Bezier; outline(d1: number, d2?: number, d3?: number, d4?: number): PolyBezier; - outlineshapes(d1: number, d2: number): Shape[]; - intersects(curve: Bezier): string[] | number[]; + outlineshapes(d1: number, d2: number, curveIntersectionThreshold?: number): Shape[]; + intersects(curve: Bezier, curveIntersectionThreshold?: number): string[] | number[]; intersects(curve: Line): string[] | number[]; lineIntersects(line: Line): number[]; - selfintersects(): string[]; - curveintersects(c1: Bezier[], c2: Bezier[]): string[]; + selfintersects(curveIntersectionThreshold?: number): string[]; + curveintersects(c1: Bezier[], c2: Bezier[], curveIntersectionThreshold?: number): string[]; arcs(errorThreshold?: number): Arc[]; private _error(pc, np1, s, e); private _iterate(errorThreshold, circles); @@ -165,8 +166,8 @@ declare module BezierJs.utils { function lli(v1: Offset, v2: Offset): Point; function makeline(p1: Point, p2: Point): Bezier; function findbbox(sections: Bezier[]): BBox; - function shapeintersections(s1: Shape, bbox1: BBox, s2: Shape, bbox2: BBox): string[][] | number[][]; - function makeshape(forward: Bezier, back: Bezier): Shape; + function shapeintersections(s1: Shape, bbox1: BBox, s2: Shape, bbox2: BBox, curveIntersectionThreshold?: number): string[][] | number[][]; + function makeshape(forward: Bezier, back: Bezier, curveIntersectionThreshold?: number): Shape; function getminmax(curve: Bezier, d: string, list: number[]): MinMax; function align(points: Point[], line: Line): Point[]; function roots(points: Point[], line: Line): number[]; @@ -174,7 +175,7 @@ declare module BezierJs.utils { function inflections(points: Point[]): number[]; function bboxoverlap(b1: BBox, b2: BBox): boolean; function expandbox(bbox: BBox, _bbox: BBox): void; - function pairiteration(c1: Bezier, c2: Bezier): string[]; + function pairiteration(c1: Bezier, c2: Bezier, curveIntersectionThreshold?: number): string[]; function getccenter(p1: Point, p2: Point, p3: Point): Arc; } declare module BezierJs { diff --git a/big.js/big.js-tests.ts b/big.js/big.js-tests.ts index 0067a0b4f5..5a12cab011 100644 --- a/big.js/big.js-tests.ts +++ b/big.js/big.js-tests.ts @@ -12,6 +12,7 @@ */ +import BigJS = BigJsLibrary.BigJS; function constructorTests() { var x = new Big(9) // '9' var y = new Big(x) // '9' @@ -247,4 +248,19 @@ function testMultipleConstructors() { x.div(3) // 1.667 y.div(3) // 1.6666666667 -} \ No newline at end of file +} + +function multipleTypesAccepted(n: number | BigJS | string) { + var y = Big(n) + .minus(n) + .mod(n) + .plus(n) + .times(n); + y.cmp(n); + y.eq(n); + y.gt(n); + y.gte(n); + y.lt(n); + y.lte(n); + y.div(n) +} diff --git a/big.js/big.js.d.ts b/big.js/big.js.d.ts index 52a653ba83..e08ee7bc57 100644 --- a/big.js/big.js.d.ts +++ b/big.js/big.js.d.ts @@ -25,23 +25,11 @@ declare namespace BigJsLibrary { RM: RoundingMode; } + type BigNumberInputType = number | string | BigJS; + interface BigJS_Constructors { - /** A decimal value. */ - new (value: number): BigJS; - /** A decimal value. - String values may be in exponential, as well as normal (non-exponential) notation. There is no limit to the number of digits of a string value (other than that of Javascript's maximum array size), but the largest recommended exponent magnitude is 1e+6. Infinity, NaN and hexadecimal literal strings, e.g. '0xff', are not valid. - String values in octal literal form will be interpreted as decimals, e.g. '011' is 11, not 9. */ - new (value: string): BigJS; - /** A decimal value. */ - new (value: BigJS): BigJS; - /** A decimal value. */ - (value: number): BigJS; - /** A decimal value. - String values may be in exponential, as well as normal (non-exponential) notation. There is no limit to the number of digits of a string value (other than that of Javascript's maximum array size), but the largest recommended exponent magnitude is 1e+6. Infinity, NaN and hexadecimal literal strings, e.g. '0xff', are not valid. - String values in octal literal form will be interpreted as decimals, e.g. '011' is 11, not 9. */ - (value: string): BigJS; - /** A decimal value. */ - (value: BigJS): BigJS; + new (value: BigNumberInputType): BigJS; + (value: BigNumberInputType): BigJS; /** A decimal value. */ (): BigJS; @@ -57,85 +45,35 @@ declare namespace BigJsLibrary { 1 = If the value of this Big number is greater than the value of n -1 = If the value of this Big number is less than the value of n 0 = If this Big number and n have the same value */ - cmp(n: number): number; - /** Compare - @returns {Number} - 1 = If the value of this Big number is greater than the value of n - -1 = If the value of this Big number is less than the value of n - 0 = If this Big number and n have the same value */ - cmp(n: string): number; - /** Compare - @returns {Number} - 1 = If the value of this Big number is greater than the value of n - -1 = If the value of this Big number is less than the value of n - 0 = If this Big number and n have the same value */ - cmp(n: BigJS): number; + cmp(n: BigNumberInputType): number; /** Returns a Big number whose value is the value of this Big number divided by n. */ - div(n: number): BigJS; - /** Returns a Big number whose value is the value of this Big number divided by n. */ - div(n: string): BigJS; - /** Returns a Big number whose value is the value of this Big number divided by n. */ - div(n: BigJS): BigJS; + div(n: BigNumberInputType): BigJS; /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ - eq(n: number): boolean; - /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ - eq(n: string): boolean; - /** Returns true if the value of this Big equals the value of n, otherwise returns false. */ - eq(n: BigJS): boolean; + eq(n: BigNumberInputType): boolean; /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ - gt(n: number): boolean; - /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ - gt(n: string): boolean; - /** Returns true if the value of this Big is greater than the value of n, otherwise returns false. */ - gt(n: BigJS): boolean; + gt(n: BigNumberInputType): boolean; /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ - gte(n: number): boolean; - /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ - gte(n: string): boolean; - /** Returns true if the value of this Big is greater than or equal to the value of n, otherwise returns false. */ - gte(n: BigJS): boolean; + gte(n: BigNumberInputType): boolean; /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ - lt(n: number): boolean; - /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ - lt(n: string): boolean; - /** Returns true if the value of this Big is less than the value of n, otherwise returns false. */ - lt(n: BigJS): boolean; + lt(n: BigNumberInputType): boolean; /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ - lte(n: number): boolean; - /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ - lte(n: string): boolean; - /** Returns true if the value of this Big is less than or equal to the value of n, otherwise returns false. */ - lte(n: BigJS): boolean; + lte(n: BigNumberInputType): boolean; /** Returns a Big number whose value is the value of this Big number minus n. */ - minus(n: number): BigJS; - /** Returns a Big number whose value is the value of this Big number minus n. */ - minus(n: string): BigJS; - /** Returns a Big number whose value is the value of this Big number minus n. */ - minus(n: BigJS): BigJS; + minus(n: BigNumberInputType): BigJS; /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. - The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ - mod(n: number): BigJS; - /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. - The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ - mod(n: string): BigJS; - /** Returns a Big number whose value is the value of this Big number modulo n, i.e. the integer remainder of dividing this Big number by n. - The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ - mod(n: BigJS): BigJS; + The result will have the same sign as this Big number, and it will match that of Javascript's % operator (within the limits of its precision) and BigDecimal's remainder method. */ + mod(n: BigNumberInputType): BigJS; /** Returns a Big number whose value is the value of this Big number plus n. */ - plus(n: number): BigJS; - /** Returns a Big number whose value is the value of this Big number plus n. */ - plus(n: string): BigJS; - /** Returns a Big number whose value is the value of this Big number plus n. */ - plus(n: BigJS): BigJS; + plus(n: BigNumberInputType): BigJS; /** Returns a Big number whose value is the value of this Big number raised to the power exp. If exp is negative and the result has more fraction digits than is specified by Big.DP, it will be rounded to Big.DP decimal places using rounding mode Big.RM. @@ -156,11 +94,7 @@ declare namespace BigJsLibrary { sqrt(): BigJS; /** Returns a Big number whose value is the value of this Big number times n. */ - times(n: number): BigJS; - /** Returns a Big number whose value is the value of this Big number times n. */ - times(n: string): BigJS; - /** Returns a Big number whose value is the value of this Big number times n. */ - times(n: BigJS): BigJS; + times(n: BigNumberInputType): BigJS; /** Returns a string representing the value of this Big number in exponential notation to a fixed number of decimal places dp. */ toExponential(): string; diff --git a/blessed/blessed-tests.ts b/blessed/blessed-tests.ts new file mode 100644 index 0000000000..4e7f7002e6 --- /dev/null +++ b/blessed/blessed-tests.ts @@ -0,0 +1,773 @@ +/// + +import * as blessed from 'blessed'; + +let screen: blessed.Widgets.Screen = null; + +// https://github.com/chjj/blessed/blob/master/test/widget-autopad.js + +screen = blessed.screen({ + dump: __dirname + '/logs/autopad.log', + smartCSR: true, + autoPadding: true, + warnings: true +}); + +var box1 = blessed.box({ + parent: screen, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line' +}); + +var box2 = blessed.box({ + parent: box1, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line' +}); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-bigtext.js + +screen = blessed.screen({ + dump: __dirname + '/logs/bigtext.log', + smartCSR: true, + warnings: true +}); + +var box = blessed.bigtext({ + parent: screen, + content: 'Hello', + shrink: true, + width: '80%', + // height: '80%', + height: 'shrink', + // width: 'shrink', + border: 'line', + fch: ' ', + ch: '\u2592', + style: { + fg: 'red', + bg: 'blue', + bold: false + } +}); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-csr.js + +screen = blessed.screen({ + dump: __dirname + '/logs/csr.log', + smartCSR: true, + warnings: true +}); + +var lorem = require('fs').readFileSync(__dirname + '/git.diff', 'utf8'); + +var cleanSides = screen.cleanSides; +function expectClean(value: any) { + screen.cleanSides = function(el: blessed.widget.Element) { + var ret = cleanSides.apply(this, arguments); + if (ret !== value) { + throw new Error('Failed. Expected ' + + value + ' from cleanSides. Got ' + + ret + '.'); + } + return ret; + }; +} +var btext = blessed.box({ + parent: screen, + left: 'center', + top: 'center', + width: '80%', + height: '80%', + style: { + bg: 'green' + }, + border: 'line', + content: 'CSR should still work.' +}); +let _oscroll = btext.scroll; +btext.scroll = function(offset, always) { + expectClean(true); + return _oscroll(offset, always); +}; + +var text = blessed.scrollabletext({ + parent: screen, + content: lorem, + border: 'line', + left: 'center', + top: 'center', + draggable: true, + width: '50%', + height: '50%', + mouse: true, + keys: true, + vi: true +}); + +_oscroll = text.scroll; +text.scroll = function(offset, always) { + var el = this; + var value = true; + if (el.left < 0) value = true; + if (el.top < 0) value = false; + if (el.left + el.width > screen.width) value = true; + if (el.top + el.height > screen.height) value = false; + expectClean(value); + return _oscroll(offset, always); +}; + +text.focus(); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-dock-noborder.js + +screen = blessed.screen({ + dump: __dirname + '/logs/dock.log', + smartCSR: true, + dockBorders: true, + warnings: true +}); + +blessed.box({ + parent: screen, + left: -1, + top: -1, + width: '50%+1', + height: '50%+1', + border: 'line', + content: 'Foo' +}); + +blessed.box({ + parent: screen, + left: '50%-1', + top: -1, + width: '50%+3', + height: '50%+1', + content: 'Bar', + border: 'line' +}); + +blessed.box({ + parent: screen, + left: -1, + top: '50%-1', + width: '50%+1', + height: '50%+3', + border: 'line', + content: 'Foo' +}); + +blessed.listtable({ + parent: screen, + left: '50%-1', + top: '50%-1', + width: '50%+3', + height: '50%+3', + border: 'line', + align: 'center', + tags: true, + keys: true, + vi: true, + mouse: true, + style: { + header: { + fg: 'blue', + bold: true + }, + cell: { + fg: 'magenta', + selected: { + bg: 'blue' + } + } + }, + data: [ + [ 'Animals', 'Foods', 'Times', 'Numbers' ], + [ 'Elephant', 'Apple', '1:00am', 'One' ], + [ 'Bird', 'Orange', '2:15pm', 'Two' ], + [ 'T-Rex', 'Taco', '8:45am', 'Three' ], + [ 'Mouse', 'Cheese', '9:05am', 'Four' ] + ] +}).focus(); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://raw.githubusercontent.com/chjj/blessed/master/example/simple-form.js + +var form = blessed.form({ + parent: screen, + keys: true, + left: 0, + top: 0, + width: 30, + height: 4, + bg: 'green', + content: 'Submit or cancel?' +}); + +var submit = blessed.button({ + parent: form, + mouse: true, + keys: true, + padding: { + left: 1, + right: 1 + }, + left: 10, + top: 2, + shrink: true, + name: 'submit', + content: 'submit', + style: { + bg: 'blue', + focus: { + bg: 'red' + }, + hover: { + bg: 'red' + } + } +}); + +var cancel = blessed.button({ + parent: form, + mouse: true, + keys: true, + padding: { + left: 1, + right: 1 + }, + left: 20, + top: 2, + shrink: true, + name: 'cancel', + content: 'cancel', + style: { + bg: 'blue', + focus: { + bg: 'red' + }, + hover: { + bg: 'red' + } + } +}); + +// https://github.com/chjj/blessed/blob/master/test/widget-layout.js + +screen = blessed.screen({ + dump: __dirname + '/logs/layout.log', + smartCSR: true, + autoPadding: true, + warnings: true +}); + +var layout = blessed.layout({ + parent: screen, + top: 'center', + left: 'center', + width: '50%', + height: '50%', + border: 'line', + layout: process.argv[2] === 'grid' ? 'grid' : 'inline', + style: { + bg: 'red', + border: { + fg: 'blue' + } + } +}); + +var box1 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '1' +}); + +var box2 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '2' +}); + +var box3 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '3' +}); + +var box4 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '4' +}); + +var box5 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '5' +}); + +var box6 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '6' +}); + +var box7 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '7' +}); + +var box8 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '8' +}); + +var box9 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '9' +}); + +var box10 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '10' +}); + +var box11 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '11' +}); + +var box12 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '12' +}); + +if (process.argv[2] !== 'grid') { + for (var i = 0; i < 10; i++) { + blessed.box({ + parent: layout, + // width: i % 2 === 0 ? 10 : 20, + // height: i % 2 === 0 ? 5 : 10, + width: Math.random() > 0.5 ? 10 : 20, + height: Math.random() > 0.5 ? 5 : 10, + border: 'line', + content: (i + 1 + 12) + '' + }); + } +} + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-form.js + +screen = blessed.screen({ + dump: __dirname + '/logs/form.log', + warnings: true +}); + +type FormData = { + radio1: boolean; + radio2: boolean; + text: string; + check: boolean; +}; + +var form2 = blessed.form({ + parent: screen, + mouse: true, + keys: true, + vi: true, + left: 0, + top: 0, + width: '100%', + //height: 12, + style: { + bg: 'green', + border: { + inverse: true + }, + scrollbar: { + inverse: true + } + }, + content: 'foobar', + scrollable: true, + scrollbar: { + ch: ' ' + } + //alwaysScroll: true +}); + +form2.on('submit', (data) => { + output.setContent(JSON.stringify(data, null, 2)); + screen.render(); +}); + +form2.key('d', function() { + form2.scroll(1, true); + screen.render(); +}); + +form2.key('u', function() { + form2.scroll(-1, true); + screen.render(); +}); + +var set = blessed.radioset({ + parent: form2, + left: 1, + top: 1, + shrink: true, + //padding: 1, + //content: 'f', + style: { + bg: 'magenta' + } +}); + +var radio1 = blessed.radiobutton({ + parent: set, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 0, + top: 0, + name: 'radio1', + content: 'radio1' +}); + +var radio2 = blessed.radiobutton({ + parent: set, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 15, + top: 0, + name: 'radio2', + content: 'radio2' +}); + +var text2 = blessed.textbox({ + parent: form2, + mouse: true, + keys: true, + style: { + bg: 'blue' + }, + height: 1, + width: 20, + left: 1, + top: 3, + name: 'text' +}); + +text2.on('focus', function() { + text2.readInput(); +}); + +var check = blessed.checkbox({ + parent: form2, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 28, + top: 1, + name: 'check', + content: 'check' +}); + +var check2 = blessed.checkbox({ + parent: form2, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 28, + top: 14, + name: 'foooooooo2', + content: 'foooooooo2' +}); + +var submit = blessed.button({ + parent: form2, + mouse: true, + keys: true, + shrink: true, + padding: { + left: 1, + right: 1 + }, + left: 29, + top: 3, + name: 'submit', + content: 'submit', + style: { + bg: 'blue', + focus: { + bg: 'red' + } + } +}); + +submit.on('press', function() { + form2.submit(); +}); + +var box1 = blessed.box({ + parent: form2, + left: 1, + top: 10, + height: 10, + width: 10, + content: 'one', + style: { + bg: 'cyan' + } +}); + +var box2 = blessed.box({ + parent: box1, + left: 1, + top: 2, + height: 8, + width: 9, + content: 'two', + style: { + bg: 'magenta' + } +}); + +var box3 = blessed.box({ + parent: box2, + left: 1, + top: 2, + height: 6, + width: 8, + content: 'three', + style: { + bg: 'yellow' + } +}); + +var box4 = blessed.box({ + parent: box3, + left: 1, + top: 2, + height: 4, + width: 7, + content: 'four', + style: { + bg: 'blue' + } +}); + +var output = blessed.scrollabletext({ + parent: form2, + mouse: true, + keys: true, + left: 0, + top: 20, + height: 5, + right: 0, + style: { + bg: 'red' + }, + content: 'foobar' +}); + +var bottom = blessed.line({ + parent: form2, + type: 'line', + orientation: 'horizontal', + left: 0, + right: 0, + top: 50, + style: { + fg: 'blue' + } +}); + +screen.key('q', function() { + return screen.destroy(); +}); + +form2.focus(); + +form2.submit(); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-table.js + +screen = blessed.screen({ + dump: __dirname + '/logs/table.log', + autoPadding: false, + fullUnicode: true, + warnings: true +}); + +var DU = '杜'; +var JUAN = '鹃'; + +var table = blessed.table({ + //parent: screen, + top: 'center', + left: 'center', + data: null, + border: 'line', + align: 'center', + tags: true, + //width: '80%', + width: 'shrink', + style: { + border: { + fg: 'red' + }, + header: { + fg: 'blue', + bold: true + }, + cell: { + fg: 'magenta' + } + } +}); + +var data1 = [ + [ 'Animals', 'Foods', 'Times' ], + [ 'Elephant', 'Apple', '1:00am' ], + [ 'Bird', 'Orange', '2:15pm' ], + [ 'T-Rex', 'Taco', '8:45am' ], + [ 'Mouse', 'Cheese', '9:05am' ] +]; + +data1[1][0] = '{red-fg}' + data1[1][0] + '{/red-fg}'; +data1[2][0] += ' (' + DU + JUAN + ')'; + +var data2 = [ + [ 'Animals', 'Foods', 'Times', 'Numbers' ], + [ 'Elephant', 'Apple', '1:00am', 'One' ], + [ 'Bird', 'Orange', '2:15pm', 'Two' ], + [ 'T-Rex', 'Taco', '8:45am', 'Three' ], + [ 'Mouse', 'Cheese', '9:05am', 'Four' ] +]; + +data2[1][0] = '{red-fg}' + data2[1][0] + '{/red-fg}'; +data2[2][0] += ' (' + DU + JUAN + ')'; + +screen.key('q', function() { + return screen.destroy(); +}); + +table.setData(data2); +screen.append(table); +screen.render(); + +setTimeout(function() { + table.setData(data1); + screen.render(); +}, 3000); diff --git a/blessed/blessed.d.ts b/blessed/blessed.d.ts index 6746afe5f5..cb9bd393ed 100644 --- a/blessed/blessed.d.ts +++ b/blessed/blessed.d.ts @@ -1,1256 +1,155 @@ -// Type definitions for blessed 0.1.5 +// Type definitions for blessed 0.1.81 // Project: https://github.com/chjj/blessed -// Definitions by: bryn austin bellomy +// Definitions by: bryn austin bellomy , Diullei Gomes // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// -declare module "blessed" -{ - import events = require('events'); - import buffer = require('buffer'); - import child_process = require('child_process'); +declare module "blessed" { + import {EventEmitter} from 'events'; + import * as stream from "stream" + import * as child_process from "child_process"; - module Blessed - { - export var colors: Colors; + export class BlessedProgram { + hideCursor: () => void; + move: any; + showCursor: any; + } - export interface GenericCallback { - (...args:any[]): void; + export module Widgets { + + export module Types { + + export type TTopLeft = string | number | "center"; + + export type TPosition = string | number; + + export type TMouseAction = "mousedown" | "mouseup" | "mousemove"; + + export type TStyle = { + type?: string; + bg?: string; + fg?: string; + ch?: string; + bold?: boolean; + underline?: boolean; + blink?: boolean; + inverse?: boolean; + invisible?: boolean; + transparent?: boolean; + border?: "line" | "bg" | TBorder; + hover?: boolean; + focus?: boolean; + label?: string; + track?: {bg?: string; fg?: string;}; + scrollbar?: {bg?: string; fg?: string;}; + } + + export type TBorder = { + /** + * Type of border (line or bg). bg by default. + */ + type?: "line" | "bg"; + /** + * Character to use if bg type, default is space. + */ + ch?: string; + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg?: number; + fg?: number; + /** + * Border attributes. + */ + bold?: string; + underline?: string; + } + + export type TCursor = { + /** + * Have blessed draw a custom cursor and hide the terminal cursor (experimental). + */ + artificial: boolean; + /** + * Shape of the cursor. Can be: block, underline, or line. + */ + shape: boolean; + /** + * Whether the cursor blinks. + */ + blink: boolean; + /** + * Color of the color. Accepts any valid color value (null is default). + */ + color: string; + } + + export type TAlign = "left" | "center" | "right"; + + export type ListbarCommand = { + key: string; + callback: () => void; + }; + + export type TImage = { + /** + * Pixel width. + */ + width: number; + /** + * Pixel height. + */ + height: number; + /** + * Image bitmap. + * */ + bmp: any; + /** + * Image cellmap (bitmap scaled down to cell size). + */ + cellmap: any; + }; + + export type Cursor = { + /** + * Have blessed draw a custom cursor and hide the terminal cursor (experimental). + */ + artificial: boolean; + /** + * Shape of the cursor. Can be: block, underline, or line. + */ + shape: boolean; + /** + * Whether the cursor blinks. + */ + blink: boolean; + /** + * Color of the color. Accepts any valid color value (null is default). + */ + color: string; + } } - export interface ColorPair { - /** background, must be number (-1 for default). */ - bg?: number; - /** foreground, must be number (-1 for default). */ - fg?: number; - } - - export interface Style extends ColorPair { - bold?: boolean; - underline?: boolean; - border: Border; - hover: ColorPair; - } - - export interface Border extends ColorPair { - /** type of border ('line' or 'bg'). */ - type?: string; //'line'|'bg'; - /** character to use if bg type, default is space. */ - ch?: string; - } - - export interface Padding { - top?:number; - right?:number; - bottom?:number; - left?:number; - } - - export interface Position { - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - top?:number|string; - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - right?:number|string; - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - bottom?:number|string; - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - left?:number|string; - /** width of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - width?:number|string; - /** height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - height?:number|string; - } - - export interface KeyCode { - name: string; - ctrl: boolean; - meta: boolean; - shift: boolean; - sequence: string; - full: string; - } - - export class Program - { - /** - Wrap the given text in terminal formatting codes corresponding to the given attribute - name. The `attr` string can be of the form `red fg` or `52 bg` where `52` is a 0-255 - integer color number. - */ - text (text:string, attr:string): string; - } - - export interface Colors { - /** Either pass a hex string, an array of 3 numbers, or three separate numbers representing an RGB value. This returns the 0-255 color number for that color. */ - match (r:string|number[]|number, g?:number, b?:number): number; - - /** An array of the 255 colors as hex strings. */ - colors: string[]; - } - - export interface NodeOptions - { - screen?: Screen; - parent?: Node; - children?: Node[]; - } - - export class Node extends events.EventEmitter - { - constructor(options?:NodeOptions); - - type : string; - options : NodeOptions; - parent : Node; - screen : Screen; - children : Node[]; - data : any; - _ : any; - $ : any; - index : number; - - // on(event:string, callback:() => void); - // on(event:'adopt', callback:() => void); - // on(event:'remove', callback:() => void); - // on(event:'reparent', callback:() => void); - // on(event:'attach', callback:() => void); - // on(event:'detach', callback:() => void); - - prepend(node:Node): void; - append(node:Node): void; - remove(node:Node): void; - insert(node:Node, index:number): void; - insertBefore(node:Node, refNode:Node): void; - insertAfter(node:Node, refNode:Node): void; - detach(): void; - // emitDescendants(): void; - // get(key:string): any; - // get(key:string, default:any): any; - // set(key:string, value:any): void; - } - - export interface ScreenOptions extends NodeOptions - { - /** the blessed Program to be associated with. will be automatically instantiated if none is provided. */ - program?: any; - /** attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with uniform cells to their sides). this is known to cause flickering with elements that are not full-width, however, it is more optimal for terminal rendering. */ - smartCSR?: boolean; - /** do CSR on any element within 20 cols of the screen edge on either side. faster than smartCSR, but may cause flickering depending on what is on each side of the element. */ - fastCSR?: boolean; - /** attempt to perform back_color_erase optimizations for terminals that support it. it will also work with terminals that don't support it, but only on lines with the default background color. as it stands with the current implementation, it's uncertain how much terminal performance this adds at the cost of overhead within node. */ - useBCE?: boolean; - /** amount of time (in ms) to redraw the screen after the terminal is resized (default: 300). */ - resizeTimeout?: number; - /** the width of tabs within an element's content. */ - tabSize?: number; - /** automatically position child elements with border and padding in mind. */ - autoPadding?: boolean; - /** the name of the logfile to use. if specified but the file does not exist, it will be created. see log method. */ - log?: string; - /** dump all output and input to desired file. can be used together with log option if set as a boolean. */ - dump?: any; - /** debug mode. enables usage of the `debug` method. also creates a debug console which will display when pressing F12. it will display all log and debug messages. */ - debug?: boolean; - /** Array of keys in their full format (e.g. C-c) to ignore when keys are locked. Useful for creating a key that will always exit no matter whether the keys are locked. */ - ignoreLocked?: string[]; - - /** Do not clear the screen, only scroll down enough to make room for the elements on the screen. do not use the alternate screenbuffer. useful for writing a CLI tool or some kind of prompt (experimental - see test/widget-noalt.js) */ - noAlt?: boolean; - - /** Options for the cursor. */ - cursor?: CursorOptions; - } - - export interface CursorOptions { - /** have blessed draw a custom cursor and hide the terminal cursor (experimental). */ - artificial?: boolean; - /** shape of the artificial cursor. can be: block, underline, or line. */ - shape?: string; //'block'|'underline'|'line'; - /** whether the artificial cursor blinks. */ - blink?: boolean; - /** color of the artificial cursor. accepts any valid color value (null is default). */ - color?: string; - } - - export interface ScreenEventCallback { - (character:string, keyCode:KeyCode): void; - } - - export class Screen extends Node - { - constructor(options?:ScreenOptions); - - /** the blessed Program object. */ - program: any; - /** the blessed Tput object (only available if you passed tput: true to the Program constructor.) */ - tput: any; - /** top of the focus history stack. */ - focused: any; - /** width of the screen (same as program.cols). */ - width: number; - /** height of the screen (same as program.rows). */ - height: number; - /** same as screen.width. */ - cols: number; - /** same as screen.height. */ - rows: number; - - /** calculated relative left offset. */ - left: number; - /** calculated relative right offset. */ - right: number; - /** calculated relative top offset. */ - top: number; - /** calculated relative bottom offset. */ - bottom: number; - /** calculated absolute left offset. */ - aleft: number; - /** calculated absolute right offset. */ - aright: number; - /** calculated absolute top offset. */ - atop: number; - /** calculated absolute bottom offset. */ - abottom: number; - - - /** whether the focused element grabs all keypresses. */ - grabKeys: boolean; - /** prevent keypresses from being received by any element. */ - lockKeys: boolean; - /** the currently hovered element. only set if mouse events are bound. */ - hover: Element; - /** set or get window title. */ - title: string; - - /** write string to the log file if one was created. */ - log(...msg:any[]): void; - /** same as the log method, but only gets called if the debug option was set. */ - debug(...msg:string[]): void; - /** allocate a new pending screen buffer and a new output screen buffer. */ - alloc(): void; - /** draw the screen based on the contents of the screen buffer. */ - draw(start:number, end:number): void; - /** render all child elements, writing all data to the screen buffer and drawing the screen. */ - render(): void; - /** clear any region on the screen. */ - clearRegion(x1:number, x2:number, y1:number, y2:number): void; - /** fill any region with a character of a certain attribute. */ - fillRegion(attr:number, ch:string, x1:number, x2:number, y1:number, y2:number): void; - /** focus element by offset of focusable elements. */ - focusOffset(offset:number): void; - /** focus previous element in the index. */ - focusPrevious(): void; - /** focus next element in the index. */ - focusNext(): void; - /** push element on the focus stack (equivalent to screen.focused = el). */ - focusPush(element:Element): void; - /** pop element off the focus stack. */ - focusPop(): void; - /** save the focused element. */ - saveFocus(): void; - /** restore the saved focused element. */ - restoreFocus(): void; - /** "rewind" focus to the last visible and attached element. */ - rewindFocus(): void; - /** bind a keypress listener for a specific key. */ - key(keyEvents:string|string[], callback:ScreenEventCallback): void; - /** bind a keypress listener for a specific key once. */ - onceKey(keyEvents:string|string[], callback:ScreenEventCallback): void; - /** remove a keypress listener for a specific key. */ - unkey(name:string, listener:ScreenEventCallback): void; - /** spawn a process in the foreground, return to blessed app after exit. */ - spawn(file:string, args:string[], options:NodeChildProcessExecOptions): child_process.ChildProcess; - /** spawn a process in the foreground, return to blessed app after exit. executes callback on error or exit. */ - exec(file:string, args:string[], options:NodeChildProcessExecOptions, callback:GenericCallback): child_process.ChildProcess; - /** read data from text editor. */ - readEditor(options:{}, callback:GenericCallback): void; - /** set effects based on two events and attributes. */ - setEffects(el:Element, fel:Element, over:string, out:string, effects:Style, temp?:string): void; - /** insert a line into the screen (using csr: this bypasses the output buffer). */ - insertLine(n:number, y:number, top:number, bottom:number): void; - /** delete a line from the screen (using csr: this bypasses the output buffer). */ - deleteLine(n:number, y:number, top:number, bottom:number): void; - /** insert a line at the bottom of the screen. */ - insertBottom(top:number, bottom:number): void; - /** insert a line at the top of the screen. */ - insertTop(top:number, bottom:number): void; - /** delete a line at the bottom of the screen. */ - deleteBottom(top:number, bottom:number): void; - /** delete a line at the top of the screen. */ - deleteTop(top:number, bottom:number): void; - - /** enable mouse events for the screen and optionally an element (automatically called when a form of on('mouse') is bound). */ - enableMouse(el?:Element): void; - /** enable keypress events for the screen and optionally an element (automatically called when a form of on('keypress') is bound). */ - enableKeys(el?:Element): void; - /** enable key and mouse events. calls bot enableMouse and enableKeys. */ - enableInput(el?:Element): void; - - /** attempt to copy text to clipboard using iTerm2's propriety sequence. returns true if successful. */ - copyToClipboard(text:string): boolean; - /** attempt to change cursor shape. will not work in all terminals (see artificial cursors for a solution to this). returns true if successful. */ - cursorShape(shape:string, blink:boolean): boolean; - /** attempt to change cursor color. returns true if successful. */ - cursorColor(color: string): boolean; - /** attempt to reset cursor. returns true if successful. */ - cursorReset(): boolean; - - } - - export interface ElementOptions extends NodeOptions - { - fg?: string; - bg?: string; - scrollbar?: ColorPair; - focus?: Style; - hover?: Style; - - /** border object, see below. */ - border?: Border; - /** positioning options. */ - position?: Position; - /** amount of padding on the inside of the element. can be a number or an object containing the properties: left, right, top, and bottom. */ - padding?: number|Padding; - /** element's text content. */ - content?: string; - /** element is clickable. */ - clickable?: boolean; - /** element is focusable and can receive key input. */ - input?: boolean; - /** element is focused. */ - focused?: boolean; - /** whether the element is hidden. */ - hidden?: boolean; - /** a simple text label for the element. */ - label?: string; - /** a floating text label for the element which appears on mouseover. */ - hoverText?: string; - /** text alignment: left, center, or right. */ - align?: string; - /** vertical text alignment: top, middle, or bottom. */ - valign?: string; - /** shrink/flex/grow to content and child elements. width/height during render. */ - shrink?: any; - /** width of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - width?: number|string; - /** height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - height?: number|string; - /** whether the element is scrollable or not. */ - scrollable?: boolean; - /** background character (default is whitespace ). */ - ch?: string; - /** allow the element to be dragged with the mouse. */ - draggable?: boolean; - } - - export class Element extends Node - { - constructor(options?:ElementOptions); - - /** name of the element. useful for form submission. */ - name: string; - /** border object. */ - border: Border; - /** contains attributes (e.g. fg/bg/underline). see above. */ - style: Style; - /** raw width, height, and offsets. */ - position: Position; - /** type of border (line or bg). bg by default. */ - type: string; //'line'|'bg'; - /** character to use if bg type, default is space. */ - ch: string; - /** raw text content. */ - content: string; - /** whether the element is hidden or not. */ - hidden: boolean; - /** whether the element is visible or not. */ - visible: boolean; - /** whether the element is attached to a screen in its ancestry somewhere. */ - detached: boolean; - /** calculated width. */ - width: number; - /** calculated height. */ - height: number; - /** whether the element is draggable. set to true to allow dragging. */ - draggable: boolean; - - - - /** calculated relative left offset. */ - left: number; - /** calculated relative right offset. */ - right: number; - /** calculated relative top offset. */ - top: number; - /** calculated relative bottom offset. */ - bottom: number; - /** calculated absolute left offset. */ - aleft: number; - /** calculated absolute right offset. */ - aright: number; - /** calculated absolute top offset. */ - atop: number; - /** calculated absolute bottom offset. */ - abottom: number; - - - /** write content and children to the screen buffer. */ - render(): void; - /** hide element. */ - hide(): void; - /** show element. */ - show(): void; - /** toggle hidden/shown. */ - toggle(): void; - /** focus element. */ - focus(): void; - /** bind a keypress listener for a specific key. */ - key(name:string|string[], listener:(character?:any, keyCode?:any) => void): void; - /** bind a keypress listener for a specific key once. */ - onceKey(name:string, listener:() => void): void; - /** remove a keypress listener for a specific key. */ - unkey(name:string, listener:() => void): void; - /** same as el.on('screen', ...) except this will automatically cleanup listeners after the element is detached. */ - onScreenEvent(event:string, listener:(...args:any[]) => void): void; - /** set the z-index of the element (changes rendering order). */ - setIndex(z:number): void; - /** put the element in front of its siblings. */ - setFront(): void; - /** put the element in back of its siblings. */ - setBack(): void; - /** set the label text for the top-left corner. example options: {text:'foo',side:'left'} */ - setLabel(textOrOptions:string|{}): void; - /** remove the label completely. */ - removeLabel(): void; - /** set the hover text for the bottom-right corner. example options: {text:'foo'} */ - setHover(textOrOptions:string|{}): void; - /** remove the hover label completely. */ - removeHover(): void; - /** set the content. note: when text is input, it will be stripped of all non-SGR escape codes, tabs will be replaced with 8 spaces, and tags will be replaced with SGR codes (if enabled). */ - setContent(text:string): void; - /** return content, slightly different from el.content. assume the above formatting. */ - getContent(): void; - /** similar to setContent, but ignore tags and remove escape codes. */ - setText(text:string): void; - /** similar to getContent, but return content with tags and escape codes removed. */ - getText(): void; - /** insert a line into the box's content. */ - insertLine(index:number, lines:string|string[]): void; - /** delete a line from the box's content. */ - deleteLine(index:number, numLines:number): void; - /** get a line from the box's content. */ - getLine(index:number): void; - /** get a line from the box's content from the visible top. */ - getBaseLine(index:number): void; - /** set a line in the box's content. */ - setLine(index:number, line:string): void; - /** set a line in the box's content from the visible top. */ - setBaseLine(index:number, line:string): void; - /** clear a line from the box's content. */ - clearLine(index:number): void; - /** clear a line from the box's content from the visible top. */ - clearBaseLine(index:number): void; - /** insert a line at the top of the box. */ - insertTop(lines:string|string[]): void; - /** insert a line at the bottom of the box. */ - insertBottom(lines:string|string[]): void; - /** delete a line at the top of the box. */ - deleteTop(): void; - /** delete a line at the bottom of the box. */ - deleteBottom(): void; - /** unshift a line onto the top of the content. */ - unshiftLine(lines:string|string[]): void; - /** shift a line off the top of the content. */ - shiftLine(index:number): void; - /** push a line onto the bottom of the content. */ - pushLine(lines:string|string[]): void; - /** pop a line off the bottom of the content. */ - popLine(index:number): void; - /** an array containing the content lines. */ - getLines(): void; - /** an array containing the lines as they are displayed on the screen. */ - getScreenLines(): void; - /** get a string's real length, taking into account tags. */ - textLength(text:string): number; - - /** enable dragging of the element. */ - enableDrag(): void; - /** disable dragging of the element. */ - disableDrag(): void; - } - - - // - // Box - // - - export interface BoxOptions extends ElementOptions { - // intentionally empty - } - - export class Box extends Element { - constructor(options?:BoxOptions); - // intentionally empty - } - - - // - // ScrollableBox - // - - export interface ScrollableBoxOptions extends BoxOptions { - /** a limit to the childBase. default is `Infinity`. */ - baseLimit: number; - /** a option which causes the ignoring of `childOffset`. this in turn causes the childBase to change every time the element is scrolled. */ - alwaysScroll: boolean; - /** object enabling a scrollbar. */ - scrollbar: ScrollBar; - } - - /** A box with scrollable content. */ - export class ScrollableBox extends Box { - constructor(options?:ScrollableBoxOptions); - - /** the offset of the top of the scroll content. */ - childBase: number; - /** the offset of the chosen item/line. */ - childOffset: number; - /** scroll the content by a relative offset. */ - scroll(offset:number): void; - /** scroll the content to an absolute index. */ - scrollTo(index:number): void; - /** same as `scrollTo`. */ - setScroll(index:number): void; - /** set the current scroll index in percentage (0-100). */ - setScrollPerc(perc:number): void; - /** get the current scroll index in lines. */ - getScroll(): number; - /** get the actual height of the scrolling area. */ - getScrollHeight(): number; - /** get the current scroll index in percentage. */ - getScrollPerc(): number; - /** reset the scroll index to its initial state. */ - resetScroll(): void; - - } - - export interface ScrollBar { - /** style of the scrollbar. */ - style: Style; - /** style of the scrollbar track if present (takes regular style options). */ - track: Style; - } - - - // - // ScrollableText - // - - export interface ScrollableTextOptions extends ScrollableBoxOptions { - /** whether to enable automatic mouse support for this element. */ - mouse: boolean; - /** use predefined keys for navigating the text. */ - keys: boolean; - /** use vi keys with the `keys` option. */ - vi: boolean; - } - - /** __DEPRECATED__ - Use Box with the `scrollable` and `alwaysScroll` options instead. A scrollable text box which can display and scroll text, as well as handle pre-existing newlines and escape codes. */ - export class ScrollableText extends ScrollableBox { - constructor(options?:ScrollableTextOptions); - } - - - - // - // Text - // - - export interface TextOptions extends ElementOptions { - align?: string; //'left'|'center'|'right'; - } - - export class Text extends Element { - constructor(options?:TextOptions); - // intentionally empty - } - - - // - // Line - // - - export interface LineOptions extends BoxOptions { - orientation?: string; //'vertical'|'horizontal'; - style?: Style; - } - - export class Line extends Box { - constructor(options?:LineOptions); - // intentionally empty - } - - - // - // List - // - - export interface ListStyle extends Style { - selected?: Style; - item?: Style; - } - - export interface ListOptions extends BoxOptions - { - style?: ListStyle; - - /** whether to automatically enable mouse support for this list (allows clicking items). */ - mouse?: boolean; - /** use predefined keys for navigating the list. */ - keys?: any; - /** use vi keys with the keys option. */ - vi?: boolean; - /** an array of strings which become the list's items. */ - items?: string[]; - /** a function that is called when vi mode is enabled and the key / is pressed. This function accepts a callback function which should be called with the search string. The search string is then used to jump to an item that is found in items. */ - search?: (callback:(searchString:string) => void) => void; - /** whether the list is interactive and can have items selected (default: true). */ - interactive?: boolean; - } - - export class List extends Box - { - constructor(options?:ListOptions); - - /** The text of the currently selected item. */ - value:string; - /** The items in the list. */ - items:string[]; - /** The items in the list. */ - ritems:string[]; - /** The index of the current selection. */ - selected:number; - - /** add an item based on a string. */ - addItem(text:string): void; - /** returns the item index from the list. child can be an element, index, or string. */ - getItemIndex(child:Element|number|string): void; - /** returns the item element. child can be an element, index, or string. */ - getItem(child:Element|number|string): void; - /** removes an item from the list. child can be an element, index, or string. */ - removeItem(child:Element|number|string): void; - /** clears all items from the list. */ - clearItems(): void; - /** sets the list items to multiple strings. */ - setItems(items:string[]): void; - /** Sets the current selection by absolute index. */ - select(index:number): void; - /** Changes the current selection based on current offset. */ - move(offset:number): void; - /** select item above selected. */ - up(amount:number): void; - /** select item below selected. */ - down(amount:number): void; - /** show/focus list and pick an item. the callback is executed with the result. */ - pick(cwd:string, callback:(err:any, file:string) => void): void; - - /** show/focus list and pick an item. the callback is executed with the result. */ - pick(callback:(err:any, file:string) => void): void; - } - - // - // Input - // - - export interface InputOptions extends BoxOptions { - // intentionally empty - } - - export class Input extends Box { - constructor(options?:InputOptions); - // intentionally empty - } - - export interface InputOptions extends BoxOptions { - // intentionally empty - } - - // - // Textarea - // - - export interface TextareaOptions extends InputOptions - { - /** use pre-defined keys (`i` or `enter` for insert, `e` for editor, `C-e` for editor while inserting). */ - keys?: boolean; - /** use pre-defined mouse events (right-click for editor). */ - mouse?: boolean; - /** call `readInput()` when the element is focused. automatically unfocus. */ - inputOnFocus?: boolean; - } - - /** A box which allows multiline text input. */ - export class Textarea extends Input - { - constructor(options?:TextareaOptions); - - /** the input text. __read-only__. */ - value: string; - - /** submit the textarea (emits `submit`). */ - submit(): void; - /** cancel the textarea (emits `cancel`). */ - cancel(): void; - /** grab key events and start reading text from the keyboard. takes a callback which receives the final value. */ - readInput(callback:GenericCallback): void; - /** open text editor in `$EDITOR`, read the output from the resulting file. takes a callback which receives the final value. */ - readEditor(callback:GenericCallback): void; - /** the same as `this.value`, for now. */ - getValue(): string; - /** clear input. */ - clearValue(): void; - /** set value. */ - setValue(text:string): void; - } - - - // - // Textbox - // - - export interface TextboxOptions extends TextareaOptions { - /** completely hide text. */ - secret?: boolean; - /** replace text with asterisks (`*`). */ - censor?: boolean; - } - - /** A box which allows text input. */ - export class Textbox extends Textarea { - constructor(options?:TextboxOptions); - - /** completely hide text. */ - secret: boolean; - /** replace text with asterisks (`*`). */ - censor: boolean; - } - - - // - // Button - // - - export interface ButtonOptions extends InputOptions { - } - - /** A button which can be focused and allows key and mouse input. */ - export class Button extends Input { - constructor(options?:ButtonOptions); - - // on(event:string, callback:() => void): void; - // on(event:'press', callback:() => void); - - /** press button. emits 'press'. */ - press(): void; - } - - - // - // ProgressBar - // - - export interface ProgressBarOptions extends InputOptions { - /** can be `horizontal` or `vertical`. */ - orientation: string; - /** the character to fill the bar with (default is space). */ - pch: string; - /** the amount filled (0 - 100). */ - filled: number; - /** same as `filled`. */ - value: number; - /** enable key support. */ - keys: boolean; - /** enable mouse support. */ - mouse: boolean; - - /** contains the extra key 'bar', which defines the style of the bar contents itself. */ - style: ProgressBarStyle; - } - - export interface ProgressBarStyle extends Style { - /** style of the bar contents itself. */ - bar: Style; - } - - - export class ProgressBar extends Input { - constructor(options?:ProgressBarOptions); - - /** progress the bar by a fill amount. */ - progress(amount:number): void; - /** set progress to specific amount. */ - setProgress(amount:number): void; - /** reset the bar. */ - reset(): void; - } - - // - // Checkbox - // - - export interface CheckboxOptions extends InputOptions { - /** whether the element is checked or not. */ - checked: boolean; - /** enable mouse support. */ - mouse: boolean; + export module Events { + + export interface IMouseEventArg { + x: number; + y: number; + action: Types.TMouseAction; + } + + export interface IKeyEventArg { + full: string; + name: string; + shift: boolean; + ctrl: boolean; + meta: boolean; + sequence: string; + } } - - /** A checkbox which can be used in a form element. */ - export class Checkbox extends Input - { - constructor(options?:CheckboxOptions); - - /** the text next to the checkbox (do not use setcontent, use `check.text = ''`). */ - text: string; - /** whether the element is checked or not. */ - checked: boolean; - /** same as `checked`. */ - value: boolean; - - /** check the element. */ - check(): void; - /** uncheck the element. */ - uncheck(): void; - /** toggle checked state. */ - toggle(): void; - } - - - // - // RadioSet - // - - export interface RadioSetOptions extends BoxOptions { - } - - - export class RadioSet extends Box { - constructor(options?:RadioSetOptions); - } - - - // - // RadioButton - // - - export interface RadioButtonOptions extends CheckboxOptions { - } - - - /** A radio button which can be used in a form element. */ - export class RadioButton extends Checkbox { - constructor(options?:RadioButtonOptions); - } - - - - // - // Prompt - // - - export interface PromptOptions extends BoxOptions { - } - - - /** A prompt box containing a text input, okay, and cancel buttons (automatically hidden). */ - export class Prompt extends Box - { - constructor(options?:PromptOptions); - - /** show the prompt and wait for the result of the textbox. set text and initial value */ - input(text:string, value:any, callback:(val:any) => void): void; - /** show the prompt and wait for the result of the textbox. set text and initial value */ - setInput(text:string, value:any, callback:(val:any) => void): void; - /** show the prompt and wait for the result of the textbox. set text and initial value */ - readInput(text:string, value:any, callback:(val:any) => void): void; - } - - - // - // Question - // - - export interface QuestionOptions extends BoxOptions { - } - - - /** A question box containing okay and cancel buttons (automatically hidden). */ - export class Question extends Box - { - constructor(options?:QuestionOptions); - - /** ask a `question`. `callback` will yield the result. */ - ask(question:string, callback:(result:any) => void): void; - } - - - // - // Message - // - - export interface MessageOptions extends BoxOptions { - } - - - /** A box containing a message to be displayed (automatically hidden). */ - export class Message extends Box - { - constructor(options?:MessageOptions); - - /** display a message for a time (default is 3 seconds). set time to 0 for a perpetual message that is dismissed on keypress. */ - log(text:string, timeOrCallback:number|MessageCallback, callback?:MessageCallback): void; - /** display a message for a time (default is 3 seconds). set time to 0 for a perpetual message that is dismissed on keypress. */ - display(text:string, timeOrCallback:number|MessageCallback, callback?:MessageCallback): void; - /** display an error in the same way. */ - error(text:string, timeOrCallback:number|MessageCallback, callback?:MessageCallback): void; - } - - export interface MessageCallback { - (): void; - } - - - // - // Loading - // - - export interface LoadingOptions extends BoxOptions { - } - - /** A box with a spinning line to denote loading (automatically hidden). */ - export class Loading extends Box - { - constructor(options?:LoadingOptions); - - /** display the loading box with a message. will lock keys until `stop` is called. */ - load(text:string): void; - /** hide loading box. unlock keys. */ - stop(): void; - } - - - // - // Listbar - // - - export interface ListbarOptions extends BoxOptions - { - /** Listbar's `style` object includes sub-styles for `selected` and `item`. */ - style?: ListbarStyle; - - /** set buttons using an object with keys as titles of buttons, containing of objects containing keys of `keys` and `callback`. */ - items?: ListbarItemSet; - /** set buttons using an object with keys as titles of buttons, containing of objects containing keys of `keys` and `callback`. */ - commands?: ListbarItemSet; - /** automatically bind list buttons to keys 0-9. */ - autoCommandKeys?: boolean; - } - - export interface ListbarItemSet { - [name: string]: ListbarItem; - } - - export interface ListbarItem { - keys: string[]; - callback: GenericCallback; - } - - export interface ListbarStyle extends Style - { - /** style for a selected item. */ - selected: Style; - /** style for an unselected item. */ - item: Style; - } - - /** A horizontal list. Useful for a main menu bar. */ - export class Listbar extends Box - { - constructor(options?:ListbarOptions); - - /** append an item to the bar. */ - add(item:ListbarItem, callback:GenericCallback): void; - /** append an item to the bar. */ - addItem(item:ListbarItem, callback:GenericCallback): void; - /** append an item to the bar. */ - appendItem(item:ListbarItem, callback:GenericCallback): void; - - /** select button and execute its callback. */ - selectTab(index: number): void; - - /** set commands (see `commands` option above). */ - setItems(commands: ListbarItemSet): void; - /** select an item on the bar. */ - select(offset: number): void; - /** remove item from the bar. */ - removeItem(child:ListbarItem): void; - /** move focus relatively across the bar. */ - move(offset: number): void; - /** move focus left relatively across the bar. */ - moveLeft(offset: number): void; - /** move focus right relatively across the bar. */ - moveRight(offset: number): void; - } - - - // - // Log - // - - export interface LogOptions extends ScrollableTextOptions { - /** amount of scrollback allowed. default: Infinity. */ - scrollback?: number; - /** scroll to bottom on input even if the user has scrolled up. default: false. */ - scrollOnInput?: boolean; - } - - - /** A log permanently scrolled to the bottom. */ - export class Log extends ScrollableText - { - constructor(options?:LogOptions); - - /** amount of scrollback allowed. default: Infinity. */ - scrollback: number; - /** scroll to bottom on input even if the user has scrolled up. default: false. */ - scrollOnInput: boolean; - - /** add a log line. */ - log(text:string): void; - /** add a log line. */ - add(text:string): void; - } - - - // - // Table - // - - export interface TableOptions extends BoxOptions - { - /** array of array of strings representing rows (same as `data`). */ - rows?: string[][]; - /** array of array of strings representing rows (same as `rows`). */ - data?: string[][]; - /** spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). */ - pad?: number; - /** do not draw inner cells. */ - noCellBorders?: boolean; - /** fill cell borders with the adjacent background color. */ - fillCellBorders?: boolean; - - /** includes `header` and `cell` substyles. */ - style?: TableStyle; - } - - export interface TableStyle extends Style { - /** header style. */ - header: Style; - /** cell style. */ - cell: Style; - } - - /** A stylized table of text elements. */ - export class Table extends Box - { - /** includes `header` and `cell` substyles. */ - style: TableStyle; - - /** set rows in table. array of arrays of strings. */ - setData(rows: string[][]): void; - /** set rows in table. array of arrays of strings. */ - setRows(rows: string[][]): void; - } - - - // - // ListTable - // - - export interface ListTableOptions extends ListOptions - { - /** array of array of strings representing rows (same as `data`). */ - rows?: string[][]; - /** array of array of strings representing rows (same as `rows`). */ - data?: string[][]; - /** spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). */ - pad?: number; - - /** do not draw inner cells. */ - noCellBorders?: boolean; - - /** includes `header` and `cell` substyles. */ - style?: TableStyle; - } - - export interface ListTableStyle extends TableStyle { - } - - - /** A stylized table of text elements with a list. */ - export class ListTable extends List - { - constructor(options?:ListTableOptions); - - /** set rows in table. array of arrays of strings. */ - setData(rows: string[][]): void; - /** set rows in table. array of arrays of strings. */ - setRows(rows: string[][]): void; - } - - // - // Image - // - - export interface ImageOptions extends BoxOptions { - /** path to image. */ - file: string; - /** path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. */ - w3m: string; - } - - - /** Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. X11 required: works in xterm, urxvt, and possibly other terminals. */ - export class Image extends Box - { - constructor(options?:ImageOptions); - - /** set the image in the box to a new path. */ - setImage (img:string, callback:GenericCallback): void; - /** clear the current image. */ - clearImage (callback:GenericCallback): void; - /** get the size of an image file in pixels. */ - imageSize (img:string, callback:GenericCallback): void; - /** get the size of the terminal in pixels. */ - termSize (callback:GenericCallback): void; - /** get the pixel to cell ratio for the terminal. */ - getPixelRatio (callback:GenericCallback): void; - } - - - // - // Form - // - - export interface FormOptions extends BoxOptions { - /** allow default keys (tab, vi keys, enter). */ - keys?:boolean; - /** allow vi keys. */ - vi?:boolean; - } - - export class Form extends Box - { - constructor(options?:FormOptions); - - /** last submitted data. */ - submission: any; - - // on(event:string, callback:() => void): void; - // on(event:'submit', callback:(data) => void): void; - // on(event:'cancel', callback:() => void): void; - // on(event:'reset', callback:() => void): void; - - next(): void; - previous(): void; - - resetSelected(): void; - /** focus first form element. */ - focusFirst(): void; - /** focus last form element. */ - focusLast(): void; - /** focus next form element. */ - focusNext(): void; - /** focus previous form element. */ - focusPrevious(): void; - /** submit the form. */ - submit(): void; - /** discard the form. */ - cancel(): void; - /** clear the form. */ - reset(): void; - } - - - // - // FileManager - // - - export interface FileManagerOptions extends ListOptions { - cwd?: string; - } - - export interface DirectoryEntry { - name: string; - text: string; - dir: boolean; - symlink: boolean; - } - - export class FileManager extends List - { - constructor(options?:FileManagerOptions); - - cwd: string; - - useFormatter (formatterFn:(entry:DirectoryEntry) => DirectoryEntry): void; - - /** refresh the file list (perform a readdir on cwd and update the list items). */ - refresh (cwd?:string, callback?:() => void): void; - - /** refresh the file list. */ - refresh (callback?:() => void): void; - - /** reset back to original cwd. */ - reset (cwd?:string, callback?:() => void): void; - } - - - // - // Terminal - // - - export interface TerminalOptions extends BoxOptions - { - /** handler for input data. */ - handler?: (userInput:Buffer) => void; - /** name of shell. $SHELL by default. */ - shell?:string; - /** args for shell. */ - args?:any; - /** can be line, underline, and block. */ - cursor?:string; //'line'|'underline'|'block'; - } - - export class Terminal extends Box - { - /** reference to the headless term.js terminal. */ - term: any; - /** reference to the pty.js pseudo terminal. */ - pty: any; - - /** write data to the terminal. */ - write(data:string): void; - - /** nearly identical to `element.screenshot`, however, the specified region includes the terminal's _entire_ scrollback, rather than just what is visible on the screen. */ - screenshot(xi?:number, xl?:number, yi?:number, yl?:number): string; - } - - - export interface NodeChildProcessExecOptions - { + export interface NodeChildProcessExecOptions { cwd?: string; stdio?: any; customFds?: any; @@ -1260,10 +159,2676 @@ declare module "blessed" maxBuffer?: number; killSignal?: string; } + + export interface IDestroyable { + destroy(): void; + } + + export interface IOptions { + } + + export interface IHasOptions { + options: T; + } + + export interface TputsOptions extends IOptions { + terminal?: string; + extended?: boolean; + debug?: boolean; + termcap?: string; + terminfoFile?: string; + terminfoPrefix?: string; + termcapFile?: string; + } + + export class Tput implements IHasOptions { + constructor(opts: TputsOptions); + + // ** properties ** // + + /** + * Original options object. + */ + options: TputsOptions; + + debug: boolean; + padding: boolean; + extended: boolean; + printf: boolean; + termcap: string; + terminfoPrefix: string; + terminfoFile: string; + termcapFile: string; + error: Error; + terminal: string; + + setup(): void; + term(is: any): boolean; + readTerminfo(term: string): string; + parseTerminfo(data: any, file: string): { + header: { + dataSize: number; + headerSize: number; + magicNumber: boolean; + namesSize: number; + boolCount: number; + numCount: number; + strCount: number; + strTableSize: number; + extended: { + dataSize: number; + headerSize: number; + boolCount: number; + numCount: number; + strCount: number; + strTableSize: number; + lastStrTableOffset: number; + } + } + name: string; + names: string[]; + desc: string; + bools: Object; + numbers: Object; + strings: Object; + }; + } + + export interface IDestroyable { + destroy(): void; + } + + export interface INodeOptions extends IOptions { + name?: string; + screen?: Screen; + parent?: Node; + children?: Node[]; + focusable?: boolean; + } + + export abstract class Node extends EventEmitter implements IHasOptions, IDestroyable { + constructor(options: INodeOptions); + + // ** properties ** // + + focusable: boolean; + + /** + * Original options object. + */ + options: INodeOptions; + + /** + * An object for any miscellanous user data. + */ + data: {[index: string]: any;}; + /** + * An object for any miscellanous user data. + */ + _: {[index: string]: any;}; + /** + * An object for any miscellanous user data. + */ + $: {[index: string]: any;}; + /** + * Type of the node (e.g. box). + */ + type: string; + /** + * Render index (document order index) of the last render call. + */ + index: number; + /** + * Parent screen. + */ + screen: Screen; + /** + * Parent node. + */ + parent: Node; + /** + * Array of node's children. + */ + children: Node[]; + + // ** methods ** // + + /** + * Prepend a node to this node's children. + */ + prepend(node: Node): void; + /** + * Append a node to this node's children. + */ + append(node: Node): void; + /** + * Remove child node from node. + */ + remove(node: Node): void; + /** + * Insert a node to this node's children at index i. + */ + insert(node: Node, index: number): void; + /** + * Insert a node to this node's children before the reference node. + */ + insertBefore(node: Node, refNode: Node): void; + /** + * Insert a node from node after the reference node. + */ + insertAfter(node: Node, refNode: Node): void; + /** + * Remove node from its parent. + */ + detach(): void; + /** + * Remove node from its parent. + */ + free(): void; + /** + * Remove node from its parent. + */ + forDescendants(iter: Function, s: any): void; + /** + * Remove node from its parent. + */ + forAncestors(iter: Function, s: any): void; + /** + * Remove node from its parent. + */ + collectDescendants(s: any): void; + /** + * Remove node from its parent. + */ + collectAncestors(s: any): void; + /** + * Remove node from its parent. + */ + emitDescendants(): void; + /** + * Remove node from its parent. + */ + emitAncestors(): void; + /** + * Remove node from its parent. + */ + hasDescendant(target: Node): void; + /** + * Remove node from its parent. + */ + hasAncestor(target: Node): boolean; + /** + * Remove node from its parent. + */ + destroy(): void; + /** + * Emit event for element, and recursively emit same event for all descendants. + */ + emitDescendants(type: string, ...args: any[]): void; + /** + * Get user property with a potential default value. + */ + get(name: string, def: T): T; + /** + * Set user property to value. + */ + set(name: string, value: T): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received when node is added to a parent. + */ + on(event: "adopt", callback: (arg: Node) => void): this; + /** + * Received when node is removed from it's current parent. + */ + on(event: "remove", callback: (arg: Node) => void): this; + /** + * Received when node gains a new parent. + */ + on(event: "reparent", callback: (arg: Node) => void): this; + /** + * Received when node is attached to the screen directly or somewhere in its ancestry. + */ + on(event: "attach", callback: (arg: Node) => void): this; + /** + * Received when node is detached from the screen directly or somewhere in its ancestry. + */ + on(event: "detach", callback: (arg: Node) => void): this; + } + + export class NodeWithEvents extends Node { + // ** methods ** // + + /** + * Bind a keypress listener for a specific key. + */ + key(name: string | string[], listener: Function): void; + /** + * Bind a keypress listener for a specific key once. + */ + onceKey(name: string, listener: Function): void; + /** + * Remove a keypress listener for a specific key. + */ + unkey(name: string, listener: Function): void; + removeKey(name: string, listener: Function): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received on screen resize. + */ + on(event: "resize", callback: () => void): this; + /** + * Received on mouse events. + */ + on(event: "mouse", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mouseout", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mouseover", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mousedown", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mouseup", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mousewheel", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "wheeldown", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "wheelup", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mousemove", callback: (arg: Events.IMouseEventArg) => void): this; + /** + * Received on key events. + */ + on(event: "keypress", callback: (ch: string, key: Events.IKeyEventArg) => void): this; + /** + * Global events received for all elements. + */ + on(event: "element click", callback: (arg: Screen) => void): this; + on(event: "element mouseover", callback: (arg: Screen) => void): this; + on(event: "element mouseout", callback: (arg: Screen) => void): this; + on(event: "element mouseup", callback: (arg: Screen) => void): this; + /** + * Received on key event for [name]. + */ + //on(event: "key", callback: (arg: BlessedScreen) => void): this; + /** + * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * focus protocol and focus needs to be passed to program.enableMouse(). + */ + on(event: "focus", callback: (arg: Screen) => void): this; + /** + * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * focus protocol and focus needs to be passed to program.enableMouse(). + */ + on(event: "blur", callback: (arg: Screen) => void): this; + /** + * Received before render. + */ + on(event: "prerender", callback: () => void): this; + /** + * Received on render. + */ + on(event: "render", callback: () => void): this; + /** + * Received when blessed notices something untoward (output is not a tty, terminfo not found, etc). + */ + on(event: "warning", callback: (text: string) => void): this; + /** + * Received when the screen is destroyed (only useful when using multiple screens). + */ + on(event: "destroy", callback: () => void): this; + /** + * Received when the element is moved. + */ + on(event: "move", callback: () => void): this; + /** + * Element was clicked (slightly smarter than mouseup). + */ + on(event: "click", callback: (arg: Screen) => void): this; + /** + * Received when element is shown. + */ + on(event: "show", callback: () => void): this; + /** + * Received when element becomes hidden. + */ + on(event: "hide", callback: () => void): this; + + on(event: "set content", callback: () => void): this; + on(event: "parsed content", callback: () => void): this; + } + + export interface IScreenOptions extends INodeOptions { + /** + * The blessed Program to be associated with. Will be automatically instantiated if none is provided. + */ + program?: BlessedProgram; + /** + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * however, it is more optimal for terminal rendering. + */ + smartCSR?: boolean; + /** + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * but may cause flickering depending on what is on each side of the element. + */ + fastCSR?: boolean; + /** + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at + * the cost of overhead within node. + */ + useBCE?: boolean; + /** + * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). + */ + resizeTimeout?: number; + /** + * The width of tabs within an element's content. + */ + tabSize?: number; + /** + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * option. It may become default in the future). + */ + autoPadding?: boolean; + + cursor?: Types.TCursor; + + /** + * Create a log file. See log method. + */ + log?: (...msg: any[]) => void; + /** + * Dump all output and input to desired file. Can be used together with log option if set as a boolean. + */ + dump?: string; + /** + * Debug mode. Enables usage of the debug method. Also creates a debug console which will display when + * pressing F12. It will display all log and debug messages. + */ + debug?: (...msg: string[]) => void; + /** + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * for creating a key that will always exit no matter whether the keys are locked. + */ + ignoreLocked?: boolean; + /** + * Automatically "dock" borders with other elements instead of overlapping, depending on position + * (experimental). For example: These border-overlapped elements: + */ + dockBorders?: boolean; + /** + * Normally, dockable borders will not dock if the colors or attributes are different. This option + * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. + */ + ignoreDockContrast?: boolean; + /** + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * removes them from an element's content if iTerm2 is detected). + */ + fullUnicode?: boolean; + /** + * Send focus events after mouse is enabled. + */ + sendFocus?: boolean; + /** + * Display warnings (such as the output not being a TTY, similar to ncurses). + */ + warnings?: boolean; + /** + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * If value is true unicode is forced. If value is false non-unicode is forced (default: null). + */ + forceUnicode?: boolean; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + input?: stream.Writable; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + output?: stream.Readable; + /** + * The blessed Tput object (only available if you passed tput: true to the Program constructor.) + */ + tput?: Tput; + /** + * Top of the focus history stack. + */ + focused?: BlessedElement; + /** + * Width of the screen (same as program.cols). + */ + width?: Types.TPosition; + /** + * Height of the screen (same as program.rows). + */ + height?: Types.TPosition; + /** + * Same as screen.width. + */ + cols?: number; + /** + * Same as screen.height. + */ + rows?: number; + /** + * Relative top offset, always zero. + */ + top?: Types.TTopLeft; + /** + * Relative left offset, always zero. + */ + left?: Types.TTopLeft; + /** + * Relative right offset, always zero. + */ + right?: Types.TPosition; + /** + * Relative bottom offset, always zero. + */ + bottom?: Types.TPosition; + /** + * Absolute top offset, always zero. + */ + atop?: Types.TTopLeft; + /** + * Absolute left offset, always zero. + */ + aleft?: Types.TTopLeft; + /** + * Absolute right offset, always zero. + */ + aright?: Types.TPosition; + /** + * Absolute bottom offset, always zero. + */ + abottom?: Types.TPosition; + /** + * Whether the focused element grabs all keypresses. + */ + grabKeys?: any; + /** + * Prevent keypresses from being received by any element. + */ + lockKeys?: boolean; + /** + * The currently hovered element. Only set if mouse events are bound. + */ + hover?: any; + /** + * Set or get terminal name. Set calls screen.setTerminal() internally. + */ + terminal?: string; + /** + * Set or get window title. + */ + title?: string; + } + + export class Screen extends NodeWithEvents implements IHasOptions { + constructor(opts: IScreenOptions); + + // ** properties ** // + cleanSides: any; + + /** + * Original options object. + */ + options: IScreenOptions; + + /** + * The blessed Program to be associated with. Will be automatically instantiated if none is provided. + */ + program: BlessedProgram; + /** + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * however, it is more optimal for terminal rendering. + */ + smartCSR: boolean; + /** + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * but may cause flickering depending on what is on each side of the element. + */ + fastCSR: boolean; + /** + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at + * the cost of overhead within node. + */ + useBCE: boolean; + /** + * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). + */ + resizeTimeout: number; + /** + * The width of tabs within an element's content. + */ + tabSize: number; + /** + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * option. It may become default in the future). + */ + autoPadding: boolean; + + cursor: Types.TCursor; + + /** + * Dump all output and input to desired file. Can be used together with log option if set as a boolean. + */ + dump: string; + /** + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * for creating a key that will always exit no matter whether the keys are locked. + */ + ignoreLocked: boolean; + /** + * Automatically "dock" borders with other elements instead of overlapping, depending on position + * (experimental). For example: These border-overlapped elements: + */ + dockBorders: boolean; + /** + * Normally, dockable borders will not dock if the colors or attributes are different. This option + * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. + */ + ignoreDockContrast: boolean; + /** + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * removes them from an element's content if iTerm2 is detected). + */ + fullUnicode: boolean; + /** + * Send focus events after mouse is enabled. + */ + sendFocus: boolean; + /** + * Display warnings (such as the output not being a TTY, similar to ncurses). + */ + warnings: boolean; + /** + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * If value is true unicode is forced. If value is false non-unicode is forced (default: null). + */ + forceUnicode: boolean; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + input: stream.Writable; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + output: stream.Readable; + /** + * The blessed Tput object (only available if you passed tput: true to the Program constructor.) + */ + tput: Tput; + /** + * Top of the focus history stack. + */ + focused: BlessedElement; + /** + * Width of the screen (same as program.cols). + */ + width: Types.TPosition; + /** + * Height of the screen (same as program.rows). + */ + height: Types.TPosition; + /** + * Same as screen.width. + */ + cols: number; + /** + * Same as screen.height. + */ + rows: number; + /** + * Relative top offset, always zero. + */ + top: Types.TTopLeft; + /** + * Relative left offset, always zero. + */ + left: Types.TTopLeft; + /** + * Relative right offset, always zero. + */ + right: Types.TPosition; + /** + * Relative bottom offset, always zero. + */ + bottom: Types.TPosition; + /** + * Absolute top offset, always zero. + */ + atop: Types.TTopLeft; + /** + * Absolute left offset, always zero. + */ + aleft: Types.TTopLeft; + /** + * Absolute right offset, always zero. + */ + aright: Types.TPosition; + /** + * Absolute bottom offset, always zero. + */ + abottom: Types.TPosition; + /** + * Whether the focused element grabs all keypresses. + */ + grabKeys: any; + /** + * Prevent keypresses from being received by any element. + */ + lockKeys: boolean; + /** + * The currently hovered element. Only set if mouse events are bound. + */ + hover: any; + /** + * Set or get terminal name. Set calls screen.setTerminal() internally. + */ + terminal: string; + /** + * Set or get window title. + */ + title: string; + + // ** methods ** // + + /** + * Write string to the log file if one was created. + */ + log(...msg: any[]): void; + /** + * Same as the log method, but only gets called if the debug option was set. + */ + debug(...msg: string[]): void; + /** + * Allocate a new pending screen buffer and a new output screen buffer. + */ + alloc(): void; + /** + * Reallocate the screen buffers and clear the screen. + */ + realloc(): void; + /** + * Draw the screen based on the contents of the screen buffer. + */ + draw(start: number, end: number): void; + /** + * Render all child elements, writing all data to the screen buffer and drawing the screen. + */ + render(): void; + /** + * Clear any region on the screen. + */ + clearRegion(x1: number, x2: number, y1: number, y2: number): void; + /** + * Fill any region with a character of a certain attribute. + */ + fillRegion(attr: string, ch: string, x1: number, x2: number, y1: number, y2: number): void; + /** + * Focus element by offset of focusable elements. + */ + focusOffset(offset: number): any; + /** + * Focus previous element in the index. + */ + focusPrevious(): void; + /** + * Focus next element in the index. + */ + focusNext(): void; + /** + * Push element on the focus stack (equivalent to screen.focused = el). + */ + focusPush(element: BlessedElement): void; + /** + * Pop element off the focus stack. + */ + focusPop(): BlessedElement; + /** + * Save the focused element. + */ + saveFocus(): BlessedElement; + /** + * Restore the saved focused element. + */ + restoreFocus(): BlessedElement; + /** + * "Rewind" focus to the last visible and attached element. + */ + rewindFocus(): BlessedElement; + /** + * Spawn a process in the foreground, return to blessed app after exit. + */ + spawn(file: string, args: string[], options: NodeChildProcessExecOptions): child_process.ChildProcess; + /** + * Spawn a process in the foreground, return to blessed app after exit. Executes callback on error or exit. + */ + exec(file: string, args: string[], options: NodeChildProcessExecOptions, callback: Function): child_process.ChildProcess; + /** + * Read data from text editor. + */ + readEditor(options: any, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + readEditor(callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /** + * Set effects based on two events and attributes. + */ + setEffects(el: BlessedElement, fel: BlessedElement, over: any, out: any, effects: any, temp: any): void; + /** + * Insert a line into the screen (using csr: this bypasses the output buffer). + */ + insertLine(n: number, y: number, top: number, bottom: number): void; + /** + * Delete a line from the screen (using csr: this bypasses the output buffer). + */ + deleteLine(n: number, y: number, top: number, bottom: number): void; + /** + * Insert a line at the bottom of the screen. + */ + insertBottom(top: number, bottom: number): void; + /** + * Insert a line at the top of the screen. + */ + insertTop(top: number, bottom: number): void; + /** + * Delete a line at the bottom of the screen. + */ + deleteBottom(top: number, bottom: number): void; + /** + * Delete a line at the top of the screen. + */ + deleteTop(top: number, bottom: number): void; + /** + * Enable mouse events for the screen and optionally an element (automatically called when a form of + * on('mouse') is bound). + */ + enableMouse(el: BlessedElement): void; + enableMouse(): void; + /** + * Enable keypress events for the screen and optionally an element (automatically called when a form of + * on('keypress') is bound). + */ + enableKeys(el: BlessedElement): void; + enableKeys(): void; + /** + * Enable key and mouse events. Calls bot enableMouse and enableKeys. + */ + enableInput(el: BlessedElement): void; + enableInput(): void; + /** + * Attempt to copy text to clipboard using iTerm2's proprietary sequence. Returns true if successful. + */ + copyToClipboard(text: string): void; + /** + * Attempt to change cursor shape. Will not work in all terminals (see artificial cursors for a solution + * to this). Returns true if successful. + */ + cursorShape(shape: boolean, blink: boolean): any; + /** + * Attempt to change cursor color. Returns true if successful. + */ + cursorColor(color: string): void; + /** + * Attempt to reset cursor. Returns true if successful. + */ + cursorReset(): void; + /** + * Take an SGR screenshot of the screen within the region. Returns a string containing only + * characters and SGR codes. Can be displayed by simply echoing it in a terminal. + */ + screenshot(xi: number, xl: number, yi: number, yl: number): string; + screenshot(): void; + /** + * Destroy the screen object and remove it from the global list. Also remove all global events relevant + * to the screen object. If all screen objects are destroyed, the node process is essentially reset + * to its initial state. + */ + destroy(): void; + /** + * Reset the terminal to term. Reloads terminfo. + */ + setTerminal(term: string): void; + } + + export interface Padding { + left?: number; + right?: number; + top?: number; + bottom?: number; + } + + export class PositionCoords { + xi: number; + xl: number; + yi: number; + yl: number; + } + + export interface Position { + left: number | string; + right: number | string; + top: number | string; + bottom: number | string; + } + + export interface Border { + /** + * Type of border (line or bg). bg by default. + */ + type?: "line" | "bg"; + /** + * Character to use if bg type, default is space. + */ + ch?: string; + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg?: number; + fg?: number; + /** + * Border attributes. + */ + bold?: string; + underline?: string; + } + + export interface ElementOptions extends INodeOptions { + tags?: boolean; + + fg?: string; + bg?: string; + bold?: string; + underline?: string; + + style?: any; + /** + * Border object, see below. + */ + border?: Border | "line" | "bg"; + /** + * Element's text content. + */ + content?: string; + /** + * Element is clickable. + */ + clickable?: boolean; + /** + * Element is focusable and can receive key input. + */ + input?: boolean; + keyable?: boolean; + /** + * Element is focused. + */ + focused?: BlessedElement; + /** + * Whether the element is hidden. + */ + hidden?: boolean; + /** + * A simple text label for the element. + */ + label?: string; + /** + * A floating text label for the element which appears on mouseover. + */ + hoverText?: string; + /** + * Text alignment: left, center, or right. + */ + align?: "left" | "center" | "right"; + /** + * Vertical text alignment: top, middle, or bottom. + */ + valign?: "top" | "middle" | "bottom"; + /** + * Shrink/flex/grow to content and child elements. Width/height during render. + */ + shrink?: boolean; + /** + * Amount of padding on the inside of the element. Can be a number or an object containing + * the properties: left, right, top, and bottom. + */ + padding?: number | Padding; + + top?: Types.TTopLeft; + left?: Types.TTopLeft; + right?: Types.TPosition; + bottom?: Types.TPosition; + + /** + * Width/height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). + * Percentages can also have offsets (50%+1, 50%-1). + */ + width?: number | string; + /** + * Offsets of the element relative to its parent. Can be a number, percentage (0-100%), or + * keyword (center). right and bottom do not accept keywords. Percentages can also have + * offsets (50%+1, 50%-1). + */ + height?: number | string; + /** + * Can contain the above options. + */ + position?: Position; + /** + * Whether the element is scrollable or not. + */ + scrollable?: boolean; + /** + * Background character (default is whitespace ). + */ + ch?: string; + /** + * Allow the element to be dragged with the mouse. + */ + draggable?: boolean; + /** + * Draw a translucent offset shadow behind the element. + */ + shadow?: boolean; + } + + export interface Coords { + xl: number; + xi: number; + yl: number; + yi: number; + base: number; + _contentEnd: {x: number; y: number;}; + notop: Types.TTopLeft; + noleft: Types.TTopLeft; + noright: Types.TPosition; + nobot: Types.TPosition; + } + + export interface LabelOptions { + text: string; + side: Types.TAlign; + } + + // TODO: scrollable - Note: If the scrollable option is enabled, Element inherits all methods from ScrollableBox. + export abstract class BlessedElement extends NodeWithEvents implements IHasOptions { + constructor(opts: ElementOptions); + + // ** properties ** // + + /** + * Original options object. + */ + options: ElementOptions; + /** + * Name of the element. Useful for form submission. + */ + name: string; + /** + * Border object. + */ + border: Border; + + style: any; + position: Position; + content: string; + hidden: boolean; + visible: boolean; + detached: boolean; + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg: number; + fg: number; + /** + * Border attributes. + */ + bold: string; + underline: string; + /** + * Calculated width. + */ + width: number | string; + /** + * Calculated height. + */ + height: number | string; + /** + * Calculated relative top offset.*/ + top: Types.TTopLeft; + /** + * Calculated relative left offset. + */ + left: Types.TTopLeft; + /** + * Calculated relative right offset. + */ + right: Types.TPosition; + /** + * Calculated relative bottom offset. + */ + bottom: Types.TPosition; + /** + * Calculated absolute top offset. + */ + atop: Types.TTopLeft; + /** + * Calculated absolute left offset. + */ + aleft: Types.TTopLeft; + /** + * Calculated absolute right offset. + */ + aright: Types.TPosition; + /** + * Calculated absolute bottom offset. + */ + abottom: Types.TPosition; + + /** + * Whether the element is draggable. Set to true to allow dragging. + */ + draggable: boolean; + + itop: Types.TTopLeft; + ileft: Types.TTopLeft; + iheight: Types.TPosition; + iwidth: Types.TPosition; + + /** + * Calculated relative top offset. + */ + rtop: Types.TTopLeft; + /** + * Calculated relative left offset. + */ + rleft: Types.TTopLeft; + /** + * Calculated relative right offset. + */ + rright: Types.TPosition; + /** + * Calculated relative bottom offset. + */ + rbottom: Types.TPosition; + + lpos: PositionCoords; + + // ** methods ** // + + /** + * Write content and children to the screen buffer. + */ + render(): Coords; + /** + * Hide element.*/ + hide(): void; + /** + * Show element. + */ + show(): void; + /** + * Toggle hidden/shown. + */ + toggle(): void; + /** + * Focus element. + */ + focus(): void; + /** + * Same asel.on('screen', ...) except this will automatically keep track of which listeners + * are bound to the screen object. For use with removeScreenEvent(), free(), and destroy(). + */ + onScreenEvent(type: string, handler: Function): void; + /** + * Same asel.removeListener('screen', ...) except this will automatically keep track of which + * listeners are bound to the screen object. For use with onScreenEvent(), free(), and destroy(). + */ + removeScreenEvent(type: string, handler: Function): void; + /** + * Free up the element. Automatically unbind all events that may have been bound to the screen + * object. This prevents memory leaks. For use with onScreenEvent(), removeScreenEvent(), + * and destroy(). + */ + free(): void; + /** + * Same as the detach() method, except this will automatically call free() and unbind any screen + * events to prevent memory leaks. for use with onScreenEvent(), removeScreenEvent(), and free(). + */ + destroy(): void; + /** + * Set the z-index of the element (changes rendering order). + */ + setIndex(z: number): void; + /** + * Put the element in front of its siblings.*/ + setFront(): void; + /** + * Put the element in back of its siblings. + */ + setBack(): void; + /** + * text/options - Set the label text for the top-left corner. Example options: {text:'foo',side:'left'} + */ + setLabel(arg: string | LabelOptions): void; + /** + * Remove the label completely. + */ + removeLabel(): any; + /** + * text/options - Set a hover text box to follow the cursor. Similar to the "title" DOM attribute + * in the browser. Example options: {text:'foo'} + */ + setHover(arg: string | LabelOptions): void; + /** + * Remove the hover label completely. + */ + removeHover(): void; + /** + * Enable mouse events for the element (automatically called when a form of on('mouse') is bound). + */ + enableMouse(): void; + /** + * Enable keypress events for the element (automatically called when a form of on('keypress') is bound). + */ + enableKeys(): void; + /** + * Enable key and mouse events. Calls bot enableMouse and enableKeys. + */ + enableInput(): void; + /** + * Enable dragging of the element. + */ + enableDrag(): void; + /** + * Disable dragging of the element. + */ + disableDrag(): void; + /** + * Take an SGR screenshot of the screen within the region. Returns a string containing only + * characters and SGR codes. Can be displayed by simply echoing it in a terminal. + */ + screenshot(xi: number, xl: number, yi: number, yl: number): string; + screenshot(): void; + + /* + Content Methods + + Methods for dealing with text content, line by line. Useful for writing a text editor, + irc client, etc. + + Note: All of these methods deal with pre-aligned, pre-wrapped text. If you use deleteTop() + on a box with a wrapped line at the top, it may remove 3-4 "real" lines (rows) depending + on how long the original line was. + + The lines parameter can be a string or an array of strings. The line parameter must + be a string. + */ + + /** + * Set the content. Note: When text is input, it will be stripped of all non-SGR + * escape codes, tabs will be replaced with 8 spaces, and tags will be replaced + * with SGR codes (if enabled). + */ + setContent(text: string): void; + /** + * Return content, slightly different from el.content. Assume the above formatting. + */ + getContent(): string; + /** + * Similar to setContent, but ignore tags and remove escape codes. + */ + setText(text: string): void; + /** + * Similar to getContent, but return content with tags and escape codes removed. + */ + getText(): string; + /** + * Insert a line into the box's content. + */ + insertLine(i: number, lines: string | string[]): void; + /** + * Delete a line from the box's content. + */ + deleteLine(i: number): void; + /** + * Get a line from the box's content. + */ + getLine(i: number): string; + /** + * Get a line from the box's content from the visible top. + */ + getBaseLine(i: number): string; + /** + * Set a line in the box's content. + */ + setLine(i: number, line: string | string[]): void; + /** + * Set a line in the box's content from the visible top. + */ + setBaseLine(i: number, line: string | string[]): void; + /** + * Clear a line from the box's content. + */ + clearLine(i: number): void; + /** + * Clear a line from the box's content from the visible top. + */ + clearBaseLine(i: number): void; + /** + * Insert a line at the top of the box. + */ + insertTop(lines: string | string[]): void; + /** + * Insert a line at the bottom of the box. + */ + insertBottom(lines: string | string[]): void; + /** + * Delete a line at the top of the box. + */ + deleteTop(): void; + /** + * Delete a line at the bottom of the box. + */ + deleteBottom(): void; + /** + * Unshift a line onto the top of the content. + */ + unshiftLine(lines: string | string[]): void; + /** + * Shift a line off the top of the content. + */ + shiftLine(i: number): void; + /** + * Push a line onto the bottom of the content. + */ + pushLine(lines: string | string[]): void; + /** + * Pop a line off the bottom of the content. + */ + popLine(i: number): string; + /** + * An array containing the content lines. + */ + getLines(): string[]; + /** + * An array containing the lines as they are displayed on the screen. + */ + getScreenLines(): string[]; + /** + * Get a string's displayed width, taking into account double-width, surrogate pairs, + * combining characters, tags, and SGR escape codes. + */ + strWidth(text: string): string; + + // ** events ** // + } + + export interface ScrollableBoxOptions extends ElementOptions { + /** + * A limit to the childBase. Default is Infinity. + */ + baseLimit?: number; + /** + * A option which causes the ignoring of childOffset. This in turn causes the + * childBase to change every time the element is scrolled. + */ + alwaysScroll?: boolean; + /** + * Object enabling a scrollbar. + * Style of the scrollbar track if present (takes regular style options). + */ + scrollbar?: { style?: any; track?: any; ch?: string; } + } + + export interface ScrollableTextOptions extends ScrollableBoxOptions { + /** + * Whether to enable automatic mouse support for this element. + * Use pre-defined mouse events (right-click for editor). + */ + mouse?: boolean | (() => void); + /** + * Use pre-defined keys (i or enter for insert, e for editor, C-e for editor while inserting). + */ + keys?: string | string[] | boolean; + /** + * Use vi keys with the keys option. + */ + vi?: boolean; + } + + export interface BoxOptions extends ScrollableTextOptions { + bindings?: any; + } + + /** + * DEPRECATED - Use Box with the scrollable option instead. A box with scrollable content. + */ + export class ScrollableBoxElement extends BlessedElement { + /** + * The offset of the top of the scroll content. + */ + childBase: number; + /** + * The offset of the chosen item/line. + */ + childOffset: number; + + /** + * Scroll the content by a relative offset. + */ + scroll(offset: number, always?: boolean): void; + /** + * Scroll the content to an absolute index. + */ + scrollTo(index: number): void; + /** + * Same as scrollTo. + */ + setScroll(index: number): void; + /** + * Set the current scroll index in percentage (0-100). + */ + setScrollPerc(perc: number): void; + /** + * Get the current scroll index in lines. + */ + getScroll(): void; + /** + * Get the actual height of the scrolling area. + */ + getScrollHeight(): void; + /** + * Get the current scroll index in percentage. + */ + getScrollPerc(): void; + /** + * Reset the scroll index to its initial state. + */ + resetScroll(): void; + + on(event: string, listener: Function): this; + /** + * Received when the element is scrolled. + */ + on(event: "scroll", callback: () => void): this; + } + + /** + * DEPRECATED - Use Box with the scrollable and alwaysScroll options instead. + * A scrollable text box which can display and scroll text, as well as handle + * pre-existing newlines and escape codes. + */ + export class ScrollableTextElement extends ScrollableBoxElement { + } + + /** + * A box element which draws a simple box containing content or other elements. + */ + export class BoxElement extends ScrollableTextElement implements IHasOptions { + constructor(opts: BoxOptions); + + /** + * Original options object. + */ + options: BoxOptions; + } + + export interface TextOptions extends ElementOptions { + /** + * Fill the entire line with chosen bg until parent bg ends, even if there + * is not enough text to fill the entire width. + */ + fill?: boolean; + /** + * Text alignment: left, center, or right. + */ + align?: Types.TAlign; + } + + /** + * An element similar to Box, but geared towards rendering simple text elements. + */ + export class TextElement extends BlessedElement implements IHasOptions { + constructor(opts: TextOptions); + + /** + * Original options object. + */ + options: TextOptions; + } + + /** + * A simple line which can be line or bg styled. + */ + export interface LineOptions extends BoxOptions { + /** + * Can be vertical or horizontal. + */ + orientation?: "vertical" | "horizontal"; + /** + * Treated the same as a border object. (attributes can be contained in style). + */ + type?: string; + bg?: string; + fg?: string; + ch?: string; + } + + /** + * A simple line which can be line or bg styled. + */ + export class LineElement extends BoxElement implements IHasOptions { + constructor(opts: LineOptions); + + /** + * Original options object. + */ + options: LineOptions; + } + + export interface BigTextOptions extends BoxOptions { + /** + * bdf->json font file to use (see ttystudio for instructions on compiling BDFs to JSON). + */ + font?: string; + /** + * bdf->json bold font file to use (see ttystudio for instructions on compiling BDFs to JSON). + */ + fontBold?: string; + /** + * foreground character. (default: ' ') + */ + fch?: string; + } + + /** + * A box which can render content drawn as 8x14 cell characters using the terminus font. + */ + export class BigTextElement extends BoxElement implements IHasOptions { + constructor(opts: BigTextOptions); + + /** + * Original options object. + */ + options: BigTextOptions; + } + + export interface ListElementStyle { + selected?: any; + item?: any; + } + + export interface ListOptions extends BoxOptions { + /** + * Style for a selected item. Style for an unselected item. + */ + style?: TStyle; + /** + * An array of strings which become the list's items. + */ + items?: string[]; + /** + * A function that is called when vi mode is enabled and the key / is pressed. This function accepts a + * callback function which should be called with the search string. The search string is then used to + * jump to an item that is found in items. + */ + search?: () => void; + /** + * Whether the list is interactive and can have items selected (Default: true). + */ + interactive?: boolean; + /** + * Whether to automatically override tags and invert fg of item when selected (Default: true). + */ + invertSelected?: boolean; + } + + export class ListElement extends BoxElement implements IHasOptions> { + constructor(opts: ListOptions); + + /** + * Original options object. + */ + options: ListOptions; + + /** + * Add an item based on a string. + */ + add(text: string): void; + /** + * Add an item based on a string. + */ + addItem(text: string): void; + /** + * Removes an item from the list. Child can be an element, index, or string. + */ + removeItem(child: BlessedElement): BlessedElement; + /** + * Push an item onto the list. + * */ + pushItem(child: BlessedElement): number; + /** + * Pop an item off the list. + * */ + popItem(): BlessedElement; + /** + * Unshift an item onto the list. + */ + unshiftItem(child: BlessedElement): number; + /** + * Shift an item off the list. + * */ + shiftItem(): BlessedElement; + /** + * Inserts an item to the list. Child can be an element, index, or string. + */ + insertItem(i: number, child: BlessedElement): void; + /** + * Returns the item element. Child can be an element, index, or string. + */ + getItem(child: BlessedElement): BlessedElement; + /** + * Set item to content. + */ + setItem(child: BlessedElement, content: BlessedElement | string): void; + /** + * Remove and insert items to the list. + * */ + spliceItem(i: number, n: number, ...items: BlessedElement[]): void; + /** + * Clears all items from the list. + * */ + clearItems(): void; + /** + * Sets the list items to multiple strings. + */ + setItems(items: BlessedElement[]): void; + /** + * Returns the item index from the list. Child can be an element, index, or string. + */ + getItemIndex(child: BlessedElement): number; + /** + * Select an index of an item. + * */ + select(index: number): void; + /** + * Select item based on current offset. + * */ + move(offset: number): void; + /** + * Select item above selected. + * */ + up(amount: number): void; + /** + * Select item below selected. + */ + down(amount: number): void; + /** + * Show/focus list and pick an item. The callback is executed with the result. + */ + pick(callback: () => void): void; + /** + * Find an item based on its text content. + */ + fuzzyFind(arg: string | RegExp | (() => void)): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received when an item is selected. + */ + on(event: "select", callback: (item: BoxElement, index: number) => void): this; + /** + * List was canceled (when esc is pressed with the keys option). + */ + on(event: "cancel", callback: () => void): this; + /** + * Either a select or a cancel event was received. + */ + on(event: "action", callback: () => void): this; + + on(event: "create item", callback: () => void): this; + on(event: "add item", callback: () => void): this; + on(event: "remove item", callback: () => void): this; + on(event: "insert item", callback: () => void): this; + on(event: "set items", callback: () => void): this; + on(event: "select item", callback: (item: BlessedElement, index: number) => void): this; + } + + export interface FileManagerOptions extends ListOptions { + /** + * Current working directory. + */ + cwd?: string; + } + + export class FileManagerElement extends ListElement implements IHasOptions { + constructor(opts: FileManagerOptions); + + /** + * Original options object. + */ + options: FileManagerOptions; + /** + * Current working directory. + */ + cwd: string; + + /** + * Refresh the file list (perform a readdir on cwd and update the list items). + */ + refresh(cwd:string, callback: () => void): void; + refresh(callback: () => void): void; + refresh(): void; + /** + * Pick a single file and return the path in the callback. + */ + pick(cwd:string, callback: () => void): void; + pick(callback: () => void): void; + /** + * Reset back to original cwd. + */ + reset(cwd:string, callback: () => void): void; + reset(callback: () => void): void; + reset(): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received when an item is selected. + */ + on(event: "cd", callback: (file: string, cwd: string) => void): this; + /** + * Received when an item is selected. + */ + on(event: "file", callback: (file: string) => void): this; + + on(event: "error", callback: (err: any, file: string) => void): this; + on(event: "refresh", callback: () => void): this; + } + + export interface StyleListTable extends ListElementStyle { + /** + * Header style. + */ + header?: any; + /** + * Cell style. + */ + cell?: any; + } + + export interface ListTableOptions extends ListOptions { + /** + * Array of array of strings representing rows. + */ + rows?: string[]; + data?: string[][]; + /** + * Spaces to attempt to pad on the sides of each cell. 2 by default: one space on each side + * (only useful if the width is shrunken). + */ + pad?: number; + /** + * Do not draw inner cells. + */ + noCellBorders?: boolean; + + style?: StyleListTable; + } + + export class ListTableElement extends ListElement implements IHasOptions { + constructor(opts: ListTableOptions); + + /** + * Original options object. + */ + options: ListTableOptions; + + /** + * Set rows in table. Array of arrays of strings. + * @example: + * + * table.setData([ + [ 'Animals', 'Foods' ], + [ 'Elephant', 'Apple' ], + [ 'Bird', 'Orange' ] + ]); + */ + setRows(rows: string[][]): void; + /** + * Set rows in table. Array of arrays of strings. + * @example: + * + * table.setData([ + [ 'Animals', 'Foods' ], + [ 'Elephant', 'Apple' ], + [ 'Bird', 'Orange' ] + ]); + */ + setData(rows: string[][]): void; + } + + export interface ListbarOptions extends BoxOptions { + style?: ListElementStyle; + /** + * Set buttons using an object with keys as titles of buttons, containing of objects + * containing keys of keys and callback. + */ + commands: Types.ListbarCommand[]; + items: Types.ListbarCommand[]; + /** + * Automatically bind list buttons to keys 0-9. + */ + autoCommandKeys: boolean; + } + + export class ListbarElement extends BoxElement implements IHasOptions { + constructor(opts: ListbarOptions); + + /** + * Original options object. + */ + options: ListbarOptions; + + /** + * Set commands (see commands option above). + */ + setItems(commands: Types.ListbarCommand[]): void; + /** + * Append an item to the bar. + */ + add(item: Types.ListbarCommand, callback: () => void): void; + /** + * Append an item to the bar. + */ + addItem(item: Types.ListbarCommand, callback: () => void): void; + /** + * Append an item to the bar. + */ + appendItem(item: Types.ListbarCommand, callback: () => void): void; + /** + * Select an item on the bar. + */ + select(offset: number): void; + /** + * Remove item from the bar. + */ + removeItem(child: BlessedElement): void; + /** + * Move relatively across the bar. + */ + move(offset: number): void; + /** + * Move left relatively across the bar. + */ + moveLeft(offset: number): void; + /** + * Move right relatively across the bar. + */ + moveRight(offset: number): void; + /** + * Select button and execute its callback. + */ + selectTab(index: number): void; + + // ** events ** // + + on(event: string, listener: Function): this; + + on(event: "set items", callback: () => void): this; + on(event: "remove item", callback: () => void): this; + on(event: "select tab", callback: () => void): this; + } + + export interface FormOptions extends BoxOptions { + /** + * Allow default keys (tab, vi keys, enter). + */ + keys?: any; + /** + * Allow vi keys. + */ + vi?: boolean; + } + + export class FormElement extends BoxElement implements IHasOptions { + constructor(opts: FormOptions); + + /** + * Original options object. + */ + options: FormOptions; + /** + * Last submitted data. + */ + submission: TFormData; + + /** + * Focus next form element. + */ + focusNext(): void; + /** + * Focus previous form element. + */ + focusPrevious(): void; + /** + * Submit the form. + */ + submit(): void; + /** + * Discard the form. + */ + cancel(): void; + /** + * Clear the form. + */ + reset(): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Form is submitted. Receives a data object. + */ + on(event: "submit", callback: (out: TFormData) => void): this; + /** + * Form is discarded. + */ + on(event: "cancel", callback: () => void): this; + /** + * Form is cleared. + */ + on(event: "reset", callback: () => void): this; + } + + export interface InputOptions extends BoxOptions { } + + export abstract class InputElement extends BoxElement { + constructor(opts: InputOptions); + } + + /** + * A box which allows multiline text input. + */ + export interface TextareaOptions extends InputOptions { + /** + * Call readInput() when the element is focused. Automatically unfocus. + */ + inputOnFocus?: boolean; + } + + export class TextareaElement extends InputElement implements IHasOptions { + constructor(opts: TextareaOptions); + + /** + * Original options object. + */ + options: TextareaOptions; + + /** + * The input text. read-only. + */ + value: string; + + /** + * Submit the textarea (emits submit). + */ + submit(): void; + /** + * Cancel the textarea (emits cancel). + */ + cancel(): void; + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + readInput(callback?: (err: any, value?: string) => void): void; + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + input(callback: (err: any, value?: string) => void): void; + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + setInput(callback: (err: any, value?: string) => void): void; + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + readEditor(callback: (err: any, value?: string) => void): void; + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + editor(callback: (err: any, value?: string) => void): void; + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + setEditor(callback: (err: any, value?: string) => void): void; + /** + * The same as this.value, for now. + */ + getValue(): string; + /** + * Clear input. + */ + clearValue(): void; + /** + * Set value. + */ + setValue(text: string): void; + + // ** events ** // + + on(event: string, listener: Function): this; + + on(event: "error", callback: (err: any) => void): this; + + /** + * Value is submitted (enter). + */ + on(event: "submit", callback: (value: any) => void): this; + /** + * Value is discared (escape). + */ + on(event: "cancel", callback: (value: any) => void): this; + /** + * Either submit or cancel. + */ + on(event: "action", callback: (value: any) => void): this; + } + + export interface TextboxOptions extends TextareaOptions { + /** + * Completely hide text. + */ + secret?: boolean; + /** + * Replace text with asterisks (*). + */ + censor?: boolean; + } + + export class TextboxElement extends TextareaElement implements IHasOptions { + constructor(opts: TextboxOptions); + + /** + * Original options object. + */ + options: TextboxOptions; + + /** + * Completely hide text. + */ + secret: boolean; + /** + * Replace text with asterisks (*). + */ + censor: boolean; + } + + export interface ButtonOptions extends BoxOptions { } + + export class ButtonElement extends InputElement implements IHasOptions { + constructor(opts: ButtonOptions); + + /** + * Original options object. + */ + options: ButtonOptions; + + /** + * Press button. Emits press. + */ + press(): void; + + on(event: string, listener: Function): this; + + on(event: "press", callback: () => void): this; + } + + export interface CheckboxOptions extends BoxOptions { + /** + * whether the element is checked or not. + * */ + checked?: boolean; + /** + * enable mouse support. + * */ + mouse?: boolean; + } + + /** + * A checkbox which can be used in a form element. + * */ + export class CheckboxElement extends InputElement implements IHasOptions { + constructor(options?: CheckboxOptions); + + /** + * Original options object. + */ + options: CheckboxOptions; + + /** + * the text next to the checkbox (do not use setcontent, use `check.text = ''`). + * */ + text: string; + /** + * whether the element is checked or not. + * */ + checked: boolean; + /** + * same as `checked`. + * */ + value: boolean; + + /** + * check the element. + * */ + check(): void; + /** + * uncheck the element. + * */ + uncheck(): void; + /** + * toggle checked state. + * */ + toggle(): void; + } + + export interface RadioSetOptions extends BoxOptions { } + + /** + * An element wrapping RadioButtons. RadioButtons within this element will be mutually exclusive + * with each other. + * */ + export abstract class RadioSetElement extends BoxElement { + constructor(opts: RadioSetOptions); + } + + export interface RadioButtonOptions extends BoxOptions { } + + /** + * A radio button which can be used in a form element. + */ + export abstract class RadioButtonElement extends CheckboxElement { + constructor(opts: RadioButtonOptions); + } + + export interface PromptOptions extends BoxOptions { } + + /** + * A prompt box containing a text input, okay, and cancel buttons (automatically hidden). + */ + export class PromptElement extends BoxElement implements IHasOptions { + constructor(opts: PromptOptions); + + options: PromptOptions; + + /** + * Show the prompt and wait for the result of the textbox. Set text and initial value. + */ + input(text: string, value: string, callback: (err: any, value: string) => void): void; + setInput(text: string, value: string, callback: (err: any, value: string) => void): void; + readInput(text: string, value: string, callback: (err: any, value: string) => void): void; + } + + export interface QuestionOptions extends BoxOptions { } + + /** + * A question box containing okay and cancel buttons (automatically hidden). + */ + export class QuestionElement extends BoxElement implements IHasOptions { + constructor(opts: QuestionOptions); + + options: QuestionOptions; + + /** + * Ask a question. callback will yield the result. + */ + ask(question: string, callback: (err: any, value: string) => void): void; + } + + export interface MessageOptions extends BoxOptions { } + + /** + * A box containing a message to be displayed (automatically hidden). + */ + export class MessageElement extends BoxElement implements IHasOptions { + constructor(opts: MessageOptions); + + options: MessageOptions; + + /** + * Display a message for a time (default is 3 seconds). Set time to 0 for a perpetual message that is dismissed on keypress. + */ + log(text: string, time: number, callback: (err: any) => void): void; + log(text: string, callback: (err: any) => void): void; + display(text: string, time: number, callback: (err: any) => void): void; + display(text: string, callback: (err: any) => void): void; + + /** + * Display an error in the same way. + */ + error(text: string, time: number, callback: () => void): void; + error(text: string, callback: () => void): void; + } + + export interface LoadingOptions extends BoxOptions { } + + /** + * A box with a spinning line to denote loading (automatically hidden). + */ + export class LoadingElement extends BoxElement implements IHasOptions { + constructor(opts: LoadingOptions); + + options: LoadingOptions; + + /** + * Display the loading box with a message. Will lock keys until stop is called. + */ + load(text: string): void; + /** + * Hide loading box. Unlock keys. + */ + stop(): void; + } + + export interface ProgressBarOptions extends BoxOptions { + /** + * can be `horizontal` or `vertical`. + * */ + orientation: string; + /** + * the character to fill the bar with (default is space). + * */ + pch: string; + /** + * the amount filled (0 - 100). + * */ + filled: number; + /** + * same as `filled`. + * */ + value: number; + /** + * enable key support. + * */ + keys: boolean; + /** + * enable mouse support. + * */ + mouse: boolean; + } + + /** + * A progress bar allowing various styles. This can also be used as a form input. + */ + export class ProgressBarElement extends InputElement implements IHasOptions { + constructor(options?: ProgressBarOptions); + + options: ProgressBarOptions; + + /** + * progress the bar by a fill amount. + * */ + progress(amount:number): void; + /** + * set progress to specific amount. + * */ + setProgress(amount:number): void; + /** + * reset the bar. + * */ + reset(): void; + + on(event: string, listener: Function): this; + /** + * Bar was reset. + */ + on(event: "reset", callback: () => void): this; + /** + * Bar has completely filled. + */ + on(event: "complete", callback: () => void): this; + } + + export interface LogOptions extends ScrollableTextOptions { + /** + * amount of scrollback allowed. default: Infinity. + * */ + scrollback?: number; + /** + * scroll to bottom on input even if the user has scrolled up. default: false. + * */ + scrollOnInput?: boolean; + } + + /** + * A log permanently scrolled to the bottom. + * */ + export class Log extends ScrollableTextElement implements IHasOptions { + constructor(options?: LogOptions); + + options: LogOptions; + + /** + * amount of scrollback allowed. default: Infinity. + * */ + scrollback: number; + /** + * scroll to bottom on input even if the user has scrolled up. default: false. + * */ + scrollOnInput: boolean; + + /** + * add a log line. + * */ + log(text:string): void; + /** + * add a log line. + * */ + add(text:string): void; + } + + export interface TableOptions extends BoxOptions { + /** + * array of array of strings representing rows (same as `data`). + * */ + rows?: string[][]; + /** + * array of array of strings representing rows (same as `rows`). + * */ + data?: string[][]; + /** + * spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). + * */ + pad?: number; + /** + * do not draw inner cells. + * */ + noCellBorders?: boolean; + /** + * fill cell borders with the adjacent background color. + * */ + fillCellBorders?: boolean; + } + + /** + * A stylized table of text elements. + * */ + export class TableElement extends BoxElement implements IHasOptions { + constructor(opts: TableOptions); + + options: TableOptions; + + /** + * set rows in table. array of arrays of strings. + * */ + setData(rows: string[][]): void; + /** + * set rows in table. array of arrays of strings. + * */ + setRows(rows: string[][]): void; + } + + export interface TerminalOptions extends BoxOptions { + /** + * handler for input data. + * */ + handler?: (userInput:Buffer) => void; + /** + * name of shell. $SHELL by default. + * */ + shell?:string; + /** + * args for shell. + * */ + args?:any; + /** + * can be line, underline, and block. + * */ + cursor?: 'line'|'underline'|'block'; + + terminal?: string; + + /** + * Object for process env. + */ + env?: any; + } + + export class TerminalElement extends BoxElement implements IHasOptions { + constructor(opts: TerminalOptions); + + options: TerminalOptions; + + /** + * reference to the headless term.js terminal. + * */ + term: any; + /** + * reference to the pty.js pseudo terminal. + * */ + pty: any; + + /** + * write data to the terminal. + * */ + write(data:string): void; + + /** + * nearly identical to `element.screenshot`, however, the specified region includes the terminal's _entire_ scrollback, rather than just what is visible on the screen. + * */ + screenshot(xi?:number, xl?:number, yi?:number, yl?:number): string; + } + + export interface ImageOptions extends BoxOptions { + /** + * path to image. + * */ + file: string; + /** + * path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. + * */ + type: "ansi" | "overlay" | "w3m"; + } + + /** + * Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. X11 required: works in xterm, urxvt, and possibly other terminals. + * */ + export class ImageElement extends BoxElement implements IHasOptions { + constructor(options?: ImageOptions); + + options: ImageOptions; + } + + export interface ANSIImageOptions extends BoxOptions { + /** + * URL or path to PNG/GIF file. Can also be a buffer. + * */ + file: string; + /** + * Scale cellmap down (0-1.0) from its original pixel width/height (Default: 1.0). + * */ + scale: number; + + /** + * This differs from other element's width or height in that only one of them is needed: blessed will maintain the aspect ratio of the image as it scales down to the proper number of cells. NOTE: PNG/GIF's are always automatically shrunken to size (based on scale) if a width or height is not given. + * */ + width: number | string; + height: number | string; + + /** + * Add various "density" ASCII characters over the rendering to give the image more detail, similar to libcaca/libcucul (the library mplayer uses to display videos in the terminal). + */ + ascii: string; + + /** + * Whether to animate if the image is an APNG/animating GIF. If false, only display the first frame or IDAT (Default: true). + */ + animate: boolean; + + /** + * Set the speed of animation. Slower: 0.0-1.0. Faster: 1-1000. It cannot go faster than 1 frame per millisecond, so 1000 is the fastest. (Default: 1.0) + */ + speed: number; + + /** + * mem or cpu. If optimizing for memory, animation frames will be rendered to bitmaps as the animation plays, using less memory. Optimizing for cpu will precompile all bitmaps beforehand, which may be faster, but might also OOM the process on large images. (Default: mem). + */ + optimization: "mem" | "cpu"; + } + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + * */ + export class ANSIImageElement extends BoxElement implements IHasOptions { + constructor(options?:ANSIImageOptions); + + options: ANSIImageOptions; + + /** + * Image object from the png reader. + */ + img: Types.TImage; + + /** + * set the image in the box to a new path. + * */ + setImage(img: string, callback: () => void): void; + /** + * clear the current image. + * */ + clearImage(callback: () => void): void; + /** + * Play animation if it has been paused or stopped. + */ + play(): void; + /** + * Pause animation. + */ + pause(): void; + /** + * Stop animation. + */ + stop(): void; + } + + export interface OverlayImageOptions extends BoxOptions { + /** + * Path to image. + */ + file: string; + /** + * Render the file as ANSI art instead of using w3m to overlay Internally uses the ANSIImage element. See the ANSIImage element for more information/options. (Default: true). + */ + ansi: boolean; + /** + * Path to w3mimgdisplay. If a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. + */ + w3m: string; + /** + * Whether to search /usr, /bin, and /lib for w3mimgdisplay (Default: true). + */ + search: string; + } + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + * */ + export class OverlayImageElement extends BoxElement implements IHasOptions { + constructor(options?: OverlayImageOptions); + + options: OverlayImageOptions; + + /** + * set the image in the box to a new path. + * */ + setImage(img: string, callback: () => void): void; + /** + * clear the current image. + * */ + clearImage(callback: () => void): void; + /** + * get the size of an image file in pixels. + * */ + imageSize(img:string, callback: () => void): void; + /** + * get the size of the terminal in pixels. + * */ + termSize(callback: () => void): void; + /** + * get the pixel to cell ratio for the terminal. + * */ + getPixelRatio(callback: () => void): void; + } + + export interface VideoOptions extends BoxOptions { + /** + * Video to play. + */ + file: string; + /** + * Start time in seconds. + */ + start: number; + } + + export class VideoElement extends BoxElement implements IHasOptions { + constructor(options?: VideoOptions); + + options: VideoOptions; + + /** + * The terminal element running mplayer or mpv. + */ + tty: any; + } + + export interface LayoutOptions extends ElementOptions { + /** + * A callback which is called right before the children are iterated over to be rendered. Should return an + * iterator callback which is called on each child element: iterator(el, i). + */ + renderer?: () => void; + + /** + * Using the default renderer, it provides two layouts: inline, and grid. inline is the default and will render + * akin to inline-block. grid will create an automatic grid based on element dimensions. The grid cells' + * width and height are always determined by the largest children in the layout. + */ + layout: "inline" | "inline-block" | "grid"; + } + + export class LayoutElement extends BlessedElement implements IHasOptions { + constructor(options?: LayoutOptions); + + options: LayoutOptions; + + /** + * A callback which is called right before the children are iterated over to be rendered. Should return an + * iterator callback which is called on each child element: iterator(el, i). + */ + renderer(coords: PositionCoords): void; + /** + * Check to see if a previous child element has been rendered and is visible on screen. This is only useful + * for checking child elements that have already been attempted to be rendered! see the example below. + */ + isRendered(el: BlessedElement): boolean; + /** + * Get the last rendered and visible child element based on an index. This is useful for basing the position + * of the current child element on the position of the last child element. + */ + getLast(i: number): Element; + /** + * Get the last rendered and visible child element coords based on an index. This is useful for basing the position + * of the current child element on the position of the last child element. See the example below. + */ + getLastCoords(i: number): PositionCoords; + } + + export class Program { + /** + Wrap the given text in terminal formatting codes corresponding to the given attribute + name. The `attr` string can be of the form `red fg` or `52 bg` where `52` is a 0-255 + integer color number. + */ + text (text:string, attr:string): string; + } } - export = Blessed; + export module widget { + export class Element extends Widgets.BlessedElement { } + export class Node extends Widgets.Node { } + export class Screen extends Widgets.Screen { } + + export class Box extends Widgets.BoxElement { } + export class ScrollableBox extends Widgets.ScrollableBoxElement { } + export class ScrollableText extends Widgets.ScrollableTextElement { } + export class Text extends Widgets.BoxElement { } + export class Line extends Widgets.LineElement { } + export class BigText extends Widgets.BigTextElement { } + export class List extends Widgets.ListElement { } + export class FileManager extends Widgets.FileManagerElement { } + export class ListTable extends Widgets.ListTableElement { } + export class ListBar extends Widgets.ListbarElement { } + export class Form extends Widgets.FormElement { } + export class Textarea extends Widgets.TextareaElement { } + export class Button extends Widgets.ButtonElement { } + export class Checkbox extends Widgets.CheckboxElement { } + export class RadioSet extends Widgets.RadioSetElement { } + export class RadioButton extends Widgets.RadioButtonElement { } + + export class Prompt extends Widgets.PromptElement { } + export class question extends Widgets.QuestionElement { } + export class Message extends Widgets.MessageElement { } + export class Loading extends Widgets.LoadingElement { } + + export class ProgressBar extends Widgets.ProgressBarElement { } + export class Terminal extends Widgets.TerminalElement { } + } + + export function screen(options?: Widgets.IScreenOptions): Widgets.Screen; + + export function box(options?: Widgets.BoxOptions): Widgets.BoxElement; + export function text(options?: Widgets.TextOptions): Widgets.TextElement; + export function line(options?: Widgets.LineOptions): Widgets.LineElement; + export function scrollablebox(options?: Widgets.BoxOptions): Widgets.BoxElement; + export function scrollabletext(options?: Widgets.BoxOptions): Widgets.BoxElement; + export function bigtext(options?: Widgets.BigTextOptions): Widgets.BigTextElement; + export function list(options?: Widgets.ListOptions): Widgets.ListElement; + export function filemanager(options?: Widgets.FileManagerOptions): Widgets.FileManagerElement; + export function listtable(options?: Widgets.ListTableOptions): Widgets.ListTableElement; + export function listbar(options?: Widgets.ListbarOptions): Widgets.ListbarElement; + export function form(options?: Widgets.FormOptions): Widgets.FormElement; + export function input(options?: Widgets.InputOptions): Widgets.InputElement; + export function textarea(options?: Widgets.TextareaOptions): Widgets.TextareaElement; + export function textbox(options?: Widgets.TextboxOptions): Widgets.TextboxElement; + export function button(options?: Widgets.ButtonOptions): Widgets.ButtonElement; + export function checkbox(options?: Widgets.CheckboxOptions): Widgets.CheckboxElement; + export function radioset(options?: Widgets.RadioSetOptions): Widgets.RadioSetElement; + export function radiobutton(options?: Widgets.RadioButtonOptions): Widgets.RadioButtonElement; + + export function table(options?: Widgets.TableOptions): Widgets.TableElement; + + export function prompt(options?: Widgets.PromptOptions): Widgets.PromptElement; + export function question(options?: Widgets.QuestionOptions): Widgets.QuestionElement; + export function message(options?: Widgets.MessageOptions): Widgets.MessageElement; + export function loading(options?: Widgets.LoadingOptions): Widgets.LoadingElement; + + export function progressbar(options?: Widgets.ProgressBarOptions): Widgets.ProgressBarElement; + export function terminal(options?: Widgets.TerminalOptions): Widgets.TerminalElement; + + export function layout(options?: Widgets.LayoutOptions): Widgets.LayoutElement; + + export function escape(item: any): any; + export const colors: { + match: (hexColor: string) => string + } } - - - diff --git a/blue-tape/blue-tape-tests.ts b/blue-tape/blue-tape-tests.ts index a01675a1c5..fc931aeed5 100644 --- a/blue-tape/blue-tape-tests.ts +++ b/blue-tape/blue-tape-tests.ts @@ -1,5 +1,5 @@ /// -/// +/// /// import tape = require('blue-tape'); diff --git a/bluebird-retry/bluebird-retry-tests.ts b/bluebird-retry/bluebird-retry-tests.ts index 5d8c32dfcb..e42b5457df 100644 --- a/bluebird-retry/bluebird-retry-tests.ts +++ b/bluebird-retry/bluebird-retry-tests.ts @@ -1,5 +1,5 @@ /// -/// +/// import Promise = require('bluebird'); import retry = require('bluebird-retry'); @@ -32,4 +32,4 @@ var options:retry.Options = { interval: 500 }; -retry(logFail, options); \ No newline at end of file +retry(logFail, options); diff --git a/bluebird-retry/bluebird-retry.d.ts b/bluebird-retry/bluebird-retry.d.ts index 1210bf3b53..b63a3cf131 100644 --- a/bluebird-retry/bluebird-retry.d.ts +++ b/bluebird-retry/bluebird-retry.d.ts @@ -3,7 +3,7 @@ // Definitions by: Pascal Vomhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "bluebird-retry" { import Promise = require('bluebird'); diff --git a/bluebird/bluebird-2.0-tests.ts b/bluebird/bluebird-2.0-tests.ts new file mode 100644 index 0000000000..3a8ddaa383 --- /dev/null +++ b/bluebird/bluebird-2.0-tests.ts @@ -0,0 +1,1404 @@ +/// + +// Tests by: Bart van der Schoor + +// Note: replicate changes to all overloads in both definition and test file +// Note: keep both static and instance members inline (so similar) + +// Note: try to maintain the ordering and separators, and keep to the pattern + +var obj: Object; +var bool: boolean; +var num: number; +var str: string; +var err: Error; +var x: any; +var f: Function; +var func: Function; +var arr: any[]; +var exp: RegExp; +var anyArr: any[]; +var strArr: string[]; +var numArr: number[]; +var voidVar: void; + +// - - - - - - - - - - - - - - - - - + +var value: any; +var reason: any; +var insanity: any; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +interface Foo { + foo(): string; +} +interface Bar { + bar(): string; +} +interface Baz { + baz(): string; +} + +// - - - - - - - - - - - - - - - - - + +interface StrFooMap { + [key:string]:Foo; +} + +interface StrBarMap { + [key:string]:Bar; +} + +// - - - - - - - - - - - - - - - - - + +interface StrFooArrMap { + [key:string]:Foo[]; +} + +interface StrBarArrMap { + [key:string]:Bar[]; +} + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var foo: Foo; +var bar: Bar; +var baz: Baz; + +var fooArr: Foo[]; +var barArr: Bar[]; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var numProm: Promise; +var strProm: Promise; +var anyProm: Promise; +var boolProm: Promise; +var objProm: Promise; +var voidProm: Promise; + +var fooProm: Promise; +var barProm: Promise; +var fooOrBarProm: Promise; +var bazProm: Promise; + +// - - - - - - - - - - - - - - - - - + +var numThen: PromiseLike; +var strThen: PromiseLike; +var anyThen: PromiseLike; +var boolThen: PromiseLike; +var objThen: PromiseLike; +var voidThen: PromiseLike; + +var fooThen: PromiseLike; +var barThen: PromiseLike; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var numArrProm: Promise; +var strArrProm: Promise; +var anyArrProm: Promise; + +var fooArrProm: Promise; +var barArrProm: Promise; + +// - - - - - - - - - - - - - - - - - + +var numArrThen: PromiseLike; +var strArrThen: PromiseLike; +var anyArrThen: PromiseLike; + +var fooArrThen: PromiseLike; +var barArrThen: PromiseLike; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var numPromArr: Promise[]; +var strPromArr: Promise[]; +var anyPromArr: Promise[]; + +var fooPromArr: Promise[]; +var barPromArr: Promise[]; + +// - - - - - - - - - - - - - - - - - + +var numThenArr: PromiseLike[]; +var strThenArr: PromiseLike[]; +var anyThenArr: PromiseLike[]; + +var fooThenArr: PromiseLike[]; +var barThenArr: PromiseLike[]; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// booya! +var fooThenArrThen: PromiseLike[]>; +var barThenArrThen: PromiseLike[]>; + +var fooResolver: Promise.Resolver; +var barResolver: Promise.Resolver; + +var fooInspection: Promise.Inspection; +var barInspection: Promise.Inspection; + +var fooInspectionArrProm: Promise[]>; +var barInspectionArrProm: Promise[]>; + +var BlueBird: typeof Promise; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var nodeCallbackFunc = (callback: (err: any, result: string) => void) => {} +var nodeCallbackFuncErrorOnly = (callback: (err: any) => void) => {} + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooThen = fooProm; +barThen = barProm; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = new Promise((resolve: (value: Foo) => void, reject: (reason: any) => void) => { + if (bool) { + resolve(foo); + } + else { + reject(new Error(str)); + } +}); +fooProm = new Promise((resolve: (value: Foo) => void) => { + if (bool) { + resolve(foo); + } +}); + +// - - - - - - - - - - - - - - - - - - - - - - - + +// needs a hint when used untyped? +fooProm = new Promise((resolve, reject) => { + if (bool) { + resolve(fooThen); + } + else { + reject(new Error(str)); + } +}); +fooProm = new Promise((resolve) => { + resolve(fooThen); +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooResolver.resolve(foo); + +fooResolver.reject(err); + +fooResolver.progress(bar); + +fooResolver.callback = (err: any, value: Foo) => { + +}; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +bool = fooInspection.isFulfilled(); + +bool = fooInspection.isRejected(); + +bool = fooInspection.isPending(); + +foo = fooInspection.value(); + +x = fooInspection.reason(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.then((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}, (note: any) => { + return bar; +}); +barProm = fooProm.then((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}); +barProm = fooProm.then((value: Foo) => { + return bar; +}, (reason: any) => { + return barProm; +}); +barProm = fooProm.then((value: Foo) => { + return bar; +}, (reason: any) => { + return; +}); +barProm = fooProm.then((value: Foo) => { + return bar; +}, (reason: any) => { + return voidProm; +}); +barProm = fooProm.then((value: Foo) => { + return bar; +}); +barProm = barProm.then((value: Bar) => { + if (value) return value; + var b:Bar; + return Promise.resolve(b); +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.catch((reason: any) => { + return; +}); + +fooProm = fooProm.caught((reason: any) => { + return; +}); +fooProm = fooProm.catch((error: any) => { + return true; +}, (reason: any) => { + return; +}); +fooProm = fooProm.caught((error: any) => { + return true; +}, (reason: any) => { + return; +}); + +fooProm = fooProm.catch((reason: any) => { + return voidProm; +}); + +fooProm = fooProm.caught((reason: any) => { + return voidProm; +}); +fooProm = fooProm.catch((error: any) => { + return true; +}, (reason: any) => { + return voidProm; +}); +fooProm = fooProm.caught((error: any) => { + return true; +}, (reason: any) => { + return voidProm; +}); + +fooProm = fooProm.catch((reason: any) => { + //handle multiple valid return types simultaneously + if (foo === null) { + return; + } else if (!reason) { + return voidProm; + } else if (foo) { + return foo; + } +}); + +fooOrBarProm = fooProm.catch((reason: any) => { + return bar; +}); +fooOrBarProm = fooProm.caught((reason: any) => { + return bar; +}); + +fooOrBarProm = fooProm.catch((error: any) => { + return true; +}, (reason: any) => { + return bar; +}); +fooOrBarProm = fooProm.caught((error: any) => { + return true; +}, (reason: any) => { + return bar; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.catch(Error, (reason: any) => { + return; +}); +fooProm = fooProm.catch(Promise.CancellationError, (reason: any) => { + return; +}); +fooProm = fooProm.caught(Error, (reason: any) => { + return; +}); +fooProm = fooProm.caught(Promise.CancellationError, (reason: any) => { + return; +}); + +fooOrBarProm = fooProm.catch(Error, (reason: any) => { + return bar; +}); +fooOrBarProm = fooProm.catch(Promise.CancellationError, (reason: any) => { + return bar; +}); +fooOrBarProm = fooProm.caught(Error, (reason: any) => { + return bar; +}); +fooOrBarProm = fooProm.caught(Promise.CancellationError, (reason: any) => { + return bar; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.error((reason: any) => { + return bar; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.finally(() => { + // non-Thenable return is ignored + return "foo"; +}); +fooProm = fooProm.finally(() => { + return fooThen; +}); +fooProm = fooProm.finally(() => { + // non-Thenable return is ignored +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.lastly(() => { + // non-Thenable return is ignored + return "foo"; +}); +fooProm = fooProm.lastly(() => { + return fooThen; +}); +fooProm = fooProm.lastly(() => { + // non-Thenable return is ignored +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.bind(obj); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +voidVar = fooProm.done((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}, (note: any) => { + +}); +voidVar = fooProm.done((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}); +voidVar = fooProm.done((value: Foo) => { + return bar; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +voidVar = fooProm.done((value: Foo) => { + return barThen; +}, (reason: any) => { + return barThen; +}, (note: any) => { + +}); +voidVar = fooProm.done((value: Foo) => { + return barThen; +}, (reason: any) => { + return barThen; +}); +voidVar = fooProm.done((value: Foo) => { + return barThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.tap((value: Foo) => { + // non-Thenable return is ignored + return "foo"; +}); +fooProm = fooProm.tap((value: Foo) => { + return fooThen; +}); +fooProm = fooProm.tap((value: Foo) => { + return voidThen; +}); +fooProm = fooProm.tap(() => { + // non-Thenable return is ignored +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.progressed((note: any) => { + return foo; +}); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.delay(num); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.timeout(num); +fooProm = fooProm.timeout(num, str); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm.nodeify(); +fooProm = fooProm.nodeify((err: any) => { }); +fooProm = fooProm.nodeify((err: any, foo?: Foo) => { }); + +fooProm.nodeify({ spread: true }); +fooProm = fooProm.nodeify((err: any) => { }, { spread: true }); +fooProm = fooProm.nodeify((err: any, foo?: Foo) => { }, { spread: true }); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.fork((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}, (note: any) => { + +}); +barProm = fooProm.fork((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}); +barProm = fooProm.fork((value: Foo) => { + return bar; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.fork((value: Foo) => { + return barThen; +}, (reason: any) => { + return barThen; +}, (note: any) => { + +}); +barProm = fooProm.fork((value: Foo) => { + return barThen; +}, (reason: any) => { + return barThen; +}); +barProm = fooProm.fork((value: Foo) => { + return barThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.cancel(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.cancellable(); +fooProm = fooProm.uncancellable(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +bool = fooProm.isCancellable(); +bool = fooProm.isFulfilled(); +bool = fooProm.isRejected(); +bool = fooProm.isPending(); +bool = fooProm.isResolved(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooInspection = fooProm.inspect(); + +anyProm = fooProm.call(str); +anyProm = fooProm.call(str, 1, 2, 3); + +//TODO enable get() test when implemented +// barProm = fooProm.get(str); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.return(bar); +barProm = fooProm.thenReturn(bar); + +voidProm = fooProm.return(); +voidProm = fooProm.thenReturn(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooProm +fooProm = fooProm.throw(err); +fooProm = fooProm.thenThrow(err); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +str = fooProm.toString(); + +obj = fooProm.toJSON(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooArrProm.spread((one: Foo, two: Bar) => { + return bar; +}, (reason: any) => { + return bar; +}); +barProm = fooArrProm.spread((one: Foo, two: Bar, twotwo: Foo) => { + return bar; +}); + +// - - - - - - - - - - - - - - - - - + +barProm = fooArrProm.spread((one: Foo, two: Bar) => { + return barThen; +}, (reason: any) => { + return barThen; +}); +barProm = fooArrProm.spread((one: Foo, two: Bar, twotwo: Foo) => { + return barThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO fix collection inference + +barArrProm = fooProm.all(); + +objProm = fooProm.props(); + +barInspectionArrProm = fooProm.settle(); + +barProm = fooProm.any(); + +barArrProm = fooProm.some(num); + +barProm = fooProm.race(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +Promise.all([fooProm, barProm]).then(result => { + result[0].foo(); + result[1].bar(); +}); + +Promise.all([fooProm, fooProm]).then(result => { + result[0].foo(); + result[1].foo(); +}); + +Promise.all([fooProm, barProm, bazProm]).then(result => { + result[0].foo(); + result[1].bar(); + result[2].baz(); +}); + +Promise.all([fooProm, barProm, fooProm]).then(result => { + result[0].foo(); + result[1].bar(); + result[2].foo(); +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO fix collection inference + +barArrProm = fooArrProm.map((item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = fooArrProm.map((item: Foo) => { + return bar; +}); + +barArrProm = fooArrProm.map((item: Foo, index: number, arrayLength: number) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = fooArrProm.map((item: Foo) => { + return bar; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barArrProm = fooArrProm.mapSeries((item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = fooArrProm.mapSeries((item: Foo) => { + return bar; +}); + + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooArrProm.reduce((memo: Bar, item: Foo, index: number, arrayLength: number) => { + return memo; +}); +barProm = fooArrProm.reduce((memo: Bar, item: Foo) => { + return memo; +}, bar); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooArrProm = fooArrProm.filter((item: Foo, index: number, arrayLength: number) => { + return bool; +}); +fooArrProm = fooArrProm.filter((item: Foo) => { + return bool; +}); + +fooArrProm = fooArrProm.filter((item: Foo, index: number, arrayLength: number) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = fooArrProm.filter((item: Foo) => { + return bool; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooArrProm = fooArrProm.each((item: Foo): Bar => bar); +fooArrProm = fooArrProm.each((item: Foo, index: number): Bar => index ? bar : null); +fooArrProm = fooArrProm.each((item: Foo, index: number, arrayLength: number): Bar => bar); +fooArrProm = fooArrProm.each((item: Foo, index: number, arrayLength: number): Promise => barProm); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +function getMaybePromise(): Foo|Promise { + return foo; +} + +fooProm = Promise.try(() => { + return getMaybePromise(); +}); +fooProm = Promise.try(() => { + return getMaybePromise(); +}); +fooProm = Promise.try(() => { + return foo; +}); +fooProm = Promise.try(() => { + return foo; +}, arr); +fooProm = Promise.try(() => { + return foo; +}, arr, x); + +// - - - - - - - - - - - - - - - - - + +fooProm = Promise.try(() => { + return fooThen; +}); +fooProm = Promise.try(() => { + return fooThen; +}, arr); +fooProm = Promise.try(() => { + return fooThen; +}, arr, x); + +// - - - - - - - - - - - - - - - - - + +fooProm = Promise.try(() => { + if (fooProm) { + return fooProm; + } + return foo; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = Promise.attempt(() => { + return getMaybePromise(); +}); +fooProm = Promise.attempt(() => { + return getMaybePromise(); +}); +fooProm = Promise.attempt(() => { + return foo; +}); +fooProm = Promise.attempt(() => { + return foo; +}, arr); +fooProm = Promise.attempt(() => { + return foo; +}, arr, x); + +// - - - - - - - - - - - - - - - - - + +fooProm = Promise.attempt(() => { + if (fooProm) { + return fooProm; + } + return foo; +}); + +// - - - - - - - - - - - - - - - - - + +fooProm = Promise.attempt(() => { + return fooThen; +}); +fooProm = Promise.attempt(() => { + return fooThen; +}, arr); +fooProm = Promise.attempt(() => { + return fooThen; +}, arr, x); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +func = Promise.method(function () { + +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = Promise.resolve(foo); +fooProm = Promise.resolve(fooThen); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +voidProm = Promise.reject(reason); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooResolver = Promise.defer(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = Promise.cast(foo); +fooProm = Promise.cast(fooThen); + +voidProm = Promise.bind(x); + +bool = Promise.is(value); + +Promise.longStackTraces(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO enable delay + +fooProm = Promise.delay(num, fooThen); +fooProm = Promise.delay(num, foo); +voidProm = Promise.delay(num); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +func = Promise.promisify(f); +func = Promise.promisify(f, obj); + +obj = Promise.promisifyAll(obj); +anyProm = Promise.fromNode(callback => nodeCallbackFunc(callback)); +anyProm = Promise.fromNode(callback => nodeCallbackFuncErrorOnly(callback)); +anyProm = Promise.fromNode(callback => nodeCallbackFunc(callback), {multiArgs : true}); +anyProm = Promise.fromNode(callback => nodeCallbackFuncErrorOnly(callback), {multiArgs : true}); + +anyProm = Promise.fromCallback(callback => nodeCallbackFunc(callback)); +anyProm = Promise.fromCallback(callback => nodeCallbackFuncErrorOnly(callback)); +anyProm = Promise.fromCallback(callback => nodeCallbackFunc(callback), {multiArgs : true}); +anyProm = Promise.fromCallback(callback => nodeCallbackFuncErrorOnly(callback), {multiArgs : true}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +declare var util: any; + +function defaultFilter(name: string, func: Function) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + !util.isClass(func); +} + +function DOMPromisifier(originalMethod: Function) { + // return a function + return function promisified() { + var args = [].slice.call(arguments); + // Needed so that the original method can be called with the correct receiver + var self = this; + // which returns a promise + return new Promise(function(resolve, reject) { + args.push(resolve, reject); + originalMethod.apply(self, args); + }); + }; +} + +obj = Promise.promisifyAll(obj, { + suffix: "", + filter: defaultFilter, + promisifier: DOMPromisifier +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO enable generator +/* + func = Promise.coroutine(f); + + barProm = Promise.spawn(f); + */ +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +BlueBird = Promise.noConflict(); + +Promise.onPossiblyUnhandledRejection((reason: any) => { + +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO expand tests to overloads +fooArrProm = Promise.all(fooThenArrThen); +fooArrProm = Promise.all(fooArrProm); +fooArrProm = Promise.all(fooThenArr); +fooArrProm = Promise.all(fooArr); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +objProm = Promise.props(objProm); +objProm = Promise.props(obj); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO expand tests to overloads +fooInspectionArrProm = Promise.settle(fooThenArrThen); +fooInspectionArrProm = Promise.settle(fooArrProm); +fooInspectionArrProm = Promise.settle(fooThenArr); +fooInspectionArrProm = Promise.settle(fooArr); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO expand tests to overloads +fooProm = Promise.any(fooThenArrThen); +fooProm = Promise.any(fooArrProm); +fooProm = Promise.any(fooThenArr); +fooProm = Promise.any(fooArr); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO expand tests to overloads +fooProm = Promise.race(fooThenArrThen); +fooProm = Promise.race(fooArrProm); +fooProm = Promise.race(fooThenArr); +fooProm = Promise.race(fooArr); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO expand tests to overloads +fooArrProm = Promise.some(fooThenArrThen, num); +fooArrProm = Promise.some(fooArrThen, num); +fooArrProm = Promise.some(fooThenArr, num); +fooArrProm = Promise.some(fooArr, num); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooArrProm = Promise.join(foo, foo, foo); +fooArrProm = Promise.join(fooThen, fooThen, fooThen); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// map() + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArrThen + +barArrProm = Promise.map(fooThenArrThen, (item: Foo) => { + return bar; +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + +barArrProm = Promise.map(fooThenArrThen, (item: Foo) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo) => { + return barThen; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}, { + concurrency: 1 +}); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArrThen + +barArrProm = Promise.map(fooArrThen, (item: Foo) => { + return bar; +}); +barArrProm = Promise.map(fooArrThen, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + +barArrProm = Promise.map(fooArrThen, (item: Foo) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArrThen, (item: Foo) => { + return barThen; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArr + +barArrProm = Promise.map(fooThenArr, (item: Foo) => { + return bar; +}); +barArrProm = Promise.map(fooThenArr, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + +barArrProm = Promise.map(fooThenArr, (item: Foo) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArr, (item: Foo) => { + return barThen; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArr + +barArrProm = Promise.map(fooArr, (item: Foo) => { + return bar; +}); +barArrProm = Promise.map(fooArr, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.map(fooArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.map(fooArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + +barArrProm = Promise.map(fooArr, (item: Foo) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArr, (item: Foo) => { + return barThen; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// mapSeries() + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArrThen + +barArrProm = Promise.mapSeries(fooThenArrThen, (item: Foo) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooThenArrThen, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.mapSeries(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArrThen + +barArrProm = Promise.mapSeries(fooArrThen, (item: Foo) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooArrThen, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.mapSeries(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArr + +barArrProm = Promise.mapSeries(fooThenArr, (item: Foo) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooThenArr, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.mapSeries(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArr + +barArrProm = Promise.mapSeries(fooArr, (item: Foo) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooArr, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.mapSeries(fooArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// reduce() + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArrThen + +barProm = Promise.reduce(fooThenArrThen, (memo: Bar, item: Foo) => { + return memo; +}, bar); +barProm = Promise.reduce(fooThenArrThen, (memo: Bar, item: Foo) => { + return barThen; +}, bar); +barProm = Promise.reduce(fooThenArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return memo; +}, bar); +barProm = Promise.reduce(fooThenArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return barThen; +}, bar); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArrThen + +barProm = Promise.reduce(fooArrThen, (memo: Bar, item: Foo) => { + return memo; +}, bar); +barProm = Promise.reduce(fooArrThen, (memo: Bar, item: Foo) => { + return barThen; +}, bar); +barProm = Promise.reduce(fooArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return memo; +}, bar); +barProm = Promise.reduce(fooArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return barThen; +}, bar); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArr + +barProm = Promise.reduce(fooThenArr, (memo: Bar, item: Foo) => { + return memo; +}, bar); +barProm = Promise.reduce(fooThenArr, (memo: Bar, item: Foo) => { + return barThen; +}, bar); +barProm = Promise.reduce(fooThenArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return memo; +}, bar); +barProm = Promise.reduce(fooThenArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return barThen; +}, bar); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArr + +barProm = Promise.reduce(fooArr, (memo: Bar, item: Foo) => { + return memo; +}, bar); +barProm = Promise.reduce(fooArr, (memo: Bar, item: Foo) => { + return barThen; +}, bar); +barProm = Promise.reduce(fooArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return memo; +}, bar); +barProm = Promise.reduce(fooArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return barThen; +}, bar); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// filter() + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArrThen + +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo) => { + return bool; +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo) => { + return boolThen; +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return bool; +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}); + +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo) => { + return boolThen; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArrThen + +fooArrProm = Promise.filter(fooArrThen, (item: Foo) => { + return bool; +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo) => { + return boolThen; +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return bool; +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}); + +fooArrProm = Promise.filter(fooArrThen, (item: Foo) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo) => { + return boolThen; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArr + +fooArrProm = Promise.filter(fooThenArr, (item: Foo) => { + return bool; +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo) => { + return boolThen; +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return bool; +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}); + +fooArrProm = Promise.filter(fooThenArr, (item: Foo) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo) => { + return boolThen; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArr + +fooArrProm = Promise.filter(fooArr, (item: Foo) => { + return bool; +}); +fooArrProm = Promise.filter(fooArr, (item: Foo) => { + return boolThen; +}); +fooArrProm = Promise.filter(fooArr, (item: Foo, index: number, arrayLength: number) => { + return bool; +}); +fooArrProm = Promise.filter(fooArr, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}); + +fooArrProm = Promise.filter(fooArr, (item: Foo) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArr, (item: Foo) => { + return boolThen; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArr, (item: Foo, index: number, arrayLength: number) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArr, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}, { + concurrency: 1 +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// each() + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArrThen + +fooArrThen = Promise.each(fooThenArrThen, (item: Foo) => bar); +fooArrThen = Promise.each(fooThenArrThen, (item: Foo) => barThen); +fooArrThen = Promise.each(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => bar); +fooArrThen = Promise.each(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => barThen); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArrThen + +fooArrThen = Promise.each(fooArrThen, (item: Foo) => bar); +fooArrThen = Promise.each(fooArrThen, (item: Foo) => barThen); +fooArrThen = Promise.each(fooArrThen, (item: Foo, index: number, arrayLength: number) => bar); +fooArrThen = Promise.each(fooArrThen, (item: Foo, index: number, arrayLength: number) => barThen); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArr + +fooArrThen = Promise.each(fooThenArr, (item: Foo) => bar); +fooArrThen = Promise.each(fooThenArr, (item: Foo) => barThen); +fooArrThen = Promise.each(fooThenArr, (item: Foo, index: number, arrayLength: number) => bar); +fooArrThen = Promise.each(fooThenArr, (item: Foo, index: number, arrayLength: number) => barThen); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArr + +fooArrThen = Promise.each(fooArr, (item: Foo) => bar); +fooArrThen = Promise.each(fooArr, (item: Foo) => barThen); +fooArrThen = Promise.each(fooArr, (item: Foo, index: number, arrayLength: number) => bar); +fooArrThen = Promise.each(fooArr, (item: Foo, index: number, arrayLength: number) => barThen); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/bluebird/bluebird-2.0.d.ts b/bluebird/bluebird-2.0.d.ts new file mode 100644 index 0000000000..34659859cb --- /dev/null +++ b/bluebird/bluebird-2.0.d.ts @@ -0,0 +1,773 @@ +// Type definitions for bluebird 2.0.0 +// Project: https://github.com/petkaantonov/bluebird +// Definitions by: Bart van der Schoor , falsandtru +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// ES6 model with generics overload was sourced and trans-multiplied from es6-promises.d.ts +// By: Campredon + +// Warning: recommended to use `tsc > v0.9.7` (critical bugs in earlier generic code): +// - https://github.com/DefinitelyTyped/DefinitelyTyped/issues/1563 + +// Note: replicate changes to all overloads in both definition and test file +// Note: keep both static and instance members inline (so similar) + +// TODO fix remaining TODO annotations in both definition and test + +// TODO verify support to have no return statement in handlers to get a Promise (more overloads?) + +declare var Promise: PromiseConstructor; + +interface PromiseCancelHandlerSetter { + (handler: () => void): void; +} + +interface PromiseConstructor { + /** + * Create a new promise. The passed in function will receive functions + * `resolve` and `reject` as its arguments which can be called to seal the + * fate of the created promise. + * + * If configured appropriately, it will also receive an `onCancel` + * function that can be used to configure a promise cancellation handler. + */ + new (callback: ( + resolve: (thenableOrResult?: T | PromiseLike) => void, + reject: (error: any) => void, + onCancel?: PromiseCancelHandlerSetter + ) => void): Promise; + + config(options: { + warnings?: boolean | {wForgottenReturn?: boolean}; + longStackTraces?: boolean; + cancellation?: boolean; + monitoring?: boolean; + }): void; + + // Ideally, we'd define e.g. "export class RangeError extends Error {}", + // but as Error is defined as an interface (not a class), TypeScript doesn't + // allow extending Error, only implementing it. + // However, if we want to catch() only a specific error type, we need to pass + // a constructor function to it. So, as a workaround, we define them here as such. + RangeError(): RangeError; + CancellationError(): Promise.CancellationError; + TimeoutError(): Promise.TimeoutError; + TypeError(): Promise.TypeError; + RejectionError(): Promise.RejectionError; + OperationalError(): Promise.OperationalError; + + /** + * Changes how bluebird schedules calls a-synchronously. + * + * @param scheduler Should be a function that asynchronously schedules + * the calling of the passed in function + */ + setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void; + + /** + * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. + * + * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. + * + * Alias for `attempt();` for compatibility with earlier ECMAScript version. + */ + try(fn: () => T | PromiseLike, args?: any[], ctx?: any): Promise; + + attempt(fn: () => T | PromiseLike, args?: any[], ctx?: any): Promise; + + /** + * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. + * This method is convenient when a function can sometimes return synchronously or throw synchronously. + */ + method(fn: Function): Function; + + /** + * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. + */ + resolve(value: T | PromiseLike): Promise; + resolve(): Promise; + + /** + * Create a promise that is rejected with the given `reason`. + */ + reject(reason: any): Promise; + reject(reason: any): Promise; + + /** + * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution). + */ + defer(): Promise.Resolver; + + /** + * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. + */ + cast(value: T | PromiseLike): Promise; + + /** + * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. + */ + bind(thisArg: any): Promise; + + /** + * See if `value` is a trusted Promise. + */ + is(value: any): boolean; + + /** + * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. + */ + longStackTraces(): void; + + /** + * Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise. + */ + // TODO enable more overloads + delay(ms: number, value: T | PromiseLike): Promise; + delay(ms: number): Promise; + + /** + * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. + * + * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. + * + * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. + */ + promisify(func: (callback: (err: any, result: T) => void) => void, receiver?: any): () => Promise; + promisify(func: (arg1: A1, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1) => Promise; + promisify(func: (arg1: A1, arg2: A2, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2) => Promise; + promisify(func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3) => Promise; + promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Promise; + promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Promise; + promisify(nodeFunction: Function, receiver?: any): Function; + + /** + * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. + * + * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. + */ + // TODO how to model promisifyAll? + promisifyAll(target: Object, options?: Promise.PromisifyAllOptions): any; + + + /** + * Returns a promise that is resolved by a node style callback function. + */ + fromNode(resolver: (callback: (err: any, result?: any) => void) => void, options? : {multiArgs? : boolean}): Promise; + fromCallback(resolver: (callback: (err: any, result?: any) => void) => void, options? : {multiArgs? : boolean}): Promise; + + /** + * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + */ + // TODO fix coroutine GeneratorFunction + coroutine(generatorFunction: Function): Function; + + /** + * Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + */ + // TODO fix spawn GeneratorFunction + spawn(generatorFunction: Function): Promise; + + /** + * This is relevant to browser environments with no module loader. + * + * Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else. + */ + noConflict(): typeof Promise; + + /** + * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. + * + * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. + */ + onPossiblyUnhandledRejection(handler: (reason: any) => any): void; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. + */ + // TODO enable more overloads + // promise of array with promises of value + all(values: PromiseLike[]>): Promise; + // promise of array with values + all(values: PromiseLike): Promise; + // array with promises of value + all(values: PromiseLike[]): Promise; + // array with promises of different types + all(values: [PromiseLike, PromiseLike, PromiseLike, PromiseLike, PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + all(values: [PromiseLike, PromiseLike, PromiseLike, PromiseLike]): Promise<[T1, T2, T3, T4]>; + all(values: [PromiseLike, PromiseLike, PromiseLike]): Promise<[T1, T2, T3]>; + all(values: [PromiseLike, PromiseLike]): Promise<[T1, T2]>; + // array with values + all(values: T[]): Promise; + + /** + * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. + * + * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. + * + * *The original object is not modified.* + */ + // TODO verify this is correct + // trusted promise for object + props(object: Promise): Promise; + // object + props(object: Object): Promise; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``PromiseInspection`` instances at respective positions in relation to the input array. + * + * *original: The array is not modified. The input array sparsity is retained in the resulting array.* + */ + // promise of array with promises of value + settle(values: PromiseLike[]>): Promise[]>; + // promise of array with values + settle(values: PromiseLike): Promise[]>; + // array with promises of value + settle(values: PromiseLike[]): Promise[]>; + // array with values + settle(values: T[]): Promise[]>; + + /** + * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. + */ + // promise of array with promises of value + any(values: PromiseLike[]>): Promise; + // promise of array with values + any(values: PromiseLike): Promise; + // array with promises of value + any(values: PromiseLike[]): Promise; + // array with values + any(values: T[]): Promise; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. + * + * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. + */ + // promise of array with promises of value + race(values: PromiseLike[]>): Promise; + // promise of array with values + race(values: PromiseLike): Promise; + // array with promises of value + race(values: PromiseLike[]): Promise; + // array with values + race(values: T[]): Promise; + + /** + * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. + * + * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + some(values: PromiseLike[]>, count: number): Promise; + // promise of array with values + some(values: PromiseLike, count: number): Promise; + // array with promises of value + some(values: PromiseLike[], count: number): Promise; + // array with values + some(values: T[], count: number): Promise; + + /** + * Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments. + */ + // variadic array with promises of value + join(...values: PromiseLike[]): Promise; + // variadic array with values + join(...values: T[]): Promise; + + /** + * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + map(values: PromiseLike[]>, mapper: (item: T, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; + + // promise of array with values + map(values: PromiseLike, mapper: (item: T, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; + + // array with promises of value + map(values: PromiseLike[], mapper: (item: T, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; + + // array with values + map(values: T[], mapper: (item: T, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; + + /** + * Similar to `map` with concurrency set to 1 but guaranteed to execute in sequential order + * + * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + mapSeries(values: PromiseLike[]>, mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; + + // promise of array with values + mapSeries(values: PromiseLike, mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; + + // array with promises of value + mapSeries(values: PromiseLike[], mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; + + // array with values + mapSeries(values: R[], mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; + + + /** + * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + * + * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* + */ + // promise of array with promises of value + reduce(values: PromiseLike[]>, reducer: (total: U, current: T, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; + + // promise of array with values + reduce(values: PromiseLike, reducer: (total: U, current: T, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; + + // array with promises of value + reduce(values: PromiseLike[], reducer: (total: U, current: T, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; + + // array with values + reduce(values: T[], reducer: (total: U, current: T, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; + + /** + * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. + * + * *The original array is not modified. + */ + // promise of array with promises of value + filter(values: PromiseLike[]>, filterer: (item: T, index: number, arrayLength: number) => boolean | PromiseLike, option?: Promise.ConcurrencyOption): Promise; + + // promise of array with values + filter(values: PromiseLike, filterer: (item: T, index: number, arrayLength: number) => boolean | PromiseLike, option?: Promise.ConcurrencyOption): Promise; + + // array with promises of value + filter(values: PromiseLike[], filterer: (item: T, index: number, arrayLength: number) => boolean | PromiseLike, option?: Promise.ConcurrencyOption): Promise; + + // array with values + filter(values: T[], filterer: (item: T, index: number, arrayLength: number) => boolean | PromiseLike, option?: Promise.ConcurrencyOption): Promise; + + /** + * Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (item, index, value) where item is the resolved value of a respective promise in the input array. Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well. + * + * Resolves to the original array unmodified, this method is meant to be used for side effects. If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + */ + // promise of array with promises of value + each(values: PromiseLike[]>, iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; + // array with promises of value + each(values: PromiseLike[], iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; + // array with values OR promise of array with values + each(values: T[] | PromiseLike, iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; +} + +interface Promise extends PromiseLike, Promise.Inspection { + /** + * Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. + */ + then(onFulfill: (value: T) => U | PromiseLike, onReject?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): Promise; + then(onFulfill: (value: T) => U | PromiseLike, onReject?: (error: any) => void | PromiseLike, onProgress?: (note: any) => any): Promise; + + /** + * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch(onReject?: (error: any) => T | PromiseLike | void | PromiseLike): Promise; + caught(onReject?: (error: any) => T | PromiseLike | void | PromiseLike): Promise; + + catch(onReject?: (error: any) => U | PromiseLike): Promise; + caught(onReject?: (error: any) => U | PromiseLike): Promise; + + /** + * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. + * + * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch(predicate: (error: any) => boolean, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; + caught(predicate: (error: any) => boolean, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; + + catch(predicate: (error: any) => boolean, onReject: (error: any) => U | PromiseLike): Promise; + caught(predicate: (error: any) => boolean, onReject: (error: any) => U | PromiseLike): Promise; + + catch(ErrorClass: Function, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; + caught(ErrorClass: Function, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; + + catch(ErrorClass: Function, onReject: (error: any) => U | PromiseLike): Promise; + caught(ErrorClass: Function, onReject: (error: any) => U | PromiseLike): Promise; + + + /** + * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. + */ + error(onReject: (reason: any) => PromiseLike): Promise; + error(onReject: (reason: any) => U): Promise; + + /** + * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. + * + * Alias `.lastly();` for compatibility with earlier ECMAScript version. + */ + finally(handler: () => U | PromiseLike): Promise; + + lastly(handler: () => U | PromiseLike): Promise; + + /** + * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. + */ + bind(thisArg: any): Promise; + + /** + * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. + */ + done(onFulfilled?: (value: T) => PromiseLike, onRejected?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): void; + done(onFulfilled?: (value: T) => U, onRejected?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): void; + + /** + * Like `.finally()`, but not called for rejections. + */ + tap(onFulFill: (value: T) => U | PromiseLike): Promise; + + /** + * Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise. + */ + progressed(handler: (note: any) => any): Promise; + + /** + * Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + delay(ms: number): Promise; + + /** + * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance. + * + * You may specify a custom error message with the `message` parameter. + */ + timeout(ms: number, message?: string): Promise; + + /** + * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. + * Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything. + */ + nodeify(callback: (err: any, value?: T) => void, options?: Promise.SpreadOption): Promise; + nodeify(...sink: any[]): Promise; + + /** + * Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise. + */ + cancellable(): Promise; + + /** + * Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending. + * + * That ancestor will then be rejected with a `CancellationError` (get a reference from `Promise.CancellationError`) object as the rejection reason. + * + * In a promise rejection handler you may check for a cancellation by seeing if the reason object has `.name === "Cancel"`. + * + * Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable. + */ + // TODO what to do with this? + cancel(reason?: any): Promise; + + /** + * Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors. + */ + fork(onFulfilled?: (value: T) => U | PromiseLike, onRejected?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): Promise; + + /** + * Create an uncancellable promise based on this promise. + */ + uncancellable(): Promise; + + /** + * See if this promise can be cancelled. + */ + isCancellable(): boolean; + + /** + * See if this `promise` has been fulfilled. + */ + isFulfilled(): boolean; + + /** + * See if this `promise` has been rejected. + */ + isRejected(): boolean; + + /** + * See if this `promise` is still defer. + */ + isPending(): boolean; + + /** + * See if this `promise` is resolved -> either fulfilled or rejected. + */ + isResolved(): boolean; + + /** + * Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet. + * + * throws `TypeError` + */ + value(): T; + + /** + * Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet. + * + * throws `TypeError` + */ + reason(): any; + + /** + * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`. + */ + inspect(): Promise.Inspection; + + /** + * This is a convenience method for doing: + * + * + * promise.then(function(obj){ + * return obj[propertyName].call(obj, arg...); + * }); + * + */ + call(propertyName: string, ...args: any[]): Promise; + + /** + * This is a convenience method for doing: + * + * + * promise.then(function(obj){ + * return obj[propertyName]; + * }); + * + */ + // TODO find way to fix get() + // get(propertyName: string): Promise; + + /** + * Convenience method for: + * + * + * .then(function() { + * return value; + * }); + * + * + * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` + * + * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. + */ + return(): Promise; + thenReturn(): Promise; + return(value: U): Promise; + thenReturn(value: U): Promise; + + /** + * Convenience method for: + * + * + * .then(function() { + * throw reason; + * }); + * + * Same limitations apply as with `.return()`. + * + * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. + */ + throw(reason: Error): Promise; + thenThrow(reason: Error): Promise; + + /** + * Convert to String. + */ + toString(): string; + + /** + * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. + */ + toJSON(): Object; + + /** + * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. + */ + // TODO how to model instance.spread()? like Q? + spread(onFulfill: Function, onReject?: (reason: any) => U | PromiseLike): Promise; + /* + // TODO or something like this? + spread(onFulfill: (...values: W[]) => PromiseLike, onReject?: (reason: any) => PromiseLike): Promise; + spread(onFulfill: (...values: W[]) => PromiseLike, onReject?: (reason: any) => U): Promise; + spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => PromiseLike): Promise; + spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise; + */ + /** + * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + all(): Promise; + + /** + * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO how to model instance.props()? + props(): Promise; + + /** + * Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + settle(): Promise[]>; + + /** + * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + any(): Promise; + + /** + * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + some(count: number): Promise; + + /** + * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + race(): Promise; + + /** + * Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + map(mapper: (item: Q, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; + + /** + * Same as `Promise.mapSeries(thisPromise, mapper)`. + */ + // TODO type inference from array-resolving promise? + mapSeries(mapper: (item: Q, index: number, arrayLength: number) => U | PromiseLike): Promise; + + /** + * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; + + /** + * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + filter(filterer: (item: U, index: number, arrayLength: number) => boolean | PromiseLike, options?: Promise.ConcurrencyOption): Promise; + + /** + * Same as calling ``Promise.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + each(iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; +} + +/** + * Don't use variable namespace such as variables, functions, and classes. + * If you use this namespace, it will conflict in es6. + */ +declare namespace Promise { + export interface RangeError extends Error { + } + export interface CancellationError extends Error { + } + export interface TimeoutError extends Error { + } + export interface TypeError extends Error { + } + export interface RejectionError extends Error { + } + export interface OperationalError extends Error { + } + + export interface ConcurrencyOption { + concurrency: number; + } + export interface SpreadOption { + spread: boolean; + } + export interface PromisifyAllOptions { + suffix?: string; + filter?: (name: string, func: Function, target?: any, passesDefaultFilter?: boolean) => boolean; + // The promisifier gets a reference to the original method and should return a function which returns a promise + promisifier?: (originalMethod: Function) => () => PromiseLike; + } + + export interface Resolver { + /** + * Returns a reference to the controlled promise that can be passed to clients. + */ + promise: Promise; + + /** + * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. + */ + resolve(value: T): void; + resolve(): void; + + /** + * Reject the underlying promise with `reason` as the rejection reason. + */ + reject(reason: any): void; + + /** + * Progress the underlying promise with `value` as the progression value. + */ + progress(value: any): void; + + /** + * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. + * + * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. + */ + // TODO specify resolver callback + callback: (err: any, value: T, ...values: T[]) => void; + } + + export interface Inspection { + /** + * See if the underlying promise was fulfilled at the creation time of this inspection object. + */ + isFulfilled(): boolean; + + /** + * See if the underlying promise was rejected at the creation time of this inspection object. + */ + isRejected(): boolean; + + /** + * See if the underlying promise was defer at the creation time of this inspection object. + */ + isPending(): boolean; + + /** + * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object. + * + * throws `TypeError` + */ + value(): T; + + /** + * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. + * + * throws `TypeError` + */ + reason(): any; + } +} + +declare module 'bluebird' { + export = Promise; +} diff --git a/bluebird/bluebird-tests.ts b/bluebird/bluebird-tests.ts index a24cdfd7ee..d7995438c1 100644 --- a/bluebird/bluebird-tests.ts +++ b/bluebird/bluebird-tests.ts @@ -7,6 +7,8 @@ // Note: try to maintain the ordering and separators, and keep to the pattern +import Promise = require("bluebird"); + var obj: Object; var bool: boolean; var num: number; @@ -80,6 +82,7 @@ var voidProm: Promise; var fooProm: Promise; var barProm: Promise; +var barOrVoidProm: Promise; var fooOrBarProm: Promise; var bazProm: Promise; @@ -141,7 +144,7 @@ var fooResolver: Promise.Resolver; var barResolver: Promise.Resolver; var fooInspection: Promise.Inspection; -var barInspection: Promise.Inspection; +var fooInspectionPromise: Promise>; var fooInspectionArrProm: Promise[]>; var barInspectionArrProm: Promise[]>; @@ -195,8 +198,6 @@ fooResolver.resolve(foo); fooResolver.reject(err); -fooResolver.progress(bar); - fooResolver.callback = (err: any, value: Foo) => { }; @@ -204,24 +205,13 @@ fooResolver.callback = (err: any, value: Foo) => { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool = fooInspection.isFulfilled(); - bool = fooInspection.isRejected(); - bool = fooInspection.isPending(); - foo = fooInspection.value(); - x = fooInspection.reason(); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -barProm = fooProm.then((value: Foo) => { - return bar; -}, (reason: any) => { - return bar; -}, (note: any) => { - return bar; -}); barProm = fooProm.then((value: Foo) => { return bar; }, (reason: any) => { @@ -232,12 +222,12 @@ barProm = fooProm.then((value: Foo) => { }, (reason: any) => { return barProm; }); -barProm = fooProm.then((value: Foo) => { +barOrVoidProm = fooProm.then((value: Foo) => { return bar; }, (reason: any) => { return; }); -barProm = fooProm.then((value: Foo) => { +barOrVoidProm = fooProm.then((value: Foo) => { return bar; }, (reason: any) => { return voidProm; @@ -384,13 +374,6 @@ fooProm = fooProm.bind(obj); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -voidVar = fooProm.done((value: Foo) => { - return bar; -}, (reason: any) => { - return bar; -}, (note: any) => { - -}); voidVar = fooProm.done((value: Foo) => { return bar; }, (reason: any) => { @@ -402,13 +385,6 @@ voidVar = fooProm.done((value: Foo) => { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -voidVar = fooProm.done((value: Foo) => { - return barThen; -}, (reason: any) => { - return barThen; -}, (note: any) => { - -}); voidVar = fooProm.done((value: Foo) => { return barThen; }, (reason: any) => { @@ -436,11 +412,6 @@ fooProm = fooProm.tap(() => { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -fooProm = fooProm.progressed((note: any) => { - return foo; -}); -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fooProm = fooProm.delay(num); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -460,52 +431,11 @@ fooProm = fooProm.nodeify((err: any, foo?: Foo) => { }, { spread: true }); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -barProm = fooProm.fork((value: Foo) => { - return bar; -}, (reason: any) => { - return bar; -}, (note: any) => { - -}); -barProm = fooProm.fork((value: Foo) => { - return bar; -}, (reason: any) => { - return bar; -}); -barProm = fooProm.fork((value: Foo) => { - return bar; -}); - -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -barProm = fooProm.fork((value: Foo) => { - return barThen; -}, (reason: any) => { - return barThen; -}, (note: any) => { - -}); -barProm = fooProm.fork((value: Foo) => { - return barThen; -}, (reason: any) => { - return barThen; -}); -barProm = fooProm.fork((value: Foo) => { - return barThen; -}); +voidVar = fooProm.cancel(); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -barProm = fooProm.cancel(); - -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -fooProm = fooProm.cancellable(); -fooProm = fooProm.uncancellable(); - -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -bool = fooProm.isCancellable(); +bool = fooProm.isCancelled(); bool = fooProm.isFulfilled(); bool = fooProm.isRejected(); bool = fooProm.isPending(); @@ -513,8 +443,6 @@ bool = fooProm.isResolved(); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -fooInspection = fooProm.inspect(); - anyProm = fooProm.call(str); anyProm = fooProm.call(str, 1, 2, 3); @@ -543,22 +471,12 @@ obj = fooProm.toJSON(); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -barProm = fooArrProm.spread((one: Foo, two: Bar) => { - return bar; -}, (reason: any) => { - return bar; -}); barProm = fooArrProm.spread((one: Foo, two: Bar, twotwo: Foo) => { return bar; }); // - - - - - - - - - - - - - - - - - -barProm = fooArrProm.spread((one: Foo, two: Bar) => { - return barThen; -}, (reason: any) => { - return barThen; -}); barProm = fooArrProm.spread((one: Foo, two: Bar, twotwo: Foo) => { return barThen; }); @@ -568,15 +486,10 @@ barProm = fooArrProm.spread((one: Foo, two: Bar, twotwo: Foo) => { //TODO fix collection inference barArrProm = fooProm.all(); - objProm = fooProm.props(); - -barInspectionArrProm = fooProm.settle(); - +fooInspectionPromise = fooProm.reflect(); barProm = fooProm.any(); - barArrProm = fooProm.some(num); - barProm = fooProm.race(); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -686,24 +599,12 @@ fooProm = Promise.try(() => { fooProm = Promise.try(() => { return foo; }); -fooProm = Promise.try(() => { - return foo; -}, arr); -fooProm = Promise.try(() => { - return foo; -}, arr, x); // - - - - - - - - - - - - - - - - - fooProm = Promise.try(() => { return fooThen; }); -fooProm = Promise.try(() => { - return fooThen; -}, arr); -fooProm = Promise.try(() => { - return fooThen; -}, arr, x); // - - - - - - - - - - - - - - - - - @@ -725,12 +626,6 @@ fooProm = Promise.attempt(() => { fooProm = Promise.attempt(() => { return foo; }); -fooProm = Promise.attempt(() => { - return foo; -}, arr); -fooProm = Promise.attempt(() => { - return foo; -}, arr, x); // - - - - - - - - - - - - - - - - - @@ -746,12 +641,6 @@ fooProm = Promise.attempt(() => { fooProm = Promise.attempt(() => { return fooThen; }); -fooProm = Promise.attempt(() => { - return fooThen; -}, arr); -fooProm = Promise.attempt(() => { - return fooThen; -}, arr, x); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -847,6 +736,7 @@ obj = Promise.promisifyAll(obj, { */ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +BlueBird = Promise.getNewLibraryCopy(); BlueBird = Promise.noConflict(); Promise.onPossiblyUnhandledRejection((reason: any) => { @@ -868,14 +758,6 @@ objProm = Promise.props(obj); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//TODO expand tests to overloads -fooInspectionArrProm = Promise.settle(fooThenArrThen); -fooInspectionArrProm = Promise.settle(fooArrProm); -fooInspectionArrProm = Promise.settle(fooThenArr); -fooInspectionArrProm = Promise.settle(fooArr); - -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //TODO expand tests to overloads fooProm = Promise.any(fooThenArrThen); fooProm = Promise.any(fooArrProm); diff --git a/bluebird/bluebird.d.ts b/bluebird/bluebird.d.ts index 4d70205a03..35b506542a 100644 --- a/bluebird/bluebird.d.ts +++ b/bluebird/bluebird.d.ts @@ -1,760 +1,775 @@ -// Type definitions for bluebird 2.0.0 +// Type definitions for bluebird 3.0.0 // Project: https://github.com/petkaantonov/bluebird -// Definitions by: Bart van der Schoor , falsandtru +// Definitions by: Leonard Hecker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// ES6 model with generics overload was sourced and trans-multiplied from es6-promises.d.ts -// By: Campredon +/*! + * The code following this comment originates from: + * https://github.com/types/npm-bluebird + * + * Licensed under: + * The MIT License (MIT) + * + * Copyright (c) 2016 unional + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ -// Warning: recommended to use `tsc > v0.9.7` (critical bugs in earlier generic code): -// - https://github.com/DefinitelyTyped/DefinitelyTyped/issues/1563 +// Generated by typings +// Source: bluebird.d.ts +declare module 'bluebird' { +// Type definitions for Bluebird v3.x.x +// Project: http://bluebirdjs.com -// Note: replicate changes to all overloads in both definition and test file -// Note: keep both static and instance members inline (so similar) +class Bluebird implements Bluebird.Thenable, Bluebird.Inspection { + /** + * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. + * If promise cancellation is enabled, passed in function will receive one more function argument `onCancel` that allows to register an optional cancellation callback. + */ + constructor(callback: (resolve: (thenableOrResult?: R | Bluebird.Thenable) => void, reject: (error?: any) => void, onCancel?: (callback: () => void) => void) => void); -// TODO fix remaining TODO annotations in both definition and test + /** + * Promises/A+ `.then()`. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. + */ + then(onFulfill: (value: R) => U1 | Bluebird.Thenable, onReject: (error: any) => U2 | Bluebird.Thenable): Bluebird; + then(onFulfill: (value: R) => U | Bluebird.Thenable, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + then(onFulfill: (value: R) => U | Bluebird.Thenable): Bluebird; + then(): Bluebird; -// TODO verify support to have no return statement in handlers to get a Promise (more overloads?) + /** + * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch(onReject?: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + caught(onReject?: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + catch(onReject?: (error: any) => U | Bluebird.Thenable): Bluebird; + caught(onReject?: (error: any) => U | Bluebird.Thenable): Bluebird; -declare var Promise: PromiseConstructor; + /** + * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. + * + * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch(predicate: (error: any) => boolean, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + caught(predicate: (error: any) => boolean, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + catch(predicate: (error: any) => boolean, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + caught(predicate: (error: any) => boolean, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + catch(ErrorClass: Function, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + caught(ErrorClass: Function, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + catch(ErrorClass: Function, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + caught(ErrorClass: Function, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + catch(predicate: Object, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + caught(predicate: Object, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + catch(predicate: Object, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + caught(predicate: Object, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; -interface PromiseConstructor { - /** - * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. - */ - new (callback: (resolve: (thenableOrResult?: T | PromiseLike) => void, reject: (error: any) => void) => void): Promise; - - config(options: { - warnings?: boolean | {wForgottenReturn?: boolean}; - longStackTraces?: boolean; - cancellation?: boolean; - monitoring?: boolean; - }): void; + /** + * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. + */ + error(onReject: (reason: any) => U | Bluebird.Thenable): Bluebird; - // Ideally, we'd define e.g. "export class RangeError extends Error {}", - // but as Error is defined as an interface (not a class), TypeScript doesn't - // allow extending Error, only implementing it. - // However, if we want to catch() only a specific error type, we need to pass - // a constructor function to it. So, as a workaround, we define them here as such. - RangeError(): RangeError; - CancellationError(): Promise.CancellationError; - TimeoutError(): Promise.TimeoutError; - TypeError(): Promise.TypeError; - RejectionError(): Promise.RejectionError; - OperationalError(): Promise.OperationalError; + /** + * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. + * + * Alias `.lastly();` for compatibility with earlier ECMAScript version. + */ + finally(handler: () => U | Bluebird.Thenable): Bluebird; - /** - * Changes how bluebird schedules calls a-synchronously. - * - * @param scheduler Should be a function that asynchronously schedules - * the calling of the passed in function - */ - setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void; + lastly(handler: () => U | Bluebird.Thenable): Bluebird; - /** - * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. - * - * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. - * - * Alias for `attempt();` for compatibility with earlier ECMAScript version. - */ - try(fn: () => T | PromiseLike, args?: any[], ctx?: any): Promise; + /** + * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. + */ + bind(thisArg: any): Bluebird; - attempt(fn: () => T | PromiseLike, args?: any[], ctx?: any): Promise; + /** + * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. + */ + done(onFulfilled?: (value: R) => U | Bluebird.Thenable, onRejected?: (error: any) => U | Bluebird.Thenable): void; - /** - * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. - * This method is convenient when a function can sometimes return synchronously or throw synchronously. - */ - method(fn: Function): Function; + /** + * Like `.finally()`, but not called for rejections. + */ + tap(onFulFill: (value: R) => Bluebird.Thenable): Bluebird; + tap(onFulfill: (value: R) => U): Bluebird; - /** - * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. - */ - resolve(value: T | PromiseLike): Promise; - resolve(): Promise; + /** + * Same as calling `Promise.delay(ms, this)`. + */ + delay(ms: number): Bluebird; - /** - * Create a promise that is rejected with the given `reason`. - */ - reject(reason: any): Promise; - reject(reason: any): Promise; + /** + * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. + * However, if this promise is not fulfilled or rejected within ms milliseconds, the returned promise + * is rejected with a TimeoutError or the error as the reason. + * + * You may specify a custom error message with the `message` parameter. + */ + timeout(ms: number, message?: string | Error): Bluebird; - /** - * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution). - */ - defer(): Promise.Resolver; + /** + * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. + * If the `callback` argument is not a function, this method does not do anything. + */ + nodeify(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this; + nodeify(...sink: any[]): this; + asCallback(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this; + asCallback(...sink: any[]): this; - /** - * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. - */ - cast(value: T | PromiseLike): Promise; + /** + * See if this `promise` has been fulfilled. + */ + isFulfilled(): boolean; - /** - * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. - */ - bind(thisArg: any): Promise; + /** + * See if this `promise` has been rejected. + */ + isRejected(): boolean; - /** - * See if `value` is a trusted Promise. - */ - is(value: any): boolean; + /** + * See if this `promise` is still defer. + */ + isPending(): boolean; - /** - * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. - */ - longStackTraces(): void; + /** + * See if this `promise` has been cancelled. + */ + isCancelled(): boolean; - /** - * Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise. - */ - // TODO enable more overloads - delay(ms: number, value: T | PromiseLike): Promise; - delay(ms: number): Promise; + /** + * See if this `promise` is resolved -> either fulfilled or rejected. + */ + isResolved(): boolean; - /** - * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. - * - * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. - * - * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. - */ - promisify(func: (callback: (err: any, result: T) => void) => void, receiver?: any): () => Promise; - promisify(func: (arg1: A1, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1) => Promise; - promisify(func: (arg1: A1, arg2: A2, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2) => Promise; - promisify(func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3) => Promise; - promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Promise; - promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Promise; - promisify(nodeFunction: Function, receiver?: any): Function; + /** + * Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet. + * + * throws `TypeError` + */ + value(): R; - /** - * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. - * - * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. - */ - // TODO how to model promisifyAll? - promisifyAll(target: Object, options?: Promise.PromisifyAllOptions): any; + /** + * Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet. + * + * throws `TypeError` + */ + reason(): any; + /** + * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of + * the promise as snapshotted at the time of calling `.reflect()`. + */ + reflect(): Bluebird>; + reflect(): Bluebird>; - /** - * Returns a promise that is resolved by a node style callback function. - */ - fromNode(resolver: (callback: (err: any, result?: any) => void) => void, options? : {multiArgs? : boolean}): Promise; - fromCallback(resolver: (callback: (err: any, result?: any) => void) => void, options? : {multiArgs? : boolean}): Promise; + /** + * This is a convenience method for doing: + * + * + * promise.then(function(obj){ + * return obj[propertyName].call(obj, arg...); + * }); + * + */ + call(propertyName: string, ...args: any[]): Bluebird; - /** - * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. - */ - // TODO fix coroutine GeneratorFunction - coroutine(generatorFunction: Function): Function; + /** + * This is a convenience method for doing: + * + * + * promise.then(function(obj){ + * return obj[propertyName]; + * }); + * + */ + // TODO: Use "type property type" once it's there + // @see https://github.com/Microsoft/TypeScript/issues/1295 + get(key: string | number): Bluebird; - /** - * Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. - */ - // TODO fix spawn GeneratorFunction - spawn(generatorFunction: Function): Promise; + /** + * Convenience method for: + * + * + * .then(function() { + * return value; + * }); + * + * + * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` + * + * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. + */ + return(): Bluebird; + thenReturn(): Bluebird; + return(value: U): Bluebird; + thenReturn(value: U): Bluebird; - /** - * This is relevant to browser environments with no module loader. - * - * Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else. - */ - noConflict(): typeof Promise; + /** + * Convenience method for: + * + * + * .then(function() { + * throw reason; + * }); + * + * Same limitations apply as with `.return()`. + * + * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. + */ + throw(reason: Error): Bluebird; + thenThrow(reason: Error): Bluebird; - /** - * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. - * - * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. - */ - onPossiblyUnhandledRejection(handler: (reason: any) => any): void; + /** + * Convert to String. + */ + toString(): string; - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. - */ - // TODO enable more overloads - // promise of array with promises of value - all(values: PromiseLike[]>): Promise; - // promise of array with values - all(values: PromiseLike): Promise; - // array with promises of value - all(values: PromiseLike[]): Promise; - // array with promises of different types - all(values: [PromiseLike, PromiseLike, PromiseLike, PromiseLike, PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; - all(values: [PromiseLike, PromiseLike, PromiseLike, PromiseLike]): Promise<[T1, T2, T3, T4]>; - all(values: [PromiseLike, PromiseLike, PromiseLike]): Promise<[T1, T2, T3]>; - all(values: [PromiseLike, PromiseLike]): Promise<[T1, T2]>; - // array with values - all(values: T[]): Promise; + /** + * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. + */ + toJSON(): Object; - /** - * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. - * - * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. - * - * *The original object is not modified.* - */ - // TODO verify this is correct - // trusted promise for object - props(object: Promise): Promise; - // object - props(object: Object): Promise; + /** + * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. + */ + spread(fulfilledHandler: (...values: W[]) => U | Bluebird.Thenable): Bluebird; + spread(fulfilledHandler: Function): Bluebird; - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``PromiseInspection`` instances at respective positions in relation to the input array. - * - * *original: The array is not modified. The input array sparsity is retained in the resulting array.* - */ - // promise of array with promises of value - settle(values: PromiseLike[]>): Promise[]>; - // promise of array with values - settle(values: PromiseLike): Promise[]>; - // array with promises of value - settle(values: PromiseLike[]): Promise[]>; - // array with values - settle(values: T[]): Promise[]>; + /** + * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + all(): Bluebird; - /** - * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. - */ - // promise of array with promises of value - any(values: PromiseLike[]>): Promise; - // promise of array with values - any(values: PromiseLike): Promise; - // array with promises of value - any(values: PromiseLike[]): Promise; - // array with values - any(values: T[]): Promise; + /** + * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO how to model instance.props()? + props(): Bluebird; - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. - * - * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. - */ - // promise of array with promises of value - race(values: PromiseLike[]>): Promise; - // promise of array with values - race(values: PromiseLike): Promise; - // array with promises of value - race(values: PromiseLike[]): Promise; - // array with values - race(values: T[]): Promise; + /** + * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + any(): Bluebird; - /** - * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. - * - * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. - * - * *The original array is not modified.* - */ - // promise of array with promises of value - some(values: PromiseLike[]>, count: number): Promise; - // promise of array with values - some(values: PromiseLike, count: number): Promise; - // array with promises of value - some(values: PromiseLike[], count: number): Promise; - // array with values - some(values: T[], count: number): Promise; + /** + * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + some(count: number): Bluebird; - /** - * Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments. - */ - // variadic array with promises of value - join(...values: PromiseLike[]): Promise; - // variadic array with values - join(...values: T[]): Promise; + /** + * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + race(): Bluebird; - /** - * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. - * - * *The original array is not modified.* - */ - // promise of array with promises of value - map(values: PromiseLike[]>, mapper: (item: T, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; + /** + * Same as calling `Bluebird.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + map(mapper: (item: Q, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; - // promise of array with values - map(values: PromiseLike, mapper: (item: T, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; + /** + * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; - // array with promises of value - map(values: PromiseLike[], mapper: (item: T, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; + /** + * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + filter(filterer: (item: U, index: number, arrayLength: number) => boolean | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; - // array with values - map(values: T[], mapper: (item: T, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; + /** + * Same as calling ``Bluebird.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + each(iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; - /** - * Similar to `map` with concurrency set to 1 but guaranteed to execute in sequential order - * - * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. - * - * *The original array is not modified.* - */ - // promise of array with promises of value - mapSeries(values: PromiseLike[]>, mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; + /** + * Same as calling ``Bluebird.mapSeries(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + mapSeries(iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; - // promise of array with values - mapSeries(values: PromiseLike, mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; + /** + * Cancel this `promise`. Will not do anything if this promise is already settled or if the cancellation feature has not been enabled + */ + cancel(): void; - // array with promises of value - mapSeries(values: PromiseLike[], mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; + /** + * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. + * + * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. + * + * Alias for `attempt();` for compatibility with earlier ECMAScript version. + */ + static try(fn: () => R | Bluebird.Thenable): Bluebird; + static attempt(fn: () => R | Bluebird.Thenable): Bluebird; - // array with values - mapSeries(values: R[], mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; - + /** + * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. + * This method is convenient when a function can sometimes return synchronously or throw synchronously. + */ + static method(fn: Function): Function; - /** - * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. - * - * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* - */ - // promise of array with promises of value - reduce(values: PromiseLike[]>, reducer: (total: U, current: T, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; + /** + * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. + */ + static resolve(): Bluebird; + static resolve(value: R | Bluebird.Thenable): Bluebird; - // promise of array with values - reduce(values: PromiseLike, reducer: (total: U, current: T, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; + /** + * Create a promise that is rejected with the given `reason`. + */ + static reject(reason: any): Bluebird; + static reject(reason: any): Bluebird; - // array with promises of value - reduce(values: PromiseLike[], reducer: (total: U, current: T, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; + /** + * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution). + */ + static defer(): Bluebird.Resolver; - // array with values - reduce(values: T[], reducer: (total: U, current: T, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; + /** + * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. + */ + static cast(value: R | Bluebird.Thenable): Bluebird; - /** - * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. - * - * *The original array is not modified. - */ - // promise of array with promises of value - filter(values: PromiseLike[]>, filterer: (item: T, index: number, arrayLength: number) => boolean | PromiseLike, option?: Promise.ConcurrencyOption): Promise; + /** + * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. + */ + static bind(thisArg: any): Bluebird; - // promise of array with values - filter(values: PromiseLike, filterer: (item: T, index: number, arrayLength: number) => boolean | PromiseLike, option?: Promise.ConcurrencyOption): Promise; + /** + * See if `value` is a trusted Promise. + */ + static is(value: any): boolean; - // array with promises of value - filter(values: PromiseLike[], filterer: (item: T, index: number, arrayLength: number) => boolean | PromiseLike, option?: Promise.ConcurrencyOption): Promise; + /** + * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. + */ + static longStackTraces(): void; - // array with values - filter(values: T[], filterer: (item: T, index: number, arrayLength: number) => boolean | PromiseLike, option?: Promise.ConcurrencyOption): Promise; + /** + * Returns a promise that will be resolved with value (or undefined) after given ms milliseconds. + * If value is a promise, the delay will start counting down when it is fulfilled and the returned + * promise will be fulfilled with the fulfillment value of the value promise. + */ + static delay(ms: number, value: R | Bluebird.Thenable): Bluebird; + static delay(ms: number): Bluebird; - /** - * Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (item, index, value) where item is the resolved value of a respective promise in the input array. Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well. - * - * Resolves to the original array unmodified, this method is meant to be used for side effects. If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. - */ - // promise of array with promises of value - each(values: PromiseLike[]>, iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; - // array with promises of value - each(values: PromiseLike[], iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; - // array with values OR promise of array with values - each(values: T[] | PromiseLike, iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; + /** + * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. + * + * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. + * + * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. + */ + static promisify(func: (callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): () => Bluebird; + static promisify(func: (arg1: A1, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1) => Bluebird; + static promisify(func: (arg1: A1, arg2: A2, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2) => Bluebird; + static promisify(func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3) => Bluebird; + static promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Bluebird; + static promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result: T) => void) => void, options?: Bluebird.PromisifyOptions): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Bluebird; + static promisify(nodeFunction: Function, options?: Bluebird.PromisifyOptions): Function; + + /** + * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. + * + * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. + */ + // TODO how to model promisifyAll? + static promisifyAll(target: Object, options?: Bluebird.PromisifyAllOptions): Object; + + /** + * Returns a promise that is resolved by a node style callback function. + */ + static fromNode(resolver: (callback: (err: any, result?: any) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; + static fromNode(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; + static fromCallback(resolver: (callback: (err: any, result?: any) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; + static fromCallback(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird; + + /** + * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + */ + // TODO fix coroutine GeneratorFunction + static coroutine(generatorFunction: Function): Function; + + /** + * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. + * + * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. + */ + static onPossiblyUnhandledRejection(handler: (reason: any) => any): void; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. + */ + // TODO enable more overloads + // array with promises of different types + static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2, Bluebird.Thenable | T3, Bluebird.Thenable | T4, Bluebird.Thenable | T5]): Bluebird<[T1, T2, T3, T4, T5]>; + static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2, Bluebird.Thenable | T3, Bluebird.Thenable | T4]): Bluebird<[T1, T2, T3, T4]>; + static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2, Bluebird.Thenable | T3]): Bluebird<[T1, T2, T3]>; + static all(values: [Bluebird.Thenable | T1, Bluebird.Thenable | T2]): Bluebird<[T1, T2]>; + static all(values: [Bluebird.Thenable | T1]): Bluebird<[T1]>; + // array with values + static all(values: Bluebird.Thenable<(Bluebird.Thenable | R)[]> | (Bluebird.Thenable | R)[]): Bluebird; + + /** + * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. + * + * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. + * + * *The original object is not modified.* + */ + // TODO verify this is correct + // trusted promise for object + static props(object: Bluebird): Bluebird; + // object + static props(object: Object): Bluebird; + + /** + * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. + */ + static any(values: Bluebird.Thenable<(Bluebird.Thenable | R)[]> | (Bluebird.Thenable | R)[]): Bluebird; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. + * + * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. + */ + static race(values: Bluebird.Thenable<(Bluebird.Thenable | R)[]> | (Bluebird.Thenable | R)[]): Bluebird; + + /** + * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. + * + * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + static some(values: Bluebird.Thenable[]>, count: number): Bluebird; + // promise of array with values + static some(values: Bluebird.Thenable, count: number): Bluebird; + // array with promises of value + static some(values: Bluebird.Thenable[], count: number): Bluebird; + // array with values + static some(values: R[], count: number): Bluebird; + + /** + * Promise.join( + * Promise|any values..., + * function handler + * ) -> Promise + * For coordinating multiple concurrent discrete promises. + * + * Note: In 1.x and 0.x Promise.join used to be a Promise.all that took the values in as arguments instead in an array. This behavior has been deprecated but is still supported partially - when the last argument is an immediate function value the new semantics will apply + */ + static join(arg1: A1 | Bluebird.Thenable, handler: (arg1?: A1) => R | Bluebird.Thenable): Bluebird; + static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, handler: (arg1?: A1, arg2?: A2) => R | Bluebird.Thenable): Bluebird; + static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, arg3: A3 | Bluebird.Thenable, handler: (arg1?: A1, arg2?: A2, arg3?: A3) => R | Bluebird.Thenable): Bluebird; + static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, arg3: A3 | Bluebird.Thenable, arg4: A4 | Bluebird.Thenable, handler: (arg1?: A1, arg2?: A2, arg3?: A3, arg4?: A4) => R | Bluebird.Thenable): Bluebird; + static join(arg1: A1 | Bluebird.Thenable, arg2: A2 | Bluebird.Thenable, arg3: A3 | Bluebird.Thenable, arg4: A4 | Bluebird.Thenable, arg5: A5 | Bluebird.Thenable, handler: (arg1?: A1, arg2?: A2, arg3?: A3, arg4?: A4, arg5?: A5) => R | Bluebird.Thenable): Bluebird; + + // variadic array + /** @deprecated use .all instead */ + static join(...values: (R | Bluebird.Thenable)[]): Bluebird; + + /** + * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + static map(values: Bluebird.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + + // promise of array with values + static map(values: Bluebird.Thenable, mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + + // array with promises of value + static map(values: Bluebird.Thenable[], mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + + // array with values + static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable, options?: Bluebird.ConcurrencyOption): Bluebird; + + /** + * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + * + * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* + */ + // promise of array with promises of value + static reduce(values: Bluebird.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + + // promise of array with values + static reduce(values: Bluebird.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + + // array with promises of value + static reduce(values: Bluebird.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + + // array with values + static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U | Bluebird.Thenable, initialValue?: U): Bluebird; + + /** + * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. + * + * *The original array is not modified. + */ + // promise of array with promises of value + static filter(values: Bluebird.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; + + // promise of array with values + static filter(values: Bluebird.Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; + + // array with promises of value + static filter(values: Bluebird.Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; + + // array with values + static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean | Bluebird.Thenable, option?: Bluebird.ConcurrencyOption): Bluebird; + + /** + * Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (item, index, value) where item is the resolved value of a respective promise in the input array. Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well. + * + * Resolves to the original array unmodified, this method is meant to be used for side effects. If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + */ + // promise of array with promises of value + static each(values: Bluebird.Thenable[]>, iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + // array with promises of value + static each(values: Bluebird.Thenable[], iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + // array with values OR promise of array with values + static each(values: R[] | Bluebird.Thenable, iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + + /** + * Given an Iterable(arrays are Iterable), or a promise of an Iterable, which produces promises (or a mix of promises and values), iterate over all the values in the Iterable into an array and iterate over the array serially, in-order. + * + * Returns a promise for an array that contains the values returned by the iterator function in their respective positions. The iterator won't be called for an item until its previous item, and the promise returned by the iterator for that item are fulfilled. This results in a mapSeries kind of utility but it can also be used simply as a side effect iterator similar to Array#forEach. + * + * If any promise in the input array is rejected or any promise returned by the iterator function is rejected, the result will be rejected as well. + */ + static mapSeries(values: (R | Bluebird.Thenable)[] | Bluebird.Thenable<(R | Bluebird.Thenable)[]>, iterator: (item: R, index: number, arrayLength: number) => U | Bluebird.Thenable): Bluebird; + + /** + * A meta method used to specify the disposer method that cleans up a resource when using `Promise.using`. + * + * Returns a Disposer object which encapsulates both the resource as well as the method to clean it up. + * The user can pass this object to `Promise.using` to get access to the resource when it becomes available, + * as well as to ensure its automatically cleaned up. + * + * The second argument passed to a disposer is the result promise of the using block, which you can + * inspect synchronously. + */ + disposer(disposeFn: (arg: R, promise: Bluebird) => void | Bluebird.Thenable): Bluebird.Disposer; + + /** + * In conjunction with `.disposer`, using will make sure that no matter what, the specified disposer + * will be called when the promise returned by the callback passed to using has settled. The disposer is + * necessary because there is no standard interface in node for disposing resources. + */ + static using(disposer: Bluebird.Disposer, executor: (transaction: R) => Bluebird.Thenable): Bluebird; + static using(disposer: Bluebird.Disposer, disposer2: Bluebird.Disposer, executor: (transaction1: R1, transaction2: R2) => Bluebird.Thenable): Bluebird; + static using(disposer: Bluebird.Disposer, disposer2: Bluebird.Disposer, disposer3: Bluebird.Disposer, executor: (transaction1: R1, transaction2: R2, transaction3: R3) => Bluebird.Thenable): Bluebird; + + /** + * Add handler as the handler to call when there is a possibly unhandled rejection. + * The default handler logs the error stack to stderr or console.error in browsers. + * + * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. + * + * Note: this hook is specific to the bluebird instance its called on, application developers should use global rejection events. + */ + static onPossiblyUnhandledRejection(handler?: (error: Error, promise: Bluebird) => void): void; + + /** + * Configure long stack traces, warnings, monitoring and cancellation. + * Note that even though false is the default here, a development environment might be detected which automatically + * enables long stack traces and warnings. + */ + static config(options: { + /** Enable warnings */ + warnings?: boolean | { + /** Enables all warnings except forgotten return statements. */ + wForgottenReturn: boolean; + }; + /** Enable long stack traces */ + longStackTraces?: boolean; + /** Enable cancellation */ + cancellation?: boolean; + /** Enable monitoring */ + monitoring?: boolean; + }): void; } -interface Promise extends PromiseLike, Promise.Inspection { +namespace Bluebird { + export interface ConcurrencyOption { + concurrency: number; + } + export interface SpreadOption { + spread: boolean; + } + export interface FromNodeOptions { + multiArgs?: boolean; + } + export interface PromisifyOptions { + context?: any; + multiArgs?: boolean; + } + export interface PromisifyAllOptions extends PromisifyOptions { + suffix?: string; + filter?: (name: string, func: Function, target?: any, passesDefaultFilter?: boolean) => boolean; + // The promisifier gets a reference to the original method and should return a function which returns a promise + promisifier?: (originalMethod: Function) => () => Thenable; + } + + /** + * Represents an error is an explicit promise rejection as opposed to a thrown error. + * For example, if an error is errbacked by a callback API promisified through undefined or undefined + * and is not a typed error, it will be converted to a `OperationalError` which has the original error in + * the `.cause` property. + * + * `OperationalError`s are caught in `.error` handlers. + */ + export class OperationalError extends Error { } + + /** + * Signals that an operation has timed out. Used as a custom cancellation reason in `.timeout`. + */ + export class TimeoutError extends Error { } + + /** + * Signals that an operation has been aborted or cancelled. The default reason used by `.cancel`. + */ + export class CancellationError extends Error {} + + /** + * A collection of errors. `AggregateError` is an array-like object, with numeric indices and a `.length` property. + * It supports all generic array methods such as `.forEach` directly. + * + * `AggregateError`s are caught in `.error` handlers, even if the contained errors are not operational. + * + * `Promise.some` and `Promise.any` use `AggregateError` as rejection reason when they fail. + */ + export class AggregateError extends Error {} + + /** + * returned by `Bluebird.disposer()`. + */ + export class Disposer { + } + + export interface Thenable { + then(onFulfilled: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; + then(onFulfilled: (value: R) => U | Thenable, onRejected?: (error: any) => void | Thenable): Thenable; + } + + export interface Resolver { /** - * Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. + * Returns a reference to the controlled promise that can be passed to clients. */ - then(onFulfill: (value: T) => U | PromiseLike, onReject?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): Promise; - then(onFulfill: (value: T) => U | PromiseLike, onReject?: (error: any) => void | PromiseLike, onProgress?: (note: any) => any): Promise; + promise: Bluebird; /** - * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. + * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. + */ + resolve(value: R): void; + resolve(): void; + + /** + * Reject the underlying promise with `reason` as the rejection reason. + */ + reject(reason: any): void; + + /** + * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. * - * Alias `.caught();` for compatibility with earlier ECMAScript version. + * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. */ - catch(onReject?: (error: any) => T | PromiseLike | void | PromiseLike): Promise; - caught(onReject?: (error: any) => T | PromiseLike | void | PromiseLike): Promise; - - catch(onReject?: (error: any) => U | PromiseLike): Promise; - caught(onReject?: (error: any) => U | PromiseLike): Promise; + // TODO specify resolver callback + callback: (err: any, value: R, ...values: R[]) => void; + } + export interface Inspection { /** - * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. - * - * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. - * - * Alias `.caught();` for compatibility with earlier ECMAScript version. - */ - catch(predicate: (error: any) => boolean, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; - caught(predicate: (error: any) => boolean, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; - - catch(predicate: (error: any) => boolean, onReject: (error: any) => U | PromiseLike): Promise; - caught(predicate: (error: any) => boolean, onReject: (error: any) => U | PromiseLike): Promise; - - catch(ErrorClass: Function, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; - caught(ErrorClass: Function, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; - - catch(ErrorClass: Function, onReject: (error: any) => U | PromiseLike): Promise; - caught(ErrorClass: Function, onReject: (error: any) => U | PromiseLike): Promise; - - - /** - * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. - */ - error(onReject: (reason: any) => PromiseLike): Promise; - error(onReject: (reason: any) => U): Promise; - - /** - * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. - * - * Alias `.lastly();` for compatibility with earlier ECMAScript version. - */ - finally(handler: () => U | PromiseLike): Promise; - - lastly(handler: () => U | PromiseLike): Promise; - - /** - * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. - */ - bind(thisArg: any): Promise; - - /** - * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. - */ - done(onFulfilled?: (value: T) => PromiseLike, onRejected?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): void; - done(onFulfilled?: (value: T) => U, onRejected?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): void; - - /** - * Like `.finally()`, but not called for rejections. - */ - tap(onFulFill: (value: T) => U | PromiseLike): Promise; - - /** - * Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise. - */ - progressed(handler: (note: any) => any): Promise; - - /** - * Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - delay(ms: number): Promise; - - /** - * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance. - * - * You may specify a custom error message with the `message` parameter. - */ - timeout(ms: number, message?: string): Promise; - - /** - * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. - * Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything. - */ - nodeify(callback: (err: any, value?: T) => void, options?: Promise.SpreadOption): Promise; - nodeify(...sink: any[]): Promise; - - /** - * Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise. - */ - cancellable(): Promise; - - /** - * Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending. - * - * That ancestor will then be rejected with a `CancellationError` (get a reference from `Promise.CancellationError`) object as the rejection reason. - * - * In a promise rejection handler you may check for a cancellation by seeing if the reason object has `.name === "Cancel"`. - * - * Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable. - */ - // TODO what to do with this? - cancel(reason?: any): Promise; - - /** - * Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors. - */ - fork(onFulfilled?: (value: T) => U | PromiseLike, onRejected?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): Promise; - - /** - * Create an uncancellable promise based on this promise. - */ - uncancellable(): Promise; - - /** - * See if this promise can be cancelled. - */ - isCancellable(): boolean; - - /** - * See if this `promise` has been fulfilled. + * See if the underlying promise was fulfilled at the creation time of this inspection object. */ isFulfilled(): boolean; /** - * See if this `promise` has been rejected. + * See if the underlying promise was rejected at the creation time of this inspection object. */ isRejected(): boolean; /** - * See if this `promise` is still defer. + * See if the underlying promise was cancelled at the creation time of this inspection object. + */ + isCancelled(): boolean; + + /** + * See if the underlying promise was defer at the creation time of this inspection object. */ isPending(): boolean; /** - * See if this `promise` is resolved -> either fulfilled or rejected. - */ - isResolved(): boolean; - - /** - * Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet. + * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object. * * throws `TypeError` */ - value(): T; + value(): R; /** - * Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet. + * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. * * throws `TypeError` */ reason(): any; + } - /** - * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`. - */ - inspect(): Promise.Inspection; + /** + * Returns a new independent copy of the Bluebird library. + * + * This method should be used before you use any of the methods which would otherwise alter the global Bluebird object - to avoid polluting global state. + */ + export function getNewLibraryCopy(): typeof Bluebird; - /** - * This is a convenience method for doing: - * - * - * promise.then(function(obj){ - * return obj[propertyName].call(obj, arg...); - * }); - * - */ - call(propertyName: string, ...args: any[]): Promise; + /** + * This is relevant to browser environments with no module loader. + * + * Release control of the Promise namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else. + */ + export function noConflict(): typeof Bluebird; - /** - * This is a convenience method for doing: - * - * - * promise.then(function(obj){ - * return obj[propertyName]; - * }); - * - */ - // TODO find way to fix get() - // get(propertyName: string): Promise; - - /** - * Convenience method for: - * - * - * .then(function() { - * return value; - * }); - * - * - * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` - * - * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. - */ - return(): Promise; - thenReturn(): Promise; - return(value: U): Promise; - thenReturn(value: U): Promise; - - /** - * Convenience method for: - * - * - * .then(function() { - * throw reason; - * }); - * - * Same limitations apply as with `.return()`. - * - * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. - */ - throw(reason: Error): Promise; - thenThrow(reason: Error): Promise; - - /** - * Convert to String. - */ - toString(): string; - - /** - * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. - */ - toJSON(): Object; - - /** - * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. - */ - // TODO how to model instance.spread()? like Q? - spread(onFulfill: Function, onReject?: (reason: any) => U | PromiseLike): Promise; - /* - // TODO or something like this? - spread(onFulfill: (...values: W[]) => PromiseLike, onReject?: (reason: any) => PromiseLike): Promise; - spread(onFulfill: (...values: W[]) => PromiseLike, onReject?: (reason: any) => U): Promise; - spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => PromiseLike): Promise; - spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise; - */ - /** - * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - all(): Promise; - - /** - * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO how to model instance.props()? - props(): Promise; - - /** - * Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - settle(): Promise[]>; - - /** - * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - any(): Promise; - - /** - * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - some(count: number): Promise; - - /** - * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - race(): Promise; - - /** - * Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - map(mapper: (item: Q, index: number, arrayLength: number) => U | PromiseLike, options?: Promise.ConcurrencyOption): Promise; - - /** - * Same as `Promise.mapSeries(thisPromise, mapper)`. - */ - // TODO type inference from array-resolving promise? - mapSeries(mapper: (item: Q, index: number, arrayLength: number) => U | PromiseLike): Promise; - - /** - * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U | PromiseLike, initialValue?: U): Promise; - - /** - * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - filter(filterer: (item: U, index: number, arrayLength: number) => boolean | PromiseLike, options?: Promise.ConcurrencyOption): Promise; - - /** - * Same as calling ``Promise.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - each(iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; + /** + * Changes how bluebird schedules calls a-synchronously. + * + * @param scheduler Should be a function that asynchronously schedules + * the calling of the passed in function + */ + export function setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void; } -/** - * Don't use variable namespace such as variables, functions, and classes. - * If you use this namespace, it will conflict in es6. - */ -declare namespace Promise { - export interface RangeError extends Error { - } - export interface CancellationError extends Error { - } - export interface TimeoutError extends Error { - } - export interface TypeError extends Error { - } - export interface RejectionError extends Error { - } - export interface OperationalError extends Error { - } - - export interface ConcurrencyOption { - concurrency: number; - } - export interface SpreadOption { - spread: boolean; - } - export interface PromisifyAllOptions { - suffix?: string; - filter?: (name: string, func: Function, target?: any, passesDefaultFilter?: boolean) => boolean; - // The promisifier gets a reference to the original method and should return a function which returns a promise - promisifier?: (originalMethod: Function) => () => PromiseLike; - } - - export interface Resolver { - /** - * Returns a reference to the controlled promise that can be passed to clients. - */ - promise: Promise; - - /** - * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. - */ - resolve(value: T): void; - resolve(): void; - - /** - * Reject the underlying promise with `reason` as the rejection reason. - */ - reject(reason: any): void; - - /** - * Progress the underlying promise with `value` as the progression value. - */ - progress(value: any): void; - - /** - * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. - * - * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. - */ - // TODO specify resolver callback - callback: (err: any, value: T, ...values: T[]) => void; - } - - export interface Inspection { - /** - * See if the underlying promise was fulfilled at the creation time of this inspection object. - */ - isFulfilled(): boolean; - - /** - * See if the underlying promise was rejected at the creation time of this inspection object. - */ - isRejected(): boolean; - - /** - * See if the underlying promise was defer at the creation time of this inspection object. - */ - isPending(): boolean; - - /** - * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object. - * - * throws `TypeError` - */ - value(): T; - - /** - * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. - * - * throws `TypeError` - */ - reason(): any; - } -} - -declare module 'bluebird' { - export = Promise; +export = Bluebird; } diff --git a/bookshelf/bookshelf.d.ts b/bookshelf/bookshelf.d.ts index 0ca3a1ebcd..34f58d62ed 100644 --- a/bookshelf/bookshelf.d.ts +++ b/bookshelf/bookshelf.d.ts @@ -3,7 +3,7 @@ // Definitions by: Andrew Schurman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// /// /// diff --git a/boom/boom.d.ts b/boom/boom.d.ts index 85c2e22b35..7495e3ae68 100644 --- a/boom/boom.d.ts +++ b/boom/boom.d.ts @@ -44,14 +44,17 @@ declare namespace Boom { export function rangeNotSatisfiable(message?: string, data?: any): BoomError; export function expectationFailed(message?: string, data?: any): BoomError; export function badData(message?: string, data?: any): BoomError; + export function locked(message?: string, data?: any): BoomError; + export function preconditionRequired(message?: string, data?: any): BoomError; export function tooManyRequests(message?: string, data?: any): BoomError; + export function illegal(message?: string, data?: any): BoomError; // 5xx + export function badImplementation(message?: string, data?: any): BoomError; export function notImplemented(message?: string, data?: any): BoomError; export function badGateway(message?: string, data?: any): BoomError; - export function serverTimeout(message?: string, data?: any): BoomError; + export function serverUnavailable(message?: string, data?: any): BoomError; export function gatewayTimeout(message?: string, data?: any): BoomError; - export function badImplementation(message?: string, data?: any): BoomError; } declare module "boom" { diff --git a/bootbox/bootbox.d.ts b/bootbox/bootbox.d.ts index ce422de880..c94b60625f 100644 --- a/bootbox/bootbox.d.ts +++ b/bootbox/bootbox.d.ts @@ -9,7 +9,7 @@ interface BootboxBaseOptions { title?: string | Element; callback?: (result: boolean | string) => any; - onEscape?: () => any | boolean; + onEscape?: (() => any) | boolean; show?: boolean; backdrop?: boolean; closeButton?: boolean; diff --git a/bootstrap.datepicker/bootstrap.datepicker-tests.ts b/bootstrap-datepicker/bootstrap-datepicker-tests.ts similarity index 98% rename from bootstrap.datepicker/bootstrap.datepicker-tests.ts rename to bootstrap-datepicker/bootstrap-datepicker-tests.ts index b275ee25a8..d290a5b8fa 100644 --- a/bootstrap.datepicker/bootstrap.datepicker-tests.ts +++ b/bootstrap-datepicker/bootstrap-datepicker-tests.ts @@ -1,4 +1,4 @@ -/// +/// function tests_simple() { $('#datepicker').datepicker(); diff --git a/bootstrap.datepicker/bootstrap.datepicker.d.ts b/bootstrap-datepicker/bootstrap-datepicker.d.ts similarity index 98% rename from bootstrap.datepicker/bootstrap.datepicker.d.ts rename to bootstrap-datepicker/bootstrap-datepicker.d.ts index f60a0ffed6..1a2bb2124b 100644 --- a/bootstrap.datepicker/bootstrap.datepicker.d.ts +++ b/bootstrap-datepicker/bootstrap-datepicker.d.ts @@ -1,4 +1,4 @@ -// Type definitions for bootstrap.datepicker +// Type definitions for bootstrap-datepicker // Project: https://github.com/eternicode/bootstrap-datepicker // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/bootstrap-slider/bootstrap-slider.d.ts b/bootstrap-slider/bootstrap-slider.d.ts index 77a5177fa0..d830e3c45a 100644 --- a/bootstrap-slider/bootstrap-slider.d.ts +++ b/bootstrap-slider/bootstrap-slider.d.ts @@ -35,7 +35,7 @@ interface SliderOptions { * Default: 'horizontal' * set the orientation. Accepts 'vertical' or 'horizontal' */ - orientation?: number; + orientation?: string; /** * Default: 5 * initial value. Use array to have a range slider. diff --git a/bowser/bowser-tests.ts b/bowser/bowser-tests.ts index 2f7cb8904c..79a846f3fb 100644 --- a/bowser/bowser-tests.ts +++ b/bowser/bowser-tests.ts @@ -7,3 +7,13 @@ Bowser.test(['msie']) === true; Bowser.a === Bowser.c; Bowser.osversion > 10; Bowser.osversion === '10.1A'; + +bowser.msedge === true; +bowser.test(['msie']) === true; +bowser.a === bowser.c; +bowser.osversion > 10; +bowser.osversion === '10.1A'; +bowser.compareVersions(['9.0', '10']); +bowser() === {android: true, x: true}; +bowser.check({msie: "11"}, window.navigator.userAgent); +bowser.isUnsupportedBrowser({msie: "10"}, window.navigator.userAgent); \ No newline at end of file diff --git a/bowser/bowser.d.ts b/bowser/bowser.d.ts index 2bf1b3d510..4d1840ff6a 100644 --- a/bowser/bowser.d.ts +++ b/bowser/bowser.d.ts @@ -3,52 +3,104 @@ // Definitions by: Paulo Cesar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var bowser: BowserModule.IBowser; + declare module 'bowser' { - var def: BowserModule.IBowser; - export = def; + export = bowser; } declare namespace BowserModule { - export interface IBowserUA { - msie: boolean; + export interface IBowserOS { + mac: boolean; + /**other than Windows Phone */ + windows: boolean; + windowsphone: boolean; + /**other than android, chromeos, webos, tizen, and sailfish */ + linux: boolean; + chromeos: boolean; + android: boolean; + /** also sets one of iphone/ipad/ipod */ + ios: boolean; + blackberry: boolean; + firefoxos: boolean; + /** may also set touchpad */ + webos: boolean; + bada: boolean; + tizen: boolean; + sailfish: boolean; + } + + export interface IBowserVersions { chrome: boolean; - webkit: boolean; - phantom: boolean; - opera: boolean; + firefox: boolean; + msie: boolean; + msedge: boolean; safari: boolean; android: boolean; ios: boolean; - webos: boolean; - msedge: boolean; - seamonkey: boolean; - firefox: boolean; - yandexbrowser: boolean; + opera: boolean; + phantom: boolean; blackberry: boolean; - tablet: boolean; - mobile: boolean; + webos: boolean; silk: boolean; bada: boolean; tizen: boolean; - windowsphone: boolean; - firefoxos: boolean; - gecko: boolean; + seamonkey: boolean; sailfish: boolean; - chromeBook: boolean; + ucbrowser: boolean; + qupzilla: boolean; + vivaldi: boolean; + sleipnir: boolean; + kMeleon: boolean; + } + + export interface IBowserEngines { + /** IE <= 11 */ + msie: boolean; + /**Chrome 0-27, Android <4.4, iOs, BB, etc. */ + webkit: boolean; + /**Chrome >=28, Android >=4.4, Opera, etc. */ + blink: boolean; + /**Firefox, etc. */ + gecko: boolean; + /** IE > 11 */ + msedge: boolean; + /** If a tablet device is detected, the flag tablet is set instead of mobile. */ + tablet: boolean; + /** All detected mobile OSes are additionally flagged mobile, unless it's a tablet */ + mobile: boolean; + + } + + export interface IBowserGrade { /** Grade A browser */ a: boolean; /** Grade C browser */ c: boolean; /** Grade X browser */ x: boolean; + /**A human readable name for this browser. E.g. 'Chrome', '' */ name: string; + /**Version number for the browser. E.g. '32.0' */ version: string|number; osversion: string|number; } - export interface IBowser extends IBowserUA { + export interface IBowserDetection extends IBowserGrade, IBowserEngines, IBowserOS, IBowserVersions { } + + export interface IBowserMinVersions { + // { msie: "11", "firefox": "4" } + [index: string]: string; + } + + export interface IBowser extends IBowserDetection { + (): IBowserDetection; test(browserList: string[]): boolean; _detect(ua: string): IBowser; + compareVersions(versions: string[]): number; + check(minVersions: IBowserMinVersions, strictMode?: boolean|string, ua?: string): Boolean; + isUnsupportedBrowser(minVersions: IBowserMinVersions, strictMode?: boolean|string, ua?: string): boolean; } } diff --git a/braintree-web/braintree-web-tests.ts b/braintree-web/braintree-web-tests.ts new file mode 100644 index 0000000000..40b34df418 --- /dev/null +++ b/braintree-web/braintree-web-tests.ts @@ -0,0 +1,432 @@ +/// + +let version: string = braintree.VERSION; + +let clientToken: string = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiI0YjlhYzVmYmI4ZTNkYzQzMmFkZjJhNzBlNjZlMWNjY2M5ODRkYzE4ZTM4YmY4NjYzZTM5NjM3NWZjYmQzY2U5fGNyZWF0ZWRfYXQ9MjAxNi0wOS0wOFQwNTowMzo0MC4xNjk1NTUwMzUrMDAwMFx1MDAyNm1lcmNoYW50X2lkPTM0OHBrOWNnZjNiZ3l3MmJcdTAwMjZwdWJsaWNfa2V5PTJuMjQ3ZHY4OWJxOXZtcHIiLCJjb25maWdVcmwiOiJodHRwczovL2FwaS5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tOjQ0My9tZXJjaGFudHMvMzQ4cGs5Y2dmM2JneXcyYi9jbGllbnRfYXBpL3YxL2NvbmZpZ3VyYXRpb24iLCJjaGFsbGVuZ2VzIjpbXSwiZW52aXJvbm1lbnQiOiJzYW5kYm94IiwiY2xpZW50QXBpVXJsIjoiaHR0cHM6Ly9hcGkuc2FuZGJveC5icmFpbnRyZWVnYXRld2F5LmNvbTo0NDMvbWVyY2hhbnRzLzM0OHBrOWNnZjNiZ3l3MmIvY2xpZW50X2FwaSIsImFzc2V0c1VybCI6Imh0dHBzOi8vYXNzZXRzLmJyYWludHJlZWdhdGV3YXkuY29tIiwiYXV0aFVybCI6Imh0dHBzOi8vYXV0aC52ZW5tby5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tIiwiYW5hbHl0aWNzIjp7InVybCI6Imh0dHBzOi8vY2xpZW50LWFuYWx5dGljcy5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tLzM0OHBrOWNnZjNiZ3l3MmIifSwidGhyZWVEU2VjdXJlRW5hYmxlZCI6dHJ1ZSwicGF5cGFsRW5hYmxlZCI6dHJ1ZSwicGF5cGFsIjp7ImRpc3BsYXlOYW1lIjoiQWNtZSBXaWRnZXRzLCBMdGQuIChTYW5kYm94KSIsImNsaWVudElkIjpudWxsLCJwcml2YWN5VXJsIjoiaHR0cDovL2V4YW1wbGUuY29tL3BwIiwidXNlckFncmVlbWVudFVybCI6Imh0dHA6Ly9leGFtcGxlLmNvbS90b3MiLCJiYXNlVXJsIjoiaHR0cHM6Ly9hc3NldHMuYnJhaW50cmVlZ2F0ZXdheS5jb20iLCJhc3NldHNVcmwiOiJodHRwczovL2NoZWNrb3V0LnBheXBhbC5jb20iLCJkaXJlY3RCYXNlVXJsIjpudWxsLCJhbGxvd0h0dHAiOnRydWUsImVudmlyb25tZW50Tm9OZXR3b3JrIjp0cnVlLCJlbnZpcm9ubWVudCI6Im9mZmxpbmUiLCJ1bnZldHRlZE1lcmNoYW50IjpmYWxzZSwiYnJhaW50cmVlQ2xpZW50SWQiOiJtYXN0ZXJjbGllbnQzIiwiYmlsbGluZ0FncmVlbWVudHNFbmFibGVkIjp0cnVlLCJtZXJjaGFudEFjY291bnRJZCI6ImFjbWV3aWRnZXRzbHRkc2FuZGJveCIsImN1cnJlbmN5SXNvQ29kZSI6IlVTRCJ9LCJjb2luYmFzZUVuYWJsZWQiOmZhbHNlLCJtZXJjaGFudElkIjoiMzQ4cGs5Y2dmM2JneXcyYiIsInZlbm1vIjoib2ZmIn0="; + +braintree.client.create({ + authorization: clientToken +}, function (error: BraintreeError, clientInstance: any) { + + var form: HTMLFormElement = document.getElementById('my-form-id') as HTMLFormElement; + var data: { creditCard: BraintreeWeb.CreditCardInfo } = { + creditCard: { + number: form['cc-number'].value, + cvv: form['cc-cvv'].value, + expirationDate: form['cc-date'].value, + billingAddress: { + postalCode: form['cc-postal'].value + } + } + }; + + clientInstance.request({ + endpoint: 'payment_methods/credit_cards', + method: 'post', + data: data + }, function (requestErr: BraintreeError, response: { creditCards: any[]; }) { + if (requestErr) { throw new Error(requestErr.message); } + + console.log('Got nonce:', response.creditCards[0].nonce); + }); + + braintree.hostedFields.create({ + client: clientInstance, + styles: { + 'input': { + 'font-size': '16pt', + 'color': '#3A3A3A' + }, + + '.number': { + 'font-family': 'monospace' + }, + '.valid': { + 'color': 'green' + } + }, + fields: { + number: { + selector: '#card-number' + }, + cvv: { + selector: '#cvv' + }, + expirationDate: { + selector: '#expiration-date' + } + } + }, function (hostedFieldsErr?: BraintreeError, hostedFieldsInstance?: any) { + + if (hostedFieldsErr) { + // Handle error in Hosted Fields creation + console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`); + return; + } + + let form = new HTMLFormElement(); + + form.addEventListener('submit', function (event: Event) { + event.preventDefault(); + + hostedFieldsInstance.tokenize(function (tokenizeErr: BraintreeError, payload: BraintreeWeb.HostedFieldsTokenizePayload) { + if (tokenizeErr) { + // Handle error in Hosted Fields tokenization + switch (tokenizeErr.code) { + case 'HOSTED_FIELDS_FIELDS_EMPTY': + console.error('All fields are empty! Please fill out the form.'); + break; + case 'HOSTED_FIELDS_FIELDS_INVALID': + console.error('Some fields are invalid:', tokenizeErr.details.invalidFieldKeys); + break; + case 'HOSTED_FIELDS_FAILED_TOKENIZATION': + console.error('Tokenization failed server side. Is the card valid?'); + break; + case 'HOSTED_FIELDS_TOKENIZATION_NETWORK_ERROR': + console.error('Network error occurred when tokenizing.'); + break; + default: + console.error('Something bad happened!', tokenizeErr); + } + return; + } + + // Put `payload.nonce` into the `payment-method-nonce` input, and then + // submit the form. Alternatively, you could send the nonce to your server + // with AJAX. + (document.querySelector('input[name="payment-method-nonce"]') as HTMLInputElement).value = payload.nonce; + form.submit(); + }); + }, false); + + hostedFieldsInstance.on('focus', function (event: BraintreeWeb.HostedFieldsStateObject) { + console.log(event.emittedBy, 'has been focused'); + }); + + hostedFieldsInstance.teardown(function (teardownErr: BraintreeError) { + if (teardownErr) { + console.error('Could not tear down Hosted Fields!'); + } else { + console.info('Hosted Fields has been torn down!'); + } + }); + + hostedFieldsInstance.tokenize({ + vault: true + }, function (tokenizeErr: BraintreeError, payload: BraintreeWeb.HostedFieldsTokenizePayload) { + if (tokenizeErr) { + console.error(tokenizeErr); + } else { + console.log('Got nonce:', payload.nonce); + } + }); + + hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: BraintreeError) { + if (addClassErr) { + console.error(addClassErr); + } + }); + + hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: BraintreeError) { + if (addClassErr) { + console.error(addClassErr); + return; + } + + // some time later... + hostedFieldsInstance.removeClass('number', 'custom-class'); + }); + + hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr: BraintreeError) { + if (placeholderErr) { + console.error(placeholderErr); + } + }); + + hostedFieldsInstance.on('cardTypeChange', function (event: BraintreeWeb.HostedFieldsStateObject) { + // Update the placeholder value if there is only one possible card type + if (event.cards.length === 1) { + braintree.hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr: BraintreeError) { + if (placeholderErr) { + // Handle errors, such as invalid field name + console.error(placeholderErr); + } + }); + } + }); + + hostedFieldsInstance.clear('number', function (clearErr: BraintreeError) { + if (clearErr) { + console.error(clearErr); + } + }); + + hostedFieldsInstance.clear('number'); + hostedFieldsInstance.clear('cvv'); + hostedFieldsInstance.clear('expirationDate'); + + var state = braintree.hostedFields.getState(); + + var formValid = Object.keys(state.fields).every(function (key) { + return state.fields[key].isValid; + }); + }); + + braintree.applePay.create({ client: clientInstance }, function (createErr?: BraintreeError, applePayInstance?: any) { + if (createErr) { + // Handle error in client creation + console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`); + + return; + } + + let request = { + countryCode: 'US', + currencyCode: 'USD', + supportedNetworks: ['visa', 'masterCard'], + merchantCapabilities: ['supports3DS'], + total: { label: 'Your Label', amount: '10.00' }, + }; + + var paymentRequest = braintree.applePay.createPaymentRequest(request); + + console.log(paymentRequest); + // { total: { }, countryCode: 'US', currencyCode: 'USD', merchantCapabilities: [ ], supportedNetworks: [ ] } + }); + + braintree.applePay.create({ client: clientInstance }, function (createErr, applePayInstance) { + let request = { + countryCode: 'US', + currencyCode: 'USD', + supportedNetworks: ['visa', 'masterCard'], + merchantCapabilities: ['supports3DS'], + total: { label: 'Your Label', amount: '10.00' }, + }; + + var session = new ApplePaySession(1, request); + + session.onvalidatemerchant = function (event: { validationURL: string }) { + braintree.applePay.performValidation({ + validationURL: event.validationURL + }, function (err, validationData) { + if (err) { + console.error(err); + session.abort(); + return; + } + session.completeMerchantValidation(validationData); + }); + }; + }); + + braintree.applePay.create({ client: clientInstance }, function (createErr, applePayInstance) { + let request = { + countryCode: 'US', + currencyCode: 'USD', + supportedNetworks: ['visa', 'masterCard'], + merchantCapabilities: ['supports3DS'], + total: { label: 'Your Label', amount: '10.00' }, + }; + + var session = new ApplePaySession(1, request); + + session.onpaymentauthorized = function (event) { + braintree.applePay.tokenize({ + token: event.payment.token + }, function (err, tokenizedPayload) { + if (err) { + session.completePayment(ApplePayStatusCodes.STATUS_FAILURE); + return; + } + session.completePayment(ApplePayStatusCodes.STATUS_SUCCESS); + + // Send the tokenizedPayload to your server. + }); + }; + }); + + braintree.paypal.create({ + client: clientInstance + }, function (createErr, paypalInstance) { + if (createErr) { + if (createErr.code === 'PAYPAL_BROWSER_NOT_SUPPORTED') { + console.error('This browser is not supported.'); + } else { + console.error('Error!', createErr); + } + } + + let button = new HTMLButtonElement(); + + button.addEventListener('click', function () { + // Disable the button so that we don't attempt to open multiple popups. + button.setAttribute('disabled', 'disabled'); + + // Because PayPal tokenization opens a popup, this must be called + // as a result of a user action, such as a button click. + paypalInstance.tokenize({ + flow: 'vault' // Required + // Any other tokenization options + }, function (tokenizeErr: BraintreeError, payload: BraintreeWeb.PayPalTokenizePayload) { + button.removeAttribute('disabled'); + + if (tokenizeErr) { + // Handle tokenization errors or premature flow closure + + switch (tokenizeErr.code) { + case 'PAYPAL_POPUP_CLOSED': + console.error('Customer closed PayPal popup.'); + break; + case 'PAYPAL_ACCOUNT_TOKENIZATION_FAILED': + console.error('PayPal tokenization failed. See details:', tokenizeErr.details); + break; + case 'PAYPAL_FLOW_FAILED': + console.error('Unable to initialize PayPal flow. Are your options correct?', tokenizeErr.details); + break; + default: + console.error('Error!', tokenizeErr); + } + } else { + // Submit payload.nonce to your server + } + }); + }); + }); + + braintree.unionpay.create({ client: clientInstance }, function (createErr, unionpayInstance) { + if (createErr) { + console.error(createErr); + return; + } + + unionpayInstance.fetchCapabilities({ + card: { + number: '4111111111111111' + } + }, function (fetchErr: BraintreeError, cardCapabilities: BraintreeWeb.UnionPayFetchCapabilitiesPayload) { + if (fetchErr) { + console.error(fetchErr); + return; + } + + if (cardCapabilities.isUnionPay) { + if (cardCapabilities.unionPay && !cardCapabilities.unionPay.isSupported) { + // Braintree cannot process this UnionPay card. + // Ask the user for a different card. + return; + } + + if (cardCapabilities.isDebit) { + // CVV and expiration date are not required + } else { + // CVV and expiration date are required + } + + // Show mobile phone number field for enrollment + } + }); + + unionpayInstance.enroll({ + card: { + number: '4111111111111111', + expirationMonth: '12', + expirationYear: '2038' + }, + mobile: { + countryCode: '62', + number: '111111111111' + } + }, function (enrollErr: BraintreeError, response: BraintreeWeb.UnionPayEnrollPayload) { + if (enrollErr) { + console.error(enrollErr); + return; + } + + if (response.smsCodeRequired) { + // If smsCodeRequired, wait for SMS auth code from customer + // Then use response.enrollmentId during {@link UnionPay#tokenize} + } else { + // SMS code is not required from the user. + // {@link UnionPay#tokenize} can be called immediately + } + }); + + let enrollResponse: { + enrollmentId: string + }; + + unionpayInstance.tokenize({ + card: { + number: '4111111111111111', + expirationMonth: '12', + expirationYear: '2038', + cvv: '123' + }, + enrollmentId: enrollResponse.enrollmentId, // Returned from enroll + smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted + }, function (tokenizeErr: BraintreeError, response: BraintreeWeb.UnionPayTokenizePayload) { + if (tokenizeErr) { + console.error(tokenizeErr); + return; + } + + // Send response.nonce to your server + }); + + unionpayInstance.teardown(function (teardownErr: BraintreeError) { + if (teardownErr) { + console.error('Could not tear down UnionPay.'); + } else { + console.log('UnionPay has been torn down.'); + } + }); + }); +}); + +let existingNonce = "fake-valid-nonce"; +let submitNonceToServer: (nonce: string) => void; + +braintree.threeDSecure.verifyCard({ + nonce: existingNonce, + amount: 123.45, + addFrame: function (err, iframe) { + // Set up your UI and add the iframe. + let my3DSContainer = document.createElement('div'); + my3DSContainer.appendChild(iframe); + document.body.appendChild(my3DSContainer); + }, + removeFrame: function () { + let my3DSContainer = document.createElement('div'); + + // Remove UI that you added in addFrame. + document.body.removeChild(my3DSContainer); + } +}, function (err: BraintreeError, payload: BraintreeWeb.ThreeDSecureVerifyPayload) { + if (err) { + console.error(err); + return; + } + + if (payload.liabilityShifted) { + // Liablity has shifted + submitNonceToServer(payload.nonce); + } else if (payload.liabilityShiftPossible) { + // Liablity may still be shifted + // Decide if you want to submit the nonce + } else { + // Liablity has not shifted and will not shift + // Decide if you want to submit the nonce + } +}); + +braintree.threeDSecure.cancelVerifyCard(function (err: BraintreeError, verifyPayload: BraintreeWeb.ThreeDSecureVerifyPayload) { + if (err) { + // Handle error + console.log(err.message); // No verification payload available + return; + } + + verifyPayload.nonce; // The nonce returned from the 3ds lookup call + verifyPayload.liabilityShifted; // boolean + verifyPayload.liabilityShiftPossible; // boolean +}); \ No newline at end of file diff --git a/braintree-web/braintree-web.d.ts b/braintree-web/braintree-web.d.ts new file mode 100644 index 0000000000..2cf2d89467 --- /dev/null +++ b/braintree-web/braintree-web.d.ts @@ -0,0 +1,1738 @@ +// Type definitions for Braintree-web v3.0.2 +// Project: https://github.com/braintree/braintree-web +// Definitions by: Guy Shahine +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * @module braintree-web/american-express + * @description This module is for use with Amex Express Checkout. To accept American Express cards, use Hosted Fields. + */ +declare namespace BraintreeWeb { + export interface AmericanExpress { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {callback} callback The second argument, `data`, is the {@link AmericanExpress} instance. + * @returns {void} + */ + create: (options: { client: Client }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {object} options Options + * @description You cannot use this constructor directly. Use {@link module:braintree-web/american-express.create|braintree.american-express.create} instead. + * @classdesc This class allows you use a nonce to interact with American Express Checkout. To accept American Express cards, use Hosted Fields. + */ + export class AmericanExpress { + /** + * @class + * @param {object} options Options + * @description You cannot use this constructor directly. Use {@link module:braintree-web/american-express.create|braintree.american-express.create} instead. + * @classdesc This class allows you use a nonce to interact with American Express Checkout. To accept American Express cards, use Hosted Fields. + */ + constructor(options: any); + + /** + * Gets the rewards balance associated with a Braintree nonce. + * @public + * @param {object} options Request options + * @param {string} options.nonce An existing Braintree nonce. + * @param {callback} callback The second argument, data, is the returned server data. + * @returns {void} + * @example + * var americanExpress = require('braintree-web/american-express'); + * + * americanExpress.create({client: clientInstance}, function (createErr, americanExpressInstance) { + * var options = {nonce: existingBraintreeNonce}; + * americanExpressInstance.getRewardsBalance(options, function (getErr, payload) { + * if (getErr || payload.error) { + * // Handle error + * return; + * } + * + * console.log('Rewards amount: ' + payload.rewardsAmount); + * }); + * }); + */ + public getRewardsBalance(options: { nonce: string }, callback: callback): void; + + /** + * Gets the Express Checkout nonce profile given a nonce from American Express. + * @public + * @param {object} options Request options + * @param {string} options.nonce An existing nonce from American Express (note that this is not a nonce from Braintree). + * @param {callback} callback The second argument, data, is the returned server data. + * @returns {void} + * @example + * var americanExpress = require('braintree-web/american-express'); + * + * americanExpress.create({client: clientInstance}, function (createErr, americanExpressInstance) { + * var options = {nonce: existingAmericanExpressNonce}; + * americanExpressInstance.getExpressCheckoutProfile(options, function (getErr, payload) { + * if (getErr) { + * // Handle error + * return; + * } + * + * console.log('Number of cards: ' + payload.amexExpressCheckoutCards.length); + * }); + * }); + */ + public getExpressCheckoutProfile(options: { nonce: string }, callback: callback): void; + } +} + + +// more info https://developer.apple.com/reference/applepayjs/1916082-applepay_js_data_types/paymentrequest + +// billingContact +// Billing contact information for the user. +// countryCode +//Required.The merchant’s two- letter ISO 3166 country code. +// currencyCode +// Required.The three- letter ISO 4217 currency code for the payment. +// lineItems +//A set of line items that explain recurring payments and additional charges. +// merchantCapabilities +// Required.The payment capabilities supported by the merchant.The value must be one or more of supports3DS, supportsEMV, supportsCredit, or supportsDebit. +// requiredBillingContactFields +// The billing information that is required from the user.The value must be one or more of postalAddress, phone, email, or name. +// requiredShippingContactFields +// The shipping information that is required from the user.The value must be one or more of postalAddress, phone, email, or name. +// shippingContact +// Shipping contact information for the user. +// shippingMethods +//A set of available shipping methods.Totals for all shipping methods must be non- negative to pass validation. +// shippingType +// How the items are to be shipped.This property is optional.If specified, it must be one or more of shipping, delivery, storePickup, or servicePickup.The default value is shipping. +// supportedNetworks +// Required.The payment networks supported by the merchant.The value must be one or more of amex, discover, interac, masterCard, privateLabel, or visa. +// total +// Required.The total amount for the payment.The total must be greater than zero and have a label to pass validation. +interface ApplePayPaymentRequest { + total: { + label: string; + amount: string; + }; + countryCode: string; + currencyCode: string; + supportedNetworks: string[]; + merchantCapabilities: string[]; + + billingContact?: any; + shippingContact?: any; + shippingMethods?: any; + shippingType?: any; + requiredBillingContactFields?: any; + requiredShippingContactFields?: any; +} + +declare enum ApplePayStatusCodes { + // The requested action succeeded. + STATUS_SUCCESS = 1, + // The requested action failed. + STATUS_FAILURE, + // The billing address is not valid. + STATUS_INVALID_BILLING_POSTAL_ADDRESS, + // The shipping address is not valid. + STATUS_INVALID_SHIPPING_POSTAL_ADDRESS, + // The shipping contact information is not valid. + STATUS_INVALID_SHIPPING_CONTACT, + // The required PIN information was not provided. Cards on the China Union Pay payment network may require a PIN to authenticate the transaction. + STATUS_PIN_REQUIRED, + // The PIN information is not valid.Cards on the China Union Pay network may require a PIN. + STATUS_PIN_INCORRECT, + // The maximum number of tries for a PIN has been reached and the user has been locked out. Cards on the China Union Pay network may require a PIN. + STATUS_PIN_LOCKOUT, +} + +interface ApplePayPayload { + merchantIdentifier: string; + domainName: string; + displayName: string; +} + +declare class ApplePaySession { + constructor(version: number, request: ApplePayPaymentRequest); + + canMakePayments(): boolean; + + canMakePaymentsWithActiveCard(merchantIdentifier: string): boolean; + + completeMerchantValidation(merchantSession: any): void; + + abort(): void; + + begin(): void; + + completePayment(status: ApplePayStatusCodes): void; + + completePaymentMethodSelection(newTotal: any, newLineItems: any): void; + + completeShippingContactSelection(status: ApplePayStatusCodes, newShippingMethods: any, newTotal: any, newLineItems: any): void; + + completeShippingMethodSelection(status: ApplePayStatusCodes, newTotal: any, newLineItems: any): void; + + supportsVersion(version: number): boolean; + + oncancel: (event: any) => void; + + onpaymentauthorized: (event: any) => void; + + onpaymentmethodselected: (event: any) => void; + + onshippingcontactselected: (event: any) => void; + + onshippingmethodselected: (event: any) => void; + + onvalidatemerchant: (event: any) => void; +} + +/** + * @module braintree-web/apple-pay + * @description Accept Apple Pay on the Web. *This component is currently in beta and is subject to change.* + */ +declare namespace BraintreeWeb { + export interface ApplePay { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {callback} callback The second argument, `data`, is the {@link ApplePay} instance. + * @returns {void} + */ + create: (options: { client: Client }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {object} options Options + * @description You cannot use this constructor directly. Use {@link module:braintree-web/apple-pay.create|braintree.apple-pay.create} instead. + * @classdesc This class represents an Apple Pay component. Instances of this class have methods for validating the merchant server and tokenizing payments. + */ + export class ApplePay { + /** + * @class + * @param {object} options Options + * @description You cannot use this constructor directly. Use {@link module:braintree-web/apple-pay.create|braintree.apple-pay.create} instead. + * @classdesc This class represents an Apple Pay component. Instances of this class have methods for validating the merchant server and tokenizing payments. + */ + constructor(options: any); + + /** + * Merges a payment request with Braintree defaults + * The following properties are assigned to `paymentRequest` if not already defined + * - countryCode + * - currencyCode + * - merchantCapabilities + * - supportedNetworks + * @public + * @param {external:ApplePayPaymentRequest} paymentRequest The payment request details to apply on top of those from Braintree. + * @returns {external:ApplePayPaymentRequest} The decorated `paymentRequest`. + * @example + * var applePay = require('braintree-web/apple-pay'); + * + * applePay.create({client: clientInstance}, function (createErr, applePayInstance) { + * // ... + * var paymentRequest = applePay.createPaymentRequest({ + * total: { + * label: 'My Company', + * amount: '19.99' + * }); + * + * console.log(paymentRequest); + * // { total: { }, countryCode: 'US', currencyCode: 'USD', merchantCapabilities: [ ], supportedNetworks: [ ] } + * + */ + public createPaymentRequest(paymentRequest: ApplePayPaymentRequest): ApplePayPaymentRequest + + /** + * Validates the merchant website, as required by ApplePaySession before payment can be authorized. + * @public + * @param {object} options Options + * @param {string} options.validationURL The validationURL fram an ApplePayValidateMerchantEvent. + * @param {string} [options.displayName] + * - The canonical name for your store. + * - The system may display this name to the user. + * - Use a 128-character or less, UTF-8 string. + * - Do not localize the name. + * @param {string} [options.merchantIdentifier] + * Your Apple merchant identifier. This is the Apple Merchant ID created on the Apple Developer Portal. + * Defaults to the merchant identifier specified in the Braintree Control Panel. + * You can use this field to override the merchant identifier for this transaction. + * @param {callback} callback The second argument, data, is the Apple Pay merchant session object. + * Pass the merchant session to your Apple Pay session's completeMerchantValidation method. + * @returns {void} + * @example + * var applePay = require('braintree-web/apple-pay'); + * + * applePay.create({client: clientInstance}, function (createErr, applePayInstance) { + * var session = new ApplePaySession(1, { + * // This should be the payment request object that + * // contains the information needed to display the payment sheet. + * }); + * + * session.onvalidatemerchant = function (event) { + * applePay.performValidation({ + * validationURL: event.validationURL + * }, function(err, validationData) { + * if (err) { + * console.error(err); + * session.abort(); + * return; + * } + * session.completeMerchantValidation(validationData); + * }); + * }; + * }); + */ + public performValidation(options: { validationURL: string, displayName?: string, merchantIdentifier?: string }, callback: callback): void; + + /** + * Tokenizes an Apple Pay payment. + * @public + * @param {object} options Options + * @param {object} options.token The `payment.token` property of an {@link external:ApplePayPaymentAuthorizedEvent} + * @param {callback} callback The second argument, data, is the tokenized payload. + * @returns {void} + * @example + * var applePay = require('braintree-web/apple-pay'); + * + * applePay.create({client: clientInstance}, function (createErr, applePayInstance) { + * var session = new ApplePaySession(1, { }); + * + * session.onpaymentauthorized = function (event) { + * applePay.tokenize({ + * token: event.payment.token + * }, function (err, tokenizedPayload) { + * if (err) { + * session.completePayment(ApplePaySession.STATUS_FAILURE); + * return; + * } + * session.completePayment(ApplePaySession.STATUS_SUCCESS); + * + * // Send the tokenizedPayload to your server. + * }); + * }; + * }); + */ + public tokenize(options: { token: any }, callback: callback): void; + + } +} + +/** @module braintree-web/client */ +declare namespace BraintreeWeb { + /** + * This object is returned by {@link Client#getConfiguration|getConfiguration}. This information is used extensively by other Braintree modules to properly configure themselves. + * @typedef {object} Client~configuration + * @property {object} client The braintree-web/client parameters. + * @property {string} client.authorization A tokenizationKey or clientToken. + * @property {object} gatewayConfiguration Gateway-supplied configuration. + * @property {object} analyticsMetadata Analytics-specific data. + * @property {string} analyticsMetadata.sessionId Uniquely identifies a browsing session. + * @property {string} analyticsMetadata.sdkVersion The braintree.js version. + * @property {string} analyticsMetadata.merchantAppId Identifies the merchant's web app. + */ + interface ClientAnalyticsMetadata { + sessionId: string; + sdkVersion: string; + merchantAppId: string; + } + + interface Configuration { + client: Client; + gatewayConfiguration: any; + analyticsMetadata: ClientAnalyticsMetadata; + } + + interface CreditCardInfo { + number: string; + cvv: string; + expirationDate: string; + billingAddress: { + postalCode?: string; + } + } + + export interface Client { + authorization: string; + + /** + * @function + * @description This function is the entry point for the braintree.client module. It is used for creating {@link Client} instances that service communication to Braintree servers. + * @param {object} options Object containing all {@link Client} options: + * @param {string} options.authorization A tokenizationKey or clientToken. + * @param {callback} callback The second argument, data, is the {@link Client} instance. + * @returns {void} + * @example + * var createClient = require('braintree-web/client').create; + * + * createClient({ + * authorization: CLIENT_AUTHORIZATION + * }, function (createErr, clientInstance) { + * ... + * }); + * @static + */ + create: (options: { authorization: string }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {Client~configuration} configuration Options + * @description Do not use this constructor directly. Use {@link module:braintree-web/client.create|braintree.client.create} instead. + * @classdesc This class is required by many other Braintree components. It serves as the base API layer that communicates with our servers. It is also capable of being used to formulate direct calls to our servers, such as direct credit card tokenization. See {@link Client#request}. + */ + export class Client { + /** + * @class + * @param {Client~configuration} configuration Options + * @description Do not use this constructor directly. Use {@link module:braintree-web/client.create|braintree.client.create} instead. + * @classdesc This class is required by many other Braintree components. It serves as the base API layer that communicates with our servers. It is also capable of being used to formulate direct calls to our servers, such as direct credit card tokenization. See {@link Client#request}. + */ + constructor(configuration: Configuration); + + + /** + * Returns a copy of the configuration values. + * @public + * @returns {Client~configuration} configuration + */ + public getConfiguration(): Configuration; + + /** + * Used by other modules to formulate all network requests to the Braintree gateway. It is also capable of being used directly from your own form to tokenize credit card information. However, be sure to satisfy PCI compliance if you use direct card tokenization. + * @public + * @param {object} options Request options: + * @param {string} options.method HTTP method. i.e. "get" or "post" + * @param {string} options.endpoint Enpoint path. i.e. "payment_methods" + * @param {object} options.data Data to send with the request + * @param {string} [options.timeout=60000] Timeout limit + * @param {callback} callback The second argument, data, is the returned server data. + * @example + * Direct Credit Card Tokenization + * var createClient = require('braintree-web/client').create; + * + * createClient({ + * authorization: CLIENT_AUTHORIZATION + * }, function (createErr, clientInstance) { + * var form = document.getElementById('my-form-id'); + * var data = { + * creditCard: { + * number: form['cc-number'].value, + * cvv: form['cc-cvv'].value, + * expirationDate: form['cc-date'].value, + * billingAddress: { + * postalCode: form['cc-postal'].value + * } + * } + * }; + * + * // Warning: For a merchant to be eligible for the easiest level of PCI compliance (SAQ A), + * // payment fields cannot be hosted on your checkout page. + * // For an alternative to the following, use Hosted Fields. + * clientInstance.request({ + * endpoint: 'payment_methods/credit_cards', + * method: 'post', + * data: data + * }, function (requestErr, response) { + * if (requestErr) { throw new Error(requestErr); } + * + * console.log('Got nonce:', response.creditCards[0].nonce); + * }); + * }); + * @returns {void} + */ + public request(options: { method: string, endpoint: string, data: any, timeout?: number }, callback: callback): void; + + } +} + +/** @module braintree-web/data-collector */ +declare namespace BraintreeWeb { + export interface DataCollector { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {boolean} [options.kount] If true, Kount fraud data collection is enabled. + * @param {boolean} [options.paypal] If true, PayPal fraud data collection is enabled. + * @param {callback} callback The second argument, `data`, is the {@link DataCollector} instance. + * @returns {void} + */ + create: (options: { client: Client, kount: boolean, paypal: boolean }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @global + * @name DataCollector + * @description Do not use this constructor directly. Use {@link module:braintree-web/data-collector.create|braintree-web.data-collector.create} instead. + * @classdesc This class is used for advanced fraud integration with PayPal and Kount. Instances of this class have {@link DataCollector#deviceData|deviceData} which is used to correlate user sessions with server transactions. + */ + export class DataCollector { + /** + * @class + * @global + * @name DataCollector + * @description Do not use this constructor directly. Use {@link module:braintree-web/data-collector.create|braintree-web.data-collector.create} instead. + * @classdesc This class is used for advanced fraud integration with PayPal and Kount. Instances of this class have {@link DataCollector#deviceData|deviceData} which is used to correlate user sessions with server transactions. + */ + constructor(); + + /** + * @memberof DataCollector + * @name deviceData + * @type string + * @description JSON string to pass with server transactions. + * @instance + */ + deviceData: string; + + /** + * @memberof DataCollector + * @name teardown + * @function + * @description Cleanly remove all event handlers and DOM nodes that were added. + * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully. + * @instance + * @returns {void} + */ + teardown(callback?: callback): void; + + } +} + +/** @module braintree-web/hosted-fields */ +declare namespace BraintreeWeb { + /** + * Fields used in {@link module:braintree-web/hosted-fields~fieldOptions fields options} + * @typedef {object} field + * @property {string} selector A CSS selector to find the container where the hosted field will be inserted. + * @property {string} [placeholder] Will be used as the `placeholder` attribute of the input. If `placeholder` is not natively supported by the browser, it will be polyfilled. + * @property {boolean} [formatInput=true] - Enable or disable automatic formatting on this field. Note: Input formatting does not work properly on Android and iOS, so input formatting is automatically disabled on those browsers. + */ + interface HostedFieldsField { + selector: string; + placeholder?: string; + formatInput?: boolean; + } + + /** + * An object that has {@link module:braintree-web/hosted-fields~field field objects} for each field. Used in {@link module:braintree-web/hosted-fields~create create}. + * @typedef {object} fieldOptions + * @property {field} [number] A field for card number. + * @property {field} [expirationDate] A field for expiration date in `MM/YYYY` format. This should not be used with the `expirationMonth` and `expirationYear` properties. + * @property {field} [expirationMonth] A field for expiration month in `MM` format. This should be used with the `expirationYear` property. + * @property {field} [expirationYear] A field for expiration year in `YYYY` format. This should be used with the `expirationMonth` property. + * @property {field} [cvv] A field for 3 or 4 digit CVV or CID. + * @property {field} [postalCode] A field for postal or region code. + */ + interface HostedFieldFieldOptions { + number: HostedFieldsField; + expirationDate?: HostedFieldsField; + expirationMonth?: HostedFieldsField; + expirationYear?: HostedFieldsField; + cvv: HostedFieldsField; + postalCode?: HostedFieldsField; + } + + /** + * @typedef {object} HostedFields~hostedFieldsCard + * @description Information about the card type, sent in {@link HostedFields~stateObject|stateObjects}. + * @property {string} type The code-friendly representation of the card type. It will be one of the following strings: + * - `american-express` + * - `diners-club` + * - `discover` + * - `jcb` + * - `maestro` + * - `master-card` + * - `unionpay` + * - `visa` + * @property {string} niceType The pretty-printed card type. It will be one of the following strings: + * - `American Express` + * - `Diners Club` + * - `Discover` + * - `JCB` + * - `Maestro` + * - `MasterCard` + * - `UnionPay` + * - `Visa` + * @property {object} code + * This object contains data relevant to the security code requirements of the card brand. + * For example, on a Visa card there will be a CVV of 3 digits, whereas an + * American Express card requires a 4-digit CID. + * @property {string} code.name "CVV" "CID" "CVC" + * @property {number} code.size The expected length of the security code. Typically, this is 3 or 4. + */ + + interface HostedFieldsCardCode { + name: string; + size: number; + } + + interface HostedFieldsHostedFieldsCard { + type: string; + niceType: string; + code: HostedFieldsCardCode; + } + + /** + * @typedef {object} HostedFields~hostedFieldsFieldData + * @description Data about Hosted Fields fields, sent in {@link HostedFields~stateObject|stateObjects}. + * @property {HTMLElement} container Reference to the container DOM element on your page associated with the current event. + * @property {boolean} isFocused Whether or not the input is currently focused. + * @property {boolean} isEmpty Whether or not the user has entered a value in the input. + * @property {boolean} isPotentiallyValid + * A determination based on the future validity of the input value. + * This is helpful when a user is entering a card number and types "41". + * While that value is not valid for submission, it is still possible for + * it to become a fully qualified entry. However, if the user enters "4x" + * it is clear that the card number can never become valid and isPotentiallyValid will + * return false. + * @property {boolean} isValid Whether or not the value of the associated input is fully qualified for submission. + */ + interface HostedFieldsHostedFieldsFieldData { + container: HTMLElement; + isFocused: boolean; + isEmpty: boolean; + isPotentiallyValid: boolean; + isValid: boolean; + } + + /** + * @typedef {object} HostedFields~stateObject + * @description The event payload sent from {@link HostedFields#on|on} or {@link HostedFields#getState|getState}. + * @property {HostedFields~hostedFieldsCard[]} cards + * This will return an array of potential {@link HostedFields~hostedFieldsCard|cards}. If the card type has been determined, the array will contain only one card. + * Internally, Hosted Fields uses credit-card-type, + * an open-source card detection library. + * @property {string} emittedBy + * The name of the field associated with an event. This will not be included if returned by {@link HostedFields#getState|getState}. It will be one of the following strings:
      + * - `"number"` + * - `"cvv"` + * - `"expirationDate"` + * - `"expirationMonth"` + * - `"expirationYear"` + * - `"postalCode"` + * @property {object} fields + * @property {?HostedFields~hostedFieldsFieldData} fields.number {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the number field, if it is present. + * @property {?HostedFields~hostedFieldsFieldData} fields.cvv {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the CVV field, if it is present. + * @property {?HostedFields~hostedFieldsFieldData} fields.expirationDate {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the expiration date field, if it is present. + * @property {?HostedFields~hostedFieldsFieldData} fields.expirationMonth {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the expiration month field, if it is present. + * @property {?HostedFields~hostedFieldsFieldData} fields.expirationYear {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the expiration year field, if it is present. + * @property {?HostedFields~hostedFieldsFieldData} fields.postalCode {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the postal code field, if it is present. + */ + interface HostedFieldsFieldDataFields { + number: HostedFieldsHostedFieldsFieldData; + cvv: HostedFieldsHostedFieldsFieldData; + expirationDate: HostedFieldsHostedFieldsFieldData; + expirationMonth: HostedFieldsHostedFieldsFieldData; + expirationYear: HostedFieldsHostedFieldsFieldData; + postalCode: HostedFieldsHostedFieldsFieldData; + } + + interface HostedFieldsStateObject { + cards: HostedFieldsHostedFieldsCard[]; + emittedBy: string; + fields: HostedFieldsFieldDataFields; + } + + /** + * @typedef {object} HostedFields~tokenizePayload + * @property {string} nonce The payment method nonce. + * @property {object} details Additional account details. + * @property {string} details.cardType Type of card, ex: Visa, MasterCard. + * @property {string} details.lastTwo Last two digits of card number. + * @property {string} description A human-readable description. + * @property {string} type The payment method type, always `CreditCard`. + */ + interface HostedFieldsAccountDetails { + cardType: string; + lastTwo: string; + } + + interface HostedFieldsTokenizePayload { + nonce: string; + details: HostedFieldsAccountDetails; + type: string; + description: string; + } + + export interface HostedFields { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {fieldOptions} options.fields A {@link module:braintree-web/hosted-fields~fieldOptions set of options for each field}. + * @param {styleOptions} options.styles {@link module:braintree-web/hosted-fields~styleOptions Styles} applied to each field. + * @param {callback} callback The second argument, `data`, is the {@link HostedFields} instance. + * @returns {void} + * @example + * braintree.hostedFields.create({ + * client: clientInstance, + * styles: { + * 'input': { + * 'font-size': '16pt', + * 'color': '#3A3A3A' + * }, + * '.number': { + * 'font-family': 'monospace' + * }, + * '.valid': { + * 'color': 'green' + * } + * }, + * fields: { + * number: { + * selector: '#card-number' + * }, + * cvv: { + * selector: '#cvv' + * }, + * expirationDate: { + * selector: '#expiration-date' + * } + * } + * }, callback); + */ + create: (options: { client: Client, fields: HostedFieldFieldOptions, styles: any }, callback: callback) => void; + + + /** + * An object that represents CSS that will be applied in each hosted field. This object looks similar to CSS. Typically, these styles involve fonts (such as `font-family` or `color`). + * + * These are the CSS properties that Hosted Fields supports. Any other CSS should be specified on your page and outside of any Braintree configuration. Trying to set unsupported properties will fail and put a warning in the console. + * + * `color` `font-family` `font-size-adjust` `font-size` `font-stretch` `font-style` `font-variant-alternates` `font-variant-caps` `font-variant-east-asian` `font-variant-ligatures` `font-variant-numeric` `font-variant` `font-weight` `font` `line-height` `opacity` `outline` `text-shadow` `transition` `-moz-osx-font-smoothing` `-moz-tap-highlight-color` `-moz-transition` `-webkit-font-smoothing` `-webkit-tap-highlight-color` `-webkit-transition` + * @typedef {object} styleOptions + */ + styleOptions: any; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class HostedFields + * @param {object} options The Hosted Fields {@link module:braintree-web/hosted-fields.create create} options. + * @description Do not use this constructor directly. Use {@link module:braintree-web/hosted-fields.create|braintree-web.hosted-fields.create} instead. + * @classdesc This class represents a Hosted Fields component produced by {@link module:braintree-web/hosted-fields.create|braintree-web/hosted-fields.create}. Instances of this class have methods for interacting with the input fields within Hosted Fields' iframes. + */ + export class HostedFields { + /** + * @class HostedFields + * @param {object} options The Hosted Fields {@link module:braintree-web/hosted-fields.create create} options. + * @description Do not use this constructor directly. Use {@link module:braintree-web/hosted-fields.create|braintree-web.hosted-fields.create} instead. + * @classdesc This class represents a Hosted Fields component produced by {@link module:braintree-web/hosted-fields.create|braintree-web/hosted-fields.create}. Instances of this class have methods for interacting with the input fields within Hosted Fields' iframes. + */ + constructor(options: any); + + /** + * @name HostedFields#on + * @function + * @param {string} event The name of the event to which you are subscribing. + * @param {function} handler A callback to handle the event. + * @description Subscribes a handler function to a named event. `event` should be {@link HostedFields#event:blur|blur}, {@link HostedFields#event:focus|focus}, {@link HostedFields#event:empty|empty}, {@link HostedFields#event:notEmpty|notEmpty}, {@link HostedFields#event:cardTypeChange|cardTypeChange}, or {@link HostedFields#event:validityChange|validityChange}. Events will emit a {@link HostedFields~stateObject|stateObject}. + * @example + * Listening to a Hosted Field event, in this case 'focus' + * hostedFields.create({ ... }, function (createErr, hostedFieldsInstance) { + * hostedFieldsInstance.on('focus', function (event) { + * console.log(event.emittedBy, 'has been focused'); + * }); + * }); + * @returns {void} + */ + on(event: string, handler: (() => any)): void; + + /** + * Cleanly tear down anything set up by {@link module:braintree-web/hosted-fields.create|create} + * @public + * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if teardown completes successfully. + * @example + * hostedFieldsInstance.teardown(function (teardownErr) { + * if (teardownErr) { + * console.error('Could not tear down Hosted Fields!'); + * } else { + * console.info('Hosted Fields has been torn down!'); + * } + * }); + * @returns {void} + */ + public teardown(callback?: callback): void; + + /** + * Tokenizes fields and returns a nonce payload. + * @public + * @param {object} [options] All tokenization options for the Hosted Fields component. + * @param {boolean} [options.vault=false] When true, will vault the tokenized card. Cards will only be vaulted when using a client created with a client token that includes a customer ID. + * @param {callback} callback The second argument, data, is a {@link HostedFields~tokenizePayload|tokenizePayload} + * @example Tokenize a card + * hostedFieldsInstance.tokenize(function (tokenizeErr, payload) { + * if (tokenizeErr) { + * switch (tokenizeErr.code) { + * case 'HOSTED_FIELDS_FIELDS_EMPTY': + * console.error('All fields are empty! Please fill out the form.'); + * break; + * case 'HOSTED_FIELDS_FIELDS_INVALID': + * console.error('Some fields are invalid:', tokenizeErr.details.invalidFieldKeys); + * break; + * case 'HOSTED_FIELDS_FAILED_TOKENIZATION': + * console.error('Tokenization failed server side. Is the card valid?'); + * break; + * case 'HOSTED_FIELDS_TOKENIZATION_NETWORK_ERROR': + * console.error('Network error occurred when tokenizing.'); + * break; + * default: + * console.error('Something bad happened!', tokenizeErr); + * } + * } else { + * console.log('Got nonce:', payload.nonce); + * } + * }); + * @example Tokenize and vault a card + * hostedFieldsInstance.tokenize({ + * vault: true + * }, function (tokenizeErr, payload) { + * if (tokenizeErr) { + * console.error(tokenizeErr); + * } else { + * console.log('Got nonce:', payload.nonce); + * } + * }); + * @returns {void} + */ + public tokenize(options?: { vault: boolean }, callback?: callback): void; + + /** + * Add a class to a {@link module:braintree-web/hosted-fields~field field}. Useful for updating field styles when events occur elsewhere in your checkout. + * @public + * @param {string} field The field you wish to add a class to. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}. + * @param {string} classname The class to be added. + * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the class is added successfully. + * + * @example + * hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr) { + * if (addClassErr) { + * console.error(addClassErr); + * } + * }); + * @returns {void} + */ + public addClass(field: string, classname: string, callback?: callback): void; + + /** + * Removes a class to a {@link module:braintree-web/hosted-fields~field field}. Useful for updating field styles when events occur elsewhere in your checkout. + * @public + * @param {string} field The field you wish to remove a class from. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}. + * @param {string} classname The class to be removed. + * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the class is removed successfully. + * + * @example + * hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr) { + * if (addClassErr) { + * console.error(addClassErr); + * return; + * } + * + * // some time later... + * hostedFieldsInstance.removeClass('number', 'custom-class'); + * }); + * @returns {void} + */ + public removeClass(field: string, classname: string, callback?: callback): void; + + /** + * Sets the placeholder of a {@link module:braintree-web/hosted-fields~field field}. + * @public + * @param {string} field The field whose placeholder you wish to change. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}. + * @param {string} placeholder Will be used as the `placeholder` attribute of the input. + * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the placeholder updated successfully. + * + * @example + * hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr) { + * if (placeholderErr) { + * console.error(placeholderErr); + * } + * }); + * + * @example Update CVV field on card type change + * hostedFieldsInstance.on('cardTypeChange', function (event) { + * // Update the placeholder value if there is only one possible card type + * if (event.cards.length === 1) { + * hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr) { + * if (placeholderErr) { + * // Handle errors, such as invalid field name + * console.error(placeholderErr); + * } + * }); + * } + * }); + * @returns {void} + */ + public setPlaceholder(field: string, placeholder: string, callback?: callback): void; + + /** + * Clear the value of a {@link module:braintree-web/hosted-fields~field field}. + * @public + * @param {string} field The field whose placeholder you wish to clear. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}. + * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the field cleared successfully. + * @returns {void} + * @example + * hostedFieldsInstance.clear('number', function (clearErr) { + * if (clearErr) { + * console.error(clearErr); + * } + * }); + * + * @example Clear several fields + * hostedFieldsInstance.clear('number'); + * hostedFieldsInstance.clear('cvv'); + * hostedFieldsInstance.clear('expirationDate'); + */ + public clear(field: string, callback?: callback): void; + + /** + * Returns an {@link HostedFields~stateObject|object} that includes the state of all fields and possible card types. + * @public + * @returns {object} {@link HostedFields~stateObject|stateObject} + * @example Check if all fields are valid + * var state = hostedFields.getState(); + * + * var formValid = Object.keys(state.fields).every(function (key) { + * return state.fields[key].isValid; + * }); + */ + public getState(): any; + } +} + +/** @module braintree-web/paypal */ +declare namespace BraintreeWeb { + /** + * @typedef {object} PayPal~tokenizeReturn + * @property {Function} close A handle to close the PayPal checkout flow. + */ + interface PayPalTokenizeReturn { + close: (() => any); + } + + /** + * @typedef {object} PayPal~tokenizePayload + * @property {string} nonce The payment method nonce. + * @property {string} type The payment method type, always `PayPalAccount`. + * @property {object} details Additional PayPal account details. + * @property {string} details.email User's email address. + * @property {string} details.payerId User's payer ID, the unique identifier for each PayPal account. + * @property {string} details.firstName User's given name. + * @property {string} details.lastName User's surname. + * @property {?string} details.countryCode User's 2 character country code. + * @property {?string} details.phone User's phone number (e.g. 555-867-5309). + * @property {?object} details.shippingAddress User's shipping address details, only available if shipping address is enabled. + * @property {string} details.shippingAddress.recipientName Recipient of postage. + * @property {string} details.shippingAddress.line1 Street number and name. + * @property {string} details.shippingAddress.line2 Extended address. + * @property {string} details.shippingAddress.city City or locality. + * @property {string} details.shippingAddress.state State or region. + * @property {string} details.shippingAddress.postalCode Postal code. + * @property {string} details.shippingAddress.countryCode 2 character country code (e.g. US). + * @property {?object} details.billingAddress User's billing address details. + * You will also need to enable the PayPal Billing Address Request feature in your PayPal account. + * To enable this feature, [contact PayPal](https://developers.braintreepayments.com/support/guides/paypal/setup-guide#contacting-paypal-support). + * @property {string} details.billingAddress.line1 Street number and name. + * @property {string} details.billingAddress.line2 Extended address. + * @property {string} details.billingAddress.city City or locality. + * @property {string} details.billingAddress.state State or region. + * @property {string} details.billingAddress.postalCode Postal code. + * @property {string} details.billingAddress.countryCode 2 character country code (e.g. US). + */ + interface PayPalShippingAddress { + recipientName: string; + line1: string; + line2: string; + city: string; + state: string; + postalCode: string; + countryCode: string; + } + + interface PayPalBillingAddress { + line1: string; + line2: string; + city: string; + state: string; + postalCode: string; + countryCode: string; + } + + interface PayPalAccountDetails { + email: string; + payerId: string; + firstName: string; + lastName: string; + countryCode: string; + phone: string; + shippingAddress: PayPalShippingAddress; + billingAddress: PayPalBillingAddress; + } + + interface PayPalTokenizePayload { + nonce: string; + type: string; + details: PayPalAccountDetails; + } + + export interface PayPal { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {callback} callback The second argument, `data`, is the {@link PayPal} instance. + * @example + * braintree.paypal.create( + * client: clientInstance + * }, function (createErr, paypalInstance) { + * if (createErr) { + * if (createErr.code === 'PAYPAL_BROWSER_NOT_SUPPORTED') { + * console.error('This browser is not supported.'); + * } else { + * console.error('Error!', createErr); + * } + * } + * } + * @returns {void} + */ + create: (options: { client: Client }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {object} options see {@link module:braintree-web/paypal.create|paypal.create} + * @classdesc This class represents a PayPal component. Instances of this class have methods for launching auth dialogs and other programmatic interactions with the PayPal component. + */ + export class PayPal { + /** + * @class + * @param {object} options see {@link module:braintree-web/paypal.create|paypal.create} + * @classdesc This class represents a PayPal component. Instances of this class have methods for launching auth dialogs and other programmatic interactions with the PayPal component. + */ + constructor(options: any); + + /** + * Launches the PayPal login flow and returns a nonce payload. Only one PayPal login flow should be active at a time. One way to achieve this is to disable your PayPal button while the flow is open. + * @public + * @param {object} options All tokenization options for the PayPal component. + * @param {string} options.flow Set to 'checkout' for one-time payment flow, or 'vault' for Vault flow. If 'vault' is used with a client token generated with a customer id, the PayPal account will be added to that customer as a saved payment method. + * @param {string} [options.intent=authorize] + * Checkout flows only. + * * `authorize` - Submits the transaction for authorization but not settlement. + * * `sale` - Payment will be immediately submitted for settlement upon creating a transaction. + * @param {boolean} [options.offerCredit=false] Offers the customer PayPal Credit if they qualify. Checkout flows only. + * @param {string} [options.useraction] + * Changes the call-to-action in the PayPal flow. By default the final button will show the localized + * word for "Continue" and implies that the final amount billed is not yet known. + * + * Setting this option to `commit` changes the button text to "Pay Now" and page text will convey to + * the user that billing will take place immediately. + * @param {string|number} [options.amount] The amount of the transaction. Required when using the Checkout flow. + * @param {string} [options.currency] The currency code of the amount, such as 'USD'. Required when using the Checkout flow. + * @param {string} [options.displayName] The merchant name displayed inside of the PayPal lightbox; defaults to the company name on your Braintree account + * @param {string} [options.locale=en_US] Use this option to change the language, links, and terminology used in the PayPal flow to suit the country and language of your customer. + * @param {boolean} [options.enableShippingAddress=false] Returns a shipping address object in {@link PayPal#tokenize}. + * @param {object} [options.shippingAddressOverride] Allows you to pass a shipping address you have already collected into the PayPal payment flow. + * @param {string} options.shippingAddressOverride.line1 Street address. + * @param {string} [options.shippingAddressOverride.line2] Street address (extended). + * @param {string} options.shippingAddressOverride.city City. + * @param {string} options.shippingAddressOverride.state State. + * @param {string} options.shippingAddressOverride.postalCode Postal code. + * @param {string} options.shippingAddressOverride.countryCode Country. + * @param {string} [options.shippingAddressOverride.phone] Phone number. + * @param {string} [options.shippingAddressOverride.recipientName] Recipient's name. + * @param {boolean} [options.shippingAddressEditable=true] Set to false to disable user editing of the shipping address. + * @param {string} [options.billingAgreementDescription] Use this option to set the description of the preapproved payment agreement visible to customers in their PayPal profile during Vault flows. Max 255 characters. + * @param {callback} callback The second argument, data, is a {@link PayPal~tokenizePayload|tokenizePayload}. + * @example + * button.addEventListener('click', function () { + * // Disable the button so that we don't attempt to open multiple popups. + * button.setAttribute('disabled', 'disabled'); + * + * // Because PayPal tokenization opens a popup, this must be called + * // as a result of a user action, such as a button click. + * paypalInstance.tokenize({ + * flow: 'vault' // Required + * // Any other tokenization options + * }, function (tokenizeErr, payload) { + * button.removeAttribute('disabled'); + * + * if (tokenizeErr) { + * // Handle tokenization errors or premature flow closure + * + * switch (tokenizeErr.code) { + * case 'PAYPAL_POPUP_CLOSED': + * console.error('Customer closed PayPal popup.'); + * break; + * case 'PAYPAL_ACCOUNT_TOKENIZATION_FAILED': + * console.error('PayPal tokenization failed. See details:', tokenizeErr.details); + * break; + * case 'PAYPAL_FLOW_FAILED': + * console.error('Unable to initialize PayPal flow. Are your options correct?', tokenizeErr.details); + * break; + * default: + * console.error('Error!', tokenizeErr); + * } + * } else { + * // Submit payload.nonce to your server + * } + * }); + * }); + * @returns {PayPal~tokenizeReturn} A handle to close the PayPal checkout frame. + */ + public tokenize(options: { flow: string, intent: string, offerCredit: boolean, useraction: string, amount: (string | number), currency: string, displayName: string, locale: string, enableShippingAddress: boolean, shippingAddressOverride: PayPalShippingAddress, shippingAddressEditable: boolean, billingAgreementDescription: string }, callback: callback): PayPalTokenizeReturn; + + /** + * Cleanly tear down anything set up by {@link module:braintree-web/paypal.create|create}. + * @public + * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully. + * @returns {void} + */ + public teardown(callback?: () => void): void; + + } +} + +/** @module braintree-web/three-d-secure */ +declare namespace BraintreeWeb { + /** + * @typedef {object} ThreeDSecure~verifyPayload + * @property {string} nonce The new payment method nonce produced by the 3D Secure lookup. The original nonce passed into {@link ThreeDSecure#verifyCard|verifyCard} was consumed. This new nonce should be used to transact on your server. + * @property {object} details Additional account details. + * @property {string} details.cardType Type of card, ex: Visa, MasterCard. + * @property {string} details.lastTwo Last two digits of card number. + * @property {string} description A human-readable description. + * @property {boolean} liabilityShiftPossible Indicates whether the card was eligible for 3D Secure. + * @property {boolean} liabilityShifted Indicates whether the liability for fraud has been shifted away from the merchant. + */ + interface ThreeDSecureAccountDetails { + cardType: string; + lastTwo: string; + } + + interface ThreeDSecureVerifyPayload { + nonce: string; + details: ThreeDSecureAccountDetails; + description: string; + liabilityShiftPossible: boolean; + liabilityShifted: boolean; + } + + export interface ThreeDSecure { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {callback} callback The second argument, `data`, is the {@link ThreeDSecure} instance. + * @returns {void} + * @example + * braintree.threeDSecure.create({ + * client: client + * }, callback); + */ + create: (options: { client: Client }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {object} options 3D Secure {@link module:braintree-web/three-d-secure.create create} options + * @description Do not use this constructor directly. Use {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create} instead. + * @classdesc This class represents a ThreeDSecure component produced by {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create}. Instances of this class have a method for launching a 3D Secure authentication flow. + */ + export class ThreeDSecure { + /** + * @class + * @param {object} options 3D Secure {@link module:braintree-web/three-d-secure.create create} options + * @description Do not use this constructor directly. Use {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create} instead. + * @classdesc This class represents a ThreeDSecure component produced by {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create}. Instances of this class have a method for launching a 3D Secure authentication flow. + */ + constructor(options: any); + + + /** + * @callback ThreeDSecure~addFrameCallback + * @param {?BraintreeError} [err] `null` or `undefined` if there was no error. + * @param {HTMLIFrameElement} iframe An iframe element containing the bank's authentication page that you must put on your page. + * @description The callback used for options.addFrame in {@link ThreeDSecure#verifyCard|verifyCard}. + * @returns {void} + */ + addFrameCallback: (err?: BraintreeError, iframe?: HTMLIFrameElement) => void; + + /** + * @callback ThreeDSecure~removeFrameCallback + * @description The callback used for options.removeFrame in {@link ThreeDSecure#verifyCard|verifyCard}. + * @returns {void} + */ + removeFrameCallback: () => void; + + /** + * Launch the 3D Secure login flow, returning a nonce payload. + * @public + * @param {object} options Options for card verification. + * @param {string} options.nonce A nonce referencing the card to be verified. For example, this can be a nonce that was returned by Hosted Fields. + * @param {number} options.amount The amount of the transaction in the current merchant account's currency. For example, if you are running a transaction of $123.45 US dollars, `amount` would be 123.45. + * @param {errback} options.addFrame This {@link ThreeDSecure~addFrameCallback|addFrameCallback} will be called when the bank frame needs to be added to your page. + * @param {callback} options.removeFrame This {@link ThreeDSecure~removeFrameCallback|removeFrameCallback} will be called when the bank frame needs to be removed from your page. + * @param {errback} callback The second argument, data, is a {@link ThreeDSecure~verifyPayload|verifyPayload} + * @returns {void} + * @example + * Verifying an existing nonce with 3DS + * var my3DSContainer; + * + * threeDSecure.verifyCard({ + * nonce: existingNonce, + * amount: 123.45, + * addFrame: function (err, iframe) { + * // Set up your UI and add the iframe. + * my3DSContainer = document.createElement('div'); + * my3DSContainer.appendChild(iframe); + * document.body.appendChild(my3DSContainer); + * }, + * removeFrame: function () { + * // Remove UI that you added in addFrame. + * document.body.removeChild(my3DSContainer); + * } + * }, function (err, payload) { + * if (err) { + * console.error(err); + * return; + * } + * + * if (payload.liabilityShifted) { + * // Liablity has shifted + * submitNonceToServer(payload.nonce); + * } else if (payload.liabilityShiftPossible) { + * // Liablity may still be shifted + * // Decide if you want to submit the nonce + * } else { + * // Liablity has not shifted and will not shift + * // Decide if you want to submit the nonce + * } + * }); + */ + public verifyCard(options: { nonce: string, amount: number, addFrame: (err?: BraintreeError, iframe?: HTMLIFrameElement) => void, removeFrame: () => void }, callback: callback): void; + + /** + * Cancel the 3DS flow and return the verification payload if available. + * @public + * @param {errback} callback The second argument is a {@link ThreeDSecure~verifyPayload|verifyPayload}. If there is no verifyPayload (the initial lookup did not complete), an error will be returned. + * @returns {void} + * @example + * threeDSecure.cancelVerifyCard(function (err, verifyPayload) { + * if (err) { + * // Handle error + * console.log(err.message); // No verification payload available + * return; + * } + * + * verifyPayload.nonce; // The nonce returned from the 3ds lookup call + * verifyPayload.liabilityShifted; // boolean + * verifyPayload.liabilityShiftPossible; // boolean + * }); + */ + public cancelVerifyCard(callback: callback): void; + + /** + * Cleanly tear down anything set up by {@link module:braintree-web/three-d-secure.create|create} + * @public + * @param {errback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully. + * @returns {void} + */ + public teardown(callback?: callback): void; + } +} + +/** + * @module braintree-web/unionpay + * @description This module allows you to accept UnionPay payments. *It is currently in beta and is subject to change.* + */ +declare namespace BraintreeWeb { + /** + * @typedef {object} UnionPay~tokenizePayload + * @property {string} nonce The payment method nonce. + * @property {string} type Always CreditCard. + * @property {object} details Additional account details: + * @property {string} details.cardType Type of card, ex: Visa, MasterCard. + * @property {string} details.lastTwo Last two digits of card number. + * @property {string} description A human-readable description. + */ + interface UnionPayAccountDetails { + cardType: string; + lastTwo: string; + description: string; + } + + interface UnionPayTokenizePayload { + nonce: string; + type: string; + details: UnionPayAccountDetails; + } + + /** + * @typedef {object} UnionPay~enrollPayload + * @property {string} enrollmentId UnionPay enrollment ID. This value should be passed to `tokenize`. + * @property {boolean} smsCodeRequired UnionPay `smsCodeRequired` flag. + *

      true - the user will receive an SMS code that needs to be supplied for tokenization. + *

      false - the card can be immediately tokenized. + */ + interface UnionPayEnrollPayload { + enrollmentId: string; + smsCodeRequired: boolean; + } + + /** + * @typedef {object} UnionPay~fetchCapabilitiesPayload + * @property {boolean} isUnionPay Determines if this card is a UnionPay card. + * @property {boolean} isDebit Determines if this card is a debit card. This property is only present if `isUnionPay` is `true`. + * @property {object} unionPay UnionPay specific properties. This property is only present if `isUnionPay` is `true`. + * @property {boolean} unionPay.supportsTwoStepAuthAndCapture Determines if the card allows for an authorization, but settling the transaction later. + * @property {boolean} unionPay.isSupported Determines if Braintree can process this UnionPay card. When false, Braintree cannot process this card and the user should use a different card. + */ + + interface UnionPayProperties { + supportsTwoStepAuthAndCapture: boolean; + isSupported: boolean; + } + + interface UnionPayFetchCapabilitiesPayload { + isUnionPay: boolean; + isDebit: boolean; + unionPay: UnionPayProperties; + } + + export interface UnionPay { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {callback} callback The second argument, `data`, is the {@link UnionPay} instance. + * @returns {void} + * @example + * braintree.unionpay.create({ client: clientInstance }, function (createErr, unionpayInstance) { + * if (createErr) { + * console.error(createErr); + * return; + * } + * // ... + * }); + */ + create: (options: { client: Client }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {object} options See {@link module:braintree-web/unionpay.create|unionpay.create}. + * @description You cannot use this constructor directly. Use {@link module:braintree-web/unionpay.create|braintree-web.unionpay.create} instead. + * @classdesc This class represents a UnionPay component. Instances of this class have methods for {@link UnionPay#fetchCapabilities fetching capabilities} of UnionPay cards, {@link UnionPay#enroll enrolling} a UnionPay card, and {@link UnionPay#tokenize tokenizing} a UnionPay card. + */ + export class UnionPay { + /** + * @class + * @param {object} options See {@link module:braintree-web/unionpay.create|unionpay.create}. + * @description You cannot use this constructor directly. Use {@link module:braintree-web/unionpay.create|braintree-web.unionpay.create} instead. + * @classdesc This class represents a UnionPay component. Instances of this class have methods for {@link UnionPay#fetchCapabilities fetching capabilities} of UnionPay cards, {@link UnionPay#enroll enrolling} a UnionPay card, and {@link UnionPay#tokenize tokenizing} a UnionPay card. + */ + constructor(options: any); + + /** + * Fetches the capabilities of a card, including whether or not the SMS enrollment process is required. + * @public + * @param {object} options UnionPay {@link UnionPay#fetchCapabilities fetchCapabilities} options + * @param {object} [options.card] The card from which to fetch capabilities. Note that this will only have one property, `number`. Required if you are not using the `hostedFields` option. + * @param {string} options.card.number Card number. + * @param {HostedFields} [options.hostedFields] The Hosted Fields instance used to collect card data. Required if you are not using the `card` option. + * @param {callback} callback The second argument, data, is a {@link UnionPay#fetchCapabilitiesPayload fetchCapabilitiesPayload}. + * @example With raw card data + * unionpayInstance.fetchCapabilities({ + * card: { + * number: '4111111111111111' + * } + * }, function (fetchErr, cardCapabilities) { + * if (fetchErr) { + * console.error(fetchErr); + * return; + * } + * + * if (cardCapabilities.isUnionPay) { + * if (cardCapabilities.unionPay && !cardCapabilities.unionPay.isSupported) { + * // Braintree cannot process this UnionPay card. + * // Ask the user for a different card. + * return; + * } + * + * if (cardCapabilities.isDebit) { + * // CVV and expiration date are not required + * } else { + * // CVV and expiration date are required + * } + * + * // Show mobile phone number field for enrollment + * } + * }); + * @example With Hosted Fields + * // Fetch capabilities on `blur` inside of the Hosted Fields `create` callback + * hostedFieldsInstance.on('blur', function (event) { + * // Only attempt to fetch capabilities when a valid card number has been entered + * if (event.emittedBy === 'number' && event.fields.number.isValid) { + * unionpayInstance.fetchCapabilities({ + * hostedFields: hostedFieldsInstance + * }, function (fetchErr, cardCapabilities) { + * if (fetchErr) { + * console.error(fetchErr); + * return; + * } + * + * if (cardCapabilities.isUnionPay) { + * if (cardCapabilities.unionPay && !cardCapabilities.unionPay.isSupported) { + * // Braintree cannot process this UnionPay card. + * // Ask the user for a different card. + * return; + * } + * if (cardCapabilities.isDebit) { + * // CVV and expiration date are not required + * // Hide the containers with your `cvv` and `expirationDate` fields + * } else { + * // CVV and expiration date are required + * } + * } else { + * // Not a UnionPay card + * // When form is complete, tokenize using your Hosted Fields instance + * } + * + * // Show your own mobile country code and phone number inputs for enrollment + * }); + * }); + * }); + * @returns {void} + */ + public fetchCapabilities(options: { card: any, hostedFields: HostedFields }, callback: callback): void; + + /** + * Enrolls a UnionPay card. Use {@link UnionPay#fetchCapabilities|fetchCapabilities} to determine if the SMS enrollment process is required. + * @public + * @param {object} options UnionPay enrollment options: + * @param {object} [options.card] The card to enroll. Required if you are not using the `hostedFields` option. + * @param {string} options.card.number The card number. + * @param {string} [options.card.expirationDate] The card's expiration date. May be in the form `MM/YY` or `MM/YYYY`. When defined `expirationMonth` and `expirationYear` are ignored. + * @param {string} [options.card.expirationMonth] The card's expiration month. This should be used with the `expirationYear` parameter. When `expirationDate` is defined this parameter is ignored. + * @param {string} [options.card.expirationYear] The card's expiration year. This should be used with the `expirationMonth` parameter. When `expirationDate` is defined this parameter is ignored. + * @param {HostedFields} [options.hostedFields] The Hosted Fields instance used to collect card data. Required if you are not using the `card` option. + * @param {object} options.mobile The mobile information collected from the customer. + * @param {string} options.mobile.countryCode The country code of the customer's mobile phone number. + * @param {string} options.mobile.number The customer's mobile phone number. + * @param {callback} callback The second argument, data, is a {@link UnionPay~enrollPayload|enrollPayload}. + * @example With raw card data + * unionpayInstance.enroll({ + * card: { + * number: '4111111111111111', + * expirationMonth: '12', + * expirationYear: '2038' + * }, + * mobile: { + * countryCode: '62', + * number: '111111111111' + * } + * }, function (enrollErr, response) { + * if (enrollErr) { + * console.error(enrollErr); + * return; + * } + * + * if (response.smsCodeRequired) { + * // If smsCodeRequired, wait for SMS auth code from customer + * // Then use response.enrollmentId during {@link UnionPay#tokenize} + * } else { + * // SMS code is not required from the user. + * // {@link UnionPay#tokenize} can be called immediately + * }); + * @example With Hosted Fields + * unionpayInstance.enroll({ + * hostedFields: hostedFields, + * mobile: { + * countryCode: '62', + * number: '111111111111' + * } + * }, function (enrollErr, response) { + * if (enrollErr) { + * console.error(enrollErr); + * return; + * } + * + * if (response.smsCodeRequired) { + * // If smsCodeRequired, wait for SMS auth code from customer + * // Then use response.enrollmentId during {@link UnionPay#tokenize} + * } else { + * // SMS code is not required from the user. + * // {@link UnionPay#tokenize} can be called immediately + * } + * }); + * @returns {void} + */ + public enroll(options: { card: any, hostedFields: HostedFields, mobile: any }, callback: callback): void; + + /** + * Tokenizes a UnionPay card and returns a nonce payload. + * @public + * @param {object} options UnionPay tokenization options: + * @param {object} [options.card] The card to enroll. Required if you are not using the `hostedFields` option. + * @param {string} options.card.number The card number. + * @param {string} [options.card.expirationDate] The card's expiration date. May be in the form `MM/YY` or `MM/YYYY`. When defined `expirationMonth` and `expirationYear` are ignored. + * @param {string} [options.card.expirationMonth] The card's expiration month. This should be used with the `expirationYear` parameter. When `expirationDate` is defined this parameter is ignored. + * @param {string} [options.card.expirationYear] The card's expiration year. This should be used with the `expirationMonth` parameter. When `expirationDate` is defined this parameter is ignored. + * @param {string} [options.card.cvv] The card's security number. + * @param {HostedFields} [options.hostedFields] The Hosted Fields instance used to collect card data. Required if you are not using the `card` option. + * @param {string} options.enrollmentId The enrollment ID from {@link UnionPay#enroll}. + * @param {string} [options.smsCode] The SMS code received from the user if {@link UnionPay#enroll} payload have `smsCodeRequired`. if `smsCodeRequired` is false, smsCode should not be passed. + * @param {callback} callback The second argument, data, is a {@link UnionPay~tokenizePayload|tokenizePayload}. + * @example With raw card data + * unionpayInstance.tokenize({ + * card: { + * number: '4111111111111111', + * expirationMonth: '12', + * expirationYear: '2038', + * cvv: '123' + * }, + * enrollmentId: enrollResponse.enrollmentId, // Returned from enroll + * smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted + * }, function (tokenizeErr, response) { + * if (tokenizeErr) { + * console.error(tokenizeErr); + * return; + * } + * + * // Send response.nonce to your server + * }); + * @example With Hosted Fields + * unionpayInstance.tokenize({ + * hostedFields: hostedFieldsInstance, + * enrollmentId: enrollResponse.enrollmentId, // Returned from enroll + * smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted + * }, function (tokenizeErr, response) { + * if (tokenizeErr) { + * console.error(tokenizeErr); + * return; + * } + * + * // Send response.nonce to your server + * }); + * @returns {void} + */ + public tokenize(options: { card: any, hostedFields: HostedFields, enrollmentId: string, smsCode: string }, callback: callback): void; + + /** + * Cleanly tear down anything set up by {@link module:braintree-web/unionpay.create|create}. This only needs to be called when using UnionPay with Hosted Fields. + * @public + * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully. + * @example + * unionpayInstance.teardown(function (teardownErr) { + * if (teardownErr) { + * console.error('Could not tear down UnionPay.'); + * } else { + * console.log('UnionPay has been torn down.'); + * } + * }); + * @returns {void} + */ + public teardown(callback?: callback): void; + + } +} + +declare namespace BraintreeError { + /** + * Enum for {@link BraintreeError} types. + * @name BraintreeError.types + * @enum + * @readonly + * @memberof BraintreeError + * @property {string} CUSTOMER An error caused by the customer. + * @property {string} MERCHANT An error that is actionable by the merchant. + * @property {string} NETWORK An error due to a network problem. + * @property {string} INTERNAL An error caused by Braintree code. + * @property {string} UNKNOWN An error where the origin is unknown. + */ + export enum Types { + CUSTOMER, + MERCHANT, + NETWORK, + INTERNAL, + UNKNOWN + } +} + +/** + * @class + * @global + * @param {object} options Construction options + * @classdesc This class is used to report error conditions, frequently as the first parameter to callbacks throughout the Braintree SDK. + * @description You cannot use this constructor directly. Interact with instances of this class through {@link callback callbacks}. + */ +declare class BraintreeError { + /** + * @class + * @global + * @param {object} options Construction options + * @classdesc This class is used to report error conditions, frequently as the first parameter to callbacks throughout the Braintree SDK. + * @description You cannot use this constructor directly. Interact with instances of this class through {@link callback callbacks}. + */ + constructor(options: any); + + /** + * @type {string} + * @description A code that corresponds to specific errors. + */ + code: string; + + /** + * @type {string} + * @description A short description of the error. + */ + message: string; + + /** + * @type {BraintreeError.types} + * @description The type of error. + */ + type: BraintreeError.Types; + + /** + * @type {object=} + * @description Additional information about the error, such as an underlying network error response. + */ + details: any; +} + +declare namespace BraintreeWeb { + /** + * @global + * @callback callback + * @param {?BraintreeError} [err] `null` or `undefined` if there was no error. + * @param {?any} [data] The successful result of the asynchronous function call (if data exists). + * @description The Node.js-style callback pattern used throughout the SDK. + * @returns {void} + */ + type callback = (err?: BraintreeError, data?: any) => void; +} + +/** + * @module braintree-web + * @description This is the top-level module exported by the Braintree JavaScript SDK. In a browser environment, this will be the global braintree object. In a CommonJS environment (like Browserify or Webpack), it will be the default export of the braintree-web package. In AMD environments (like RequireJS), it can be `require`d like other modules. + * @example + * CommonJS + * var braintree = require('braintree-web'); + * + * braintree.client.create(...); + * @example + * In the browser + * + * + * @example + * AMD + * // main.js + * require.config({ + * paths: { + * braintreeClient: 'https://js.braintreegateway.com/web/3.0.2/js/client.min' + * } + * }); + * + * require(['braintreeClient'], function (braintreeClient) { + * braintreeClient.create(...); + * }); + */ +interface BraintreeStatic { + /** @type {module:braintree-web/client} */ + client: BraintreeWeb.Client; + + /** @type {module:braintree-web/paypal} */ + paypal: BraintreeWeb.PayPal; + + /** @type {module:braintree-web/hosted-fields} */ + hostedFields: BraintreeWeb.HostedFields; + + /** @type {module:braintree-web/three-d-secure} */ + threeDSecure: BraintreeWeb.ThreeDSecure; + + /** @type {module:braintree-web/data-collector} */ + dataCollector: BraintreeWeb.DataCollector; + + /** @type {module:braintree-web/american-express} */ + americanExpress: BraintreeWeb.AmericanExpress; + + /** @type {module:braintree-web/unionpay} */ + unionpay: BraintreeWeb.UnionPay; + + /** @type {module:braintree-web/apple-pay} */ + applePay: BraintreeWeb.ApplePay; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; +} + +declare var braintree: BraintreeStatic; \ No newline at end of file diff --git a/breeze/breeze.d.ts b/breeze/breeze.d.ts index 3fc54dc5d4..8cc109d746 100644 --- a/breeze/breeze.d.ts +++ b/breeze/breeze.d.ts @@ -12,6 +12,7 @@ // Updated Jan 20 2015 for Breeze 1.5.2 and merging changes from DefinitelyTyped // Updated Feb 28 2015 add any/all clause on Predicate // Updated Jun 27 2016 - Marcel Good (www.ideablade.com) +// Updated Jul 28 2016 - Serkan "coni2k" Holat declare namespace breeze.core { @@ -1043,6 +1044,10 @@ declare namespace breeze.config { @return {an instance of the specified adapter} **/ export function getAdapterInstance(interfaceName: string, adapterName?: string): Object; + + export interface Adapter { + getRoutePrefix: Function + } /** Initializes a single adapter implementation. Initialization means either newing a instance of the specified interface and then calling "initialize" on it or simply calling "initialize" on the instance @@ -1052,7 +1057,7 @@ declare namespace breeze.config { @param isDefault=true {Boolean} - Whether to make this the default "adapter" for this interface. @return {an instance of the specified adapter} **/ - export function initializeAdapterInstance(interfaceName: string, adapterName: string, isDefault?: boolean): void; + export function initializeAdapterInstance(interfaceName: string, adapterName: string, isDefault?: boolean): Adapter; export interface AdapterInstancesConfig { /** the name of a previously registered "ajax" adapter */ diff --git a/bunnymq/bunnymq-tests.ts b/bunnymq/bunnymq-tests.ts new file mode 100644 index 0000000000..208eb7e992 --- /dev/null +++ b/bunnymq/bunnymq-tests.ts @@ -0,0 +1,36 @@ +/// + +import * as bunnymq from "bunnymq"; + +// Basic usage +var instance = bunnymq({ host: 'amqp://localhost' }); + +// Publisher +instance.producer.produce('queue:name', 'Hello World!'); +// Subscriber +instance.consumer.consume('queue:name', message => { }); + +// RPC Support +instance.producer.produce('queue:name', { message: 'content' }, { rpc: true }) + .then(function (consumerResponse) { + console.log(consumerResponse); + }); + +// Routing keys +instance.producer.produce('queue:name', { message: 'content' }, { routingKey: 'my-routing-key' }); + +// Config +var custom = bunnymq({ + host: 'amqp://localhost', + //number of fetched messages at once on the channel + prefetch: 5, + //requeue put back message into the broker if consumer crashes/trigger exception + requeue: true, + //time between two reconnect (ms) + timeout: 1000, + consumerSuffix: '', + //generate a hostname so we can track this connection on the broker (rabbitmq management plugin) + hostname: "", + //the transport to use to debug. if provided, bunnymq will show some logs + transport: new Object() +}); \ No newline at end of file diff --git a/bunnymq/bunnymq.d.ts b/bunnymq/bunnymq.d.ts new file mode 100644 index 0000000000..1167db21ed --- /dev/null +++ b/bunnymq/bunnymq.d.ts @@ -0,0 +1,120 @@ +// Type definitions for node-bunnymq 2.2.1 +// Project: https://github.com/dial-once/node-bunnymq +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "bunnymq" { + namespace bunnymq { + export type ConsumerCallback = (message: Object) => void; + + /** + * Consumer. + * @interface + */ + export interface Consumer { + /** + * Handle messages from a named queue. + * @param {string} queue A named queue. + * @param {ConsumerCallback} callback A callback. + */ + consume(queue: string, callback: ConsumerCallback): void; + } + + /** + * bunnymq instance. + * @interface + */ + export interface Instance { + /** + * Consumer. + * @type {Consumer} + */ + consumer: Consumer; + + /** + * Producer. + * @type {Producer} + */ + producer: Producer; + } + + /** + * Options. + * @interface + */ + export interface Options { + /** + * Consumer suffix. + * @type {string} + */ + consumerSuffix?: string; + + /** + * Host. + * @type {string} + */ + host?: string; + + /** + * Hostname. + * @type {string} + */ + hostname?: string; + + /** + * Number of fetched messages at once on the channel. + * @type {number} + */ + prefetch?: number; + + /** + * Requeue put back message into the broker if consumer crashes/trigger exception. + * @type {boolean} + */ + requeue?: boolean; + + /** + * Time between two reconnect (in milliseconds). + * @type {number} + */ + timeout?: number; + + /** + * Transport. + * @type {any} + */ + transport?: any; + } + + /** + * Producer. + * @inteface + */ + export interface Producer { + /** + * Send messages to a named queue. + * @param {string} queue A named queue. + * @param {Object} message A message. + * @return {Object} The consumer response. + */ + produce(queue: string, message: Object, options?: ProducerOptions): PromiseLike; + } + + /** + * Options for producer. + * @interface + */ + export interface ProducerOptions { + routingKey?: string; + rpc?: boolean; + } + } + + /** + * Constructor. + * @param {Options} [options] Options. + * @return {Instance} A instance of bunnymq. + */ + function bunnymq(options?: bunnymq.Options): bunnymq.Instance; + export = bunnymq; +} diff --git a/busboy/busboy-tests.ts b/busboy/busboy-tests.ts new file mode 100644 index 0000000000..058b5c92d3 --- /dev/null +++ b/busboy/busboy-tests.ts @@ -0,0 +1,39 @@ +/// +/// + +import * as Busboy from 'busboy'; +import * as http from 'http'; +import * as util from 'util'; + +function serverFn(req: http.ServerRequest, res: http.ServerResponse) { + if (req.method === 'POST') { + var busboy = new Busboy({ headers: req.headers }); + busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { + console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype); + file.on('data', function(data: Buffer) { + console.log('File [' + fieldname + '] got ' + data.length + ' bytes'); + }); + file.on('end', function() { + console.log('File [' + fieldname + '] Finished'); + }); + }); + busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) { + console.log('Field [' + fieldname + ']: value: ' + util.inspect(val)); + }); + busboy.on('finish', function() { + console.log('Done parsing form!'); + res.writeHead(303, { Connection: 'close', Location: '/' }); + res.end(); + }); + req.pipe(busboy); + } else if (req.method === 'GET') { + res.writeHead(200, { Connection: 'close' }); + res.end('\ +
      \ +
      \ +
      \ + \ +
      \ + '); + } +} diff --git a/busboy/busboy.d.ts b/busboy/busboy.d.ts new file mode 100644 index 0000000000..3b64f3d112 --- /dev/null +++ b/busboy/busboy.d.ts @@ -0,0 +1,60 @@ +// Type definitions for busboy v0.2.13 +// Project: https://www.npmjs.com/package/busboy +// Definitions by: Jacob Baskin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + +declare namespace busboy { + interface Options { + headers: any; + } + + interface BusboyConfig { + headers?: any; + highWaterMark?: number; + fileHwm?: number; + defCharset?: string; + preservePath?: boolean; + limits?: { + fieldNameSize?: number; + fieldSize?: number; + fields?: number; + fileSize?: number; + files?: number; + parts?: number; + headerPairs?: number; + }; + } + + interface Busboy extends NodeJS.WritableStream { + on(event: 'field', + listener: ( + fieldname: string, + val: any, + fieldnameTruncated: boolean, + valTruncated: boolean, + encoding: string, + mimetype: string) => void): this; + on(event: 'file', + listener: ( + fieldname: string, + file: NodeJS.ReadableStream, + filename: string, + encoding: string, + mimetype: string) => void): this; + on(event: 'finish', callback: () => void): this; + on(event: 'partsLimit', callback: () => void): this; + on(event: 'filesLimit', callback: () => void): this; + on(event: 'fieldsLimit', callback: () => void): this; + on(event: string, listener: Function): this; + } + + interface BusboyConstructor { + new (options: BusboyConfig): Busboy; + } +} + +declare module 'busboy' { + const temp: busboy.BusboyConstructor; + export = temp; +} diff --git a/bytes/bytes-tests.ts b/bytes/bytes-tests.ts index 4a981aee47..31f2f78b4e 100644 --- a/bytes/bytes-tests.ts +++ b/bytes/bytes-tests.ts @@ -8,9 +8,11 @@ console.log(bytes(104857, { thousandsSeparator: ' ' })); console.log(bytes.format(104857)); console.log(bytes.format(104857, { thousandsSeparator: ' ' })); - +console.log(bytes.format(104857, { decimalPlaces: 2 })); +console.log(bytes.format(104857, { fixedDecimals: true })); +console.log(bytes.format(104857, { unitSeparator: '-' })); console.log(bytes('1024kb')); console.log(bytes(1024)); console.log(bytes.parse('1024kb')); -console.log(bytes.parse(1024)); \ No newline at end of file +console.log(bytes.parse(1024)); diff --git a/bytes/bytes.d.ts b/bytes/bytes.d.ts index b99ebee7c6..bd3a2f93bd 100644 --- a/bytes/bytes.d.ts +++ b/bytes/bytes.d.ts @@ -1,10 +1,15 @@ -// Type definitions for bytes v2.1.0 +// Type definitions for bytes v2.4.0 // Project: https://github.com/visionmedia/bytes.js // Definitions by: Zhiyuan Wang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'bytes' { - + interface BytesOptions { + decimalPlaces?: number, + thousandsSeparator?: string, + unitSeparator?: string, + fixedDecimals?: boolean + } /** *Convert the given value in bytes into a string. * @@ -15,7 +20,7 @@ declare module 'bytes' { * * @returns {string} */ - function bytes(value: number, options?: { thousandsSeparator: string }): string; + function bytes(value: number, options?: BytesOptions): string; /** *Parse string to an integer in bytes. @@ -37,7 +42,7 @@ declare module 'bytes' { * @param {BytesFormatOptions} [options] */ - function format(value: number, options?: { thousandsSeparator: string }): string; + function format(value: number, options?: BytesOptions): string; /** * Just return the input number value. diff --git a/c3/c3.d.ts b/c3/c3.d.ts index f5159090d2..e815b44391 100644 --- a/c3/c3.d.ts +++ b/c3/c3.d.ts @@ -681,7 +681,7 @@ declare namespace c3 { * Specified function receives name, ratio, id and index of the data point to show. ratio will be undefined if the chart is not donut/pie/gauge. * If undefined returned, the row of that value will be skipped. */ - value?: (name: string, ratio: number, id: string, index: number) => string; + value?: (value: any, ratio: number, id: string, index: number) => string; }; /** * Set custom position for the tooltip. This option can be used to modify the tooltip position by returning object that has top and left. @@ -747,7 +747,7 @@ declare namespace c3 { /** * The radius size of each point. */ - r?: number; + r?: number | ((d: any) => number); focus?: { expand: { diff --git a/cache-manager/cache-manager.d.ts b/cache-manager/cache-manager.d.ts index 9570857f01..de6cf867a7 100644 --- a/cache-manager/cache-manager.d.ts +++ b/cache-manager/cache-manager.d.ts @@ -28,7 +28,7 @@ declare module 'cache-manager' { module cacheManager { - function caching(ICongig: StoreConfig): Cache; + function caching(IConfig: StoreConfig): Cache; function multiCaching(Caches: Cache[]): Cache; } diff --git a/canvas-gauges/canvas-gauges-tests.ts b/canvas-gauges/canvas-gauges-tests.ts new file mode 100644 index 0000000000..d0f04e1082 --- /dev/null +++ b/canvas-gauges/canvas-gauges-tests.ts @@ -0,0 +1,20 @@ +/// + +import { + LinearGaugeOptions, + RadialGaugeOptions, + LinearGauge, + RadialGauge +} from 'canvas-gauges'; + +let linearOptions: LinearGaugeOptions = { + renderTo: document.createElement('canvas') +}; +let radialOptions: RadialGaugeOptions = { + renderTo: 'gauge-id' +}; + +new LinearGauge(linearOptions); +new RadialGauge(radialOptions); + +console.log(document.gauges.length); diff --git a/canvas-gauges/canvas-gauges.d.ts b/canvas-gauges/canvas-gauges.d.ts new file mode 100644 index 0000000000..53858e566e --- /dev/null +++ b/canvas-gauges/canvas-gauges.d.ts @@ -0,0 +1,263 @@ +// Type definitions for canvas-gauges +// Project: https://github.com/Mikhus/canvas-gauges +// Definitions by: Mikhus +// Definitions: https://github.com/Mikhus/DefinitelyTyped + +declare namespace CanvasGauges { + export type RenderTarget = string|HTMLElement; + + export interface AnimationRule { + (percent: number): number; + } + + export interface Highlight { + from: number, + to: number, + color: string + } + + export type MajorTicks = string[]|number[]; + + export interface GenericOptions { + renderTo: RenderTarget, + width?: number, + height?: number, + minValue?: number, + maxValue?: number, + value?: number, + units?: string|boolean, + majorTicks?: MajorTicks, + minorTicks?: number, + strokeTicks?: boolean, + animatedValue?: boolean, + title?: string|boolean, + borders?: boolean, + valueInt?: number, + valueDec?: number, + majorTicksInt?: number, + majorTicksDec?: number, + animation?: boolean, + animationDuration?: number, + animationRule?: string|AnimationRule, + colorPlate?: string, + colorMajorTicks?: string, + colorMinorTicks?: string, + colorTitle?: string, + colorUnits?: string, + colorNumbers?: string, + colorNeedle?: string, + colorNeedleEnd?: string, + colorValueText?: string, + colorValueTextShadow?: string, + colorBorderShadow?: string, + colorBorderOuter?: string, + colorBorderOuterEnd?: string, + colorBorderMiddle?: string, + colorBorderMiddleEnd?: string, + colorBorderInner?: string, + colorBorderInnerEnd?: string, + colorValueBoxRect?: string, + colorValueBoxRectEnd?: string, + colorValueBoxBackground?: string, + colorValueBoxShadow?: string, + colorNeedleShadowUp?: string, + colorNeedleShadowDown?: string, + needle?: boolean, + needleShadow?: boolean, + needleType?: string, + needleStart?: number, + needleEnd?: number, + needleWidth?: number, + borderOuterWidth?: number, + borderMiddleWidth?: number, + borderInnerWidth?: number, + borderShadowWidth?: number, + valueBox?: boolean, + valueBoxStroke?: number, + valueText?: string, + valueTextShadow?: boolean, + valueBoxBorderRadius?: number, + highlights?: Highlight[], + fontNumbers?: string, + fontTitle?: string, + fontUnits?: string, + fontValue?: string, + fontTitleSize?: number, + fontValueSize?: number, + fontUnitsSize?: number, + fontNumbersSize?: number + } + + export interface RadialGaugeOptions extends GenericOptions { + ticksAngle?: number, + startAngle?: number, + colorNeedleCircleOuter?: string, + colorNeedleCircleOuterEnd?: string, + colorNeedleCircleInner?: string, + colorNeedleCircleInnerEnd?: string, + needleCircleSize?: number, + needleCircleInner?: boolean, + needleCircleOuter?: boolean, + animationTarget?: string + } + + export interface LinearGaugeOptions extends GenericOptions { + borderRadius?: number, + barBeginCircle?: number, + barWidth?: number, + barStrokeWidth?: number, + barProgress?: boolean, + colorBar?: string, + colorBarEnd?: string, + colorBarStroke?: string, + colorBarProgress?: string, + colorBarProgressEnd?: string, + tickSide?: string, + needleSide?: string, + numberSide?: string, + ticksWidth?: number, + ticksWidthMinor?: number, + ticksPadding?: number, + barLength?: number + } + + export interface DrawEventCallback { + (percent: number): any; + } + + export interface EndEventCallback { + (): any; + } + + export interface rules { + linear: AnimationRule, + quad: AnimationRule, + dequad: AnimationRule, + quint: AnimationRule, + dequint: AnimationRule, + cycle: AnimationRule, + decycle: AnimationRule, + bounce: AnimationRule, + debounce: AnimationRule, + elastic: AnimationRule, + delastic: AnimationRule + } + + export class Animation { + public duration: number; + public rule: string|AnimationRule; + public draw: DrawEventCallback; + public end: EndEventCallback; + + public static rules: rules; + + constructor(rule?: string|AnimationRule, duration?: number, + draw?: DrawEventCallback, end?: EndEventCallback); + + public animate(draw?: DrawEventCallback, end?: EndEventCallback): any; + public destroy(): any; + } + + export class SmartCanvas { + public element: HTMLCanvasElement; + public elementClone: HTMLCanvasElement; + public context: CanvasRenderingContext2D; + public contextClone: CanvasRenderingContext2D; + public drawWidth: number; + public drawHeight: number; + public drawX: number; + public drawY: number; + public minSide: number; + public width: number; + public height: number; + + constructor(element: HTMLCanvasElement, + width?: number, + height?: number); + + public init(): any; + public onRedraw(): any; + public destroy(): any; + public commit(): SmartCanvas; + public redraw(): SmartCanvas; + + public pixelRatio: number; + public static redraw(): any; + public static collection: Array; + } + + export class DomObserver { + public Type: BaseGauge; + public mutationsObserved: boolean; + public isObservable: boolean; + public options: GenericOptions; + public element: string; + public type: string; + + constructor(options: GenericOptions, + element: string, + type: string); + + public isValidNode(node: Node|HTMLElement): boolean; + public traverse(): any; + public observe(records: MutationRecord[]): any; + public process(node: Node|HTMLElement): BaseGauge; + + public static parse(value: any): any; + public static toDashed(camelCase: string): string; + public static toAttributeName(str: string): string; + static domReady(handler: Function): any; + } + + export abstract class BaseGauge { + public type: BaseGauge; + public options: GenericOptions; + public canvas: SmartCanvas; + public animation: Animation; + public value: number; + + constructor(options: GenericOptions); + + public update(options: GenericOptions): BaseGauge; + public destroy(): any; + public abstract draw(): BaseGauge; + + public static initialize(type: string, options: GenericOptions): any; + } + + export class RadialGauge extends BaseGauge { + public type: RadialGauge; + public options: RadialGaugeOptions; + + constructor(options: RadialGaugeOptions); + + public draw(): RadialGauge; + } + + export class LinearGauge extends BaseGauge { + public type: LinearGauge; + public options: LinearGaugeOptions; + + constructor(options: LinearGaugeOptions); + + public draw(): LinearGauge; + } + + export interface Collection extends Array { + get: (id: number | string) => BaseGauge; + } +} + +declare module 'canvas-gauges' { + export = CanvasGauges; +} + +interface Document { + gauges: CanvasGauges.Collection; +} + +interface Window { + BaseGauge: CanvasGauges.BaseGauge; + RadialGauge: CanvasGauges.RadialGauge; + LinearGauge: CanvasGauges.LinearGauge; +} diff --git a/cassandra-driver/cassandra-driver.d.ts b/cassandra-driver/cassandra-driver.d.ts index 0da40f2081..9a4184b62e 100644 --- a/cassandra-driver/cassandra-driver.d.ts +++ b/cassandra-driver/cassandra-driver.d.ts @@ -16,10 +16,10 @@ declare module "cassandra-driver" { namespace policies { namespace addressResolution { - var EC2MultiRegionTranslator: EC2MultiRegionTranslatorStatic; + var EC2MultiRegionTranslator: EC2MultiRegionTranslatorStatic; interface AddressTranslator { - translate(address: string, port: number, callback: Callback): void; + translate(address: string, port: number, callback: Callback): void; } interface EC2MultiRegionTranslatorStatic { @@ -141,7 +141,7 @@ declare module "cassandra-driver" { var Tuple: TupleStatic; var Uuid: UuidStatic; - enum consistencies { + enum consistencies { any = 0, one, two, @@ -154,7 +154,7 @@ declare module "cassandra-driver" { localSerial, localOne } - + enum dataTypes { custom = 0, ascii, @@ -204,7 +204,7 @@ declare module "cassandra-driver" { fromString(value: string): BigDecimal; fromNumber(value: number): BigDecimal; } - + interface BigDecimal { equals(other: BigDecimal): boolean; inspect(): string; @@ -239,7 +239,7 @@ declare module "cassandra-driver" { interface IntegerStatic { new(bits: Array, sign: number): Integer; - + fromInt(value: number): Integer; fromNumber(value: number): Integer; fromBits(bits: Array): Integer; @@ -295,7 +295,7 @@ declare module "cassandra-driver" { fromString(value: string): LocalDate; fromBuffer(buffer: Buffer): LocalDate; } - + interface LocalDate { _value: number; year: number; @@ -384,7 +384,7 @@ declare module "cassandra-driver" { interface TimeUuidStatic { new (value?: Date, ticks?: number, nodeId?: string|Buffer, clockId?: string|Buffer): TimeUuid; - + fromDate(date: Date, ticks?: number, nodeId?: string|Buffer, clockId?: string|Buffer): TimeUuid; fromString(value: string): TimeUuid; min(date: Date, ticks?: number): TimeUuid; @@ -408,7 +408,7 @@ declare module "cassandra-driver" { interface Tuple { elements: Array; length: number; - + get(index: number): any; toString(): string; toJSON(): string; @@ -480,10 +480,10 @@ declare module "cassandra-driver" { interface QueryOptions { autoPage?: boolean; captureStackTrace?: boolean; - consistency: number; + consistency?: number; customPayload?: any; fetchSize?: number; - hints: Array | Array>; + hints?: Array | Array>; logged?: boolean; pageState?: Buffer|string; prepare?: boolean; @@ -513,7 +513,7 @@ declare module "cassandra-driver" { execute(query: string, params?: any, options?: QueryOptions, callback?: ResultCallback): void; getReplicas(keyspace: string, token: Buffer): Array; // TODO: Should this be a more explicit return? shutdown(callback?: Callback): void; - stream(query: string, params?: any, options?: QueryOptions, callback?: Callback): void; + stream(query: string, params?: any, options?: QueryOptions, callback?: Callback): NodeJS.ReadableStream; } interface HostStatic { @@ -549,7 +549,7 @@ declare module "cassandra-driver" { } interface EncoderStatic { - new(protocolVersion: number, options: ClientOptions) : Encoder; + new(protocolVersion: number, options: ClientOptions) : Encoder; } interface Encoder { @@ -590,29 +590,29 @@ declare module "cassandra-driver" { } class ArgumentError extends DriverError { - constructor(message: string); + constructor(message: string); } class AuthenticationError extends DriverError { - constructor(message: string); + constructor(message: string); } class DriverInternalError extends DriverError { - constructor(message: string); + constructor(message: string); } class NoHostAvailableError extends DriverError { - constructor(innerErrors: any, message?: string); + constructor(innerErrors: any, message?: string); } class NotSupportedError extends DriverError { - constructor(message: string); + constructor(message: string); } class OperationTimedOutError extends DriverError {} class ResponseError extends DriverError { - constructor(code: number, message: string); + constructor(code: number, message: string); } } @@ -688,7 +688,7 @@ declare module "cassandra-driver" { interface IndexStatic { new (name: string, target: string, kind: IndexType, options: Object): Index; - + fromRows(indexRows: Array): Array; fromColumnRows(columnRows: Array, columnsByName: { [key:string]: ColumnInfo }): Array; } @@ -758,4 +758,4 @@ declare module "cassandra-driver" { replicateOnWrite: boolean; } } -} \ No newline at end of file +} diff --git a/chai-dom/chai-dom-tests.ts b/chai-dom/chai-dom-tests.ts new file mode 100644 index 0000000000..2fca54765e --- /dev/null +++ b/chai-dom/chai-dom-tests.ts @@ -0,0 +1,27 @@ +/// + +import * as chai from 'chai'; +import * as chaiDom from 'chai-dom'; + +chai.use(chaiDom); +var expect = chai.expect; + +function test() { + + var testElement = '
      '; + expect(testElement).to.have.attribute('foo', 'bar'); + expect(testElement).to.have.attr('foo').match(/bar/); + expect(testElement).to.have.class('foo'); + expect(testElement).to.have.id('id'); + expect(testElement).to.have.html('foo'); + expect(testElement).to.have.text('foo'); + expect(testElement).to.have.text(['foo', 'bar']); + expect(testElement).to.have.value('foo'); + expect(testElement).to.be.empty; + expect(testElement).to.have.length(2); + expect(testElement).to.exist; + expect(testElement).to.match('foo'); + expect(testElement).to.contain('foo'); + expect(testElement).to.contain(document.body); + +} \ No newline at end of file diff --git a/chai-dom/chai-dom.d.ts b/chai-dom/chai-dom.d.ts new file mode 100644 index 0000000000..64cf97f516 --- /dev/null +++ b/chai-dom/chai-dom.d.ts @@ -0,0 +1,46 @@ +// Type definitions for chai-dom +// Project: https://github.com/nathanboktae/chai-dom +// Definitions by: Matt Lewis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace Chai { + + interface Assertion { + + attr(name: string, value?: string): Assertion; + + attribute(name: string, value?: string): Assertion; + + class(className: string): Assertion; + + id(id: string): Assertion; + + html(html: string): Assertion; + + text(text: string|string[]): Assertion; + + value(text: string): Assertion; + + } + + interface Include { + + text(text: string|string[]): Assertion; + + html(text: string|string[]): Assertion; + + } + +} + +declare module "chai-dom" { + + function chaiDom(chai: any, utils: any): void; + + namespace chaiDom { + } + + export = chaiDom; +} diff --git a/chai-enzyme/chai-enzyme-tests.tsx b/chai-enzyme/chai-enzyme-tests.tsx new file mode 100644 index 0000000000..f85320cee0 --- /dev/null +++ b/chai-enzyme/chai-enzyme-tests.tsx @@ -0,0 +1,45 @@ +/// +/// +/// +/// + +import * as React from "react"; +import * as chaiEnzyme from "chai-enzyme"; +import { expect } from "chai"; +import { shallow } from "enzyme"; + +const Test = () =>
      ; + +class Test2 extends React.Component<{}, {}> { + render() { + return
      ; + } +} + +chai.use(chaiEnzyme()); + +const wrapper = shallow(); + +expect(wrapper).to.be.checked(); +expect(wrapper).to.have.className("test"); +expect(wrapper).to.have.descendants({ a: "b" }); +expect(wrapper).to.have.descendants(Test); +expect(wrapper).to.have.exactly(1).descendants(Test2); +expect(wrapper).to.have.descendants("div"); +expect(wrapper).to.be.disabled(); +expect(wrapper).to.be.blank(); +expect(wrapper).to.be.present(); +expect(wrapper).to.have.html("
      "); +expect(wrapper).to.have.id("test"); +expect(wrapper).to.have.ref("test"); +expect(wrapper).to.be.selected(); +expect(wrapper).to.have.tagName("div"); +expect(wrapper).to.have.text(""); +expect(wrapper).to.have.value("test"); +expect(wrapper).to.have.attr("test", "test"); +expect(wrapper).to.have.data("test", "Test"); +expect(wrapper).to.have.style("background", "green"); +expect(wrapper).to.have.state("test", "test"); +expect(wrapper).to.have.prop("test", 5); +expect(wrapper).to.contain(); +expect(wrapper).to.match(); diff --git a/chai-enzyme/chai-enzyme.d.ts b/chai-enzyme/chai-enzyme.d.ts new file mode 100644 index 0000000000..21e463dac5 --- /dev/null +++ b/chai-enzyme/chai-enzyme.d.ts @@ -0,0 +1,153 @@ +// Type definitions for chai-enzyme 0.5.0 +// Project: https://github.com/producthunt/chai-enzyme +// Definitions by: Alexey Svetliakov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/// +/// +/// + +declare namespace Chai { + type EnzymeSelector = string | __React.StatelessComponent | __React.ComponentClass | { [key: string]: any }; + + interface Match { + /** + * Assert that the wrapper matches given selector: + * @param selector + */ + (selector: EnzymeSelector): Assertion; + } + interface Include { + /** + * Assert that the wrapper contains a given node: + * @param code + */ + (selector: EnzymeSelector): Assertion; + } + interface Assertion { + /** + * Assert that the given wrapper is checked: + */ + checked(): Assertion; + + /** + * Assert that the wrapper has a given class: + * @param name + */ + className(name: string): Assertion; + + /** + * Assert that the wrapper contains a descendant matching the given selector: + * @param selector + */ + descendants(selector?: EnzymeSelector): Assertion; + + /** + * Assert that the wrapper contains an exact amount of descendants matching the given selector: + */ + exactly(count?: number): Assertion; + + /** + * Assert that the given wrapper is disabled: + */ + disabled(): Assertion; + + /** + * Assert that the given wrapper is empty: + */ + blank(): Assertion; + + /** + * Assert that the given wrapper exists: + */ + present(): Assertion; + + /** + * Assert that the wrapper has given html: + * @param str + */ + html(str?: string): Assertion; + + /** + * Assert that the wrapper has given ID attribute: + * @param str + */ + id(str: string): Assertion; + + /** + * Assert that the wrapper has a given ref + * @param key + */ + ref(key: string): Assertion; + + /** + * Assert that the given wrapper is selected: + */ + selected(): Assertion; + + /** + * Assert that the given wrapper has the tag name: + * @param str + */ + tagName(str: string): Assertion; + + /** + * Assert that the given wrapper has the supplied text: + * @param str + */ + text(str?: string): Assertion; + + /** + * Assert that the given wrapper has given value: + * @param str + */ + value(str: string): Assertion; + + /** + * Assert that the wrapper has given attribute [with value]: + * @param key + * @param val + */ + attr(key: string, val?: string): Assertion; + + /** + * Assert that the wrapper has a given data attribute [with value]: + * @param key + * @param val + */ + data(key: string, val?: string): Assertion; + + /** + * Assert that the wrapper has given style: + * @param key + * @param val + */ + style(key: string, val?: string): Assertion; + + /** + * Assert that the wrapper has given state [with value]: + * @param key + * @param val + */ + state(key: string, val?: any): Assertion; + + /** + * Assert that the wrapper has given prop [with value]: + * @param key + * @param val + */ + prop(key: string, val?: any): Assertion; + } +} + +declare module "chai-enzyme" { + import { ShallowWrapper, ReactWrapper, CheerioWrapper } from "enzyme"; + + type DebugWrapper = ShallowWrapper | CheerioWrapper | ReactWrapper; + function chaiEnzyMe(wrapper?: (debugWrapper: DebugWrapper) => string): (chai: any) => void; + + module chaiEnzyMe { + } + export = chaiEnzyMe; +} diff --git a/chai-jquery/chai-jquery.d.ts b/chai-jquery/chai-jquery.d.ts index 3d287f30fc..e7256bb7ab 100644 --- a/chai-jquery/chai-jquery.d.ts +++ b/chai-jquery/chai-jquery.d.ts @@ -17,7 +17,7 @@ declare namespace Chai { html(html: string): Assertion; text(text: string): Assertion; value(text: string): Assertion; - (selector: string): Assertion; + descendants(selector: string): Assertion; visible: Assertion; hidden: Assertion; selected: Assertion; diff --git a/chai-things/chai-things-tests.ts b/chai-things/chai-things-tests.ts index de6a4c3ffe..c49ac3b468 100644 --- a/chai-things/chai-things-tests.ts +++ b/chai-things/chai-things-tests.ts @@ -18,9 +18,19 @@ function test_somethingSyntax() { array.should.include.something.with.property('b', 2); array.should.not.include.something.with.property('b', 3); + chai.expect(array).to.include.something(); + chai.expect(array).to.include.something.that.deep.equals({ b: 2 }); + chai.expect(array).to.include.something.that.not.deep.equals({ b: 2 }); + chai.expect(array).not.to.include.something.that.deep.equals({ c: 3 }); + chai.expect(array).to.include.something.that.not.deep.equals({ c: 3 }); + chai.expect(array).to.include.something.with.property('b', 2); + chai.expect(array).not.to.include.something.with.property('b', 3); + var array2 = [{ a: 'b' }, { a: 'b' }]; array2.should.include.something.that.have.property("a"); array2.should.include.something.that.have.property("a").not.equal("d"); + chai.expect(array2).to.include.something.that.have.property("a"); + chai.expect(array2).to.include.something.that.have.property("a").not.equal("d"); } function test_somethingVariantsSyntax() { @@ -35,6 +45,16 @@ function test_somethingVariantsSyntax() { array.should.include.one.that.deep.equals({ b: 2 }); array.should.include.some(); array.should.include.some.that.deep.equal({ b: 2 }); + + chai.expect(array).to.include.a.thing(); + chai.expect(array).to.include.a.thing.that.deep.equals({ b: 2 }); + chai.expect(array).to.include.an.item(); + chai.expect(array).to.include.an.item.that.deep.equals({ b: 2 }); + chai.expect(array).to.include.one.that.deep.equals({ b: 2 }); + chai.expect(array).to.include.some(); + chai.expect(array).to.include.some.that.deep.equal({ b: 2 }); + chai.expect(array).to.contain.a.thing(); + chai.expect(array).to.contain.a.thing.with.property('a', 1); } function test_allSyntax() { diff --git a/chai-things/chai-things.d.ts b/chai-things/chai-things.d.ts index 2636c9dcea..18c138ff38 100644 --- a/chai-things/chai-things.d.ts +++ b/chai-things/chai-things.d.ts @@ -23,6 +23,15 @@ declare namespace Chai { any: Anything; } + interface Include { + (item: any): any; + a: Item; + an: Item; + one: Something; + some: Something; + something: Something; + } + interface Anything extends Assertion { (): any; that: Assertion; diff --git a/chance/chance.d.ts b/chance/chance.d.ts index 290cde8048..6390b57864 100644 --- a/chance/chance.d.ts +++ b/chance/chance.d.ts @@ -114,8 +114,16 @@ declare namespace Chance { capitalize(str: string): string; mixin(desc: MixinDescriptor): any; pad(num: number, width: number, padChar?: string): string; + /** + * @deprecated Use pickone + */ pick(arr: T[]): T; + pickone(arr: T[]): T; + /** + * @deprecated Use pickset + */ pick(arr: T[], count: number): T[]; + pickset(arr: T[], count: number): T[]; set: Setter; shuffle(arr: T[]): T[]; diff --git a/change-emitter/change-emitter-tests.ts b/change-emitter/change-emitter-tests.ts new file mode 100644 index 0000000000..379c7636a5 --- /dev/null +++ b/change-emitter/change-emitter-tests.ts @@ -0,0 +1,124 @@ +/// + +import { createChangeEmitter, ChangeEmitterOf0 } from "change-emitter"; + +function usage() { + // https://github.com/acdlite/change-emitter#usage + + const emitter = createChangeEmitter() + + // Called `listen` instead of `subscribe` to avoid confusion with observable spec + const unlisten = emitter.listen((...args) => { + console.log(args) + }) + + emitter.emit(1, 2, 3) // logs `[1, 2, 3]` + unlisten() + emitter.emit(4, 5, 6) // doesn't log +} + +function largerExample() { + // https://github.com/acdlite/change-emitter#larger-example + + const createStore = (reducer: Function, initialState: any) => { + let state = initialState + const emitter = createChangeEmitter() + + function dispatch(action: any) { + state = reducer(state, action) + emitter.emit() + return action + } + + function getState() { + return state + } + + return { + dispatch, + getState, + subscribe: emitter.listen + } + } +} + +function untypedEmitter() { + const { emit, listen } = createChangeEmitter(); + + const unlisten0 = listen(() => {/* do something */}); + const unlisten1 = listen(value => {/* do something with value */}); + const unlisten2 = listen((value1, value2) => {/* do something with values */}); + const unlistenArgs = listen((...args: any[]) => {/* do something with values */}); + + emit(); + emit("hello"); + emit("hello", "world"); + emit(1, 2, 3, 4, 5); + + unlisten0(); + unlisten1(); + unlisten2(); + unlistenArgs(); +} + +function emitterOf0Args() { + const { emit, listen }: ChangeEmitterOf0 = createChangeEmitter(); + + const unlisten = listen(() => { }); + // const unlisten = listen(value => {}); // SYNTAX ERROR + + emit(); + // emit("hello"); // SYNTAX ERROR + + unlisten(); +} + +function emitterOf1Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen(value => { value.length }); + + emit("hello"); + + unlisten(); +} + +function emitterOf2Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen((value, success) => { value.length > 0 === success }); + + emit("hello", true); + + unlisten(); +} + +function emitterOf3Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen((value, success, count) => { value.length > count === success }); + + emit("hello", true, 3); + + unlisten(); +} + +function emitterOf4Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen((v1, v2, v3, v4) => { }); + + emit("hello", true, 3, new Date()); + + unlisten(); +} + +function emitterOf5Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen((v1, v2, v3, v4, v5) => { }); + + emit("hello", true, 3, new Date(), "world"); + + unlisten(); +} diff --git a/change-emitter/change-emitter.d.ts b/change-emitter/change-emitter.d.ts new file mode 100644 index 0000000000..85abf116ed --- /dev/null +++ b/change-emitter/change-emitter.d.ts @@ -0,0 +1,58 @@ +// Type definitions for change-emitter v0.1.2 +// Project: https://github.com/acdlite/change-emitter +// Definitions by: Iskander Sierra +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'change-emitter' { + + type Unlisten = () => void; + type Listener = (...args: any[]) => void; + type ListenerOf0 = () => void; + type ListenerOf1 = (value: T) => void; + type ListenerOf2 = (value1: T1, value2: T2) => void; + type ListenerOf3 = (value1: T1, value2: T2, value3: T3) => void; + type ListenerOf4 = (value1: T1, value2: T2, value3: T3, value4: T4) => void; + type ListenerOf5 = (value1: T1, value2: T2, value3: T3, value4: T4, value5: T5) => void; + + interface ChangeEmitter { + listen(listener: Listener): Unlisten; + emit(...args: any[]): void; + } + + interface ChangeEmitterOf1 { + listen(listener: ListenerOf1): Unlisten; + emit(value: T): void; + } + + interface ChangeEmitterOf0 { + listen(listener: ListenerOf0): Unlisten; + emit(): void; + } + + interface ChangeEmitterOf2 { + listen(listener: ListenerOf2): Unlisten; + emit(value1: T1, value2: T2): void; + } + + interface ChangeEmitterOf3 { + listen(listener: ListenerOf3): Unlisten; + emit(value1: T1, value2: T2, value3: T3): void; + } + + interface ChangeEmitterOf4 { + listen(listener: ListenerOf4): Unlisten; + emit(value1: T1, value2: T2, value3: T3, value4: T4): void; + } + + interface ChangeEmitterOf5 { + listen(listener: ListenerOf5): Unlisten; + emit(value1: T1, value2: T2, value3: T3, value4: T4, value5: T5): void; + } + + export function createChangeEmitter(): ChangeEmitter; + export function createChangeEmitter(): ChangeEmitterOf1; + export function createChangeEmitter(): ChangeEmitterOf2; + export function createChangeEmitter(): ChangeEmitterOf3; + export function createChangeEmitter(): ChangeEmitterOf4; + export function createChangeEmitter(): ChangeEmitterOf5; +} diff --git a/chart.js/chart.js.d.ts b/chart.js/chart.js.d.ts new file mode 100644 index 0000000000..57389ee4ea --- /dev/null +++ b/chart.js/chart.js.d.ts @@ -0,0 +1,410 @@ +// Type definitions for Chart.js +// Project: https://github.com/nnnick/Chart.js +// Definitions by: Alberto Nuti +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare enum ChartType { + line, bar, radar, doughnut, polarArea, bubble +} +declare enum TimeUnit { + millisecond, second, minute, + hour, day, week, + month, quarter, year +} +interface ChartLegendItem { + text?: string; + fillStyle?: string; + hidden?: boolean; + lineCap?: string; + lineDash?: number[]; + lineDashOffset?: number; + lineJoin?: string; + lineWidth?: number; + strokeStyle?: string; +} +interface ChartTooltipItem { + xLabel?: string; + yLabel?: string; + datasetIndex?: number; + index?: number; +} +interface ChartTooltipCallback { + beforeTitle?: (item?: ChartTooltipItem[], data?: any) => void; + title?: (item?: ChartTooltipItem[], data?: any) => void; + afterTitle?: (item?: ChartTooltipItem[], data?: any) => void; + beforeBody?: (item?: ChartTooltipItem[], data?: any) => void; + beforeLabel?: (tooltipItem?: ChartTooltipItem, data?: any) => void; + label?: (tooltipItem?: ChartTooltipItem, data?: any) => void; + afterLabel?: (tooltipItem?: ChartTooltipItem, data?: any) => void; + afterBody?: (item?: ChartTooltipItem[], data?: any) => void; + beforeFooter?: (item?: ChartTooltipItem[], data?: any) => void; + footer?: (item?: ChartTooltipItem[], data?: any) => void; + afterfooter?: (item?: ChartTooltipItem[], data?: any) => void; +} +interface ChartAnimationParameter { + chartInstance?: any; + animationObject?: any; +} +interface ChartPoint { + x?: number; + y?: number; +} + +interface ChartConfiguration { + type?: string; + data?: ChartData; + options?: ChartOptions; +} + +interface ChartData { + +} + +interface LinearChartData extends ChartData { + labels?: string[]; + datasets?: ChartDataSets[]; +} + +interface ChartOptions { + responsive?: boolean; + responsiveAnimationDuration?: number; + maintainAspectRatio?: boolean; + events?: string[]; + onClick?: (any?: any) => any; + title?: ChartTitleOptions; + legend?: ChartLegendOptions; + tooltips?: ChartTooltipOptions; + hover?: ChartHoverOptions; + animation?: ChartAnimationOptions; + elements?: ChartElementsOptions; + scales?: ChartScales; +} + +interface ChartFontOptions { + defaultFontColor?: ChartColor; + defaultFontFamily?: string; + defaultFontSize?: number; + defaultFontStyle?: string; +} + +interface ChartTitleOptions { + display?: boolean; + position?: string; + fullWdith?: boolean; + fontSize?: number; + fontFamily?: string; + fontColor?: ChartColor; + fontStyle?: string; + padding?: number; + text?: string; +} + +interface ChartLegendOptions { + display?: boolean; + position?: string; + fullWidth?: boolean; + onClick?: (event: any, legendItem: any) => void; + labels?: ChartLegendLabelOptions; +} + +interface ChartLegendLabelOptions { + boxWidth?: number; + fontSize?: number; + fontStyle?: number; + fontColor?: ChartColor; + fontFamily?: string; + padding?: number; + generateLabels?: (chart: any) => any; +} + +interface ChartTooltipOptions { + enabled?: boolean; + custom?: (a: any) => void; + mode?: string; + backgroundColor?: ChartColor; + titleFontFamily?: string; + titleFontSize?: number; + titleFontStyle?: string; + titleFontColor?: ChartColor; + titleSpacing?: number; + titleMarginBottom?: number; + bodyFontFamily?: string; + bodyFontSize?: number; + bodyFontStyle?: string; + bodyFontColor?: ChartColor; + bodySpacing?: number; + footerFontFamily?: string; + footerFontSize?: number; + footerFontStyle?: string; + footerFontColor?: ChartColor; + footerSpacing?: number; + footerMarginTop?: number; + xPadding?: number; + yPadding?: number; + caretSize?: number; + cornerRadius?: number; + multiKeyBackground?: string; + callbacks?: ChartTooltipCallback; +} + +interface ChartHoverOptions { + mode?: string; + animationDuration?: number; + onHover?: (active: any) => void; +} + +interface ChartAnimationObject { + currentStep?: number; + numSteps?: number; + easing?: string; + render?: (arg: any) => void; + onAnimationProgress?: (arg: any) => void; + onAnimationComplete?: (arg: any) => void; +} + +interface ChartAnimationOptions { + duration?: number; + easing?: string; + onProgress?: (chart: any) => void; + onComplete?: (chart: any) => void; +} + +interface ChartElementsOptions { + point?: ChartPointOptions; + line?: ChartLineOptions; + arg?: ChartArcOtpions; + rectangle?: ChartRectangleOptions; +} + +interface ChartArcOtpions { + backgroundColor?: ChartColor; + borderColor?: ChartColor; + borderWidth?: number; +} + +interface ChartLineOptions { + tension?: number; + backgroundColor?: ChartColor; + borderWidth?: number; + borderColor?: ChartColor; + borderCapStyle?: string; + borderDash?: any[]; + borderDashOffset?: number; + borderJoinStyle?: string; +} + +interface ChartPointOptions { + radius?: number; + pointStyle?: string; + backgroundColor?: ChartColor; + borderWidth?: number; + borderColor?: ChartColor; + hitRadius?: number; + hoverRadius?: number; + hoverBorderWidth?: number; +} + +interface ChartRectangleOptions { + backgroundColor?: ChartColor; + borderWidth?: number; + borderColor?: ChartColor; + borderSkipped?: string; +} +interface GridLineOptions { + display?: boolean; + color?: ChartColor; + lineWidth?: number; + drawBorder?: boolean; + drawOnChartArea?: boolean; + drawticks?: boolean; + tickMarkLength?: number; + zeroLineWidth?: number; + zeroLineColor?: ChartColor; + offsetGridLines?: boolean; +} + +interface ScaleTitleOptions { + display?: boolean; + labelString?: string; + fontColor?: ChartColor; + fontFamily?: string; + fontSize?: number; + fontStyle?: string; +} + +interface TickOptions { + autoSkip?: boolean; + callback?: (value: any, index: any, values: any) => string; + display?: boolean; + fontColor?: ChartColor; + fontFamily?: string; + fontSize?: number; + fontStyle?: string; + labelOffset?: number; + maxRotation?: number; + minRotation?: number; + mirror?: boolean; + padding?: number; + reverse?: boolean; + min?: any; + max?: any; +} +interface AngleLineOptions { + display?: boolean; + color?: ChartColor; + lineWidth?: number; +} + +interface PointLabelOptions { + callback?: (arg: any) => any; + fontColor?: ChartColor; + fontFamily?: string; + fontSize?: number; + fontStyle?: string; +} + +interface TickOptions { + backdropColor?: ChartColor; + backdropPaddingX?: number; + backdropPaddingY?: number; + maxTicksLimit?: number; + showLabelBackdrop?: boolean; +} +interface LinearTickOptions extends TickOptions { + beginAtZero?: boolean; + min?: number; + max?: number; + maxTicksLimit?: number; + stepSize?: number; + suggestedMin?: number; + suggestedMax?: number; +} + +interface LogarithmicTickOptions extends TickOptions { + min?: number; + max?: number; +} + +type ChartColor = string | CanvasGradient | CanvasPattern; + +interface ChartDataSets { + backgroundColor?: ChartColor; + borderWidth?: number; + borderColor?: ChartColor; + borderCapStyle?: string; + borderDash?: number[]; + borderDashOffset?: number; + borderJoinStyle?: string; + data?: number[] | ChartPoint[]; + fill?: boolean; + label?: string; + lineTension?: number; + pointBorderColor?: ChartColor | ChartColor[]; + pointBackgroundColor?: ChartColor | ChartColor[]; + pointBorderWidth?: number | number[]; + pointRadius?: number | number[]; + pointHoverRadius?: number | number[]; + pointHitRadius?: number | number[]; + pointHoverBackgroundColor?: ChartColor | ChartColor[]; + pointHoverBorderColor?: ChartColor | ChartColor[]; + pointHoverBorderWidth?: number | number[]; + pointStyle?: string | string[] | HTMLImageElement | HTMLImageElement[]; + xAxisID?: string; + yAxisID?: string; +} + +interface ChartScales { + type?: string; + display?: boolean; + position?: string; + beforeUpdate?: (scale?: any) => void; + beforeSetDimension?: (scale?: any) => void; + beforeDataLimits?: (scale?: any) => void; + beforeBuildTicks?: (scale?: any) => void; + beforeTickToLabelConversion?: (scale?: any) => void; + beforeCalculateTickRotation?: (scale?: any) => void; + beforeFit?: (scale?: any) => void; + afterUpdate?: (scale?: any) => void; + afterSetDimension?: (scale?: any) => void; + afterDataLimits?: (scale?: any) => void; + afterBuildTicks?: (scale?: any) => void; + afterTickToLabelConversion?: (scale?: any) => void; + afterCalculateTickRotation?: (scale?: any) => void; + afterFit?: (scale?: any) => void; + gridLines?: GridLineOptions; + scaleLabel?: ScaleTitleOptions; + ticks?: TickOptions; + xAxes?: ChartXAxe[]; + yAxes?: ChartYAxe[]; +} + +interface ChartXAxe { + type?: string; + display?: boolean; + id?: string; + stacked?: boolean; + categoryPercentage?: number; + barPercentage?: number; + gridLines?: GridLineOptions; + position?: string; + ticks?: TickOptions; + time?: TimeScale; + scaleLabel?: ScaleTitleOptions; +} + +interface ChartYAxe { + type?: string; + display?: boolean; + id?: string; + stacked?: boolean; + position?: string; + ticks?: TickOptions; + scaleLabel?: ScaleTitleOptions; +} + +interface LinearScale extends ChartScales { + ticks?: LinearTickOptions; +} + +interface LogarithmicScale extends ChartScales { + ticks?: LogarithmicTickOptions; +} + +interface TimeScale extends ChartScales { + format?: string; + displayFormats?: string; + isoWeekday?: boolean; + max?: string; + min?: string; + parser?: string | ((arg: any) => any); + round?: string; + tooltipFormat?: string; + unit?: TimeUnit; + unitStepSize?: number; +} + +interface RadialLinearScale { + lineArc?: boolean; + angleLines?: AngleLineOptions; + pointLabels?: PointLabelOptions; + ticks?: TickOptions; +} + +declare var Chart: { + new (context: CanvasRenderingContext2D, options: ChartConfiguration): {}; + destroy: () => {}; + update: (duration: any, lazy: any) => {}; + render: (duration: any, lazy: any) => {}; + stop: () => {}; + resize: () => {}; + clear: () => {}; + toBase64: () => string; + generateLegend: () => {}; + getElementAtEvent: (e: any) => {}; + getElementsAtEvent: (e: any) => {}[]; + getDatasetAtEvent: (e: any) => {}[]; + + defaults: { + global: ChartOptions; + } +}; diff --git a/chosen/chosen-tests.ts b/chosen/chosen-tests.ts index 818b1e1261..764b57fb0e 100644 --- a/chosen/chosen-tests.ts +++ b/chosen/chosen-tests.ts @@ -1,8 +1,26 @@ /// -$(".chzn-select").chosen({ no_results_text: "No results matched" }); -$("#form_field").chosen().change(); -$("#form_field").trigger("liszt:updated"); +// Options +$(".my_select_box").chosen(); -$(".chzn-select").chosen(); -$(".chzn-select-deselect").chosen({ allow_single_deselect: true }); \ No newline at end of file +$(".my_select_box").chosen({}); + +$(".my_select_box").chosen({ + disable_search_threshold: 10, + max_selected_options: 5, + no_results_text: "Oops, nothing found!", + width: "95%" +}); + +// Destroy +$(".my_select_box").chosen("destroy"); + +// Triggered Events +$(".my_select_box").on("change", function(evt, params) { + evt.preventDefault(); + let s = params.selected; + console.log(s); +}); + +// Triggerable Events +$(".my_select_box").trigger("chosen:updated"); diff --git a/chosen/chosen.jquery.d.ts b/chosen/chosen.jquery.d.ts index 0033bfdd1d..c7f7c6b7ee 100644 --- a/chosen/chosen.jquery.d.ts +++ b/chosen/chosen.jquery.d.ts @@ -1,30 +1,98 @@ -// Type definitions for Chosen.JQuery 1.4.2 +// Type definitions for Chosen.JQuery 1.6.1 // Project: http://harvesthq.github.com/chosen/ -// Definitions by: Boris Yankov +// Definitions by: Boris Yankov , denis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - /// -interface ChosenOptions { - allow_single_deselect?: boolean; - disable_search?: boolean; - disable_search_threshold?: number; - enable_split_word_search?: boolean; - inherit_select_classes?: boolean; - max_selected_options?: number; - no_results_text?: string; - placeholder_text_multiple?: string; - placeholder_text_single?: string; - search_contains?: boolean; - single_backstroke_delete?: boolean; - width?: number|string; - display_disabled_options?: boolean; - display_selected_options?: boolean; - include_group_label_in_selected?: boolean; +declare namespace Chosen { + type OnEvent = "chosen:ready" | "chosen:maxselected" | "chosen:showing_dropdown" | "chosen:hiding_dropdown" | "chosen:no_results"; + type TriggerEvent = "chosen:updated" | "chosen:activate" | "chosen:open" | "chosen:close"; + + interface Options { + /**When set to true on a single select, Chosen adds a UI element which selects the first element (if it is blank). + * @default: false + */ + allow_single_deselect?: boolean; + /**By default Chosen's search is case-insensitive. Setting this option to true makes the search case-sensitive. + * @default: false + */ + case_sensitive_search?: boolean; + /**When set to true, Chosen will not display the search field (single selects only). + * @default: false + */ + disable_search?: boolean; + /**Hide the search input on single selects if there are n or fewer options. + * @default: 0 + */ + disable_search_threshold?: number; + /**By default, searching will match on any word within an option tag. Set this option to false if you want to only match on the entire text of an option tag. + * @default: true + */ + enable_split_word_search?: boolean; + /**When set to true, Chosen will grab any classes on the original select field and add them to Chosen’s container div. + * @default: false + */ + inherit_select_classes?: boolean; + /**Limits how many options the user can select. When the limit is reached, the chosen:maxselected event is triggered. + * @default: Infinity + */ + max_selected_options?: number; + /**The text to be displayed when no matching results are found. The current search is shown at the end of the text (e.g., No results match "Bad Search"). + * @default: "No results match" + */ + no_results_text?: string; + /**The text to be displayed as a placeholder when no options are selected for a multiple select. + * @default: "Select Some Options" + */ + placeholder_text_multiple?: string; + /**The text to be displayed as a placeholder when no options are selected for a single select. + * @default: "Select an Option" + */ + placeholder_text_single?: string; + /**By default, Chosen’s search matches starting at the beginning of a word. Setting this option to true allows matches starting from anywhere within a word. This is especially useful for options that include a lot of special characters or phrases in ()s and []s. + * @default: false + */ + search_contains?: boolean; + /**By default, pressing delete/backspace on multiple selects will remove a selected choice. When false, pressing delete/backspace will highlight the last choice, and a second press deselects it. + * @default: true + */ + single_backstroke_delete?: boolean; + /**The width of the Chosen select box. By default, Chosen attempts to match the width of the select box you are replacing. If your select is hidden when Chosen is instantiated, you must specify a width or the select will show up with a width of 0. */ + width?: string; + /**By default, Chosen includes disabled options in search results with a special styling. Setting this option to false will hide disabled results and exclude them from searches. + * @default: true + */ + display_disabled_options?: boolean; + /**By default, Chosen includes selected options in search results with a special styling. Setting this option to false will hide selected results and exclude them from searches. + * Note: this is for multiple selects only. In single selects, the selected result will always be displayed. + * @default: true + */ + display_selected_options?: boolean; + /**By default, Chosen only shows the text of a selected option. Setting this option to true will show the text and group (if any) of the selected option. + * @default: false + */ + include_group_label_in_selected?: boolean; + /**Only show the first (n) matching options in the results. This can be used to increase performance for selects with very many options. + * @default: Infinity + */ + max_shown_results?: number; + } + + interface SelectedData { + selected: string; + deselected: string; + } } interface JQuery { chosen(): JQuery; - chosen(options: ChosenOptions): JQuery; + chosen(options: Chosen.Options | "destroy"): JQuery; + + /**Chosen triggers the standard DOM event whenever a selection is made (it also sends a selected or deselected parameter that tells you which option was changed). */ + on(events: "change", handler: (eventObject: JQueryEventObject, args: Chosen.SelectedData) => any): JQuery; + + on(events: Chosen.OnEvent, handler: (eventObject: JQueryEventObject) => any): JQuery; + + trigger(eventType: Chosen.TriggerEvent): JQuery; } diff --git a/chroma-js/chroma-js-0.5.6-tests.ts b/chroma-js/chroma-js-0.5.6-tests.ts new file mode 100644 index 0000000000..cb8b593d26 --- /dev/null +++ b/chroma-js/chroma-js-0.5.6-tests.ts @@ -0,0 +1,120 @@ +/// + +function test_chroma() { + chroma("red"); + chroma("#ff0000"); + chroma("#f00"); + chroma("FF0000"); + chroma(255, 0, 0); + chroma([255, 0, 0]); + chroma(0, 1, 0.5, 'hsl'); + chroma([0, 1, 0.5], 'hsl'); + chroma(0, 1, 1, 'hsv'); + chroma("rgb(255,0,0)"); + chroma("rgb(100%,0%,0%)"); + chroma("hsl(0,100%,50%)"); + chroma(53.24, 80.09, 67.20, 'lab'); + chroma(53.24, 104.55, 40, 'lch'); + chroma(1, 0, 0, 'gl'); + + chroma.hex("#ff0000"); + chroma.hex("red"); + chroma.hex("rgb(255, 0, 0)"); + + chroma.rgb(255, 0, 0); + chroma.hsl(0, 1, 0.5); + chroma.hsv(120, 0.5, 0.5); + chroma.lab(53.24, 80.09, 67.20); + chroma.lch(53.24, 104.55, 40); + chroma.gl(1, 0, 0); + + chroma.interpolate('white', 'black', 0) // #ffffff + chroma.interpolate('white', 'black', 1) // #000000 + chroma.interpolate('white', 'black', 0.5) // #7f7f7f + chroma.interpolate('white', 'black', 0.5, 'hsv') // #808080 + chroma.interpolate('white', 'black', 0.5, 'lab') // #777777 + + chroma.interpolate('rgba(0,0,0,0)', 'rgba(255,0,0,1)', 0.5).css() //"rgba(127.5,0,0,0.5)" + + var bezInterpolator = chroma.interpolate.bezier(['white', 'yellow', 'red', 'black']); + bezInterpolator(0).hex() // #ffffff + bezInterpolator(0.33).hex() // #ffcc67 + bezInterpolator(0.66).hex() // #b65f1a + bezInterpolator(1).hex() // #000000 + + chroma.luminance('black') // 0 + chroma.luminance('white') // 1 + chroma.luminance('#ff0000') // 0.2126 + + chroma.contrast('white', 'navy') // 16.00 – ok + chroma.contrast('white', 'yellow') // 1.07 – not ok! +} + +function test_color() { + chroma('red').hex() // "#FF0000"" + chroma('red').rgb() // [255, 0, 0] + chroma('red').hsv() // [0, 1, 1] + chroma('red').hsl() // [0, 1, 0.5] + chroma('red').lab() // [53.2407, 80.0924, 67.2031] + chroma('red').lch() // [53.2407, 104.5517, 39.9990] + chroma('red').rgba() // [255, 0, 0, 1] + chroma('red').css() // "rgb(255,0,0)" + chroma('red').alpha(0.7).css() // "rgba(255,0,0,0.7)" + chroma('red').css('hsl') // "hsl(0,100%,50%)" + chroma('red').alpha(0.7).css('hsl') // "hsla(0,100%,50%,0.7)" + chroma('blue').css('hsla') // "hsla(240,100%,50%,1)" + + var red = chroma('red'); + red.alpha(0.5); + red.css(); // rgba(255,0,0,0.5); + + chroma('red').darken().hex() // #BC0000 + chroma('red').brighten().hex() // #FF603B + chroma('#eecc99').saturate().hex() // #fcc973 + chroma('red').desaturate().hex() // #ec3d23 + + chroma('black').luminance() // 0 + chroma('white').luminance() // 1 + chroma('red').luminance() // 0.2126 +} + +function test_scale() { + var scale = chroma.scale(['lightyellow', 'navy']); + scale(0.5); // #7F7FB0 + + chroma.scale('RdYlBu'); + + var col = scale(0.5); + col.hex(); // #7F7FB0 + col.rgb(); // [127.5, 127.5, 176] + + scale = chroma.scale(['lightyellow', 'navy']).out('hex'); + scale(0.5); // "#7F7FB0" + + var scale = chroma.scale(['lightyellow', 'navy']); + scale.mode('hsv')(0.5); // #54C08A + scale.mode('hsl')(0.5); // #31FF98 + scale.mode('lab')(0.5); // #967CB2 + scale.mode('lch')(0.5); // #D26662 + + var scale = chroma.scale(['lightyellow', 'navy']).domain([0, 400]); + scale(200); // #7F7FB0 + + var scale = chroma.scale(['lightyellow', 'navy']).domain([0, 100, 200, 300, 400]); + scale(98); // #7F7FB0 + scale(99); // #7F7FB0 + scale(100); // #AAAAC0 + scale(101); // #AAAAC0 + + chroma.scale(['#eee', '#900']).domain([0, 400], 7); + chroma.scale(['#eee', '#900']).domain([1, 1000000], 7, 'log'); + chroma.scale(['#eee', '#900']).domain([1, 1000000], 5, 'quantiles'); + chroma.scale(['#eee', '#900']).domain([1, 1000000], 5, 'k-means'); + chroma.scale(['white', 'red']).domain([0, 100], 4).domain() // [0, 25, 50, 75, 100] + + chroma.scale().range(['lightyellow', 'navy']); + + chroma.scale(['lightyellow', 'navy']).correctLightness(true); + + chroma.scale('RdYlGn').domain([0,1], 5).colors() +} diff --git a/chroma-js/chroma-js-0.5.6.d.ts b/chroma-js/chroma-js-0.5.6.d.ts new file mode 100644 index 0000000000..5d785eda27 --- /dev/null +++ b/chroma-js/chroma-js-0.5.6.d.ts @@ -0,0 +1,317 @@ +// Type definitions for Chroma.js v0.5.6 +// Project: https://github.com/gka/chroma.js +// Definitions by: Sebastian Brückner +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Chroma.js is a tiny library for all kinds of color conversions and color scales. + */ +declare namespace Chroma { + + export interface ChromaStatic { + /** + * Creates a color from a string representation (as supported in CSS). + * + * @param color The string to convert to a color. + * @return the color object. + */ + (color: string): Color; + + /** + * Create a color in the specified color space using a, b and c as values. + * + * @param a + * @param b + * @param c + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + * @return the color object. + */ + (a: number, b: number, c: number, colorSpace?: string): Color; + + /** + * Create a color in the specified color space using values. + * + * @param values An array of values (e.g. [r, g, b, a?]). + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + * @return the color object. + */ + (values: number[], colorSpace?: string): Color; + + /** + * Create a color in the specified color space using a, b and c as values. + * + * @param a + * @param b + * @param c + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + * @return the color object. + */ + color(a: number, b: number, c: number, colorSpace?: string): Color; + + /** + * Calculate the contrast ratio of two colors. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(color1: Color, color2: Color): number; + /** + * Calculate the contrast ratio of two colors. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(color1: Color, color2: string): number; + /** + * Calculate the contrast ratio of two colors. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(color1: string, color2: Color): number; + /** + * Calculate the contrast ratio of two colors. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(color1: string, color2: string): number; + + /** + * Create a color from a hex or string representation (as supported in CSS). + * + * This is an alias of chroma.hex(). + * + * @param color The string to convert to a color. + * @return the color object. + */ + css(color: string): Color; + + /** + * Create a color from a hex or string representation (as supported in CSS). + * + * This is an alias of chroma.css(). + * + * @param color The string to convert to a color. + * @return the color object. + */ + hex(color: string): Color; + + rgb(red: number, green: number, blue: number, alpha?: number): Color; + hsl(hue: number, saturation: number, lightness: number, alpha?: number): Color; + hsv(hue: number, saturation: number, value: number, alpha?: number): Color; + lab(lightness: number, a: number, b: number, alpha?: number): Color; + lch(lightness: number, chroma: number, hue: number, alpha?: number): Color; + gl(red: number, green: number, blue: number, alpha?: number): Color; + + interpolate: InterpolateFunction; + mix: InterpolateFunction; + + luminance(color: Color): number; + luminance(color: string): number; + + /** + * Creates a color scale using a pre-defined color scale. + * + * @param name The name of the color scale. + * @return the resulting color scale. + */ + scale(name: string): Scale; + + /** + * Creates a color scale function from the given set of colors. + * + * @param colors An Array of at least two color names or hex values. + * @return the resulting color scale. + */ + scale(colors?: string[]): Scale; + + scales: PredefinedScales; + } + + interface InterpolateFunction { + (color1: Color, color2: Color, f: number, mode?: string): Color; + (color1: Color, color2: string, f: number, mode?: string): Color; + (color1: string, color2: Color, f: number, mode?: string): Color; + (color1: string, color2: string, f: number, mode?: string): Color; + + bezier(colors: any[]): (t: number) => Color; + } + + interface PredefinedScales { + [key: string]: Scale; + + cool: Scale; + hot: Scale; + } + + export interface Color { + /** + * Creates a color from a string representation (as supported in CSS). + * + * @param color The string to convert to a color. + */ + new(color: string): Color; + + /** + * Create a color in the specified color space using a, b and c as values. + * + * @param a + * @param b + * @param c + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + */ + new(a: number, b: number, c: number, colorSpace?: string): Color; + + /** + * Create a color in the specified color space using a, b and c as color values and alpha as the alpha value. + * + * @param a + * @param b + * @param c + * @param alpha The alpha value of the color. + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + */ + new(a: number, b: number, c: number, alpha: number, colorSpace?: string): Color; + + /** + * Create a color in the specified color space using values. + * + * @param values An array of values (e.g. [r, g, b, a?]). + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + */ + new(values: number[], colorSpace: string): Color; + + /** + * Convert this color to CSS hex representation. + * + * @return this color's hex representation. + */ + hex(): string; + + /** + * @return the relative luminance of the color, which is a value between 0 (black) and 1 (white). + */ + luminance(): number; + + /** + * @return the X11 name of this color or its hex value if it does not have a name. + */ + name(): string; + + /** + * @return the alpha value of the color. + */ + alpha(): number; + + /** + * Set the alpha value. + * + * @param alpha The alpha value. + * @return this + */ + alpha(alpha: number): Color; + + css(mode?: string): string; + + interpolate(color: Color, f: number, mode?: string): Color; + interpolate(color: string, f: number, mode?: string): Color; + + premultiply(): Color; + + rgb(): number[]; + rgba(): number[]; + hsl(): number[]; + hsv(): number[]; + lab(): number[]; + lch(): number[]; + hsi(): number[]; + gl(): number[]; + + darken(amount?: number): Color; + darker(amount: number): Color; + brighten(amount?: number): Color; + brighter(amount: number): Color; + saturate(amount?: number): Color; + desaturate(amount?: number): Color; + + toString(): string; + } + + export interface Scale { + /** + * Interpolate a color using the currently set range and domain. + * + * @param value The value to use for interpolation. + * @return the interpolated hex color OR a Color object (depending on the mode set on this Scale). + */ + (value: number): any; + + /** + * Retreive all possible colors generated by this scale if it has distinct classes. + * + * @param mode The output mode to use. Must be one of Color's getters. Defaults to "hex". + * @return an array of colors in the type specified by mode. + */ + colors(mode?: string): any[]; + + correctLightness(): boolean; + + /** + * Enable or disable automatic lightness correction of this scale. + * + * @param Whether to enable or disable automatic lightness correction. + * @return this + */ + correctLightness(enable: boolean): Scale; + + /** + * Get the current domain. + * + * @return The current domain. + */ + domain(): number[]; + + /** + * Set the domain. + * + * @param domain An Array of at least two numbers (min and max). + * @param classes The number of fixed classes to create between min and max. + * @param mode The scale to use. Examples: log, quantiles, k-means. + * @return this + */ + domain(domain: number[], classes?: number, mode?: string): Scale; + + /** + * Specify in which color space the colors should be interpolated. Defaults to "rgb". + * You can use any of the following spaces: rgb, hsv, hsl, lab, lch + * + * @param colorSpace The color space to use for interpolation. + * @return this + */ + mode(colorSpace: string): Scale; + + /** + * Set the output mode of this Scale. + * + * @param mode The output mode to use. Must be one of Color's getters. + * @return this + */ + out(mode: string): Scale; + + /** + * Set the color range after initialization. + * + * @param colors An Array of at least two color names or hex values. + * @return this + */ + range(colors: string[]): Scale; + } + +} + +declare var chroma: Chroma.ChromaStatic; diff --git a/chroma-js/chroma-js-tests.ts b/chroma-js/chroma-js-tests.ts index 3240ac11f8..a994af975f 100644 --- a/chroma-js/chroma-js-tests.ts +++ b/chroma-js/chroma-js-tests.ts @@ -1,120 +1,188 @@ /// +import * as myChroma from "chroma-js"; + function test_chroma() { - chroma("red"); - chroma("#ff0000"); - chroma("#f00"); - chroma("FF0000"); - chroma(255, 0, 0); - chroma([255, 0, 0]); - chroma(0, 1, 0.5, 'hsl'); - chroma([0, 1, 0.5], 'hsl'); - chroma(0, 1, 1, 'hsv'); - chroma("rgb(255,0,0)"); - chroma("rgb(100%,0%,0%)"); - chroma("hsl(0,100%,50%)"); - chroma(53.24, 80.09, 67.20, 'lab'); - chroma(53.24, 104.55, 40, 'lch'); - chroma(1, 0, 0, 'gl'); + chroma('hotpink'); + chroma('#ff3399'); + chroma('F39'); + chroma.hex("#fff"); + + chroma(0xff3399); + chroma(0xff, 0x33, 0x99); + chroma(255, 51, 153); + chroma([255, 51, 153]); + chroma(330, 1, 0.6, 'hsl'); + chroma.hsl(330, 1, 0.6); + chroma.lch(80, 40, 130); + chroma(80, 40, 130, 'lch'); + chroma.cmyk(0.2, 0.8, 0, 0); + chroma(0.2, 0.8, 0, 0, 'cmyk'); + chroma.gl(0.6, 0, 0.8); + chroma.gl(0.6, 0, 0.8, 0.5); + chroma(0.6, 0, 0.8, 'gl'); + chroma.temperature(2000); + chroma.temperature(3500); + chroma.temperature(6000); + chroma.mix('red', 'blue'); + chroma.mix('red', 'blue', 0.25); + chroma.mix('red', 'blue', 0.5, 'rgb'); + chroma.mix('red', 'blue', 0.5, 'hsl'); + chroma.mix('red', 'blue', 0.5, 'lab'); + chroma.mix('red', 'blue', 0.5, 'lch'); + chroma.blend('4CBBFC', 'EEEE22', 'multiply'); + chroma.blend('4CBBFC', 'EEEE22', 'darken'); + chroma.blend('4CBBFC', 'EEEE22', 'lighten'); + chroma.random(); + chroma.contrast('pink', 'hotpink'); + chroma.contrast('pink', 'purple'); + chroma.brewer.OrRd; + var data = [3.0, 3.5, 3.6, 3.8, 3.8, 4.1, 4.3, 4.4, + 4.6, 4.9, 5.2, 5.3, 5.4, 5.7, 5.8, 5.9, + 6.2, 6.5, 6.8, 7.2, 9]; + chroma.limits(data, 'e', 5); + chroma.limits(data, 'q', 5); + chroma.limits(data, 'k', 5); - chroma.hex("#ff0000"); - chroma.hex("red"); - chroma.hex("rgb(255, 0, 0)"); - - chroma.rgb(255, 0, 0); - chroma.hsl(0, 1, 0.5); - chroma.hsv(120, 0.5, 0.5); - chroma.lab(53.24, 80.09, 67.20); - chroma.lch(53.24, 104.55, 40); - chroma.gl(1, 0, 0); - - chroma.interpolate('white', 'black', 0) // #ffffff - chroma.interpolate('white', 'black', 1) // #000000 - chroma.interpolate('white', 'black', 0.5) // #7f7f7f - chroma.interpolate('white', 'black', 0.5, 'hsv') // #808080 - chroma.interpolate('white', 'black', 0.5, 'lab') // #777777 - - chroma.interpolate('rgba(0,0,0,0)', 'rgba(255,0,0,1)', 0.5).css() //"rgba(127.5,0,0,0.5)" - - var bezInterpolator = chroma.interpolate.bezier(['white', 'yellow', 'red', 'black']); - bezInterpolator(0).hex() // #ffffff - bezInterpolator(0.33).hex() // #ffcc67 - bezInterpolator(0.66).hex() // #b65f1a - bezInterpolator(1).hex() // #000000 - - chroma.luminance('black') // 0 - chroma.luminance('white') // 1 - chroma.luminance('#ff0000') // 0.2126 - - chroma.contrast('white', 'navy') // 16.00 – ok - chroma.contrast('white', 'yellow') // 1.07 – not ok! + myChroma(0xff3399); + myChroma.limits(data, 'k', 5); } function test_color() { - chroma('red').hex() // "#FF0000"" - chroma('red').rgb() // [255, 0, 0] - chroma('red').hsv() // [0, 1, 1] - chroma('red').hsl() // [0, 1, 0.5] - chroma('red').lab() // [53.2407, 80.0924, 67.2031] - chroma('red').lch() // [53.2407, 104.5517, 39.9990] - chroma('red').rgba() // [255, 0, 0, 1] - chroma('red').css() // "rgb(255,0,0)" - chroma('red').alpha(0.7).css() // "rgba(255,0,0,0.7)" - chroma('red').css('hsl') // "hsl(0,100%,50%)" - chroma('red').alpha(0.7).css('hsl') // "hsla(0,100%,50%,0.7)" - chroma('blue').css('hsla') // "hsla(240,100%,50%,1)" + chroma('red').alpha(0.5); + chroma('rgba(255,0,0,0.35)').alpha(); + chroma('hotpink').darken(); + chroma('hotpink').darken(2); + chroma('hotpink').brighten(); + chroma('slategray').saturate(); + chroma('slategray').saturate(2); + chroma('hotpink').desaturate(); + chroma('hotpink').desaturate(2); + chroma('hotpink').desaturate(3); + // change hue to 0 deg (=red) + chroma('skyblue').set('hsl.h', 0); + // set chromacity to 30 + chroma('hotpink').set('lch.c', 30); + // half Lab lightness + chroma('orangered').set('lab.l', '*0.5'); + // double Lch saturation + chroma('darkseagreen').set('lch.c', '*2'); + chroma('orangered').get('lab.l'); + chroma('orangered').get('hsl.l'); + chroma('orangered').get('rgb.g'); + chroma('white').luminance(); + chroma('aquamarine').luminance(); + chroma('hotpink').luminance(); + chroma('darkslateblue').luminance(); + chroma('black').luminance(); + chroma('white').luminance(0.5); + chroma('aquamarine').luminance(0.5); + chroma('hotpink').luminance(0.5); + chroma('darkslateblue').luminance(0.5); + chroma('aquamarine').luminance(0.5); + chroma('aquamarine').luminance(0.5, 'lab'); + chroma('aquamarine').luminance(0.5, 'hsl'); + chroma('orange').hex(); + chroma('#ffa500').name(); + chroma('#ffa505').name(); + chroma('teal').css(); + chroma('teal').alpha(0.5).css(); + chroma('teal').css('hsl'); + chroma('orange').rgb(); + chroma('orange').hsl(); + chroma('white').hsl(); + chroma('orange').hsv(); + chroma('white').hsv(); + chroma('orange').hsi(); + chroma('white').hsi(); + chroma('orange').lab(); + chroma('skyblue').lch(); + chroma('skyblue').hcl(); + chroma('#ff3300').temperature(); + chroma('#ff8a13').temperature(); + chroma('#ffe3cd').temperature(); + chroma('#cbdbff').temperature(); + chroma('#b3ccff').temperature(); + chroma('33cc00').gl(); - var red = chroma('red'); - red.alpha(0.5); - red.css(); // rgba(255,0,0,0.5); - - chroma('red').darken().hex() // #BC0000 - chroma('red').brighten().hex() // #FF603B - chroma('#eecc99').saturate().hex() // #fcc973 - chroma('red').desaturate().hex() // #ec3d23 - - chroma('black').luminance() // 0 - chroma('white').luminance() // 1 - chroma('red').luminance() // 0.2126 + myChroma('teal').alpha(0.5).css(); + myChroma('teal').css('hsl'); + myChroma('orange').rgb(); } function test_scale() { - var scale = chroma.scale(['lightyellow', 'navy']); - scale(0.5); // #7F7FB0 + var f = chroma.scale(); + f(0.25); + f(0.5); + f(0.75); + chroma.scale(['yellow', '008ae5']); + chroma.scale(['yellow', 'red', 'black']); + // default domain is [0,1] + chroma.scale(['yellow', '008ae5']); + // set domain to [0,100] + chroma.scale(['yellow', '008ae5']).domain([0, 100]); + // default domain is [0,1] + chroma.scale(['yellow', 'lightgreen', '008ae5']) + .domain([0, 0.25, 1]); + chroma.scale(['yellow', '008ae5']); + chroma.scale(['yellow', 'navy']); + chroma.scale(['yellow', 'navy']).mode('lab'); + chroma.scale(['yellow', 'navy']).mode('lab'); + chroma.scale(['yellow', 'navy']).mode('hsl'); + chroma.scale(['yellow', 'navy']).mode('lch'); + chroma.scale('YlGnBu'); + chroma.scale('Spectral'); + chroma.scale('Spectral').domain([1, 0]); + chroma.brewer.OrRd; + chroma.scale(['yellow', '008ae5']).mode('lch'); + + chroma.scale(['yellow', '008ae5']) + .mode('lch') + .correctLightness(); + // linear interpolation + chroma.scale(['yellow', 'red', 'black']); + // bezier interpolation + chroma.bezier(['yellow', 'red', 'black']); + // convert bezier interpolator into chroma.scale + chroma.bezier(['yellow', 'red', 'black']) + .scale().colors(5); + // use the default helix... + chroma.cubehelix(); + // or customize it + chroma.cubehelix() + .start(200) + .rotations(-0.5) + .gamma(0.8) + .lightness([0.3, 0.8]); + + chroma.cubehelix() + .start(200) + .rotations(-0.35) + .gamma(0.7) + .lightness([0.3, 0.8]) + .scale() // convert to chroma.scale + .correctLightness() + .colors(5); chroma.scale('RdYlBu'); + chroma.scale('RdYlBu').padding(0.15); - var col = scale(0.5); - col.hex(); // #7F7FB0 - col.rgb(); // [127.5, 127.5, 176] + chroma.scale('OrRd'); + chroma.scale('OrRd').padding([0.2, 0]); - scale = chroma.scale(['lightyellow', 'navy']).out('hex'); - scale(0.5); // "#7F7FB0" + chroma.scale('OrRd').classes(5); + chroma.scale('OrRd').classes(8); - var scale = chroma.scale(['lightyellow', 'navy']); - scale.mode('hsv')(0.5); // #54C08A - scale.mode('hsl')(0.5); // #31FF98 - scale.mode('lab')(0.5); // #967CB2 - scale.mode('lch')(0.5); // #D26662 + myChroma.cubehelix() + .start(200) + .rotations(-0.35) + .gamma(0.7) + .lightness([0.3, 0.8]) + .scale() // convert to chroma.scale - var scale = chroma.scale(['lightyellow', 'navy']).domain([0, 400]); - scale(200); // #7F7FB0 + .correctLightness() + .colors(5); - var scale = chroma.scale(['lightyellow', 'navy']).domain([0, 100, 200, 300, 400]); - scale(98); // #7F7FB0 - scale(99); // #7F7FB0 - scale(100); // #AAAAC0 - scale(101); // #AAAAC0 - - chroma.scale(['#eee', '#900']).domain([0, 400], 7); - chroma.scale(['#eee', '#900']).domain([1, 1000000], 7, 'log'); - chroma.scale(['#eee', '#900']).domain([1, 1000000], 5, 'quantiles'); - chroma.scale(['#eee', '#900']).domain([1, 1000000], 5, 'k-means'); - chroma.scale(['white', 'red']).domain([0, 100], 4).domain() // [0, 25, 50, 75, 100] - - chroma.scale().range(['lightyellow', 'navy']); - - chroma.scale(['lightyellow', 'navy']).correctLightness(true); - - chroma.scale('RdYlGn').domain([0,1], 5).colors() + myChroma.scale('RdYlBu'); + myChroma.scale('RdYlBu').padding(0.15); } diff --git a/chroma-js/chroma-js.d.ts b/chroma-js/chroma-js.d.ts index 5d785eda27..e3f463d368 100644 --- a/chroma-js/chroma-js.d.ts +++ b/chroma-js/chroma-js.d.ts @@ -1,14 +1,14 @@ -// Type definitions for Chroma.js v0.5.6 +// Type definitions for Chroma.js v1.1.1 // Project: https://github.com/gka/chroma.js -// Definitions by: Sebastian Brückner +// Definitions by: Sebastian Brückner , Marcin Pacholec // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** * Chroma.js is a tiny library for all kinds of color conversions and color scales. */ declare namespace Chroma { - export interface ChromaStatic { + /** * Creates a color from a string representation (as supported in CSS). * @@ -17,6 +17,14 @@ declare namespace Chroma { */ (color: string): Color; + /** + * Creates a color from a number representation [0; 16777215] + * + * @param color The number to convert to a color. + * @return the color object. + */ + (number: number): Color; + /** * Create a color in the specified color space using a, b and c as values. * @@ -25,72 +33,20 @@ declare namespace Chroma { * @param c * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". * @return the color object. - */ + */ (a: number, b: number, c: number, colorSpace?: string): Color; + (a: number, b: number, c: number, d: number, colorSpace?: string): Color; + /** - * Create a color in the specified color space using values. - * - * @param values An array of values (e.g. [r, g, b, a?]). - * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". - * @return the color object. - */ + * Create a color in the specified color space using values. + * + * @param values An array of values (e.g. [r, g, b, a?]). + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + * @return the color object. + */ (values: number[], colorSpace?: string): Color; - /** - * Create a color in the specified color space using a, b and c as values. - * - * @param a - * @param b - * @param c - * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". - * @return the color object. - */ - color(a: number, b: number, c: number, colorSpace?: string): Color; - - /** - * Calculate the contrast ratio of two colors. - * - * @param color1 The first color. - * @param color2 The second color. - * @return the contrast ratio. - */ - contrast(color1: Color, color2: Color): number; - /** - * Calculate the contrast ratio of two colors. - * - * @param color1 The first color. - * @param color2 The second color. - * @return the contrast ratio. - */ - contrast(color1: Color, color2: string): number; - /** - * Calculate the contrast ratio of two colors. - * - * @param color1 The first color. - * @param color2 The second color. - * @return the contrast ratio. - */ - contrast(color1: string, color2: Color): number; - /** - * Calculate the contrast ratio of two colors. - * - * @param color1 The first color. - * @param color2 The second color. - * @return the contrast ratio. - */ - contrast(color1: string, color2: string): number; - - /** - * Create a color from a hex or string representation (as supported in CSS). - * - * This is an alias of chroma.hex(). - * - * @param color The string to convert to a color. - * @return the color object. - */ - css(color: string): Color; - /** * Create a color from a hex or string representation (as supported in CSS). * @@ -101,217 +57,213 @@ declare namespace Chroma { */ hex(color: string): Color; - rgb(red: number, green: number, blue: number, alpha?: number): Color; - hsl(hue: number, saturation: number, lightness: number, alpha?: number): Color; - hsv(hue: number, saturation: number, value: number, alpha?: number): Color; + hsl(h: number, s: number, l: number): Color; + + hsv(h: number, s: number, v: number): Color; + lab(lightness: number, a: number, b: number, alpha?: number): Color; - lch(lightness: number, chroma: number, hue: number, alpha?: number): Color; + + lch(l: number, c: number, h: number): Color; + + rgb(r: number, g: number, b: number): Color; + + /** + * GL is a variant of RGB(A), with the only difference that the components are normalized to the range of 0..1. + */ gl(red: number, green: number, blue: number, alpha?: number): Color; - interpolate: InterpolateFunction; - mix: InterpolateFunction; + /** + * light 2000K, bright sunlight 6000K. Based on Neil Bartlett's implementation. + * https://github.com/neilbartlett/color-temperature + */ + temperature(t: number): Color; - luminance(color: Color): number; - luminance(color: string): number; + mix(col1: string | Color, col2: string | Color, f?: number, colorSpace?: string): Color; + + interpolate(col1: string | Color, col2: string | Color, f?: number, colorSpace?: string): Color; /** - * Creates a color scale using a pre-defined color scale. - * - * @param name The name of the color scale. - * @return the resulting color scale. + * Blends two colors using RGB channel-wise blend functions. Valid blend modes are multiply, darken, lighten, screen, overlay, burn, and dogde. */ + blend(col1: string, col2: string, blendMode: string): Color; + + /** + * Returns a random color. + */ + random(): Color; + + /** + * Computes the WCAG contrast ratio between two colors. + * A minimum contrast of 4.5:1 is recommended to ensure that text is still readable against a background color. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(col1: string | Color, col2: string | Color): number; + + bezier(colors: string[]): Scale; + + /** + * chroma.brewer is an map of ColorBrewer scales that are included in chroma.js for convenience. + * chroma.scale uses the colors to construct. + */ + brewer: { + OrRd: string[]; + PuBu: string[]; + BuPu: string[]; + Oranges: string[]; + BuGn: string[]; + YlOrBr: string[]; + YlGn: string[]; + Reds: string[]; + RdPu: string[]; + Greens: string[]; + YlGnBu: string[]; + Purples: string[]; + GnBu: string[]; + Greys: string[]; + YlOrRd: string[]; + PuRd: string[]; + Blues: string[]; + PuBuGn: string[]; + Spectral: string[]; + RdYlGn: string[]; + RdBu: string[]; + PiYG: string[]; + PRGn: string[]; + RdYlBu: string[]; + BrBG: string[]; + RdGy: string[]; + PuOr: string[]; + Set2: string[]; + Accent: string[]; + Set1: string[]; + Set3: string[]; + Dark2: string[]; + Paired: string[]; + Pastel2: string[]; + Pastel1: string[]; + }; + + /** + * Helper function that computes class breaks for you, based on actual data. + * Supports three different modes: equidistant breaks, quantiles breaks and breaks based on k-means clusting. + */ + limits(data: number[], mode: string, c: number): number[]; + scale(name: string): Scale; - /** - * Creates a color scale function from the given set of colors. - * - * @param colors An Array of at least two color names or hex values. - * @return the resulting color scale. - */ scale(colors?: string[]): Scale; - scales: PredefinedScales; - } + cubehelix(): Cubehelix; - interface InterpolateFunction { - (color1: Color, color2: Color, f: number, mode?: string): Color; - (color1: Color, color2: string, f: number, mode?: string): Color; - (color1: string, color2: Color, f: number, mode?: string): Color; - (color1: string, color2: string, f: number, mode?: string): Color; - - bezier(colors: any[]): (t: number) => Color; - } - - interface PredefinedScales { - [key: string]: Scale; - - cool: Scale; - hot: Scale; + cmyk(c: number, m: number, y: number, k: number): Color; + + /** + * Create a color from a hex or string representation (as supported in CSS). + * + * This is an alias of chroma.hex(). + * + * @param color The string to convert to a color. + * @return the color object. + */ + css(col: string, mode?: string): string; } export interface Color { - /** - * Creates a color from a string representation (as supported in CSS). - * - * @param color The string to convert to a color. - */ - new(color: string): Color; + alpha(a?: number): Color; - /** - * Create a color in the specified color space using a, b and c as values. - * - * @param a - * @param b - * @param c - * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". - */ - new(a: number, b: number, c: number, colorSpace?: string): Color; + darken(f?: number): Color; - /** - * Create a color in the specified color space using a, b and c as color values and alpha as the alpha value. - * - * @param a - * @param b - * @param c - * @param alpha The alpha value of the color. - * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". - */ - new(a: number, b: number, c: number, alpha: number, colorSpace?: string): Color; + brighten(f?: number): Color; - /** - * Create a color in the specified color space using values. - * - * @param values An array of values (e.g. [r, g, b, a?]). - * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". - */ - new(values: number[], colorSpace: string): Color; + saturate(s?: number): Color; - /** - * Convert this color to CSS hex representation. - * - * @return this color's hex representation. - */ - hex(): string; + desaturate(s?: number): Color; + + set(modechan: string, v: number | string): Color; + + get(modechan: string): number; - /** - * @return the relative luminance of the color, which is a value between 0 (black) and 1 (white). - */ luminance(): number; - /** - * @return the X11 name of this color or its hex value if it does not have a name. - */ + luminance(l: number, mode?: string): Color; + + hex(): string; + name(): string; /** - * @return the alpha value of the color. - */ - alpha(): number; - - /** - * Set the alpha value. + * Create a color from a hex or string representation (as supported in CSS). * - * @param alpha The alpha value. - * @return this + * This is an alias of chroma.hex(). + * + * @param color The string to convert to a color. + * @return the color object. */ - alpha(alpha: number): Color; - css(mode?: string): string; - interpolate(color: Color, f: number, mode?: string): Color; - interpolate(color: string, f: number, mode?: string): Color; - - premultiply(): Color; - rgb(): number[]; + rgba(): number[]; + hsl(): number[]; + hsv(): number[]; - lab(): number[]; - lch(): number[]; + hsi(): number[]; + + lab(): number[]; + + lch(): number[]; + + hcl(): number[]; + + temperature(): number; + gl(): number[]; - - darken(amount?: number): Color; - darker(amount: number): Color; - brighten(amount?: number): Color; - brighter(amount: number): Color; - saturate(amount?: number): Color; - desaturate(amount?: number): Color; - - toString(): string; } export interface Scale { - /** - * Interpolate a color using the currently set range and domain. - * - * @param value The value to use for interpolation. - * @return the interpolated hex color OR a Color object (depending on the mode set on this Scale). - */ + (c: string[]): Scale; + (value: number): any; - /** - * Retreive all possible colors generated by this scale if it has distinct classes. - * - * @param mode The output mode to use. Must be one of Color's getters. Defaults to "hex". - * @return an array of colors in the type specified by mode. - */ - colors(mode?: string): any[]; + domain(d?: number[], n?: number, mode?: string): Scale; - correctLightness(): boolean; + mode(mode: string): Scale; - /** - * Enable or disable automatic lightness correction of this scale. - * - * @param Whether to enable or disable automatic lightness correction. - * @return this - */ - correctLightness(enable: boolean): Scale; + correctLightness(enable?: boolean): Scale; - /** - * Get the current domain. - * - * @return The current domain. - */ - domain(): number[]; + bezier(colors: string[]): Scale; - /** - * Set the domain. - * - * @param domain An Array of at least two numbers (min and max). - * @param classes The number of fixed classes to create between min and max. - * @param mode The scale to use. Examples: log, quantiles, k-means. - * @return this - */ - domain(domain: number[], classes?: number, mode?: string): Scale; + padding(p: number | number[]): Scale; - /** - * Specify in which color space the colors should be interpolated. Defaults to "rgb". - * You can use any of the following spaces: rgb, hsv, hsl, lab, lch - * - * @param colorSpace The color space to use for interpolation. - * @return this - */ - mode(colorSpace: string): Scale; + colors(c?: number): string[]; + + classes(c: number | number[]): (t: number) => Color; + + range(arg: string[]): Scale; + + scale(): Scale; - /** - * Set the output mode of this Scale. - * - * @param mode The output mode to use. Must be one of Color's getters. - * @return this - */ out(mode: string): Scale; - - /** - * Set the color range after initialization. - * - * @param colors An Array of at least two color names or hex values. - * @return this - */ - range(colors: string[]): Scale; } + export interface Cubehelix extends Scale { + start(s: number): Cubehelix; + + rotations(r: number): Cubehelix; + + gamma(g: number): Cubehelix; + + lightness(l: number[]): Cubehelix; + } } declare var chroma: Chroma.ChromaStatic; + +declare module "chroma-js" { + export = chroma; +} diff --git a/chrome/chrome-app.d.ts b/chrome/chrome-app.d.ts index 3b63357986..1019f4066c 100644 --- a/chrome/chrome-app.d.ts +++ b/chrome/chrome-app.d.ts @@ -6,6 +6,17 @@ /// /// +//////////////////// +// App +//////////////////// +declare namespace chrome.app { + interface AppDetails extends chrome.runtime.Manifest { + id: string; + } + + export function getDetails(): AppDetails; +} + //////////////////// // App Runtime //////////////////// diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index bdd0271fca..dbf6a12446 100644 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -7219,7 +7219,7 @@ declare namespace chrome.webRequest { * Optional. * If the request method is POST and the body is a sequence of key-value pairs encoded in UTF8, encoded as either multipart/form-data, or application/x-www-form-urlencoded, this dictionary is present and for each key contains the list of all values for that key. If the data is of another media type, or if it is malformed, the dictionary is not present. An example value of this dictionary is {'key': ['value1', 'value2']}. */ - formData?: Object; + formData?: { [key: string]: string[] }; /** * Optional. * If the request method is PUT or POST, and the body is not already parsed in formData, then the unparsed request body elements are contained in this array. @@ -7233,6 +7233,7 @@ declare namespace chrome.webRequest { } interface ResourceRequest { + url: string; /** The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request. */ requestId: string; /** The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. */ @@ -7251,7 +7252,6 @@ declare namespace chrome.webRequest { } interface WebRequestDetails extends ResourceRequest { - url: string; /** Standard HTTP method. */ method: string; } @@ -7304,7 +7304,7 @@ declare namespace chrome.webRequest { interface WebAuthenticationChallengeDetails extends WebResponseHeadersDetails { /** The authentication scheme, e.g. Basic or Digest. */ - schema: string; + scheme: string; /** The authentication realm provided by the server, if there is one. */ realm?: string; /** The server requesting authentication. */ @@ -7336,7 +7336,9 @@ declare namespace chrome.webRequest { interface WebRedirectionResponseEvent extends _WebResponseHeadersEvent {} - interface WebAuthenticationChallengeEvent extends chrome.events.Event<(details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void> {} + interface WebAuthenticationChallengeEvent extends chrome.events.Event<(details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void> { + addListener(callback: (details: WebAuthenticationChallengeDetails) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; + } interface WebResponseErrorEvent extends _WebResponseHeadersEvent {} diff --git a/ckeditor/ckeditor.d.ts b/ckeditor/ckeditor.d.ts index 9d8728338f..60b6491407 100644 --- a/ckeditor/ckeditor.d.ts +++ b/ckeditor/ckeditor.d.ts @@ -57,6 +57,7 @@ declare namespace CKEDITOR { var basePath: string; var currentInstance: editor; var document: dom.document; + var env: environmentConfig; var instances: editor[]; var loadFullCoreTimeout: number; var revision: string; @@ -1029,6 +1030,12 @@ declare namespace CKEDITOR { } + interface IMenuItemDefinition { + label:string, + command:string, + group:string, + order:number + } class editor extends event { activeEnterMode: number; @@ -1066,13 +1073,14 @@ declare namespace CKEDITOR { addCommand(commandName: string, commandDefinition: commandDefinition): void; addFeature(feature: feature): boolean; addMenuGroup(name: string, order?: number): void; - addMenuItem(name: string, definition?: any): void; - addMenuItems(definitions: any[]): void; + addMenuItem(name: string, definition?: IMenuItemDefinition): void; + addMenuItems(definitions: {[id:string]:IMenuItemDefinition}): void; addMode(mode: string, exec: () => void): void; addRemoveFormatFilter(func: Function): void; applyStyle(style: style): void; attachStyleStateChange(style: style, callback: Function): void; checkDirty(): boolean; + commands:any; createFakeElement(realElement: Object, className: Object, realElementType: Object, isResizable: Object): void; createFakeParserElement(realElement: Object, className: Object, realElementType: Object, isResizable: Object): void; createRange(): dom.range; @@ -1235,6 +1243,11 @@ declare namespace CKEDITOR { } + interface buttonDefinition { + label : string; + command : string; + toolbar : string; + } interface template { @@ -1284,10 +1297,31 @@ declare namespace CKEDITOR { class ui extends event { constructor(editor: editor); add(name: string, type: Object, definition: Object): void; - addButton(name: string, definition: dialog.definition.button): void; + addButton(name: string, definition: buttonDefinition): void; addHandler(type: Object, handler: Object): void; } + class environmentConfig { + air : boolean; + chrome : boolean; + cssClass : string; + edge : boolean; + gecko : boolean; + hc : boolean; + hidpi : boolean; + iOS : boolean; + ie : boolean; + isCompatible : boolean; + mac : boolean; + needsBrFiller : boolean; + needsNbspFiller : boolean; + quirks : boolean; + safari : boolean; + version : number; + webkit : boolean; + secure( ) : boolean; + } + namespace ui { namespace dialog { class uiElement { @@ -1761,6 +1795,7 @@ declare namespace CKEDITOR { namespace tools { var callFunction: Function; + function enableHtml5Elements(doc: Object, withAppend? : Boolean) : void; } @@ -1772,3 +1807,4 @@ declare namespace CKEDITOR { function detect(defaultLanguage: string, probeLanguage: string): string; } } + diff --git a/colors/colors-tests.ts b/colors/colors-tests.ts index 15fd5ab4e5..ff838da995 100644 --- a/colors/colors-tests.ts +++ b/colors/colors-tests.ts @@ -3,9 +3,17 @@ import colors = require("colors"); +colors.enabled = true; + console.log(colors.black.underline('test')); console.log(colors.rainbow.black.blue.gray('test')); console.log(colors.random.reset.bgWhite.dim('test')); +console.log(colors.random.reset.bgWhite.strip('test')); console.log('test'.black.underline); console.log('test'.rainbow.black.blue.gray); console.log('test'.random.reset.bgWhite.dim); +console.log('test'.random.reset.bgWhite.dim.stripColors); + +colors.enabled = false; + +console.log(colors.black.underline('test')); diff --git a/colors/colors.d.ts b/colors/colors.d.ts index 7a78240287..50e960c416 100644 --- a/colors/colors.d.ts +++ b/colors/colors.d.ts @@ -7,6 +7,9 @@ declare module "colors" { interface Color { (text: string): string; + strip: Color; + stripColors: Color; + black: Color; red: Color; green: Color; @@ -47,6 +50,11 @@ declare module "colors" { namespace e { export function setTheme(theme:any): void; + export var enabled: boolean; + + export var strip: Color; + export var stripColors: Color; + export var black: Color; export var red: Color; export var green: Color; @@ -88,6 +96,9 @@ declare module "colors" { } interface String { + strip: string; + stripColors: string; + black: string; red: string; green: string; diff --git a/concaveman/concaveman-tests.ts b/concaveman/concaveman-tests.ts new file mode 100644 index 0000000000..ddb1e6d125 --- /dev/null +++ b/concaveman/concaveman-tests.ts @@ -0,0 +1,5 @@ +/// +import * as concaveman from 'concaveman'; + +var points = [[10, 20], [30, 12.5]]; +var polygon = concaveman(points); \ No newline at end of file diff --git a/concaveman/concaveman.d.ts b/concaveman/concaveman.d.ts new file mode 100644 index 0000000000..a5b55c8fa3 --- /dev/null +++ b/concaveman/concaveman.d.ts @@ -0,0 +1,24 @@ +// Type definitions for concaveman 1.1.0 +// Project: https://github.com/mapbox/concaveman +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "concaveman" { + /** + * A very fast 2D concave hull algorithm in JavaScript (generates a general outline of a point set). + * + * @name concaveman + * @param {Array>} points is an array of [x, y] points. + * @param {number} [concavity=2] is a relative measure of concavity. 1 results in a relatively detailed shape, Infinity results in a convex hull. You can use values lower than 1, but they can produce pretty crazy shapes. + * @param {number} [lengthThreshold=0] when a segment length is under this threshold, it stops being considered for further detalization. Higher values result in simpler shapes. + * @return {Array>} + * @example + * var points = [[10, 20], [30, 12.5], ...]; + * var polygon = concaveman(points); + * + * //=hull + */ + function concaveman(points: number[][], concavity?: number, lengthThreshold?: number): number[][]; + namespace concaveman {} + export = concaveman; +} diff --git a/consolidate/consolidate.d.ts b/consolidate/consolidate.d.ts index ff54a83a8e..aa07150f20 100644 --- a/consolidate/consolidate.d.ts +++ b/consolidate/consolidate.d.ts @@ -6,7 +6,7 @@ // Imported from: https://github.com/soywiz/typescript-node-definitions/consolidate.d.ts /// -/// +/// declare module "consolidate" { var cons: Consolidate; diff --git a/convict/convict-tests.ts b/convict/convict-tests.ts index 3bd64c5929..56326c00b3 100644 --- a/convict/convict-tests.ts +++ b/convict/convict-tests.ts @@ -104,7 +104,7 @@ conf.loadFile(['./configs/always.json', './configs/sometimes.json']); // perform validation -conf.validate(); +conf.validate({ strict: true }); var port: number = conf.default('port'); diff --git a/convict/convict.d.ts b/convict/convict.d.ts index 05323de269..07bf5940ff 100644 --- a/convict/convict.d.ts +++ b/convict/convict.d.ts @@ -41,7 +41,7 @@ declare module "convict" { load(conf: Object): void; loadFile(file: string): void; loadFile(files: string[]): void; - validate(): void; + validate(options?: { strict?: boolean }): void; /** * Exports all the properties (that is the keys and their current values) as a {JSON} {Object} * @returns {Object} A {JSON} compliant {Object} diff --git a/cordova/cordova-tests.ts b/cordova/cordova-tests.ts index 7e97305a25..6d98471b12 100644 --- a/cordova/cordova-tests.ts +++ b/cordova/cordova-tests.ts @@ -126,12 +126,27 @@ function fsaccessor(fs: FileSystem) { (err: FileError)=> { alert('Error: ' + err.code); }); } + + +//---------------------------------------------------------------------- +// FileSystem plugin +// +//cordova states that the enums for requestFileSystem live on LocalFileSystem +// window.requestFileSystem( - window.TEMPORARY, + LocalFileSystem.TEMPORARY, 1024 * 1024 * 5, fsaccessor, (err: FileError) => { alert('Error: ' + err.code); } ); +window.requestFileSystem( + LocalFileSystem.PERSISTENT, + 1024 * 1024 * 5, + fsaccessor, + (err: FileError) => { alert('Error: ' + err.code); } +); +// FileSystem plugin +//---------------------------------------------------------------------- window.resolveLocalFileSystemURI(cordova.file.applicationDirectory, (entry: Entry)=> { diff --git a/cordova/plugins/Contacts.d.ts b/cordova/plugins/Contacts.d.ts index d940fccd77..90b21ae2bb 100644 --- a/cordova/plugins/Contacts.d.ts +++ b/cordova/plugins/Contacts.d.ts @@ -42,6 +42,40 @@ interface Contacts { */ pickContact(onSuccess: (contact: Contact) => void, onError: (error: ContactError) => void): void + + /** + * This allows us to use an enumeration when setting the desired fields for the ContactFindOptions. + * The values will correspond to the type of string literals in ContactFieldType. + */ + fieldType: { + addresses: "addresses", + birthday: "birthday", + categories: "categories", + country: "country", + department: "department", + displayName: "displayName", + emails: "emails", + familyName: "familyName", + formatted: "formatted", + givenName: "givenName", + honorificPrefix: "honorificPrefix", + honorificSuffix: "honorificSuffix", + id: "id", + ims: "ims", + locality: "locality", + middleName: "middleName", + name: "name", + nickname: "nickname", + note: "note", + organizations: "organizations", + phoneNumbers: "phoneNumbers", + photos: "photos", + postalCode: "postalCode", + region: "region", + streetAddress: "streetAddress", + title: "title", + urls: "urls" + } } interface ContactProperties { @@ -105,7 +139,7 @@ interface Contact extends ContactProperties { declare var Contact: { /** Constructor of Contact object */ - new(id?: string, + new (id?: string, displayName?: string, name?: ContactName, nickname?: string, @@ -130,7 +164,7 @@ interface ContactError { } declare var ContactError: { - new(code: number): ContactError; + new (code: number): ContactError; UNKNOWN_ERROR: number; INVALID_ARGUMENT_ERROR: number; TIMEOUT_ERROR: number; @@ -158,7 +192,7 @@ interface ContactName { declare var ContactName: { /** Constructor for ContactName object */ - new(formatted?: string, + new (formatted?: string, familyName?: string, givenName?: string, middleName?: string, @@ -189,7 +223,7 @@ interface ContactField { declare var ContactField: { /** Constructor for ContactField object */ - new(type?: string, + new (type?: string, value?: string, pref?: boolean): ContactField }; @@ -219,7 +253,7 @@ interface ContactAddress { declare var ContactAddress: { /** Constructor of ContactAddress object */ - new(pref?: boolean, + new (pref?: boolean, type?: string, formatted?: string, streetAddress?: string, @@ -248,7 +282,7 @@ interface ContactOrganization { declare var ContactOrganization: { /** Constructor for ContactOrganization object */ - new(pref?: boolean, + new (pref?: boolean, type?: string, name?: string, department?: string, @@ -262,12 +296,42 @@ interface ContactFindOptions { /** Determines if the find operation returns multiple navigator.contacts. */ multiple?: boolean; /* Contact fields to be returned back. If specified, the resulting Contact object only features values for these fields. */ - desiredFields?: string[]; + desiredFields?: ContactFieldType[]; } +/** these are the string values that are valid for the desired fields in ContactFindOptions */ +declare type ContactFieldType = + "addresses" + | "birthday" + | "categories" + | "country" + | "department" + | "displayName" + | "emails" + | "familyName" + | "formatted" + | "givenName" + | "honorificPrefix" + | "honorificSuffix" + | "id" + | "ims" + | "locality" + | "middleName" + | "name" + | "nickname" + | "note" + | "organizations" + | "phoneNumbers" + | "photos" + | "postalCode" + | "region" + | "streetAddress" + | "title" + | "urls"; + declare var ContactFindOptions: { /** Constructor for ContactFindOptions object */ - new(filter?: string, + new (filter?: string, multiple?: boolean, - desiredFields?: string[]): ContactFindOptions -}; \ No newline at end of file + desiredFields?: ContactFieldType[]): ContactFindOptions +}; diff --git a/cordova/plugins/FileSystem.d.ts b/cordova/plugins/FileSystem.d.ts index 66a6014dea..f9471eda72 100644 --- a/cordova/plugins/FileSystem.d.ts +++ b/cordova/plugins/FileSystem.d.ts @@ -15,7 +15,7 @@ interface Window { * @param errorCallback A callback that is called when errors happen, or when the request to obtain the filesystem is denied. */ requestFileSystem( - type: number, + type: LocalFileSystem, size: number, successCallback: (fileSystem: FileSystem) => void, errorCallback?: (fileError: FileError) => void): void; @@ -371,3 +371,8 @@ interface Cordova { } } + +declare enum LocalFileSystem { + PERSISTENT=0, + TEMPORARY=1 +} diff --git a/core-js/core-js.d.ts b/core-js/core-js.d.ts index e9be316364..1ad88ff41a 100644 --- a/core-js/core-js.d.ts +++ b/core-js/core-js.d.ts @@ -31,7 +31,34 @@ interface ObjectConstructor { * Copy the values of all of the enumerable own properties from one or more source objects to a * target object. Returns the target object. * @param target The target object to copy to. - * @param sources One or more source objects to copy properties from. + * @param source The source object from which to copy properties. + */ + assign(target: T, source: U): T & U; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V): T & U & V; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param source1 The first source object from which to copy properties. + * @param source2 The second source object from which to copy properties. + * @param source3 The third source object from which to copy properties. + */ + assign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + + /** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * @param target The target object to copy to. + * @param sources One or more source objects from which to copy properties */ assign(target: any, ...sources: any[]): any; @@ -1862,7 +1889,7 @@ declare module "core-js/fn/number/max-safe-integer" { var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER; export = MAX_SAFE_INTEGER; } -declare module "core-js/fn/number/min-safe-interger" { +declare module "core-js/fn/number/min-safe-integer" { var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER; export = MIN_SAFE_INTEGER; } @@ -2641,7 +2668,7 @@ declare module "core-js/library/fn/number/max-safe-integer" { var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER; export = MAX_SAFE_INTEGER; } -declare module "core-js/library/fn/number/min-safe-interger" { +declare module "core-js/library/fn/number/min-safe-integer" { var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER; export = MIN_SAFE_INTEGER; } diff --git a/cors/cors.d.ts b/cors/cors.d.ts index eaf917fb1f..97ef574138 100644 --- a/cors/cors.d.ts +++ b/cors/cors.d.ts @@ -16,6 +16,7 @@ declare module "cors" { exposedHeaders?: any; credentials?: boolean; maxAge?: number; + preflightContinue?: boolean; } } diff --git a/couchbase/couchbase.d.ts b/couchbase/couchbase.d.ts index 351c9a806d..2508f0e1d5 100644 --- a/couchbase/couchbase.d.ts +++ b/couchbase/couchbase.d.ts @@ -159,6 +159,14 @@ declare module 'couchbase' { * Creates a manager allowing the management of a Couchbase cluster. */ manager(): ClusterManager; + + + /** + * Creates a manager allowing the management of a Couchbase cluster using credentials. + * @param username The username for your cluster. + * @param password The password for your cluster. + */ + manager(username: string, password: string): ClusterManager; /** * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this. diff --git a/countdown/countdown-tests.ts b/countdown/countdown-tests.ts new file mode 100644 index 0000000000..3ad8890aab --- /dev/null +++ b/countdown/countdown-tests.ts @@ -0,0 +1,42 @@ +/// + +import * as countdown from 'countdown'; + +let ts: countdown.Timespan; +let interval: number; + +ts = countdown(new Date()); +ts = countdown(150); + +interval = countdown(new Date(), + function (ts: countdown.Timespan) { + document.getElementById('pageTimer').innerHTML = ts.toHTML('strong'); + }, + countdown.HOURS | countdown.MINUTES | countdown.SECONDS, + 2, + 2 +); + +clearInterval(interval); + +ts.toString('foo'); +ts.toHTML('em', 'foo'); + +countdown.resetFormat(); +countdown.setLabels('a', 'b', 'c', 'd', 'e'); + +countdown.setLabels('a', 'b', 'c', 'd', 'e', function (value: number): string { + return 'ok'; +}, function (value: number, unit: number): string { + return 'ok'; +}); + +countdown.setLabels(null, null, null, null, 'Now.'); + +countdown.setLabels( + ' millisecond| second| minute| hour| day| week| month| year| decade| century| millennium', + ' milliseconds| seconds| minutes| hours| days| weeks| months| years| decades| centuries| millennia', + ' and ', + ', ', + '', + n => n.toString()); diff --git a/countdown/countdown.d.ts b/countdown/countdown.d.ts new file mode 100644 index 0000000000..bcb0d07976 --- /dev/null +++ b/countdown/countdown.d.ts @@ -0,0 +1,72 @@ +// Type definitions for countdown.js +// Project: http://countdownjs.org/ +// Definitions by: Gabriel Juchault +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace countdown { + type DateFunction = (timespan: Timespan) => void; + type DateTime = number | Date | DateFunction; + + interface Timespan { + start?: Date; + end?: Date; + units?: number; + value?: number; + millennia?: number; + centuries?: number; + decades?: number; + years?: number; + months?: number; + days?: number; + hours?: number; + minutes?: number; + seconds?: number; + milliseconds?: number; + toString(label?: string): string; + toHTML(tagName?: string, label?: string): string; + } + + interface Format { + singular?: string | Array; + plural?: string | Array; + last?: string; + delim?: string; + empty?: string; + formatNumber?(value: number): string; + formatter?(value: number, unit: number): string; + } + + interface CountdownStatic { + (start: DateTime, end?: DateTime, units?: number, max?: number, digits?: number): Timespan | number; + MILLENNIA: number; + CENTURIES: number; + DECADES: number; + YEARS: number; + MONTHS: number; + WEEKS: number; + DAYS: number; + HOURS: number; + MINUTES: number; + SECONDS: number; + MILLISECONDS: number; + ALL: number; + DEFAULTS: number; + resetLabels(): void; + setLabels( + singular?: string, + plural?: string, + last?: string, + delim?: string, + empty?: string, + formatNumber?: (value: number) => string, + formatter?: (value: number, unit: number) => string + ): void; + resetFormat(): void; + setFormat(format: Format): void; + } +} + +declare module 'countdown' { + let countdown: countdown.CountdownStatic; + export = countdown; +} diff --git a/credential/credential-tests.ts b/credential/credential-tests.ts index 6013436b05..307201c76e 100644 --- a/credential/credential-tests.ts +++ b/credential/credential-tests.ts @@ -1,16 +1,29 @@ /// +// all from current main repo examples + import * as credential from 'credential'; -credential.hash('password', function(err: Error, hash: string) { - if (err) console.error(err); - else console.log(hash); +var pw = credential(); +var newPassword = 'I have a really great password.'; + +pw.hash(newPassword, function (err, hash) { + if (err) { throw err; } + console.log('Store the password hash.', hash); }); -const hash = '{}'; -const password = 'test'; +var storedHash = { + "hash": "gNofnhlBl36AdRyktwATxKoqWKa6hsIEzwCmW/YXN//7PtiJwCRbepV9fUKu0L9TJELCKoDiBy6rGM8ov7lg2yLY", + "salt": "yyN3KUzlr4KrKWMM2K3d2Ddxf8OTq+vkKG+mtnmQVIibxSJz8drfzkYzqcH0EM+PVKR/1nClRr/CPDuJsq+FOcIw", + "keyLength": 66, + "hashMethod": "pbkdf2", + "iterations": 181019 +}; +var userInput = 'I have a really great password.'; -credential.verify(hash, password, function(err: Error, isValid: boolean) { - if (err) console.error(err); - else console.log(isValid ? 'Password match' : 'Incorrect password'); +pw.verify(storedHash, userInput, function (err, isValid) { + var msg: string; + if (err) { throw err; } + msg = isValid ? 'Passwords match!' : 'Wrong password.'; + console.log(msg); }); diff --git a/credential/credential.d.ts b/credential/credential.d.ts index 2934a090d4..af16e0e412 100644 --- a/credential/credential.d.ts +++ b/credential/credential.d.ts @@ -4,15 +4,33 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'credential' { + interface defaultOptions { + keyLength: number; + work: number; + hashMethod: string; + } - type HashCallback = (err: Error, hash: string) => void; - type VerifyCallback = (err: Error, isValid: boolean) => void; + interface hashObject { + hash: string; + salt: string; + keyLength: number; + hashMethod: string; + iterations: number; + } - namespace credential { - function hash(password: string, callback: HashCallback): void; - function verify(hash: string, password: string, callback: VerifyCallback): void; - } + type HashCallback = (err: Error, hash: hashObject) => void; + type VerifyCallback = (err: Error, isValid: boolean) => void; - export = credential; + function credential(defaultOptions?: defaultOptions): { + hash(password: string, callback: HashCallback): void; + hash(password: string): Promise; + // iterations(work: number, base): number; + verify(hash: hashObject | string, password: string, callback: VerifyCallback): void; + verify(hash: hashObject | string, password: string): Promise; + expired(hash: string, days: number): boolean; + } + namespace credential { } + + export = credential; } diff --git a/cropperjs/cropperjs-tests.ts b/cropperjs/cropperjs-tests.ts index d328a12b4a..82232c268a 100644 --- a/cropperjs/cropperjs-tests.ts +++ b/cropperjs/cropperjs-tests.ts @@ -1,2 +1,16 @@ /// import * as Cropper from 'cropperjs'; + +var image = document.getElementById('image'); +var cropper = new Cropper(image, { + aspectRatio: 16 / 9, + crop: function(e) { + console.log(e.detail.x); + console.log(e.detail.y); + console.log(e.detail.width); + console.log(e.detail.height); + console.log(e.detail.rotate); + console.log(e.detail.scaleX); + console.log(e.detail.scaleY); + } +}); diff --git a/cropperjs/cropperjs.d.ts b/cropperjs/cropperjs.d.ts index f2f8e861e5..c76b4c7766 100644 --- a/cropperjs/cropperjs.d.ts +++ b/cropperjs/cropperjs.d.ts @@ -11,7 +11,26 @@ declare module cropperjs { CanvasShouldNotBeWithInTheContainer = 2, ContainerSshouldBeWithInTheCanvas = 3 } + export interface CropperCustomEvent extends CustomEvent { + detail: Data; + } export interface CropperOptions { + /** + * Function called when crop box is moved or resized + */ + crop?: (event: CropperCustomEvent) => void; + /** + * Function called at start of crop box being moved or resized + */ + cropstart?: (event: CropperCustomEvent) => void; + /** + * Function called when crop box is moved + */ + cropmove?: (event: CropperCustomEvent) => void; + /** + * Function called when crop box is finished being moved or resized + */ + cropend?: (event: CropperCustomEvent) => void; /** * Define the view mode of the cropper. * @default 0 diff --git a/crypto-js/crypto-js.d.ts b/crypto-js/crypto-js.d.ts index 0ab6681dce..e58b9c9339 100644 --- a/crypto-js/crypto-js.d.ts +++ b/crypto-js/crypto-js.d.ts @@ -93,6 +93,7 @@ declare namespace CryptoJS { Base64: Encoder; }; mode: { + CBC: Mode; CFB: Mode; CTR: Mode; CTRGladman: Mode; diff --git a/csurf/csurf.d.ts b/csurf/csurf.d.ts index ed2b2e68ed..3d213c76cd 100644 --- a/csurf/csurf.d.ts +++ b/csurf/csurf.d.ts @@ -1,4 +1,4 @@ -// Type definitions for csurf +// Type definitions for csurf 1.9.0 // Project: https://www.npmjs.org/package/csurf // Definitions by: Hiroki Horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -17,6 +17,8 @@ declare module "csurf" { function csurf(options?: { value?: (req: express.Request) => string; cookie?: csurf.CookieOptions | boolean; + ignoreMethods?: string[]; + sessionKey?: string; }): express.RequestHandler; namespace csurf { diff --git a/csv-stringify/csv-stringify.d.ts b/csv-stringify/csv-stringify.d.ts index a1cc16a15b..1effe84f61 100644 --- a/csv-stringify/csv-stringify.d.ts +++ b/csv-stringify/csv-stringify.d.ts @@ -58,8 +58,8 @@ declare module "csv-stringify" { interface Stringifier extends NodeJS.ReadWriteStream { - // Stringifier stream takes array of strings - write(line: string[]): boolean; + // Stringifier stream takes array of strings or Object + write(line: string[] | Object): boolean; // repeat declarations from NodeJS.WritableStream to avoid compile error write(buffer: Buffer, cb?: Function): boolean; diff --git a/cucumber/cucumber-tests.ts b/cucumber/cucumber-tests.ts index d6ada278c2..aa17cd331e 100644 --- a/cucumber/cucumber-tests.ts +++ b/cucumber/cucumber-tests.ts @@ -1,30 +1,32 @@ /// +/// function StepSample() { type Callback = cucumber.CallbackStepDefinition; + type Table = cucumber.TableDefinition; var step = this; var hook = this; - + hook.Before(function(scenario, callback){ scenario.isFailed() && callback.pending(); }) - + hook.Around(function(scenario, runScenario) { scenario.isFailed() && runScenario(null, function(){ console.log('finish tasks'); }); }); - + hook.registerHandler('AfterFeatures', function (event, callback) { callback(); }); - + step.Given(/^I am on the Cucumber.js GitHub repository$/, function(callback:Callback) { this.visit('https://github.com/cucumber/cucumber-js', callback); }); step.When(/^I go to the README file$/, function(title:string, callback:Callback) { - callback.pending(); + callback(null, 'pending'); }); step.Then(/^I should see "(.*)" as the page title$/, { timeout:60*1000}, function(title:string, callback:Callback) { @@ -36,5 +38,43 @@ function StepSample() { callback(new Error("Expected to be on page with title " + title)); } }); + + // Type for data_table.js on + // https://github.com/cucumber/cucumber-js/blob/a5fd8251918c278ab2e389226d165cedb44df14a/lib/cucumber/ast/data_table.js + + step.Given(/^a table step with Table raw$/, function(table:Table){ + var expected = [ + ['Cucumber', 'Cucumis sativus'], + ['Burr Gherkin', 'Cucumis anguria'] + ]; + + assert.deepEqual(table.raw(), expected); + }); + + step.Given(/^a table step with Table rows$/, function(table: Table){ + var expected = [ + ['Apricot', '5'], + ['Brocolli', '2'], + ['Cucumber', '10'] + ]; + assert.deepEqual(table.rows(), expected) + }); + + step.Given(/^a table step with Table rowHash$/, function(table:Table){ + var expected = { + 'Cucumber': 'Cucumis sativus', + 'Burr Gherkin': 'Cucumis anguria' + }; + assert.deepEqual(table.rowsHash(), expected) + }); + + step.Given(/^a table step$/, function(table:Table){ + var expected = [ + {'Vegetable': 'Apricot', 'Rating': '5'}, + {'Vegetable': 'Brocolli', 'Rating': '2'}, + {'Vegetable': 'Cucumber', 'Rating': '10'} + ]; + assert.deepEqual(table.hashes(), expected) + }); } diff --git a/cucumber/cucumber.d.ts b/cucumber/cucumber.d.ts index 6c4273e4e0..a415a478e2 100644 --- a/cucumber/cucumber.d.ts +++ b/cucumber/cucumber.d.ts @@ -7,11 +7,20 @@ declare namespace cucumber { export interface CallbackStepDefinition{ pending : () => PromiseLike; - (errror?:any):void; + (errror?:any, pending?: string):void; } + export interface TableDefinition{ + raw: () => Array; + rows: () => Array; + rowsHash: () => {}; + hashes: () => {}; + } + + type StepDefinitionParam = string | CallbackStepDefinition | TableDefinition; + interface StepDefinitionCode { - (...stepArgs: Array): PromiseLike | any | void; + (...stepArgs: Array): PromiseLike | any | void; } interface StepDefinitionOptions{ diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 1da10a78ab..d539b7439d 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -297,7 +297,7 @@ declare namespace d3 { * @param value the function to compute data for each node */ datum(value: (datum: Datum, index: number, outerIndex: number) => NewDatum): Update; - + /** * Set the data item for each node in the selection. * @param value the constant element to use for each node @@ -415,7 +415,7 @@ declare namespace d3 { select(name: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; call(func: (selection: Enter, ...args: any[]) => any, ...args: any[]): Enter; - + empty(): boolean; size(): number; } @@ -1078,7 +1078,7 @@ declare namespace d3 { * Return the min and max simultaneously. */ export function extent(array: T[], accessor: (datum: T, index: number) => string): [string, string]; - + /** * Return the min and max simultaneously. */ @@ -2928,6 +2928,8 @@ declare namespace d3 { start(): Force; + tick(): Force; + alpha(): number; alpha(value: number): Force; @@ -2988,6 +2990,7 @@ declare namespace d3 { range(): (values: T[], index: number) => [number, number]; range(range: (values: T[], index: number) => [number, number]): Histogram; + range(range: [number, number]): Histogram; bins(): (range: [number, number], values: T[], index: number) => number[]; bins(count: number): Histogram; diff --git a/date-fns/date-fns-tests.ts b/date-fns/date-fns-tests.ts new file mode 100644 index 0000000000..4c1dfc2476 --- /dev/null +++ b/date-fns/date-fns-tests.ts @@ -0,0 +1,16 @@ +/// + +import {addDays, closestIndexTo, differenceInCalendarWeeks, max, isDate} from 'date-fns'; +import * as addHours from 'date-fns/add_hours'; + +function test() { + + addDays(new Date(), 5); + closestIndexTo(new Date(), [new Date(), new Date()]); + addHours(new Date(), 5); + differenceInCalendarWeeks(new Date(), new Date()); + differenceInCalendarWeeks(new Date(), new Date(), {weekStartsOn: 1}); + max(new Date(), new Date()); + isDate({}); + +} \ No newline at end of file diff --git a/date-fns/date-fns.d.ts b/date-fns/date-fns.d.ts new file mode 100644 index 0000000000..d0582c2571 --- /dev/null +++ b/date-fns/date-fns.d.ts @@ -0,0 +1,1195 @@ +// Type definitions for date-fns +// Project: https://date-fns.org/ +// Definitions by: Matt Lewis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type DateOrStringOrNumber = Date | string | number; + +declare module 'date-fns' { + + function addDays(date: DateOrStringOrNumber, amount: number): Date; + namespace addDays {} + + function addHours(date: DateOrStringOrNumber, amount: number): Date; + namespace addHours {} + + function addISOYears(date: DateOrStringOrNumber, amount: number): Date; + namespace addISOYears {} + + function addMilliseconds(date: DateOrStringOrNumber, amount: number): Date; + namespace addMilliseconds {} + + function addMinutes(date: DateOrStringOrNumber, amount: number): Date; + namespace addMinutes {} + + function addMonths(date: DateOrStringOrNumber, amount: number): Date; + namespace addMonths {} + + function addQuarters(date: DateOrStringOrNumber, amount: number): Date; + namespace addQuarters {} + + function addSeconds(date: DateOrStringOrNumber, amount: number): Date; + namespace addSeconds {} + + function addWeeks(date: DateOrStringOrNumber, amount: number): Date; + namespace addWeeks {} + + function addYears(date: DateOrStringOrNumber, amount: number): Date; + namespace addYears {} + + function closestIndexTo(dateToCompare: DateOrStringOrNumber, datesArray: DateOrStringOrNumber[]): number; + namespace closestIndexTo {} + + function closestTo(dateToCompare: DateOrStringOrNumber, datesArray: DateOrStringOrNumber[]): Date; + namespace closestTo {} + + function compareAsc(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace compareAsc {} + + function compareDesc(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace compareDesc {} + + function differenceInCalendarDays(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarDays {} + + function differenceInCalendarISOWeeks(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarISOWeeks {} + + function differenceInCalendarISOYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarISOYears {} + + function differenceInCalendarMonths(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarMonths {} + + function differenceInCalendarQuarters(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarQuarters {} + + function differenceInCalendarWeeks(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber, options?: {weekStartsOn: number}): number; + namespace differenceInCalendarWeeks {} + + function differenceInCalendarYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarYears {} + + function differenceInDays(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInDays {} + + function differenceInHours(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInHours {} + + function differenceInISOYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInISOYears {} + + function differenceInMilliseconds(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInMilliseconds {} + + function differenceInMinutes(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInMinutes {} + + function differenceInMonths(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInMonths {} + + function differenceInQuarters(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInQuarters {} + + function differenceInSeconds(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInSeconds {} + + function differenceInWeeks(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInWeeks {} + + function differenceInYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInYears {} + + function distanceInWords(dateFrom: DateOrStringOrNumber, dateTo: DateOrStringOrNumber, options?: {includeSeconds: boolean}): string; + namespace distanceInWords {} + + function distanceInWordsToNow(date: DateOrStringOrNumber, options?: {includeSeconds: boolean}): string; + namespace distanceInWordsToNow {} + + function eachDay(startDate: DateOrStringOrNumber, endDate: DateOrStringOrNumber): Date[]; + namespace eachDay {} + + function endOfDay(date: DateOrStringOrNumber): Date; + namespace endOfDay {} + + function endOfHour(date: DateOrStringOrNumber): Date; + namespace endOfHour {} + + function endOfISOWeek(date: DateOrStringOrNumber): Date; + namespace endOfISOWeek {} + + function endOfISOYear(date: DateOrStringOrNumber): Date; + namespace endOfISOYear {} + + function endOfMinute(date: DateOrStringOrNumber): Date; + namespace endOfMinute {} + + function endOfMonth(date: DateOrStringOrNumber): Date; + namespace endOfMonth {} + + function endOfQuarter(date: DateOrStringOrNumber): Date; + namespace endOfQuarter {} + + function endOfSecond(date: DateOrStringOrNumber): Date; + namespace endOfSecond {} + + function endOfToday(): Date; + namespace endOfToday {} + + function endOfTomorrow(): Date; + namespace endOfTomorrow {} + + function endOfWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): Date; + namespace endOfWeek {} + + function endOfYear(date: DateOrStringOrNumber): Date; + namespace endOfYear {} + + function endOfYesterday(): Date; + namespace endOfYesterday {} + + function format(date: DateOrStringOrNumber, format?: string): string; + namespace format {} + + function getDate(date: DateOrStringOrNumber): number; + namespace getDate {} + + function getDay(date: DateOrStringOrNumber): number; + namespace getDay {} + + function getDayOfYear(date: DateOrStringOrNumber): number; + namespace getDayOfYear {} + + function getDaysInMonth(date: DateOrStringOrNumber): number; + namespace getDaysInMonth {} + + function getDaysInYear(date: DateOrStringOrNumber): number; + namespace getDaysInYear {} + + function getHours(date: DateOrStringOrNumber): number; + namespace getHours {} + + function getISOWeek(date: DateOrStringOrNumber): number; + namespace getISOWeek {} + + function getISOWeeksInYear(date: DateOrStringOrNumber): number; + namespace getISOWeeksInYear {} + + function getISOYear(date: DateOrStringOrNumber): number; + namespace getISOYear {} + + function getMilliseconds(date: DateOrStringOrNumber): number; + namespace getMilliseconds {} + + function getMinutes(date: DateOrStringOrNumber): number; + namespace getMinutes {} + + function getMonth(date: DateOrStringOrNumber): number; + namespace getMonth {} + + function getQuarter(date: DateOrStringOrNumber): number; + namespace getQuarter {} + + function getSeconds(date: DateOrStringOrNumber): number; + namespace getSeconds {} + + function getYear(date: DateOrStringOrNumber): number; + namespace getYear {} + + function isAfter(dateToCompare: DateOrStringOrNumber, date: DateOrStringOrNumber): boolean; + namespace isAfter {} + + function isBefore(dateToCompare: DateOrStringOrNumber, date: DateOrStringOrNumber): boolean; + namespace isBefore {} + + function isDate(argument: any): boolean; + namespace isDate {} + + function isEqual(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isEqual {} + + function isFirstDayOfMonth(date: DateOrStringOrNumber): boolean; + namespace isFirstDayOfMonth {} + + function isFriday(date: DateOrStringOrNumber): boolean; + namespace isFriday {} + + function isFuture(date: DateOrStringOrNumber): boolean; + namespace isFuture {} + + function isLastDayOfMonth(date: DateOrStringOrNumber): boolean; + namespace isLastDayOfMonth {} + + function isLeapYear(date: DateOrStringOrNumber): boolean; + namespace isLeapYear {} + + function isMonday(date: DateOrStringOrNumber): boolean; + namespace isMonday {} + + function isPast(date: DateOrStringOrNumber): boolean; + namespace isPast {} + + function isSameDay(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameDay {} + + function isSameHour(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameHour {} + + function isSameISOWeek(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameISOWeek {} + + function isSameISOYear(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameISOYear {} + + function isSameMinute(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameMinute {} + + function isSameMonth(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameMonth {} + + function isSameQuarter(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameQuarter {} + + function isSameSecond(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameSecond {} + + function isSameWeek(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber, options?: {weekStartsOn: number}): boolean; + namespace isSameWeek {} + + function isSameYear(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameYear {} + + function isSaturday(date: DateOrStringOrNumber): boolean; + namespace isSaturday {} + + function isSunday(date: DateOrStringOrNumber): boolean; + namespace isSunday {} + + function isThisHour(date: DateOrStringOrNumber): boolean; + namespace isThisHour {} + + function isThisISOWeek(date: DateOrStringOrNumber): boolean; + namespace isThisISOWeek {} + + function isThisISOYear(date: DateOrStringOrNumber): boolean; + namespace isThisISOYear {} + + function isThisMinute(date: DateOrStringOrNumber): boolean; + namespace isThisMinute {} + + function isThisMonth(date: DateOrStringOrNumber): boolean; + namespace isThisMonth {} + + function isThisQuarter(date: DateOrStringOrNumber): boolean; + namespace isThisQuarter {} + + function isThisSecond(date: DateOrStringOrNumber): boolean; + namespace isThisSecond {} + + function isThisWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): boolean; + namespace isThisWeek {} + + function isThisYear(date: DateOrStringOrNumber): boolean; + namespace isThisYear {} + + function isThursday(date: DateOrStringOrNumber): boolean; + namespace isThursday {} + + function isToday(date: DateOrStringOrNumber): boolean; + namespace isToday {} + + function isTomorrow(date: DateOrStringOrNumber): boolean; + namespace isTomorrow {} + + function isTuesday(date: DateOrStringOrNumber): boolean; + namespace isTuesday {} + + function isValid(date: DateOrStringOrNumber): boolean; + namespace isValid {} + + function isWednesday(date: DateOrStringOrNumber): boolean; + namespace isWednesday {} + + function isWeekend(date: DateOrStringOrNumber): boolean; + namespace isWeekend {} + + function isWithinRange(date: DateOrStringOrNumber, startDate: DateOrStringOrNumber, endDate: DateOrStringOrNumber): boolean; + namespace isWithinRange {} + + function isYesterday(date: DateOrStringOrNumber): boolean; + namespace isYesterday {} + + function lastDayOfISOWeek(date: DateOrStringOrNumber): Date; + namespace lastDayOfISOWeek {} + + function lastDayOfISOYear(date: DateOrStringOrNumber): Date; + namespace lastDayOfISOYear {} + + function lastDayOfMonth(date: DateOrStringOrNumber): Date; + namespace lastDayOfMonth {} + + function lastDayOfQuarter(date: DateOrStringOrNumber): Date; + namespace lastDayOfQuarter {} + + function lastDayOfWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): Date; + namespace lastDayOfWeek {} + + function lastDayOfYear(date: DateOrStringOrNumber): Date; + namespace lastDayOfYear {} + + function max(...dates: DateOrStringOrNumber[]): Date; + namespace max {} + + function min(...dates: DateOrStringOrNumber[]): Date; + namespace min {} + + function parse(dateString: string): Date; + namespace parse {} + + function setDate(date: DateOrStringOrNumber, dayOfMonth: number): Date; + namespace setDate {} + + function setDay(date: DateOrStringOrNumber, day: number, options?: {weekStartsOn: number}): Date; + namespace setDay {} + + function setDayOfYear(date: DateOrStringOrNumber, dayOfYear: number): Date; + namespace setDayOfYear {} + + function setHours(date: DateOrStringOrNumber, hours: number): Date; + namespace setHours {} + + function setISOWeek(date: DateOrStringOrNumber, isoWeek: number): Date; + namespace setISOWeek {} + + function setISOYear(date: DateOrStringOrNumber, isoYear: number): Date; + namespace setISOYear {} + + function setMilliseconds(date: DateOrStringOrNumber, milliseconds: number): Date; + namespace setMilliseconds {} + + function setMinutes(date: DateOrStringOrNumber, minutes: number): Date; + namespace setMinutes {} + + function setMonth(date: DateOrStringOrNumber, month: number): Date; + namespace setMonth {} + + function setQuarter(date: DateOrStringOrNumber, quarter: number): Date; + namespace setQuarter {} + + function setSeconds(date: DateOrStringOrNumber, seconds: number): Date; + namespace setSeconds {} + + function setYear(date: DateOrStringOrNumber, year: number): Date; + namespace setYear {} + + function startOfDay(date: DateOrStringOrNumber): Date; + namespace startOfDay {} + + function startOfHour(date: DateOrStringOrNumber): Date; + namespace startOfHour {} + + function startOfISOWeek(date: DateOrStringOrNumber): Date; + namespace startOfISOWeek {} + + function startOfISOYear(date: DateOrStringOrNumber): Date; + namespace startOfISOYear {} + + function startOfMinute(date: DateOrStringOrNumber): Date; + namespace startOfMinute {} + + function startOfMonth(date: DateOrStringOrNumber): Date; + namespace startOfMonth {} + + function startOfQuarter(date: DateOrStringOrNumber): Date; + namespace startOfQuarter {} + + function startOfSecond(date: DateOrStringOrNumber): Date; + namespace startOfSecond {} + + function startOfToday(): Date; + namespace startOfToday {} + + function startOfTomorrow(): Date; + namespace startOfTomorrow {} + + function startOfWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): Date; + namespace startOfWeek {} + + function startOfYear(date: DateOrStringOrNumber): Date; + namespace startOfYear {} + + function startOfYesterday(): Date; + namespace startOfYesterday {} + + function subDays(date: DateOrStringOrNumber, amount: number): Date; + namespace subDays {} + + function subHours(date: DateOrStringOrNumber, amount: number): Date; + namespace subHours {} + + function subISOYears(date: DateOrStringOrNumber, amount: number): Date; + namespace subISOYears {} + + function subMilliseconds(date: DateOrStringOrNumber, amount: number): Date; + namespace subMilliseconds {} + + function subMinutes(date: DateOrStringOrNumber, amount: number): Date; + namespace subMinutes {} + + function subMonths(date: DateOrStringOrNumber, amount: number): Date; + namespace subMonths {} + + function subQuarters(date: DateOrStringOrNumber, amount: number): Date; + namespace subQuarters {} + + function subSeconds(date: DateOrStringOrNumber, amount: number): Date; + namespace subSeconds {} + + function subWeeks(date: DateOrStringOrNumber, amount: number): Date; + namespace subWeeks {} + + function subYears(date: DateOrStringOrNumber, amount: number): Date; + namespace subYears {} + +} + +declare module 'date-fns/add_days' { + import {addDays} from 'date-fns'; + export = addDays; +} + +declare module 'date-fns/add_hours' { + import {addHours} from 'date-fns'; + export = addHours; +} + +declare module 'date-fns/add_iso_years' { + import {addISOYears} from 'date-fns'; + export = addISOYears; +} + +declare module 'date-fns/add_milliseconds' { + import {addMilliseconds} from 'date-fns'; + export = addMilliseconds; +} + +declare module 'date-fns/add_minutes' { + import {addMinutes} from 'date-fns'; + export = addMinutes; +} + +declare module 'date-fns/add_months' { + import {addMonths} from 'date-fns'; + export = addMonths; +} + +declare module 'date-fns/add_quarters' { + import {addQuarters} from 'date-fns'; + export = addQuarters; +} + +declare module 'date-fns/add_seconds' { + import {addSeconds} from 'date-fns'; + export = addSeconds; +} + +declare module 'date-fns/add_weeks' { + import {addWeeks} from 'date-fns'; + export = addWeeks; +} + +declare module 'date-fns/add_years' { + import {addYears} from 'date-fns'; + export = addYears; +} + +declare module 'date-fns/closest_index_to' { + import {closestIndexTo} from 'date-fns'; + export = closestIndexTo; +} + +declare module 'date-fns/closest_to' { + import {closestTo} from 'date-fns'; + export = closestTo; +} + +declare module 'date-fns/compare_asc' { + import {compareAsc} from 'date-fns'; + export = compareAsc; +} + +declare module 'date-fns/compare_desc' { + import {compareDesc} from 'date-fns'; + export = compareDesc; +} + +declare module 'date-fns/difference_in_calendar_days' { + import {differenceInCalendarDays} from 'date-fns'; + export = differenceInCalendarDays; +} + +declare module 'date-fns/difference_in_calendar_iso_weeks' { + import {differenceInCalendarISOWeeks} from 'date-fns'; + export = differenceInCalendarISOWeeks; +} + +declare module 'date-fns/difference_in_calendar_iso_years' { + import {differenceInCalendarISOYears} from 'date-fns'; + export = differenceInCalendarISOYears; +} + +declare module 'date-fns/difference_in_calendar_months' { + import {differenceInCalendarMonths} from 'date-fns'; + export = differenceInCalendarMonths; +} + +declare module 'date-fns/difference_in_calendar_quarters' { + import {differenceInCalendarQuarters} from 'date-fns'; + export = differenceInCalendarQuarters; +} + +declare module 'date-fns/difference_in_calendar_weeks' { + import {differenceInCalendarWeeks} from 'date-fns'; + export = differenceInCalendarWeeks; +} + +declare module 'date-fns/difference_in_calendar_years' { + import {differenceInCalendarYears} from 'date-fns'; + export = differenceInCalendarYears; +} + +declare module 'date-fns/difference_in_days' { + import {differenceInDays} from 'date-fns'; + export = differenceInDays; +} + +declare module 'date-fns/difference_in_hours' { + import {differenceInHours} from 'date-fns'; + export = differenceInHours; +} + +declare module 'date-fns/difference_in_iso_years' { + import {differenceInISOYears} from 'date-fns'; + export = differenceInISOYears; +} + +declare module 'date-fns/difference_in_milliseconds' { + import {differenceInMilliseconds} from 'date-fns'; + export = differenceInMilliseconds; +} + +declare module 'date-fns/difference_in_minutes' { + import {differenceInMinutes} from 'date-fns'; + export = differenceInMinutes; +} + +declare module 'date-fns/difference_in_months' { + import {differenceInMonths} from 'date-fns'; + export = differenceInMonths; +} + +declare module 'date-fns/difference_in_quarters' { + import {differenceInQuarters} from 'date-fns'; + export = differenceInQuarters; +} + +declare module 'date-fns/difference_in_seconds' { + import {differenceInSeconds} from 'date-fns'; + export = differenceInSeconds; +} + +declare module 'date-fns/difference_in_weeks' { + import {differenceInWeeks} from 'date-fns'; + export = differenceInWeeks; +} + +declare module 'date-fns/difference_in_years' { + import {differenceInYears} from 'date-fns'; + export = differenceInYears; +} + +declare module 'date-fns/distance_in_words' { + import {distanceInWords} from 'date-fns'; + export = distanceInWords; +} + +declare module 'date-fns/distance_in_words_to_now' { + import {distanceInWordsToNow} from 'date-fns'; + export = distanceInWordsToNow; +} + +declare module 'date-fns/each_day' { + import {eachDay} from 'date-fns'; + export = eachDay; +} + +declare module 'date-fns/end_of_day' { + import {endOfDay} from 'date-fns'; + export = endOfDay; +} + +declare module 'date-fns/end_of_hour' { + import {endOfHour} from 'date-fns'; + export = endOfHour; +} + +declare module 'date-fns/end_of_iso_week' { + import {endOfISOWeek} from 'date-fns'; + export = endOfISOWeek; +} + +declare module 'date-fns/end_of_iso_year' { + import {endOfISOYear} from 'date-fns'; + export = endOfISOYear; +} + +declare module 'date-fns/end_of_minute' { + import {endOfMinute} from 'date-fns'; + export = endOfMinute; +} + +declare module 'date-fns/end_of_month' { + import {endOfMonth} from 'date-fns'; + export = endOfMonth; +} + +declare module 'date-fns/end_of_quarter' { + import {endOfQuarter} from 'date-fns'; + export = endOfQuarter; +} + +declare module 'date-fns/end_of_second' { + import {endOfSecond} from 'date-fns'; + export = endOfSecond; +} + +declare module 'date-fns/end_of_today' { + import {endOfToday} from 'date-fns'; + export = endOfToday; +} + +declare module 'date-fns/end_of_tomorrow' { + import {endOfTomorrow} from 'date-fns'; + export = endOfTomorrow; +} + +declare module 'date-fns/end_of_week' { + import {endOfWeek} from 'date-fns'; + export = endOfWeek; +} + +declare module 'date-fns/end_of_year' { + import {endOfYear} from 'date-fns'; + export = endOfYear; +} + +declare module 'date-fns/end_of_yesterday' { + import {endOfYesterday} from 'date-fns'; + export = endOfYesterday; +} + +declare module 'date-fns/format' { + import {format} from 'date-fns'; + export = format; +} + +declare module 'date-fns/get_date' { + import {getDate} from 'date-fns'; + export = getDate; +} + +declare module 'date-fns/get_day' { + import {getDay} from 'date-fns'; + export = getDay; +} + +declare module 'date-fns/get_day_of_year' { + import {getDayOfYear} from 'date-fns'; + export = getDayOfYear; +} + +declare module 'date-fns/get_days_in_month' { + import {getDaysInMonth} from 'date-fns'; + export = getDaysInMonth; +} + +declare module 'date-fns/get_days_in_year' { + import {getDaysInYear} from 'date-fns'; + export = getDaysInYear; +} + +declare module 'date-fns/get_hours' { + import {getHours} from 'date-fns'; + export = getHours; +} + +declare module 'date-fns/get_iso_week' { + import {getISOWeek} from 'date-fns'; + export = getISOWeek; +} + +declare module 'date-fns/get_iso_weeks_in_year' { + import {getISOWeeksInYear} from 'date-fns'; + export = getISOWeeksInYear; +} + +declare module 'date-fns/get_iso_year' { + import {getISOYear} from 'date-fns'; + export = getISOYear; +} + +declare module 'date-fns/get_milliseconds' { + import {getMilliseconds} from 'date-fns'; + export = getMilliseconds; +} + +declare module 'date-fns/get_minutes' { + import {getMinutes} from 'date-fns'; + export = getMinutes; +} + +declare module 'date-fns/get_month' { + import {getMonth} from 'date-fns'; + export = getMonth; +} + +declare module 'date-fns/get_quarter' { + import {getQuarter} from 'date-fns'; + export = getQuarter; +} + +declare module 'date-fns/get_seconds' { + import {getSeconds} from 'date-fns'; + export = getSeconds; +} + +declare module 'date-fns/get_year' { + import {getYear} from 'date-fns'; + export = getYear; +} + +declare module 'date-fns/is_after' { + import {isAfter} from 'date-fns'; + export = isAfter; +} + +declare module 'date-fns/is_before' { + import {isBefore} from 'date-fns'; + export = isBefore; +} + +declare module 'date-fns/is_date' { + import {isDate} from 'date-fns'; + export = isDate; +} + +declare module 'date-fns/is_equal' { + import {isEqual} from 'date-fns'; + export = isEqual; +} + +declare module 'date-fns/is_first_day_of_month' { + import {isFirstDayOfMonth} from 'date-fns'; + export = isFirstDayOfMonth; +} + +declare module 'date-fns/is_friday' { + import {isFriday} from 'date-fns'; + export = isFriday; +} + +declare module 'date-fns/is_future' { + import {isFuture} from 'date-fns'; + export = isFuture; +} + +declare module 'date-fns/is_last_day_of_month' { + import {isLastDayOfMonth} from 'date-fns'; + export = isLastDayOfMonth; +} + +declare module 'date-fns/is_leap_year' { + import {isLeapYear} from 'date-fns'; + export = isLeapYear; +} + +declare module 'date-fns/is_monday' { + import {isMonday} from 'date-fns'; + export = isMonday; +} + +declare module 'date-fns/is_past' { + import {isPast} from 'date-fns'; + export = isPast; +} + +declare module 'date-fns/is_same_day' { + import {isSameDay} from 'date-fns'; + export = isSameDay; +} + +declare module 'date-fns/is_same_hour' { + import {isSameHour} from 'date-fns'; + export = isSameHour; +} + +declare module 'date-fns/is_same_iso_week' { + import {isSameISOWeek} from 'date-fns'; + export = isSameISOWeek; +} + +declare module 'date-fns/is_same_iso_year' { + import {isSameISOYear} from 'date-fns'; + export = isSameISOYear; +} + +declare module 'date-fns/is_same_minute' { + import {isSameMinute} from 'date-fns'; + export = isSameMinute; +} + +declare module 'date-fns/is_same_month' { + import {isSameMonth} from 'date-fns'; + export = isSameMonth; +} + +declare module 'date-fns/is_same_quarter' { + import {isSameQuarter} from 'date-fns'; + export = isSameQuarter; +} + +declare module 'date-fns/is_same_second' { + import {isSameSecond} from 'date-fns'; + export = isSameSecond; +} + +declare module 'date-fns/is_same_week' { + import {isSameWeek} from 'date-fns'; + export = isSameWeek; +} + +declare module 'date-fns/is_same_year' { + import {isSameYear} from 'date-fns'; + export = isSameYear; +} + +declare module 'date-fns/is_saturday' { + import {isSaturday} from 'date-fns'; + export = isSaturday; +} + +declare module 'date-fns/is_sunday' { + import {isSunday} from 'date-fns'; + export = isSunday; +} + +declare module 'date-fns/is_this_hour' { + import {isThisHour} from 'date-fns'; + export = isThisHour; +} + +declare module 'date-fns/is_this_iso_week' { + import {isThisISOWeek} from 'date-fns'; + export = isThisISOWeek; +} + +declare module 'date-fns/is_this_iso_year' { + import {isThisISOYear} from 'date-fns'; + export = isThisISOYear; +} + +declare module 'date-fns/is_this_minute' { + import {isThisMinute} from 'date-fns'; + export = isThisMinute; +} + +declare module 'date-fns/is_this_month' { + import {isThisMonth} from 'date-fns'; + export = isThisMonth; +} + +declare module 'date-fns/is_this_quarter' { + import {isThisQuarter} from 'date-fns'; + export = isThisQuarter; +} + +declare module 'date-fns/is_this_second' { + import {isThisSecond} from 'date-fns'; + export = isThisSecond; +} + +declare module 'date-fns/is_this_week' { + import {isThisWeek} from 'date-fns'; + export = isThisWeek; +} + +declare module 'date-fns/is_this_year' { + import {isThisYear} from 'date-fns'; + export = isThisYear; +} + +declare module 'date-fns/is_thursday' { + import {isThursday} from 'date-fns'; + export = isThursday; +} + +declare module 'date-fns/is_today' { + import {isToday} from 'date-fns'; + export = isToday; +} + +declare module 'date-fns/is_tomorrow' { + import {isTomorrow} from 'date-fns'; + export = isTomorrow; +} + +declare module 'date-fns/is_tuesday' { + import {isTuesday} from 'date-fns'; + export = isTuesday; +} + +declare module 'date-fns/is_valid' { + import {isValid} from 'date-fns'; + export = isValid; +} + +declare module 'date-fns/is_wednesday' { + import {isWednesday} from 'date-fns'; + export = isWednesday; +} + +declare module 'date-fns/is_weekend' { + import {isWeekend} from 'date-fns'; + export = isWeekend; +} + +declare module 'date-fns/is_within_range' { + import {isWithinRange} from 'date-fns'; + export = isWithinRange; +} + +declare module 'date-fns/is_yesterday' { + import {isYesterday} from 'date-fns'; + export = isYesterday; +} + +declare module 'date-fns/last_day_of_iso_week' { + import {lastDayOfISOWeek} from 'date-fns'; + export = lastDayOfISOWeek; +} + +declare module 'date-fns/last_day_of_iso_year' { + import {lastDayOfISOYear} from 'date-fns'; + export = lastDayOfISOYear; +} + +declare module 'date-fns/last_day_of_month' { + import {lastDayOfMonth} from 'date-fns'; + export = lastDayOfMonth; +} + +declare module 'date-fns/last_day_of_quarter' { + import {lastDayOfQuarter} from 'date-fns'; + export = lastDayOfQuarter; +} + +declare module 'date-fns/last_day_of_week' { + import {lastDayOfWeek} from 'date-fns'; + export = lastDayOfWeek; +} + +declare module 'date-fns/last_day_of_year' { + import {lastDayOfYear} from 'date-fns'; + export = lastDayOfYear; +} + +declare module 'date-fns/max' { + import {max} from 'date-fns'; + export = max; +} + +declare module 'date-fns/min' { + import {min} from 'date-fns'; + export = min; +} + +declare module 'date-fns/parse' { + import {parse} from 'date-fns'; + export = parse; +} + +declare module 'date-fns/set_date' { + import {setDate} from 'date-fns'; + export = setDate; +} + +declare module 'date-fns/set_day' { + import {setDay} from 'date-fns'; + export = setDay; +} + +declare module 'date-fns/set_day_of_year' { + import {setDayOfYear} from 'date-fns'; + export = setDayOfYear; +} + +declare module 'date-fns/set_hours' { + import {setHours} from 'date-fns'; + export = setHours; +} + +declare module 'date-fns/set_iso_week' { + import {setISOWeek} from 'date-fns'; + export = setISOWeek; +} + +declare module 'date-fns/set_iso_year' { + import {setISOYear} from 'date-fns'; + export = setISOYear; +} + +declare module 'date-fns/set_milliseconds' { + import {setMilliseconds} from 'date-fns'; + export = setMilliseconds; +} + +declare module 'date-fns/set_minutes' { + import {setMinutes} from 'date-fns'; + export = setMinutes; +} + +declare module 'date-fns/set_month' { + import {setMonth} from 'date-fns'; + export = setMonth; +} + +declare module 'date-fns/set_quarter' { + import {setQuarter} from 'date-fns'; + export = setQuarter; +} + +declare module 'date-fns/set_seconds' { + import {setSeconds} from 'date-fns'; + export = setSeconds; +} + +declare module 'date-fns/set_year' { + import {setYear} from 'date-fns'; + export = setYear; +} + +declare module 'date-fns/start_of_day' { + import {startOfDay} from 'date-fns'; + export = startOfDay; +} + +declare module 'date-fns/start_of_hour' { + import {startOfHour} from 'date-fns'; + export = startOfHour; +} + +declare module 'date-fns/start_of_iso_week' { + import {startOfISOWeek} from 'date-fns'; + export = startOfISOWeek; +} + +declare module 'date-fns/start_of_iso_year' { + import {startOfISOYear} from 'date-fns'; + export = startOfISOYear; +} + +declare module 'date-fns/start_of_minute' { + import {startOfMinute} from 'date-fns'; + export = startOfMinute; +} + +declare module 'date-fns/start_of_month' { + import {startOfMonth} from 'date-fns'; + export = startOfMonth; +} + +declare module 'date-fns/start_of_quarter' { + import {startOfQuarter} from 'date-fns'; + export = startOfQuarter; +} + +declare module 'date-fns/start_of_second' { + import {startOfSecond} from 'date-fns'; + export = startOfSecond; +} + +declare module 'date-fns/start_of_today' { + import {startOfToday} from 'date-fns'; + export = startOfToday; +} + +declare module 'date-fns/start_of_tomorrow' { + import {startOfTomorrow} from 'date-fns'; + export = startOfTomorrow; +} + +declare module 'date-fns/start_of_week' { + import {startOfWeek} from 'date-fns'; + export = startOfWeek; +} + +declare module 'date-fns/start_of_year' { + import {startOfYear} from 'date-fns'; + export = startOfYear; +} + +declare module 'date-fns/start_of_yesterday' { + import {startOfYesterday} from 'date-fns'; + export = startOfYesterday; +} + +declare module 'date-fns/sub_days' { + import {subDays} from 'date-fns'; + export = subDays; +} + +declare module 'date-fns/sub_hours' { + import {subHours} from 'date-fns'; + export = subHours; +} + +declare module 'date-fns/sub_iso_years' { + import {subISOYears} from 'date-fns'; + export = subISOYears; +} + +declare module 'date-fns/sub_milliseconds' { + import {subMilliseconds} from 'date-fns'; + export = subMilliseconds; +} + +declare module 'date-fns/sub_minutes' { + import {subMinutes} from 'date-fns'; + export = subMinutes; +} + +declare module 'date-fns/sub_months' { + import {subMonths} from 'date-fns'; + export = subMonths; +} + +declare module 'date-fns/sub_quarters' { + import {subQuarters} from 'date-fns'; + export = subQuarters; +} + +declare module 'date-fns/sub_seconds' { + import {subSeconds} from 'date-fns'; + export = subSeconds; +} + +declare module 'date-fns/sub_weeks' { + import {subWeeks} from 'date-fns'; + export = subWeeks; +} + +declare module 'date-fns/sub_years' { + import {subYears} from 'date-fns'; + export = subYears; +} + diff --git a/daterangepicker/daterangepicker.d.ts b/daterangepicker/daterangepicker.d.ts index f3534a197e..a86614cfe8 100644 --- a/daterangepicker/daterangepicker.d.ts +++ b/daterangepicker/daterangepicker.d.ts @@ -11,7 +11,7 @@ interface JQuery { daterangepicker(settings?: daterangepicker.Settings, callback?: (start?: string | Date | moment.Moment, end?: string | Date | moment.Moment, label?: string) => any): JQuery; } -declare module daterangepicker { +declare namespace daterangepicker { interface DatepickerEventObject extends JQueryEventObject { date: Date; @@ -164,3 +164,7 @@ declare module daterangepicker { monthNames?: string[]; } } + +declare module "daterangepicker" { + export = daterangepicker; +} diff --git a/db-migrate-base/db-migrate-base-tests.ts b/db-migrate-base/db-migrate-base-tests.ts new file mode 100644 index 0000000000..55d471b98f --- /dev/null +++ b/db-migrate-base/db-migrate-base-tests.ts @@ -0,0 +1,322 @@ +// Test file for db-migrate-base Definition file +/// + +import * as DbMigrateBase from "db-migrate-base"; + +// Throw together a dummy driver +let db = {}; + +let callback = (err: any, response: any) => { + // Do nothing. +}; + +/// createTable(tableName, columnSpec, callback) +db.createTable('pets', { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' +}, callback); + +db.createTable('pets', { + columns: { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' + }, + ifNotExists: true +}, callback); + +db.createTable('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: 'id' + } + } +}, callback); + +db.createTable('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + product_id: 'id' + } + } + } +}, callback); + +/// dropTable(tableName, [options,] callback) +db.dropTable('pets', callback); + +db.dropTable('pets', { ifExists: true }, callback); + +/// renameTable(tableName, newTableName, callback) +db.renameTable('pets', 'pets_OLD', callback); + +/// addColumn(tableName, columnName, columnSpec, callback) +db.addColumn('pets', 'eyeColor', { + type: 'string', + length: 25, + notNull: true, +}, callback); + +db.addColumn('pets', 'id', { + type: 'int', + primaryKey: true, + autoIncrement: true, + notNull: true, + unique: true +}, callback); + +/// renameColumn(tableName, oldColumnName, newColumnName, callback) +db.renameColumn('pets', 'id', 'pet_id', callback); + +/// changeColumn(tableName, columnName, columnSpec, callback) +db.changeColumn('pets', 'eye_color', { + type: 'int', + unsigned: true, + notNull: true, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + eye_color: 'id' + } + } +}, callback); + +/// addIndex(tableName, indexName, columns, [unique,] callback) +db.addIndex('pets', 'pets_eye_color_idx', ['eye_color'], callback); +db.addIndex('pets', 'pets_registration_code_idx', ['registration_code'], true, callback); + +/// addForeignKey(tableName, referencedTableName, keyName, fieldMapping, rules, callback) +db.addForeignKey('module_user', 'modules', 'module_user_module_id_fk', +{ + 'module_id': 'id' +}, +{ + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' +}, callback); + +/// removeForeignKey(tableName, keyName, options, callback) +db.removeForeignKey('module_user', 'module_uer_module_id_foreign', callback); +db.removeForeignKey('module_user', 'module_user_module_id_foreign', { + dropIndex: true, +}, callback); + +/// insert(tableName, [columnNameArray,] valueArray, callback) +db.insert('module_user', ['first_name', 'last_name'], ['Test', 'Testerson'], callback); +db.insert('module_user', ['Test', 'Testerson'], callback); + +/// removeIndex([tableName,] indexName, callback) +db.removeIndex('pets', 'pets_eye_color_idx', callback); +db.removeIndex('pets_eye_color_idx', callback); + +/// runSql(sql, [params,] callback) +db.runSql('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [ + 'first_name', 'last_name', + 'Test', 'Testerson' +], callback); +db.runSql('DROP TABLE `pets`', callback); + +/// all(sql, [params,] callback) +db.all('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test'], callback); +db.all('SELECT * FROM `module_user`', callback); + +/// ========= +/// Async +/// ========= + +let onResolve = (result: any) => {}; + +/// createTableAsync(tableName, columnSpec) +db.createTableAsync('pets', { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' +}).then(onResolve); + +db.createTableAsync('pets', { + columns: { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' + }, + ifNotExists: true +}).then(onResolve); + +db.createTableAsync('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: 'id' + } + } +}).then(onResolve); + +db.createTableAsync('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + product_id: 'id' + } + } + } +}).then(onResolve); + +/// dropTableAsync(tableName, [options]) +db.dropTableAsync('pets').then(onResolve); +db.dropTableAsync('pets', { ifExists: true }).then(onResolve); + +/// renameTableAsync(tableName, newTableName) +db.renameTableAsync('pets', 'pets_OLD').then(onResolve); + +/// addColumnAsync(tableName, columnName, columnSpec) +db.addColumnAsync('pets', 'eyeColor', { + type: 'string', + length: 25, + notNull: true, +}).then(onResolve); + +db.addColumnAsync('pets', 'id', { + type: 'int', + primaryKey: true, + autoIncrement: true, + notNull: true, + unique: true +}).then(onResolve); + +/// renameColumnAsync(tableName, oldColumnName, newColumnName) +db.renameColumnAsync('pets', 'id', 'pet_id').then(onResolve); + +/// changeColumnAsync(tableName, columnName, columnSpec) +db.changeColumnAsync('pets', 'eye_color', { + type: 'int', + unsigned: true, + notNull: true, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + eye_color: 'id' + } + } +}).then(onResolve); + +/// addIndexAsync(tableName, indexName, columns, [unique]) +db.addIndexAsync('pets', 'pets_eye_color_idx', ['eye_color']).then(onResolve); +db.addIndexAsync('pets', 'pets_registration_code_idx', ['registration_code'], true).then(onResolve); + +/// addForeignKeyAsync(tableName, referencedTableName, keyName, fieldMapping, rules) +db.addForeignKeyAsync('module_user', 'modules', 'module_user_module_id_fk', +{ + 'module_id': 'id' +}, +{ + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' +}).then(onResolve); + +/// removeForeignKeyAsync(tableName, keyName, options) +db.removeForeignKeyAsync('module_user', 'module_uer_module_id_foreign').then(onResolve); +db.removeForeignKeyAsync('module_user', 'module_user_module_id_foreign', { + dropIndex: true, +}).then(onResolve); + +/// insertAsync(tableName, [columnNameArray,] valueArray) +db.insertAsync('module_user', ['first_name', 'last_name'], ['Test', 'Testerson']).then(onResolve); +db.insertAsync('module_user', ['Test', 'Testerson']).then(onResolve); + +/// removeIndexAsync([tableName,] indexName) +db.removeIndexAsync('pets', 'pets_eye_color_idx').then(onResolve); +db.removeIndexAsync('pets_eye_color_idx').then(onResolve); + +/// runSqlAsync(sql, [params]) +db.runSqlAsync('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [ + 'first_name', 'last_name', + 'Test', 'Testerson' +]).then(onResolve); +db.runSqlAsync('DROP TABLE `pets`').then(onResolve); + +/// allAsync(sql, [params]) +db.allAsync('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test']).then(onResolve); +db.allAsync('SELECT * FROM `module_user`').then(onResolve); \ No newline at end of file diff --git a/db-migrate-base/db-migrate-base.d.ts b/db-migrate-base/db-migrate-base.d.ts new file mode 100644 index 0000000000..d24388fdaf --- /dev/null +++ b/db-migrate-base/db-migrate-base.d.ts @@ -0,0 +1,152 @@ +// Type definitions for db-migrate-base +// Project: https://github.com/db-migrate/db-migrate-base +// Definitions by: nickiannone +// Definitions: https://github.com/nickiannone/DefinitelyTyped + +/// +/// + +declare module "db-migrate-base" { + + import * as Promise from "bluebird"; + + export interface CallbackFunction { (err: any, response: any): void; } + + export interface InternalModule { + log: any; + type: any; + } + + export interface InternalOptions { + mod: InternalModule; + } + + export interface ColumnSpec { + length?: number; + type: string; + unsigned?: boolean; + primaryKey?: boolean; + autoIncrement?: boolean; + notNull?: boolean; + unique?: boolean; + defaultValue?: any; + foreignKey?: ForeignKeySpec; + } + + export interface ForeignKeySpec { + name: string; + table: string; + rules?: ForeignKeyRules; + mapping: string | any; + } + + export interface ForeignKeyRules { + onDelete: string; + onUpdate: string; + } + + export interface RemoveForeignKeyOptions { + dropIndex?: boolean; + } + + export interface ColumnDef { + foreignKey?: any; // TODO Figure this out! + constraints: string; + } + + export interface CreateTableOptions { + columns?: Array; + ifNotExists?: boolean; + } + + export interface DropTableOptions { + ifExists?: boolean; + } + + export class Base { + constructor(intern: InternalOptions); + + close(callback?: CallbackFunction): void; + mapDataType(str: string): string; + truncate(tableName: string, callback: CallbackFunction): void; + checkDBMS(dbms: any, callback: CallbackFunction): void; + createDatabase(...options: any[]): void; + switchDatabase(...options: any[]): void; + dropDatabase(...options: any[]): void; + recurseCallbackArray(foreignKeys: Array, callback: CallbackFunction): void; + bindForeignKey(tableName: string, columnName: string, fkOptions: ForeignKeySpec): (callback: CallbackFunction) => void; + createColumnDef(name: string, spec: ColumnSpec, options?: any): ColumnDef; // TODO Figure out a type for `options`! + //createColumnConstraint(spec: ColumnSpec, options?: any, ...implementationDefinedOptions: any[]): string; + createMigrationsTable(callback: CallbackFunction): void; + createSeedsTable(callback: CallbackFunction): void; + createTable(tableName: string, options: any | CreateTableOptions, callback: CallbackFunction): void; + dropTable(tableName: string, optionsOrCb?: DropTableOptions | CallbackFunction, callback?: CallbackFunction): void; + renameTable(tableName: string, newTableName: string, callback: CallbackFunction): void; + addColumn(tableName: string, columnName: string, columnSpec: ColumnSpec, callback: CallbackFunction): void; + removeColumn(tableName: string, columnName: string, callback: CallbackFunction): void; + renameColumn(tableName: string, oldColumnName: string, newColumnName: string, callback: CallbackFunction): void; + changeColumn(tableName: string, columnName: string, columnSpec: ColumnSpec, callback: CallbackFunction): void; + quoteDDLArr(arr: Array): Array; + quoteArr(arr: Array): Array; + addIndex(tableName: string, indexName: string, columns: string | Array, uniqueOrCb?: boolean | CallbackFunction, callback?: CallbackFunction): void; + insert(tableName: string, columnNameOrValueArray: any, valueArrayOrCb?: any | CallbackFunction, callback?: CallbackFunction): void; + update(tableName: string, columnNameOrValueArray: any, valueArrayOrIds?: any, idsOrCb?: any | CallbackFunction, callback?: CallbackFunction): void; + lookup(tableName: string, column: string, id?: any, callback?: CallbackFunction): void; + removeIndex(tableNameOrIndexName: string, indexNameOrCb?: string | CallbackFunction, callback?: CallbackFunction): void; + addForeignKey(tableName: string, referencedTableName: string, keyName: string, fieldMapping: any, rules: ForeignKeyRules, callback: CallbackFunction): void; + removeForeignKey(tableName: string, keyName: string, optionsOrCb?: RemoveForeignKeyOptions | CallbackFunction, callback?: CallbackFunction): void; + normalizeColumnSpec(spec: string | ColumnSpec): ColumnSpec; + addMigrationRecord(name: string, callback: CallbackFunction): void; + addSeedRecord(name: string, callback: CallbackFunction): void; + startMigration(callback: CallbackFunction): void; + endMigration(callback: CallbackFunction): void; + runSql(sql?: string, paramsOrCb?: Array | CallbackFunction, callback?: CallbackFunction): void; + allLoadedMigrations(callback: CallbackFunction): void; + allLoadedSeeds(callback: CallbackFunction): void; + deleteMigration(migrationName: string, callback: CallbackFunction): void; + remove(table: string, ids: any, callback: CallbackFunction): void; // TODO Make ids match the type of ids in buildWhereClause(ids); + buildWhereClause(ids: any): string; + deleteSeed(seedName: string, callback: CallbackFunction): void; + all(sql: string, paramsOrCb?: Array | CallbackFunction, callback?: CallbackFunction): void; + escape(str: string): string; + escapeString(str: string): string; + escapeDDL(str: string): string; + + // Promisified methods + closeAsync(): Promise; + truncateAsync(tableName: string): Promise; + checkDBMSAsync(dbms: any): Promise; + createDatabaseAsync(...options: any[]): Promise; + switchDatabaseAsync(...options: any[]): Promise; + dropDatabaseAsync(...options: any[]): Promise; + recurseCallbackArrayAsync(foreignKeys: Array): Promise; + createMigrationsTableAsync(): Promise; + createSeedsTableAsync(): Promise; + createTableAsync(tableName: string, options: any | CreateTableOptions): Promise; + dropTableAsync(tableName: string, options?: DropTableOptions): Promise; + renameTableAsync(tableName: string, newTableName: string): Promise; + addColumnAsync(tableName: string, columnName: string, columnSpec: ColumnSpec): Promise; + removeColumnAsync(tableName: string, columnName: string): Promise; + renameColumnAsync(tableName: string, oldColumnName: string, newColumnName: string): Promise; + changeColumnAsync(tableName: string, columnName: string, columnSpec: ColumnSpec): Promise; + addIndexAsync(tableName: string, indexName: string, columns: string | Array, unique?: boolean): Promise; + insertAsync(tableName: string, columnNameOrValueArray: any, valueArrayOrCb?: any | CallbackFunction, callback?: CallbackFunction): Promise; + updateAsync(tableName: string, columnNameOrValueArray: any, valueArrayOrIds?: any, idsOrCb?: any | CallbackFunction, callback?: CallbackFunction): Promise; + lookupAsync(tableName: string, column: string, id?: any, callback?: CallbackFunction): Promise; + removeIndexAsync(tableNameOrIndexName: string, indexName?: string): Promise; + addForeignKeyAsync(tableName: string, referencedTableName: string, keyName: string, fieldMapping: any, rules: ForeignKeyRules): Promise; + removeForeignKeyAsync(tableName: string, keyName: string, options?: RemoveForeignKeyOptions): Promise; + addMigrationRecordAsync(name: string): Promise; + addSeedRecordAsync(name: string): Promise; + startMigrationAsync(): Promise; + endMigrationAsync(callback: CallbackFunction): Promise; + runSqlAsync(sql?: string, params?: Array): Promise; + allLoadedMigrationsAsync(): Promise; + allLoadedSeedsAsync(): Promise; + deleteMigrationAsync(migrationName: string): Promise; + removeAsync(table: string, ids: any): Promise; + deleteSeedAsync(seedName: string): Promise; + allAsync(sql: string, params?: Array): Promise; + } + +} \ No newline at end of file diff --git a/db-migrate-pg/db-migrate-pg-tests.ts b/db-migrate-pg/db-migrate-pg-tests.ts new file mode 100644 index 0000000000..3878c54607 --- /dev/null +++ b/db-migrate-pg/db-migrate-pg-tests.ts @@ -0,0 +1,411 @@ +// Test file for db-migrate-pg Definition file +/// + +import * as DbMigratePg from "db-migrate-pg"; + +// Throw together a dummy driver +let db = {}; + +let callback = (err: any, response: any) => { + // Do nothing. +}; + +/// createTable(tableName, columnSpec, callback) +db.createTable('pets', { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' +}, callback); + +db.createTable('pets', { + columns: { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' + }, + ifNotExists: true +}, callback); + +db.createTable('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: 'id' + } + } +}, callback); + +db.createTable('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + product_id: 'id' + } + } + } +}, callback); + +/// dropTable(tableName, [options,] callback) +db.dropTable('pets', callback); + +db.dropTable('pets', { ifExists: true }, callback); + +/// renameTable(tableName, newTableName, callback) +db.renameTable('pets', 'pets_OLD', callback); + +/// addColumn(tableName, columnName, columnSpec, callback) +db.addColumn('pets', 'eyeColor', { + type: 'string', + length: 25, + notNull: true, +}, callback); + +db.addColumn('pets', 'id', { + type: 'int', + primaryKey: true, + autoIncrement: true, + notNull: true, + unique: true +}, callback); + +/// renameColumn(tableName, oldColumnName, newColumnName, callback) +db.renameColumn('pets', 'id', 'pet_id', callback); + +/// changeColumn(tableName, columnName, columnSpec, callback) +db.changeColumn('pets', 'eye_color', { + type: 'int', + unsigned: true, + notNull: true, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + eye_color: 'id' + } + } +}, callback); + +/// addIndex(tableName, indexName, columns, [unique,] callback) +db.addIndex('pets', 'pets_eye_color_idx', ['eye_color'], callback); +db.addIndex('pets', 'pets_registration_code_idx', ['registration_code'], true, callback); + +/// addForeignKey(tableName, referencedTableName, keyName, fieldMapping, rules, callback) +db.addForeignKey('module_user', 'modules', 'module_user_module_id_fk', +{ + 'module_id': 'id' +}, +{ + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' +}, callback); + +/// removeForeignKey(tableName, keyName, options, callback) +db.removeForeignKey('module_user', 'module_uer_module_id_foreign', callback); +db.removeForeignKey('module_user', 'module_user_module_id_foreign', { + dropIndex: true, +}, callback); + +/// insert(tableName, [columnNameArray,] valueArray, callback) +db.insert('module_user', ['first_name', 'last_name'], ['Test', 'Testerson'], callback); +db.insert('module_user', ['Test', 'Testerson'], callback); + +/// removeIndex([tableName,] indexName, callback) +db.removeIndex('pets', 'pets_eye_color_idx', callback); +db.removeIndex('pets_eye_color_idx', callback); + +/// runSql(sql, [params,] callback) +db.runSql('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [ + 'first_name', 'last_name', + 'Test', 'Testerson' +], callback); +db.runSql('DROP TABLE `pets`', callback); + +/// all(sql, [params,] callback) +db.all('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test'], callback); +db.all('SELECT * FROM `module_user`', callback); + +/// ========= +/// Async +/// ========= + +let onResolve = (result: any) => {}; + +/// createTableAsync(tableName, columnSpec) +db.createTableAsync('pets', { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' +}).then(onResolve); + +db.createTableAsync('pets', { + columns: { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' + }, + ifNotExists: true +}).then(onResolve); + +db.createTableAsync('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: 'id' + } + } +}).then(onResolve); + +db.createTableAsync('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + product_id: 'id' + } + } + } +}).then(onResolve); + +/// dropTableAsync(tableName, [options]) +db.dropTableAsync('pets').then(onResolve); +db.dropTableAsync('pets', { ifExists: true }).then(onResolve); + +/// renameTableAsync(tableName, newTableName) +db.renameTableAsync('pets', 'pets_OLD').then(onResolve); + +/// addColumnAsync(tableName, columnName, columnSpec) +db.addColumnAsync('pets', 'eyeColor', { + type: 'string', + length: 25, + notNull: true, +}).then(onResolve); + +db.addColumnAsync('pets', 'id', { + type: 'int', + primaryKey: true, + autoIncrement: true, + notNull: true, + unique: true +}).then(onResolve); + +/// renameColumnAsync(tableName, oldColumnName, newColumnName) +db.renameColumnAsync('pets', 'id', 'pet_id').then(onResolve); + +/// changeColumnAsync(tableName, columnName, columnSpec) +db.changeColumnAsync('pets', 'eye_color', { + type: 'int', + unsigned: true, + notNull: true, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + eye_color: 'id' + } + } +}).then(onResolve); + +/// addIndexAsync(tableName, indexName, columns, [unique]) +db.addIndexAsync('pets', 'pets_eye_color_idx', ['eye_color']).then(onResolve); +db.addIndexAsync('pets', 'pets_registration_code_idx', ['registration_code'], true).then(onResolve); + +/// addForeignKeyAsync(tableName, referencedTableName, keyName, fieldMapping, rules) +db.addForeignKeyAsync('module_user', 'modules', 'module_user_module_id_fk', +{ + 'module_id': 'id' +}, +{ + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' +}).then(onResolve); + +/// removeForeignKeyAsync(tableName, keyName, options) +db.removeForeignKeyAsync('module_user', 'module_uer_module_id_foreign').then(onResolve); +db.removeForeignKeyAsync('module_user', 'module_user_module_id_foreign', { + dropIndex: true, +}).then(onResolve); + +/// insertAsync(tableName, [columnNameArray,] valueArray) +db.insertAsync('module_user', ['first_name', 'last_name'], ['Test', 'Testerson']).then(onResolve); +db.insertAsync('module_user', ['Test', 'Testerson']).then(onResolve); + +/// removeIndexAsync([tableName,] indexName) +db.removeIndexAsync('pets', 'pets_eye_color_idx').then(onResolve); +db.removeIndexAsync('pets_eye_color_idx').then(onResolve); + +/// runSqlAsync(sql, [params]) +db.runSqlAsync('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [ + 'first_name', 'last_name', + 'Test', 'Testerson' +]).then(onResolve); +db.runSqlAsync('DROP TABLE `pets`').then(onResolve); + +/// allAsync(sql, [params]) +db.allAsync('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test']).then(onResolve); +db.allAsync('SELECT * FROM `module_user`').then(onResolve); + +/// ==================== +/// PG-specific tests +/// ==================== + +/// createColumnConstraint(spec, options, tableName, columnName) (INTERNAL USE ONLY) +let constraint: DbMigratePg.ColumnConstraint; + +constraint = db.createColumnConstraint({ + type: 'int', + length: 10, + unsigned: true, + primaryKey: false, + autoIncrement: false, + notNull: true, + unique: false, + defaultValue: 0, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + 'eye_color': 'id' + } + } +}, { + emitPrimaryKey: false +}, 'pets', 'eye_color'); + +// Print the SQL constraints +console.log(constraint.constraints); + +// Invoke the foreign key builder +constraint.foreignKey(callback); + +/// Public Callback Methods: + +/// createDatabase(dbName, [options,] callback) +db.createDatabase('petstore', callback); +db.createDatabase('petstore', {}, callback); + +/// dropDatabase(dbName, [options,] callback) +db.dropDatabase('petstore', callback); +db.dropDatabase('petstore', { ifExists: true }, callback); + +/// createSequence(sqName, [options,] callback) +db.createSequence('pets_id_sq', callback); +db.createSequence('pets_id_sq', { temp: true }, callback); + +/// switchDatabase(options, callback) +db.switchDatabase('petstore', callback); +db.switchDatabase({ database: 'petstore' }, callback); + +/// dropSequence(sqName, [options,] callback) +db.dropSequence('pets_id_sq', callback); +db.dropSequence('pets_id_sq', { + ifExists: true, + cascade: true, + restrict: true, +}, callback); + +/// Public Promisified Methods: + +/// createDatabaseAsync(dbName, [options]) +db.createDatabaseAsync('petstore').then(onResolve); +db.createDatabaseAsync('petstore', {}).then(onResolve); + +/// dropDatabaseAsync(dbName, [options]) +db.dropDatabaseAsync('petstore').then(onResolve); +db.dropDatabaseAsync('petstore', { ifExists: true }).then(onResolve); + +/// createSequenceAsync(sqName, [options]) +db.createSequenceAsync('pets_id_sq').then(onResolve); +db.createSequenceAsync('pets_id_sq', { temp: true }).then(onResolve); + +/// switchDatabaseAsync(options) +db.switchDatabaseAsync('petstore').then(onResolve); +db.switchDatabaseAsync({ database: 'petstore' }).then(onResolve); + +/// dropSequenceAsync(sqName, [options]) +db.dropSequenceAsync('pets_id_sq').then(onResolve); +db.dropSequenceAsync('pets_id_sq', { + ifExists: true, + cascade: true, + restrict: true, +}).then(onResolve); diff --git a/db-migrate-pg/db-migrate-pg.d.ts b/db-migrate-pg/db-migrate-pg.d.ts new file mode 100644 index 0000000000..533b8ff91d --- /dev/null +++ b/db-migrate-pg/db-migrate-pg.d.ts @@ -0,0 +1,60 @@ +// Type definitions for db-migrate-pg +// Project: https://github.com/db-migrate/pg +// Definitions by: nickiannone +// Definitions: https://github.com/nickiannone/DefinitelyTyped + +/// +/// + +declare module "db-migrate-pg" { + + import * as pg from "pg"; + import * as DbMigrateBase from "db-migrate-base"; + import * as Promise from "bluebird"; + + // Yes, this is a dummy interface for now; the current implementation of the pg driver doesn't need any options. + export interface CreateDatabaseOptions {} + + export interface DropDatabaseOptions { + ifExists?: boolean; + } + + export interface CreateSequenceOptions { + temp?: boolean; + } + + export interface SwitchDatabaseOptions { + database?: string; + } + + export interface DropSequenceOptions { + ifExists?: boolean; + cascade?: boolean; + restrict?: boolean; + } + + export interface ColumnConstraint { + foreignKey: (callback: DbMigrateBase.CallbackFunction) => void; + constraints: string; + } + + export interface ColumnConstraintOptions { + emitPrimaryKey?: boolean; + } + + export class PgDriver extends DbMigrateBase.Base { + constructor(connection: pg.Client, schema: string, intern: DbMigrateBase.InternalOptions); + createDatabase(dbName: string, optionsOrCb: CreateDatabaseOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void; + dropDatabase(dbName: string, optionsOrCb: DropDatabaseOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void; + createSequence(sqName: string, optionsOrCb: CreateSequenceOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void; + switchDatabase(options: string | SwitchDatabaseOptions, callback: DbMigrateBase.CallbackFunction): void; + dropSequence(dbName: string, optionsOrCb: DropSequenceOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void; + createColumnConstraint(spec: DbMigrateBase.ColumnSpec, options: ColumnConstraintOptions, tableName: string, columnName: string): ColumnConstraint; + + createDatabaseAsync(dbName: string, options?: CreateDatabaseOptions): Promise; + dropDatabaseAsync(dbName: string, options?: DropDatabaseOptions): Promise; + createSequenceAsync(sqName: string, options?: CreateSequenceOptions): Promise; + switchDatabaseAsync(options: string | SwitchDatabaseOptions): Promise; + dropSequenceAsync(dbName: string, options?: DropSequenceOptions): Promise; + } +} \ No newline at end of file diff --git a/devexpress-web/devexpress-web.d.ts b/devexpress-web/devexpress-web.d.ts index 6671a45ec4..c2e0014f85 100644 --- a/devexpress-web/devexpress-web.d.ts +++ b/devexpress-web/devexpress-web.d.ts @@ -250,6 +250,9 @@ interface ASPxClientDashboardItemWidgetCreatedEventHandler { */ (source: S, e: ASPxClientDashboardItemWidgetEventArgs): void; } +/** + * References a method that will handle the ItemWidgetUpdating event. + */ interface ASPxClientDashboardItemWidgetUpdatingEventHandler { /** * References a method that will handle the ItemWidgetUpdating event. @@ -258,6 +261,9 @@ interface ASPxClientDashboardItemWidgetUpdatingEventHandler { */ (source: S, e: ASPxClientDashboardItemWidgetEventArgs): void; } +/** + * References a method that will handle the ItemWidgetUpdated event. + */ interface ASPxClientDashboardItemWidgetUpdatedEventHandler { /** * References a method that will handle the ItemWidgetUpdated event. @@ -616,6 +622,11 @@ interface ASPxClientDashboardDesigner extends ASPxClientControl { * Occurs after a dashboard displayed in the ASPxClientDashboardDesigner is changed. */ DashboardChanged: ASPxClientEvent>; + /** + * For internal use. + */ + CustomizeMenuItems: ASPxClientEvent>; + BeforeRender: ASPxClientEvent>; /** * Switches the ASPxClientDashboardDesigner to the viewer mode. */ @@ -650,6 +661,9 @@ interface ASPxClientDashboardDesigner extends ASPxClientControl { */ SaveDashboard(): void; } +/** + * References a method that will handle the DashboardStateChanged event. + */ interface ASPxClientDashboardStateChangedEventHandler { /** * References a method that will handle the DashboardStateChanged event. @@ -668,6 +682,9 @@ interface ASPxClientDashboardStateChangedEventArgs extends ASPxClientEventArgs { */ DashboardState: string; } +/** + * References a method that will handle the DashboardChanged event. + */ interface ASPxClientDashboardChangedEventHandler { /** * References a method that will handle the DashboardChanged event. @@ -691,6 +708,26 @@ interface ASPxClientDashboardChangedEventArgs extends ASPxClientEventArgs { */ DashboardName: string; } +interface ASPxClientDashboardDesignerCustomizeMenuItemsEventHandler { + (source: S, e: ASPxClientDashboardDesignerCustomizeMenuItemsEventArgs): void; +} +interface ASPxClientDashboardDesignerMenuItem { + id: string; + title: string; + template: string; + selected: boolean; + disabled: boolean; + hasSeparator: boolean; + click: Function; + hotKey: number; +} +interface ASPxClientDashboardDesignerCustomizeMenuItemsEventArgs extends ASPxClientEventArgs { + Items: ASPxClientDashboardDesignerMenuItem[]; + FindById(itemId: string): ASPxClientDashboardDesignerMenuItem; +} +interface ASPxClientDashboardDesignerBeforeRenderEventHandler { + (source: S, e: ASPxClientEventArgs): void; +} /** * A client-side equivalent of the ASPxDashboardViewer control. */ @@ -1332,6 +1369,9 @@ interface ASPxClientDashboardActionAvailabilityChangedEventArgs extends ASPxClie */ ItemActions: ASPxClientDashboardItemAction[]; } +/** + * References a method that will handle the DataLoadingError event. + */ interface ASPxClientDashboardDataLoadingErrorEventHandler { /** * References a method that will handle the DataLoadingError event. @@ -1630,11 +1670,11 @@ interface ASPxClientBinaryImage extends ASPxClientEdit { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param parameter A string value that contains any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * Represents the client-side equivalent of the ASPxButton control. @@ -2482,8 +2522,8 @@ interface ASPxClientListEdit extends ASPxClientEdit { */ interface ASPxClientListEditItem { /** - * Gets a value that indicates whether a list box item is selected. - * Value: true if a list box item is selected; otherwise, false. + * Gets a value that indicates whether a list edit item is selected. + * Value: true if a list edit item is selected; otherwise, false. */ selected: boolean; /** @@ -3367,11 +3407,11 @@ interface ASPxClientGaugeControl extends ASPxClientControl { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * Represents the client ASPxGridView. @@ -6159,7 +6199,7 @@ interface ASPxClientVerticalGrid extends ASPxClientGridBase { */ RowSorting: ASPxClientEvent>; /** - * Fires on the client side before the expansion state of a row is changed via end-user interaction. + * Fires on the client side before the expansion state of a row is changed by end-user interaction. */ RowExpandedChanging: ASPxClientEvent>; /** @@ -7406,6 +7446,27 @@ interface ASPxClientHtmlEditorInsertYouTubeVideoCommandArguments extends ASPxCli */ interface ASPxClientHtmlEditorChangeYouTubeVideoCommandArguments extends ASPxClientHtmlEditorInsertYouTubeVideoCommandArguments { } +/** + * A method that will handle the DialogInitialized client event. + */ +interface ASPxClientHtmlEditorDialogInitializedEventHandler { + /** + * A method that will handle the client DialogInitialized event. + * @param source An object representing the event's source. + * @param e An ASPxClientHtmlEditorDialogInitializedEventArgs object that contains event data. + */ + (source: S, e: ASPxClientHtmlEditorDialogInitializedEventArgs): void; +} +/** + * Provides data for the DialogInitialized client event. + */ +interface ASPxClientHtmlEditorDialogInitializedEventArgs extends ASPxClientEventArgs { + /** + * Gets the name of the dialog that has been initialized. + * Value: A string value that is the name of the initialized dialog. + */ + dialogName: string; +} /** * A method that will handle the CommandExecuting event. */ @@ -7634,6 +7695,10 @@ interface ASPxClientHtmlEditorBeforePasteEventArgs extends ASPxClientEventArgs { * Represents a client-side equivalent of the ASPxHtmlEditor control. */ interface ASPxClientHtmlEditor extends ASPxClientControl { + /** + * Occurs on the client side after a dialog has been initialized. + */ + DialogInitialized: ASPxClientEvent>; /** * Occurs before a default or custom command has been executed and allows you to cancel the action. */ @@ -7797,7 +7862,7 @@ interface ASPxClientHtmlEditor extends ASPxClientControl { */ SetToolbarDropDownItemPickerValue(commandName: string, value: string): void; /** - * Specifies the visibility of a ribbon context tab ?ategory specified by its name. + * Specifies the visibility of a ribbon context tab category specified by its name. * @param categoryName A Name property value of the required category. * @param active true to make a category visible; false to make it hidden. */ @@ -7958,11 +8023,11 @@ interface ASPxClientPivotGrid extends ASPxClientControl { */ PerformCallback(args: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param args A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param args + * @param onSuccess */ - PerformCallback(args: string, onSuccess: Function): void; + PerformCallback(args: string, onSuccess: (arg1: string) => void): void; } /** * A method that will handle the CellDblClick event. @@ -8239,11 +8304,11 @@ interface ASPxClientRichEdit extends ASPxClientControl { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; /** * Indicates whether any unsaved changes are contained in the current document. */ @@ -9122,11 +9187,7 @@ interface RichEditCommands { * Value: A object that provides methods for executing the command and checking its state. */ toggleTableCellBottomBorder: ToggleTableCellBottomBorderCommand; - /** - * Gets a command to toggle left borders for selected cells on/off. - * Value: A object that provides methods for executing the command and checking its state. - */ - toggleTableCellsLeftBorder: ToggleTableCellsLeftBorderCommand; + toggleTableCellLeftBorder: ToggleTableCellLeftBorderCommand; /** * Gets a command to remove the borders of the selected table cells. * Value: A object that provides methods for executing the command and checking its state. @@ -9202,6 +9263,7 @@ interface RichEditCommands { * Value: A object that provides methods for executing the command and checking its state. */ replaceNext: ReplaceNextCommand; + openSpellingDialog: OpenSpellingDialogCommand; } /** * Serves as a base for objects that implement different client command functionalities. @@ -10814,10 +10876,10 @@ interface OpenPageMarginsDialogCommand extends CommandWithSimpleStateBase { */ interface ChangePageOrientationCommand extends CommandBase { /** - * Executes the ChangePageOrientationCommand command by applying the specified setting. May result in taking no action if the command's state does not allow command execution. Use the object's getState method to check the command state. - * @param isPortrait true to apply portrait page orientation, false to apply landscape page orientation. + * + * @param isPortrait */ - execute(isPortrait: boolean): boolean; + execute(isPortrait: any): boolean; /** * Gets information about the command state. */ @@ -11428,6 +11490,9 @@ declare enum ParagraphFirstLineIndent { Indented=1, Hanging=2 } +interface OpenSpellingDialogCommand extends CommandWithSimpleStateBase { + execute(): boolean; +} /** * A command to invoke the Insert Table dialog. */ @@ -11519,7 +11584,7 @@ interface ChangeTableColumnPreferredWidthCommand extends CommandBase { interface ChangeTableCellFormattingCommand extends CommandBase { /** * Executes the ChangeTableCellFormattingCommand command by applying the specified setting. May result in taking no action if the command's state does not allow command execution. Use the object's getState method to check the command state. - * @param settings A TableFormattingSettings object specifying ?ell formatting of the selected table elements. + * @param settings A TableFormattingSettings object specifying cell formatting of the selected table elements. */ execute(settings: TableCellFormattingSettings): boolean; /** @@ -11656,7 +11721,7 @@ interface SplitTableCellsDialogCommand extends CommandWithSimpleStateBase { /** * A command to split the selected table cells based on the specified options. */ -interface SplitTableCellsCommand extends CommandBase { +interface SplitTableCellsCommand extends CommandWithSimpleStateBase { /** * Executes the SplitTableCellsCommand command by applying the specified settings. May result in taking no action if the command's state does not allow command execution. Use the object's getState method to check the command state. * @param rowCount An integer value specifying number of rows in the splitted table cells. @@ -11664,10 +11729,6 @@ interface SplitTableCellsCommand extends CommandBase { * @param mergeBeforeSplit true to merge the selected cells before splitting; otherwise, false. */ execute(rowCount: number, columnCount: number, mergeBeforeSplit: boolean): boolean; - /** - * Gets information about the command state. - */ - getState(): SimpleCommandState; } /** * A command to insert table cells with a vertical shift into the selected table. @@ -11829,13 +11890,7 @@ interface ToggleTableCellBottomBorderCommand extends CommandWithBooleanStateBase */ execute(): boolean; } -/** - * A command to toggle left borders for selected cells on/off. - */ -interface ToggleTableCellsLeftBorderCommand extends CommandWithBooleanStateBase { - /** - * Executes the ToggleTableCellsLeftBorderCommand command by imitating the corresponding end-user action made in the RichEdit's UI. May result in taking no action if the command's state does not allow command execution. Use the object's getState method to check the command state. - */ +interface ToggleTableCellLeftBorderCommand extends CommandWithBooleanStateBase { execute(): boolean; } /** @@ -12202,10 +12257,6 @@ interface TableHeightUnit { * Value: An integer value specifying the table height. */ value: number; - /** - * Gets or sets the unit type for the table height. - * Value: One of the values. - */ type: any; } declare enum TableHeightUnitType { @@ -12816,18 +12867,42 @@ interface ASPxClientAppointment { * A client point object. */ interface ASPxClientPoint { + /** + * Gets the point's X-coordinate. + */ GetX(): number; + /** + * Gets the point's Y-coordinate. + */ GetY(): number; } /** * A client rectangle object. */ interface ASPxClientRect { + /** + * Gets the X-coordinate of the rectangle's left edge. + */ GetLeft(): number; + /** + * Gets the X-coordinate of the rectangle's right edge. + */ GetRight(): number; + /** + * Gets the Y-coordinate of the rectangle's top edge. + */ GetTop(): number; + /** + * Gets the Y-coordinate of the rectangle's bottom edge. + */ GetBottom(): number; + /** + * Gets the rectangle's width. + */ GetWidth(): number; + /** + * Gets the rectangle's height. + */ GetHeight(): number; } /** @@ -13078,10 +13153,13 @@ interface ASPxClientWeekOfMonth { * Represents a client-side equivalent of the WeekDaysCheckEdit control. */ interface ASPxClientWeekDaysCheckEdit extends ASPxClientControl { + /** + * Gets the selection state of the week day check boxes. + */ GetValue(): ASPxClientWeekDays; /** - * - * @param value + * Gets the selection state of the week day check boxes. + * @param value An ASPxClientWeekDays object specifying the selection state of the week day check boxes. */ SetValue(value: ASPxClientWeekDays): void; } @@ -13089,22 +13167,31 @@ interface ASPxClientWeekDaysCheckEdit extends ASPxClientControl { * Represents a client-side equivalent of the RecurrenceRangeControl. */ interface ASPxClientRecurrenceRangeControl extends ASPxClientControl { + /** + * Gets the type of the recurrence range. + */ GetRange(): ASPxClientRecurrenceRange; + /** + * Gets how many times the appointment occurs. + */ GetOccurrenceCount(): number; + /** + * Gets the recurrence end date. + */ GetEndDate(): Date; /** - * - * @param range + * Sets the type of the recurrence range. + * @param range An ASPxClientRecurrenceRangeenumeration value that specifies the recurrence range type. */ SetRange(range: ASPxClientRecurrenceRange): void; /** - * - * @param occurrenceCount + * Sets how many times the appointment occurs. + * @param occurrenceCount An integer value that specifies how many times the appointment occurs. */ SetOccurrenceCount(occurrenceCount: number): void; /** - * - * @param date + * Sets the recurrence end date. + * @param date A JavaScript Date object that specifies the end date for the recurrence. */ SetEndDate(date: Date): void; } @@ -13112,10 +13199,13 @@ interface ASPxClientRecurrenceRangeControl extends ASPxClientControl { * A base for client equivalents of recurrence controls available in the XtraScheduler library. */ interface ASPxClientRecurrenceControlBase extends ASPxClientControl { + /** + * Returns an object providing access to the ASPxClientRecurrenceControlBase control's editor values. + */ CreateValueAccessor(): DefaultRecurrenceRuleValuesAccessor; /** - * - * @param recurrenceInfo + * Updates values of editors displayed by the ASPxClientRecurrenceControlBase control. + * @param recurrenceInfo An ASPxClientRecurrenceInfo object containing new editor values. */ Update(recurrenceInfo: ASPxClientRecurrenceInfo): void; } @@ -13123,10 +13213,13 @@ interface ASPxClientRecurrenceControlBase extends ASPxClientControl { * Represents a client-side equivalent of the DailyRecurrenceControl - a control for specifying the daily recurrence. */ interface ASPxClientDailyRecurrenceControl extends ASPxClientRecurrenceControlBase { + /** + * Returns an object providing access to the ASPxClientDailyRecurrenceControl's editor values. + */ CreateValueAccessor(): DefaultRecurrenceRuleValuesAccessor; /** - * - * @param recurrenceInfo + * Updates values of editors displayed by the ASPxClientDailyRecurrenceControl. + * @param recurrenceInfo An ASPxClientRecurrenceInfo object containing new editor values. */ Update(recurrenceInfo: ASPxClientRecurrenceInfo): void; } @@ -13134,10 +13227,13 @@ interface ASPxClientDailyRecurrenceControl extends ASPxClientRecurrenceControlBa * Represents a client-side equivalent of the WeeklyRecurrenceControl. */ interface ASPxClientWeeklyRecurrenceControl extends ASPxClientRecurrenceControlBase { + /** + * Returns an object providing access to the ASPxClientWeeklyRecurrenceControl's editor values. + */ CreateValueAccessor(): DefaultRecurrenceRuleValuesAccessor; /** - * - * @param recurrenceInfo + * Updates values of editors displayed by the ASPxClientWeeklyRecurrenceControl. + * @param recurrenceInfo An ASPxClientRecurrenceInfo object containing new editor values. */ Update(recurrenceInfo: ASPxClientRecurrenceInfo): void; } @@ -13145,10 +13241,13 @@ interface ASPxClientWeeklyRecurrenceControl extends ASPxClientRecurrenceControlB * Represents a client-side equivalent of the MonthlyRecurrenceControl. */ interface ASPxClientMonthlyRecurrenceControl extends ASPxClientRecurrenceControlBase { + /** + * Returns an object providing access to the ASPxClientMonthlyRecurrenceControl's editor values. + */ CreateValueAccessor(): DefaultRecurrenceRuleValuesAccessor; /** - * - * @param recurrenceInfo + * Updates values of editors displayed by the ASPxClientMonthlyRecurrenceControll. + * @param recurrenceInfo An ASPxClientRecurrenceInfo object containing new editor values. */ Update(recurrenceInfo: ASPxClientRecurrenceInfo): void; } @@ -13156,55 +13255,139 @@ interface ASPxClientMonthlyRecurrenceControl extends ASPxClientRecurrenceControl * Represents a client-side equivalent of the YearlyRecurrenceControl. */ interface ASPxClientYearlyRecurrenceControl extends ASPxClientRecurrenceControlBase { + /** + * Returns an object providing access to the ASPxClientYearlyRecurrenceControl's editor values. + */ CreateValueAccessor(): DefaultRecurrenceRuleValuesAccessor; /** - * - * @param recurrenceInfo + * Updates values of editors displayed by the ASPxClientYearlyRecurrenceControl. + * @param recurrenceInfo An ASPxClientRecurrenceInfo object containing new editor values. */ Update(recurrenceInfo: ASPxClientRecurrenceInfo): void; } +/** + * An object providing access to an ASPxClientRecurrenceControlBase control's editor values. + */ interface DefaultRecurrenceRuleValuesAccessor { + /** + * Get the frequency with which the appointment occurs with respect to the appointment's recurrence type. + */ GetPeriodicity(): number; + /** + * Gets the number of the month's day in which the appointment is scheduled. + */ GetDayNumber(): number; + /** + * Gets or sets the month's number. + */ GetMonth(): number; + /** + * Gets the days of the week to which a weekly recurrent appointment is scheduled. + */ GetWeekDays(): ASPxClientWeekDays; + /** + * Gets the number of the week in a month when an appointment is scheduled. + */ GetWeekOfMonth(): ASPxClientWeekOfMonth; } +/** + * An object providing access to an ASPxClientDailyRecurrenceControl's editor values. + */ interface DailyRecurrenceValuesAccessor extends DefaultRecurrenceRuleValuesAccessor { + /** + * Gets the number of days between appointment occurrences. + */ GetPeriodicity(): number; + /** + * Gets the days of the week to which a daily recurrent appointment is scheduled. + */ GetWeekDays(): ASPxClientWeekDays; } +/** + * An object providing access to an ASPxClientWeeklyRecurrenceControl's editor values. + */ interface WeeklyRecurrenceValuesAccessor extends DefaultRecurrenceRuleValuesAccessor { + /** + * Gets the number of weeks between appointment occurrences. + */ GetPeriodicity(): number; + /** + * Gets the days of the week to which a weekly recurrent appointment is scheduled. + */ GetWeekDays(): ASPxClientWeekDays; } +/** + * An object providing access to an ASPxClientMonthlyRecurrenceControl's editor values. + */ interface MonthlyRecurrenceValuesAccessor extends DefaultRecurrenceRuleValuesAccessor { + /** + * Gets the number of the month's day in which the appointment is scheduled. + */ GetDayNumber(): number; + /** + * Gets the number of months between appointment occurrences. + */ GetPeriodicity(): number; + /** + * Gets the days of the week to which a monthly recurrent appointment is scheduled. + */ GetWeekDays(): ASPxClientWeekDays; + /** + * Gets the number of the week in a month when an appointment is scheduled. + */ GetWeekOfMonth(): ASPxClientWeekOfMonth; } +/** + * An object providing access to an ASPxClientYearlyRecurrenceControl's editor values. + */ interface YearlyRecurrenceValuesAccessor extends DefaultRecurrenceRuleValuesAccessor { + /** + * Gets the number of the month's day in which the appointment is scheduled. + */ GetDayNumber(): number; + /** + * Gets or sets the month's number. + */ GetMonth(): number; + /** + * Gets the days of the week to which a yearly recurrent appointment is scheduled. + */ GetWeekDays(): ASPxClientWeekDays; + /** + * Gets or sets the number of a week in a month when an appointment is scheduled. + */ GetWeekOfMonth(): ASPxClientWeekOfMonth; } +/** + * Provides base functionality for ASPxClientScheduler's forms. + */ interface ASPxClientFormBase { + /** + * Occurs when the form has been closed. + */ FormClosed: ASPxClientEvent>; + /** + * Closes the form. + */ Close(): void; /** - * - * @param element - * @param isVisible + * Sets the visibility state of the specified form element. + * @param element An object specifying the element whose visibility state should be changed. + * @param isVisible true to display the element; false to hide the element. */ SetVisibleCore(element: Object, isVisible: boolean): void; } +/** + * Represents a client-side equivalent of the RecurrenceTypeEdit. + */ interface ASPxClientRecurrenceTypeEdit extends ASPxClientRadioButtonList { + /** + * Gets the selected recurrence type. + */ GetRecurrenceType(): ASPxClientRecurrenceType; /** - * - * @param recurrenceType + * Sets the selected recurrence type. + * @param recurrenceType An ASPxClientRecurrenceType enumeration value. */ SetRecurrenceType(recurrenceType: ASPxClientRecurrenceType): void; } @@ -13227,10 +13410,13 @@ interface AppointmentPropertyNames { * Represents the client-side equivalent of the TimeInterval class. */ interface ASPxClientTimeInterval { + /** + * Gets a value indicating if the time interval is All-Day. + */ GetAllDay(): boolean; /** - * - * @param allDayValue + * Sets a value specifying if the time interval is All-Day. + * @param allDayValue true, if this is an all-day time interval; otherwise, false. */ SetAllDay(allDayValue: boolean): void; /** @@ -13908,23 +14094,44 @@ interface ASPxClientAppointmentResizeEventArgs extends ASPxClientEventArgs { */ operation: ASPxClientAppointmentOperation; } +/** + * Contains information about a client tooltip. + */ interface ASPxClientSchedulerToolTipData { + /** + * Returns the client appointment for which the tooltip is displayed. + */ GetAppointment(): ASPxClientAppointment; + /** + * Returns the client time interval for which the tooltip is displayed. + */ GetInterval(): ASPxClientTimeInterval; + /** + * Returns the resources associated with the appointment for which the tooltip is displayed. + */ GetResources(): Object[]; } +/** + * A client-side equivalent of the ASPxSchedulerToolTipBase control. + */ interface ASPxClientToolTipBase { + /** + * Returns the value that indicates whether or not the tooltip can be displayed. + */ CanShowToolTip(): boolean; /** - * - * @param toolTipData + * Ends updating the tooltip content. + * @param toolTipData An ASPxClientSchedulerToolTipData object providing data required to update the tooltip content. */ FinalizeUpdate(toolTipData: ASPxClientSchedulerToolTipData): void; /** - * - * @param toolTipData + * Updates the tooltip content. + * @param toolTipData An ASPxClientSchedulerToolTipData object providing data required to update the tooltip content. */ Update(toolTipData: ASPxClientSchedulerToolTipData): void; + /** + * Closes the tooltip. + */ Close(): void; /** * @@ -13932,18 +14139,18 @@ interface ASPxClientToolTipBase { */ CalculatePosition(bounds: Object): ASPxClientPoint; /** - * - * @param eventObject + * Displays the Appointment Menu in the position of the tooltip. + * @param eventObject An object containing information about the event on which the menu is displayed. */ ShowAppointmentMenu(eventObject: Object): void; /** - * - * @param eventObject + * Displays the View Menu in the position of the tooltip. + * @param eventObject An object containing information about the event on which the menu is displayed. */ ShowViewMenu(eventObject: Object): void; /** - * - * @param interval + * Returns the string representation of the specified interval. + * @param interval An ASPxClientTimeInterval object to convert. */ ConvertIntervalToString(interval: ASPxClientTimeInterval): string; } @@ -14222,11 +14429,11 @@ interface ASPxClientSpreadsheet extends ASPxClientControl { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side DocumentCallback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side DocumentCallback event. @@ -14373,6 +14580,7 @@ interface ASPxClientTreeList extends ASPxClientControl { * Sets input focus to the ASPxTreeList. */ Focus(): void; + GetPopupEditForm(): ASPxClientPopupControl; /** * Returns the focused node's key value. */ @@ -14430,11 +14638,11 @@ interface ASPxClientTreeList extends ASPxClientControl { */ PerformCallback(args: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param args A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param args + * @param onSuccess */ - PerformCallback(args: string, onSuccess: Function): void; + PerformCallback(args: string, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side CustomDataCallback event passing it the specified argument. * @param arg A string value that represents any information that needs to be sent to the server-side CustomDataCallback event. @@ -15011,22 +15219,22 @@ interface MVCxClientCallbackPanel extends ASPxClientCallbackPanel { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the Callback Panel by processing the passed information on the server, in an Action specified by the Callback Panel's CallbackRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified by the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the CardView extension. @@ -15042,11 +15250,11 @@ interface MVCxClientCardView extends ASPxClientCardView { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the CardView by processing the passed information on the server, in an Action specified via the CardView's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CardView's CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback with a parameter to process the passed information on the server, in an Action specified via the CardView's CustomDataActionRouteValues property, and then process the returned result in the specified client function. This method does not update the CardView. * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomDataActionRouteValues property. @@ -15079,22 +15287,22 @@ interface MVCxClientChart extends ASPxClientWebChartControl { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update a Chart by processing the passed information on the server, in an Action specified via the Chart's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side event, passing it the specified argument. * @param args A string value that represents any information that needs to be sent to the server-side event. */ PerformCallback(args: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param args A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param args + * @param onSuccess */ - PerformCallback(args: string, onSuccess: Function): void; + PerformCallback(args: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the ComboBox and ComboBoxFor extensions. @@ -15110,11 +15318,11 @@ interface MVCxClientComboBox extends ASPxClientComboBox { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the ComboBox by processing the passed information on the server, in an Action specified by the ComboBox's CallbackRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified by the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. @@ -15135,22 +15343,22 @@ interface MVCxClientDataView extends ASPxClientDataView { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the DataView by processing the passed information on the server, in an Action specified via the DataView's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side CustomCallback event. */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the DateEdit extension. @@ -15167,22 +15375,22 @@ interface MVCxClientDockManager extends ASPxClientDockManager { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the DockManager by processing the passed information on the server, in an Action specified by the DockManager's CallbackRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified by the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. * @param parameter A string value that contains any information that needs to be sent to the server-side Callback event. */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that contains any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the DockPanel extension. @@ -15198,11 +15406,11 @@ interface MVCxClientDockPanel extends ASPxClientDockPanel { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the DockPanel by processing the passed information on the server, in an Action specified by the DockPanel's DockPanelSettings.CallbackRouteValues) property. - * @param data An object containing any information that needs to be passed to a handling Action specified by the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side WindowCallback event, passing the specified argument to it. * @param parameter A string value that is any information that needs to be sent to the server-side WindowCallback event. @@ -15223,22 +15431,22 @@ interface MVCxClientFileManager extends ASPxClientFileManager { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the FileManager by processing the passed information on the server, in an Action specified via the extension's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the file manager's CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. * @param args A string value that specifies any information that needs to be sent to the server-side CustomCallback event. */ PerformCallback(args: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param args A string value that specifies any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param args + * @param onSuccess */ - PerformCallback(args: string, onSuccess: Function): void; + PerformCallback(args: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the GridView extension. @@ -15254,11 +15462,11 @@ interface MVCxClientGridView extends ASPxClientGridView { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the GridView by processing the passed information on the server, in an Action specified via the grid's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the grid's CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback with a parameter to process the passed information on the server, in an Action specified via the GridView's CustomDataActionRouteValues property, and then process the returned result in the specified client function. This method does not update the GridView. * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomDataActionRouteValues property. @@ -15317,22 +15525,22 @@ interface MVCxClientImageGallery extends ASPxClientImageGallery { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the ImageGallery by processing the passed information on the server, in an Action specified via the ImageGallery's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side CustomCallback event. */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the ListBox and ListBoxFor extensions. @@ -15348,11 +15556,11 @@ interface MVCxClientListBox extends ASPxClientListBox { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the ListBox by processing the passed information on the server, in an Action specified by the ListBox's CallbackRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified by the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server, and generates the server-side Callback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. @@ -15382,11 +15590,11 @@ interface MVCxClientPivotGrid extends ASPxClientPivotGrid { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the PivotGrid by processing the passed information on the server, in an Action specified via the grid's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the grid's CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Passes PivotGrid callback parameters to the specified object. * @param obj An object that receives PivotGrid callback parameters. @@ -15398,11 +15606,11 @@ interface MVCxClientPivotGrid extends ASPxClientPivotGrid { */ PerformCallback(args: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param args A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param args + * @param onSuccess */ - PerformCallback(args: string, onSuccess: Function): void; + PerformCallback(args: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the PopupControl extension. @@ -15418,11 +15626,11 @@ interface MVCxClientPopupControl extends ASPxClientPopupControl { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the PopupControl by processing the passed information on the server, in an Action specified via the PopupControl's CallbackRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback with a parameters to update the popup window by processing the related popup window and the passed information on the server, in an Action specified by the PopupControl's CallbackRouteValues property. * @param window A ASPxClientPopupWindow object identifying the processed popup window. @@ -15436,12 +15644,12 @@ interface MVCxClientPopupControl extends ASPxClientPopupControl { */ PerformWindowCallback(window: ASPxClientPopupWindow, parameter: string): void; /** - * Sends a callback to the server and generates the server-side WindowCallback event, passing it the related popup window object and the specified argument. - * @param window An ASPxClientPopupWindow object identifying the processed popup window. - * @param parameter A string value specifying any information that needs to be sent to the server-side WindowCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param window + * @param parameter + * @param onSuccess */ - PerformWindowCallback(window: ASPxClientPopupWindow, parameter: string, onSuccess: Function): void; + PerformWindowCallback(window: ASPxClientPopupWindow, parameter: string, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side WindowCallback event, passing the specified argument to it. * @param parameter A string value that is any information that needs to be sent to the server-side WindowCallback event. @@ -15513,22 +15721,22 @@ interface MVCxClientReportDesigner extends ASPxClientReportDesigner { */ PerformCallback(arg: Object): void; /** - * Sends a callback to the server with the specified argument. - * @param arg A Object value, specifying the callback argument. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param arg + * @param onSuccess */ - PerformCallback(arg: Object, onSuccess: Function): void; + PerformCallback(arg: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server with the specified argument. * @param arg A String value, specifying the callback argument. */ PerformCallback(arg: string): void; /** - * Sends a callback to the server with the specified argument. - * @param arg A String value, specifying the callback argument. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param arg + * @param onSuccess */ - PerformCallback(arg: string, onSuccess: Function): void; + PerformCallback(arg: string, onSuccess: (arg1: string) => void): void; } /** * A method that will handle the SaveCommandExecuted event. @@ -15565,22 +15773,22 @@ interface MVCxClientRichEdit extends ASPxClientRichEdit { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the RichEdit by processing the passed information on the server, in an Action specified via the CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side event. */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the RoundPanel extension. @@ -15596,22 +15804,22 @@ interface MVCxClientRoundPanel extends ASPxClientRoundPanel { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the Round Panel by processing the passed information on the server, in an Action specified by the Round Panel's CallbackRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified by the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side ContentCallback event, passing it the specified argument. * @param parameter A string value that is any information that needs to be sent to the server-side ContentCallback event. */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side ContentCallback event, passing it the specified argument. - * @param parameter A string value that is any information that needs to be sent to the server-side ContentCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the Scheduler extension. @@ -15628,11 +15836,11 @@ interface MVCxClientScheduler extends ASPxClientScheduler { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the Scheduler by processing the passed information on the server, in an Action specified via the Scheduler's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument * @param parameter A string value that represents any information that needs to be sent to the server-side CustomCallback event. @@ -15682,22 +15890,22 @@ interface MVCxClientSpreadsheet extends ASPxClientSpreadsheet { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the Spreadsheet by processing the passed information on the server, in an Action specified via the CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side event. */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the PageControl extension. @@ -15713,22 +15921,22 @@ interface MVCxClientPageControl extends ASPxClientPageControl { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the PageControl by processing the passed information on the server, in an Action specified by the PageControl's CallbackRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified by the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A client-side counterpart of the TokenBox and TokenBoxFor extensions. @@ -15744,11 +15952,11 @@ interface MVCxClientTokenBox extends ASPxClientTokenBox { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the TokenBox by processing the passed information on the server, in an Action specified by the TokenBox's CallbackRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified by the CallbackRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. @@ -15769,11 +15977,11 @@ interface MVCxClientTreeList extends ASPxClientTreeList { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the TreeList by processing the passed information on the server, in an Action specified via the TreeList's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback with a parameter to process the passed information on the server, in an Action specified via the TreeList's CustomDataCallback event. This method does not update the TreeList. * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomDataActionRouteValues property. @@ -15785,11 +15993,11 @@ interface MVCxClientTreeList extends ASPxClientTreeList { */ PerformCallback(args: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param args A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param args + * @param onSuccess */ - PerformCallback(args: string, onSuccess: Function): void; + PerformCallback(args: string, onSuccess: (arg1: string) => void): void; /** * Sends a callback to the server and generates the server-side CustomDataCallback event passing it the specified argument. * @param arg A string value that represents any information that needs to be sent to the server-side CustomDataCallback event. @@ -15887,11 +16095,11 @@ interface MVCxClientVerticalGrid extends ASPxClientVerticalGrid { */ PerformCallback(data: Object): void; /** - * Sends a callback with a parameter to update the VerticalGrid by processing the passed information on the server in an Action specified via the grid's CustomActionRouteValues property. - * @param data An object containing any information that needs to be passed to a handling Action specified via the grid's CustomActionRouteValues property. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param data + * @param onSuccess */ - PerformCallback(data: Object, onSuccess: Function): void; + PerformCallback(data: Object, onSuccess: (arg1: string) => void): void; /** * Sends a callback with a parameter to process the passed information on the server, in an Action specified via the VerticalGrid's CustomDataActionRouteValues property, and then process the returned result in the specified client function. This method does not update the VerticalGrid. * @param data An object containing any information that needs to be passed to a handling Action specified via the CustomDataActionRouteValues property. @@ -16013,11 +16221,11 @@ interface ASPxClientCallback extends ASPxClientControl { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A method that will handle the client events related to completion of callback server-side processing. @@ -16072,11 +16280,11 @@ interface ASPxClientCallbackPanel extends ASPxClientControl { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; /** * Returns the text displayed within the control's loading panel. */ @@ -16460,6 +16668,12 @@ interface ASPxClientControlsInitializedEventArgs extends ASPxClientEventArgs { */ isCallback: boolean; } +interface ASPxClientControlPredicate { + (control: Object): boolean; +} +interface ASPxClientControlAction { + (control: Object): void; +} /** * A collection object used on the client side to maintain particular client control objects */ @@ -16498,6 +16712,21 @@ interface ASPxClientControlCollection { * @param name A string value that is the hierarchically-qualified identifier of the required DevExpress control. */ GetByName(name: string): Object; + /** + * + * @param predicate + */ + GetControlsByPredicate(predicate: ASPxClientControlPredicate): Object[]; + /** + * + * @param type + */ + GetControlsByType(type: Object): Object[]; + /** + * + * @param action + */ + ForEachControl(action: ASPxClientControlAction): void; } /** * Represents a client-side equivalent of the ASPxDataView object. @@ -16559,11 +16788,11 @@ interface ASPxClientDataView extends ASPxClientControl { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * A JavaScript function which returns a value specifying whether an object meets the criteria defined within the method specified by this delegate. @@ -16629,11 +16858,11 @@ interface ASPxClientDockManager extends ASPxClientControl { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that contains any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; /** * Returns a zone specified by its unique identifier (zoneUID). * @param zoneUID A string value specifying the unique identifier of the zone. @@ -17375,11 +17604,11 @@ interface ASPxClientFileManager extends ASPxClientControl { */ PerformCallback(args: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param args A string value that specifies any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param args + * @param onSuccess */ - PerformCallback(args: string, onSuccess: Function): void; + PerformCallback(args: string, onSuccess: (arg1: string) => void): void; } /** * A JavaScript function which receives callback data obtained via a call to the client SetCurrentFolderPath method. @@ -17448,6 +17677,7 @@ interface ASPxClientFileManagerFile extends ASPxClientFileManagerItem { * A client-side equivalent of the FileManagerFolder object. */ interface ASPxClientFileManagerFolder extends ASPxClientFileManagerItem { + isParentFolder: boolean; } /** * A JavaScript function which receives callback data obtained by a call to the client GetAllItems method. @@ -18659,6 +18889,7 @@ interface ASPxClientMenuBase extends ASPxClientControl { * Represents a client collection that maintains client menu objects. */ interface ASPxClientMenuCollection extends ASPxClientControlCollection { + RecalculateAll(): void; /** * Hides all menus maitained by the collection. */ @@ -19358,12 +19589,12 @@ interface ASPxClientPopupControl extends ASPxClientPopupControlBase { */ PerformWindowCallback(window: ASPxClientPopupWindow, parameter: string): void; /** - * Sends a callback to the server and generates the server-side WindowCallback event, passing it the related popup window object and the specified argument. - * @param window An ASPxClientPopupWindow object identifying the processed popup window. - * @param parameter A string value specifying any information that needs to be sent to the server-side WindowCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param window + * @param parameter + * @param onSuccess */ - PerformWindowCallback(window: ASPxClientPopupWindow, parameter: string, onSuccess: Function): void; + PerformWindowCallback(window: ASPxClientPopupWindow, parameter: string, onSuccess: (arg1: string) => void): void; /** * Specifies the default popup window's size. * @param width An integer value that specifies the default popup window's width. @@ -20006,7 +20237,7 @@ interface ASPxClientRibbon extends ASPxClientControl { */ GetMinimized(): boolean; /** - * Specifies the visibility of a context tab ?ategory specified by its name. + * Specifies the visibility of a context tab category specified by its name. * @param categoryName A Name property value of the required category. * @param visible true to make a category visible; false to make it hidden. */ @@ -20248,11 +20479,11 @@ interface ASPxClientRoundPanel extends ASPxClientPanelBase { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side ContentCallback event, passing it the specified argument. - * @param parameter A string value that is any information that needs to be sent to the server-side ContentCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; /** * Returns the text displayed within the panel's header. */ @@ -20623,11 +20854,11 @@ interface ASPxClientPageControl extends ASPxClientTabControlBase { */ PerformCallback(parameter: string): void; /** - * Sends a callback to the server and generates the server-side Callback event, passing it the specified argument. - * @param parameter A string value that represents any information that needs to be sent to the server-side Callback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param parameter + * @param onSuccess */ - PerformCallback(parameter: string, onSuccess: Function): void; + PerformCallback(parameter: string, onSuccess: (arg1: string) => void): void; } /** * Represents a client-side equivalent of a tab control's TabPage object. @@ -21481,11 +21712,15 @@ interface ASPxClientChartDesigner extends ASPxClientControl { */ PerformCallback(arg: string): void; /** - * Sends a callback to the server and generates the server-side event, passing it the specified argument. - * @param arg A string value that represents any information that needs to be sent to the server-side event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param arg + * @param onSuccess + */ + PerformCallback(arg: string, onSuccess: (arg1: string) => void): void; + /** + * Updates the localization settings of the ASPxClientChartDesigner properties. + * @param localization A dictionary containing the property names, along with their localized equivalents. */ - PerformCallback(arg: string, onSuccess: Function): void; UpdateLocalization(localization: { [key: string]: string; }): void; /** * Returns the model of the Client Chart Designer. @@ -21636,11 +21871,11 @@ interface ASPxClientWebChartControl extends ASPxClientControl { */ PerformCallback(args: string): void; /** - * Sends a callback to the server and generates the server-side CustomCallback event, passing it the specified argument. - * @param args A string value that represents any information that needs to be sent to the server-side CustomCallback event. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param args + * @param onSuccess */ - PerformCallback(args: string, onSuccess: Function): void; + PerformCallback(args: string, onSuccess: (arg1: string) => void): void; /** * Prints the current chart on the client side. */ @@ -23640,11 +23875,15 @@ interface ASPxClientQueryBuilder extends ASPxClientControl { */ PerformCallback(arg: string): void; /** - * Sends a callback to the server with the specified argument. - * @param arg A String value, specifying the callback argument. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param arg + * @param onSuccess + */ + PerformCallback(arg: string, onSuccess: (arg1: string) => void): void; + /** + * Updates the localization settings of the ASPxClientQueryBuilder properties. + * @param localization A dictionary containing the property names, along with their localized equivalents. */ - PerformCallback(arg: string, onSuccess: Function): void; UpdateLocalization(localization: { [key: string]: string; }): void; /** * Returns the object model of a Query Builder. @@ -23797,11 +24036,15 @@ interface ASPxClientReportDesigner extends ASPxClientControl { */ PerformCallback(arg: string): void; /** - * Sends a callback to the server with the specified argument. - * @param arg A String value, specifying the callback argument. - * @param onSuccess A delegate method that will be called if the callback is successful. + * + * @param arg + * @param onSuccess + */ + PerformCallback(arg: string, onSuccess: (arg1: string) => void): void; + /** + * Updates the localization settings of the ASPxClientReportDesigner properties. + * @param localization A dictionary containing the property names, along with their localized equivalents. */ - PerformCallback(arg: string, onSuccess: Function): void; UpdateLocalization(localization: { [key: string]: string; }): void; /** * Returns the object model of a Web Report Designer. @@ -24013,6 +24256,10 @@ interface ASPxClientReportViewer extends ASPxClientControl { * Occurs on the client side when another report page is loaded into this ASPxClientReportViewer instance. */ PageLoad: ASPxClientEvent>; + /** + * Submits the values of the specified parameters. + * @param parameters A dictionary containing the parameter names, along with their Object values. + */ SubmitParameters(parameters: { [key: string]: Object; }): void; /** * Prints a report shown in the ReportViewer. @@ -24260,6 +24507,10 @@ interface ASPxClientWebDocumentViewer extends ASPxClientControl { * @param format A String value, specifying the export format. The following formats are currently supported: 'csv', 'html', 'image', 'mht', 'pdf', 'rtf', 'txt', 'xls', and 'xlsx'. */ ExportTo(format: string): void; + /** + * Updates the localization settings of the ASPxClientWebDocumentViewer properties. + * @param localization A dictionary containing the property names, along with their localized equivalents. + */ UpdateLocalization(localization: { [key: string]: string; }): void; } /** @@ -25661,30 +25912,30 @@ interface ASPxClientRichEditStatic extends ASPxClientControlStatic { } interface ASPxSchedulerDateTimeHelperStatic { /** - * - * @param date + * Returns the date part of the specified DateTime value. + * @param date A DateTime object from which to extract the date. */ TruncToDate(date: Date): Date; /** - * - * @param date + * Returns the day time part of the specified DateTime value. + * @param date A DateTime object from which to extract the day time. */ ToDayTime(date: Date): any; /** - * - * @param date + * Adds the specified number of days to a DateTime object and returns the result. + * @param date A DateTime object to which to add days. */ AddDays(date: Date): Date; /** - * - * @param date - * @param timeSpan + * Adds the specified timespan to a DateTime object and returns the result. + * @param date A DateTime object to which to add a timespan. + * @param timeSpan A TimeSpan object specifying the timespan to add. */ AddTimeSpan(date: Date, timeSpan: any): Date; /** - * - * @param date - * @param spanInMs + * Rounds a DateTime value up to the nearest interval. + * @param date A DateTime object containing a value to round. + * @param spanInMs A TimeSpan object specifying an interval to which to round. */ CeilDateTime(date: Date, spanInMs: any): Date; } @@ -25706,9 +25957,9 @@ interface ASPxClientRecurrenceTypeEditStatic extends ASPxClientRadioButtonListSt } interface ASPxClientTimeIntervalStatic { /** - * - * @param start - * @param end + * Gets the duration of a time interval between two points in time. + * @param start A DateTime object specifying the starting point of the time interval. + * @param end A DateTime object specifying the ending point of the time interval. */ CalculateDuration(start: Date, end: Date): number; } diff --git a/devtools-detect/devtools-detect-tests.ts b/devtools-detect/devtools-detect-tests.ts new file mode 100644 index 0000000000..9cd1d2f7a7 --- /dev/null +++ b/devtools-detect/devtools-detect-tests.ts @@ -0,0 +1,12 @@ +/// + +// check if it's open +console.log('is DevTools open?', window.devtools.open); +// check it's orientation, null if not open +console.log('and DevTools orientation?', window.devtools.orientation); + +// get notified when it's opened/closed or orientation changes +window.addEventListener('devtoolschange', function (e) { + console.log('is DevTools open?', e.detail.open); + console.log('and DevTools orientation?', e.detail.orientation); +}); diff --git a/devtools-detect/devtools-detect.d.ts b/devtools-detect/devtools-detect.d.ts new file mode 100644 index 0000000000..c66d63f0fa --- /dev/null +++ b/devtools-detect/devtools-detect.d.ts @@ -0,0 +1,16 @@ +// Type definitions for ajv +// Project: https://github.com/sindresorhus/devtools-detect +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type DevTools = { + open: boolean; + orientation: "vertical" | "horizontal"; +} +interface DevToolsEvent extends Event { + detail: DevTools; +} +interface Window { + devtools: DevTools; + addEventListener(type: "devtoolschange", listener: (ev: DevToolsEvent) => any, useCapture?: boolean): void; +} diff --git a/diff/diff-tests.ts b/diff/diff-tests.ts index 46d367bf68..20d75b38ea 100644 --- a/diff/diff-tests.ts +++ b/diff/diff-tests.ts @@ -49,5 +49,44 @@ function printDiff(diff:jsdiff.IDiffResult[]) { console.log(addLineHeader(" ", part.value)); } }); +} -} \ No newline at end of file +function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { + var verifyPatch = jsdiff.parsePatch( + jsdiff.createTwoFilesPatch("oldFile.ts", "newFile.ts", oldStr, newStr, + "old", "new", { context: 1 })); + if (JSON.stringify(verifyPatch) !== JSON.stringify(uniDiff)) { + console.error("Patch did not match uniDiff"); + } +} + +function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { + var verifyApply = [ + jsdiff.applyPatch(oldStr, uniDiff), + jsdiff.applyPatch(oldStr, [uniDiff]) + ]; + jsdiff.applyPatches([uniDiff], { + loadFile: (index: number, callback: (err: Error, data: string) => void) => { + callback(undefined, one); + }, + patched: (index: number, content: string) => { + verifyApply.push(content); + }, + complete: (err?: Error) => { + if (err) { + console.error(err); + } + + verifyApply.forEach(result => { + if (result !== newStr) { + console.error("Result did not match newStr"); + } + }); + } + }); +} + +verifyPatchMethods(one, other, uniDiff); +var uniDiff = jsdiff.structuredPatch("oldFile.ts", "newFile.ts", one, other, + "old", "new", { context: 1 }); +verifyApplyMethods(one, other, uniDiff); diff --git a/diff/diff.d.ts b/diff/diff.d.ts index b1f947300b..fc4708c2a1 100644 --- a/diff/diff.d.ts +++ b/diff/diff.d.ts @@ -16,6 +16,22 @@ declare namespace JsDiff { componenets: IDiffResult[]; } + interface IHunk { + oldStart: number; + oldLines: number; + newStart: number; + newLines: number; + lines: string[]; + } + + interface IUniDiff { + oldFileName: string; + newFileName: string; + oldHeader: string; + newHeader: string; + hunks: IHunk[]; + } + class Diff { ignoreWhitespace:boolean; @@ -46,9 +62,21 @@ declare namespace JsDiff { function diffCss(oldStr:string, newStr:string):IDiffResult[]; - function createPatch(fileName:string, oldStr:string, newStr:string, oldHeader:string, newHeader:string):string; + function createPatch(fileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; - function applyPatch(oldStr:string, uniDiff:string):string; + function createTwoFilesPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): string; + + function structuredPatch(oldFileName: string, newFileName: string, oldStr: string, newStr: string, oldHeader: string, newHeader: string, options?: {context: number}): IUniDiff; + + function applyPatch(oldStr: string, uniDiff: string | IUniDiff | IUniDiff[]): string; + + function applyPatches(uniDiff: IUniDiff[], options: { + loadFile: (index: number, callback: (err: Error, data: string) => void) => void, + patched: (index: number, content: string) => void, + complete: (err?: Error) => void + }): void; + + function parsePatch(diffStr: string, options?: {strict: boolean}): IUniDiff[]; function convertChangesToXML(changes:IDiffResult[]):string; diff --git a/diff2html/diff2html-tests.ts b/diff2html/diff2html-tests.ts new file mode 100644 index 0000000000..35448baa90 --- /dev/null +++ b/diff2html/diff2html-tests.ts @@ -0,0 +1,26 @@ +/// + +import Diff2Html = require('diff2html'); + +let d2h = Diff2Html.Diff2Html; + +class Diff2HtmlOptionsImpl implements Diff2Html.Options { + constructor (public inputFormat: string) { + } +} + +let strInput = + 'diff --git a/sample b/sample\n' + + 'index 0000001..0ddf2ba\n' + + '--- a/sample\n' + + '+++ b/sample\n' + + '@@ -1 +1 @@\n' + + '-test\n' + + '+test1r\n'; + +let strConfiguration = new Diff2HtmlOptionsImpl('diff'); +let diffInput = d2h.getJsonFromDiff(strInput, strConfiguration); + +let diffConfiguration = new Diff2HtmlOptionsImpl('json'); +let htmlString = d2h.getPrettyHtml(diffInput, diffConfiguration); +console.log(htmlString); diff --git a/diff2html/diff2html.d.ts b/diff2html/diff2html.d.ts new file mode 100644 index 0000000000..398cb1aba1 --- /dev/null +++ b/diff2html/diff2html.d.ts @@ -0,0 +1,66 @@ +// Type definitions for diff2html +// Project: https://github.com/rtfpessoa/diff2html +// Definitions by: rtfpessoa +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Diff2Html { + + export interface Options { + inputFormat?: string; + outputFormat?: string; + showFiles?: boolean; + matching?: string; + synchronisedScroll?: boolean; + matchWordsThreshold?: number; + matchingMaxComparisons?: number; + } + + export interface Line { + content: string; + type: string; + oldNumber: number; + newNumber: number; + } + + export interface Block { + oldStartLine: number; + oldStartLine2?: number; + newStartLine: number; + header: string; + lines: Line[]; + } + + export interface Result { + addedLines: number; + deletedLines: number; + isCombined: boolean; + isGitDiff: boolean; + oldName: string; + newName: string; + language: string; + blocks: Block[]; + oldMode?: string; + newMode?: string; + deletedFileMode?: string; + newFileMode?: string; + isDeleted?: boolean; + isNew?: boolean; + isCopy?: boolean; + isRename?: boolean; + unchangedPercentage?: number; + changedPercentage?: number; + checksumBefore?: string; + checksumAfter?: string; + mode?: string; + } + + export interface Diff2Html { + getJsonFromDiff(input: string, configuration?: Options): Result; + getPrettyHtml(input: any, configuration?: Options): string; + } +} + +declare module "diff2html" { + var d2h: { "Diff2Html": Diff2Html.Diff2Html }; + export = d2h; +} diff --git a/documentdb/documentdb.d.ts b/documentdb/documentdb.d.ts index 1d901179a6..b37cec9313 100644 --- a/documentdb/documentdb.d.ts +++ b/documentdb/documentdb.d.ts @@ -93,8 +93,13 @@ declare module 'documentdb' { /** Represents the result returned from a query. */ interface QueryIterator { - - toArray(callback: (error: QueryError, result: TResultRow[]) => void): void; + current(): TResultRow; + executeNext(callback: (error: QueryError, result: TResultRow[], responseHeaders? : any) => void): void; + forEach(iteratorFunction : (error: QueryError, element: TResultRow, responseHeaders? : any) => void): void; + hasMoreResults(): boolean; + nextItem(callback: (error : QueryError, item : TResultRow, responseHeaders? : any) => void): void; + reset() : void; + toArray(callback: (error: QueryError, result: TResultRow[], responseHeaders? : any) => void): void; } /** Reprents an object with a unique identifier. */ diff --git a/dojo/dijit.d.ts b/dojo/dijit.d.ts index 8d3e99b6b5..29abf02211 100644 --- a/dojo/dijit.d.ts +++ b/dojo/dijit.d.ts @@ -1606,7 +1606,7 @@ declare module dijit { * already removed/destroyed manually. * */ - own(): any; + own(...args: any[]): any[]; /** * Place this widget somewhere in the DOM based * on standard domConstruct.place() conventions. diff --git a/dojo/dojo.d.ts b/dojo/dojo.d.ts index bf3258a14a..eaab995a36 100644 --- a/dojo/dojo.d.ts +++ b/dojo/dojo.d.ts @@ -5617,7 +5617,7 @@ declare namespace dojo { * @param scope The scope to use when method executes. If method is a string,scope is also the object containing method. * @param method A function to be hitched to scope, or the name of the method inscope to be hitched. */ - hitch(scope: Object, method: Function): any; + hitch(scope: Object, method: (...args: any[]) => any, ...args: any[]): any; /** * Returns a function that will only ever execute in the a given scope. * This allows for easy use of object member functions @@ -5631,7 +5631,7 @@ declare namespace dojo { * @param scope The scope to use when method executes. If method is a string,scope is also the object containing method. * @param method A function to be hitched to scope, or the name of the method inscope to be hitched. */ - hitch(scope: Object, method: String[]): any; + hitch(scope: Object, method: string, ...args: any[]): any; /** * Returns true if it is a built-in function or some other kind of * oddball that should report as a function but doesn't @@ -5686,7 +5686,23 @@ declare namespace dojo { * @param dest The object to which to copy/add all properties contained in source. If dest is falsy, thena new object is manufactured before copying/adding properties begins. * @param sources One of more objects from which to draw all properties to copy into dest. sources are processedleft-to-right and if more than one of these objects contain the same property name, the right-mostvalue "wins". */ - mixin(dest: Object, sources: Object[]): Object; + mixin(dest: T): T; + mixin( + dest: T, + source: U + ): T & U; + mixin( + dest: T, + source1: U, + source2: V + ): T & U & V; + mixin( + dest: T, + source1: U, + source2: V, + source3: W + ): T & U & V & W; + mixin(dest: Object, ...sources: Object[]): T; /** * similar to hitch() except that the scope object is left to be * whatever the execution context eventually becomes. diff --git a/domurl/domurl-tests.ts b/domurl/domurl-tests.ts new file mode 100644 index 0000000000..825dcdd7d0 --- /dev/null +++ b/domurl/domurl-tests.ts @@ -0,0 +1,81 @@ +/// + +interface UModel extends QueryString { + a: any; + b: string; +} + +interface U2Model extends QueryString { + a: any; +} + +interface U3Model extends QueryString { + foo: string; +} + +var u = new Url(); // current document URL will be used +// or we can instantiate as +var u2 = new Url("http://example.com/some/path?a=b&c=d#someAnchor"); +// it should support relative URLs also +var u3 = new Url("/my/site/doc/path?foo=bar#baz"); + +// get the value of some query string parameter +console.log(u2.query.a); +// or +console.log(u3.query["foo"]); + +// Manipulating query string parameters +u.query.a = [1, 2, 3]; // adds/replaces in query string params a=1&a=2&a=3 +u.query.b = 'woohoo'; // adds/replaces in query string param b=woohoo + +if (u.query.a instanceof Array) { // the way to add a parameter + u.query.a.push(4); // now it's "a=1&a=2&a=3&a=4&b=woohoo" +} + +else { // if not an array but scalar value here is a way how to convert to array + u.query.a = [u.query.a]; + u.query.a.push(8) +} + + +// The way to remove the parameter: +delete u.query.a; +// or: +delete u.query["a"]; + +// If you need to remove all query string params: +console.log(u.clearQuery()); +console.log(u.queryLength()); +console.log(u.isEmptyQuery()); + +// Lookup URL parts: +console.log( + 'protocol = ' + u.protocol + '\n' + + 'user = ' + u.user + '\n' + + 'pass = ' + u.pass + '\n' + + 'host = ' + u.host + '\n' + + 'port = ' + u.port + '\n' + + 'path = ' + u.path + '\n' + + 'query = ' + u.query + '\n' + + 'hash = ' + u.hash +); + +// Manipulating URL parts +u.path = '/some/new/path'; // the way to change URL path +u.protocol = 'https'; // the way to force https protocol on the source URL + +// inject into string +var str = 'My Cool Link'; + +// or use in DOM context +var a = document.createElement('a'); +a.href = u.toString(); +a.innerHTML = 'test'; +document.body.appendChild(a); + +// Stringify +var su1 = u + ''; +var su2 = String(u); +var su3 = u.toString(); +// NOTE, that usually it will be done automatically, so only in special +// cases direct stringify is required diff --git a/domurl/domurl.d.ts b/domurl/domurl.d.ts new file mode 100644 index 0000000000..8c418c75cc --- /dev/null +++ b/domurl/domurl.d.ts @@ -0,0 +1,30 @@ +// Type definitions for domurl +// Project: https://github.com/Mikhus/domurl +// Definitions by: Mikhus +// Definitions: https://github.com/Mikhus/DefinitelyTyped + +declare class QueryString { + constructor(qs?: string); + toString: () => string; +} + +declare class Url { + constructor(url?: string); + query: T; + protocol: string; + user: string; + pass: string; + host: string; + port: string; + path: string; + hash: string; + href: string; + toString: () => string; + encode: (s: string) => string; + decode: (s: string) => string; + isAbsolute: () => boolean; + paths: (paths?: [string]) => [string]; + isEmptyQuery: () => boolean; + queryLength: () => number; + clearQuery: () => Url; +} diff --git a/draft-js/draft-js-0.2.2.d.ts b/draft-js/draft-js-0.2.2.d.ts new file mode 100644 index 0000000000..ac5eb21f33 --- /dev/null +++ b/draft-js/draft-js-0.2.2.d.ts @@ -0,0 +1,277 @@ +// Type definitions for draft-js 0.2.2 +// Project: https://github.com/facebook/draft-js +// Definitions by: Pavel Evsegneev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module "draft-js" { + namespace Draft { + interface IEditor { + new(): Editor + } + + interface EditorState { + getCurrentContent(): ContentState, + getSelection(): SelectionState, + getCurrentInlineStyle(): any, + getBlockTree(): any, + + createEmpty(decorator?: any): EditorState, + createWithContent(contentState: ContentState, decorator?: any): EditorState, + create(config: any): EditorState, + push(editorState: EditorState, contentState: ContentState, actionType: string): EditorState, + undo(editorState: EditorState): EditorState, + redo(editorState: EditorState): EditorState, + acceptSelection(editorState: EditorState, selectionState: SelectionState): EditorState, + forceSelection(editorState: EditorState, selectionState: SelectionState): EditorState, + + moveFocusToEnd(editorState: EditorState): EditorState + } + + interface CompositeDecorator { + getDecorations(): Array, + getComponentForKey(): any, + getPropsForKey(): any + } + + interface Entity { + create(type: string, mutability: string, data?: Object): EntityInstance, + add(instance: EntityInstance): string, + get(key: string): EntityInstance, + mergeData(key: string, toMerge: any): EntityInstance, + replaceData(key: string, newData: any): EntityInstance + } + + interface EntityInstance { + getData(): any, + getKey(): string, + getMutability(): string + } + + interface BlockMapBuilder { + createFromArray(blocks: Array): BlockMap + } + + interface CharacterMetadata { + create(config?: any): CharacterMetadata, + + applyStyle(record: CharacterMetadata, + style: string): CharacterMetadata, + + removeStyle(record: CharacterMetadata, + style: string): CharacterMetadata, + + applyEntity(record: CharacterMetadata, + entityKey?: string): CharacterMetadata, + + getStyle(): any, + hasStyle(style: string): boolean, + + getEntity(): string + } + + interface IContentBlock { + new(draftContentBlock: any): ContentBlock; + } + interface ContentBlock { + key: string, + type: string, + text: string, + characterList: any, + depth: number, + + getKey(): string, + getType(): string, + getText(): string, + getCharacterList(): any, + getLength(): number, + getDepth(): number, + getInlineStyleAt(offset: number): any, + getEntityAt(offset: number): string, + findStyleRanges(filterFn: Function, callback: Function): void, + findEntityRanges(filterFn: Function, callback: Function): void + + } + + interface ContentState { + createFromText(text: string): ContentState, + createFromBlockArray(blocks: Array): ContentState, + + getBlockMap(): BlockMap, + getSelectionBefore(): SelectionState, + getSelectionAfter(): SelectionState, + + getBlockForKey(key: string): ContentBlock, + getKeyBefore(key: string): string, + getKeyAfter(key: string): string, + + getBlockBefore(key: string): ContentBlock, + getBlockAfter(key: string): ContentBlock, + + getBlocksAsArray(): Array, + + getPlainText(): string, + hasText(): boolean, + + set(key: string, value: any): ContentState, + toJS(): any + } + + interface ISelectionState { + new(draftSelectionState: any): SelectionState; + createEmpty(blockKey: string): SelectionState; + } + + interface SelectionState { + getStartKey(): string, + getStartOffset(): number, + getEndKey(): string, + getEndOffset(): number, + getAnchorKey(): string, + getAnchorOffset(): number, + getFocusKey(): string, + getFocusOffset(): number, + + getIsBackward(): boolean, + getHasFocus(): boolean, + isCollapsed(): boolean, + + hasEdgeWithin(blockKey: string, start: number, end: number): boolean, + serialize(): string, + + get(key: string): any, + set(key: string, value: any): SelectionState + } + + interface BlockMap { + get(key: string): ContentBlock, + set(key: string, value: any): BlockMap, + delete(key: string): BlockMap, + find(cb: any): ContentBlock + } + + interface Modifier { + replaceText(contentState: ContentState, + rangeToReplace: SelectionState, + text: string, + inlineStyle?: any, + entityKey?: string): ContentState, + + insertText(contentState: ContentState, + targetRange: SelectionState, + text: string, + inlineStyle?: any, + entityKey?: string): ContentState, + + moveText(contentState: ContentState, + removalRange: SelectionState, + targetRange: SelectionState): ContentState, + + replaceWithFragment(contentState: ContentState, + targetRange: SelectionState, + fragment: BlockMap): ContentState, + + removeRange(contentState: ContentState, + rangeToRemove: SelectionState, + removalDirection: string): ContentState, + + splitBlock(contentState: ContentState, + selectionState: SelectionState): ContentState, + + applyInlineStyle(contentState: ContentState, + selectionState: SelectionState, + inlineStyle: string): ContentState, + + removeInlineStyle(contentState: ContentState, + selectionState: SelectionState, + inlineStyle: string): ContentState, + + setBlockType(contentState: ContentState, + selectionState: SelectionState, + blockType: string): ContentState, + + applyEntity(contentState: ContentState, + selectionState: SelectionState, + entityKey: string): ContentState + } + + interface RichUtils { + currentBlockContainsLink(editorState: EditorState): boolean, + getCurrentBlockType(editor: EditorState): string, + handleKeyCommand(editorState: EditorState, command: string): any, + insertSoftNewline(editorState: EditorState): EditorState, + onBackspace(editorState: EditorState): EditorState, + onDelete(editorState: EditorState): EditorState, + onTab(event: Event, editorState: EditorState, maxDepth: number): EditorState, + toggleBlockType(editorState: EditorState, blockType: string): EditorState, + toggleCode(editorState: EditorState): EditorState, + toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string): EditorState, + tryToRemoveBlockStyle(editorState: EditorState): EditorState + } + + interface EditorProps { + editorState: EditorState, + onChange(editorState: EditorState): void, + + placeholder?: string, + textAlignment?: any, + blockRendererFn?: (ContentBlock: ContentBlock) => any, + blockStyleFn?: (ContentBlock: ContentBlock) => string, + customStyleMap?: any, + + readOnly?: boolean, + spellCheck?: boolean, + stripPastedStyles?: boolean, + + handleReturn?: (e: any) => boolean, + handleKeyCommand?: (command: string) => boolean, + handleBeforeInput?: (chars: string) => boolean, + handlePastedFiles?: (files: Array) => boolean, + handleDroppedFiles?: (selection: SelectionState, files: Array) => boolean, + handleDrop?: (selection: SelectionState, dataTransfer: any, isInternal: any) => boolean, + + onEscape?: (e: any) => void, + onTab?: (e: any) => void, + onUpArrow?: (e: any) => void, + onDownArrow?: (e: any) => void, + + suppressContentEditableWarning?: any, + + onBlur?: (e: any) => void, + onFocus?: (e: any) => void + } + + interface Editor { + props: EditorProps + state: any, + refs: any, + context: any, + setState(): any, + render(): any, + forceUpdate(): any + } + + var Editor: IEditor; + var EditorState: EditorState; + + var CompositeDecorator: CompositeDecorator; + var Entity: Entity; + var EntityInstance: EntityInstance; + + var BlockMapBuilder: BlockMapBuilder; + var CharacterMetadata: CharacterMetadata; + var ContentBlock: IContentBlock; + var ContentState: ContentState; + var SelectionState: ISelectionState; + + var Modifier: Modifier; + var RichUtils: RichUtils; + + function convertFromRaw(rawState: any): Array; + + function convertToRaw(contentState: ContentState): any; + + function genKey(): string + } + + export = Draft; + +} diff --git a/draft-js/draft-js-tests-0.2.2.tsx b/draft-js/draft-js-tests-0.2.2.tsx new file mode 100644 index 0000000000..88271465f5 --- /dev/null +++ b/draft-js/draft-js-tests-0.2.2.tsx @@ -0,0 +1,183 @@ +/// +/// +/// + +import * as React from "react"; + +import { + Editor, + EditorState, + Entity, + CharacterMetadata, + ContentBlock, + Modifier, + SelectionState, + genKey +} from "draft-js"; + +export class Tag extends React.Component { + constructor(props: any) { + super(props); + } + + remove = (): void => { + this.props.blockProps.removeBlock(this.props.block.getKey()); + } + + render () { + const {block} = this.props; + if (block.getEntityAt(0)) { + const data = Entity.get(block.getEntityAt(0)).getData(); + + return ( +
      + {data.content.name} + + clear + +
      + ); + } + } +} + +export class Hint extends React.Component { + constructor(props: any) { + super(props); + } + + render () { + const {block} = this.props; + if (block.getEntityAt(0)) { + const data = Entity.get(block.getEntityAt(0)).getData(); + + return ( +
      + {this.props.blockProps.autocomplete} + {data.content.text} +
      + ); + } + } +} + +export function removeBlock(editorState: EditorState, blockKey: string) { + const content = editorState.getCurrentContent(); + + const targetRange = new SelectionState({ + anchorKey: blockKey, + anchorOffset: 0, + focusKey: blockKey, + focusOffset: 1 + }); + + const withoutTag = Modifier.removeRange(content, targetRange, "backward"); + const resetBlock = Modifier.setBlockType( + withoutTag, + withoutTag.getSelectionAfter(), + "unstyled" + ); + + const newState = EditorState.push(editorState, resetBlock, "remove-range"); + return EditorState.forceSelection(newState, resetBlock.getSelectionAfter()); +} + +export function applyEntity(editorState: EditorState, blockKey: string, entityKey: string) { + const content = editorState.getCurrentContent(); + + const targetRange = new SelectionState({ + anchorKey: blockKey, + anchorOffset: 0, + focusKey: blockKey, + focusOffset: 1 + }); + + const withNewEntity = Modifier.applyEntity( + content, + targetRange, + entityKey + ) + + const newState = EditorState.push(editorState, withNewEntity, "change-entity"); + return EditorState.forceSelection(newState, withNewEntity.getSelectionAfter()); +} + +export function addTagBlock(content: any, editorState: EditorState): any { + const contentState = editorState.getCurrentContent(); + + const entityKey = Entity.create( + "TOKEN", + "IMMUTABLE", + {content} + ); + + const charData = CharacterMetadata.create({entity: entityKey}); + const tag = new ContentBlock({ + key: genKey(), + type: "tag", + text: "", + characterList: [], + }); + + const withTag = contentState.set("blockMap", contentState.getBlockMap().set(tag.key, tag)); + + const withRemovedPreviousBlock = withTag.set("blockMap", withTag.getBlockMap().delete(contentState.getSelectionBefore().getAnchorKey())) + + const withTagBlock = EditorState.push(editorState, withRemovedPreviousBlock, "insert-fragment"); + + return withTagBlock; +} + +export function addHintBlock(content: any, editorState: EditorState): any { + const contentState = editorState.getCurrentContent(); + const selectionState = editorState.getSelection(); + + const entityKey = Entity.create( + "TOKEN", + "IMMUTABLE", + {content} + ); + + const charData = CharacterMetadata.create({entity: entityKey}); + const hint = new ContentBlock({ + key: genKey(), + type: "hint", + text: "", + characterList: [], + }); + const empty = new ContentBlock({ + key: genKey(), + type: "unstyled", + text: "", + characterList: [], + }); + + const withEmpty = contentState.set("blockMap", contentState.getBlockMap().set(empty.key, empty)); + const withHint = withEmpty.set("blockMap", withEmpty.getBlockMap().set(hint.key, hint)); + return { + editorState: EditorState.forceSelection(EditorState.push(editorState, withHint, "insert-fragment"), selectionState), + blockKey: hint.key + } + +} + +export class SearchField extends React.Component { + public onChange: any; + + constructor(props: any) { + super(props); + this.onChange = (editorState: EditorState) => { + this.setState({editorState}) + }; + } + + render() { + const {editorState} = this.state; + return ( + + ) + } +} diff --git a/draft-js/draft-js-tests.tsx b/draft-js/draft-js-tests.tsx index 91706cd7e0..eb3aaa4012 100644 --- a/draft-js/draft-js-tests.tsx +++ b/draft-js/draft-js-tests.tsx @@ -1,183 +1,184 @@ -/// -/// -/// +/// +/// +/// + +// Using Rich text editor example as a test: https://github.com/facebook/draft-js/tree/master/examples/rich import * as React from "react"; +import * as ReactDOM from "react-dom"; +import {Map} from "immutable"; -import { -Editor, - EditorState, - Entity, - CharacterMetadata, - ContentBlock, - Modifier, - SelectionState, - genKey -} from "draft-js"; +import {Editor, EditorState, RichUtils, DefaultDraftBlockRenderMap, ContentBlock} from 'draft-js'; -export class Tag extends React.Component { - constructor(props: any) { - super(props); +class RichEditorExample extends React.Component<{}, { editorState: EditorState }> { + constructor() { + super(); + + this.state = { editorState: EditorState.createEmpty() }; + } + + onChange: (editorState: EditorState) => void = (editorState: EditorState) => this.setState({ editorState }); + + handleKeyCommand: (command: string) => boolean = (command: string) => { + const {editorState} = this.state; + const newState = RichUtils.handleKeyCommand(editorState, command); + if (newState) { + this.onChange(newState); + return true; } - remove = (): void => { - this.props.blockProps.removeBlock(this.props.block.getKey()); + return false; + } + + toggleBlockType: (blockType: string) => void = (blockType: string) => { + this.onChange(RichUtils.toggleBlockType(this.state.editorState, blockType)); + } + + toggleInlineStyle: (inlineStyle: string) => void = (inlineStyle: string) => { + this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, inlineStyle)); + } + + render(): React.ReactElement<{}> { + // If the user changes block type before entering any text, we can + // either style the placeholder or hide it. Let's just hide it now. + let className = 'RichEditor-editor'; + var contentState = this.state.editorState.getCurrentContent(); + if (!contentState.hasText()) { + if (contentState.getBlockMap().first().getType() !== 'unstyled') { + className += ' RichEditor-hidePlaceholder'; + } } - render () { - const {block} = this.props; - if (block.getEntityAt(0)) { - const data = Entity.get(block.getEntityAt(0)).getData(); - - return ( -
      - {data.content.name} - - clear - -
      - ); - } - } -} - -export class Hint extends React.Component { - constructor(props: any) { - super(props); - } - - render () { - const {block} = this.props; - if (block.getEntityAt(0)) { - const data = Entity.get(block.getEntityAt(0)).getData(); - - return ( -
      - {this.props.blockProps.autocomplete} - {data.content.text} -
      - ); - } - } -} - -export function removeBlock(editorState: EditorState, blockKey: string) { - const content = editorState.getCurrentContent(); - - const targetRange = new SelectionState({ - anchorKey: blockKey, - anchorOffset: 0, - focusKey: blockKey, - focusOffset: 1 - }); - - const withoutTag = Modifier.removeRange(content, targetRange, "backward"); - const resetBlock = Modifier.setBlockType( - withoutTag, - withoutTag.getSelectionAfter(), - "unstyled" + return ( +
      + + +
      + +
      +
      ); - - const newState = EditorState.push(editorState, resetBlock, "remove-range"); - return EditorState.forceSelection(newState, resetBlock.getSelectionAfter()); + } } -export function applyEntity(editorState: EditorState, blockKey: string, entityKey: string) { - const content = editorState.getCurrentContent(); +// Custom overrides for "code" style. +const styleMap = { + CODE: { + backgroundColor: 'rgba(0, 0, 0, 0.05)', + fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace', + fontSize: 16, + padding: 2, + }, +}; - const targetRange = new SelectionState({ - anchorKey: blockKey, - anchorOffset: 0, - focusKey: blockKey, - focusOffset: 1 - }); - - const withNewEntity = Modifier.applyEntity( - content, - targetRange, - entityKey - ) - - const newState = EditorState.push(editorState, withNewEntity, "change-entity"); - return EditorState.forceSelection(newState, withNewEntity.getSelectionAfter()); +function getBlockStyle(block: ContentBlock) { + switch (block.getType()) { + case 'blockquote': return 'RichEditor-blockquote'; + default: return null; + } } -export function addTagBlock(content: any, editorState: EditorState): any { - const contentState = editorState.getCurrentContent(); +class StyleButton extends React.Component<{key: string, active: boolean, label: string, onToggle: (blockType: string) => void, style: string}, {}> { + constructor() { + super(); + } - const entityKey = Entity.create( - "TOKEN", - "IMMUTABLE", - {content} + onToggle: (event: Event) => void = (event: Event) => { + event.preventDefault(); + this.props.onToggle(this.props.style); + }; + + render(): React.ReactElement<{}> { + let className = 'RichEditor-styleButton'; + + if (this.props.active) { + className += ' RichEditor-activeButton'; + } + + return ( + + {this.props.label} + ); - - const charData = CharacterMetadata.create({entity: entityKey}); - const tag = new ContentBlock({ - key: genKey(), - type: "tag", - text: "", - characterList: [], - }); - - const withTag = contentState.set("blockMap", contentState.getBlockMap().set(tag.key, tag)); - - const withRemovedPreviousBlock = withTag.set("blockMap", withTag.getBlockMap().delete(contentState.getSelectionBefore().getAnchorKey())) - - const withTagBlock = EditorState.push(editorState, withRemovedPreviousBlock, "insert-fragment"); - - return withTagBlock; + } } -export function addHintBlock(content: any, editorState: EditorState): any { - const contentState = editorState.getCurrentContent(); - const selectionState = editorState.getSelection(); +const BLOCK_TYPES = [ + { label: 'H1', style: 'header-one' }, + { label: 'H2', style: 'header-two' }, + { label: 'H3', style: 'header-three' }, + { label: 'H4', style: 'header-four' }, + { label: 'H5', style: 'header-five' }, + { label: 'H6', style: 'header-six' }, + { label: 'Blockquote', style: 'blockquote' }, + { label: 'UL', style: 'unordered-list-item' }, + { label: 'OL', style: 'ordered-list-item' }, + { label: 'Code Block', style: 'code-block' }, +]; - const entityKey = Entity.create( - "TOKEN", - "IMMUTABLE", - {content} - ); +const BlockStyleControls = (props: {editorState: EditorState, onToggle: (blockType: string) => void}) => { + const {editorState} = props; + const selection = editorState.getSelection(); + const blockType = editorState + .getCurrentContent() + .getBlockForKey(selection.getStartKey()) + .getType(); - const charData = CharacterMetadata.create({entity: entityKey}); - const hint = new ContentBlock({ - key: genKey(), - type: "hint", - text: "", - characterList: [], - }); - const empty = new ContentBlock({ - key: genKey(), - type: "unstyled", - text: "", - characterList: [], - }); + return ( +
      + {BLOCK_TYPES.map((type) => + + ) } +
      + ); +}; - const withEmpty = contentState.set("blockMap", contentState.getBlockMap().set(empty.key, empty)); - const withHint = withEmpty.set("blockMap", withEmpty.getBlockMap().set(hint.key, hint)); - return { - editorState: EditorState.forceSelection(EditorState.push(editorState, withHint, "insert-fragment"), selectionState), - blockKey: hint.key - } +var INLINE_STYLES = [ + { label: 'Bold', style: 'BOLD' }, + { label: 'Italic', style: 'ITALIC' }, + { label: 'Underline', style: 'UNDERLINE' }, + { label: 'Monospace', style: 'CODE' }, +]; -} +const InlineStyleControls = (props: {editorState: EditorState, onToggle: (blockType: string) => void}) => { + var currentStyle = props.editorState.getCurrentInlineStyle(); + return ( +
      + {INLINE_STYLES.map(type => + + ) } +
      + ); +}; -export class SearchField extends React.Component { - public onChange: any; - - constructor(props: any) { - super(props); - this.onChange = (editorState: EditorState) => { - this.setState({editorState}) - }; - } - - render() { - const {editorState} = this.state; - return ( - - ) - } -} +ReactDOM.render( + , + document.getElementById('target') +); \ No newline at end of file diff --git a/draft-js/draft-js.d.ts b/draft-js/draft-js.d.ts index ac5eb21f33..bf10cd22c4 100644 --- a/draft-js/draft-js.d.ts +++ b/draft-js/draft-js.d.ts @@ -1,277 +1,939 @@ -// Type definitions for draft-js 0.2.2 -// Project: https://github.com/facebook/draft-js -// Definitions by: Pavel Evsegneev +// Type definitions for Draft.js v0.7.0 +// Project: https://facebook.github.io/draft-js/ +// Definitions by: Dmitry Rogozhny // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "draft-js" { - namespace Draft { - interface IEditor { - new(): Editor + +/// +/// + +import SyntheticKeyboardEvent = React.KeyboardEvent; +import SyntheticEvent = React.SyntheticEvent; + +import React = __React; + +declare namespace Draft { + namespace Component { + namespace Base { + import DraftEditorCommand = Draft.Model.Constants.DraftEditorCommand; + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + import DraftDragType = Draft.Model.Constants.DraftDragType; + + import EditorState = Draft.Model.ImmutableData.EditorState; + import ContentBlock = Draft.Model.ImmutableData.ContentBlock; + import SelectionState = Draft.Model.ImmutableData.SelectionState; + + import DraftBlockRenderConfig = Draft.Model.ImmutableData.DraftBlockRenderConfig; + + type DraftBlockRenderMap = Immutable.Map; + + /** + * `DraftEditor` is the root editor component. It composes a `contentEditable` + * div, and provides a wide variety of useful function props for managing the + * state of the editor. See `DraftEditorProps` for details. + */ + class DraftEditor extends React.Component { + // Force focus back onto the editor node. + focus(): void; + // Remove focus from the editor node. + blur(): void; + } + + /** + * The two most critical props are `editorState` and `onChange`. + * + * The `editorState` prop defines the entire state of the editor, while the + * `onChange` prop is the method in which all state changes are propagated + * upward to higher-level components. + * + * These props are analagous to `value` and `onChange` in controlled React + * text inputs. + */ + interface DraftEditorProps { + editorState: EditorState; + onChange(editorState: EditorState): void; + + placeholder?: string; + + // Specify whether text alignment should be forced in a direction + // regardless of input characters. + textAlignment?: DraftTextAlignment; + + // For a given `ContentBlock` object, return an object that specifies + // a custom block component and/or props. If no object is returned, + // the default `TextEditorBlock` is used. + blockRendererFn?(block: ContentBlock): any; + + // Function that allows to define class names to apply to the given block when it is rendered. + blockStyleFn?(block: ContentBlock): string; + + // Provide a map of inline style names corresponding to CSS style objects + // that will be rendered for matching ranges. + customStyleMap?: any, + + // A function that accepts a synthetic key event and returns + // the matching DraftEditorCommand constant, or null if no command should + // be invoked. + keyBindingFn?(e: SyntheticKeyboardEvent): DraftEditorCommand; + keyBindingFn?(e: SyntheticKeyboardEvent): string; + + // Set whether the `DraftEditor` component should be editable. Useful for + // temporarily disabling edit behavior or allowing `DraftEditor` rendering + // to be used for consumption purposes. + readOnly?: boolean, + + // Note: spellcheck is always disabled for IE. If enabled in Safari, OSX + // autocorrect is enabled as well. + spellCheck?: boolean, + + // Set whether to remove all style information from pasted content. If your + // use case should not have any block or inline styles, it is recommended + // that you set this to `true`. + stripPastedStyles?: boolean, + + tabIndex?: number, + + ariaActiveDescendantID?: string, + ariaAutoComplete?: string, + ariaDescribedBy?: string, + ariaExpanded?: boolean, + ariaHasPopup?: boolean, + ariaLabel?: string, + ariaOwneeID?: string, + + webDriverTestID?: string, + + /** + * Cancelable event handlers, handled from the top level down. A handler + * that returns true will be the last handler to execute for that event. + */ + + // Useful for managing special behavior for pressing the `Return` key. E.g. + // removing the style from an empty list item. + handleReturn?(e: SyntheticKeyboardEvent): boolean, + + // Map a key command string provided by your key binding function to a + // specified behavior. + handleKeyCommand?(command: DraftEditorCommand): boolean, + handleKeyCommand?(command: string): boolean, + + + // Handle intended text insertion before the insertion occurs. This may be + // useful in cases where the user has entered characters that you would like + // to trigger some special behavior. E.g. immediately converting `:)` to an + // emoji Unicode character, or replacing ASCII quote characters with smart + // quotes. + handleBeforeInput?(chars: string): boolean, + + handlePastedText?(text: string, html?: string): boolean, + + handlePastedFiles?(files: Array): boolean, + + // Handle dropped files + handleDroppedFiles?(selection: SelectionState, files: Array): boolean, + + // Handle other drops to prevent default text movement/insertion behaviour + handleDrop?(selection: SelectionState, dataTransfer: Object, isInternal: DraftDragType): boolean, + + /** + * Non-cancelable event triggers. + */ + onEscape?(e: SyntheticKeyboardEvent): void, + onTab?(e: SyntheticKeyboardEvent): void, + onUpArrow?(e: SyntheticKeyboardEvent): void, + onDownArrow?(e: SyntheticKeyboardEvent): void, + + onBlur?(e: SyntheticEvent): void, + onFocus?(e: SyntheticEvent): void, + + // Provide a map of block rendering configurations. Each block type maps to + // an element tag and an optional react element wrapper. This configuration + // is used for both rendering and paste processing. + blockRenderMap?: DraftBlockRenderMap + } + + type DraftTextAlignment = "left" | "center" | "right"; } - interface EditorState { - getCurrentContent(): ContentState, - getSelection(): SelectionState, - getCurrentInlineStyle(): any, - getBlockTree(): any, - - createEmpty(decorator?: any): EditorState, - createWithContent(contentState: ContentState, decorator?: any): EditorState, - create(config: any): EditorState, - push(editorState: EditorState, contentState: ContentState, actionType: string): EditorState, - undo(editorState: EditorState): EditorState, - redo(editorState: EditorState): EditorState, - acceptSelection(editorState: EditorState, selectionState: SelectionState): EditorState, - forceSelection(editorState: EditorState, selectionState: SelectionState): EditorState, - - moveFocusToEnd(editorState: EditorState): EditorState + namespace Components { + class DraftEditorBlock extends React.Component { + } } - interface CompositeDecorator { - getDecorations(): Array, - getComponentForKey(): any, - getPropsForKey(): any + namespace Selection { + interface FakeClientRect { + left: number, + width: number, + right: number, + top: number, + bottom: number, + height: number, + } + + /** + * Return the bounding ClientRect for the visible DOM selection, if any. + * In cases where there are no selected ranges or the bounding rect is + * temporarily invalid, return null. + */ + function getVisibleSelectionRect(global: any): FakeClientRect; } - interface Entity { - create(type: string, mutability: string, data?: Object): EntityInstance, - add(instance: EntityInstance): string, - get(key: string): EntityInstance, - mergeData(key: string, toMerge: any): EntityInstance, - replaceData(key: string, newData: any): EntityInstance + namespace Utils { + import DraftEditorCommand = Draft.Model.Constants.DraftEditorCommand; + + class KeyBindingUtil { + /** + * Check whether the ctrlKey modifier is *not* being used in conjunction with + * the altKey modifier. If they are combined, the result is an `altGraph` + * key modifier, which should not be handled by this set of key bindings. + */ + static isCtrlKeyCommand(e: SyntheticKeyboardEvent): boolean; + + static isOptionKeyCommand(e: SyntheticKeyboardEvent): boolean; + + static hasCommandModifier(e: SyntheticKeyboardEvent): boolean; + } + + /** + * Retrieve a bound key command for the given event. + */ + function getDefaultKeyBinding(e: SyntheticKeyboardEvent): DraftEditorCommand; + function getDefaultKeyBinding(e: SyntheticKeyboardEvent): string; } - - interface EntityInstance { - getData(): any, - getKey(): string, - getMutability(): string - } - - interface BlockMapBuilder { - createFromArray(blocks: Array): BlockMap - } - - interface CharacterMetadata { - create(config?: any): CharacterMetadata, - - applyStyle(record: CharacterMetadata, - style: string): CharacterMetadata, - - removeStyle(record: CharacterMetadata, - style: string): CharacterMetadata, - - applyEntity(record: CharacterMetadata, - entityKey?: string): CharacterMetadata, - - getStyle(): any, - hasStyle(style: string): boolean, - - getEntity(): string - } - - interface IContentBlock { - new(draftContentBlock: any): ContentBlock; - } - interface ContentBlock { - key: string, - type: string, - text: string, - characterList: any, - depth: number, - - getKey(): string, - getType(): string, - getText(): string, - getCharacterList(): any, - getLength(): number, - getDepth(): number, - getInlineStyleAt(offset: number): any, - getEntityAt(offset: number): string, - findStyleRanges(filterFn: Function, callback: Function): void, - findEntityRanges(filterFn: Function, callback: Function): void - - } - - interface ContentState { - createFromText(text: string): ContentState, - createFromBlockArray(blocks: Array): ContentState, - - getBlockMap(): BlockMap, - getSelectionBefore(): SelectionState, - getSelectionAfter(): SelectionState, - - getBlockForKey(key: string): ContentBlock, - getKeyBefore(key: string): string, - getKeyAfter(key: string): string, - - getBlockBefore(key: string): ContentBlock, - getBlockAfter(key: string): ContentBlock, - - getBlocksAsArray(): Array, - - getPlainText(): string, - hasText(): boolean, - - set(key: string, value: any): ContentState, - toJS(): any - } - - interface ISelectionState { - new(draftSelectionState: any): SelectionState; - createEmpty(blockKey: string): SelectionState; - } - - interface SelectionState { - getStartKey(): string, - getStartOffset(): number, - getEndKey(): string, - getEndOffset(): number, - getAnchorKey(): string, - getAnchorOffset(): number, - getFocusKey(): string, - getFocusOffset(): number, - - getIsBackward(): boolean, - getHasFocus(): boolean, - isCollapsed(): boolean, - - hasEdgeWithin(blockKey: string, start: number, end: number): boolean, - serialize(): string, - - get(key: string): any, - set(key: string, value: any): SelectionState - } - - interface BlockMap { - get(key: string): ContentBlock, - set(key: string, value: any): BlockMap, - delete(key: string): BlockMap, - find(cb: any): ContentBlock - } - - interface Modifier { - replaceText(contentState: ContentState, - rangeToReplace: SelectionState, - text: string, - inlineStyle?: any, - entityKey?: string): ContentState, - - insertText(contentState: ContentState, - targetRange: SelectionState, - text: string, - inlineStyle?: any, - entityKey?: string): ContentState, - - moveText(contentState: ContentState, - removalRange: SelectionState, - targetRange: SelectionState): ContentState, - - replaceWithFragment(contentState: ContentState, - targetRange: SelectionState, - fragment: BlockMap): ContentState, - - removeRange(contentState: ContentState, - rangeToRemove: SelectionState, - removalDirection: string): ContentState, - - splitBlock(contentState: ContentState, - selectionState: SelectionState): ContentState, - - applyInlineStyle(contentState: ContentState, - selectionState: SelectionState, - inlineStyle: string): ContentState, - - removeInlineStyle(contentState: ContentState, - selectionState: SelectionState, - inlineStyle: string): ContentState, - - setBlockType(contentState: ContentState, - selectionState: SelectionState, - blockType: string): ContentState, - - applyEntity(contentState: ContentState, - selectionState: SelectionState, - entityKey: string): ContentState - } - - interface RichUtils { - currentBlockContainsLink(editorState: EditorState): boolean, - getCurrentBlockType(editor: EditorState): string, - handleKeyCommand(editorState: EditorState, command: string): any, - insertSoftNewline(editorState: EditorState): EditorState, - onBackspace(editorState: EditorState): EditorState, - onDelete(editorState: EditorState): EditorState, - onTab(event: Event, editorState: EditorState, maxDepth: number): EditorState, - toggleBlockType(editorState: EditorState, blockType: string): EditorState, - toggleCode(editorState: EditorState): EditorState, - toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string): EditorState, - tryToRemoveBlockStyle(editorState: EditorState): EditorState - } - - interface EditorProps { - editorState: EditorState, - onChange(editorState: EditorState): void, - - placeholder?: string, - textAlignment?: any, - blockRendererFn?: (ContentBlock: ContentBlock) => any, - blockStyleFn?: (ContentBlock: ContentBlock) => string, - customStyleMap?: any, - - readOnly?: boolean, - spellCheck?: boolean, - stripPastedStyles?: boolean, - - handleReturn?: (e: any) => boolean, - handleKeyCommand?: (command: string) => boolean, - handleBeforeInput?: (chars: string) => boolean, - handlePastedFiles?: (files: Array) => boolean, - handleDroppedFiles?: (selection: SelectionState, files: Array) => boolean, - handleDrop?: (selection: SelectionState, dataTransfer: any, isInternal: any) => boolean, - - onEscape?: (e: any) => void, - onTab?: (e: any) => void, - onUpArrow?: (e: any) => void, - onDownArrow?: (e: any) => void, - - suppressContentEditableWarning?: any, - - onBlur?: (e: any) => void, - onFocus?: (e: any) => void - } - - interface Editor { - props: EditorProps - state: any, - refs: any, - context: any, - setState(): any, - render(): any, - forceUpdate(): any - } - - var Editor: IEditor; - var EditorState: EditorState; - - var CompositeDecorator: CompositeDecorator; - var Entity: Entity; - var EntityInstance: EntityInstance; - - var BlockMapBuilder: BlockMapBuilder; - var CharacterMetadata: CharacterMetadata; - var ContentBlock: IContentBlock; - var ContentState: ContentState; - var SelectionState: ISelectionState; - - var Modifier: Modifier; - var RichUtils: RichUtils; - - function convertFromRaw(rawState: any): Array; - - function convertToRaw(contentState: ContentState): any; - - function genKey(): string } - export = Draft; + namespace Model { + namespace Constants { + /** + * A set of editor commands that may be invoked by keyboard commands or UI + * controls. These commands should map to operations that modify content or + * selection state and update the editor state accordingly. + */ + type DraftEditorCommand = ( + /** + * Self-explanatory. + */ + "undo" | + "redo" | + /** + * Perform a forward deletion. + */ + "delete" | + + /** + * Perform a forward deletion to the next word boundary after the selection. + */ + "delete-word" | + + /** + * Perform a backward deletion. + */ + "backspace" | + + /** + * Perform a backward deletion to the previous word boundary before the + * selection. + */ + "backspace-word" | + + /** + * Perform a backward deletion to the beginning of the current line. + */ + "backspace-to-start-of-line" | + + /** + * Toggle styles. Commands may be intepreted to modify inline text ranges + * or block types. + */ + "bold" | + "italic" | + "underline" | + "code" | + + /** + * Split a block in two. + */ + "split-block" | + + /** + * Self-explanatory. + */ + "transpose-characters" | + "move-selection-to-start-of-block" | + "move-selection-to-end-of-block" | + + /** + * Commands to support the "secondary" clipboard provided by certain + * browsers and operating systems. + */ + "secondary-cut" | + "secondary-paste" + ); + + /** + * A type that allows us to avoid passing boolean arguments + * around to indicate whether a drag type is internal or external. + */ + type DraftDragType = "internal" | "external"; + + /** + * The list of default valid block types. + */ + type DraftBlockType = ( + "unstyled" | + "paragraph" | + "header-one" | + "header-two" | + "header-three" | + "header-four" | + "header-five" | + "header-six" | + "unordered-list-item" | + "ordered-list-item" | + "blockquote" | + "code-block" | + "atomic" + ); + + /** + * A type that allows us to avoid passing boolean arguments + * around to indicate whether a deletion is forward or backward. + */ + type DraftRemovalDirection = "backward" | "forward"; + } + + namespace Decorators { + import ContentBlock = Draft.Model.ImmutableData.ContentBlock; + + /** + * An interface for document decorator classes, allowing the creation of + * custom decorator classes. + * + * See `CompositeDraftDecorator` for the most common use case. + */ + interface DraftDecoratorType { + /** + * Given a `ContentBlock`, return an immutable List of decorator keys. + */ + getDecorations(block: ContentBlock): Immutable.List; + + /** + * Given a decorator key, return the component to use when rendering + * this decorated range. + */ + getComponentForKey(key: string): Function; + + /** + * Given a decorator key, optionally return the props to use when rendering + * this decorated range. + */ + getPropsForKey(key: string): any; + } + + /** + * A DraftDecorator is a strategy-component pair intended for use when + * rendering content. + * + * - A "strategy": A function that accepts a ContentBlock object and + * continuously executes a callback with start/end values corresponding to + * relevant matches in the document text. For example, getHashtagMatches + * uses a hashtag regex to find hashtag strings in the block, and + * for each hashtag match, executes the callback with start/end pairs. + * + * - A "component": A React component that will be used to render the + * "decorated" section of text. + * + * - "props": Props to be passed into the React component that will be used. + */ + interface DraftDecorator { + strategy: (block: ContentBlock, callback: (start: number, end: number) => void) => void; + component: Function; + props?: Object; + } + + /** + * A CompositeDraftDecorator traverses through a list of DraftDecorator + * instances to identify sections of a ContentBlock that should be rendered + * in a "decorated" manner. For example, hashtags, mentions, and links may + * be intended to stand out visually, be rendered as anchors, etc. + * + * The list of decorators supplied to the constructor will be used in the + * order they are provided. This allows the caller to specify a priority for + * string matching, in case of match collisions among decorators. + * + * For instance, I may have a link with a `#` in its text. Though this section + * of text may match our hashtag decorator, it should not be treated as a + * hashtag. I should therefore list my link DraftDecorator + * before my hashtag DraftDecorator when constructing this composite + * decorator instance. + * + * Thus, when a collision like this is encountered, the earlier match is + * preserved and the new match is discarded. + */ + class CompositeDraftDecorator { + constructor(decorators: Array); + + getDecorations(block: ContentBlock): Immutable.List; + getComponentForKey(key: string): Function; + getPropsForKey(key: string): Object; + } + } + + namespace Encoding { + import ContentBlock = Draft.Model.ImmutableData.ContentBlock; + import ContentState = Draft.Model.ImmutableData.ContentState; + + import DraftBlockRenderMap = Draft.Component.Base.DraftBlockRenderMap; + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + + import DraftEntityType = Draft.Model.Entity.DraftEntityType; + import DraftEntityMutability = Draft.Model.Entity.DraftEntityMutability; + + /** + * A plain object representation of an entity attribution. + * + * The `key` value corresponds to the key of the entity in the `entityMap` of + * a `ComposedText` object, not for use with `DraftEntity.get()`. + */ + interface EntityRange { + key: number, + offset: number, + length: number, + } + + /** + * A plain object representation of an inline style range. + */ + interface InlineStyleRange { + style: string; + offset: number; + length: number; + } + + /** + * A plain object representation of an EntityInstance. + */ + interface RawDraftEntity { + type: DraftEntityType; + mutability: DraftEntityMutability; + data: { [key: string]: any }; + } + + /** + * A plain object representation of a ContentBlock, with all style and entity + * attribution repackaged as range objects. + */ + interface RawDraftContentBlock { + key: string; + type: DraftBlockType; + text: string; + depth: number; + inlineStyleRanges: Array; + entityRanges: Array; + data?: Object; + } + + /** + * A type that represents a composed document as vanilla JavaScript objects, + * with all styles and entities represented as ranges. Corresponding entity + * objects are packaged as objects as well. + * + * This object is especially useful when sending the document state to the + * server for storage, as its representation is more concise than our + * immutable objects. + */ + interface RawDraftContentState { + blocks: Array; + entityMap: { [key: string]: RawDraftEntity }; + } + + function convertFromHTMLtoContentBlocks(html: string, DOMBuilder: Function, blockRenderMap?: DraftBlockRenderMap): Array; + function convertFromRawToDraftState(rawState: RawDraftContentState): ContentState; + function convertFromDraftStateToRaw(contentState: ContentState): RawDraftContentState; + } + + namespace Entity { + type ComposedEntityType = "LINK" | "TOKEN" | "PHOTO"; + type DraftEntityType = string | ComposedEntityType; + + /** + * An enum representing the possible "mutability" options for an entity. + * This refers to the behavior that should occur when inserting or removing + * characters in a text range with an entity applied to it. + * + * `MUTABLE`: + * The text range can be modified freely. Generally used in cases where + * the text content and the entity do not necessarily have a direct + * relationship. For instance, the text and URI for a link may be completely + * different. The user is allowed to edit the text as needed, and the entity + * is preserved and applied to any characters added within the range. + * + * `IMMUTABLE`: + * Not to be confused with immutable data structures used to represent the + * state of the editor. Immutable entity ranges cannot be modified in any + * way. Adding characters within the range will remove the entity from the + * entire range. Deleting characters will delete the entire range. Example: + * Facebook Page mentions. + * + * `SEGMENTED`: + * Segmented entities allow the removal of partial ranges of text, as + * separated by a delimiter. Adding characters wihin the range will remove + * the entity from the entire range. Deleting characters within a segmented + * entity will delete only the segments affected by the deletion. Example: + * Facebook User mentions. + */ + type DraftEntityMutability = "MUTABLE" | "IMMUTABLE" | "SEGMENTED"; + + /** + * A "document entity" is an object containing metadata associated with a + * piece of text in a ContentBlock. + * + * For example, a `link` entity might include a `uri` property. When a + * ContentBlock is rendered in the browser, text that refers to that link + * entity may be rendered as an anchor, with the `uri` as the href value. + * + * In a ContentBlock, every position in the text may correspond to zero + * or one entities. This correspondence is tracked using a key string, + * generated via DraftEntity.create() and used to obtain entity metadata + * via DraftEntity.get(). + */ + class DraftEntity { + /** + * Create a DraftEntityInstance and store it for later retrieval. + * + * A random key string will be generated and returned. This key may + * be used to track the entity's usage in a ContentBlock, and for + * retrieving data about the entity at render time. + */ + static create(type: DraftEntityType, mutability: DraftEntityMutability, data?: Object): string; + + /** + * Add an existing DraftEntityInstance to the DraftEntity map. This is + * useful when restoring instances from the server. + */ + static add(instance: DraftEntityInstance): string; + + /** + * Retrieve the entity corresponding to the supplied key string. + */ + static get(key: string): DraftEntityInstance; + + /** + * Entity instances are immutable. If you need to update the data for an + * instance, this method will merge your data updates and return a new + * instance. + */ + static mergeData(key: string, toMerge: { [key: string]: any }): DraftEntityInstance; + + /** + * Completely replace the data for a given instance. + */ + static replaceData(key: string, newData: { [key: string]: any }): DraftEntityInstance; + } + + /** + * An instance of a document entity, consisting of a `type` and relevant + * `data`, metadata about the entity. + * + * For instance, a "link" entity might provide a URI, and a "mention" + * entity might provide the mentioned user's ID. These pieces of data + * may be used when rendering the entity as part of a ContentBlock DOM + * representation. For a link, the data would be used as an href for + * the rendered anchor. For a mention, the ID could be used to retrieve + * a hovercard. + */ + interface DraftEntityInstance { + getType(): DraftEntityType; + getMutability(): DraftEntityMutability; + getData(): any; + } + } + + namespace ImmutableData { + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + import DraftDecoratorType = Draft.Model.Decorators.DraftDecoratorType; + + type DraftInlineStyle = Immutable.OrderedSet; + type BlockMap = Immutable.OrderedMap; + + var Record: Immutable.Record.Class; + + interface DraftBlockRenderConfig { + element: string; + wrapper?: React.ReactElement; + } + + class EditorState extends Record { + static createEmpty(decorator?: DraftDecoratorType): EditorState; + static createWithContent(contentState: ContentState, decorator?: DraftDecoratorType): EditorState; + static create(config: Object): EditorState; + static set(editorState: EditorState, put: Object): EditorState; + + /** + * Incorporate native DOM selection changes into the EditorState. This + * method can be used when we simply want to accept whatever the DOM + * has given us to represent selection, and we do not need to re-render + * the editor. + * + * To forcibly move the DOM selection, see `EditorState.forceSelection`. + */ + static acceptSelection(editorState: EditorState, selection: SelectionState): EditorState; + + /** + * At times, we need to force the DOM selection to be where we + * need it to be. This can occur when the anchor or focus nodes + * are non-text nodes, for instance. In this case, we want to trigger + * a re-render of the editor, which in turn forces selection into + * the correct place in the DOM. The `forceSelection` method + * accomplishes this. + * + * This method should be used in cases where you need to explicitly + * move the DOM selection from one place to another without a change + * in ContentState. + */ + static forceSelection(editorState: EditorState, selection: SelectionState): EditorState; + + /** + * Move selection to the end of the editor without forcing focus. + */ + static moveSelectionToEnd(editorState: EditorState): EditorState; + + /** + * Force focus to the end of the editor. This is useful in scenarios + * where we want to programmatically focus the input and it makes sense + * to allow the user to continue working seamlessly. + */ + static moveFocusToEnd(editorState: EditorState): EditorState; + + /** + * Push the current ContentState onto the undo stack if it should be + * considered a boundary state, and set the provided ContentState as the + * new current content. + */ + static push(editorState: EditorState, contentState: ContentState, changeType: EditorChangeType): EditorState; + + /** + * Make the top ContentState in the undo stack the new current content and + * push the current content onto the redo stack. + */ + static undo(editorState: EditorState): EditorState; + + /** + * Make the top ContentState in the redo stack the new current content and + * push the current content onto the undo stack. + */ + static redo(editorState: EditorState): EditorState; + + toJS(): Object; + getAllowUndo(): boolean; + getCurrentContent(): ContentState; + getUndoStack(): Immutable.Stack; + getRedoStack(): Immutable.Stack; + getSelection(): SelectionState; + getDecorator(): DraftDecoratorType; + isInCompositionMode(): boolean; + mustForceSelection(): boolean; + getNativelyRenderedContent(): ContentState; + getLastChangeType(): EditorChangeType; + + /** + * While editing, the user may apply inline style commands with a collapsed + * cursor, intending to type text that adopts the specified style. In this + * case, we track the specified style as an "override" that takes precedence + * over the inline style of the text adjacent to the cursor. + * + * If null, there is no override in place. + */ + getInlineStyleOverride(): DraftInlineStyle; + + static setInlineStyleOverride(editorState: EditorState, inlineStyleOverride: DraftInlineStyle): EditorState; + + /** + * Get the appropriate inline style for the editor state. If an + * override is in place, use it. Otherwise, the current style is + * based on the location of the selection state. + */ + getCurrentInlineStyle(): DraftInlineStyle; + + getBlockTree(blockKey: string): Immutable.List; + isSelectionAtStartOfContent(): boolean; + isSelectionAtEndOfContent(): boolean; + getDirectionMap(): Immutable.OrderedMap; + } + + class ContentBlock extends Record { + getKey(): string; + + getType(): DraftBlockType; + getType(): string; + + getText(): string; + getCharacterList(): Immutable.List; + getLength(): number; + getDepth(): number; + getData(): Immutable.Map; + getInlineStyleAt(offset: number): DraftInlineStyle; + getEntityAt(offset: number): string; + + /** + * Execute a callback for every contiguous range of styles within the block. + */ + findStyleRanges(filterFn: (value: CharacterMetadata) => boolean, callback: (start: number, end: number) => void): void; + + /** + * Execute a callback for every contiguous range of entities within the block. + */ + findEntityRanges(filterFn: (value: CharacterMetadata) => boolean, callback: (start: number, end: number) => void): void; + } + + class ContentState extends Record { + static createFromBlockArray(blocks: Array): ContentState; + static createFromText(text: string, delimiter?: string): ContentState; + + getBlockMap(): BlockMap; + getSelectionBefore(): SelectionState; + getSelectionAfter(): SelectionState; + getBlockForKey(key: string): ContentBlock; + + getKeyBefore(key: string): string; + getKeyAfter(key: string): string; + getBlockAfter(key: string): ContentBlock; + getBlockBefore(key: string): ContentBlock; + + getBlocksAsArray(): Array; + getFirstBlock(): ContentBlock; + getLastBlock(): ContentBlock; + getPlainText(delimiter?: string): string; + hasText(): boolean; + } + + class SelectionState extends Record { + static createEmpty(key: string): SelectionState; + + serialize(): string; + getAnchorKey(): string; + getAnchorOffset(): number; + getFocusKey(): string; + getFocusOffset(): number; + getIsBackward(): boolean; + getHasFocus(): boolean; + /** + * Return whether the specified range overlaps with an edge of the + * SelectionState. + */ + hasEdgeWithin(blockKey: string, start: number, end: number): boolean; + isCollapsed(): boolean; + getStartKey(): string; + getStartOffset(): number; + getEndKey(): string; + getEndOffset(): number; + } + + class CharacterMetadata { + static applyStyle(record: CharacterMetadata, style: string): CharacterMetadata; + static removeStyle(record: CharacterMetadata, style: string): CharacterMetadata; + static applyEntity(record: CharacterMetadata, entityKey: string): CharacterMetadata; + static applyEntity(record: CharacterMetadata): CharacterMetadata; + /** + * Use this function instead of the `CharacterMetadata` constructor. + * Since most content generally uses only a very small number of + * style/entity permutations, we can reuse these objects as often as + * possible. + */ + static create(config?: CharacterMetadataConfig): CharacterMetadata; + static create(): CharacterMetadata; + + getStyle(): DraftInlineStyle; + getEntity(): string; + hasStyle(style: string): boolean; + } + + interface CharacterMetadataConfig { + style?: DraftInlineStyle; + entity?: string; + } + + type EditorChangeType = ( + "adjust-depth" | + "apply-entity" | + "backspace-character" | + "change-block-data" | + "change-block-type" | + "change-inline-style" | + "delete-character" | + "insert-characters" | + "insert-fragment" | + "redo" | + "remove-range" | + "spellcheck-change" | + "split-block" | + "undo" + ) + + interface BlockMapBuilder { + createFromArray(blocks: Array): BlockMap; + } + + const DefaultDraftBlockRenderMap: Immutable.Map; + const DefaultDraftInlineStyle: Immutable.Map; + } + + namespace Keys { + function generateRandomKey(): string; + } + + namespace Modifier { + import EditorState = Draft.Model.ImmutableData.EditorState; + import ContentState = Draft.Model.ImmutableData.ContentState; + import SelectionState = Draft.Model.ImmutableData.SelectionState; + + import BlockMap = Draft.Model.ImmutableData.BlockMap; + import DraftInlineStyle = Draft.Model.ImmutableData.DraftInlineStyle; + + import DraftRemovalDirection = Draft.Model.Constants.DraftRemovalDirection; + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + + import DraftEditorCommand = Draft.Model.Constants.DraftEditorCommand; + + type URI = any; + + class AtomicBlockUtils { + static insertAtomicBlock(editorState: EditorState, entityKey: string, character: string): EditorState; + } + + /** + * `DraftModifier` provides a set of convenience methods that apply + * modifications to a `ContentState` object based on a target `SelectionState`. + * + * Any change to a `ContentState` should be decomposable into a series of + * transaction functions that apply the required changes and return output + * `ContentState` objects. + * + * These functions encapsulate some of the most common transaction sequences. + */ + class DraftModifier { + static replaceText(contentState: ContentState, rangeToReplace: SelectionState, text: string, inlineStyle?: DraftInlineStyle, entityKey?: string): ContentState; + static insertText(contentState: ContentState, targetRange: SelectionState, text: string, inlineStyle?: DraftInlineStyle, entityKey?: string): ContentState; + static moveText(contentState: ContentState, removalRange: SelectionState, targetRange: SelectionState): ContentState; + static replaceWithFragment(contentState: ContentState, targetRange: SelectionState, fragment: BlockMap): ContentState; + + static removeRange(contentState: ContentState, rangeToRemove: SelectionState, removalDirection: DraftRemovalDirection): ContentState; + + static splitBlock(contentState: ContentState, selectionState: SelectionState): ContentState; + static applyInlineStyle(contentState: ContentState, selectionState: SelectionState, inlineStyle: string): ContentState; + static removeInlineStyle(contentState: ContentState, selectionState: SelectionState, inlineStyle: string): ContentState; + + static setBlockType(contentState: ContentState, selectionState: SelectionState, blockType: DraftBlockType): ContentState; + static setBlockType(contentState: ContentState, selectionState: SelectionState, blockType: string): ContentState; + + static setBlockData(contentState: ContentState, selectionState: SelectionState, blockData: Immutable.Map): ContentState; + static mergeBlockData(contentState: ContentState, selectionState: SelectionState, blockData: Immutable.Map): ContentState; + static applyEntity(contentState: ContentState, selectionState: SelectionState, entityKey: string): ContentState; + } + + class RichTextEditorUtil { + static currentBlockContainsLink(editorState: EditorState): boolean; + static getCurrentBlockType(editorState: EditorState): DraftBlockType; + static getCurrentBlockType(editorState: EditorState): string; + static getDataObjectForLinkURL(uri: URI): Object; + + static handleKeyCommand(editorState: EditorState, command: DraftEditorCommand): EditorState; + static handleKeyCommand(editorState: EditorState, command: string): EditorState; + + static insertSoftNewline(editorState: EditorState): EditorState; + + /** + * For collapsed selections at the start of styled blocks, backspace should + * just remove the existing style. + */ + static onBackspace(editorState: EditorState): EditorState; + static onDelete(editorState: EditorState): EditorState; + static onTab(event: SyntheticKeyboardEvent, editorState: EditorState, maxDepth: number): EditorState; + + static toggleBlockType(editorState: EditorState, blockType: DraftBlockType): EditorState; + static toggleBlockType(editorState: EditorState, blockType: string): EditorState; + + static toggleCode(editorState: EditorState): EditorState; + + /** + * Toggle the specified inline style for the selection. If the + * user's selection is collapsed, apply or remove the style for the + * internal state. If it is not collapsed, apply the change directly + * to the document state. + */ + static toggleInlineStyle(editorState: EditorState, inlineStyle: string): EditorState; + + static toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string): EditorState; + + /** + * When a collapsed cursor is at the start of an empty styled block, allow + * certain key commands (newline, backspace) to simply change the + * style of the block instead of the default behavior. + */ + static tryToRemoveBlockStyle(editorState: EditorState): ContentState; + } + } + } } + +declare module "draft-js" { + import Editor = Draft.Component.Base.DraftEditor; + import EditorBlock = Draft.Component.Components.DraftEditorBlock; + import EditorState = Draft.Model.ImmutableData.EditorState; + + import CompositeDecorator = Draft.Model.Decorators.CompositeDraftDecorator; + import Entity = Draft.Model.Entity.DraftEntity; + import EntityInstance = Draft.Model.Entity.DraftEntityInstance; + + import BlockMapBuilder = Draft.Model.ImmutableData.BlockMapBuilder; + import CharacterMetadata = Draft.Model.ImmutableData.CharacterMetadata; + import ContentBlock = Draft.Model.ImmutableData.ContentBlock; + import ContentState = Draft.Model.ImmutableData.ContentState; + import SelectionState = Draft.Model.ImmutableData.SelectionState; + + import AtomicBlockUtils = Draft.Model.Modifier.AtomicBlockUtils; + import KeyBindingUtil = Draft.Component.Utils.KeyBindingUtil; + import Modifier = Draft.Model.Modifier.DraftModifier; + import RichUtils = Draft.Model.Modifier.RichTextEditorUtil; + + import DefaultDraftBlockRenderMap = Draft.Model.ImmutableData.DefaultDraftBlockRenderMap; + import DefaultDraftInlineStyle = Draft.Model.ImmutableData.DefaultDraftInlineStyle; + + import convertFromHTML = Draft.Model.Encoding.convertFromHTMLtoContentBlocks; + import convertFromRaw = Draft.Model.Encoding.convertFromRawToDraftState; + import convertToRaw = Draft.Model.Encoding.convertFromDraftStateToRaw; + import genKey = Draft.Model.Keys.generateRandomKey; + import getDefaultKeyBinding = Draft.Component.Utils.getDefaultKeyBinding; + import getVisibleSelectionRect = Draft.Component.Selection.getVisibleSelectionRect; + + export { + Editor, + EditorBlock, + EditorState, + + CompositeDecorator, + Entity, + EntityInstance, + + BlockMapBuilder, + CharacterMetadata, + ContentBlock, + ContentState, + SelectionState, + + AtomicBlockUtils, + KeyBindingUtil, + Modifier, + RichUtils, + + DefaultDraftBlockRenderMap, + DefaultDraftInlineStyle, + + convertFromHTML, + convertFromRaw, + convertToRaw, + genKey, + getDefaultKeyBinding, + getVisibleSelectionRect + }; +} \ No newline at end of file diff --git a/dropzone/dropzone.d.ts b/dropzone/dropzone.d.ts index 7464151b3b..ff8412b0e8 100644 --- a/dropzone/dropzone.d.ts +++ b/dropzone/dropzone.d.ts @@ -95,8 +95,8 @@ interface DropzoneOptions { uploadprogress?(file:DropzoneFile, progress:number, bytesSent:number):void; totaluploadprogress?(totalProgress:number, totalBytes:number, totalBytesSent:number):void; - sending?(file:DropzoneFile, xhr:XMLHttpRequest, formData:{}):void; - sendingmultiple?(files:DropzoneFile[], xhr:XMLHttpRequest, formData:{}):void; + sending?(file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData):void; + sendingmultiple?(files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData):void; success?(file: DropzoneFile, response: Object|string): void; successmultiple?(files:DropzoneFile[], responseText:string):void; @@ -206,8 +206,8 @@ declare class Dropzone { on(eventName:"uploadprogress", callback:(file:DropzoneFile, progress:number, bytesSent:number) => any):void; on(eventName:"totaluploadprogress", callback:(totalProgress:number, totalBytes:number, totalBytesSent:number) => any):void; - on(eventName:"sending", callback:(file:DropzoneFile, xhr:XMLHttpRequest, formData:{}) => any):void; - on(eventName:"sendingmultiple", callback:(files:DropzoneFile[], xhr:XMLHttpRequest, formData:{}) => any):void; + on(eventName:"sending", callback:(file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData) => any):void; + on(eventName:"sendingmultiple", callback:(files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData) => any):void; on(eventName:"success", callback:(file:DropzoneFile) => any):void; on(eventName:"successmultiple", callback:(files:DropzoneFile[]) => any):void; @@ -246,8 +246,8 @@ declare class Dropzone { emit(eventName:"uploadprogress", file:DropzoneFile, progress:number, bytesSent:number):void; emit(eventName:"totaluploadprogress", totalProgress:number, totalBytes:number, totalBytesSent:number):void; - emit(eventName:"sending", file:DropzoneFile, xhr:XMLHttpRequest, formData:{}):void; - emit(eventName:"sendingmultiple", files:DropzoneFile[], xhr:XMLHttpRequest, formData:{}):void; + emit(eventName:"sending", file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData):void; + emit(eventName:"sendingmultiple", files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData):void; emit(eventName:"success", file:DropzoneFile):void; emit(eventName:"successmultiple", files:DropzoneFile[]):void; diff --git a/durandal/durandal.d.ts b/durandal/durandal.d.ts index c5ec79ae61..1b28ca7bc3 100644 --- a/durandal/durandal.d.ts +++ b/durandal/durandal.d.ts @@ -690,9 +690,15 @@ declare module 'plugins/dialog' { * @param {object} context The composition context. */ compositionComplete(child: HTMLElement, parent: HTMLElement, context: composition.CompositionContext): void; + + /** + * Opacity of the blockout. The default is 0.6. + */ + blockoutOpacity?: number; } interface Dialog { + host: HTMLElement; owner: any; context: DialogContext; activator: DurandalActivator; @@ -727,7 +733,7 @@ declare module 'plugins/dialog' { * @param {string} [name] The name of the context to retrieve. * @returns {DialogContext} True context. */ - export function getContext(name: string): DialogContext; + export function getContext(name?: string): DialogContext; /** * Adds (or replaces) a dialog context. diff --git a/dustjs-linkedin/dustjs-linkedin.d.ts b/dustjs-linkedin/dustjs-linkedin.d.ts index 70bd288a39..9bb05b1424 100644 --- a/dustjs-linkedin/dustjs-linkedin.d.ts +++ b/dustjs-linkedin/dustjs-linkedin.d.ts @@ -89,7 +89,7 @@ declare module "dustjs-linkedin" { * Registers an event listener. Streams accept a single listener for a given event. * @param evt the event. Possible values are data, end, error (maybe more, look in the source). */ - on(evt: string, callback: (data?: any) => any); + on(evt: string, callback: (data?: any) => any): this; pipe(stream: Stream): Stream; } @@ -126,8 +126,8 @@ declare module "dustjs-linkedin" { * @param name the template name. * @param context a plain object or an instance of dust.Context. */ - export function render(name: string, context: any, callback: (err: any, out: string) => any); - export function render(name: string, context: Context, callback: (err: any, out: string) => any); + export function render(name: string, context: any, callback: (err: any, out: string) => any): void; + export function render(name: string, context: Context, callback: (err: any, out: string) => any): void; /** * Compiles and renders source, invoking callback on completion. If no callback is supplied this function returns a Stream object. Use this function when precompilation is not required. diff --git a/dva/dva-tests.tsx b/dva/dva-tests.tsx new file mode 100644 index 0000000000..917ee69e60 --- /dev/null +++ b/dva/dva-tests.tsx @@ -0,0 +1,48 @@ +/// +/// + +import React = __React; + +import dva from 'dva'; +import { connect } from 'dva'; +import { Router, Route } from 'dva/router'; + +// 1. Initialize +const app = dva(); + +// 2. Model +app.model({ + namespace: 'count', + state: 0, + reducers: { + add(count: number) { + return count + 1 + }, + minus(count: number) { + return count - 1 + }, + }, +}); + +// 3. View +const App = connect(({ count }) => ({ + count +}))(function ({ count, dispatch }) { + return ( +
      +

      { count }

      + + +
      + ); +}); + +// 4. Router +app.router(({ history }) => + + + +); + +// 5. Start +const countApp = app.start(); diff --git a/dva/dva.d.ts b/dva/dva.d.ts new file mode 100644 index 0000000000..0cf7206e63 --- /dev/null +++ b/dva/dva.d.ts @@ -0,0 +1,61 @@ +// Type definitions for dva v1.0.0 +// Project: https://github.com/dvajs/dva +// Definitions by: nikogu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +declare module 'dva' { + /** connecting Container Components */ + export function connect(maps:Object):Function; + + export default function dva(opts?:Object):{ + + /** dva plugin */ + use: (hooks:Object)=>void, + + /** dva bootstrap */ + start: (selector?:String|HTMLElement)=>void, + + /** dva add model */ + model: (model:Object)=>void, + + /** dva setting router */ + router: (router:Object)=>Object|JSX.Element, + }; +} + +/** + * https://github.com/reactjs/react-router + */ +declare module 'dva/router' { + import React = __React; + + interface RouterProps { + history?: Object + } + export class Router extends React.Component { + render():JSX.Element + } + + + interface RouteProps { + path?: string, + component?: React.ReactNode + } + export class Route extends React.Component { + render():JSX.Element + } + + /** + * https://github.com/reactjs/react-router-redux + */ + export class routerRedux {} + +} + +/** + * https://github.com/fis-components/whatwg-fetch + */ +declare module 'dva/fetch' { + export default Function; +} diff --git a/easeljs/easeljs.d.ts b/easeljs/easeljs.d.ts index 3ddeabdef9..ab8cd5a0e1 100644 --- a/easeljs/easeljs.d.ts +++ b/easeljs/easeljs.d.ts @@ -650,6 +650,7 @@ declare namespace createjs { autoReset: boolean; static buildDate: string; currentFrame: number; + totalFrames: number; currentLabel: string; frameBounds: Rectangle[]; framerate: number; @@ -662,6 +663,7 @@ declare namespace createjs { startPosition: number; static SYNCHED: string; timeline: Timeline; + duration: number; static version: string; // methods diff --git a/elastic.js/elastic.js-tests.ts b/elastic.js/elastic.js-tests.ts new file mode 100644 index 0000000000..24c9784f81 --- /dev/null +++ b/elastic.js/elastic.js-tests.ts @@ -0,0 +1,6 @@ +/// + +let body = new elasticjs.Request({}) + .query(new elasticjs.MatchQuery('title_field', 'testQuery')) + .facet(new elasticjs.TermsFacet('tags').field('tags')) + .toJSON(); diff --git a/elastic.js/elastic.js.d.ts b/elastic.js/elastic.js.d.ts new file mode 100644 index 0000000000..9bf5f6a9dc --- /dev/null +++ b/elastic.js/elastic.js.d.ts @@ -0,0 +1,8972 @@ +// Type definitions for elastic.js v1.2.0 +// Project: https://www.npmjs.com/package/elastic.js +// Definitions by: Oleksii Trekhleb +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module elasticjs { + + export interface Facet {} + export interface Geo {} + export interface Suggest {} + export interface Generator {} + export interface Query {} + export interface Filter {} + export interface Aggregation {} + export interface ScoreFunction {} + + export class AggregationMixin implements Aggregation { + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): AggregationMixin; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): AggregationMixin; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A container Filter that allows Boolean AND composition of Filters. + */ + export class AndFilter implements Filter { + + /* + A container Filter that allows Boolean AND composition of Filters. + */ + constructor(f: Filter | Filter[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): AndFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): AndFilter; + + /* + Sets the filters for the filter. If fltr is a single + Filter, it is added to the current filters. If fltr is an array + of Filters, then they replace all existing filters. + */ + filters(fltr: Filter | Filter[]): AndFilter; + + /* + Sets the filter name. + */ + name(name: string): AndFilter; + + /* + Returns the filter object. + */ + toJSON(): AndFilter; + + } + + + /* + A single-value metrics aggregation that computes the average of numeric + values that are extracted from the aggregated documents. These values can be + extracted either from specific numeric fields in the documents, or be + generated by a provided script. + */ + export class AvgAggregation implements Aggregation { + + /* + Aggregation that computes the average of numeric values that are extracted + from the aggregated documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the field to operate on. + */ + field(field: string): AvgAggregation; + + /* + The script language being used. + */ + lang(language: string): AvgAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): AvgAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): AvgAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): AvgAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A BoolFilter allows you to build Boolean filter constructs + from individual filters. Similar in concept to Boolean query, except that + the clauses are other filters. Can be placed within queries that accept a + filter. + */ + export class BoolFilter implements Filter { + + /* + A Filter that matches documents matching boolean combinations of other + filters. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): BoolFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): BoolFilter; + + /* + Adds filter to boolean container. Given filter "must" appear in + matching documents. If passed a single Filter it is added to the + list of existing filters. If passed an array of Filters, they + replace all existing filters. + */ + must(oFilter: Filter | Filter[]): BoolFilter; + + /* + Adds filter to boolean container. Given filter "must not" appear + in matching documents. If passed a single Filter it is added to + the list of existing filters. If passed an array of Filters, + they replace all existing filters. + */ + mustNot(oFilter: Filter | Filter[]): BoolFilter; + + /* + Sets the filter name. + */ + name(name: string): BoolFilter; + + /* + Adds filter to boolean container. Given filter "should" appear in + matching documents. If passed a single Filter it is added to + the list of existing filters. If passed an array of Filters, + they replace all existing filters. + */ + should(oFilter: Filter | Filter[]): BoolFilter; + + /* + Returns the filter object. + */ + toJSON(): BoolFilter; + + } + + + /* + A boolQuery allows you to build Boolean query constructs + from individual term or phrase queries. For example you might want to search + for documents containing the terms javascript and python. + */ + export class BoolQuery implements Query { + + /* + A Query that matches documents matching boolean combinations of other + queries, e.g. termQuerys, phraseQuerys or other boolQuerys. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets if the Query should be enhanced with a + MatchAllQuery in order to act as a pure exclude when + only negative (mustNot) clauses exist. Default: true. + */ + adjustPureNegative(trueFalse: string): BoolQuery; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): BoolQuery; + + /* + Enables or disables similarity coordinate scoring of documents + matching the Query. Default: false. + */ + disableCoord(trueFalse: string): BoolQuery; + + /* + Sets the number of optional clauses that must match. + + By default no optional clauses are necessary for a match + (unless there are no required clauses). If this method is used, + then the specified number of clauses is required. + + Use of this method is totally independent of specifying that + any specific clauses are required (or prohibited). This number will + only be compared against the number of matching optional clauses. + */ + minimumNumberShouldMatch(minMatch: number): BoolQuery; + + /* + Adds query to boolean container. Given query "must" appear in matching documents. + */ + must(oQuery: Object): BoolQuery; + + /* + Adds query to boolean container. Given query "must not" appear in matching documents. + */ + mustNot(oQuery: Object): BoolQuery; + + /* + Adds query to boolean container. Given query "should" appear in matching documents. + */ + should(oQuery: Object): BoolQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + The boost_factor score allows you to multiply the score by the provided + boost_factor. This can sometimes be desired since boost value set on specific + queries gets normalized, while for this score function it does not. + */ + export class BoostFactorScoreFunction implements ScoreFunction { + + /* + Multiply the score by the provided boost_factor. + */ + constructor(boostVal: number); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost factor. + */ + boost(b: number): BoostFactorScoreFunction; + + /* + Adds a filter whose matching documents will have the score function applied. + */ + filter(oFilter: Filter): BoostFactorScoreFunction; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + The boosting query can be used to effectively demote results that match + a given query. Unlike the “NOT” clause in bool query, this still selects + documents that contain undesirable terms, but reduces their overall + score. + */ + export class BoostingQuery implements Query { + + /* + Constructs a query that can demote search results. A negative boost. + */ + constructor(positiveQry: Object, negativeQry: Object, negativeBoost: number); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): BoostingQuery; + + /* + Sets the query used to match documents in the positive + query that will be negatively boosted. + */ + negative(oQuery: Object): BoostingQuery; + + /* + Sets the negative boost value. + */ + negativeBoost(boost: number): BoostingQuery; + + /* + Sets the "master" query that determines which results are returned. + */ + positive(oQuery: Object): BoostingQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A single-value metrics aggregation that calculates an approximate count of + distinct values. Values can be extracted either from specific fields in the + document or generated by a script. + */ + export class CardinalityAggregation implements Aggregation { + + /* + Aggregation that calculates an approximate count of distinct values. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the field to operate on. + */ + field(field: string): CardinalityAggregation; + + /* + The script language being used. + */ + lang(language: string): CardinalityAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): CardinalityAggregation; + + /* + Allows to trade memory for accuracy, and defines a unique count below which + counts are expected to be close to accurate. Above this value, counts might + become a bit more fuzzy. The maximum supported value is 40000, thresholds + above this number will have the same effect as a threshold of 40000. + Default value depends on the number of parent aggregations that multiple + create buckets (such as terms or histograms). + */ + precisionThreshold(num: number): CardinalityAggregation; + + /* + Set to false to disable rehashing of values. You must have computed a hash + on the client-side and stored it into your documents if you disable this. + */ + rehash(trueFalse: boolean): CardinalityAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): CardinalityAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A query that executes high-frequency terms in a optional sub-query to + prevent slow queries due to "common" terms like stopwords. + + This query basically builds two queries out of the terms in the query + string where low-frequency terms are added to a required boolean clause and + high-frequency terms are added to an optional boolean clause. The optional + clause is only executed if the required "low-frequency' clause matches. + + CommonTermsQuery has several advantages over stopword + filtering at index or query time since a term can be "classified" based on + the actual document frequency in the index and can prevent slow queries even + across domains without specialized stopword files. + */ + export class CommonTermsQuery implements Query { + + /* + A query that executes high-frequency terms in a optional sub-query. + */ + constructor(field: string, qstr: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the analyzer name used to analyze the Query object. + */ + analyzer(analyzer: string): CommonTermsQuery; + + /* + Sets the boost value for documents commoning the Query. + */ + boost(boost: Number): CommonTermsQuery; + + /* + Sets the maximum threshold/frequency to be considered a low + frequency term. Set to a value between 0 and 1. + */ + cutoffFrequency(freq: Number): CommonTermsQuery; + + /* + Enables or disables similarity coordinate scoring of documents + commoning the Query. Default: false. + */ + disableCoord(trueFalse: string): CommonTermsQuery; + + /* + Sets the field to query against. + */ + field(f: string): CommonTermsQuery; + + /* + Sets the boolean operator to be used for high frequency terms. + Default: AND + */ + highFreqOperator(op: string): CommonTermsQuery; + + /* + Sets the boolean operator to be used for low frequency terms. + Default: AND + */ + lowFreqOperator(op: string): CommonTermsQuery; + + /* + Sets the minimum number of low freq matches that need to match in + a document before that document is returned in the results. + */ + minimumShouldMatch(min: number): CommonTermsQuery; + + /* + Sets the minimum number of high freq matches that need to match in + a document before that document is returned in the results. + */ + minimumShouldMatchHighFreq(min: number): CommonTermsQuery; + + /* + Sets the minimum number of low freq matches that need to match in + a document before that document is returned in the results. + */ + minimumShouldMatchLowFreq(min: number): CommonTermsQuery; + + /* + Sets the query string. + */ + query(qstr: string): CommonTermsQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + export class CompletionSuggester implements Suggest { + + /* + A suggester that allows basic auto-complete functionality. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets analyzer used to analyze the suggest text. + */ + analyzer(analyzer: string): CompletionSuggester; + + /* + Maximum edit distance (fuzziness), defaults to 1. Automatically + enables fuzzy suggestions when set to any value. + */ + editDistance(d: number): CompletionSuggester; + + /* + Sets the field used to generate suggestions from. + */ + field(field: string): CompletionSuggester; + + /* + Enable fuzzy completions which means a can spell a word + incorrectly and still get a suggestion. + */ + fuzzy(trueFalse: boolean): CompletionSuggester; + + /* + Minimum length of the input before fuzzy suggestions are returned, defaults + to 3. Automatically enables fuzzy suggestions when set to any value. + */ + minLength(m: number): CompletionSuggester; + + /* + Minimum length of the input, which is not checked for fuzzy alternatives, defaults + to 1. Automatically enables fuzzy suggestions when set to any value. + */ + prefixLength(l: number): CompletionSuggester; + + /* + Sets the maximum number of suggestions to be retrieved from + each individual shard. + */ + shardSize(s: number): CompletionSuggester; + + /* + Sets the number of suggestions returned for each token. + */ + size(s: number): CompletionSuggester; + + /* + Sets the text to get suggestions for. If not set, the global + suggestion text will be used. + */ + text(txt: string): CompletionSuggester; + + /* + Retrieves the internal suggest object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets if transpositions should be counted as one or two changes, defaults + to true when fuzzy is enabled. Automatically enables fuzzy suggestions + when set to any value. + */ + transpositions(trueFalse: boolean): CompletionSuggester; + + /* + Sets all are measurements (like edit distance, transpositions and lengths) + in unicode code points (actual letters) instead of bytes. Automatically + enables fuzzy suggestions when set to any value. + */ + unicodeAware(trueFalse: boolean): CompletionSuggester; + + } + + + /* + A constant score query wraps another Query or + Filter and returns a constant score for each + result that is equal to the query boost. + + Note that lucene's query normalization (queryNorm) attempts + to make scores between different queries comparable. It does not + change the relevance of your query, but it might confuse you when + you look at the score of your documents and they are not equal to + the query boost value as expected. The scores were normalized by + queryNorm, but maintain the same relevance. + */ + export class ConstantScoreQuery implements Query { + + /* + Constructs a query where each documents returned by the internal + query or filter have a constant score equal to the boost factor. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): ConstantScoreQuery; + + /* + Enables caching of the filter. + */ + cache(trueFalse: boolean): ConstantScoreQuery; + + /* + Set the cache key. + */ + cacheKey(k: string): ConstantScoreQuery; + + /* + Adds the filter to apply a constant score to. + */ + filter(oFilter: Object): ConstantScoreQuery; + + /* + Adds the query to apply a constant score to. + */ + query(oQuery: Object): ConstantScoreQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A multi-bucket aggregation similar to the histogram except it can only be + applied on date values. Since dates are represented in elasticsearch + internally as long values, it is possible to use the normal histogram on + dates as well, though accuracy will be compromised. The reason for this is + in the fact that time based intervals are not fixed (think of leap years and + on the number of days in a month). For this reason, we need a special + support for time based data. From a functionality perspective, this + histogram supports the same features as the normal histogram. The main + difference is that the interval can be specified by date/time expressions. + */ + export class DateHistogramAggregation implements Aggregation { + + /* + Aggregation similar to the histogram except it can only be applied on + date values. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): DateHistogramAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): DateHistogramAggregation; + + /* + Set's the range/bounds for the histogram aggregation. Useful when you + want to include buckets that might be outside the bounds of indexed + documents. + */ + extendedBounds(min: string | number, max: string | number): DateHistogramAggregation; + + /* + Sets the field to gather terms from. + */ + field(field: string): DateHistogramAggregation; + + /* + Sets the format expression for the terms. Use for number or date + formatting + */ + format(f: string): DateHistogramAggregation; + + /* + Sets the histogram interval. Buckets are generated based on this interval + value. + */ + interval(i: string): DateHistogramAggregation; + + /* + Enable the response to be returned as a keyed object where the key is the + bucket interval. + */ + keyed(trueFalse: boolean): DateHistogramAggregation; + + /* + The script language being used. + */ + lang(language: string): DateHistogramAggregation; + + /* + Only return terms that match more than a configured number of hits. + */ + minDocCount(num: number): DateHistogramAggregation; + + /* + Sets order for the aggregated values. + */ + order(order: string, direction: string): DateHistogramAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): DateHistogramAggregation; + + /* + Set the post-rouding offset. + */ + postOffset(offset: string): DateHistogramAggregation; + + /* + Set the post-rouding date time zone. + */ + postZone(tz: string): DateHistogramAggregation; + + /* + Set the pre-rouding offset. + */ + preOffset(offset: string): DateHistogramAggregation; + + /* + Set the pre-rouding date time zone. + */ + preZone(tz: string): DateHistogramAggregation; + + /* + Set to true to apply interval adjusts to day and above intervals. + */ + preZoneAdjustLargeInterval(trueFalse: boolean): DateHistogramAggregation; + + /* + Allows you generate or modify the terms using a script. + */ + script(scriptCode: string): DateHistogramAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): DateHistogramAggregation; + + /* + Set the date time zone. + */ + timeZone(tz: string): DateHistogramAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + The DateHistogram facet works with time-based values by building a histogram across time + intervals of the value field. Each value is rounded into an interval (or + placed in a bucket), and statistics are provided per interval/bucket (count and total). + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + + + Tip: + For more information on faceted navigation, see + this + Wikipedia article on Faceted Classification. + + + */ + export class DateHistogramFacet implements Facet { + + /* + A facet which returns the N most frequent terms within a collection + or set of collections. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): DateHistogramFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): DateHistogramFacet; + + /* + The date histogram works on numeric values (since time is stored + in milliseconds since the epoch in UTC). + + But, sometimes, systems will store a different resolution (like seconds since UTC) + in a numeric field. The factor parameter can be used to change the value in the field + to milliseconds to actual do the relevant rounding, and then be applied again to get to + the original unit. + + For example, when storing in a numeric field seconds resolution, + the factor can be set to 1000. + */ + factor(f: number): DateHistogramFacet; + + /* + Sets the field to be used to construct the this facet. + */ + field(fieldName: string): DateHistogramFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): DateHistogramFacet; + + /* + Sets the bucket interval used to calculate the distribution. + */ + interval(timeInterval: string): DateHistogramFacet; + + /* + Allows you to specify a different key field to be used to group intervals. + */ + keyField(fieldName: string): DateHistogramFacet; + + /* + The script language being used. Currently supported values are + javascript, groovy, and mvel. + */ + lang(language: string): DateHistogramFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): DateHistogramFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): DateHistogramFacet; + + /* + Sets the type of ordering that will be performed on the date + buckets. Valid values are: + + + time - the default, sort by the buckets start time in milliseconds. + count - sort by the number of items in the bucket + total - sort by the sum/total of the items in the bucket + + */ + order(o: string): DateHistogramFacet; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): DateHistogramFacet; + + /* + Set's a specific post-rounding offset. Format is 1d, 1h, etc. + */ + postOffset(offset: string): DateHistogramFacet; + + /* + By default, time values are stored in UTC format. + + This method allows users to set a time zone value that is then used to compute + intervals after rounding on the interval value. The value is an offset from UTC. + The tz offset value is simply added to the resulting bucket's date value. + + For example, to use EST you would set the value to -5. + */ + postZone(tz: number): DateHistogramFacet; + + /* + Set's a specific pre-rounding offset. Format is 1d, 1h, etc. + */ + preOffset(offset: string): DateHistogramFacet; + + /* + By default, time values are stored in UTC format. + + This method allows users to set a time zone value that is then used to + compute intervals before rounding on the interval value. The value is an + offset from UTC. + + For example, to use EST you would set the value to -5. + */ + preZone(tz: number): DateHistogramFacet; + + /* + Enables large date interval conversions (day and up). + + Set to true to enable and then set the interval to an + interval greater than a day. + */ + preZoneAdjustLargeInterval(trueFalse: boolean): DateHistogramFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): DateHistogramFacet; + + /* + By default, time values are stored in UTC format. + + This method allows users to set a time zone value that is then used + to compute intervals before rounding on the interval value. Equalivent to + preZone. Use preZone if possible. The + value is an offset from UTC. + + For example, to use EST you would set the value to -5. + */ + timeZone(tz: number): DateHistogramFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Allows you to specify a different value field to aggrerate over. + */ + valueField(fieldName: string): DateHistogramFacet; + + /* + Allows you modify the value field using a script. The modified value + is then used to compute the statistical data. + */ + valueScript(scriptCode: string): DateHistogramFacet; + + } + + + /* + A range aggregation that is dedicated for date values. The main difference + between this aggregation and the normal range aggregation is that the from + and to values can be expressed in Date Math expressions, and it is also + possible to specify a date format by which the from and to response fields + will be returned. Note that this aggregration includes the from value and + excludes the to value for each range. + + Note that this aggregration includes the from value and excludes the to + value for each range. + */ + export class DateRangeAggregation implements Aggregation { + + /* + Aggregation that is dedicated for date value ranges. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): DateRangeAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): DateRangeAggregation; + + /* + Sets the field to gather terms from. + */ + field(field: string): DateRangeAggregation; + + /* + Sets the date format expression. + */ + format(f: string): DateRangeAggregation; + + /* + Enable the response to be returned as a keyed object where the key is the + bucket interval. + */ + keyed(trueFalse: boolean): DateRangeAggregation; + + /* + The script language being used. + */ + lang(language: string): DateRangeAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): DateRangeAggregation; + + /* + Adds a range to the list of exsiting range expressions. + */ + range(from: string, to: string, key: string): DateRangeAggregation; + + /* + Allows you generate or modify the terms using a script. + */ + script(scriptCode: string): DateRangeAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): DateRangeAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + Decay functions score a document with a function that decays depending on + the distance of a numeric field value of the document from a user given + origin. This is similar to a range query, but with smooth edges instead of + boxes. + + Supported decay functions are: linear, exp, and gauss. + */ + export class DecayScoreFunction implements ScoreFunction { + + /* + Score a document with a function that decays depending on the distance + of a numeric field value of the document from given origin. + */ + constructor(field: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the decay value which defines how documents are scored at the distance + given at scale. + */ + decay(d: number): DecayScoreFunction; + + /* + Use the exp decay function. Exponential decay. + */ + exp(): DecayScoreFunction; + + /* + Sets the fields to run the decay function against. + */ + field(f: string): DecayScoreFunction; + + /* + Adds a filter whose matching documents will have the score function applied. + */ + filter(oFilter: Filter): DecayScoreFunction; + + /* + Use the gauss decay function. Normal decay. + */ + gauss(): DecayScoreFunction; + + /* + Use the linear decay function. Linear decay. + */ + linear(): DecayScoreFunction; + + /* + Sets the decay offset. The decay function will only compute a the decay + function for documents with a distance greater that the defined offset. + The default is 0. + */ + offset(o: string): DecayScoreFunction; + + /* + Sets the origin which is the “central point” from which the distance is + calculated. + */ + origin(o: string): DecayScoreFunction; + + /* + Sets the scale/rate of decay. + */ + scale(s: string): DecayScoreFunction; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + DirectGenerator is a candidate generator for PhraseSuggester. + It generates terms based on edit distance and operators much like the + TermSuggester. + */ + export class DirectGenerator implements Generator { + + /* + A candidate generator that generates terms based on edit distance. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the accuracy. How similar the suggested terms at least + need to be compared to the original suggest text. + */ + accuracy(a: number): DirectGenerator; + + /* + Sets the field used to generate suggestions from. + */ + field(field: string): DirectGenerator; + + /* + Sets the maximum edit distance candidate suggestions can have + in order to be considered as a suggestion. + */ + maxEdits(max: number): DirectGenerator; + + /* + The factor that is used to multiply with the size in order + to inspect more candidate suggestions. + */ + maxInspections(max: number): DirectGenerator; + + /* + Sets a maximum threshold in number of documents a suggest text + token can exist in order to be corrected. + */ + maxTermFreq(max: number): DirectGenerator; + + /* + Sets a minimal threshold of the number of documents a suggested + term should appear in. + */ + minDocFreq(min: number): DirectGenerator; + + /* + Sets the minimum length a suggest text term must have in order + to be corrected. + */ + minWordLen(len: number): DirectGenerator; + + /* + Sets an analyzer that is applied to each of the generated tokens + before they are passed to the actual phrase scorer. + */ + postFilter(analyzer: string): DirectGenerator; + + /* + Sets an analyzer that is applied to each of the tokens passed to + this generator. The analyzer is applied to the original tokens, + not the generated tokens. + */ + preFilter(analyzer: string): DirectGenerator; + + /* + Sets the number of suggestions returned for each token. + */ + size(s: number): DirectGenerator; + + /* + Sets the sort mode. Valid values are: + + + score - Sort by score first, then document frequency, and then the term itself + frequency - Sort by document frequency first, then simlarity score and then the term itself + + */ + sort(s: string): DirectGenerator; + + /* + Sets what string distance implementation to use for comparing + how similar suggested terms are. Valid values are: + + + internal - based on damerau_levenshtein but but highly optimized for comparing string distance for terms inside the index + damerau_levenshtein - String distance algorithm based on Damerau-Levenshtein algorithm + levenstein - String distance algorithm based on Levenstein edit distance algorithm + jarowinkler - String distance algorithm based on Jaro-Winkler algorithm + ngram - String distance algorithm based on character n-grams + + */ + stringDistance(s: string): DirectGenerator; + + /* + Sets the suggest mode. Valid values are: + + + missing - Only suggest terms in the suggest text that aren't in the index + popular - Only suggest suggestions that occur in more docs then the original suggest text term + always - Suggest any matching suggestions based on terms in the suggest text + + */ + suggestMode(m: string): DirectGenerator; + + /* + Retrieves the internal generator object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + export class DirectSettingsMixin { + + + /* + Sets the accuracy. How similar the suggested terms at least + need to be compared to the original suggest text. + */ + accuracy(a: number): DirectSettingsMixin; + + /* + Sets the maximum edit distance candidate suggestions can have + in order to be considered as a suggestion. + */ + maxEdits(max: number): DirectSettingsMixin; + + /* + The factor that is used to multiply with the size in order + to inspect more candidate suggestions. + */ + maxInspections(max: number): DirectSettingsMixin; + + /* + Sets a maximum threshold in number of documents a suggest text + token can exist in order to be corrected. + */ + maxTermFreq(max: number): DirectSettingsMixin; + + /* + Sets a minimal threshold of the number of documents a suggested + term should appear in. + */ + minDocFreq(min: number): DirectSettingsMixin; + + /* + Sets the minimum length a suggest text term must have in order + to be corrected. + */ + minWordLen(len: number): DirectSettingsMixin; + + /* + Sets the number of minimal prefix characters that must match in + order be a candidate suggestion. + */ + prefixLen(len: number): DirectSettingsMixin; + + /* + Sets the sort mode. Valid values are: + + + score - Sort by score first, then document frequency, and then the term itself + frequency - Sort by document frequency first, then simlarity score and then the term itself + + */ + sort(s: string): DirectSettingsMixin; + + /* + Sets what string distance implementation to use for comparing + how similar suggested terms are. Valid values are: + + + internal - based on damerau_levenshtein but but highly optimized for comparing string distance for terms inside the index + damerau_levenshtein - String distance algorithm based on Damerau-Levenshtein algorithm + levenstein - String distance algorithm based on Levenstein edit distance algorithm + jarowinkler - String distance algorithm based on Jaro-Winkler algorithm + ngram - String distance algorithm based on character n-grams + + */ + stringDistance(s: string): DirectSettingsMixin; + + /* + Sets the suggest mode. Valid values are: + + + missing - Only suggest terms in the suggest text that aren't in the index + popular - Only suggest suggestions that occur in more docs then the original suggest text term + always - Suggest any matching suggestions based on terms in the suggest text + + */ + suggestMode(m: string): DirectSettingsMixin; + + } + + + /* + A query that generates the union of documents produced by its subqueries, and + that scores each document with the maximum score for that document as produced + by any subquery, plus a tie breaking increment for any additional matching + subqueries. + */ + export class DisMaxQuery implements Query { + + /* + A query that generates the union of documents produced by its subqueries such + as termQuerys, phraseQuerys, boolQuerys, etc. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): DisMaxQuery; + + /* + Updates the queries. If passed a single Query, it is added to the + list of existing queries. If passed an array of Queries, it + replaces all existing values. + */ + queries(qs: Query | Query[]): DisMaxQuery; + + /* + The tie breaker value. + + The tie breaker capability allows results that include the same term in multiple + fields to be judged better than results that include this term in only the best of those + multiple fields, without confusing this with the better case of two different terms in + the multiple fields. + + Default: 0.0. + */ + tieBreaker(tieBreaker: number): DisMaxQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + An existsFilter matches documents where the specified field is present + and the field contains a legitimate value. + */ + export class ExistsFilter implements Filter { + + /* + Filters documents where a specified field exists and contains a value. + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): ExistsFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): ExistsFilter; + + /* + Sets the field to check for missing values. + */ + field(name: string): ExistsFilter; + + /* + Sets the filter name. + */ + name(name: string): ExistsFilter; + + /* + Returns the filter object. + */ + toJSON(): ExistsFilter; + + } + + + /* + A multi-value metrics aggregation that computes stats over numeric values + extracted from the aggregated documents. These values can be extracted either + from specific numeric fields in the documents, or be generated by a provided + script. + + The extended_stats aggregations is an extended version of the + StatsAggregation, where additional metrics are added such as + sum_of_squares, variance and std_deviation. + */ + export class ExtendedStatsAggregation implements Aggregation { + + /* + Aggregation that computes extra stats over numeric values extracted from + the aggregated documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the field to operate on. + */ + field(field: string): ExtendedStatsAggregation; + + /* + The script language being used. + */ + lang(language: string): ExtendedStatsAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): ExtendedStatsAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): ExtendedStatsAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): ExtendedStatsAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + export class FacetMixin { + + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): FacetMixin; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): FacetMixin; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): FacetMixin; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): FacetMixin; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): FacetMixin; + + /* + Computes values across the the specified scope + */ + scope(scope: string): FacetMixin; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + Wrapper to allow SpanQuery objects participate in composite single-field + SpanQueries by 'lying' about their search field. That is, the masked + SpanQuery will function as normal, but when asked for the field it + queries against, it will return the value specified as the masked field vs. + the real field used in the wrapped span query. + */ + export class FieldMaskingSpanQuery implements Query { + + /* + Wraps a SpanQuery and hides the real field being searched across. + */ + constructor(spanQry: Query, field: number); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): FieldMaskingSpanQuery; + + /* + Sets the value of the "masked" field. + */ + field(f: string): FieldMaskingSpanQuery; + + /* + Sets the span query to wrap. + */ + query(spanQuery: Query): FieldMaskingSpanQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + Defines a single bucket of all the documents in the current document set + context that match a specified filter. Often this will be used to narrow down + the current aggregation context to a specific set of documents. + */ + export class FilterAggregation implements Aggregation { + + /* + Defines a single bucket of all the documents that match a given filter. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): FilterAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): FilterAggregation; + + /* + Sets the filter to be used for this aggregation. + */ + filter(oFilter: Filter): FilterAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + Filter queries allow you to restrict the results returned by a query. There are + several different types of filters that can be applied + (see filter module). A filterQuery + takes a Query and a Filter object as arguments and constructs + a new Query that is then used for the search. + */ + export class FilteredQuery implements Query { + + /* + A query that applies a filter to the results of another query. + */ + constructor(someQuery: Object, someFilter: Object); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): FilteredQuery; + + /* + Enables caching of the filter. + */ + cache(trueFalse: boolean): FilteredQuery; + + /* + Set the cache key. + */ + cacheKey(k: string): FilteredQuery; + + /* + Adds the filter to apply a constant score to. + */ + filter(oFilter: Object): FilteredQuery; + + /* + Adds the query to apply a constant score to. + */ + query(oQuery: Object): FilteredQuery; + + /* + Sets the filter strategy. + + The strategy defines how the filter is applied during document collection. + Valid values are: + + + query_first - advance query scorer first then filter + random_access_random - random access filter + leap_frog - query scorer and filter "leap-frog", query goes first + leap_frog_filter_first - same as leap_frog, but filter goes first + random_access_N - replace N with integer, same as random access + except you can specify a custom threshold + + + This is an advanced setting, use with care. + */ + strategy(strategy: string): FilteredQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + The FilterFacet allows you to specify any valid Filter and + have the number of matching hits returned as the value. + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + + + Tip: + For more information on faceted navigation, see + this + Wikipedia article on Faceted Classification. + + + */ + export class FilterFacet implements Facet { + + /* + A facet that return a count of the hits matching the given filter. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): FilterFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): FilterFacet; + + /* + Sets the filter to be used for this facet. + */ + filter(oFilter: Object): FilterFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): FilterFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): FilterFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): FilterFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): FilterFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + export class FilterMixin { + + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): FilterMixin; + + /* + Sets the cache key. + */ + cacheKey(key: string): FilterMixin; + + /* + Sets the filter name. + */ + name(name: string): FilterMixin; + + /* + Returns the filter object. + */ + toJSON(): FilterMixin; + + } + + + /* + The function_score allows you to modify the score of documents that are + retrieved by a query. This can be useful if, for example, a score function is + computationally expensive and it is sufficient to compute the score on a + filtered set of documents. + */ + export class FunctionScoreQuery implements Query { + + /* + A query that allows you to modify the score of matching documents. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): FunctionScoreQuery; + + /* + Set the setermines how the new calculated score is combined with the + score from the original query. Valid values are: multiply, replace, sum, + avg, max, and min. + */ + boostMode(mode: string): FunctionScoreQuery; + + /* + Set the source filter. + */ + filter(oFilter: Filter): FunctionScoreQuery; + + /* + Add a single score function to the list of existing functions. + */ + //function (func: ScoreFunction): FunctionScoreQuery; + + /* + Sets the score functions. Replaces any existing score functions. + */ + functions(funcs: ScoreFunction[]): FunctionScoreQuery; + + /* + Set the source query. + */ + query(oQuery: Query): FunctionScoreQuery; + + /* + Set the scoring mode which specifies how the computed scores are combined. + Valid values are: avg, max, min, sum, multiply, and first. + */ + scoreMode(mode: string): FunctionScoreQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + The fuzzy_like_this_field query is the same as the fuzzy_like_this + query, except that it runs against a single field. It provides nicer query + DSL over the generic fuzzy_like_this query, and support typed fields + query (automatically wraps typed fields with type filter to match only on + the specific type). + + Fuzzifies ALL terms provided as strings and then picks the best n + differentiating terms. In effect this mixes the behaviour of FuzzyQuery and + MoreLikeThis but with special consideration of fuzzy scoring factors. This + generally produces good results for queries where users may provide details + in a number of fields and have no knowledge of boolean query syntax and + also want a degree of fuzzy matching and a fast query. + + For each source term the fuzzy variants are held in a BooleanQuery with + no coord factor (because we are not looking for matches on multiple variants + in any one doc). Additionally, a specialized TermQuery is used for variants + and does not use that variant term’s IDF because this would favour rarer + terms eg misspellings. Instead, all variants use the same IDF + ranking (the one for the source query term) and this is factored into the + variant’s boost. If the source query term does not exist in the index the + average IDF of the variants is used. + */ + export class FuzzyLikeThisFieldQuery implements Query { + + /* + Constructs a query where each documents returned are “like” provided text + */ + constructor(field: string, likeText: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + The analyzer that will be used to analyze the text. Defaults to the + analyzer associated with the field. + */ + analyzer(analyzerName: string): FuzzyLikeThisFieldQuery; + + /* + Sets the boost value of the Query. + */ + boost(boost: number): FuzzyLikeThisFieldQuery; + + /* + Should the Query fail when an unsupported field + is specified. Defaults to true. + */ + failOnUnsupportedField(trueFalse: boolean): FuzzyLikeThisFieldQuery; + + /* + The field to run the query against. + */ + field(f: string): FuzzyLikeThisFieldQuery; + + /* + Should term frequency be ignored. Defaults to false. + */ + ignoreTf(trueFalse: boolean): FuzzyLikeThisFieldQuery; + + /* + The text to find documents like + */ + likeText(s: string): FuzzyLikeThisFieldQuery; + + /* + The maximum number of query terms that will be included in any + generated query. Defaults to 25. + */ + maxQueryTerms(max: number): FuzzyLikeThisFieldQuery; + + /* + The minimum similarity of the term variants. Defaults to 0.5. + */ + minSimilarity(min: number): FuzzyLikeThisFieldQuery; + + /* + Length of required common prefix on variant terms. Defaults to 0.. + */ + prefixLength(len: number): FuzzyLikeThisFieldQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + Fuzzy like this query find documents that are “like” provided text by + running it against one or more fields. + + Fuzzifies ALL terms provided as strings and then picks the best n + differentiating terms. In effect this mixes the behaviour of FuzzyQuery and + MoreLikeThis but with special consideration of fuzzy scoring factors. This + generally produces good results for queries where users may provide details + in a number of fields and have no knowledge of boolean query syntax and + also want a degree of fuzzy matching and a fast query. + + For each source term the fuzzy variants are held in a BooleanQuery with + no coord factor (because we are not looking for matches on multiple variants + in any one doc). Additionally, a specialized TermQuery is used for variants + and does not use that variant term’s IDF because this would favour rarer + terms eg misspellings. Instead, all variants use the same IDF + ranking (the one for the source query term) and this is factored into the + variant’s boost. If the source query term does not exist in the index the + average IDF of the variants is used. + */ + export class FuzzyLikeThisQuery implements Query { + + /* + Constructs a query where each documents returned are “like” provided text + */ + constructor(likeText: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + The analyzer that will be used to analyze the text. Defaults to the + analyzer associated with the field. + */ + analyzer(analyzerName: string): FuzzyLikeThisQuery; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): FuzzyLikeThisQuery; + + /* + Should the Query fail when an unsupported field + is specified. Defaults to true. + */ + failOnUnsupportedField(trueFalse: boolean): FuzzyLikeThisQuery; + + /* + The fields to run the query against. If you call with a single field, + it is added to the existing list of fields. If called with an array + of field names, it replaces any existing values with the new array. + */ + fields(f: string | string[]): FuzzyLikeThisQuery; + + /* + Should term frequency be ignored. Defaults to false. + */ + ignoreTf(trueFalse: boolean): FuzzyLikeThisQuery; + + /* + The text to find documents like + */ + likeText(s: string): FuzzyLikeThisQuery; + + /* + The maximum number of query terms that will be included in any + generated query. Defaults to 25. + */ + maxQueryTerms(max: number): FuzzyLikeThisQuery; + + /* + The minimum similarity of the term variants. Defaults to 0.5. + */ + minSimilarity(min: number): FuzzyLikeThisQuery; + + /* + Length of required common prefix on variant terms. Defaults to 0.. + */ + prefixLength(len: number): FuzzyLikeThisQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A fuzzy search query based on the Damerau-Levenshtein (optimal string + alignment) algorithm, though you can explicitly choose classic Levenshtein + by passing false to the transpositions parameter./p> + + fuzzy query on a numeric field will result in a range query “around” + the value using the min_similarity value. As an example, if you perform a + fuzzy query against a field value of "12" with a min similarity setting + of "2", the query will search for values between "10" and "14". + */ + export class FuzzyQuery implements Query { + + /* + Constructs a query where each documents returned are “like” provided text + */ + constructor(field: string, value: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value of the Query. + */ + boost(boost: number): FuzzyQuery; + + /* + The field to run the query against. + */ + field(f: string): FuzzyQuery; + + /* + The maximum number of query terms that will be included in any + generated query. Defaults to 50. + */ + maxExpansions(max: number): FuzzyQuery; + + /* + The minimum similarity of the term variants. Defaults to 0.5. + */ + minSimilarity(min: number): FuzzyQuery; + + /* + Length of required common prefix on variant terms. Defaults to 0. + */ + prefixLength(len: number): FuzzyQuery; + + /* + Sets rewrite method. Valid values are: + + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + rewrite(m: string): FuzzyQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Set to false to use classic Levenshtein edit distance. + */ + transpositions(trueFalse: boolean): FuzzyQuery; + + /* + The query text to fuzzify. + */ + value(s: string): FuzzyQuery; + + } + + + /* + A filter that restricts matched results/docs to a geographic bounding box described by + the specified lon and lat coordinates. The format conforms with the GeoJSON specification. + */ + export class GeoBboxFilter implements Filter { + + /* + Filter results to those which are contained within the defined bounding box. + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the bottom-right coordinate of the bounding box + */ + bottomRight(p: GeoPoint): GeoBboxFilter; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): GeoBboxFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): GeoBboxFilter; + + /* + Sets the fields to filter against. + */ + field(f: string): GeoBboxFilter; + + /* + Sets the filter name. + */ + name(name: string): GeoBboxFilter; + + /* + If the lat/long points should be normalized to lie within their + respective normalized ranges. + + Normalized ranges are: + lon = -180 (exclusive) to 180 (inclusive) range + lat = -90 to 90 (both inclusive) range + */ + normalize(trueFalse: string): GeoBboxFilter; + + /* + Returns the filter object. + */ + toJSON(): GeoBboxFilter; + + /* + Sets the top-left coordinate of the bounding box + */ + topLeft(p: GeoPoint): GeoBboxFilter; + + /* + Sets the type of the bounding box execution. Valid values are + "memory" and "indexed". Default is memory. + */ + type(type: string): GeoBboxFilter; + + } + + + /* + A multi-bucket aggregation that works on geo_point fields and conceptually + works very similar to the range aggregation. The user can define a point of + origin and a set of distance range buckets. The aggregation evaluate the + distance of each document value from the origin point and determines the + buckets it belongs to based on the ranges (a document belongs to a bucket + if the distance between the document and the origin falls within the distance + range of the bucket). + */ + export class GeoDistanceAggregation implements Aggregation { + + /* + Aggregation that works on geo_point fields and conceptually works very + similar to the range aggregation. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): GeoDistanceAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): GeoDistanceAggregation; + + /* + Sets the point of origin from where distances will be measured. Same as + origin. + */ + center(p: GeoPoint): GeoDistanceAggregation; + + /* + How to compute the distance. Valid values are: + plane, arc, sloppy_arc, and factor. + */ + distanceType(type: string): GeoDistanceAggregation; + + /* + Sets the field to gather terms from. + */ + field(field: string): GeoDistanceAggregation; + + /* + Enable the response to be returned as a keyed object where the key is the + bucket interval. + */ + keyed(trueFalse: boolean): GeoDistanceAggregation; + + /* + Sets the point of origin from where distances will be measured. + */ + origin(p: GeoPoint): GeoDistanceAggregation; + + /* + Sets the point of origin from where distances will be measured. Same as + origin. + */ + point(p: GeoPoint): GeoDistanceAggregation; + + /* + Adds a range to the list of exsiting range expressions. + */ + range(from: string, to: string, key: string): GeoDistanceAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets the distance unit. Valid values are: + in, yd, ft, km, NM, mm, cm, mi, and m. + */ + unit(unit: Number): GeoDistanceAggregation; + + } + + + /* + The geoDistanceFacet facet provides information over a range of distances from a + provided point. This includes the number of hits that fall within each range, + along with aggregate information (like total). + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + + + Tip: + For more information on faceted navigation, see + this + Wikipedia article on Faceted Classification. + + + */ + export class GeoDistanceFacet implements Facet { + + /* + A facet which provides information over a range of distances from a provided point. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Adds a new bounded range. + */ + addRange(from: Number, to: Number): GeoDistanceFacet; + + /* + Adds a new unbounded lower limit. + */ + addUnboundedFrom(from: Number): GeoDistanceFacet; + + /* + Adds a new unbounded upper limit. + */ + addUnboundedTo(to: Number): GeoDistanceFacet; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): GeoDistanceFacet; + + /* + How to compute the distance. Can either be arc (better precision) + or plane (faster). Defaults to arc. + */ + distanceType(type: string): GeoDistanceFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): GeoDistanceFacet; + + /* + Sets the document field containing the geo-coordinate to be used + to calculate the distance. Defaults to "location". + */ + field(fieldName: string): GeoDistanceFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): GeoDistanceFacet; + + /* + The script language being used. Currently supported values are + javascript, groovy, and mvel. + */ + lang(language: string): GeoDistanceFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): GeoDistanceFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): GeoDistanceFacet; + + /* + If the lat/long points should be normalized to lie within their + respective normalized ranges. + + Normalized ranges are: + lon = -180 (exclusive) to 180 (inclusive) range + lat = -90 to 90 (both inclusive) range + */ + normalize(trueFalse: string): GeoDistanceFacet; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): GeoDistanceFacet; + + /* + Sets the point of origin from where distances will be measured. + */ + point(p: GeoPoint): GeoDistanceFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): GeoDistanceFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets the distance unit. Valid values are "mi" for miles or "km" + for kilometers. Defaults to "km". + */ + unit(unit: Number): GeoDistanceFacet; + + /* + Allows you to specify a different value field to aggrerate over. + */ + valueField(fieldName: string): GeoDistanceFacet; + + /* + Allows you modify the value field using a script. The modified value + is then used to compute the statistical data. + */ + valueScript(scriptCode: string): GeoDistanceFacet; + + } + + + /* + A filter that restricts matched results/docs to a given distance from the + point of origin. The format conforms with the GeoJSON specification. + */ + export class GeoDistanceFilter implements Filter { + + /* + Filter results to those which fall within the given distance of the point of origin. + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): GeoDistanceFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): GeoDistanceFilter; + + /* + Sets the numeric distance to be used. The distance can be a + numeric value, and then the unit (either mi or km can be set) + controlling the unit. Or a single string with the unit as well. + */ + distance(numericDistance: Number): GeoDistanceFilter; + + /* + How to compute the distance. Can either be arc (better precision) + or plane (faster). Defaults to arc. + */ + distanceType(type: string): GeoDistanceFilter; + + /* + Sets the fields to filter against. + */ + field(f: string): GeoDistanceFilter; + + /* + Sets the filter name. + */ + name(name: string): GeoDistanceFilter; + + /* + If the lat/long points should be normalized to lie within their + respective normalized ranges. + + Normalized ranges are: + lon = -180 (exclusive) to 180 (inclusive) range + lat = -90 to 90 (both inclusive) range + */ + normalize(trueFalse: string): GeoDistanceFilter; + + /* + Will an optimization of using first a bounding box check will be + used. Defaults to memory which will do in memory checks. Can also + have values of indexed to use indexed value check, or none which + disables bounding box optimization. + */ + optimizeBbox(t: string): GeoDistanceFilter; + + /* + Sets the point of origin in which distance will be measured from + */ + point(p: GeoPoint): GeoDistanceFilter; + + /* + Returns the filter object. + */ + toJSON(): GeoDistanceFilter; + + /* + Sets the distance unit. Valid values are "mi" for miles or "km" + for kilometers. Defaults to "km". + */ + unit(unit: Number): GeoDistanceFilter; + + } + + + /* + A filter that restricts matched results/docs to a given distance range from the + point of origin. The format conforms with the GeoJSON specification. + */ + export class GeoDistanceRangeFilter implements Filter { + + /* + Filter results to those which fall within the given distance range of the point of origin. + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): GeoDistanceRangeFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): GeoDistanceRangeFilter; + + /* + How to compute the distance. Can either be arc (better precision) + or plane (faster). Defaults to arc. + */ + distanceType(type: string): GeoDistanceRangeFilter; + + /* + Sets the fields to filter against. + */ + field(f: string): GeoDistanceRangeFilter; + + /* + Sets the start point of the distance range + */ + from(numericDistance: Number): GeoDistanceRangeFilter; + + /* + Greater than value. Same as setting from to the value, and + include_lower to false, + */ + gt(val: Number): GeoDistanceRangeFilter; + + /* + Greater than or equal to value. Same as setting from to the value, + and include_lower to true. + */ + gte(val: Number): GeoDistanceRangeFilter; + + /* + Should the first from (if set) be inclusive or not. + Defaults to true + */ + includeLower(trueFalse: boolean): GeoDistanceRangeFilter; + + /* + Should the last to (if set) be inclusive or not. Defaults to true. + */ + includeUpper(trueFalse: boolean): GeoDistanceRangeFilter; + + /* + Less than value. Same as setting to to the value, and include_upper + to false. + */ + lt(val: Number): GeoDistanceRangeFilter; + + /* + Less than or equal to value. Same as setting to to the value, + and include_upper to true. + */ + lte(val: Number): GeoDistanceRangeFilter; + + /* + Sets the filter name. + */ + name(name: string): GeoDistanceRangeFilter; + + /* + If the lat/long points should be normalized to lie within their + respective normalized ranges. + + Normalized ranges are: + lon = -180 (exclusive) to 180 (inclusive) range + lat = -90 to 90 (both inclusive) range + */ + normalize(trueFalse: string): GeoDistanceRangeFilter; + + /* + Will an optimization of using first a bounding box check will be + used. Defaults to memory which will do in memory checks. Can also + have values of indexed to use indexed value check, or none which + disables bounding box optimization. + */ + optimizeBbox(t: string): GeoDistanceRangeFilter; + + /* + Sets the point of origin in which distance will be measured from + */ + point(p: GeoPoint): GeoDistanceRangeFilter; + + /* + Sets the end point of the distance range + */ + to(numericDistance: Number): GeoDistanceRangeFilter; + + /* + Returns the filter object. + */ + toJSON(): GeoDistanceRangeFilter; + + /* + Sets the distance unit. Valid values are "mi" for miles or "km" + for kilometers. Defaults to "km". + */ + unit(unit: Number): GeoDistanceRangeFilter; + + } + + + /* + A multi-bucket aggregation that works on geo_point fields and groups points + into buckets that represent cells in a grid. The resulting grid can be sparse + and only contains cells that have matching data. Each cell is labeled using a + geohash which is of user-definable precision. + */ + export class GeoHashGridAggregation implements Aggregation { + + /* + Aggregation that works on geo_point fields and groups points into buckets + that represent cells in a grid. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): GeoHashGridAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): GeoHashGridAggregation; + + /* + Sets the geo field to perform calculations from. + */ + field(field: string): GeoHashGridAggregation; + + /* + Sets the Geo Hash precision. The precision value can be between 1 and 12 + where 12 is the highest precision. + */ + precision(p: number): GeoHashGridAggregation; + + /* + Determines how many geohash_grid the coordinating node will request from + each shard. + */ + shardSize(shardSize: number): GeoHashGridAggregation; + + /* + Sets the number of aggregation entries that will be returned. + */ + size(size: number): GeoHashGridAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A GeoPoint object that can be used in queries and filters that + take a GeoPoint. GeoPoint supports various input formats. + + See http://www.elasticsearch.org/guide/reference/mapping/geo-point-type.html + */ + export class GeoPoint implements Geo { + + /* + Defines a point + */ + constructor(p: any[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the GeoPoint from an array point. The array must contain only + 2 values. The first value is the lat and the 2nd value is the lon. + + Example: + [41.12, -71.34] + */ + array(a: any[]): GeoPoint; + + /* + Sets the GeoPoint as a GeoHash. The hash is a string of + alpha-numeric characters with a precision length that defaults to 12. + + Example: + "drm3btev3e86" + */ + geohash(hash: string, precision: number): GeoPoint; + + /* + Sets the GeoPoint as properties on an object. The object must have + a 'lat' and 'lon' or a 'geohash' property. + + Example: + {lat: 41.12, lon: -71.34} or {geohash: "drm3btev3e86"} + */ + properties(obj: Object): GeoPoint; + + /* + Sets the GeoPoint as a string. The format is "lat,lon". + + Example: + + "41.12,-71.34" + */ + string(s: string): GeoPoint; + + /* + Retrieves the internal script object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A filter for locating documents that fall within a polygon of points. Simply provide a lon/lat + for each document as a Geo Point type. The format conforms with the GeoJSON specification. + */ + export class GeoPolygonFilter { + + /* + Filter results to those which are contained within the polygon of points. + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): GeoPolygonFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): GeoPolygonFilter; + + /* + Sets the fields to filter against. + */ + field(f: string): GeoPolygonFilter; + + /* + Sets the filter name. + */ + name(name: string): GeoPolygonFilter; + + /* + If the lat/long points should be normalized to lie within their + respective normalized ranges. + + Normalized ranges are: + lon = -180 (exclusive) to 180 (inclusive) range + lat = -90 to 90 (both inclusive) range + */ + normalize(trueFalse: string): GeoPolygonFilter; + + /* + Sets a series of points that represent a polygon. If passed a + single GeoPoint object, it is added to the current + list of points. If passed an array of GeoPoint + objects it replaces all current values. + */ + points(pointsArray: any[]): GeoPolygonFilter; + + /* + Returns the filter object. + */ + toJSON(): GeoPolygonFilter; + + } + + + /* + Efficient filtering of documents containing shapes indexed using the + geo_shape type. + + Much like the geo_shape type, the geo_shape filter uses a grid square + representation of the filter shape to find those documents which have shapes + that relate to the filter shape in a specified way. In order to do this, the + field being queried must be of geo_shape type. The filter will use the same + PrefixTree configuration as defined for the field. + */ + export class GeoShapeFilter implements Filter { + + /* + A Filter to find documents with a geo_shapes matching a specific shape. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): GeoShapeFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): GeoShapeFilter; + + /* + Sets the field to filter against. + */ + field(f: string): GeoShapeFilter; + + /* + Sets the indexed shape. Use this if you already have shape definitions + already indexed. + */ + indexedShape(indexedShape: string): GeoShapeFilter; + + /* + Sets the filter name. + */ + name(name: string): GeoShapeFilter; + + /* + Sets the shape relation type. A relationship between a Query Shape + and indexed Shapes that will be used to determine if a Document + should be matched or not. Valid values are: intersects, disjoint, + and within. + */ + relation(indexedShape: string): GeoShapeFilter; + + /* + Sets the shape + */ + shape(shape: string): GeoShapeFilter; + + /* + Sets the spatial strategy. + Valid values are: + + + recursive - default, recursively traverse nodes in + the spatial prefix tree. This strategy has support for + searching non-point shapes. + term - uses a large TermsFilter on each node + in the spatial prefix tree. It only supports the search of + indexed Point shapes. + + + This is an advanced setting, use with care. + */ + strategy(strategy: string): GeoShapeFilter; + + /* + Returns the filter object. + */ + toJSON(): GeoShapeFilter; + + } + + + /* + Efficient querying of documents containing shapes indexed using the + geo_shape type. + + Much like the geo_shape type, the geo_shape query uses a grid square + representation of the query shape to find those documents which have shapes + that relate to the query shape in a specified way. In order to do this, the + field being queried must be of geo_shape type. The query will use the same + PrefixTree configuration as defined for the field. + */ + export class GeoShapeQuery implements Query { + + /* + A Query to find documents with a geo_shapes matching a specific shape. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: Number): GeoShapeQuery; + + /* + Sets the field to query against. + */ + field(f: string): GeoShapeQuery; + + /* + Sets the indexed shape. Use this if you already have shape definitions + already indexed. + */ + indexedShape(indexedShape: string): GeoShapeQuery; + + /* + Sets the shape relation type. A relationship between a Query Shape + and indexed Shapes that will be used to determine if a Document + should be matched or not. Valid values are: intersects, disjoint, + and within. + */ + relation(indexedShape: string): GeoShapeQuery; + + /* + Sets the shape + */ + shape(shape: string): GeoShapeQuery; + + /* + Sets the spatial strategy. + Valid values are: + + + recursive - default, recursively traverse nodes in + the spatial prefix tree. This strategy has support for + searching non-point shapes. + term - uses a large TermsFilter on each node + in the spatial prefix tree. It only supports the search of + indexed Point shapes. + + + This is an advanced setting, use with care. + */ + strategy(strategy: string): GeoShapeQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + Defines a single bucket of all the documents within the search execution + context. This context is defined by the indices and the document types you’re + searching on, but is not influenced by the search query itself. + */ + export class GlobalAggregation implements Aggregation { + + /* + Defines a single bucket of all the documents within the search context. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): GlobalAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): GlobalAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + The has_child filter results in parent documents that have child docs + matching the query being returned. + */ + export class HasChildFilter implements Filter { + + /* + Returns results that have child documents matching the filter. + */ + constructor(qry: Object, type: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): HasChildFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): HasChildFilter; + + /* + Sets the filter + */ + filter(f: Query): HasChildFilter; + + /* + Sets the filter name. + */ + name(name: string): HasChildFilter; + + /* + Sets the query + */ + query(q: Query): HasChildFilter; + + /* + Sets the scope of the filter. A scope allows to run facets on the + same scope name that will work against the child documents. + */ + scope(s: string): HasChildFilter; + + /* + Sets the cutoff value to short circuit processing. + */ + shortCircuitCutoff(cutoff: number): HasChildFilter; + + /* + Returns the filter object. + */ + toJSON(): HasChildFilter; + + /* + Sets the child document type to search against + */ + type(t: string): HasChildFilter; + + } + + + /* + The has_child query works the same as the has_child filter, + by automatically wrapping the filter with a constant_score. Results in + parent documents that have child docs matching the query being returned. + */ + export class HasChildQuery implements Query { + + /* + Returns results that have child documents matching the query. + */ + constructor(qry: Object, type: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): HasChildQuery; + + /* + Sets the query + */ + query(q: Object): HasChildQuery; + + /* + Sets the scope of the query. A scope allows to run facets on the + same scope name that will work against the child documents. + */ + scope(s: string): HasChildQuery; + + /* + Sets the scoring method. Valid values are: + + none - the default, no scoring + max - the highest score of all matched child documents is used + sum - the sum the all the matched child documents is used + avg - the average of all matched child documents is used + */ + scoreMode(s: string): HasChildQuery; + + /* + Sets the scoring method. Valid values are: + + none - the default, no scoring + max - the highest score of all matched child documents is used + sum - the sum the all the matched child documents is used + avg - the average of all matched child documents is used + */ + scoreType(s: string): HasChildQuery; + + /* + Sets the cutoff value to short circuit processing. + */ + shortCircuitCutoff(cutoff: number): HasChildQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets the child document type to search against + */ + type(t: string): HasChildQuery; + + } + + + /* + The has_parent results in child documents that have parent docs matching + the query being returned. + */ + export class HasParentFilter implements Filter { + + /* + Returns results that have parent documents matching the filter. + */ + constructor(qry: Object, parentType: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): HasParentFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): HasParentFilter; + + /* + Sets the filter + */ + filter(f: Object): HasParentFilter; + + /* + Sets the filter name. + */ + name(name: string): HasParentFilter; + + /* + Sets the child document type to search against + */ + parentType(t: string): HasParentFilter; + + /* + Sets the query + */ + query(q: Object): HasParentFilter; + + /* + Sets the scope of the filter. A scope allows to run facets on the + same scope name that will work against the parent documents. + */ + scope(s: string): HasParentFilter; + + /* + Returns the filter object. + */ + toJSON(): HasParentFilter; + + } + + + /* + The has_parent query works the same as the has_parent filter, by + automatically wrapping the filter with a constant_score. Results in + child documents that have parent docs matching the query being returned. + */ + export class HasParentQuery implements Query { + + /* + Returns results that have parent documents matching the query. + */ + constructor(qry: Object, parentType: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): HasParentQuery; + + /* + Sets the child document type to search against + */ + parentType(t: string): HasParentQuery; + + /* + Sets the query + */ + query(q: Object): HasParentQuery; + + /* + Sets the scope of the query. A scope allows to run facets on the + same scope name that will work against the parent documents. + */ + scope(s: string): HasParentQuery; + + /* + Sets the scoring method. Valid values are: + + none - the default, no scoring + score - the score of the parent is used in all child documents. + */ + scoreMode(s: string): HasParentQuery; + + /* + Sets the scoring method. Valid values are: + + none - the default, no scoring + score - the score of the parent is used in all child documents. + */ + scoreType(s: string): HasParentQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + Allows to highlight search results on one or more fields. In order to + perform highlighting, the actual content of the field is required. If the + field in question is stored (has store set to yes in the mapping), it will + be used, otherwise, the actual _source will be loaded and the relevant + field will be extracted from it. + + If no term_vector information is provided (by setting it to + with_positions_offsets in the mapping), then the plain highlighter will be + used. If it is provided, then the fast vector highlighter will be used. + When term vectors are available, highlighting will be performed faster at + the cost of bigger index size. + + See http://www.elasticsearch.org/guide/reference/api/search/highlighting.html + */ + export class Highlight { + + /* + Allows to highlight search results on one or more fields. + */ + constructor(fields: string | string[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Set's the boundary characters. When highlighting a field that is + mapped with term vectors, boundary_chars can be configured to + define what constitutes a boundary for highlighting. It’s a single + string with each boundary character defined in it. You can apply + the option to a specific field by passing the field name in to + the oField parameter. It defaults to ".,!? \t\n". + */ + boundaryChars(charStr: string, oField: string): Highlight; + + /* + Sets the max number of characters to scan while looking for the + start of a boundary character. You can apply the option to a + specific field by passing the field name in to the + oField parameter. Default: 20 + */ + boundaryMaxScan(cnt: number, oField: string): Highlight; + + /* + Sets highlight encoder. Valid values are: + + default - the default, no encoding + html - to encode html characters if you use html tags + */ + encoder(e: string): Highlight; + + /* + Allows you to set the fields that will be highlighted. You can + specify a single field or an array of fields. All fields are + added to the current list of fields. + */ + fields(vals: string | string[]): Highlight; + + /* + Sets the fragmenter type. You can apply the option + to a specific field by passing the field name in to the + oField parameter. Valid values for order are: + + simple - breaks text up into same-size fragments with no concerns + over spotting sentence boundaries. + span - breaks text up into same-size fragments but does not split + up Spans. + */ + fragmenter(f: string, oField: string): Highlight; + + /* + Sets the size of each highlight fragment in characters. + You can apply the option to a specific field by passing the field + name in to the oField parameter. Default: 100 + */ + fragmentSize(size: number, oField: string): Highlight; + + /* + Enables highlights in documents matched by a filter. + You can apply the option to a specific field by passing the field + name in to the oField parameter. Defaults to false. + */ + highlightFilter(trueFalse: boolean, oField: string): Highlight; + + /* + Sets the number of highlight fragments. + You can apply the option to a specific field by passing the field + name in to the oField parameter. Default: 5 + */ + numberOfFragments(cnt: number, oField: string): Highlight; + + /* + Sets arbitrary options that can be passed to the highlighter + implementation in use. + */ + options(opts: string, oField: string): Highlight; + + /* + Sets the order of highlight fragments. You can apply the option + to a specific field by passing the field name in to the + oField parameter. Valid values for order are: + + score - the score calculated by Lucene's highlighting framework. + */ + order(o: string, oField: string): Highlight; + + /* + Sets the post tags for highlighted fragments. You can apply the + tags to a specific field by passing the field name in to the + oField parameter. + */ + postTags(tags: string | string[], oField: string): Highlight; + + /* + Sets the pre tags for highlighted fragments. You can apply the + tags to a specific field by passing the field name in to the + oField parameter. + */ + preTags(tags: string | string[], oField: string): Highlight; + + /* + When enabled it will cause a field to be highlighted only if a + query matched that field. false means that terms are highlighted + on all requested fields regardless if the query matches + specifically on them. You can apply the option to a specific + field by passing the field name in to the oField + parameter. Defaults to false. + */ + requireFieldMatch(trueFalse: boolean, oField: string): Highlight; + + /* + Sets the schema to be used for the tags. Valid values are: + + styled - 10 pre tags with css class of hltN, where N is 1-10 + */ + tagsSchema(s: string): Highlight; + + /* + Retrieves the internal script object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets the highligher type. You can apply the option + to a specific field by passing the field name in to the + oField parameter. Valid values for order are: + + fast-vector-highlighter - the fast vector based highligher + highlighter - the slower plain highligher + */ + type(t: string, oField: string): Highlight; + + } + + + /* + A multi-bucket values source based aggregation that can be applied on + numeric values extracted from the documents. It dynamically builds fixed + size (a.k.a. interval) buckets over the values. + */ + export class HistogramAggregation implements Aggregation { + + /* + Aggregation that can be applied on numeric values extracted from the + documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): HistogramAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): HistogramAggregation; + + /* + Set's the range/bounds for the histogram aggregation. Useful when you + want to include buckets that might be outside the bounds of indexed + documents. + */ + extendedBounds(min: number, max: number): HistogramAggregation; + + /* + Sets the field to gather terms from. + */ + field(field: string): HistogramAggregation; + + /* + Sets the format expression for the terms. Use for number or date + formatting + */ + format(f: string): HistogramAggregation; + + /* + Sets the histogram interval. Buckets are generated based on this interval + value. + */ + interval(i: number): HistogramAggregation; + + /* + Enable the response to be returned as a keyed object where the key is the + bucket interval. + */ + keyed(trueFalse: boolean): HistogramAggregation; + + /* + The script language being used. + */ + lang(language: string): HistogramAggregation; + + /* + Only return terms that match more than a configured number of hits. + */ + minDocCount(num: number): HistogramAggregation; + + /* + Sets order for the aggregated values. + */ + order(order: string, direction: string): HistogramAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): HistogramAggregation; + + /* + Allows you generate or modify the terms using a script. + */ + script(scriptCode: string): HistogramAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): HistogramAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + The histogram facet works with numeric data by building a histogram across intervals + of the field values. Each value is rounded into an interval (or placed in a + bucket), and statistics are provided per interval/bucket (count and total). + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + + + Tip: + For more information on faceted navigation, see + this + Wikipedia article on Faceted Classification. + + + */ + export class HistogramFacet implements Facet { + + /* + A facet which returns the N most frequent terms within a collection + or set of collections. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): HistogramFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): HistogramFacet; + + /* + Sets the field to be used to construct the this facet. + */ + field(fieldName: string): HistogramFacet; + + /* + Sets the "from", "start", or lower bounds bucket. For example if + you have a value of 1023, an interval of 100, and a from value of + 1500, it will be placed into the 1500 bucket vs. the normal bucket + of 1000. + */ + from(from: Number): HistogramFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): HistogramFacet; + + /* + Sets the bucket interval used to calculate the distribution. + */ + interval(numericInterval: Number): HistogramFacet; + + /* + Allows you to specify a different key field to be used to group intervals. + */ + keyField(fieldName: string): HistogramFacet; + + /* + Allows you modify the key field using a script. The modified value + is then used to generate the interval. + */ + keyScript(scriptCode: string): HistogramFacet; + + /* + The script language being used. Currently supported values are + javascript, groovy, and mvel. + */ + lang(language: string): HistogramFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): HistogramFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): HistogramFacet; + + /* + Sets the type of ordering that will be performed on the date + buckets. Valid values are: + + key - the default, sort by the bucket's key value + count - sort by the number of items in the bucket + total - sort by the sum/total of the items in the bucket + */ + order(o: string): HistogramFacet; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): HistogramFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): HistogramFacet; + + /* + Sets the bucket interval used to calculate the distribution based + on a time value such as "1d", "1w", etc. + */ + timeInterval(timeInterval: Number): HistogramFacet; + + /* + Sets the "to", "end", or upper bounds bucket. For example if + you have a value of 1023, an interval of 100, and a to value of + 900, it will be placed into the 900 bucket vs. the normal bucket + of 1000. + */ + to(to: Number): HistogramFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Allows you to specify a different value field to aggrerate over. + */ + valueField(fieldName: string): HistogramFacet; + + /* + Allows you modify the value field using a script. The modified value + is then used to compute the statistical data. + */ + valueScript(scriptCode: string): HistogramFacet; + + } + + + /* + Filters documents that only have the provided ids. Note, this filter + does not require the _id field to be indexed since it works using the + _uid field. + */ + export class IdsFilter implements Filter { + + /* + Matches documents with the specified id(s). + */ + constructor(ids: string | string[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): IdsFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): IdsFilter; + + /* + Sets the filter name. + */ + name(name: string): IdsFilter; + + /* + Returns the filter object. + */ + toJSON(): IdsFilter; + + /* + Sets the type as a single type or an array of types. If type is a + string, it is added to the list of existing types. If type is an + array, it is set as the types and overwrites an existing types. This + parameter is optional. + */ + type(type: string | string[]): IdsFilter; + + /* + Sets the values array or adds a new value. if val is a string, it + is added to the list of existing document ids. If val is an + array it is set as the document values and replaces any existing values. + */ + values(val: string | string[]): IdsFilter; + + } + + + /* + Filters documents that only have the provided ids. Note, this filter + does not require the _id field to be indexed since it works using the + _uid field. + */ + export class IdsQuery implements Query { + + /* + Matches documents with the specified id(s). + */ + constructor(ids: string | string[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): IdsQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets the type as a single type or an array of types. If type is a + string, it is added to the list of existing types. If type is an + array, it is set as the types and overwrites an existing types. This + parameter is optional. + */ + type(type: string | string[]): IdsQuery; + + /* + Sets the values array or adds a new value. if val is a string, it + is added to the list of existing document ids. If val is an + array it is set as the document values and replaces any existing values. + */ + values(val: string | string[]): IdsQuery; + + } + + + /* + A shape which has already been indexed in another index and/or index + type. This is particularly useful for when you have a pre-defined list of + shapes which are useful to your application and you want to reference this + using a logical name (for example ‘New Zealand’) rather than having to + provide their coordinates each time. + */ + export class IndexedShape implements Geo { + + /* + Defines a shape that already exists in an index/type. + */ + constructor(type: string, id: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the document id of the indexed shape. + */ + id(id: string): IndexedShape; + + /* + Sets the index which the shape is indexed under. + Defaults to "shapes". + */ + index(idx: string): IndexedShape; + + /* + Sets the field name containing the indexed shape. + Defaults to "shape". + */ + shapeFieldName(field: string): IndexedShape; + + /* + Retrieves the internal script object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets the type which the shape is indexed under. + */ + type(t: string): IndexedShape; + + } + + + /* + The indices filter can be used when executed across multiple indices, + allowing to have a filter that executes only when executed on an index that + matches a specific list of indices, and another filter that executes when it + is executed on an index that does not match the listed indices. + */ + export class IndicesFilter implements Filter { + + /* + A configurable filter that is dependent on the index name. + */ + constructor(fltr: Object, indices: string | string[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): IndicesFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): IndicesFilter; + + /* + Sets the filter to be used when executing on one of the indicies + specified. + */ + filter(f: Object): IndicesFilter; + + /* + Sets the indicies the filter should match. When passed a string, + the index name is added to the current list of indices. When passed + an array, it overwites all current indices. + */ + indices(i: string | string[]): IndicesFilter; + + /* + Sets the filter name. + */ + name(name: string): IndicesFilter; + + /* + Sets the filter to be used on an index that does not match an index + name in the indices list. Can also be set to "none" to not match any + documents or "all" to match all documents. + */ + noMatchFilter(f: Filter | string): IndicesFilter; + + /* + Returns the filter object. + */ + toJSON(): IndicesFilter; + + } + + + /* + The indices query can be used when executed across multiple indices, + allowing to have a query that executes only when executed on an index that + matches a specific list of indices, and another query that executes when it + is executed on an index that does not match the listed indices. + */ + export class IndicesQuery implements Query { + + /* + A configurable query that is dependent on the index name. + */ + constructor(qry: Query, indices: string | string[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): IndicesQuery; + + /* + Sets the indicies the query should match. When passed a string, + the index name is added to the current list of indices. When passed + an array, it overwites all current indices. + */ + indices(i: string | string[]): IndicesQuery; + + /* + Sets the query to be used on an index that does not match an index + name in the indices list. Can also be set to "none" to not match any + documents or "all" to match all documents. + */ + noMatchQuery(q: Query | string): IndicesQuery; + + /* + Sets the query to be executed against the indices specified. + */ + query(q: Query): IndicesQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A dedicated range aggregation for IPv4 typed fields. + + Note that this aggregration includes the from value and excludes the to + value for each range. + */ + export class IPv4RangeAggregation implements Aggregation { + + /* + A dedicated range aggregation for IPv4 typed fields. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): IPv4RangeAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): IPv4RangeAggregation; + + /* + Sets the field to gather terms from. + */ + field(field: string): IPv4RangeAggregation; + + /* + Enable the response to be returned as a keyed object where the key is the + bucket interval. + */ + keyed(trueFalse: boolean): IPv4RangeAggregation; + + /* + The script language being used. + */ + lang(language: string): IPv4RangeAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): IPv4RangeAggregation; + + /* + Adds a range to the list of exsiting range expressions. + */ + range(from: string, to: string, key: string): IPv4RangeAggregation; + + /* + Allows you generate or modify the terms using a script. + */ + script(scriptCode: string): IPv4RangeAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): IPv4RangeAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A limit filter limits the number of documents (per shard) to execute on. + */ + export class LimitFilter implements Filter { + + /* + Limits the number of documents to execute on. + */ + constructor(limit: number); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): LimitFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): LimitFilter; + + /* + Sets the filter name. + */ + name(name: string): LimitFilter; + + /* + Returns the filter object. + */ + toJSON(): LimitFilter; + + /* + Sets the limit value. + */ + value(val: number): LimitFilter; + + } + + + /* + This filter can be used to match on all the documents + in a given set of collections and/or types. + */ + export class MatchAllFilter implements Filter { + + /* + A filter that matches on all documents + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): MatchAllFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): MatchAllFilter; + + /* + Sets the filter name. + */ + name(name: string): MatchAllFilter; + + /* + Returns the filter object. + */ + toJSON(): MatchAllFilter; + + } + + + /* + This query can be used to match all the documents + in a given set of collections and/or types. + */ + export class MatchAllQuery implements Query { + + /* + A query that returns all documents. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): MatchAllQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A MatchQuery is a type of Query that accepts + text/numerics/dates, analyzes it, generates a query based on the + MatchQuery type. + */ + export class MatchQuery implements Query { + + /* + A Query that appects text, analyzes it, generates internal query based + on the MatchQuery type. + */ + constructor(field: string, qstr: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the analyzer name used to analyze the Query object. + */ + analyzer(analyzer: string): MatchQuery; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: Number): MatchQuery; + + /* + Sets the maximum threshold/frequency to be considered a low + frequency term in a CommonTermsQuery. + Set to a value between 0 and 1. + */ + cutoffFrequency(freq: Number): MatchQuery; + + /* + Sets the fuzziness value for the Query. + */ + fuzziness(fuzz: number): MatchQuery; + + /* + Sets fuzzy rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + fuzzyRewrite(m: string): MatchQuery; + + /* + Set to false to use classic Levenshtein edit distance in the + fuzzy query. + */ + fuzzyTranspositions(trueFalse: boolean): MatchQuery; + + /* + Enables lenient parsing of the query string. + */ + lenient(trueFalse: boolean): MatchQuery; + + /* + Sets the max expansions of a fuzzy MatchQuery. + */ + maxExpansions(e: number): MatchQuery; + + /* + Sets a percent value controlling how many "should" clauses in the + resulting Query should match. + */ + minimumShouldMatch(minMatch: number): MatchQuery; + + /* + Sets default operator of the Query. Default: or. + */ + operator(op: string): MatchQuery; + + /* + Sets the prefix length for a fuzzy prefix MatchQuery. + */ + prefixLength(l: number): MatchQuery; + + /* + Sets the query string for the Query. + */ + query(qstr: string): MatchQuery; + + /* + Sets rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + rewrite(m: string): MatchQuery; + + /* + Sets the default slop for phrases. If zero, then exact phrase matches + are required. Default: 0. + */ + slop(slop: number): MatchQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets the type of the MatchQuery. Valid values are + boolean, phrase, and phrase_prefix. + */ + type(type: string): MatchQuery; + + /* + Sets what happens when no terms match. Valid values are + "all" or "none". + */ + zeroTermsQuery(q: string): MatchQuery; + + } + + + /* + A single-value metrics aggregation that keeps track and returns the + maximum value among the numeric values extracted from the aggregated + documents. These values can be extracted either from specific numeric fields + in the documents, or be generated by a provided script. + */ + export class MaxAggregation implements Aggregation { + + /* + Aggregation that keeps track and returns the maximum value among the + numeric values extracted from the aggregated documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the field to operate on. + */ + field(field: string): MaxAggregation; + + /* + The script language being used. + */ + lang(language: string): MaxAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): MaxAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): MaxAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): MaxAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + export class MetricsAggregationMixin implements Aggregation { + + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the field to operate on. + */ + field(field: string): MetricsAggregationMixin; + + /* + The script language being used. + */ + lang(language: string): MetricsAggregationMixin; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): MetricsAggregationMixin; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): MetricsAggregationMixin; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): MetricsAggregationMixin; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A single-value metrics aggregation that keeps track and returns the + minimum value among numeric values extracted from the aggregated documents. + These values can be extracted either from specific numeric fields in the + documents, or be generated by a provided script. + */ + export class MinAggregation implements Aggregation { + + /* + Aggregation that keeps track and returns the minimum value among numeric + values extracted from the aggregated documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the field to operate on. + */ + field(field: string): MinAggregation; + + /* + The script language being used. + */ + lang(language: string): MinAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): MinAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): MinAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): MinAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A field data based single bucket aggregation, that creates a bucket of all + documents in the current document set context that are missing a field value + (effectively, missing a field or having the configured NULL value set). + */ + export class MissingAggregation implements Aggregation { + + /* + Defines a bucket of all documents that are missing a field value. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): MissingAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): MissingAggregation; + + /* + Sets the field to gather missing terms from. + */ + field(field: string): MissingAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + An missingFilter matches documents where the specified field contains no legitimate value. + */ + export class MissingFilter implements Filter { + + /* + Filters documents where a specific field has no value present. + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): MissingFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): MissingFilter; + + /* + Checks if the field doesn't exist. + */ + existence(trueFalse: boolean): MissingFilter; + + /* + Sets the field to check for missing values. + */ + field(name: string): MissingFilter; + + /* + Sets the filter name. + */ + name(name: string): MissingFilter; + + /* + Checks if the field has null values. + */ + nullValue(trueFalse: boolean): MissingFilter; + + /* + Returns the filter object. + */ + toJSON(): MissingFilter; + + } + + + /* + The more_like_this_field query is the same as the more_like_this query, + except it runs against a single field. + */ + export class MoreLikeThisFieldQuery implements Query { + + /* + Constructs a query where each documents returned are “like” provided text + */ + constructor(field: string, likeText: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + The analyzer that will be used to analyze the text. Defaults to the + analyzer associated with the field. + */ + analyzer(analyzerName: string): MoreLikeThisFieldQuery; + + /* + Sets the boost value of the Query. + */ + boost(boost: number): MoreLikeThisFieldQuery; + + /* + Sets the boost factor to use when boosting terms. + Defaults to 1. + */ + boostTerms(boost: number): MoreLikeThisFieldQuery; + + /* + Should the Query fail when an unsupported field + is specified. Defaults to true. + */ + failOnUnsupportedField(trueFalse: boolean): MoreLikeThisFieldQuery; + + /* + The field to run the query against. + */ + field(f: string): MoreLikeThisFieldQuery; + + /* + The text to find documents like + */ + likeText(s: string): MoreLikeThisFieldQuery; + + /* + The maximum frequency in which words may still appear. Words that + appear in more than this many docs will be ignored. + Defaults to unbounded. + */ + maxDocFreq(max: number): MoreLikeThisFieldQuery; + + /* + The maximum number of query terms that will be included in any + generated query. Defaults to 25. + */ + maxQueryTerms(max: number): MoreLikeThisFieldQuery; + + /* + The maximum word length above which words will be ignored. + Defaults to unbounded (0). + */ + maxWordLen(len: number): MoreLikeThisFieldQuery; + + /* + The frequency at which words will be ignored which do not occur in + at least this many docs. Defaults to 5. + */ + minDocFreq(min: number): MoreLikeThisFieldQuery; + + /* + The frequency below which terms will be ignored in the source doc. + The default frequency is 2. + */ + minTermFreq(freq: number): MoreLikeThisFieldQuery; + + /* + The minimum word length below which words will be ignored. + Defaults to 0. + */ + minWordLen(len: number): MoreLikeThisFieldQuery; + + /* + The percentage of terms to match on (float value). + Defaults to 0.3 (30 percent). + */ + percentTermsToMatch(percent: number): MoreLikeThisFieldQuery; + + /* + An array of stop words. Any word in this set is considered + “uninteresting” and ignored. Even if your Analyzer allows stopwords, + you might want to tell the MoreLikeThis code to ignore them, as for + the purposes of document similarity it seems reasonable to assume + that “a stop word is never interesting”. + */ + stopWords(stopWords: any[]): MoreLikeThisFieldQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + More like this query find documents that are “like” provided text by + running it against one or more fields. + */ + export class MoreLikeThisQuery implements Query { + + /* + Constructs a query where each documents returned are “like” provided text + */ + constructor(fields: string | string[], likeText: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + The analyzer that will be used to analyze the text. Defaults to the + analyzer associated with the field. + */ + analyzer(analyzerName: string): MoreLikeThisQuery; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): MoreLikeThisQuery; + + /* + Sets the boost factor to use when boosting terms. + Defaults to 1. + */ + boostTerms(boost: number): MoreLikeThisQuery; + + /* + Should the Query fail when an unsupported field + is specified. Defaults to true. + */ + failOnUnsupportedField(trueFalse: boolean): MoreLikeThisQuery; + + /* + The fields to run the query against. If you call with a single field, + it is added to the existing list of fields. If called with an array + of field names, it replaces any existing values with the new array. + */ + fields(f: string | string[]): MoreLikeThisQuery; + + /* + The text to find documents like + */ + likeText(s: string): MoreLikeThisQuery; + + /* + The maximum frequency in which words may still appear. Words that + appear in more than this many docs will be ignored. + Defaults to unbounded. + */ + maxDocFreq(max: number): MoreLikeThisQuery; + + /* + The maximum number of query terms that will be included in any + generated query. Defaults to 25. + */ + maxQueryTerms(max: number): MoreLikeThisQuery; + + /* + The maximum word length above which words will be ignored. + Defaults to unbounded (0). + */ + maxWordLen(len: number): MoreLikeThisQuery; + + /* + The frequency at which words will be ignored which do not occur in + at least this many docs. Defaults to 5. + */ + minDocFreq(min: number): MoreLikeThisQuery; + + /* + The frequency below which terms will be ignored in the source doc. + The default frequency is 2. + */ + minTermFreq(freq: number): MoreLikeThisQuery; + + /* + The minimum word length below which words will be ignored. + Defaults to 0. + */ + minWordLen(len: number): MoreLikeThisQuery; + + /* + The percentage of terms to match on (float value). + Defaults to 0.3 (30 percent). + */ + percentTermsToMatch(percent: number): MoreLikeThisQuery; + + /* + An array of stop words. Any word in this set is considered + “uninteresting” and ignored. Even if your Analyzer allows stopwords, + you might want to tell the MoreLikeThis code to ignore them, as for + the purposes of document similarity it seems reasonable to assume + that “a stop word is never interesting”. + */ + stopWords(stopWords: any[]): MoreLikeThisQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A MultiMatchQuery query builds further on top of the + MatchQuery by allowing multiple fields to be specified. + The idea here is to allow to more easily build a concise match type query + over multiple fields instead of using a relatively more expressive query + by using multiple match queries within a bool query. + */ + export class MultiMatchQuery implements Query { + + /* + A Query that allow to more easily build a MatchQuery + over multiple fields + */ + constructor(fields: string | string[], qstr: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the analyzer name used to analyze the Query object. + */ + analyzer(analyzer: string): MultiMatchQuery; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): MultiMatchQuery; + + /* + Sets the maximum threshold/frequency to be considered a low + frequency term in a CommonTermsQuery. + Set to a value between 0 and 1. + */ + cutoffFrequency(freq: Number): MultiMatchQuery; + + /* + Sets the fields to search across. If passed a single value it is + added to the existing list of fields. If passed an array of + values, they overwite all existing values. + */ + fields(f: string | string[]): MultiMatchQuery; + + /* + Sets the fuzziness value for the Query. + */ + fuzziness(fuzz: number): MultiMatchQuery; + + /* + Sets fuzzy rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + fuzzyRewrite(m: string): MultiMatchQuery; + + /* + Enables lenient parsing of the query string. + */ + lenient(trueFalse: boolean): MultiMatchQuery; + + /* + Sets the max expansions of a fuzzy Query. + */ + maxExpansions(e: number): MultiMatchQuery; + + /* + Sets a percent value controlling how many "should" clauses in the + resulting Query should match. + */ + minimumShouldMatch(minMatch: number): MultiMatchQuery; + + /* + Sets default operator of the Query. Default: or. + */ + operator(op: string): MultiMatchQuery; + + /* + Sets the prefix length for a fuzzy prefix Query. + */ + prefixLength(l: number): MultiMatchQuery; + + /* + Sets the query string for the Query. + */ + query(qstr: string): MultiMatchQuery; + + /* + Sets rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + rewrite(m: string): MultiMatchQuery; + + /* + Sets the default slop for phrases. If zero, then exact phrase matches + are required. Default: 0. + */ + slop(slop: number): MultiMatchQuery; + + /* + The tie breaker value. The tie breaker capability allows results + that include the same term in multiple fields to be judged better than + results that include this term in only the best of those multiple + fields, without confusing this with the better case of two different + terms in the multiple fields. Default: 0.0. + */ + tieBreaker(tieBreaker: number): MultiMatchQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets the type of the MultiMatchQuery. Valid values are + boolean, phrase, and phrase_prefix or phrasePrefix. + */ + type(type: string): MultiMatchQuery; + + /* + Sets whether or not queries against multiple fields should be combined using Lucene's + + DisjunctionMaxQuery + */ + useDisMax(trueFalse: string): MultiMatchQuery; + + /* + Sets what happens when no terms match. Valid values are + "all" or "none". + */ + zeroTermsQuery(q: string): MultiMatchQuery; + + } + + + /* + A special single bucket aggregation that enables aggregating nested + documents. + */ + export class NestedAggregation implements Aggregation { + + /* + A special single bucket aggregation that enables aggregating nested + documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): NestedAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): NestedAggregation; + + /* + Sets the nested path. + */ + path(path: string): NestedAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + Nested filters allow you to search against content within objects that are + embedded inside of other objects. It is similar to XPath + expressions in XML both conceptually and syntactically. + + + The filter is executed against the nested objects / docs as if they were + indexed as separate docs and resulting in the root + parent doc (or parent nested mapping). + */ + export class NestedFilter implements Filter { + + /* + Constructs a filter that is capable of executing a filter against objects + nested within a document. + */ + constructor(path: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value of the nested Query. + */ + boost(boost: number): NestedFilter; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): NestedFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): NestedFilter; + + /* + Sets the nested filter to be executed. + */ + filter(oFilter: Object): NestedFilter; + + /* + If the nested query should be "joined" with the parent document. + Defaults to false. + */ + join(trueFalse: boolean): NestedFilter; + + /* + Sets the filter name. + */ + name(name: string): NestedFilter; + + /* + Sets the root context for the nested filter. + */ + path(p: string): NestedFilter; + + /* + Sets the nested query to be executed. + */ + query(oQuery: Query): NestedFilter; + + /* + Sets the scope of the filter. A scope allows to run facets on the + same scope name that will work against the nested documents. + */ + scope(s: string): NestedFilter; + + /* + Returns the filter object. + */ + toJSON(): NestedFilter; + + } + + + /* + Nested queries allow you to search against content within objects that are + embedded inside of other objects. It is similar to XPath expressions + in XML both conceptually and syntactically. + + The query is executed against the nested objects / docs as if they were + indexed as separate docs and resulting in the rootparent doc (or parent + nested mapping). + */ + export class NestedQuery implements Query { + + /* + Constructs a query that is capable of executing a search against objects + nested within a document. + */ + constructor(path: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): NestedQuery; + + /* + Sets the nested filter to be executed. + */ + filter(oFilter: Object): NestedQuery; + + /* + Sets the root context for the nested query. + */ + path(path: string): NestedQuery; + + /* + Sets the nested query to be executed. + */ + query(oQuery: Object): NestedQuery; + + /* + Sets the scope of the query. A scope allows to run facets on the + same scope name that will work against the nested documents. + */ + scope(s: string): NestedQuery; + + /* + Sets how the inner (nested) matches affect scoring on the parent document. + */ + scoreMode(mode: string): NestedQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A container Filter that excludes the documents matched by the + contained filter. + */ + export class NotFilter implements Filter { + + /* + Container filter that excludes the matched documents of the contained filter. + */ + constructor(oFilter: Object); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): NotFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): NotFilter; + + /* + Sets the filter + */ + filter(fltr: Object): NotFilter; + + /* + Sets the filter name. + */ + name(name: string): NotFilter; + + /* + Returns the filter object. + */ + toJSON(): NotFilter; + + } + + + /* + Filters documents with fields that have values within a certain numeric + range. Similar to range filter, except that it works only with numeric + values, and the filter execution works differently. + + The numeric range filter works by loading all the relevant field values + into memory, and checking for the relevant docs if they satisfy the range + requirements. This requires more memory since the numeric range data are + loaded to memory, but can provide a significant increase in performance. + + Note, if the relevant field values have already been loaded to memory, + for example because it was used in facets or was sorted on, then this + filter should be used. + */ + export class NumericRangeFilter implements Filter { + + /* + A Filter that only accepts numeric values within a specified range. + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): NumericRangeFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): NumericRangeFilter; + + /* + Returns the field name used to create this object. + */ + field(field: string): NumericRangeFilter; + + /* + Sets the endpoint for the current range. + */ + from(startPoint: Number): NumericRangeFilter; + + /* + Greater than value. Same as setting from to the value, and + include_lower to false, + */ + gt(val: any): NumericRangeFilter; + + /* + Greater than or equal to value. Same as setting from to the value, + and include_lower to true. + */ + gte(val: any): NumericRangeFilter; + + /* + Should the first from (if set) be inclusive or not. + Defaults to true + */ + includeLower(trueFalse: boolean): NumericRangeFilter; + + /* + Should the last to (if set) be inclusive or not. Defaults to true. + */ + includeUpper(trueFalse: boolean): NumericRangeFilter; + + /* + Less than value. Same as setting to to the value, and include_upper + to false. + */ + lt(val: any): NumericRangeFilter; + + /* + Less than or equal to value. Same as setting to to the value, + and include_upper to true. + */ + lte(val: any): NumericRangeFilter; + + /* + Sets the filter name. + */ + name(name: string): NumericRangeFilter; + + /* + Sets the endpoint for the current range. + */ + to(endPoint: Number): NumericRangeFilter; + + /* + Returns the filter object. + */ + toJSON(): NumericRangeFilter; + + } + + + /* + A container filter that allows Boolean OR composition of filters. + */ + export class OrFilter implements Filter { + + /* + A container Filter that allows Boolean OR composition of filters. + */ + constructor(filters: Filter | Filter[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): OrFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): OrFilter; + + /* + Updates the filters. If passed a single Filter it is added to + the existing filters. If passed an array of Filters, they + replace all existing Filters. + */ + filters(fltr: Filter | Filter[]): OrFilter; + + /* + Sets the filter name. + */ + name(name: string): OrFilter; + + /* + Returns the filter object. + */ + toJSON(): OrFilter; + + } + + + /* + A multi-value metrics aggregation that calculates one or more percentiles + over numeric values extracted from the aggregated documents. These values can + be extracted either from specific numeric fields in the documents, or be + generated by a provided script. + */ + export class PercentilesAggregation implements Aggregation { + + /* + Aggregation that calculates one or more percentiles over numeric values + extracted from the aggregated documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Compression controls memory usage and approximation error. The compression + value limits the maximum number of nodes to 100 * compression. By + increasing the compression value, you can increase the accuracy of your + percentiles at the cost of more memory. Larger compression values also make + the algorithm slower since the underlying tree data structure grows in + size, resulting in more expensive operations. The default compression + value is 100. + */ + compression(c: number): PercentilesAggregation; + + /* + Sets the field to operate on. + */ + field(field: string): PercentilesAggregation; + + /* + Enable the response to be returned as a keyed object where the key is the + bucket interval. + */ + keyed(trueFalse: boolean): PercentilesAggregation; + + /* + The script language being used. + */ + lang(language: string): PercentilesAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): PercentilesAggregation; + + /* + Add a single percentile to the current list of percentiles. + */ + percent(percentile: number): PercentilesAggregation; + + /* + Sets the percentile bucket array. Overwrites all existing values. + */ + percents(percents: number[]): PercentilesAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): PercentilesAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): PercentilesAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + PhraseSuggester extends the PhraseSuggester and suggests + entire corrected phrases instead of individual tokens. The individual + phrase suggestions are weighted based on ngram-langugage models. In practice + it will be able to make better decision about which tokens to pick based on + co-occurence and frequencies. + */ + export class PhraseSuggester implements Suggest { + + /* + A suggester that suggests entire corrected phrases. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets analyzer used to analyze the suggest text. + */ + analyzer(analyzer: string): PhraseSuggester; + + /* + Sets the confidence level defines a factor applied to the input + phrases score which is used as a threshold for other suggest + candidates. Only candidates that score higher than the threshold + will be included in the result. + */ + confidence(c: number): PhraseSuggester; + + /* + Adds a direct generator. If passed a single Generator + it is added to the list of existing generators. If passed an + array of Generators, they replace all existing generators. + */ + directGenerator(oGenerator: Generator | Generator[]): PhraseSuggester; + + /* + Sets the field used to generate suggestions from. + */ + field(field: string): PhraseSuggester; + + /* + Forces the use of unigrams. + */ + forceUnigrams(trueFalse: boolean): PhraseSuggester; + + /* + Sets the max size of the n-grams (shingles) in the field. If + the field doesn't contain n-grams (shingles) this should be + omitted or set to 1. + */ + gramSize(s: number): PhraseSuggester; + + /* + Enables highlighting of suggestions + */ + highlight(preTag: string, postTag: string): PhraseSuggester; + + /* + A smoothing model that uses an additive smoothing model where a + constant (typically 1.0 or smaller) is added to all counts to + balance weights, The default alpha is 0.5. + */ + laplaceSmoothing(alpha: number): PhraseSuggester; + + /* + A smoothing model that takes the weighted mean of the unigrams, + bigrams and trigrams based on user supplied weights (lambdas). The + sum of tl, bl, and ul must equal 1. + */ + linearSmoothing(tl: number, bl: number, ul: number): PhraseSuggester; + + /* + Sets the maximum percentage of the terms that at most + considered to be misspellings in order to form a correction. + */ + maxErrors(c: number): PhraseSuggester; + + /* + Sets the likelihood of a term being a misspelled even if the + term exists in the dictionary. The default it 0.95 corresponding + to 5% or the real words are misspelled. + */ + realWordErrorLikelihood(l: number): PhraseSuggester; + + /* + Sets the separator that is used to separate terms in the bigram + field. If not set the whitespce character is used as a + separator. + */ + separator(sep: string): PhraseSuggester; + + /* + Sets the maximum number of suggestions to be retrieved from + each individual shard. + */ + shardSize(s: number): PhraseSuggester; + + /* + Sets the number of suggestions returned for each token. + */ + size(s: number): PhraseSuggester; + + /* + A simple backoff model that backs off to lower order n-gram + models if the higher order count is 0 and discounts the lower + order n-gram model by a constant factor. The default discount is + 0.4. + */ + stupidBackoffSmoothing(discount: number): PhraseSuggester; + + /* + Sets the text to get suggestions for. If not set, the global + suggestion text will be used. + */ + text(txt: string): PhraseSuggester; + + /* + Retrieves the internal suggest object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets the token limit. + */ + tokenLimit(l: number): PhraseSuggester; + + } + + + /* + Filters documents that have fields containing terms with a specified prefix (not analyzed). Similar + to phrase query, except that it acts as a filter. Can be placed within queries that accept a filter. + */ + export class PrefixFilter implements Filter { + + /* + Filters documents that have fields containing terms with a specified prefix. + */ + constructor(fieldName: string, prefix: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): PrefixFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): PrefixFilter; + + /* + Returns the field name used to create this object. + */ + field(field: string): PrefixFilter; + + /* + Sets the filter name. + */ + name(name: string): PrefixFilter; + + /* + Sets the prefix to search for. + */ + prefix(value: string): PrefixFilter; + + /* + Returns the filter object. + */ + toJSON(): PrefixFilter; + + } + + + /* + Matches documents that have fields containing terms with a specified + prefix (not analyzed). The prefix query maps to Lucene PrefixQuery. + */ + export class PrefixQuery implements Query { + + /* + Matches documents containing the specified un-analyzed prefix. + */ + constructor(field: string, value: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value of the Query. + */ + boost(boost: number): PrefixQuery; + + /* + The field to run the query against. + */ + field(f: string): PrefixQuery; + + /* + Sets rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + rewrite(m: string): PrefixQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + The prefix value. + */ + value(p: string): PrefixQuery; + + } + + + /* + The QueryFacet facet allows you to specify any valid Query and + have the number of matching hits returned as the value. + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + + + Tip: + For more information on faceted navigation, see + this + Wikipedia article on Faceted Classification. + + + */ + export class QueryFacet implements Facet { + + /* + A facet that return a count of the hits matching the given query. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): QueryFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): QueryFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): QueryFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): QueryFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): QueryFacet; + + /* + Sets the query to be used for this facet. + */ + query(oQuery: Object): QueryFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): QueryFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + Wraps any query to be used as a filter. Can be placed within queries + that accept a filter. + + The result of the filter is not cached by default. Set the cache + parameter to true to cache the result of the filter. This is handy when the + same query is used on several (many) other queries. + + Note, the process of caching the first execution is higher when not + caching (since it needs to satisfy different queries). + */ + export class QueryFilter implements Filter { + + /* + Filters documents matching the wrapped query. + */ + constructor(qry: Object); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): QueryFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): QueryFilter; + + /* + Sets the filter name. + */ + name(name: string): QueryFilter; + + /* + Sets the query + */ + query(q: Object): QueryFilter; + + /* + Returns the filter object. + */ + toJSON(): QueryFilter; + + } + + export class QueryMixin { + + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): QueryMixin; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A query that is parsed using Lucene's default query parser. Although Lucene provides the + ability to create your own queries through its API, it also provides a rich query language + through the Query Parser, a lexer which interprets a string into a Lucene Query. + + See the Lucene Query Parser Syntax + for more information. + */ + export class QueryStringQuery implements Query { + + /* + A query that is parsed using Lucene's default query parser. + */ + constructor(qstr: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets whether or not wildcard characters (* and ?) are allowed as the + first character of the Query. Default: true. + */ + allowLeadingWildcard(trueFalse: boolean): QueryStringQuery; + + /* + Sets the analyzer name used to analyze the Query object. + */ + analyzer(analyzer: string): QueryStringQuery; + + /* + Sets whether or not we should attempt to analyzed wilcard terms in the + Query. By default, wildcard terms are not analyzed. + Analysis of wildcard characters is not perfect. Default: false. + */ + analyzeWildcard(trueFalse: boolean): QueryStringQuery; + + /* + Sets whether or not we should auto generate phrase queries *if* the + analyzer returns more than one term. Default: false. + */ + autoGeneratePhraseQueries(trueFalse: boolean): QueryStringQuery; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): QueryStringQuery; + + /* + Sets the default field/property this query should execute against. + */ + defaultField(fieldName: string): QueryStringQuery; + + /* + Set the default Boolean operator. This operator is used to join individual query + terms when no operator is explicity used in the query string (i.e., this AND that). + Defaults to OR. + */ + defaultOperator(op: string): QueryStringQuery; + + /* + Sets whether or not position increments will be used in the + Query. Default: true. + */ + enablePositionIncrements(trueFalse: boolean): QueryStringQuery; + + /* + If they query string should be escaped or not. + */ + escape(trueFalse: boolean): QueryStringQuery; + + /* + A set of fields/properties this query should execute against. + Pass a single value to add to the existing list of fields and + pass an array to overwrite all existing fields. For each field, + you can apply a field specific boost by appending a ^boost to the + field name. For example, title^10, to give the title field a + boost of 10. + */ + fields(fieldNames: any[]): QueryStringQuery; + + /* + Sets the max number of term expansions for fuzzy queries. + */ + fuzzyMaxExpansions(max: number): QueryStringQuery; + + /* + Set the minimum similarity for fuzzy queries. Default: 0.5. + */ + fuzzyMinSim(minSim: number): QueryStringQuery; + + /* + Sets the prefix length for fuzzy queries. Default: 0. + */ + fuzzyPrefixLength(fuzzLen: number): QueryStringQuery; + + /* + Sets fuzzy rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + fuzzyRewrite(m: string): QueryStringQuery; + + /* + Enables lenient parsing of the query string. + */ + lenient(trueFalse: boolean): QueryStringQuery; + + /* + Sets whether or not terms from wildcard, prefix, fuzzy, and + range queries should automatically be lowercased in the Query + since they are not analyzed. Default: true. + */ + lowercaseExpandedTerms(trueFalse: boolean): QueryStringQuery; + + /* + Sets a percent value controlling how many "should" clauses in the + resulting Query should match. + */ + minimumShouldMatch(minMatch: number): QueryStringQuery; + + /* + Sets the default slop for phrases. If zero, then exact phrase matches + are required. Default: 0. + */ + phraseSlop(slop: number): QueryStringQuery; + + /* + Sets the query string on this Query object. + */ + query(qstr: string): QueryStringQuery; + + /* + Sets the quote analyzer name used to analyze the query + when in quoted text. + */ + quoteAnalyzer(analyzer: string): QueryStringQuery; + + /* + Sets the suffix to automatically add to the field name when + performing a quoted search. + */ + quoteFieldSuffix(s: string): QueryStringQuery; + + /* + Sets rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + rewrite(m: string): QueryStringQuery; + + /* + Sets the tie breaker value for a Query using + DisMax. The tie breaker capability allows results + that include the same term in multiple fields to be judged better than + results that include this term in only the best of those multiple + fields, without confusing this with the better case of two different + terms in the multiple fields. Default: 0.0. + */ + tieBreaker(tieBreaker: number): QueryStringQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets whether or not queries against multiple fields should be combined using Lucene's + + DisjunctionMaxQuery + */ + useDisMax(trueFalse: string): QueryStringQuery; + + } + + + /* + The random_score generates scores via a pseudo random number algorithm + that is initialized with a seed. + */ + export class RandomScoreFunction implements ScoreFunction { + + /* + Randomly score documents. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Adds a filter whose matching documents will have the score function applied. + */ + filter(oFilter: Filter): RandomScoreFunction; + + /* + Sets random seed value. + */ + seed(s: number): RandomScoreFunction; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A multi-bucket value source based aggregation that enables the user to + define a set of ranges - each representing a bucket. During the aggregation + process, the values extracted from each document will be checked against each + bucket range and "bucket" the relevant/matching document. + + Note that this aggregration includes the from value and excludes the to + value for each range. + */ + export class RangeAggregation implements Aggregation { + + /* + Aggregation that enables the user to define a set of ranges that each + represent a bucket. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): RangeAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): RangeAggregation; + + /* + Sets the field to gather terms from. + */ + field(field: string): RangeAggregation; + + /* + Enable the response to be returned as a keyed object where the key is the + bucket interval. + */ + keyed(trueFalse: boolean): RangeAggregation; + + /* + The script language being used. + */ + lang(language: string): RangeAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): RangeAggregation; + + /* + Adds a range to the list of exsiting range expressions. + */ + range(from: number, to?: number, key?: string): RangeAggregation; + + /* + Allows you generate or modify the terms using a script. + */ + script(scriptCode: string): RangeAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): RangeAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A RangeFacet allows you to specify a set of ranges and get both the number of docs (count) that + fall within each range, and aggregated data based on the field, or another specified field. + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + + + Tip: + For more information on faceted navigation, see + this + Wikipedia article on Faceted Classification. + + + */ + export class RangeFacet implements Facet { + + /* + A facet which provides information over a range of numeric intervals. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Adds a new bounded range. + */ + addRange(from: Number, to: Number): RangeFacet; + + /* + Adds a new unbounded lower limit. + */ + addUnboundedFrom(from: Number): RangeFacet; + + /* + Adds a new unbounded upper limit. + */ + addUnboundedTo(to: Number): RangeFacet; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): RangeFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): RangeFacet; + + /* + Sets the document field to be used for the facet. + */ + field(fieldName: string): RangeFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): RangeFacet; + + /* + Allows you to specify an alternate key field to be used to compute the interval. + */ + keyField(fieldName: string): RangeFacet; + + /* + Allows you modify the key field using a script. The modified value + is then used to generate the interval. + */ + keyScript(scriptCode: string): RangeFacet; + + /* + The script language being used. Currently supported values are + javascript, groovy, and mvel. + */ + lang(language: string): RangeFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): RangeFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): RangeFacet; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): RangeFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): RangeFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Allows you to specify an alternate value field to be used to compute statistical information. + */ + valueField(fieldName: string): RangeFacet; + + /* + Allows you modify the value field using a script. The modified value + is then used to compute the statistical data. + */ + valueScript(scriptCode: string): RangeFacet; + + } + + + /* + Matches documents with fields that have terms within a certain range. + */ + export class RangeFilter implements Filter { + + /* + Filters documents with fields that have terms within a certain range. + */ + constructor(field: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): RangeFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): RangeFilter; + + /* + The field to run the filter against. + */ + field(f: string): RangeFilter; + + /* + The lower bound. Defaults to start from the first. + */ + from(f: any): RangeFilter; + + /* + Greater than value. Same as setting from to the value, and + include_lower to false, + */ + gt(val: any): RangeFilter; + + /* + Greater than or equal to value. Same as setting from to the value, + and include_lower to true. + */ + gte(val: any): RangeFilter; + + /* + Should the first from (if set) be inclusive or not. + Defaults to true + */ + includeLower(trueFalse: boolean): RangeFilter; + + /* + Should the last to (if set) be inclusive or not. Defaults to true. + */ + includeUpper(trueFalse: boolean): RangeFilter; + + /* + Less than value. Same as setting to to the value, and include_upper + to false. + */ + lt(val: any): RangeFilter; + + /* + Less than or equal to value. Same as setting to to the value, + and include_upper to true. + */ + lte(val: any): RangeFilter; + + /* + Sets the filter name. + */ + name(name: string): RangeFilter; + + /* + The upper bound. Defaults to unbounded. + */ + to(t: any): RangeFilter; + + /* + Returns the filter object. + */ + toJSON(): RangeFilter; + + } + + + /* + Matches documents with fields that have terms within a certain range. + The type of the Lucene query depends on the field type, for string fields, + the TermRangeQuery, while for number/date fields, the query is a + NumericRangeQuery. + */ + export class RangeQuery implements Query { + + /* + Matches documents with fields that have terms within a certain range. + */ + constructor(field: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value of the Query. + */ + boost(boost: number): RangeQuery; + + /* + The field to run the query against. + */ + field(f: string): RangeQuery; + + /* + The lower bound. Defaults to start from the first. + */ + from(f: any): RangeQuery; + + /* + Greater than value. Same as setting from to the value, and + include_lower to false, + */ + gt(val: any): RangeQuery; + + /* + Greater than or equal to value. Same as setting from to the value, + and include_lower to true. + */ + gte(val: any): RangeQuery; + + /* + Should the first from (if set) be inclusive or not. + Defaults to true + */ + includeLower(trueFalse: boolean): RangeQuery; + + /* + Should the last to (if set) be inclusive or not. Defaults to true. + */ + includeUpper(trueFalse: boolean): RangeQuery; + + /* + Less than value. Same as setting to to the value, and include_upper + to false. + */ + lt(val: any): RangeQuery; + + /* + Less than or equal to value. Same as setting to to the value, + and include_upper to true. + */ + lte(val: any): RangeQuery; + + /* + The upper bound. Defaults to unbounded. + */ + to(t: any): RangeQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + Filters documents that have a field value matching a regular expression. + Based on Lucene 4.0 RegexpFilter which uses automaton to efficiently iterate + over index terms. + */ + export class RegexpFilter implements Filter { + + /* + Matches documents that have fields matching a regular expression. + */ + constructor(field: string, value: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): RegexpFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): RegexpFilter; + + /* + The field to run the filter against. + */ + field(f: string): RegexpFilter; + + /* + The regex flags to use. Valid flags are: + + INTERSECTION - Support for intersection notation + COMPLEMENT - Support for complement notation + EMPTY - Support for the empty language symbol: # + ANYSTRING - Support for the any string symbol: @ + INTERVAL - Support for numerical interval notation: + NONE - Disable support for all syntax options + ALL - Enables support for all syntax options + + Use multiple flags by separating with a "|" character. Example: + + INTERSECTION|COMPLEMENT|EMPTY + */ + flags(f: string): RegexpFilter; + + /* + The regex flags to use as a numeric value. Advanced use only, + it is probably better to stick with the flags option. + */ + flagsValue(v: string): RegexpFilter; + + /* + Sets the filter name. + */ + name(name: string): RegexpFilter; + + /* + Returns the filter object. + */ + toJSON(): RegexpFilter; + + /* + The regexp value. + */ + value(p: string): RegexpFilter; + + } + + + /* + Matches documents that have fields matching a regular expression. Based + on Lucene 4.0 RegexpQuery which uses automaton to efficiently iterate over + index terms. + */ + export class RegexpQuery implements Query { + + /* + Matches documents that have fields matching a regular expression. + */ + constructor(field: string, value: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value of the Query. + */ + boost(boost: number): RegexpQuery; + + /* + The field to run the query against. + */ + field(f: string): RegexpQuery; + + /* + The regex flags to use. Valid flags are: + + INTERSECTION - Support for intersection notation + COMPLEMENT - Support for complement notation + EMPTY - Support for the empty language symbol: # + ANYSTRING - Support for the any string symbol: @ + INTERVAL - Support for numerical interval notation: + NONE - Disable support for all syntax options + ALL - Enables support for all syntax options + + Use multiple flags by separating with a "|" character. Example: + + INTERSECTION|COMPLEMENT|EMPTY + */ + flags(f: string): RegexpQuery; + + /* + The regex flags to use as a numeric value. Advanced use only, + it is probably better to stick with the flags option. + */ + flagsValue(v: string): RegexpQuery; + + /* + Sets rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + rewrite(m: string): RegexpQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + The regexp value. + */ + value(p: string): RegexpQuery; + + } + + + /* + The Request object provides methods generating an elasticsearch request body. + */ + export class Request { + + /* + Provides methods for generating request bodies. + */ + constructor(conf: Object); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Add an aggregation. This method can be called multiple times + in order to set multiple nested aggregations that will be executed + at the same time as the search request. Alias for the aggregation method. + */ + agg(agg: Aggregation): Request; + + /* + Add an aggregation. This method can be called multiple times + in order to set multiple nested aggregations that will be executed + at the same time as the search request. + */ + aggregation(agg: Aggregation): Request; + + /* + Enable/Disable explanation of score for each search result. + */ + explain(trueFalse: boolean): Request; + + /* + Allows you to set the specified facet on this request object. Multiple facets can + be set, all of which will be returned when the search is executed. + */ + facet(facet: Facet): Request; + + /* + By default, searches return full documents, meaning every property or field. + This method allows you to specify which fields you want returned. + + Pass a single field name and it is appended to the current list of + fields. Pass an array of fields and it replaces all existing + fields. + */ + fields(s: string | string[]): Request; + + /* + Allows you to set a specified filter on this request object. + */ + filter(filter: Object): Request; + + /* + A search result set could be very large (think Google). Setting the + from parameter allows you to page through the result set + by making multiple request. This parameters specifies the starting + result/document number point. Combine with size() to achieve paging. + */ + from(f: number): Request; + + /* + Performs highlighting based on the Highlight + settings. + */ + highlight(h: Highlight): Request; + + /* + Boosts hits in the specified index by the given boost value. + */ + indexBoost(index: string, boost: number): Request; + + /* + Filters out search results will scores less than the specified minimum score. + */ + minScore(min: number): Request; + + /* + Allows you to set the specified query on this search object. This is the + query that will be used when the search is executed. + */ + query(someQuery: Query): Request; + + /* + Once a query executes, you can use rescore to run a secondary, more + expensive query to re-order the results. + */ + rescore(r: Rescore): Request; + + /* + Computes a document property dynamically based on the supplied ScriptField. + */ + scriptField(oScriptField: ScriptField): Request; + + /* + Sets the number of results/documents to be returned. This is set on a per page basis. + */ + size(s: number): Request; + + /* + Sets the sorting for the query. This accepts many input formats. + + + sort() - The current sorting values are returned. + sort(fieldName) - Adds the field to the current list of sorting values. + sort(fieldName, order) - Adds the field to the current list of + sorting with the specified order. Order must be asc or desc. + sort(ejs.Sort) - Adds the Sort value to the current list of sorting values. + sort(array) - Replaces all current sorting values with values + from the array. The array must contain only strings and Sort objects. + + + Multi-level sorting is supported so the order in which sort fields + are added to the query requests is relevant. + + It is recommended to use Sort objects when possible. + */ + sort(fieldName?: string | any[] | Sort, order?: string): Request; + + /* + Allows to control how the _source field is returned with every hit. + By default operations return the contents of the _source field + unless you have used the fields parameter or if the _source field + is disabled. Set the includes parameter to false to completely + disable returning the source field. + */ + source(includes: string | boolean | string[], excludes: string | string[]): Request; + + /* + Allows you to set the specified suggester on this request object. + Multiple suggesters can be set, all of which will be returned when + the search is executed. Global suggestion text can be set by + passing in a string vs. a Suggest object. + */ + suggest(s: string | Suggest): Request; + + /* + A timeout, bounding the request to be executed within the + specified time value and bail when expired. Defaults to no timeout. + + This option is valid during the following operations: + search and delete by query + */ + timeout(t: number): Request; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Enables score computation and tracking during sorting. Be default, + when sorting scores are not computed. + */ + trackScores(trueFalse: boolean): Request; + + /* + Enable/Disable returning version number for each search result. + */ + version(trueFalse: boolean): Request; + + } + + + /* + A method that allows to rescore queries with a typically more expensive. + */ + export class Rescore { + + /* + Defines an operation that rescores a query with another query. + */ + //constructor(windowSize: Number, windowSize: Query); + constructor(windowSize: Number); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the weight assigned to the original query of the rescoring. + */ + queryWeight(weight: Number): Rescore; + + /* + Sets the query used by the rescoring. + */ + rescoreQuery(someQuery: Query): Rescore; + + /* + Sets the weight assigned to the query used to rescore the original query. + */ + rescoreQueryWeight(weight: Number): Rescore; + + /* + Sets the scoring mode. Valid values are: + + total - default mode, the scores combined + multiply - the scores multiplied + min - the lowest of the scores + max - the highest score + avg - the average of the scores + */ + scoreMode(s: string): Rescore; + + /* + Retrieves the internal script object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets the window_size parameter of the rescoring. + */ + windowSize(size: Number): Rescore; + + } + + export class ScoreFunctionMixin implements ScoreFunction { + + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Adds a filter whose matching documents will have the score function applied. + */ + filter(oFilter: Filter): ScoreFunctionMixin; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + ScriptField's allow you create dynamic fields on stored documents at query + time. For example, you might have a set of document thats containsthe fields + price and quantity. At query time, you could define a computed + property that dynamically creates a new field called totalin each document + based on the calculation price * quantity. + */ + export class ScriptField { + + /* + Computes dynamic document properties based on information from other fields. + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + If execeptions thrown from the script should be ignored or not. + Default: false + */ + ignoreFailure(trueFalse: boolean): ScriptField; + + /* + The script language being used. Currently supported values are + javascript and mvel. + */ + lang(language: string): ScriptField; + + /* + Allows you to set script parameters to be used during the execution of the script. + */ + params(oParams: Object): ScriptField; + + /* + Sets the script/code that will be used to perform the calculation. + */ + script(expression: string): ScriptField; + + /* + Retrieves the internal script object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A filter allowing to define scripts as filters + */ + export class ScriptFilter implements Filter { + + /* + A filter allowing to define scripts as filters. + */ + constructor(script: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): ScriptFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): ScriptFilter; + + /* + Sets the script language. + */ + lang(lang: string): ScriptFilter; + + /* + Sets the filter name. + */ + name(name: string): ScriptFilter; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): ScriptFilter; + + /* + Sets the script. + */ + script(s: string): ScriptFilter; + + /* + Returns the filter object. + */ + toJSON(): ScriptFilter; + + } + + + /* + The script_score function allows you to wrap another query and customize + the scoring of it optionally with a computation derived from other numeric + field values in the doc using a script expression. + */ + export class ScriptScoreFunction implements ScoreFunction { + + /* + Modify a documents score using a script. + */ + constructor(); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Adds a filter whose matching documents will have the score function applied. + */ + filter(oFilter: Filter): ScriptScoreFunction; + + /* + The script language being used. + */ + lang(language: string): ScriptScoreFunction; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): ScriptScoreFunction; + + /* + Set the script that will modify the score. + */ + script(scriptCode: string): ScriptScoreFunction; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A Shape object that can be used in queries and filters that + take a Shape. Shape uses the GeoJSON format. + + See http://www.geojson.org/ + */ + export class Shape implements Geo { + + /* + Defines a shape + */ + constructor(type: string, coords: any[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the coordinates for the shape definition. Note, the coordinates + are not validated in this api. Please see GeoJSON and ElasticSearch + documentation for correct coordinate definitions. + */ + coordinates(c: any[]): Shape; + + /* + Sets the radius for parsing a circle Shape. + */ + radius(r: string): Shape; + + /* + Retrieves the internal script object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets the shape type. Can be set to one of: point, linestring, polygon, + multipoint, envelope, or multipolygon. + */ + type(t: string): Shape; + + } + + + /* + An aggregation that returns interesting or unusual occurrences of terms in + a set. + */ + export class SignificantTermsAggregation implements Aggregation { + + /* + An aggregation that returns interesting or unusual occurrences of terms in + a set. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): SignificantTermsAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): SignificantTermsAggregation; + + /* + Allows you to filter out unwanted facet entries using a regular + expression. You can also optionally pass in a set of flags to apply + to the regular expression. Valid flags are: CASE_INSENSITIVE, + MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL, + COMMENTS, and UNICODE_CHAR_CLASS. Separate multiple flags with a | + character. + */ + exclude(exclude: string, flags: string): SignificantTermsAggregation; + + /* + Sets the execution hint determines how the aggregation is computed. + Supported values are: map and ordinals. + */ + executionHint(h: string): SignificantTermsAggregation; + + /* + Sets the field to gather terms from. + */ + field(field: string): SignificantTermsAggregation; + + /* + Sets the format expression for the terms. Use for number or date + formatting. + */ + format(f: string): SignificantTermsAggregation; + + /* + Allows you to allow only specific entries using a regular + expression. You can also optionally pass in a set of flags to apply + to the regular expression. Valid flags are: CASE_INSENSITIVE, + MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL, + COMMENTS, and UNICODE_CHAR_CLASS. Separate multiple flags with a | + character. + */ + include(include: string, flags: string): SignificantTermsAggregation; + + /* + Only return terms that match more than a configured number of hits. + */ + minDocCount(num: number): SignificantTermsAggregation; + + /* + Determines how many terms the coordinating node will request from + each shard. + */ + shardSize(shardSize: number): SignificantTermsAggregation; + + /* + Sets the number of aggregation entries that will be returned. + */ + size(size: number): SignificantTermsAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A Sort object that can be used in on the Request object to specify + various types of sorting. + + See http://www.elasticsearch.org/guide/reference/api/search/sort.html + */ + export class Sort { + + /* + Defines a sort value + */ + constructor(fieldName: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the sort order to ascending (asc). Same as calling + order('asc'). + */ + asc(): Sort; + + /* + Sets the sort order to descending (desc). Same as calling + order('desc'). + */ + desc(): Sort; + + /* + How to compute the distance. Can either be arc (better precision) + or plane (faster). Defaults to arc. + + Valid during sort types: geo distance + */ + distanceType(type: string): Sort; + + /* + Set's the field to sort on + */ + field(f: string): Sort; + + /* + Enables sorting based on a distance from a GeoPoint + */ + geoDistance(point: GeoPoint): Sort; + + /* + Sets if the sort should ignore unmapped fields vs throwing an error. + + Valid during sort types: field + */ + ignoreUnmapped(trueFalse: boolean): Sort; + + /* + Sets the script language. + + Valid during sort types: script + */ + lang(lang: string): Sort; + + /* + Sets the value to use for missing fields. Valid values are: + + _last - to put documents with the field missing last + _first - to put documents with the field missing first + {String} - any string value to use as the sort value. + + Valid during sort types: field + */ + missing(m: string): Sort; + + /* + Sets the sort mode. Valid values are: + + + min - sort by lowest value + max - sort by highest value + sum - sort by the sum of all values + avg - sort by the average of all values + + + Valid during sort types: field, geo distance + */ + mode(m: string): Sort; + + /* + Allows you to set a filter that nested objects must match + in order to be considered during sorting. + + Valid during sort types: field, geo distance + */ + nestedFilter(oFilter: Object): Sort; + + /* + Sets the path of the nested object. + + Valid during sort types: field, geo distance + */ + nestedPath(path: string): Sort; + + /* + If the lat/long points should be normalized to lie within their + respective normalized ranges. + + Normalized ranges are: + lon = -180 (exclusive) to 180 (inclusive) range + lat = -90 to 90 (both inclusive) range + + Valid during sort types: geo distance + */ + normalize(trueFalse: string): Sort; + + /* + Sets the sort order. Valid values are: + + asc - for ascending order + desc - for descending order + + Valid during sort types: field, geo distance, and script + */ + order(o: string): Sort; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + + Valid during sort types: script + */ + params(p: Object): Sort; + + /* + Sets the order with a boolean value. + + true = descending sort order + false = ascending sort order + + Valid during sort types: field, geo distance, and script + */ + reverse(trueFalse: boolean): Sort; + + /* + Enables sorting based on a script. + */ + script(scriptCode: string): Sort; + + /* + Retrieves the internal script object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets the script sort type. Valid values are: + + + string - script return value is sorted as a string + number - script return value is sorted as a number + + + Valid during sort types: script + */ + type(type: string): Sort; + + /* + Sets the distance unit. Valid values are "mi" for miles or "km" + for kilometers. Defaults to "km". + + Valid during sort types: geo distance + */ + unit(unit: Number): Sort; + + } + + + /* + Matches spans near the beginning of a field. The spanFirstQuery allows you to search + for Spans that start and end within the first n positions of the document. + The span first query maps to Lucene SpanFirstQuery. + */ + export class SpanFirstQuery implements Query { + + /* + Matches spans near the beginning of a field. + */ + constructor(spanQry: Query, end: number); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): SpanFirstQuery; + + /* + Sets the maximum end position permitted in a match. + */ + end(position: Number): SpanFirstQuery; + + /* + Sets the span query to match on. + */ + match(spanQuery: Object): SpanFirstQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + Wraps lucene MultiTermQueries as a SpanQuery so it can be used in the + various Span* queries. Examples of valid MultiTermQueries are + Fuzzy, NumericRange, Prefix, Regex, Range, and Wildcard. + */ + export class SpanMultiTermQuery implements Query { + + /* + Use MultiTermQueries as a SpanQuery. + */ + constructor(qry: Query); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): SpanMultiTermQuery; + + /* + Sets the span query to match on. + */ + match(mtQuery: Object): SpanMultiTermQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A spanNearQuery will look to find a number of spanQuerys within a given + distance from each other. + */ + export class SpanNearQuery implements Query { + + /* + Matches spans which are near one another. + */ + constructor(clauses: Query | Query[], slop: number); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): SpanNearQuery; + + /* + Sets the clauses used. If passed a single SpanQuery, it is added + to the existing list of clauses. If passed an array of + SpanQueries, they replace any existing clauses. + */ + clauses(clauses: Query | Query[]): SpanNearQuery; + + /* + Sets whether or not payloads are being used. A payload is an arbitrary + byte array stored at a specific position (i.e. token/term). + */ + collectPayloads(trueFalse: boolean): SpanNearQuery; + + /* + Sets whether or not matches are required to be in-order. + */ + inOrder(trueFalse: boolean): SpanNearQuery; + + /* + Sets the maximum number of intervening unmatched positions. + */ + slop(distance: Number): SpanNearQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + Removes matches which overlap with another span query. + The span not query maps to Lucene SpanNotQuery. + */ + export class SpanNotQuery implements Query { + + /* + Removes matches which overlap with another span query. + */ + constructor(includeQry: Query, excludeQry: Query); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): SpanNotQuery; + + /* + Sets the span query whose matches must not overlap those returned. + */ + exclude(spanQuery: Object): SpanNotQuery; + + /* + Set the span query whose matches are filtered. + */ + include(spanQuery: Object): SpanNotQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + The spanOrQuery takes an array of SpanQuerys and will match if any of the + underlying SpanQueries match. The span or query maps to Lucene SpanOrQuery. + */ + export class SpanOrQuery implements Query { + + /* + Matches the union of its span clauses. + */ + constructor(clauses: Object); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): SpanOrQuery; + + /* + Sets the clauses used. If passed a single SpanQuery, it is added + to the existing list of clauses. If passed an array of + SpanQueries, they replace any existing clauses. + */ + clauses(clauses: Query | Query[]): SpanOrQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A spanTermQuery is the basic unit of Lucene's Span Query which allows for nested, + positional restrictions when matching documents. The spanTermQuery simply matches + spans containing a term. It's essentially a termQuery with positional information asscoaited. + */ + export class SpanTermQuery implements Query { + + /* + Matches spans containing a term + */ + constructor(field: string, value: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): SpanTermQuery; + + /* + Sets the field to query against. + */ + field(f: string): SpanTermQuery; + + /* + Sets the term. + */ + term(t: string): SpanTermQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A statistical facet allows you to compute statistical data over a numeric fields. Statistical data includes + the count, total, sum of squares, mean (average), minimum, maximum, variance, and standard deviation. + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + + + Tip: + For more information on faceted navigation, see + this + Wikipedia article on Faceted Classification. + + + */ + export class StatisticalFacet implements Facet { + + /* + A facet which returns statistical information about a numeric field + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): StatisticalFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): StatisticalFacet; + + /* + Sets the field to be used to construct the this facet. + */ + field(fieldName: string): StatisticalFacet; + + /* + Aggregate statistical info across a set of fields. + */ + fields(aFieldName: any[]): StatisticalFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): StatisticalFacet; + + /* + The script language being used. Currently supported values are + javascript, groovy, and mvel. + */ + lang(language: string): StatisticalFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): StatisticalFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): StatisticalFacet; + + /* + Allows you to set script parameters to be used during the execution of the script. + */ + params(oParams: Object): StatisticalFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): StatisticalFacet; + + /* + Define a script to evaluate of which the result will be used to generate + the statistical information. + */ + script(code: string): StatisticalFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A multi-value metrics aggregation that computes stats over numeric values + extracted from the aggregated documents. These values can be extracted either + from specific numeric fields in the documents, or be generated by a provided + script. + + The stats that are returned consist of: min, max, sum, count and avg. + */ + export class StatsAggregation implements Aggregation { + + /* + Aggregation that computes stats over numeric values extracted from the + aggregated documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the field to operate on. + */ + field(field: string): StatsAggregation; + + /* + The script language being used. + */ + lang(language: string): StatsAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): StatsAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): StatsAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): StatsAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + export class SuggestContextMixin { + + + /* + Sets analyzer used to analyze the suggest text. + */ + analyzer(analyzer: string): SuggestContextMixin; + + /* + Sets the field used to generate suggestions from. + */ + field(field: string): SuggestContextMixin; + + /* + Sets the maximum number of suggestions to be retrieved from + each individual shard. + */ + shardSize(s: number): SuggestContextMixin; + + /* + Sets the number of suggestions returned for each token. + */ + size(s: number): SuggestContextMixin; + + } + + export class SuggesterMixin { + + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the text to get suggestions for. If not set, the global + suggestion text will be used. + */ + text(txt: string): SuggesterMixin; + + /* + Retrieves the internal suggest object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A single-value metrics aggregation that sums up numeric values that are + extracted from the aggregated documents. These values can be extracted either + from specific numeric fields in the documents, or be generated by a + provided script. + */ + export class SumAggregation implements Aggregation { + + /* + Aggregation that sums up numeric values that are extracted from the + aggregated documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the field to operate on. + */ + field(field: string): SumAggregation; + + /* + The script language being used. + */ + lang(language: string): SumAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): SumAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): SumAggregation; + + /* + Set to true to assume script values are sorted. + */ + scriptValuesSorted(trueFalse: boolean): SumAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + Constructs a filter for docs matching any of the terms added to this + object. Unlike a RangeFilter this can be used for filtering on multiple + terms that are not necessarily in a sequence. + */ + export class TermFilter implements Filter { + + /* + Constructs a filter for docs matching the term added to this object. + */ + constructor(fieldName: string, term: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): TermFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): TermFilter; + + /* + Provides access to the filter fieldName used to construct the + termFilter object. + */ + field(f: string): TermFilter; + + /* + Sets the filter name. + */ + name(name: string): TermFilter; + + /* + Provides access to the filter term used to construct the + termFilter object. + */ + term(): TermFilter; + + /* + Returns the filter object. + */ + toJSON(): TermFilter; + + } + + + /* + A TermQuery can be used to return documents containing a given + keyword or term. For instance, you might want to retieve all the + documents/objects that contain the term Javascript. Term filters + often serve as the basis for more complex queries such as Boolean queries. + */ + export class TermQuery implements Query { + + /* + A Query that matches documents containing a term. This may be + combined with other terms with a BooleanQuery. + */ + constructor(field: string, term: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: Number): TermQuery; + + /* + Sets the fields to query against. + */ + field(f: string): TermQuery; + + /* + Sets the term. + */ + term(t: string): TermQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A multi-bucket value source based aggregation where buckets are dynamically + built - one per unique value. + */ + export class TermsAggregation implements Aggregation { + + /* + Defines an aggregation of unique values/terms. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. Alias for the + aggregation method. + */ + agg(agg: Aggregation): TermsAggregation; + + /* + Add a nested aggregation. This method can be called multiple times + in order to set multiple nested aggregations what will be executed + at the same time as the parent aggregation. + */ + aggregation(agg: Aggregation): TermsAggregation; + + /* + Allows you to filter out unwanted facet entries using a regular + expression. You can also optionally pass in a set of flags to apply + to the regular expression. Valid flags are: CASE_INSENSITIVE, + MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL, + COMMENTS, and UNICODE_CHAR_CLASS. Separate multiple flags with a | + character. + */ + exclude(exclude: string, flags: string): TermsAggregation; + + /* + Sets the execution hint determines how the aggregation is computed. + Supported values are: map and ordinals. + */ + executionHint(h: string): TermsAggregation; + + /* + Sets the field to gather terms from. + */ + field(field: string): TermsAggregation; + + /* + Sets the format expression for the terms. Use for number or date + formatting + */ + format(f: string): TermsAggregation; + + /* + Allows you to allow only specific entries using a regular + expression. You can also optionally pass in a set of flags to apply + to the regular expression. Valid flags are: CASE_INSENSITIVE, + MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL, + COMMENTS, and UNICODE_CHAR_CLASS. Separate multiple flags with a | + character. + */ + include(include: string, flags: string): TermsAggregation; + + /* + The script language being used. + */ + lang(language: string): TermsAggregation; + + /* + Only return terms that match more than a configured number of hits. + */ + minDocCount(num: number): TermsAggregation; + + /* + Sets order for the aggregated values. + */ + order(order: string, direction: string): TermsAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): TermsAggregation; + + /* + Allows you generate or modify the terms using a script. + */ + script(scriptCode: string): TermsAggregation; + + /* + Set to true to assume script values are unique. + */ + scriptValuesUnique(trueFalse: boolean): TermsAggregation; + + /* + Determines how many terms the coordinating node will request from + each shard. + */ + shardSize(shardSize: number): TermsAggregation; + + /* + Sets the number of aggregation entries that will be returned. + */ + size(size: number): TermsAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets the type of the field value for use in scripts. Current values are: + string, double, float, long, integer, short, and byte. + */ + valueType(v: string): TermsAggregation; + + } + + + /* + A facet which returns the N most frequent terms within a collection + or set of collections. Term facets are useful for building constructs + which allow users to refine search results by filtering on terms returned + by the facet. + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + For more information on faceted navigation, see this Wikipedia article on + Faceted Classification + */ + export class TermsFacet implements Facet { + + /* + A facet which returns the N most frequent terms within a collection + or set of collections. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Allows you to return all terms, even if the frequency count is 0. This should not be + used on fields that contain a large number of unique terms because it could cause + out-of-memory errors. + */ + allTerms(trueFalse: string): TermsFacet; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): TermsFacet; + + /* + Allows you to filter out unwanted facet entries. When passed + a single term, it is appended to the list of currently excluded + terms. If passed an array, it overwrites all existing values. + */ + exclude(exclude: string | string[]): TermsFacet; + + /* + Sets the execution hint determines how the facet is computed. + Currently only supported value is "map". + */ + executionHint(h: Object): TermsFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): TermsFacet; + + /* + Sets the field to be used to construct the this facet. Set to + _index to return a facet count of hits per _index the search was + executed on. + */ + field(fieldName: string): TermsFacet; + + /* + Aggregate statistical info across a set of fields. + */ + fields(aFieldName: any[]): TermsFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): TermsFacet; + + /* + The script language being used. Currently supported values are + javascript, groovy, and mvel. + */ + lang(language: string): TermsFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): TermsFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): TermsFacet; + + /* + Sets the type of ordering that will be performed on the date + buckets. Valid values are: + + count - default, sort by the number of items in the bucket + term - sort by term value. + reverse_count - reverse sort of the number of items in the bucket + reverse_term - reverse sort of the term value. + */ + order(o: string): TermsFacet; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): TermsFacet; + + /* + Allows you to only include facet entries matching a specified regular expression. + */ + regex(exp: string): TermsFacet; + + /* + Allows you to set the regular expression flags to be used + with the regex + */ + regexFlags(flags: string): TermsFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): TermsFacet; + + /* + Allows you modify the term using a script. The modified value + is then used in the facet collection. + */ + script(scriptCode: string): TermsFacet; + + /* + Sets a script that will provide the terms for a given document. + */ + scriptField(script: string): TermsFacet; + + /* + Determines how many terms the coordinating node will request from + each shard. + */ + shardSize(shardSize: number): TermsFacet; + + /* + Sets the number of facet entries that will be returned for this facet. For instance, you + might ask for only the top 5 authors although there might be hundreds of + unique authors. + */ + size(facetSize: number): TermsFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + Filters documents that have fields that match any of the provided + terms (not analyzed) + */ + export class TermsFilter implements Filter { + + /* + A Filter that matches documents containing provided terms. + */ + constructor(field: string, terms: string | string[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): TermsFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): TermsFilter; + + /* + Enable or disable caching of the lookup + */ + cacheLookup(trueFalse: boolean): TermsFilter; + + /* + Sets the way terms filter executes is by iterating over the terms + provided and finding matches docs (loading into a bitset) and + caching it. Valid values are: plain, bool, bool_nocache, and, + and_nocache, or, or_nocache. Defaults to plain. + */ + execution(e: string): TermsFilter; + + /* + Sets the fields to filter against. + */ + field(f: string): TermsFilter; + + /* + Sets the document id of the document containing the terms to use + when performing a terms lookup. + */ + id(id: string): TermsFilter; + + /* + Sets the index the document containing the terms is in when + performing a terms lookup. Defaults to the index currently + being searched. + */ + index(idx: string): TermsFilter; + + /* + Sets the filter name. + */ + name(name: string): TermsFilter; + + /* + Sets the path/field name where the terms in the source document + are located when performing a terms lookup. + */ + path(path: string): TermsFilter; + + /* + Sets the routing value for the source document when performing a + terms lookup. + */ + routing(path: string): TermsFilter; + + /* + Sets the terms. If t is a String, it is added to the existing + list of terms. If t is an array, the list of terms replaces the + existing terms. + */ + terms(t: string | string[]): TermsFilter; + + /* + Returns the filter object. + */ + toJSON(): TermsFilter; + + /* + Sets the type the document containing the terms when performing a + terms lookup. + */ + type(type: string): TermsFilter; + + } + + + /* + A query that match on any (configurable) of the provided terms. This is + a simpler syntax query for using a bool query with several term queries + in the should clauses. + */ + export class TermsQuery implements Query { + + /* + A Query that matches documents containing provided terms. + */ + constructor(field: string, terms: string | string[]); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): TermsQuery; + + /* + Enables or disables similarity coordinate scoring of documents + matching the Query. Default: false. + */ + disableCoord(trueFalse: string): TermsQuery; + + /* + Sets the fields to query against. + */ + field(f: string): TermsQuery; + + /* + Sets the minimum number of terms that need to match in a document + before that document is returned in the results. + */ + minimumShouldMatch(min: number): TermsQuery; + + /* + Sets the terms. If you t is a String, it is added to the existing + list of terms. If t is an array, the list of terms replaces the + existing terms. + */ + terms(t: string | string[]): TermsQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + A termsStatsFacet allows you to compute statistics over an aggregate key (term). Essentially this + facet provides the functionality of what is often refered to as a pivot table. + + Facets are similar to SQL GROUP BY statements but perform much + better. You can also construct several "groups" at once by simply + specifying multiple facets. + + + + Tip: + For more information on faceted navigation, see + this + Wikipedia article on Faceted Classification. + + + */ + export class TermStatsFacet implements Facet { + + /* + A facet which computes statistical data based on an aggregate key. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Allows you to return all terms, even if the frequency count is 0. This should not be + used on fields that contain a large number of unique terms because it could cause + out-of-memory errors. + */ + allTerms(trueFalse: string): TermStatsFacet; + + /* + Enables caching of the facetFilter + */ + cacheFilter(trueFalse: boolean): TermStatsFacet; + + /* + Allows you to reduce the documents used for computing facet results. + */ + facetFilter(oFilter: Object): TermStatsFacet; + + /* + Computes values across the entire index + */ + global(trueFalse: boolean): TermStatsFacet; + + /* + Sets the field which will be used to pivot on (group-by). + */ + keyField(fieldName: string): TermStatsFacet; + + /* + The script language being used. Currently supported values are + javascript, groovy, and mvel. + */ + lang(language: string): TermStatsFacet; + + /* + Sets the mode the facet will use. + + + collector + post + + */ + mode(m: string): TermStatsFacet; + + /* + Sets the path to the nested document if faceting against a + nested field. + */ + nested(path: string): TermStatsFacet; + + /* + Sets the type of ordering that will be performed on the date + buckets. Valid values are: + + count - default, sort by the number of items in the bucket + term - sort by term value. + reverse_count - reverse sort of the number of items in the bucket + reverse_term - reverse sort of the term value. + total - sorts by the total value of the bucket contents + reverse_total - reverse sort of the total value of bucket contents + min - the minimum value in the bucket + reverse_min - the reverse sort of the minimum value + max - the maximum value in the bucket + reverse_max - the reverse sort of the maximum value + mean - the mean value of the bucket contents + reverse_mean - the reverse sort of the mean value of bucket contents. + */ + order(o: string): TermStatsFacet; + + /* + Allows you to set script parameters to be used during the execution of the script. + */ + params(oParams: Object): TermStatsFacet; + + /* + Computes values across the the specified scope + */ + scope(scope: string): TermStatsFacet; + + /* + Sets a script that will provide the terms for a given document. + */ + scriptField(script: string): TermStatsFacet; + + /* + Sets the number of facet entries that will be returned for this facet. For instance, you + might ask for only the top 5 aggregate keys although there might be hundreds of + unique keys. Higher settings could cause memory strain. + */ + size(facetSize: number): TermStatsFacet; + + /* + Retrieves the internal facet object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets the field for which statistical information will be generated. + */ + valueField(fieldName: string): TermStatsFacet; + + /* + Define a script to evaluate of which the result will be used to generate + the statistical information. + */ + valueScript(code: string): TermStatsFacet; + + } + + + /* + TermSuggester suggests terms based on edit distance. The provided suggest + text is analyzed before terms are suggested. The suggested terms are + provided per analyzed suggest text token. This leaves the suggest-selection + to the API consumer. For a higher level suggester, please use the + PhraseSuggester. + */ + export class TermSuggester implements Suggest { + + /* + A suggester that suggests terms based on edit distance. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the accuracy. How similar the suggested terms at least + need to be compared to the original suggest text. + */ + accuracy(a: number): TermSuggester; + + /* + Sets analyzer used to analyze the suggest text. + */ + analyzer(analyzer: string): TermSuggester; + + /* + Sets the field used to generate suggestions from. + */ + field(field: string): TermSuggester; + + /* + Sets the maximum edit distance candidate suggestions can have + in order to be considered as a suggestion. + */ + maxEdits(max: number): TermSuggester; + + /* + The factor that is used to multiply with the size in order + to inspect more candidate suggestions. + */ + maxInspections(max: number): TermSuggester; + + /* + Sets a maximum threshold in number of documents a suggest text + token can exist in order to be corrected. + */ + maxTermFreq(max: number): TermSuggester; + + /* + Sets a minimal threshold of the number of documents a suggested + term should appear in. + */ + minDocFreq(min: number): TermSuggester; + + /* + Sets the minimum length a suggest text term must have in order + to be corrected. + */ + minWordLen(len: number): TermSuggester; + + /* + Sets the maximum number of suggestions to be retrieved from + each individual shard. + */ + shardSize(s: number): TermSuggester; + + /* + Sets the number of suggestions returned for each token. + */ + size(s: number): TermSuggester; + + /* + Sets the sort mode. Valid values are: + + + score - Sort by score first, then document frequency, and then the term itself + frequency - Sort by document frequency first, then simlarity score and then the term itself + + */ + sort(s: string): TermSuggester; + + /* + Sets what string distance implementation to use for comparing + how similar suggested terms are. Valid values are: + + + internal - based on damerau_levenshtein but but highly optimized for comparing string distance for terms inside the index + damerau_levenshtein - String distance algorithm based on Damerau-Levenshtein algorithm + levenstein - String distance algorithm based on Levenstein edit distance algorithm + jarowinkler - String distance algorithm based on Jaro-Winkler algorithm + ngram - String distance algorithm based on character n-grams + + */ + stringDistance(s: string): TermSuggester; + + /* + Sets the suggest mode. Valid values are: + + + missing - Only suggest terms in the suggest text that aren't in the index + popular - Only suggest suggestions that occur in more docs then the original suggest text term + always - Suggest any matching suggestions based on terms in the suggest text + + */ + suggestMode(m: string): TermSuggester; + + /* + Sets the text to get suggestions for. If not set, the global + suggestion text will be used. + */ + text(txt: string): TermSuggester; + + /* + Retrieves the internal suggest object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + TThe top_children query runs the child query with an estimated hits size, + and out of the hit docs, aggregates it into parent docs. If there aren’t + enough parent docs matching the requested from/size search request, then it + is run again with a wider (more hits) search. + + The top_children also provide scoring capabilities, with the ability to + specify max, sum or avg as the score type. + */ + export class TopChildrenQuery implements Query { + + /* + Returns child documents matching the query aggregated into the parent docs. + */ + constructor(qry: Object, type: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: number): TopChildrenQuery; + + /* + Sets the factor which is the number of hits that are asked for in + the child query. Defaults to 5. + */ + factor(f: number): TopChildrenQuery; + + /* + Sets the incremental factor. The incremental factor is used when not + enough child documents are returned so the factor is multiplied by + the incremental factor to fetch more results. Defaults to 52 + */ + incrementalFactor(f: number): TopChildrenQuery; + + /* + Sets the query + */ + query(q: Object): TopChildrenQuery; + + /* + Sets the scope of the query. A scope allows to run facets on the + same scope name that will work against the child documents. + */ + scope(s: string): TopChildrenQuery; + + /* + Sets the scoring type. Valid values are max, sum, or avg. If + another value is passed it we silently ignore the value. + */ + score(s: string): TopChildrenQuery; + + /* + Sets the scoring type. Valid values are max, sum, total, or avg. + If another value is passed it we silently ignore the value. + */ + scoreMode(s: string): TopChildrenQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets the child document type to search against + */ + type(t: string): TopChildrenQuery; + + } + + + /* + A Filter that filters results by a specified index type. + */ + export class TypeFilter implements Filter { + + /* + Filter results by a specified index type. + */ + constructor(type: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Enable or disable caching of the filter + */ + cache(trueFalse: boolean): TypeFilter; + + /* + Sets the cache key. + */ + cacheKey(key: string): TypeFilter; + + /* + Sets the filter name. + */ + name(name: string): TypeFilter; + + /* + Returns the filter object. + */ + toJSON(): TypeFilter; + + /* + Sets the type + */ + type(type: string): TypeFilter; + + } + + + /* + A single-value metrics aggregation that counts the number of values that + are extracted from the aggregated documents. These values can be extracted + either from specific fields in the documents, or be generated by a provided + script. Typically, this aggregator will be used in conjunction with other + single-value aggregations. + */ + export class ValueCountAggregation implements Aggregation { + + /* + Aggregation that counts the number of values that are extracted from the + aggregated documents. + */ + constructor(name: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the field to operate on. + */ + field(field: string): ValueCountAggregation; + + /* + The script language being used. + */ + lang(language: string): ValueCountAggregation; + + /* + Sets parameters that will be applied to the script. Overwrites + any existing params. + */ + params(p: Object): ValueCountAggregation; + + /* + Allows you generate or modify the terms/values using a script. + */ + script(scriptCode: string): ValueCountAggregation; + + /* + Set to true to assume script values are unique. + */ + scriptValuesUnique(trueFalse: boolean): ValueCountAggregation; + + /* + Retrieves the internal agg object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + } + + + /* + Matches documents that have fields matching a wildcard expression + (not analyzed). Supported wildcards are *, which matches any character + sequence (including the empty one), and ?, which matches any single + character. Note this query can be slow, as it needs to iterate over many + wildcards. In order to prevent extremely slow wildcard queries, a wildcard + wildcard should not start with one of the wildcards * or ?. The wildcard query + maps to Lucene WildcardQuery. + */ + export class WildcardQuery implements Query { + + /* + A Query that matches documents containing a wildcard. This may be + combined with other wildcards with a BooleanQuery. + */ + constructor(field: string, value: string); + + /* + The type of ejs object. For internal use only. + */ + _type(): string; + + /* + Sets the boost value for documents matching the Query. + */ + boost(boost: Number): WildcardQuery; + + /* + Sets the fields to query against. + */ + field(f: string): WildcardQuery; + + /* + Sets rewrite method. Valid values are: + + constant_score_auto - tries to pick the best constant-score rewrite + method based on term and document counts from the query + + scoring_boolean - translates each term into boolean should and + keeps the scores as computed by the query + + constant_score_boolean - same as scoring_boolean, expect no scores + are computed. + + constant_score_filter - first creates a private Filter, by visiting + each term in sequence and marking all docs for that term + + top_terms_boost_N - first translates each term into boolean should + and scores are only computed as the boost using the top N + scoring terms. Replace N with an integer value. + + top_terms_N - first translates each term into boolean should + and keeps the scores as computed by the query. Only the top N + scoring terms are used. Replace N with an integer value. + + Default is constant_score_auto. + + This is an advanced option, use with care. + */ + rewrite(m: string): WildcardQuery; + + /* + Retrieves the internal query object. This is typically used by + internal API functions so use with caution. + */ + toJSON(): any; + + /* + Sets the wildcard query value. + */ + value(v: string): WildcardQuery; + + } + +} diff --git a/elasticsearch/elasticsearch-tests.ts b/elasticsearch/elasticsearch-tests.ts index 9a85f2c908..6d308dc6ed 100644 --- a/elasticsearch/elasticsearch-tests.ts +++ b/elasticsearch/elasticsearch-tests.ts @@ -32,4 +32,57 @@ client.indices.delete({ ignore: [404] }).then(function (body) { }, function (error) { +}); + +client.create({ + id: '123', + index: 'index', + type: 'type' +}); + +client.create({ + id: '123', + index: 'index', + type: 'type' +}, (err, repsonse, status) => { +}); + +client.cluster.getSettings({ + masterTimeout: 100 +}, (err, response) => { +}); + +client.cluster.health({ + masterTimeout: 100 +}, (err, response) => { +}); + +client.cluster.pendingTasks({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.putSettings({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.putSettings({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.reroute({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.state({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.stats({ + ignore: 1 +}, (err, response) => { }); \ No newline at end of file diff --git a/elasticsearch/elasticsearch.d.ts b/elasticsearch/elasticsearch.d.ts index 5b7ba8055c..d983817869 100644 --- a/elasticsearch/elasticsearch.d.ts +++ b/elasticsearch/elasticsearch.d.ts @@ -1,30 +1,34 @@ // Type definitions for elasticsearch // Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html -// Definitions by: Casper Skydt +// Definitions by: Casper Skydt , Blake Smith , Dave Dunkin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module Elasticsearch { export class Client { constructor(params: ConfigOptions); indices: Indices; + cluster: Cluster; + cat: Cat; bulk(params: BulkIndexDocumentsParams): PromiseLike; bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; + create(params: CreateDocumentParams): PromiseLike; + create(params: CreateDocumentParams, callback: (err: any, response: any, status: any) => void): void; delete(params: DeleteDocumentParams): PromiseLike; delete(params: DeleteDocumentParams, callback: (error: any, response: any) => void): void; - get(params: GetParams, callback: (error: any, response: any) => void): void; + get(params: GetParams, callback: (error: any, response: GetResponse) => void): void; get(params: GetParams): PromiseLike>; index(params: IndexDocumentParams): PromiseLike; index(params: IndexDocumentParams, callback: (error: any, response: any) => void): void; - mget(params: MGetParams, callback: (error: any, response: any) => void): void; - mget(params: MGetParams): PromiseLike>; - msearch(params: MSearchParams, callback: (error: any, response: any) => void): void; - msearch(params: MSearchParams): PromiseLike>; + mget(params: MGetParams, callback: (error: any, response: MGetResponse) => void): void; + mget(params: MGetParams): PromiseLike>; + msearch(params: MSearchParams, callback: (error: any, response: MSearchResponse) => void): void; + msearch(params: MSearchParams): PromiseLike>; ping(params: PingParams): PromiseLike; ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void; scroll(params: ScrollParams): PromiseLike; scroll(params: ScrollParams, callback: (error: any, response: any) => void): void; - search(params: SearchParams): PromiseLike; - search(params: SearchParams, callback: (error: any, response: any) => void): void; + search(params: SearchParams): PromiseLike>; + search(params: SearchParams, callback: (error: any, response: SearchResponse) => void): void; suggest(params: SuggestParams): PromiseLike; suggest(params: SuggestParams, callback: (error: any, response: any) => void): void; update(params: UpdateDocumentParams): PromiseLike; @@ -38,6 +42,8 @@ declare module Elasticsearch { create(params: IndicesCreateParams): PromiseLike; exists(params: IndicesIndexExitsParams, callback: (error: any, response: any, status: any) => void): void; exists(params: IndicesIndexExitsParams): PromiseLike; + existsType(params: IndicesIndexExitsParams & {type: string}, callback: (error: any, response: any, status: any) => void): void; + existsType(params: IndicesIndexExitsParams & {type: string}): PromiseLike; get(params: IndicesGetParams, callback: (error: any, response: any, status: any) => void): void; get(params: IndicesGetParams): PromiseLike; getAlias(params: IndicesGetAliasParams, callback: (error: any, response: any, status: any) => void): void; @@ -46,6 +52,8 @@ declare module Elasticsearch { putAlias(params: IndicesPutAliasParams): PromiseLike; putTemplate(params: IndicesPutTemplateParams, callback: (error: any, response: any) => void): void; putTemplate(params: IndicesPutTemplateParams): PromiseLike; + putMapping(params: IndicesPutMappingParams, callback: (error: any, response: any) => void): void; + putMapping(params: IndicesPutMappingParams): PromiseLike; refresh(params: IndicesRefreshParams, callback: (error: any, response: any) => void): void; refresh(params: IndicesRefreshParams): PromiseLike; } @@ -75,6 +83,12 @@ declare module Elasticsearch { createNodeAgent?: any; } + export interface Explanation { + value: number, + description: string, + details: Explanation[] + } + export interface GenericParams { requestTimeout?: number; maxRetries?: number; @@ -92,6 +106,21 @@ declare module Elasticsearch { index?: string; } + export interface CreateDocumentParams extends GenericParams { + consistency?: "one" | "quorum" | "all"; + parent?: string; + refressh?: boolean; + routing?: string; + timeout?: number | Date; + timestamp?: number | Date; + ttl?: number; + version?: number; + versionType?: "internal" | "external" | "external_gte" | "force"; + id: string; + index: string; + type: string; + } + export interface IndicesGetParams extends GenericParams { ignoreUnavailable?: boolean; index: string | string[] | boolean; @@ -125,10 +154,21 @@ declare module Elasticsearch { body: string | any; } + export interface IndicesPutMappingParams extends GenericParams { + timeout?: Date | number; + masterTimeout?: Date | number; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: "open" | "closed" | "none" | "all"; + updateAllTypes?: boolean; + index: string | string[] | boolean; + type: string; + } + export interface IndicesGetAliasParams extends GenericParams { ignoreUnavailable?: boolean; allowNoIndices?: boolean; - expandWildcards?: string; + expandWildcards?: "open" | "closed" | "none" | "all"; local?: boolean; index?: string | string[] | boolean; name: string | string[] | boolean; @@ -156,7 +196,8 @@ declare module Elasticsearch { versionType?: string; } - export interface GetResponse extends GenericParams { + export interface GetResponse { + _index: string; _type: string; _id: string; _version: number; @@ -192,6 +233,7 @@ declare module Elasticsearch { scroll?: string; search_type?: string; fields?: string[]; + from?: number; size?: number; sort?: string | string[] | boolean; _source?: string | string[] | boolean; @@ -204,12 +246,44 @@ declare module Elasticsearch { timeout?: Date | number; } + export interface SearchResponse { + took: number, + timed_out: boolean, + _scroll_id?: string, + _shards: { + total: number, + successful: number, + failed: number + }, + hits: { + total: number, + max_score: number, + hits: { + _index: string, + _type: string, + _id: string, + _score: number, + _source: T, + _version: number, + _explanation?: Explanation, + fields?: any, + highlight?: any, + inner_hits?: any + }[] + }, + aggregations?: any + } + export interface MSearchParams extends GenericParams { index?: string | string[] | Boolean; type?: string | string[] | Boolean; search_type?: string; } + export interface MSearchResponse { + responses?: SearchResponse[]; + } + export interface MGetParams extends GenericParams { fields?: string | string[] | Boolean; preference?: string; @@ -221,6 +295,10 @@ declare module Elasticsearch { type?: string; } + export interface MGetResponse { + docs?: GetResponse[]; + } + export interface IndicesIndexExitsParams extends GenericParams { index: string | string[] | boolean; ignoreUnavailable?: boolean; @@ -260,13 +338,98 @@ declare module Elasticsearch { export interface SuggestParams extends GenericParams { ignoreUnavailable?: boolean; allowNoIndices?: boolean; - expandWildcards?: string; + expandWildcards?: "open" | "closed" | "none" | "all"; preference?: string; routing?: string; source?: string; body: string | any; index: string | string[] | boolean; } + + export interface Cat { + health(params: CatHealthOptions, callback: (error: any, response: any) => void): void; + health(params: CatHealthOptions): PromiseLike + } + + export interface CatHealthOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + h?: string | string[] | boolean; + help?: boolean; + ts?: boolean; + v?: boolean; + } + + export interface Cluster { + getSettings(params: ClusterGetSettingsOptions, callback: (error: any, response: any) => void): void; + getSettings(params: ClusterGetSettingsOptions): PromiseLike; + health(params: ClusterHealthOptions, callback: (error: any, response: any) => void): void; + health(params: ClusterHealthOptions): PromiseLike; + pendingTasks(params: ClusterPendingTasksOptions, callback: (error: any, response: any) => void): void; + pendingTasks(params: ClusterPendingTasksOptions): PromiseLike; + putSettings(params: ClusterPutSettingsOptions, callback: (error: any, response: any) => void): void; + putSettings(params: ClusterPutSettingsOptions): PromiseLike; + reroute(params: ClusterRerouteOptions, callback: (error: any, response: any) => void): void; + reroute(params: ClusterRerouteOptions): PromiseLike; + state(params: ClusterStateOptions, callback: (error: any, response: any) => void): void; + state(params: ClusterStateOptions): PromiseLike; + stats(params: ClusterStatsOptions, callback: (error: any, response: any) => void): void; + stats(params: ClusterStatsOptions): PromiseLike; + } + + export interface ClusterGetSettingsOptions extends GenericParams { + flatSettings?: boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterHealthOptions extends GenericParams { + level?: string; // cluster, indices, shards + local?: boolean; + masterTimeout?: number | Date; + waitForActiveShards?: number; + waitForNodes?: string; + waitForRelocatingShards?: number; + waitForStatus?: string; // green, yellow, red + index?: string | string[] | boolean; + } + + export interface ClusterPendingTasksOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + } + + export interface ClusterPutSettingsOptions extends GenericParams { + flatSettings?: boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterRerouteOptions extends GenericParams { + dryRun?: boolean; + explain?: boolean; + metric?: string | string[] | boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterStateOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + flatSettings?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: string; // open, closed, none, all (default open) + index?: string | string[] | boolean; + metric?: string | string[] | boolean; + } + + export interface ClusterStatsOptions extends GenericParams { + flatSettings?: boolean; + human?: boolean; + timeout?: number | Date; + nodeId?: string | string[] | boolean; + } } declare module "elasticsearch" { diff --git a/electron-notifications/electron-notifications-tests.ts b/electron-notifications/electron-notifications-tests.ts new file mode 100644 index 0000000000..7730747acc --- /dev/null +++ b/electron-notifications/electron-notifications-tests.ts @@ -0,0 +1,13 @@ +/// + +import * as notifier from 'electron-notifications'; + +const data: ElectronNotifications.NotifierOptions = { + message: 'message', + icon: 'icon', + buttons: ['ok', 'cancel'] +}; +const notification = notifier.notify('title', data); +notification.on('clicked', () => { console.log('clicked') }); +notification.on('swipedRight', () => { console.log('swipedRight') }); +notification.on('buttonClicked', (text) => { console.log(`buttonClicked: ${text}`) }); \ No newline at end of file diff --git a/electron-notifications/electron-notifications.d.ts b/electron-notifications/electron-notifications.d.ts new file mode 100644 index 0000000000..5cbb655246 --- /dev/null +++ b/electron-notifications/electron-notifications.d.ts @@ -0,0 +1,41 @@ +// Type definitions for electron-notifications v0.0.3 +// Project: https://github.com/blainesch/electron-notifications +// Definitions by: Daniel Pereira +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace ElectronNotifications { + + interface NotifierOptions { + + /** A message to display under the title. */ + message?: string, + + /** The absolute URL of a icon displayed to the left of the text. */ + icon?: string, + + /** One or two buttons to display on the right of the notification. */ + buttons?: string[] + } + + class NotificationWindow extends Electron.BrowserWindow { + + /** When the notification was clicked, but not dragged. This usually does the default action, or closes the notification. */ + on(event: 'clicked', listener: Function): this; + + /** When the notification has been swiped to the right. This usually indiciated the user wants to dismiss the notification. */ + on(event: 'swipedRight', listener: Function): this; + + /** When any one of the buttons are clicked, it will trigger a buttonClicked event, and pass the text that was clicked to the handler. */ + on(event: 'buttonClicked', listener: (text: string) => void): this; + + on(event: string, listener: Function): this; + } + +} + +/** A node module for sending notifications in electron applications */ +declare module 'electron-notifications' { + export function notify(title: string, data?: ElectronNotifications.NotifierOptions): ElectronNotifications.NotificationWindow; +} \ No newline at end of file diff --git a/electron-notify/electron-notify-tests.ts b/electron-notify/electron-notify-tests.ts new file mode 100644 index 0000000000..95e2edf998 --- /dev/null +++ b/electron-notify/electron-notify-tests.ts @@ -0,0 +1,26 @@ +/// + +import * as eNotify from 'electron-notify'; + +eNotify.setConfig({ + appIcon: 'images/otherIcon.png', + displayTime: 6000, + defaultStyleText: { + color: '#FF0000', + fontWeight: 'bold' + } +}); + +eNotify.notify({ + title: 'Title', + text: 'Some text', + image: 'path/to/image.png', + url: 'http://google.de', + sound: 'notification.wav', + onClickFunc: (event) => { + console.log('onClick ' + event.id); + event.closeNotification('onClick'); + }, + onShowFunc: (event) => { console.log('onShow ' + event.id) }, + onCloseFunc: (event) => { console.log('onClose ' + event.id) } +}); \ No newline at end of file diff --git a/electron-notify/electron-notify.d.ts b/electron-notify/electron-notify.d.ts new file mode 100644 index 0000000000..b29efa0e50 --- /dev/null +++ b/electron-notify/electron-notify.d.ts @@ -0,0 +1,64 @@ +// Type definitions for electron-notify v0.1.0 +// Project: https://github.com/hankbao/electron-notify +// Definitions by: Daniel Pereira +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** Nice and simple notifications for electron apps */ +declare module 'electron-notify' { + + export interface ICustomConfig { + width?: number, + height?: number, + padding?: number, + borderRadius?: number, + displayTime?: number, + animationSteps?: number, + animationStepMs?: number, + animateInParallel?: boolean, + appIcon?: string, + pathToModule?: string, + logging?: boolean, + defaultWindow?: Electron.BrowserWindowOptions, + defaultStyleContainer?: any, + defaultStyleAppIcon?: any, + defaultStyleImage?: any, + defaultStyleClose?: any, + defaultStyleText?: any + } + + export interface ICloseNotificationEvent { + event: 'close' | 'show' | 'click', + id: number + } + + export interface INotificationEvent extends ICloseNotificationEvent { + closeNotification: (reason: any) => void, + } + + export interface INotification { + title: string, + text?: string, + image?: string, + url?: string, + sound?: string, + onClickFunc?: (event: INotificationEvent) => void, + onShowFunc?: (event: INotificationEvent) => void, + onCloseFunc?: (event: ICloseNotificationEvent) => void + } + + /** Change some config options. Can be run multiple times, also between notify()-calls to change electron-notifys behaviour. */ + export function setConfig(customConfig: ICustomConfig): void; + + /** Displays new notification. */ + export function notify(notification: INotification): void; + + /** Clears the animation queue and closes all windows opened by electron-notify. Call this to clean up before quiting your app. */ + export function closeAll(): void; + + export function getTemplatePath(): string; + + export function setTemplatePath(path: string): void; + +} \ No newline at end of file diff --git a/ember/ember-1.11.3-tests.ts b/ember/ember-1.11.3-tests.ts new file mode 100644 index 0000000000..6cd304c54a --- /dev/null +++ b/ember/ember-1.11.3-tests.ts @@ -0,0 +1,210 @@ +/// +/// + + +var App : any; + +App = Em.Application.create(); + +App.president = Em.Object.create({ + name: 'Barack Obama' +}); +App.country = Em.Object.create({ + presidentNameBinding: 'MyApp.president.name' +}); +App.country.get('presidentName'); +App.president = Em.Object.create({ + firstName: 'Barack', + lastName: 'Obama', + fullName: function () { + return this.get('firstName') + ' ' + this.get('lastName'); + }.property() +}); +App.president.get('fullName'); + +declare class MyPerson extends Em.Object { + static createMan(): MyPerson; +} + +var Person1 = Em.Object.extend({ + say: (thing: string) => { + alert(thing); + } +}); + +declare class MyPerson2 extends Em.Object { + helloWorld(): void; +} +var tom = Person1.create({ + name: 'Tom Dale', + helloWorld: function() { + this.say('Hi my name is ' + this.get('name')); + } +}); +tom.helloWorld(); + +Person1.reopen({ isPerson: true }); +Person1.create().get('isPerson'); + +Person1.reopenClass({ + createMan: () => { + return Person1.create({ isMan: true }); + } +}); +// ReSharper disable once DuplicatingLocalDeclaration +declare var Person1: typeof MyPerson; +Person1.createMan().get('isMan'); + +var person = Person1.create({ + firstName: 'Yehuda', + lastName: 'Katz' +}); +person.addObserver('fullName', null, () => { }); +person.set('firstName', 'Brohuda'); + +App.todosController = Em.Object.create({ + todos: [ + Em.Object.create({ isDone: false }) + ], + remaining: (function() { + var todos = this.get('todos'); + return todos.filterProperty('isDone', false).get('length'); + }).property('todos.@each.isDone') +}); + +var todos = App.todosController.get('todos'); +var todo = todos.objectAt(0); +todo.set('isDone', true); +App.todosController.get('remaining'); +todo = Em.Object.create({ isDone: false }); +todos.pushObject(todo); +App.todosController.get('remaining'); + +App.wife = Em.Object.create({ + householdIncome: 80000 +}); +App.husband = Em.Object.create({ + householdIncomeBinding: 'App.wife.householdIncome' +}); +App.husband.get('householdIncome'); +App.husband.set('householdIncome', 90000); +App.wife.get('householdIncome'); + +App.user = Em.Object.create({ + fullName: 'Kara Gates' +}); +App.userView = Em.View.create({ + userNameBinding: Em.Binding.oneWay('App.user.fullName') +}); +App.user.set('fullName', 'Krang Gates'); +App.userView.set('userName', 'Truckasaurus Gates'); +App.user.get('fullName'); + +App = Em.Application.create({ + rootElement: '#sidebar' +}); + +var view = Em.View.create({ + templateName: 'say-hello', + name: 'Bob' +}); +view.appendTo('#container'); +view.append(); +view.remove(); + +App.AlertView = Em.View.extend({ + priority: 'p4', + isUrgent: true +}); + +App.ListingView = Em.View.extend({ + templateName: 'listing', + edit: (event: any) => { + event.view.set('isEditing', true); + } +}); + +App.userController = Em.Object.create({ + content: Em.Object.create({ + firstName: 'Albert', + lastName: 'Hofmann', + posts: 25, + hobbies: 'Riding bicycles' + }) +}); + +Handlebars.registerHelper('highlight', function(property: string, options: any) { + var value = Em.Handlebars.get(this, property, options); + return new Handlebars.SafeString('' + value + ''); +}); + +App.MyText = Em.TextField.extend({ + formBlurredBinding: 'App.adminController.formBlurred', + change: function() { + this.set('formBlurred', true); + } +}); + +var textArea = Em.TextArea.create({ + valueBinding: 'TestObject.value' +}); + +App.ClickableView = Em.View.extend({ + click: () => { + alert('ClickableView was clicked!'); + } +}); + +var container = Em.ContainerView.create(); +container.append(); +var coolView = App.CoolView.create(), + childViews = container.get('childViews'); +childViews.pushObject(coolView); + +var Person2 = Em.Object.extend({ + sayHello: function() { + console.log('Hello from ' + this.get('name')); + } +}); +var people = [ + Person2.create({ name: 'Juan' }), + Person2.create({ name: 'Charles' }), + Person2.create({ name: 'Majd' }) +]; +people.invoke('sayHello'); + +var arr = [Em.Object.create(), Em.Object.create()]; +arr.setEach('name', 'unknown'); +arr.getEach('name'); + +var Person3 = Em.Object.extend({ + name: null, + isHappy: false +}); +var people2 = [ + Person3.create({ name: 'Yehuda', isHappy: true }), + Person3.create({ name: 'Majd', isHappy: false }) +]; +people2.every((person: Em.Object) => { + return !!person.get('isHappy'); +}); +people2.some((person: Em.Object) => { + return !!person.get('isHappy'); +}); +people2.everyProperty('isHappy', true); +people2.someProperty('isHappy', true); + +// Examples taken from http://emberjs.com/api/classes/Ember.RSVP.Promise.html +var promise = new Ember.RSVP.Promise(function(resolve: Function, reject: Function) { + // on success + resolve('ok!'); + + // on failure + reject('no-k!'); +}); + +promise.then(function(value: any) { + // on fulfillment +}, function(reason: any) { + // on rejection +}); diff --git a/ember/ember-1.11.3.d.ts b/ember/ember-1.11.3.d.ts new file mode 100644 index 0000000000..c24661d763 --- /dev/null +++ b/ember/ember-1.11.3.d.ts @@ -0,0 +1,3492 @@ +// Type definitions for Ember.js 1.11.3 +// Project: http://emberjs.com/ +// Definitions by: Jed Mao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare var Handlebars: HandlebarsStatic; + +declare namespace EmberStates { + + interface Transition { + targetName: string; + urlMethod: string; + intent: any; + params: {}|any; + pivotHandler: any; + resolveIndex: number; + handlerInfos: any; + resolvedModels: {}|any; + isActive: boolean; + state: any; + queryParams: {}|any; + queryParamsOnly: boolean; + + isTransition: boolean; + + /** + The Transition's internal promise. Calling `.then` on this property + is that same as calling `.then` on the Transition object itself, but + this property is exposed for when you want to pass around a + Transition's promise, but not the Transition object itself, since + Transition object can be externally `abort`ed, while the promise + cannot. + */ + promise: Ember.RSVP.Promise; + + /** + Custom state can be stored on a Transition's `data` object. + This can be useful for decorating a Transition within an earlier + hook and shared with a later hook. Properties set on `data` will + be copied to new transitions generated by calling `retry` on this + transition. + */ + data: any; + + /** + A standard promise hook that resolves if the transition + succeeds and rejects if it fails/redirects/aborts. + + Forwards to the internal `promise` property which you can + use in situations where you want to pass around a thennable, + but not the Transition itself. + + @arg {Function} onFulfilled + @arg {Function} onRejected + @arg {String} label optional string for labeling the promise. Useful for tooling. + @return {Promise} + */ + then(onFulfilled: Function, onRejected?: Function, label?: string): Ember.RSVP.Promise; + + /** + Forwards to the internal `promise` property which you can + use in situations where you want to pass around a thennable, + but not the Transition itself. + + @method catch + @arg {Function} onRejection + @arg {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + catch(onRejection: Function, label?: string): Ember.RSVP.Promise; + + /** + Forwards to the internal `promise` property which you can + use in situations where you want to pass around a thennable, + but not the Transition itself. + + @method finally + @arg {Function} callback + @arg {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + finally(callback: Function, label?: string): Ember.RSVP.Promise; + + /** + Aborts the Transition. Note you can also implicitly abort a transition + by initiating another transition while a previous one is underway. + */ + abort(): EmberStates.Transition; + normalize(manager: Ember.StateManager, contexts: any[]): void; + + /** + Retries a previously-aborted transition (making sure to abort the + transition if it's still active). Returns a new transition that + represents the new attempt to transition. + */ + retry(): EmberStates.Transition; + + /** + Sets the URL-changing method to be employed at the end of a + successful transition. By default, a new Transition will just + use `updateURL`, but passing 'replace' to this method will + cause the URL to update using 'replaceWith' instead. Omitting + a parameter will disable the URL change, allowing for transitions + that don't update the URL at completion (this is also used for + handleURL, since the URL has already changed before the + transition took place). + + @arg {String} method the type of URL-changing method to use + at the end of a transition. Accepted values are 'replace', + falsy values, or any other non-falsy value (which is + interpreted as an updateURL transition). + + @return {Transition} this transition + */ + method(method: string): EmberStates.Transition; + + /** + Fires an event on the current list of resolved/resolving + handlers within this transition. Useful for firing events + on route hierarchies that haven't fully been entered yet. + + Note: This method is also aliased as `send` + + @arg {Boolean} [ignoreFailure=false] a boolean specifying whether unhandled events throw an error + @arg {String} name the name of the event to fire + */ + trigger(ignoreFailure:boolean, eventName: string): void; + /** + Fires an event on the current list of resolved/resolving + handlers within this transition. Useful for firing events + on route hierarchies that haven't fully been entered yet. + + Note: This method is also aliased as `send` + + @arg {String} name the name of the event to fire + */ + trigger(eventName: string): void; + + /** + Transitions are aborted and their promises rejected + when redirects occur; this method returns a promise + that will follow any redirects that occur and fulfill + with the value fulfilled by any redirecting transitions + that occur. + + @return {Promise} a promise that fulfills with the same + value that the final redirecting transition fulfills with + */ + followRedirects(): Ember.RSVP.Promise; + } + +} + +declare namespace EmberTesting { + + namespace Test { + + class Adapter { + asyncEnd(): void; + asyncStart(): void; + exception(error: string): void; + } + + class QUnitAdapter extends Adapter { } + + } + +} + +interface Function { + observes(...args: string[]): Function; + observesBefore(...args: string[]): Function; + on(...args: string[]): Function; + property(...args: string[]): Function; +} + +interface String { + camelize(): string; + capitalize(): string; + classify(): string; + dasherize(): string; + decamelize(): string; + fmt(...args: string[]): string; + htmlSafe(): typeof Handlebars.SafeString; + loc(...args: string[]): string; + underscore(): string; + w(): string[]; +} + +interface Array { + constructor(arr: any[]): void; + activate(): void; + addArrayObserver(target: any, opts?: EnumerableConfigurationOptions): any[]; + addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): any[]; + any(callback: Function, target?: any): boolean; + anyBy(key: string, value?: string): boolean; + arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): any[]; + arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): any[]; + someProperty(key: string, value?: any): boolean; + clear(): any[]; + compact(): any[]; + contains(obj: any): boolean; + enumerableContentDidChange(start: number, removing: number, adding: number): any; + enumerableContentDidChange(start: number, removing: Ember.Enumerable, adding: number): any; + enumerableContentDidChange(start: number, removing: number, adding: Ember.Enumerable): any; + enumerableContentDidChange(start: number, removing: Ember.Enumerable, adding: Ember.Enumerable): any; + enumerableContentDidChange(removing: number, adding: number): any; + enumerableContentDidChange(removing: Ember.Enumerable, adding: number): any; + enumerableContentDidChange(removing: number, adding: Ember.Enumerable): any; + enumerableContentDidChange(removing: Ember.Enumerable, adding: Ember.Enumerable): any; + enumerableContentWillChange(removing: number, adding: number): any[]; + enumerableContentWillChange(removing: Ember.Enumerable, adding: number): any[]; + enumerableContentWillChange(removing: number, adding: Ember.Enumerable): any[]; + enumerableContentWillChange(removing: Ember.Enumerable, adding: Ember.Enumerable): any[]; + every(callback: Function, target?: any): boolean; + everyBy(key: string, value?: string): boolean; + everyProperty(key: string, value?: any): boolean; + filter(callback: Function, target?: any): any[]; + filterBy(key: string, value?: string): any[]; + + /** + Returns the first item in the array for which the callback returns true. + This method works similar to the `filter()` method defined in JavaScript 1.6 + except that it will stop working on the array once a match is found. + The callback method you provide should have the following signature (all + parameters are optional): + ```javascript + function(item, index, enumerable); + ``` + - `item` is the current item in the iteration. + - `index` is the current index in the iteration. + - `enumerable` is the enumerable object itself. + It should return the `true` to include the item in the results, `false` + otherwise. + Note that in addition to a callback, you can also pass an optional target + object that will be set as `this` on the context. This is a good way + to give your iterator function access to the current object. + @function find + @arg callback The callback to execute + @arg {Object} [target] The target object to use + @return {Object} Found item or `undefined`. +*/ + find(callback: Function, target?: any): any; + findBy(key: string, value?: string): any; + forEach(callback: Function, target?: any): any; + getEach(key: string): any[]; + indexOf(object: any, startAt?: number): number; + insertAt(idx: number, object: any): any[]; + invoke(methodName: string, ...args: any[]): any[]; + lastIndexOf(object: any, startAt?: number): number; + map(callback: Function, target?: any): any[]; + mapBy(key: string): any[]; + nextObject(index: number, previousObject: any, context: any): any; + objectAt(idx: number): any; + objectsAt(...args: number[]): any[]; + popObject(): any; + pushObject(obj: any): any; + pushObjects(...args: any[]): any[]; + reduce(callback: ReduceCallback, initialValue: any, reducerProperty: string): any; + reject: ItemIndexEnumerableCallbackTarget; + rejectBy(key: string, value?: string): any[]; + removeArrayObserver(target: any, opts: EnumerableConfigurationOptions): any[]; + removeAt(start: number, len: number): any; + removeEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): any[]; + replace(idx: number, amt: number, objects: any[]): void; + reverseObjects(): any[]; + setEach(key: string, value?: any): any; + setObjects(objects: any[]): any[]; + shiftObject(): any; + slice(beginIndex?: number, endIndex?: number): any[]; + some(callback: Function, target?: any): boolean; + toArray(): any[]; + uniq(): any[]; + unshiftObject(object: any): any; + unshiftObjects(objects: any[]): any[]; + without(value: any): any[]; + '[]': any[]; + '@each': Ember.EachProxy; + Boolean: boolean; + firstObject: any; + hasEnumerableObservers: boolean; + lastObject: any; + addObject(object: any): any; + addObjects(objects: Ember.Enumerable): any[]; + removeObject(object: any): any; + removeObjects(objects: Ember.Enumerable): any[]; + addObserver: ModifyObserver; + beginPropertyChanges(): any[]; + cacheFor(keyName: string): any; + decrementProperty(keyName: string, decrement?: number): number; + endPropertyChanges(): any[]; + get(keyName: string): any; + getProperties(...args: string[]): {}; + getProperties(keys: string[]): {}; + getWithDefault(keyName: string, defaultValue: any): any; + hasObserverFor(key: string): boolean; + incrementProperty(keyName: string, increment?: number): number; + notifyPropertyChange(keyName: string): any[]; + propertyDidChange(keyName: string): any[]; + propertyWillChange(keyName: string): any[]; + removeObserver(key: string, target: any, method: string): Ember.Observable; + removeObserver(key: string, target: any, method: Function): Ember.Observable; + set(keyName: string, value: any): any[]; + setProperties(hash: {}): any[]; + toggleProperty(keyName: string): any; + copy(deep: boolean): any[]; + frozenCopy(): any[]; + // 1.3 + isAny(key: string, value?: string): boolean; + isEvery(key: string, value?: string): boolean; +} + +interface ApplicationCreateArguments { + customEvents?: {}; + rootElement?: string; + /** + Basic logging of successful transitions. + **/ + LOG_TRANSITIONS?: boolean; + /** + Detailed logging of all routing steps. + **/ + LOG_TRANSITIONS_INTERNAL?: boolean; +} + +interface ApplicationInitializerArguments { + name?: string; + initialize?: ApplicationInitializerFunction; +} + +interface ApplicationInitializerFunction { + (container: Ember.Container, application: Ember.Application): void; +} + +interface CoreObjectArguments { + /** + An overridable method called when objects are instantiated. By default, does nothing unless it is + overridden during class definition. NOTE: If you do override init for a framework class like Ember.View + or Ember.ArrayController, be sure to call this._super() in your init declaration! If you don't, Ember + may not have an opportunity to do important setup work, and you'll see strange behavior in your application. + **/ + init?: Function; + /** + Override to implement teardown. + **/ + willDestroy?: Function; + + [propName: string]: any; +} + +interface EnumerableConfigurationOptions { + willChange?: boolean ; + didChange?: boolean ; +} + +interface ItemIndexEnumerableCallbackTarget { + (callback: ItemIndexEnumerableCallback, target?: any): any[]; +} + +interface ItemIndexEnumerableCallback { + (item: any, index: number, enumerable: Ember.Enumerable): void; +} + +interface ReduceCallback { + (previousValue: any, item: any, index: number, enumerable: Ember.Enumerable): void; +} + +interface TransitionsHash { + contexts: any[]; + exitStates: Ember.State[]; + enterStates: Ember.State[]; + resolveState: Ember.State; +} + +interface ActionsHash { + willTransition?: Function; + error?: Function; +} + +interface DisconnectOutletOptions { + outlet?: string; + parentView?: string; +} + +interface RenderOptions { + into?: string; + controller?: string; + model?: any; + outlet?: string; + view?: string; +} + +interface ModifyObserver { + (obj: any, path: string, target: any, method?: Function): void; + (obj: any, path: string, target: any, method?: string): void; + (obj: any, path: string, func: Function, method?: Function): void; + (obj: any, path: string, func: Function, method?: string): void; +} + +declare namespace Ember { + /** + Alias for jQuery. + **/ + // ReSharper disable once DuplicatingLocalDeclaration + var $: JQueryStatic; + /** + Creates an Ember.NativeArray from an Array like object. Does not modify the original object. + Ember.A is not needed if Ember.EXTEND_PROTOTYPES is true (the default value). However, it is + recommended that you use Ember.A when creating addons for ember or when you can not garentee + that Ember.EXTEND_PROTOTYPES will be true. + **/ + function A(arr?: any[]): NativeArray; + /** + The Ember.ActionHandler mixin implements support for moving an actions property to an _actions + property at extend time, and adding _actions to the object's mergedProperties list. + **/ + class ActionHandlerMixin { + /** + Triggers a named action on the ActionHandler + **/ + send(name: string, ...args: any[]): void; + /** + The collection of functions, keyed by name, available on this ActionHandler as action targets. + **/ + actions: ActionsHash; + } + /** + An instance of Ember.Application is the starting point for every Ember application. It helps to + instantiate, initialize and coordinate the many objects that make up your app. + **/ + class Application extends Namespace { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + static initializer(args?: ApplicationInitializerArguments): void; + /** + Call advanceReadiness after any asynchronous setup logic has completed. + Each call to deferReadiness must be matched by a call to advanceReadiness + or the application will never become ready and routing will not begin. + **/ + advanceReadiness(): void; + /** + Use this to defer readiness until some condition is true. + + This allows you to perform asynchronous setup logic and defer + booting your application until the setup has finished. + + However, if the setup requires a loading UI, it might be better + to use the router for this purpose. + */ + deferReadiness(): void; + /** + defines an injection or typeInjection + **/ + inject(factoryNameOrType: string, property: string, injectionName: string): void; + /** + This injects the test helpers into the window's scope. If a function of the + same name has already been defined it will be cached (so that it can be reset + if the helper is removed with `unregisterHelper` or `removeTestHelpers`). + Any callbacks registered with `onInjectHelpers` will be called once the + helpers have been injected. + **/ + injectTestHelpers(): void; + /** + registers a factory for later injection + @param fullName type:name (e.g., 'model:user') + @param factory (e.g., App.Person) + **/ + register(fullName: string, factory: Function, options?: {}): void; + /** + This removes all helpers that have been registered, and resets and functions + that were overridden by the helpers. + **/ + removeTestHelpers(): void; + /** + Reset the application. This is typically used only in tests. + **/ + reset(): void; + /** + This hook defers the readiness of the application, so that you can start + the app when your tests are ready to run. It also sets the router's + location to 'none', so that the window's location will not be modified + (preventing both accidental leaking of state between tests and interference + with your testing framework). + **/ + setupForTesting(): void; + /** + The DOM events for which the event dispatcher should listen. + */ + customEvents: {}; + /** + The Ember.EventDispatcher responsible for delegating events to this application's views. + **/ + eventDispatcher: EventDispatcher; + /** + Set this to provide an alternate class to Ember.DefaultResolver + **/ + resolver: DefaultResolver; + /** + The root DOM element of the Application. This can be specified as an + element or a jQuery-compatible selector string. + + This is the element that will be passed to the Application's, eventDispatcher, + which sets up the listeners for event delegation. Every view in your application + should be a child of the element you specify here. + **/ + rootElement: HTMLElement; + /** + Called when the Application has become ready. + The call will be delayed until the DOM has become ready. + **/ + ready: Function; + /** + Application's router. + **/ + Router: Router; + } + /** + This module implements Observer-friendly Array-like behavior. This mixin is picked up by the + Array class as well as other controllers, etc. that want to appear to be arrays. + **/ + class Array implements Enumerable { + addArrayObserver(target: any, opts?: EnumerableConfigurationOptions): any[]; + addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; + any(callback: Function, target?: any): boolean; + anyBy(key: string, value?: string): boolean; + arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): any[]; + arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): any[]; + someProperty(key: string, value?: string): boolean; + compact(): any[]; + contains(obj: any): boolean; + enumerableContentDidChange(start: number, removing: number, adding: number): any; + enumerableContentDidChange(start: number, removing: Enumerable, adding: number): any; + enumerableContentDidChange(start: number, removing: number, adding: Enumerable): any; + enumerableContentDidChange(start: number, removing: Enumerable, adding: Enumerable): any; + enumerableContentDidChange(removing: number, adding: number): any; + enumerableContentDidChange(removing: Enumerable, adding: number): any; + enumerableContentDidChange(removing: number, adding: Enumerable): any; + enumerableContentDidChange(removing: Enumerable, adding: Enumerable): any; + enumerableContentWillChange(removing: number, adding: number): Enumerable; + enumerableContentWillChange(removing: Enumerable, adding: number): Enumerable; + enumerableContentWillChange(removing: number, adding: Enumerable): Enumerable; + enumerableContentWillChange(removing: Enumerable, adding: Enumerable): Enumerable; + every(callback: Function, target?: any): boolean; + everyBy(key: string, value?: string): boolean; + everyProperty(key: string, value?: string): boolean; + filter(callback: Function, target: any): any[]; + filterBy(key: string, value?: string): any[]; + find(callback: Function, target?: any): any; + findBy(key: string, value?: string): any; + forEach(callback: Function, target?: any): any; + getEach(key: string): any[]; + indexOf(object: any, startAt: number): number; + invoke(methodName: string, ...args: any[]): any[]; + lastIndexOf(object: any, startAt: number): number; + map: ItemIndexEnumerableCallbackTarget; + mapBy(key: string): any[]; + nextObject(index: number, previousObject: any, context: any): any; + objectAt(idx: number): any; + objectsAt(...args: number[]): any[]; + reduce(callback: ReduceCallback, initialValue: any, reducerProperty: string): any; + reject: ItemIndexEnumerableCallbackTarget; + rejectBy(key: string, value?: string): any[]; + removeArrayObserver(target: any, opts: EnumerableConfigurationOptions): any[]; + removeEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; + setEach(key: string, value?: any): any; + slice(beginIndex?: number, endIndex?: number): any[]; + some(callback: Function, target?: any): boolean; + toArray(): any[]; + uniq(): Enumerable; + without(value: any): Enumerable; + '@each': EachProxy; + Boolean: boolean; + '[]': any[]; + firstObject: any; + hasEnumerableObservers: boolean; + lastObject: any; + length: number; + } + /** + Provides a way for you to publish a collection of objects so that you can easily bind to the + collection from a Handlebars #each helper, an Ember.CollectionView, or other controllers. + **/ + class ArrayController extends ArrayProxy implements SortableMixin, ControllerMixin { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + lookupItemController(object: any): string; + arrangedContent: any; + itemController: string; + sortAscending: boolean; + sortFunction: Comparable; + sortProperties: any[]; + replaceRoute(name: string, ...args: any[]): void; + transitionToRoute(name: string, ...args: any[]): void; + controllers: {}; + needs: string[]; + target: any; + model: any; + queryParams: any; + send(name: string, ...args: any[]): void; + actions: {}; + + } + /** + Array polyfills to support ES5 features in older browsers. + **/ + var ArrayPolyfills: { + map: typeof Array.prototype.map; + forEach: typeof Array.prototype.forEach; + indexOf: typeof Array.prototype.indexOf; + }; + /** + An ArrayProxy wraps any other object that implements Ember.Array and/or Ember.MutableArray, + forwarding all requests. This makes it very useful for a number of binding use cases or other cases + where being able to swap out the underlying array is useful. + **/ + class ArrayProxy extends Object implements MutableArray { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + addArrayObserver(target: any, opts?: EnumerableConfigurationOptions): any[]; + addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; + any(callback: Function, target?: any): boolean; + anyBy(key: string, value?: string): boolean; + arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): any[]; + arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): any[]; + someProperty(key: string, value?: string): boolean; + clear(): any[]; + compact(): any[]; + contains(obj: any): boolean; + enumerableContentDidChange(start: number, removing: number, adding: number): any; + enumerableContentDidChange(start: number, removing: Enumerable, adding: number): any; + enumerableContentDidChange(start: number, removing: number, adding: Enumerable): any; + enumerableContentDidChange(start: number, removing: Enumerable, adding: Enumerable): any; + enumerableContentDidChange(removing: number, adding: number): any; + enumerableContentDidChange(removing: Enumerable, adding: number): any; + enumerableContentDidChange(removing: number, adding: Enumerable): any; + enumerableContentDidChange(removing: Enumerable, adding: Enumerable): any; + enumerableContentWillChange(removing: number, adding: number): Enumerable; + enumerableContentWillChange(removing: Enumerable, adding: number): Enumerable; + enumerableContentWillChange(removing: number, adding: Enumerable): Enumerable; + enumerableContentWillChange(removing: Enumerable, adding: Enumerable): Enumerable; + every(callback: Function, target?: any): boolean; + everyBy(key: string, value?: string): boolean; + everyProperty(key: string, value?: string): boolean; + filter(callback: Function, target: any): any[]; + filterBy(key: string, value?: string): any[]; + find(callback: Function, target: any): any; + findBy(key: string, value?: string): any; + forEach(callback: Function, target?: any): any; + getEach(key: string): any[]; + indexOf(object: any, startAt: number): number; + insertAt(idx: number, object: any): any[]; + invoke(methodName: string, ...args: any[]): any[]; + lastIndexOf(object: any, startAt: number): number; + map: ItemIndexEnumerableCallbackTarget; + mapBy(key: string): any[]; + nextObject(index: number, previousObject: any, context: any): any; + objectAt(idx: number): any; + objectAtContent(idx: number): any; + objectsAt(...args: number[]): any[]; + popObject(): any; + pushObject(obj: any): any; + pushObjects(...args: any[]): any[]; + reduce(callback: ReduceCallback, initialValue: any, reducerProperty: string): any; + reject: ItemIndexEnumerableCallbackTarget; + rejectBy(key: string, value?: string): any[]; + removeArrayObserver(target: any, opts: EnumerableConfigurationOptions): any[]; + removeAt(start: number, len: number): any; + removeEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; + replace(idx: number, amt: number, objects: any[]): any; + replaceContent(idx: number, amt: number, objects: any[]): void; + reverseObjects(): any[]; + setEach(key: string, value?: any): any; + setObjects(objects: any[]): any[]; + shiftObject(): any; + slice(beginIndex?: number, endIndex?: number): any[]; + some(callback: Function, target?: any): boolean; + toArray(): any[]; + uniq(): Enumerable; + unshiftObject(object: any): any; + unshiftObjects(objects: any[]): any[]; + without(value: any): Enumerable; + '[]': any[]; + '@each': EachProxy; + Boolean: boolean; + firstObject: any; + hasEnumerableObservers: boolean; + lastObject: any; + length: number; + addObject(object: any): any; + addObjects(objects: Enumerable): MutableEnumberable; + removeObject(object: any): any; + removeObjects(objects: Enumerable): MutableEnumberable; + } + var BOOTED: boolean; + /** + Connects the properties of two objects so that whenever the value of one property changes, + the other property will be changed also. + **/ + class Binding { + constructor(toPath: string, fromPath: string); + connect(obj: any): Binding; + copy(): Binding; + disconnect(obj: any): Binding; + from(path: string): Binding; + static oneWay(from: string, flag?: boolean): Binding; + to(path: string): Binding; + to(pathTuple: any[]): Binding; + toString(): string; + } + class Button extends View implements TargetActionSupport { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + triggerAction(opts: {}): boolean; + } + /** + The internal class used to create text inputs when the {{input}} helper is used + with type of checkbox. See Handlebars.helpers.input for usage details. + **/ + class Checkbox extends View { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + } + /** + An Ember.View descendent responsible for managing a collection (an array or array-like object) + by maintaining a child view object and associated DOM representation for each item in the array + and ensuring that child views and their associated rendered HTML are updated when items in the + array are added, removed, or replaced. + **/ + class CollectionView extends ContainerView { + arrayDidChange(content: any[], start: number, removed: number, added: number): void; + arrayWillChange(content: any[], start: number, removed: number): void; + createChildView(viewClass: {}, attrs?: {}): CollectionView; + destroy(): CollectionView; + init(): void; + static CONTAINER_MAP: {}; + content: any[]; + emptyView: View; + itemViewClass: View; + } + /** + Implements some standard methods for comparing objects. Add this mixin to any class + you create that can compare its instances. + **/ + class Comparable { + compare(a: any, b: any): number; + } + /** + A view that is completely isolated. Property access in its templates go to the view object + and actions are targeted at the view object. There is no access to the surrounding context or + outer controller; all contextual information is passed in. + **/ + class Component extends View { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + sendAction(action: string, context: any): void; + targetObject: Controller; + } + /** + A computed property transforms an objects function into a property. + By default the function backing the computed property will only be called once and the result + will be cached. You can specify various properties that your computed property is dependent on. + This will force the cached result to be recomputed if the dependencies are modified. + **/ + class ComputedProperty { + cacheable(aFlag?: boolean): ComputedProperty; + get(keyName: string): any; + meta(meta: {}): ComputedProperty; + property(...args: string[]): ComputedProperty; + readOnly(): ComputedProperty; + set(keyName: string, newValue: any, oldValue: string): any; + // ReSharper disable UsingOfReservedWord + volatile(): ComputedProperty; + // ReSharper restore UsingOfReservedWord + } + class Container { + constructor(parent: Container); + parent: Container; + children: any[]; + resolver: Function; + registry: {}; + cache: {}; + typeInjections: {}; + injections: {}; + child(): Container; + set(object: {}, key: string, value: any): void; + /** + registers a factory for later injection + @param fullName type:name (e.g., 'model:user') + @param factory (e.g., App.Person) + **/ + register(fullName: string, factory: Function, options?: {}): void; + unregister(fullName: string): void; + resolve(fullName: string): Function; + describe(fullName: string): string; + normalize(fullName: string): string; + makeToString(factory: any, fullName: string): Function; + lookup(fullName: string, options?: {}): any; + lookupFactory(fullName: string): any; + has(fullName: string): boolean; + optionsForType(type: string, options: {}): void; + options(type: string, options: {}): void; + injection(factoryName: string, property: string, injectionName: string): void; + factoryInjection(factoryName: string, property: string, injectionName: string): void; + destroy(): void; + reset(): void; + } + /** + An Ember.View subclass that implements Ember.MutableArray allowing programatic + management of its child views. + **/ + class ContainerView extends View { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + } + class Controller extends Object implements ControllerMixin { + replaceRoute(name: string, ...args: any[]): void; + transitionToRoute(name: string, ...args: any[]): void; + controllers: {}; + model: any; + needs: string[]; + queryParams: any; + target: any; + send(name: string, ...args: any[]): void; + actions: ActionsHash; + } + /** + Additional methods for the ControllerMixin. + **/ + class ControllerMixin extends ActionHandlerMixin { + replaceRoute(name: string, ...args: any[]): void; + transitionToRoute(name: string, ...args: any[]): void; + controllers: {}; + model : any; + needs: string[]; + queryParams: any; + target: any; + } + /** + Implements some standard methods for copying an object. Add this mixin to any object you + create that can create a copy of itself. This mixin is added automatically to the built-in array. + You should generally implement the copy() method to return a copy of the receiver. + Note that frozenCopy() will only work if you also implement Ember.Freezable. + **/ + class Copyable { + copy(deep: boolean): Copyable; + frozenCopy(): Copyable; + } + class CoreObject { + /** + An overridable method called when objects are instantiated. By default, + does nothing unless it is overridden during class definition. + @method init + **/ + init(): void; + + /** + Defines the properties that will be concatenated from the superclass (instead of overridden). + @property concatenatedProperties + @type Array + @default null + **/ + concatenatedProperties: any[]; + + /** + Destroyed object property flag. If this property is true the observers and bindings were + already removed by the effect of calling the destroy() method. + @property isDestroyed + @default false + **/ + isDestroyed: boolean; + /** + Destruction scheduled flag. The destroy() method has been called. The object stays intact + until the end of the run loop at which point the isDestroyed flag is set. + @property isDestroying + @default false + **/ + isDestroying: boolean; + + /** + Destroys an object by setting the `isDestroyed` flag and removing its + metadata, which effectively destroys observers and bindings. + If you try to set a property on a destroyed object, an exception will be + raised. + Note that destruction is scheduled for the end of the run loop and does not + happen immediately. It will set an isDestroying flag immediately. + @method destroy + @return {Ember.Object} receiver + */ + destroy(): CoreObject; + + /** + Override to implement teardown. + @method willDestroy + */ + willDestroy(): void; + + /** + Returns a string representation which attempts to provide more information than Javascript's toString + typically does, in a generic way for all Ember objects (e.g., ""). + @method toString + @return {String} string representation + **/ + toString(): string; + + static isClass: boolean; + static isMethod: boolean; + + /** + Creates a new subclass. + @method extend + @static + @param {Object} [args] - Object containing values to use within the new class + **/ + static extend(args?: CoreObjectArguments): T; + /** + Creates a new subclass. + @method extend + @static + @param {Mixin} [mixins] - One or more Mixin classes + @param {Object} [args] - Object containing values to use within the new class + **/ + static extend(mixins?: Mixin, args?: CoreObjectArguments): T; + + /** + Creates a new subclass. + @method extend + @param {Object} [args] - Object containing values to use within the new class + Non-static method because Ember classes aren't currently 'real' TypeScript classes. + **/ + extend(args ?: CoreObjectArguments): T; + /** + Creates a new subclass. + @method extend + @param {Mixin} [mixins] - One or more Mixin classes + @param {Object} [args] - Object containing values to use within the new class + Non-static method because Ember classes aren't currently 'real' TypeScript classes. + **/ + extend(mixins ? : Mixin, args ?: CoreObjectArguments): T; + + /** + Equivalent to doing extend(arguments).create(). If possible use the normal create method instead. + @method createWithMixins + @static + @param [args] + **/ + static createWithMixins(args?: {}): T; + + /** + Creates an instance of the class. + @method create + @static + @param [args] - A hash containing values with which to initialize the newly instantiated object. + **/ + static create(args?: {}): T; + + /** + Augments a constructor's prototype with additional properties and functions. + To add functions and properties to the constructor itself, see reopenClass. + @method reopen + **/ + static reopen(args?: {}): T; + + /** + Augments a constructor's own properties and functions. + To add functions and properties to instances of a constructor by extending the + constructor's prototype see reopen. + @method reopenClass + **/ + static reopenClass(args?: {}): T; + + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + + /** + Returns the original hash that was passed to meta(). + @method metaForProperty + @static + @param key {String} property name + **/ + static metaForProperty(key: string): {}; + + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + + @method eachComputedProperty + @static + @param {Function} callback + @param {Object} binding + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + } + /** + An abstract class that exists to give view-like behavior to both Ember's main view class Ember.View + and other classes like Ember._SimpleMetamorphView that don't need the fully functionaltiy of Ember.View. + Unless you have specific needs for CoreView, you will use Ember.View in your applications. + **/ + class CoreView extends Object implements ActionHandlerMixin { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + send(name: string, ...args: any[]): void; + actions: ActionsHash; + parentView: CoreView; + } + class DAG { + add(name: string): any; + map(name: string, value: any): void; + addEdge(fromName: string, toName: string): void; + topsort(fn: Function): void; + addEdges(name: string, value: any, before: any, after: any): void; + names: any[]; + vertices: {}; + } + function DEFAULT_GETTER_FUNCTION(name: string): Function; + /** + The DefaultResolver defines the default lookup rules to resolve container lookups before consulting + the container for registered items: + templates are looked up on Ember.TEMPLATES + other names are looked up on the application after converting the name. + For example, controller:post looks up App.PostController by default. + **/ + class DefaultResolver { + resolve(fullName: string): {}; + namespace: Application; + } + class Deferred { + reject(value: any): void; + resolve(value: any): void; + then(resolve: Function, reject: Function): void; + } + class DeferredMixin extends Mixin { + reject(value: any): void; + resolve(value: any): void; + then(resolve: Function, reject: Function): void; + } + /** + Objects of this type can implement an interface to respond to requests to get and set. + The default implementation handles simple properties. + You generally won't need to create or subclass this directly. + **/ + class Descriptor { } + var EMPTY_META: {}; // TODO: define interface + var ENV: {}; + var EXTEND_PROTOTYPES: boolean; + /** + This is the object instance returned when you get the @each property on an array. It uses + the unknownProperty handler to automatically create EachArray instances for property names. + **/ + class EachProxy extends Object { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + unknownProperty(keyName: string, value: any): any[]; + } + /** + This mixin defines the common interface implemented by enumerable objects in Ember. Most of these + methods follow the standard Array iteration API defined up to JavaScript 1.8 (excluding language-specific + features that cannot be emulated in older versions of JavaScript). + This mixin is applied automatically to the Array class on page load, so you can use any of these methods + on simple arrays. If Array already implements one of these methods, the mixin will not override them. + **/ + class Enumerable { + addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; + any(callback: Function, target?: any): boolean; + anyBy(key: string, value?: string): boolean; + someProperty(key: string, value?: string): boolean; + compact(): any[]; + contains(obj: any): boolean; + enumerableContentDidChange(start: number, removing: number, adding: number): any; + enumerableContentDidChange(start: number, removing: Enumerable, adding: number): any; + enumerableContentDidChange(start: number, removing: number, adding: Enumerable): any; + enumerableContentDidChange(start: number, removing: Enumerable, adding: Enumerable): any; + enumerableContentDidChange(removing: number, adding: number): any; + enumerableContentDidChange(removing: Enumerable, adding: number): any; + enumerableContentDidChange(removing: number, adding: Enumerable): any; + enumerableContentDidChange(removing: Enumerable, adding: Enumerable): any; + enumerableContentWillChange(removing: number, adding: number): Enumerable; + enumerableContentWillChange(removing: Enumerable, adding: number): Enumerable; + enumerableContentWillChange(removing: number, adding: Enumerable): Enumerable; + enumerableContentWillChange(removing: Enumerable, adding: Enumerable): Enumerable; + every(callback: Function, target?: any): boolean; + everyBy(key: string, value?: string): boolean; + everyProperty(key: string, value?: string): boolean; + filter(callback: Function, target: any): any[]; + filterBy(key: string, value?: string): any[]; + find(callback: Function, target: any): any; + findBy(key: string, value?: string): any; + forEach(callback: Function, target?: any): any; + getEach(key: string): any[]; + invoke(methodName: string, ...args: any[]): any[]; + map: ItemIndexEnumerableCallbackTarget; + mapBy(key: string): any[]; + nextObject(index: number, previousObject: any, context: any): any; + reduce(callback: ReduceCallback, initialValue: any, reducerProperty: string): any; + reject: ItemIndexEnumerableCallbackTarget; + rejectBy(key: string, value?: string): any[]; + removeEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; + setEach(key: string, value?: any): any; + some(callback: Function, target?: any): boolean; + toArray(): any[]; + uniq(): Enumerable; + without(value: any): Enumerable; + '[]': any[]; + firstObject: any; + hasEnumerableObservers: boolean; + lastObject: any; + } + var EnumerableUtils: {}; // TODO: define interface + /** + A subclass of the JavaScript Error object for use in Ember. + **/ + // Restore this to 'typeof Error' when https://github.com/Microsoft/TypeScript/issues/983 is resolved + // ReSharper disable once DuplicatingLocalDeclaration + var Error: any; // typeof Error; + /** + Handles delegating browser events to their corresponding Ember.Views. For example, when you click on + a view, Ember.EventDispatcher ensures that that view's mouseDown method gets called. + **/ + class EventDispatcher extends Object { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + events: {}; + } + /** + This mixin allows for Ember objects to subscribe to and emit events. + You can also chain multiple event subscriptions. + **/ + class Evented { + has(name: string): boolean; + off(name: string, target: any, method: Function): Evented; + on(name: string, target: any, method: Function): Evented; + one(name: string, target: any, method: Function): Evented; + trigger(name: string, ...args: string[]): void; + } + var FROZEN_ERROR: string; + class Freezable { + freeze(): Freezable; + isFrozen: boolean; + } + var GUID_KEY: string; + namespace Handlebars { + function compile(string: string): Function; + function get(root: any, path: string, options?: {}): any; + function helper(name: string, func: Function, dependentKeys?: string): void; + function helper(name: string, view: View, dependentKeys?: string): void; + class helpers { + action(actionName: string, context: any, options?: {}): void; + bindAttr(options?: {}): string; + connectOutlet(outletName: string, view: {}): void; + control(path: string, modelPath: string, options?: {}): string; + debugger(property: string): void; + disconnectOutlet(outletName: string): void; + each(name: string, path: string, options?: {}): void; + if(context: Function, options?: {}): string; + init(): void; + input(options?: {}): void; + linkTo(routeName: string, context: any, options?: {}): string; + loc(str: string): void; + log(property: string): void; + outlet(property: string): string; + partial(partialName: string): void; + render(name: string, context?: string, options?: {}): string; + textarea(options?: {}): void; + unbound(property: string): string; + unless(context: Function, options?: {}): string; + view(path: string, options?: {}): string; + with(context: Function, options?: {}): string; + yield(options?: {}): string; + } + function precompile(string: string): void; + function registerBoundHelper(name: string, func: Function, dependentKeys?: string): void; + class Compiler { } + class JavaScriptCompiler { } + function registerHelper(name: string, fn: Function, inverse?: boolean): void; + function registerPartial(name: string, str: any): void; + function K(): any; + function createFrame(objec: any): any; + function Exception(message: string): void; + class SafeString { + constructor(str: string); + static toString(): string; + } + function parse(string: string): any; + function print(ast: any): void; + var logger: typeof Ember.Logger; + function log(level: string, str: string): void; + function compile(environment: any, options?: any, context?: any, asObject?: any): any; + } + class HashLocation extends Object { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + } + class HistoryLocation extends Object { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + rootURL: string; + } + var IS_BINDING: RegExp; + class Instrumentation { + getProperties(obj: any, list: any[]): {}; + getProperties(obj: any, ...args: string[]): {}; + instrument(name: string, payload: any, callback: Function, binding: any): void; + reset(): void; + subscribe(pattern: string, object: any): void; + unsubscribe(subscriber: any): void; + } + var K: Function; + var LOG_BINDINGS: boolean; + var LOG_STACKTRACE_ON_DEPRECATION: boolean; + var LOG_VERSION: boolean; + class LinkView extends View { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + init(): void; + active: any; + activeClass: string; + attributeBindings: any; + classNameBindings: string[]; + disabled: any; + disabledClass: string; + eventName: string; + href: any; + loading: any; + loadingClass: string; + loadingHref: string; + rel: any; + replace: boolean; + title: any; + click: Function; + } + class Location { + create(options?: {}): any; + registerImplementation(name: string, implementation: any): void; + } + var Logger: { + assert(param: any): void; + debug(...args: any[]): void; + error(...args: any[]): void; + info(...args: any[]): void; + log(...args: any[]): void; + warn(...args: any[]): void; + }; + function MANDATORY_SETTER_FUNCTION(value: string): void; + var META_KEY: string; + class Map { + copy(): Map; + static create(): Map; + forEach(callback: Function, self: any): void; + get(key: any): any; + has(key: any): boolean; + remove(key: any): boolean; + set(key: any, value: any): void; + length: number; + } + class MapWithDefault extends Map { + copy(): MapWithDefault; + static create(): MapWithDefault; + } + class Mixin { + apply(obj: any): any; + /** + Creates an instance of the class. + @param arguments A hash containing values with which to initialize the newly instantiated object. + **/ + static create(...args: CoreObjectArguments[]): T; + detect(obj: any): boolean; + reopen(args?: {}): T; + } + class MutableArray implements Array, MutableEnumberable { + addArrayObserver(target: any, opts?: EnumerableConfigurationOptions): any[]; + addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; + any(callback: Function, target?: any): boolean; + anyBy(key: string, value?: string): boolean; + arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): any[]; + arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): any[]; + someProperty(key: string, value?: string): boolean; + clear(): any[]; + compact(): any[]; + contains(obj: any): boolean; + enumerableContentDidChange(start: number, removing: number, adding: number): any; + enumerableContentDidChange(start: number, removing: Enumerable, adding: number): any; + enumerableContentDidChange(start: number, removing: number, adding: Enumerable): any; + enumerableContentDidChange(start: number, removing: Enumerable, adding: Enumerable): any; + enumerableContentDidChange(removing: number, adding: number): any; + enumerableContentDidChange(removing: Enumerable, adding: number): any; + enumerableContentDidChange(removing: number, adding: Enumerable): any; + enumerableContentDidChange(removing: Enumerable, adding: Enumerable): any; + enumerableContentWillChange(removing: number, adding: number): Enumerable; + enumerableContentWillChange(removing: Enumerable, adding: number): Enumerable; + enumerableContentWillChange(removing: number, adding: Enumerable): Enumerable; + enumerableContentWillChange(removing: Enumerable, adding: Enumerable): Enumerable; + every(callback: Function, target?: any): boolean; + everyBy(key: string, value?: string): boolean; + everyProperty(key: string, value?: string): boolean; + filter(callback: Function, target: any): any[]; + filterBy(key: string, value?: string): any[]; + find(callback: Function, target: any): any; + findBy(key: string, value?: string): any; + forEach(callback: Function, target?: any): any; + getEach(key: string): any[]; + indexOf(object: any, startAt: number): number; + insertAt(idx: number, object: any): any[]; + invoke(methodName: string, ...args: any[]): any[]; + lastIndexOf(object: any, startAt: number): number; + map: ItemIndexEnumerableCallbackTarget; + mapBy(key: string): any[]; + nextObject(index: number, previousObject: any, context: any): any; + objectAt(idx: number): any; + objectsAt(...args: number[]): any[]; + popObject(): any; + pushObject(obj: any): any; + pushObjects(...args: any[]): any[]; + reduce(callback: ReduceCallback, initialValue: any, reducerProperty: string): any; + reject: ItemIndexEnumerableCallbackTarget; + rejectBy(key: string, value?: string): any[]; + removeArrayObserver(target: any, opts: EnumerableConfigurationOptions): any[]; + removeAt(start: number, len: number): any; + removeEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; + replace(idx: number, amt: number, objects: any[]): any; + reverseObjects(): any[]; + setEach(key: string, value?: any): any; + setObjects(objects: any[]): any[]; + shiftObject(): any; + slice(beginIndex?: number, endIndex?: number): any[]; + some(callback: Function, target?: any): boolean; + toArray(): any[]; + uniq(): Enumerable; + unshiftObject(object: any): any; + unshiftObjects(objects: any[]): any[]; + without(value: any): Enumerable; + '[]': any[]; + '@each': EachProxy; + Boolean: boolean; + firstObject: any; + hasEnumerableObservers: boolean; + lastObject: any; + length: number; + addObject(object: any): any; + addObjects(objects: Enumerable): MutableEnumberable; + removeObject(object: any): any; + removeObjects(objects: Enumerable): MutableEnumberable; + } + class MutableEnumberable implements Enumerable { + addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; + addObject(object: any): any; + addObjects(objects: Enumerable): MutableEnumberable; + any(callback: Function, target?: any): boolean; + anyBy(key: string, value?: string): boolean; + someProperty(key: string, value?: string): boolean; + compact(): any[]; + contains(obj: any): boolean; + enumerableContentDidChange(start: number, removing: number, adding: number): any; + enumerableContentDidChange(start: number, removing: Enumerable, adding: number): any; + enumerableContentDidChange(start: number, removing: number, adding: Enumerable): any; + enumerableContentDidChange(start: number, removing: Enumerable, adding: Enumerable): any; + enumerableContentDidChange(removing: number, adding: number): any; + enumerableContentDidChange(removing: Enumerable, adding: number): any; + enumerableContentDidChange(removing: number, adding: Enumerable): any; + enumerableContentDidChange(removing: Enumerable, adding: Enumerable): any; + enumerableContentWillChange(removing: number, adding: number): Enumerable; + enumerableContentWillChange(removing: Enumerable, adding: number): Enumerable; + enumerableContentWillChange(removing: number, adding: Enumerable): Enumerable; + enumerableContentWillChange(removing: Enumerable, adding: Enumerable): Enumerable; + every(callback: Function, target?: any): boolean; + everyBy(key: string, value?: string): boolean; + everyProperty(key: string, value?: string): boolean; + filter(callback: Function, target: any): any[]; + filterBy(key: string, value?: string): any[]; + find(callback: Function, target: any): any; + findBy(key: string, value?: string): any; + forEach(callback: Function, target?: any): any; + getEach(key: string): any[]; + invoke(methodName: string, ...args: any[]): any[]; + map: ItemIndexEnumerableCallbackTarget; + mapBy(key: string): any[]; + nextObject(index: number, previousObject: any, context: any): any; + reduce(callback: ReduceCallback, initialValue: any, reducerProperty: string): any; + reject: ItemIndexEnumerableCallbackTarget; + rejectBy(key: string, value?: string): any[]; + removeEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; + removeObject(object: any): any; + removeObjects(objects: Enumerable): MutableEnumberable; + setEach(key: string, value?: any): any; + some(callback: Function, target?: any): boolean; + toArray(): any[]; + uniq(): Enumerable; + without(value: any): Enumerable; + '[]': any[]; + firstObject: any; + hasEnumerableObservers: boolean; + lastObject: any; + } + var NAME_KEY: string; + class Namespace extends Object { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + } + class NativeArray implements MutableArray, Observable, Copyable { + constructor(arr: any[]); + static activate(): void; + addArrayObserver(target: any, opts?: EnumerableConfigurationOptions): any[]; + addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; + any(callback: Function, target?: any): boolean; + anyBy(key: string, value?: string): boolean; + arrayContentDidChange(startIdx: number, removeAmt: number, addAmt: number): any[]; + arrayContentWillChange(startIdx: number, removeAmt: number, addAmt: number): any[]; + someProperty(key: string, value?: any): boolean; + clear(): any[]; + compact(): any[]; + contains(obj: any): boolean; + enumerableContentDidChange(start: number, removing: number, adding: number): any; + enumerableContentDidChange(start: number, removing: Enumerable, adding: number): any; + enumerableContentDidChange(start: number, removing: number, adding: Enumerable): any; + enumerableContentDidChange(start: number, removing: Enumerable, adding: Enumerable): any; + enumerableContentDidChange(removing: number, adding: number): any; + enumerableContentDidChange(removing: Enumerable, adding: number): any; + enumerableContentDidChange(removing: number, adding: Enumerable): any; + enumerableContentDidChange(removing: Enumerable, adding: Enumerable): any; + enumerableContentWillChange(removing: number, adding: number): Enumerable; + enumerableContentWillChange(removing: Enumerable, adding: number): Enumerable; + enumerableContentWillChange(removing: number, adding: Enumerable): Enumerable; + enumerableContentWillChange(removing: Enumerable, adding: Enumerable): Enumerable; + every(callback: Function, target?: any): boolean; + everyBy(key: string, value?: string): boolean; + everyProperty(key: string, value?: any): boolean; + filter(callback: Function, target: any): any[]; + filterBy(key: string, value?: string): any[]; + find(callback: Function, target: any): any; + findBy(key: string, value?: string): any; + forEach(callback: Function, target?: any): any; + getEach(key: string): any[]; + indexOf(object: any, startAt: number): number; + insertAt(idx: number, object: any): any[]; + invoke(methodName: string, ...args: any[]): any[]; + lastIndexOf(object: any, startAt: number): number; + map: ItemIndexEnumerableCallbackTarget; + mapBy(key: string): any[]; + nextObject(index: number, previousObject: any, context: any): any; + objectAt(idx: number): any; + objectsAt(...args: number[]): any[]; + popObject(): any; + pushObject(obj: any): any; + pushObjects(...args: any[]): any[]; + reduce(callback: ReduceCallback, initialValue: any, reducerProperty: string): any; + reject: ItemIndexEnumerableCallbackTarget; + rejectBy(key: string, value?: string): any[]; + removeArrayObserver(target: any, opts: EnumerableConfigurationOptions): any[]; + removeAt(start: number, len: number): any; + removeEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; + replace(idx: number, amt: number, objects: any[]): any; + reverseObjects(): any[]; + setEach(key: string, value?: any): any; + setObjects(objects: any[]): any[]; + shiftObject(): any; + slice(beginIndex?: number, endIndex?: number): any[]; + some(callback: Function, target?: any): boolean; + toArray(): any[]; + uniq(): Enumerable; + unshiftObject(object: any): any; + unshiftObjects(objects: any[]): any[]; + without(value: any): Enumerable; + '[]': any[]; + '@each': EachProxy; + Boolean: boolean; + firstObject: any; + hasEnumerableObservers: boolean; + lastObject: any; + length: number; + addObject(object: any): any; + addObjects(objects: Enumerable): MutableEnumberable; + removeObject(object: any): any; + removeObjects(objects: Enumerable): MutableEnumberable; + addObserver: ModifyObserver; + beginPropertyChanges(): Observable; + cacheFor(keyName: string): any; + decrementProperty(keyName: string, decrement?: number): number; + endPropertyChanges(): Observable; + get(keyName: string): any; + getProperties(...args: string[]): {}; + getProperties(keys: string[]): {}; + getWithDefault(keyName: string, defaultValue: any): any; + hasObserverFor(key: string): boolean; + incrementProperty(keyName: string, increment?: number): number; + notifyPropertyChange(keyName: string): Observable; + propertyDidChange(keyName: string): Observable; + propertyWillChange(keyName: string): Observable; + removeObserver(key: string, target: any, method: string): void; + removeObserver(key: string, target: any, method: Function): void; + set(keyName: string, value: any): Observable; + setProperties(hash: {}): Observable; + toggleProperty(keyName: string): any; + copy(deep: boolean): Copyable; + frozenCopy(): Copyable; + } + class NoneLocation extends Object { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + } + var ORDER_DEFINITION: string[]; + class Object extends CoreObject implements Observable { + addObserver: ModifyObserver; + beginPropertyChanges(): Observable; + cacheFor(keyName: string): any; + decrementProperty(keyName: string, decrement?: number): number; + endPropertyChanges(): Observable; + + /** + * Retrieves the value of a property from the object + * @param keyName + * @returns {} + */ + get(keyName: string): any; + + /** + * Retrieves the value of a property from the object + * @param keyName + * @returns {} + */ + get(keyName: string): T; + + getProperties(...args: string[]): {}; + getProperties(keys: string[]): {}; + getWithDefault(keyName: string, defaultValue: any): any; + hasObserverFor(key: string): boolean; + incrementProperty(keyName: string, increment?: number): number; + notifyPropertyChange(keyName: string): Observable; + propertyDidChange(keyName: string): Observable; + propertyWillChange(keyName: string): Observable; + removeObserver(key: string, target: any, method: string): Observable; + removeObserver(key: string, target: any, method: Function): Observable; + set(keyName: string, value: any): Observable; + setProperties(hash: {}): Observable; + toggleProperty(keyName: string): any; + } + class ObjectController extends ObjectProxy implements ControllerMixin { + replaceRoute(name: string, ...args: any[]): void; + transitionToRoute(name: string, ...args: any[]): void; + controllers: Object; + needs: string[]; + target: any; + model: any; + queryParams: any; + send(name: string, ...args: any[]): void; + actions: {}; + } + class ObjectProxy extends Object { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + /** + The object whose properties will be forwarded. + **/ + content: Object; + } + class Observable { + addObserver: ModifyObserver; + beginPropertyChanges(): Observable; + cacheFor(keyName: string): any; + decrementProperty(keyName: string, decrement?: number): number; + endPropertyChanges(): Observable; + get(keyName: string): any; + getProperties(...args: string[]): {}; + getProperties(keys: string[]): {}; + getWithDefault(keyName: string, defaultValue: any): any; + hasObserverFor(key: string): boolean; + incrementProperty(keyName: string, increment?: number): number; + notifyPropertyChange(keyName: string): Observable; + propertyDidChange(keyName: string): Observable; + propertyWillChange(keyName: string): Observable; + removeObserver(key: string, target: {}, method: string): void; + removeObserver(key: string, target: {}, method: Function): void; + set(keyName: string, value: any): Observable; + setProperties(hash: {}): Observable; + /** + Set the value of a boolean property to the opposite of its current value. + */ + toggleProperty(keyName: string): boolean; + } + class OrderedSet { + add(obj: any): void; + clear(): void; + copy(): OrderedSet; + static create(): OrderedSet; + forEach(fn: Function, self: any): void; + has(obj: any): boolean; + isEmpty(): boolean; + remove(obj: any): void; + toArray(): any[]; + } + + // FYI - RSVP source comes from https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/promise.js + namespace RSVP { + interface PromiseResolve { + (value?: any): void; + } + interface PromiseReject { + (reason?: any): void; + } + interface PromiseResolverFunction { + (resolve: PromiseResolve, reject: PromiseReject): void; + } + + class Promise { + + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + @class RSVP.Promise + @param {function} resolver + @param {String} label optional string for labeling the promise. + Useful for tooling. + @constructor + */ + constructor(resolver: PromiseResolverFunction, label?: string); + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + @method then + @param {Function} onFulfilled + @param {Function} onRejected + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + then(onFulfilled?: Function, onRejected?: Function): Promise; + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + @method catch + @param {Function} onRejection + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + catch(onRejection: Function, label?: string): Promise; + + /** + `finally` will be invoked regardless of the promise's fate just as native + try/catch/finally behaves + + @method finally + @param {Function} callback + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + finally(callback: Function, label?: string): Promise; + } + } + class RenderBuffer { + addClass(className: string): RenderBuffer; + attr(name: string, value: any): any; + element(): HTMLElement; + id(id: string): RenderBuffer; + prop(name: string, value: string): any; + push(string: string): RenderBuffer; + removeAttr(name: string): RenderBuffer; + removeProp(name: string): RenderBuffer; + string(): string; + style(name: string, value: string): RenderBuffer; + classes: any[]; + elementAttributes: {}; + elementId: string; + elementProperties: {}; + elementStyle: {}; + elementTag: string; + parentBuffer: RenderBuffer; + } + + /** + The `Ember.Route` class is used to define individual routes. Refer to + the [routing guide](http://emberjs.com/guides/routing/) for documentation. + */ + class Route extends Object implements ActionHandlerMixin, Evented { + + static isClass: boolean; + static isMethod: boolean; + + /** + This hook is executed when the router enters the route. It is not executed + when the model for the route changes. + @method activate + */ + activate: Function; + + /** + This hook is called after this route's model has resolved. + It follows identical async/promise semantics to `beforeModel` + but is provided the route's resolved model in addition to + the `transition`, and is therefore suited to performing + logic that can only take place after the model has already + resolved. + + Refer to documentation for `beforeModel` for a description + of transition-pausing semantics when a promise is returned + from this hook. + @method afterModel + @param {Object} resolvedModel the value returned from `model`, + or its resolved value if it was a promise + @param {Transition} transition + @return {Promise} if the value returned from this hook is + a promise, the transition will pause until the transition + resolves. Otherwise, non-promise return values are not + utilized in any way. + */ + afterModel(resolvedModel: any, transition: EmberStates.Transition): RSVP.Promise; + + /** + This hook is the first of the route entry validation hooks + called when an attempt is made to transition into a route + or one of its children. It is called before `model` and + `afterModel`, and is appropriate for cases when: + 1) A decision can be made to redirect elsewhere without + needing to resolve the model first. + 2) Any async operations need to occur first before the + model is attempted to be resolved. + This hook is provided the current `transition` attempt + as a parameter, which can be used to `.abort()` the transition, + save it for a later `.retry()`, or retrieve values set + on it from a previous hook. You can also just call + `this.transitionTo` to another route to implicitly + abort the `transition`. + You can return a promise from this hook to pause the + transition until the promise resolves (or rejects). This could + be useful, for instance, for retrieving async code from + the server that is required to enter a route. + + @method beforeModel + @param {Transition} transition + @return {Promise} if the value returned from this hook is + a promise, the transition will pause until the transition + resolves. Otherwise, non-promise return values are not + utilized in any way. + */ + beforeModel(transition: EmberStates.Transition): RSVP.Promise; + + /** + The controller associated with this route. + + @property controller + @type Ember.Controller + @since 1.6.0 + */ + controller: Controller; + + /** + Returns the controller for a particular route or name. + The controller instance must already have been created, either through entering the + associated route or using `generateController`. + + @method controllerFor + @param {String} name the name of the route or controller + @return {Ember.Controller} + */ + controllerFor(name: string): Controller; + + /** + The name of the controller to associate with this route. + By default, Ember will lookup a route's controller that matches the name + of the route (i.e. `App.PostController` for `App.PostRoute`). However, + if you would like to define a specific controller to use, you can do so + using this property. + This is useful in many ways, as the controller specified will be: + * passed to the `setupController` method. + * used as the controller for the view being rendered by the route. + * returned from a call to `controllerFor` for the route. + @property controllerName + @type String + @default null + @since 1.4.0 + */ + controllerName: string; + + /** + This hook is executed when the router completely exits this route. It is + not executed when the model for the route changes. + @method deactivate + */ + deactivate: Function; + + /** + Deserializes value of the query parameter based on defaultValueType + @method deserializeQueryParam + @param {Object} value + @param {String} urlKey + @param {String} defaultValueType + */ + deserializeQueryParam(value: any, urlKey: string, defaultValueType: string): any; + + /** + Disconnects a view that has been rendered into an outlet. + You may pass any or all of the following options to `disconnectOutlet`: + * `outlet`: the name of the outlet to clear (default: 'main') + * `parentView`: the name of the view containing the outlet to clear + (default: the view rendered by the parent route) + + @method disconnectOutlet + @param {Object|String} options the options hash or outlet name + */ + disconnectOutlet(options: DisconnectOutletOptions|string): void; + + /** + @method findModel + @param {String} type the model type + @param {Object} value the value passed to find + */ + findModel(type: string, value: any): any; + + /** + Generates a controller for a route. + If the optional model is passed then the controller type is determined automatically, + e.g., an ArrayController for arrays. + + @method generateController + @param {String} name the name of the controller + @param {Object} model the model to infer the type of the controller (optional) + */ + generateController(name: string, model: {}): Controller; + + /** + Perform a synchronous transition into another route without attempting + to resolve promises, update the URL, or abort any currently active + asynchronous transitions (i.e. regular transitions caused by + `transitionTo` or URL changes). + This method is handy for performing intermediate transitions on the + way to a final destination route, and is called internally by the + default implementations of the `error` and `loading` handlers. + @method intermediateTransitionTo + @param {String} name the name of the route + @param {...Object} models the model(s) to be used while transitioning + to the route. + @since 1.2.0 + */ + intermediateTransitionTo(name: string, ...models: any[]): void; + + /** + A hook you can implement to convert the URL into the model for + this route. + + @method model + @param {Object} params the parameters extracted from the URL + @param {Transition} transition + @return {Object|Promise} the model for this route. If + a promise is returned, the transition will pause until + the promise resolves, and the resolved value of the promise + will be used as the model for this route. + */ + model(params: {}, transition: EmberStates.Transition): any|RSVP.Promise; + + /** + Returns the model of a parent (or any ancestor) route + in a route hierarchy. During a transition, all routes + must resolve a model object, and if a route + needs access to a parent route's model in order to + resolve a model (or just reuse the model from a parent), + it can call `this.modelFor(theNameOfParentRoute)` to + retrieve it. + + @method modelFor + @param {String} name the name of the route + @return {Object} the model object + */ + modelFor(name: string): {}; + + /** + Retrieves parameters, for current route using the state.params + variable and getQueryParamsFor, using the supplied routeName. + @method paramsFor + @param {String} name + */ + paramsFor(name: string) : any; + + /** + Configuration hash for this route's queryParams. + @property queryParams + @for Ember.Route + @type Hash + */ + queryParams: {}; + + /** + Refresh the model on this route and any child routes, firing the + `beforeModel`, `model`, and `afterModel` hooks in a similar fashion + to how routes are entered when transitioning in from other route. + The current route params (e.g. `article_id`) will be passed in + to the respective model hooks, and if a different model is returned, + `setupController` and associated route hooks will re-fire as well. + An example usage of this method is re-querying the server for the + latest information using the same parameters as when the route + was first entered. + Note that this will cause `model` hooks to fire even on routes + that were provided a model object when the route was initially + entered. + @method refresh + @return {Transition} the transition object associated with this + attempted transition + @since 1.4.0 + */ + redirect(): EmberStates.Transition; + + + /** + Refresh the model on this route and any child routes, firing the + `beforeModel`, `model`, and `afterModel` hooks in a similar fashion + to how routes are entered when transitioning in from other route. + The current route params (e.g. `article_id`) will be passed in + to the respective model hooks, and if a different model is returned, + `setupController` and associated route hooks will re-fire as well. + An example usage of this method is re-querying the server for the + latest information using the same parameters as when the route + was first entered. + Note that this will cause `model` hooks to fire even on routes + that were provided a model object when the route was initially + entered. + @method refresh + @return {Transition} the transition object associated with this + attempted transition + @since 1.4.0 + */ + refresh(): EmberStates.Transition; + + /** + `render` is used to render a template into a region of another template + (indicated by an `{{outlet}}`). `render` is used both during the entry + phase of routing (via the `renderTemplate` hook) and later in response to + user interaction. + + @method render + @param {String} name the name of the template to render + @param {Object} [options] the options + @param {String} [options.into] the template to render into, + referenced by name. Defaults to the parent template + @param {String} [options.outlet] the outlet inside `options.template` to render into. + Defaults to 'main' + @param {String|Object} [options.controller] the controller to use for this template, + referenced by name or as a controller instance. Defaults to the Route's paired controller + @param {Object} [options.model] the model object to set on `options.controller`. + Defaults to the return value of the Route's model hook + */ + render(name: string, options?: RenderOptions): void; + + /** + A hook you can use to render the template for the current route. + This method is called with the controller for the current route and the + model supplied by the `model` hook. By default, it renders the route's + template, configured with the controller for the route. + This method can be overridden to set up and render additional or + alternative templates. + + @method renderTemplate + @param {Object} controller the route's controller + @param {Object} model the route's model + */ + renderTemplate(controller: Controller, model: {}): void; + + /** + Transition into another route while replacing the current URL, if possible. + This will replace the current history entry instead of adding a new one. + Beside that, it is identical to `transitionTo` in all other respects. See + 'transitionTo' for additional information regarding multiple models. + + @method replaceWith + @param {String} name the name of the route or a URL + @param {...Object} models the model(s) or identifier(s) to be used while + transitioning to the route. + @return {Transition} the transition object associated with this + attempted transition + */ + replaceWith(name: string, ...models: any[]): void; + + /** + A hook you can use to reset controller values either when the model + changes or the route is exiting. + + @method resetController + @param {Controller} controller instance + @param {Boolean} isExiting + @param {Object} transition + @since 1.7.0 + */ + resetController(controller: Ember.Controller, isExiting: boolean, transition: any): void; + + /** + A hook you can implement to convert the route's model into parameters + for the URL. + + The default `serialize` method will insert the model's `id` into the + route's dynamic segment (in this case, `:post_id`) if the segment contains '_id'. + If the route has multiple dynamic segments or does not contain '_id', `serialize` + will return `Ember.getProperties(model, params)` + This method is called when `transitionTo` is called with a context + in order to populate the URL. + @method serialize + @param {Object} model the route's model + @param {Array} params an Array of parameter names for the current + route (in the example, `['post_id']`. + @return {Object} the serialized parameters + */ + serialize(model: {}, params: string[]): string; + + /** + Serializes value of the query parameter based on defaultValueType + @method serializeQueryParam + @param {Object} value + @param {String} urlKey + @param {String} defaultValueType + */ + serializeQueryParam(value: any, urlKey: string, defaultValueType: string): string; + + /** + Serializes the query parameter key + @method serializeQueryParamKey + @param {String} controllerPropertyName + */ + serializeQueryParamKey(controllerPropertyName: string): string; + + /** + A hook you can use to setup the controller for the current route. + This method is called with the controller for the current route and the + model supplied by the `model` hook. + By default, the `setupController` hook sets the `model` property of + the controller to the `model`. + If you implement the `setupController` hook in your Route, it will + prevent this default behavior. If you want to preserve that behavior + when implementing your `setupController` function, make sure to call + `_super` + @method setupController + @param {Controller} controller instance + @param {Object} model + */ + setupController(controller: Controller, model: {}): void; + + /** + Store property provides a hook for data persistence libraries to inject themselves. + By default, this store property provides the exact same functionality previously + in the model hook. + Currently, the required interface is: + `store.find(modelName, findArguments)` + @method store + @param {Object} store + */ + store(store: any): any; + + /** + The name of the template to use by default when rendering this routes + template. + This is similar with `viewName`, but is useful when you just want a custom + template without a view. + + @property templateName + @type String + @default null + @since 1.4.0 + */ + templateName: string; + + /** + Transition the application into another route. The route may + be either a single route or route path + + @method transitionTo + @param {String} name the name of the route or a URL + @param {...Object} models the model(s) or identifier(s) to be used while + transitioning to the route. + @param {Object} [options] optional hash with a queryParams property + containing a mapping of query parameters + @return {Transition} the transition object associated with this + attempted transition + */ + transitionTo(name: string, ...object: any[]): EmberStates.Transition; + + /** + The name of the view to use by default when rendering this routes template. + When rendering a template, the route will, by default, determine the + template and view to use from the name of the route itself. If you need to + define a specific view, set this property. + This is useful when multiple routes would benefit from using the same view + because it doesn't require a custom `renderTemplate` method. + @property viewName + @type String + @default null + @since 1.4.0 + */ + viewName: string; + + // ActionHandlerMixin methods + + /** + Sends an action to the router, which will delegate it to the currently + active route hierarchy per the bubbling rules explained under actions + + @method send + @param {String} actionName The action to trigger + @param {*} context a context to send with the action + */ + send(name: string, ...args: any[]): void; + + /** + The collection of functions, keyed by name, available on this + `ActionHandler` as action targets. + These functions will be invoked when a matching `{{action}}` is triggered + from within a template and the application's current route is this route. + Actions can also be invoked from other parts of your application + via `ActionHandler#send`. + The `actions` hash will inherit action handlers from + the `actions` hash defined on extended parent classes + or mixins rather than just replace the entire hash. + + Within a Controller, Route, View or Component's action handler, + the value of the `this` context is the Controller, Route, View or + Component object: + + It is also possible to call `this._super.apply(this, arguments)` from within an + action handler if it overrides a handler defined on a parent + class or mixin. + + ## Bubbling + By default, an action will stop bubbling once a handler defined + on the `actions` hash handles it. To continue bubbling the action, + you must return `true` from the handler + + @property actions + @type Hash + @default null + */ + actions: ActionsHash; + + // Evented methods + + /** + Subscribes to a named event with given function. + + An optional target can be passed in as the 2nd argument that will + be set as the "this" for the callback. This is a good way to give your + function access to the object triggering the event. When the target + parameter is used the callback becomes the third argument. + + @method on + @param {String} name The name of the event + @param {Object} [target] The "this" binding for the callback + @param {Function} method The callback to execute + @return this + */ + on(name: string, target: any, method: Function): Evented; + + /** + Subscribes a function to a named event and then cancels the subscription + after the first time the event is triggered. It is good to use ``one`` when + you only care about the first time an event has taken place. + This function takes an optional 2nd argument that will become the "this" + value for the callback. If this argument is passed then the 3rd argument + becomes the function. + + @method one + @param {String} name The name of the event + @param {Object} [target] The "this" binding for the callback + @param {Function} method The callback to execute + @return this + */ + one(name: string, target: any, method: Function): Evented; + + /** + Triggers a named event for the object. Any additional arguments + will be passed as parameters to the functions that are subscribed to the + event. + + @method trigger + @param {String} name The name of the event + @param {Object...} args Optional arguments to pass on + */ + trigger(name: string, ...args: string[]): void; + + /** + Cancels subscription for given name, target, and method. + + @method off + @param {String} name The name of the event + @param {Object} target The target of the subscription + @param {Function} method The function of the subscription + @return this + */ + off(name: string, target:any , method: Function): Evented; + + /** + Checks to see if object has any subscriptions for named event. + + @method has + @param {String} name The name of the event + @return {Boolean} does the object have a subscription for event + */ + has(name: string): boolean; + } + + class Router extends Object { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + map(callback: Function): Router; + } + class RouterDSL { + resource(name: string, options?: {}, callback?: Function): void; + resource(name: string, callback: Function): void; + route(name: string, options?: {}): void; + } + var SHIM_ES5: boolean; + var STRINGS: boolean; + class Select extends View { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + content: any[]; + groupView: View; + multiple: boolean; + optionGroupPath: string; + optionLabelPath: string; + optionValuePath: string; + optionView: View; + prompt: string; + selection: any; + value: string; + } + class SelectOption extends View { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + } + class Set extends CoreObject implements MutableEnumberable, Copyable, Freezable { + addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Set; + addObject(object: any): any; + addObjects(objects: Enumerable): Set; + any(callback: Function, target?: any): boolean; + anyBy(key: string, value?: string): boolean; + someProperty(key: string, value?: string): boolean; + compact(): any[]; + contains(obj: any): boolean; + enumerableContentDidChange(start: number, removing: number, adding: number): any; + enumerableContentDidChange(start: number, removing: Enumerable, adding: number): any; + enumerableContentDidChange(start: number, removing: number, adding: Enumerable): any; + enumerableContentDidChange(start: number, removing: Enumerable, adding: Enumerable): any; + enumerableContentDidChange(removing: number, adding: number): any; + enumerableContentDidChange(removing: Enumerable, adding: number): any; + enumerableContentDidChange(removing: number, adding: Enumerable): any; + enumerableContentDidChange(removing: Enumerable, adding: Enumerable): any; + enumerableContentWillChange(removing: number, adding: number): Set; + enumerableContentWillChange(removing: Enumerable, adding: number): Set; + enumerableContentWillChange(removing: number, adding: Enumerable): Set; + enumerableContentWillChange(removing: Enumerable, adding: Enumerable): Set; + every(callback: Function, target?: any): boolean; + everyBy(key: string, value?: string): boolean; + everyProperty(key: string, value?: string): boolean; + filter(callback: Function, target: any): any[]; + filterBy(key: string, value?: string): any[]; + find(callback: Function, target: any): any; + findBy(key: string, value?: string): any; + forEach(callback: Function, target?: any): any; + getEach(key: string): any[]; + invoke(methodName: string, ...args: any[]): any[]; + map: ItemIndexEnumerableCallbackTarget; + mapBy(key: string): any[]; + nextObject(index: number, previousObject: any, context: any): any; + reduce(callback: ReduceCallback, initialValue: any, reducerProperty: string): any; + reject: ItemIndexEnumerableCallbackTarget; + rejectBy(key: string, value?: string): any[]; + removeEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Set; + removeObject(object: any): any; + removeObjects(objects: Enumerable): Set; + setEach(key: string, value?: any): any; + some(callback: Function, target?: any): boolean; + toArray(): any[]; + uniq(): Set; + without(value: any): Set; + '[]': any[]; + firstObject: any; + hasEnumerableObservers: boolean; + lastObject: any; + copy(deep: boolean): Set; + frozenCopy(): Set; + freeze(): Set; + isFrozen: boolean; + add(obj: any): Set; + addEach(...args: any[]): Set; + clear(): Set; + isEqual(obj: Set): boolean; + pop(): any; + push(obj: any): Set; + remove(obj: any): Set; + removeEach(...args: any[]): Set; + shift(): any; + unshift(obj: any): Set; + length: number; + } + class SortableMixin implements MutableEnumberable { + addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; + addObject(object: any): any; + addObjects(objects: Enumerable): MutableEnumberable; + any(callback: Function, target?: any): boolean; + anyBy(key: string, value?: string): boolean; + someProperty(key: string, value?: string): boolean; + compact(): any[]; + contains(obj: any): boolean; + enumerableContentDidChange(start: number, removing: number, adding: number): any; + enumerableContentDidChange(start: number, removing: Enumerable, adding: number): any; + enumerableContentDidChange(start: number, removing: number, adding: Enumerable): any; + enumerableContentDidChange(start: number, removing: Enumerable, adding: Enumerable): any; + enumerableContentDidChange(removing: number, adding: number): any; + enumerableContentDidChange(removing: Enumerable, adding: number): any; + enumerableContentDidChange(removing: number, adding: Enumerable): any; + enumerableContentDidChange(removing: Enumerable, adding: Enumerable): any; + enumerableContentWillChange(removing: number, adding: number): Enumerable; + enumerableContentWillChange(removing: Enumerable, adding: number): Enumerable; + enumerableContentWillChange(removing: number, adding: Enumerable): Enumerable; + enumerableContentWillChange(removing: Enumerable, adding: Enumerable): Enumerable; + every(callback: Function, target?: any): boolean; + everyBy(key: string, value?: string): boolean; + everyProperty(key: string, value?: string): boolean; + filter(callback: Function, target: any): any[]; + filterBy(key: string, value?: string): any[]; + find(callback: Function, target: any): any; + findBy(key: string, value?: string): any; + forEach(callback: Function, target?: any): any; + getEach(key: string): any[]; + invoke(methodName: string, ...args: any[]): any[]; + map: ItemIndexEnumerableCallbackTarget; + mapBy(key: string): any[]; + nextObject(index: number, previousObject: any, context: any): any; + reduce(callback: ReduceCallback, initialValue: any, reducerProperty: string): any; + reject: ItemIndexEnumerableCallbackTarget; + rejectBy(key: string, value?: string): any[]; + removeEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; + removeObject(object: any): any; + removeObjects(objects: Enumerable): MutableEnumberable; + setEach(key: string, value?: any): any; + some(callback: Function, target?: any): boolean; + toArray(): any[]; + uniq(): Enumerable; + without(value: any): Enumerable; + '[]': any[]; + arrangedContent: any; + firstObject: any; + hasEnumerableObservers: boolean; + lastObject: any; + sortAscending: boolean; + sortFunction: Comparable; + sortProperties: any[]; + } + class State extends Object implements Evented { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + has(name: string): boolean; + off(name: string, target: any, method: Function): State; + on(name: string, target: any, method: Function): State; + one(name: string, target: any, method: Function): State; + trigger(name: string, ...args: string[]): void; + getPathsCache(stateManager: {}, path: string): {}; + init(): void; + setPathsCache(stateManager: {}, path: string, transitions: any): void; + static transitionTo(target: string): void; + hasContext: boolean; + isLeaf: boolean; + name: string; + parentState: State; + path: string; + enter: Function; + exit: Function; + setup: Function; + } + class StateManager extends State { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + contextFreeTransition(currentState: State, path: string): TransitionsHash; + enterState(transition: TransitionsHash): void; + getState(name: string): State; + getStateByPath(root: State, path: string): State; + getStateMeta(state: State, key: string): any; + getStatesInPath(root: State, path: string): State[]; + goToState(path: string, context: any): void; + send(event: string): void; + setStateMeta(state: State, key: string, value: any): any; + stateMetaFor(state: State): {}; + transitionTo(path: string, context: any): void; + triggerSetupContext(transitions: TransitionsHash): void; + unhandledEvent(manager: StateManager, event: string): any; + currentPath: string; + currentState: State; + errorOnUnhandledEvents: boolean; + transitionEvent: string; + } + namespace String { + function camelize(str: string): string; + function capitalize(str: string): string; + function classify(str: string): string; + function dasherize(str: string): string; + function decamelize(str: string): string; + function fmt(...args: string[]): string; + function htmlSafe(str: string): void; // TODO: @returns Handlebars.SafeStringStatic; + function loc(...args: string[]): string; + function underscore(str: string): string; + function w(str: string): string[]; + } + var TEMPLATES: {}; + class TargetActionSupport { + triggerAction(opts: {}): boolean; + } + class Test { + click(selector: string): RSVP.Promise; + fillin(selector: string, text: string): RSVP.Promise; + find(selector: string): JQuery; + findWithAssert(selector: string): JQuery; + injectTestHelpers(): void; + keyEvent(selector: string, type: string, keyCode: number): RSVP.Promise; + static oninjectHelpers(callback: Function): void; + static promise(resolver: Function): RSVP.Promise; + static registerHelper(name: string, helperMethod: Function): void; + removeTestHelpers(): void; + setupForTesting(): void; + static unregisterHelper(name: string): void; + visit(url: string): RSVP.Promise; + wait(value: any): RSVP.Promise; + static adapter: Object; + testHelpers: {}; + } + class TextArea extends View implements TextSupport { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + cancel(event: Function): void; + focusIn(event: Function): void; + focusOut(event: Function): void; + insertNewLine(event: Function): void; + keyPress(event: Function): void; + action: string; + bubbles: boolean; + onEvent: string; + } + class TextField extends View implements TextSupport { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + cancel(event: Function): void; + focusIn(event: Function): void; + focusOut(event: Function): void; + insertNewLine(event: Function): void; + keyPress(event: Function): void; + action: string; + bubbles: boolean; + onEvent: string; + pattern: string; + size: string; + type: string; + value: string; + } + class TextSupport { + cancel(event: Function): void; + focusIn(event: Function): void; + focusOut(event: Function): void; + insertNewLine(event: Function): void; + keyPress(event: Function): void; + action: string; + bubbles: boolean; + onEvent: string; + } + var VERSION: string; + class View extends CoreView { + static detect(obj: any): boolean; + static detectInstance(obj: any): boolean; + /** + Iterate over each computed property for the class, passing its name and any + associated metadata (see metaForProperty) to the callback. + **/ + static eachComputedProperty(callback: Function, binding: {}): void; + /** + Returns the original hash that was passed to meta(). + @param key property name + **/ + static metaForProperty(key: string): {}; + static isClass: boolean; + static isMethod: boolean; + $(): JQuery; + append(): View; + // ReSharper disable InconsistentNaming + appendTo(A: string): View; + appendTo(A: HTMLElement): View; + appendTo(A: JQuery): View; + // ReSharper restore InconsistentNaming + createChildView(viewClass: {}, attrs?: {}): View; + createChildView(viewClass: string, attrs?: {}): View; + createElement(): View; + destroy(): View; + destroyElement(): View; + findElementInParentElement(parentElement: HTMLElement): HTMLElement; + remove(): View; + removeAllChildren(): View; + removeChild(view: View): View; + removeFromParent(): View; + render(buffer: RenderBuffer): void; + // ReSharper disable InconsistentNaming + replaceIn(A: string): View; + replaceIn(A: HTMLElement): View; + replaceIn(A: JQuery): View; + // ReSharper restore InconsistentNaming + rerender(): void; + ariaRole: string; + attributeBindings: any; + classNameBindings: string[]; + classNames: string[]; + context: any; + controller: any; + element: HTMLElement; + isView: boolean; + isVisible: boolean; + layout: Function; + layoutName: string; + nearestChildOf: View; + nearestOfType: View; + nearestWithProperty: View; + tagName: string; + template: Function; + templateName: string; + templates: {}; + views: {}; + didInsertElement: Function; + parentViewDidChange: Function; + willClearRender: Function; + willDestroyElement: Function; + willInsertElement: Function; + } + class ViewTargetActionSupport extends Mixin { + target: any; + actionContext: any; + } + var ViewUtils: {}; // TODO: define interface + function addBeforeObserver(obj: any, path: string, target: any, method: Function): any; + function addListener(obj: any, eventName: string, target: any, method: Function, once?: boolean): void; + function addListener(obj: any, eventName: string, target: any, method: string, once?: boolean): void; + function addListener(obj: any, eventName: string, func: Function, method: Function, once?: boolean): void; + function addListener(obj: any, eventName: string, func: Function, method: string, once?: boolean): void; + var addObserver: ModifyObserver; + /** + Ember.alias is deprecated. Please use Ember.aliasMethod or Ember.computed.alias instead. + **/ + var alias: typeof deprecateFunc; + function aliasMethod(methodName: string): Descriptor; + var anyUnprocessedMixins: boolean; + function assert(desc: string, test: boolean): void; + function beforeObserver(func: Function, propertyName: string): Function; + function beforeObserversFor(obj: any, path: string): string[]; + function beginPropertyChanges(): void; + function bind(obj: any, to: string, from: string): Binding; + function cacheFor(obj: any, key: string): any; + function canInvoke(obj: any, methodName: string): boolean; + function changeProperties(callback: Function, binding?: any): void; + function compare(v: any, w: any): number; + // ReSharper disable once DuplicatingLocalDeclaration + var computed: { + (...args: any[]): ComputedProperty; + alias(dependentKey: string): ComputedProperty; + and(...args: string[]): ComputedProperty; + any(...args: string[]): ComputedProperty; + bool(dependentKey: string): ComputedProperty; + defaultTo(defaultPath: string): ComputedProperty; + empty(dependentKey: string): ComputedProperty; + equal(dependentKey: string, value: any): ComputedProperty; + gt(dependentKey: string, value: number): ComputedProperty; + gte(dependentKey: string, value: number): ComputedProperty; + lt(dependentKey: string, value: number): ComputedProperty; + lte(dependentKey: string, value: number): ComputedProperty; + map(...args: string[]): ComputedProperty; + match(dependentKey: string, regexp: RegExp): ComputedProperty; + none(dependentKey: string): ComputedProperty; + not(dependentKey: string): ComputedProperty; + notEmpty(dependentKey: string): ComputedProperty; + oneWay(dependentKey: string): ComputedProperty; + or(...args: string[]): ComputedProperty; + }; + // ReSharper disable DuplicatingLocalDeclaration + var config: {}; + // ReSharper restore DuplicatingLocalDeclaration + function controllerFor(container: Container, controllerName: string, lookupOptions?: {}): Controller; + function copy(obj: any, deep: boolean): any; + /** + Creates an instance of the CoreObject class. + @param arguments A hash containing values with which to initialize the newly instantiated object. + **/ + function create(arguments?: {}): CoreObject; + function debug(message: string): void; + function defineProperty(obj: any, keyName: string, desc: {}): void; + function deprecate(message: string, test?: boolean): void; + function deprecateFunc(message: string, func: Function): Function; + function destroy(obj: any): void; + /** + Ember.empty is deprecated. Please use Ember.isEmpty instead. + **/ + // ReSharper disable once DuplicatingLocalDeclaration + var empty: typeof deprecateFunc; + function endPropertyChanges(): void; + // ReSharper disable once DuplicatingLocalDeclaration + var exports: {}; + function finishChains(obj: any): void; + function flushPendingChains(): void; + function generateController(container: Container, controllerName: string, context: any): Controller; + function generateGuid(obj: any, prefix?: string): string; + function get(obj: any, keyName: string): any; + function getMeta(obj: any, property: string): any; + /** + getPath is deprecated since get now supports paths. + **/ + var getPath: typeof deprecateFunc; + function getWithDefault(root: string, key: string, defaultValue: any): any; + function guidFor(obj: any): string; + function handleErrors(func: Function, context: any): any; + function hasListeners(context: any, name: string): boolean; + function hasOwnProperty(prop: string): boolean; + function immediateObserver(func: Function, ...propertyNames: any[]): Function; + var imports: {}; + function inspect(obj: any): string; + function instrument(name: string, payload: any, callback: Function, binding: any): void; + function isArray(obj: any): boolean; + function isEmpty(obj: any): boolean; + function isEqual(a: any, b: any): boolean; + function isGlobalPath(path: string): boolean; + var isNamespace: boolean; + function isNone(obj: any): boolean; + function isPrototypeOf(obj: {}): boolean; + function isWatching(obj: any, key: string): boolean; + function keys(obj: any): any[]; + function listenersDiff(obj: any, eventName: string, otherActions: any[]): any[]; + function listenersFor(obj: any, eventName: string): any[]; + function listenersUnion(obj: any, eventName: string, otherActions: any[]): void; + // ReSharper disable once DuplicatingLocalDeclaration + var lookup: {}; // TODO: define interface + function makeArray(obj: any): any[]; + function merge(original: any, updates: any): any; + function meta(obj: any, writable?: boolean): {}; + function metaPath(obj: any, path: string, writable?: boolean): any; + function mixin(obj: any, ...args: any[]): any; + /** + Ember.none is deprecated. Please use Ember.isNone instead. + **/ + var none: typeof deprecateFunc; + function normalizeTuple(target: any, path: string): any[]; + function observer(...args: any[]): Function; + function observersFor(obj: any, path: string): any[]; + function onLoad(name: string, callback: Function): void; + function oneWay(obj: any, to: string, from: string): Binding; + var onError: Error; + function overrideChains(obj: any, keyName: string, m: any): boolean; + // ReSharper disable once DuplicatingLocalDeclaration + var platform: { + addBeforeObserver: ModifyObserver; + addObserver: ModifyObserver; + defineProperty(obj: any, keyName: string, desc: {}): void; + removeBeforeObserver: ModifyObserver; + removeObserver: ModifyObserver; + hasPropertyAccessors: boolean; + }; + function propertyDidChange(obj: any, keyName: string): void; + function propertyIsEnumerable(prop: string): boolean; + function propertyWillChange(obj: any, keyName: string): void; + function removeBeforeObserver(obj: any, path: string, target: any, method: Function): any; + function removeChainWatcher(obj: any, keyName: string, node: any): void; + function removeListener(obj: any, eventName: string, target: any, method: Function): void; + function removeListener(obj: any, eventName: string, target: any, method: string): void; + function removeListener(obj: any, eventName: string, func: Function, method: Function): void; + function removeListener(obj: any, eventName: string, func: Function, method: string): void; + function removeObserver(obj: any, path: string, target: any, method: Function): any; + function required(): Descriptor; + function rewatch(obj: any): void; + var run: { + (target: any, method: Function): void; + begin(): void; + cancel(timer: any): void; + debounce(target: any, method: Function, ...args: any[]): void; + debounce(target: any, method: string, ...args: any[]): void; + end(): void; + join(target: any, method: Function, ...args: any[]): any; + join(target: any, method: string, ...args: any[]): any; + later(target: any, method: Function, ...args: any[]): string; + later(target: any, method: string, ...args: any[]): string; + next(target: any, method: Function, ...args: any[]): number; + next(target: any, method: string, ...args: any[]): number; + once(target: any, method: Function, ...args: any[]): number; + once(target: any, method: string, ...args: any[]): number; + schedule(queue: string, target: any, method: Function, ...args: any[]): void; + schedule(queue: string, target: any, method: string, ...args: any[]): void; + scheduleOnce(queue: string, target: any, method: Function, ...args: any[]): void; + scheduleOnce(queue: string, target: any, method: string, ...args: any[]): void; + sync(): void; + throttle(target: any, method: Function, ...args: any[]): void; + throttle(target: any, method: string, ...args: any[]): void; + queues: any[]; + }; + function runLoadHooks(name: string, object: any): void; + function sendEvent(obj: any, eventName: string, params?: any[], actions?: any[]): boolean; + function set(obj: any, keyName: string, value: any): any; + function setMeta(obj: any, property: string, value: any): void; + /** + setPath is deprecated since set now supports paths. + **/ + var setPath: typeof deprecateFunc; + function setProperties(self: any, hash: {}): any; + function subscribe(pattern: string, object: any): void; + function toLocaleString(): string; + function toString(): string; + function tryCatchFinally(tryable: Function, catchable: Function, finalizer: Function, binding?: any): any; + function tryFinally(tryable: Function, finalizer: Function, binding?: any): any; + function tryInvoke(obj: any, methodName: string, args?: any[]): any; + function trySet(obj: any, path: string, value: any): void; + /** + trySetPath has been renamed to trySet. + **/ + var trySetPath: typeof deprecateFunc; + function typeOf(item: any): string; + function unwatch(obj: any, keyPath: string): void; + function unwatchKey(obj: any, keyName: string): void; + function unwatchPath(obj: any, keyPath: string): void; + // ReSharper disable once DuplicatingLocalDeclaration + var uuid: number; + function valueOf(): {}; + function warn(message: string, test?: boolean): void; + function watch(obj: any, keyPath: string): void; + function watchKey(obj: any, keyName: string): void; + function watchPath(obj: any, keyPath: string): void; + function watchedEvents(obj: {}): any[]; + function wrap(func: Function, superFunc: Function): Function; +} + +// ReSharper disable DuplicatingLocalDeclaration +declare namespace Em { + /** + Alias for jQuery. + **/ + var $: typeof Ember.$; + var A: typeof Ember.A; + class ActionHandlerMixin extends Ember.ActionHandlerMixin { } + class Application extends Ember.Application { } + class Array extends Ember.Array { } + class ArrayController extends Ember.ArrayController { } + var ArrayPolyfills: typeof Ember.ArrayPolyfills; + class ArrayProxy extends Ember.ArrayProxy { } + var BOOTED: typeof Ember.BOOTED; + class Binding extends Ember.Binding { } + class Button extends Ember.Button { } + class Checkbox extends Ember.Checkbox { } + class CollectionView extends Ember.CollectionView { } + class Comparable extends Ember.Comparable { } + class Component extends Ember.Component { } + class ComputedProperty extends Ember.ComputedProperty { } + class Container extends Ember.Container { } + class ContainerView extends Ember.ContainerView { } + class Controller extends Ember.Controller { } + class ControllerMixin extends Ember.ControllerMixin { } + class Copyable extends Ember.Copyable { } + class CoreObject extends Ember.CoreObject { } + class CoreView extends Ember.CoreView { } + class DAG extends Ember.DAG { } + var DEFAULT_GETTER_FUNCTION: typeof Ember.DEFAULT_GETTER_FUNCTION; + class DefaultResolver extends Ember.DefaultResolver { } + class Deffered extends Ember.Deferred { } + class DeferredMixin extends Ember.DeferredMixin { } + class Descriptor extends Ember.Descriptor { } + var EMPTY_META: typeof Ember.EMPTY_META; + var ENV: typeof Ember.ENV; + var EXTEND_PROTOTYPES: typeof Ember.EXTEND_PROTOTYPES; + class EachProxy extends Ember.EachProxy { } + class Enumerable extends Ember.Enumerable { } + var EnumerableUtils: typeof Ember.EnumerableUtils; + var Error: typeof Ember.Error; + class EventDispatcher extends Ember.EventDispatcher { } + class Evented extends Ember.Evented { } + var FROZEN_ERROR: typeof Ember.FROZEN_ERROR; + class Freezable extends Ember.Freezable { } + var GUID_KEY: typeof Ember.GUID_KEY; + namespace Handlebars { + var compile: typeof Ember.Handlebars.compile; + var get: typeof Ember.Handlebars.get; + var helper: typeof Ember.Handlebars.helper; + class helpers extends Ember.Handlebars.helpers { } + var precompile: typeof Ember.Handlebars.precompile; + var registerBoundHelper: typeof Ember.Handlebars.registerBoundHelper; + class Compiler extends Ember.Handlebars.Compiler { } + class JavaScriptCompiler extends Ember.Handlebars.JavaScriptCompiler { } + var registerHelper: typeof Ember.Handlebars.registerHelper; + var registerPartial: typeof Ember.Handlebars.registerPartial; + var K: typeof Ember.Handlebars.K; + var createFrame: typeof Ember.Handlebars.createFrame; + var Exception: typeof Ember.Handlebars.Exception; + class SafeString extends Ember.Handlebars.SafeString { } + var parse: typeof Ember.Handlebars.parse; + var print: typeof Ember.Handlebars.print; + var logger: typeof Ember.Handlebars.logger; + var log: typeof Ember.Handlebars.log; + } + class HashLocation extends Ember.HashLocation { } + class HistoryLocation extends Ember.HistoryLocation { } + var IS_BINDING: typeof Ember.IS_BINDING; + class Instrumentation extends Ember.Instrumentation { } + var K: typeof Ember.K; + var LOG_BINDINGS: typeof Ember.LOG_BINDINGS; + var LOG_STACKTRACE_ON_DEPRECATION: typeof Ember.LOG_STACKTRACE_ON_DEPRECATION; + var LOG_VERSION: typeof Ember.LOG_VERSION; + class LinkView extends Ember.LinkView { } + class Location extends Ember.Location { } + var Logger: typeof Ember.Logger; + var MANDATORY_SETTER_FUNCTION: typeof Ember.MANDATORY_SETTER_FUNCTION; + var META_KEY: typeof Ember.META_KEY; + class Map extends Ember.Map { } + class MapWithDefault extends Ember.MapWithDefault { } + class Mixin extends Ember.Mixin { } + class MutableArray extends Ember.MutableArray { } + class MutableEnumerable extends Ember.MutableEnumberable { } + var NAME_KEY: typeof Ember.NAME_KEY; + class Namespace extends Ember.Namespace { } + class NativeArray extends Ember.NativeArray { } + class NoneLocation extends Ember.NoneLocation { } + var ORDER_DEFINITION: typeof Ember.ORDER_DEFINITION; + class Object extends Ember.Object { } + class ObjectController extends Ember.ObjectController { } + class ObjectProxy extends Ember.ObjectProxy { } + class Observable extends Ember.Observable { } + class OrderedSet extends Ember.OrderedSet { } + namespace RSVP { + interface PromiseResolve extends Ember.RSVP.PromiseResolve { } + interface PromiseReject extends Ember.RSVP.PromiseReject { } + interface PromiseResolverFunction extends Ember.RSVP.PromiseResolverFunction { } + class Promise extends Ember.RSVP.Promise { } + } + class RenderBuffer extends Ember.RenderBuffer { } + class Route extends Ember.Route { } + class Router extends Ember.Router { } + class RouterDSL extends Ember.RouterDSL { } + var SHIM_ES5: typeof Ember.SHIM_ES5; + var STRINGS: typeof Ember.STRINGS; + class Select extends Ember.Select { } + class SelectOption extends Ember.SelectOption { } + class Set extends Ember.Set { } + class SortableMixin extends Ember.SortableMixin { } + class State extends Ember.State { } + class StateManager extends Ember.StateManager { } + namespace String { + var camelize: typeof Ember.String.camelize; + var capitalize: typeof Ember.String.capitalize; + var classify: typeof Ember.String.classify; + var dasherize: typeof Ember.String.dasherize; + var decamelize: typeof Ember.String.decamelize; + var fmt: typeof Ember.String.fmt; + var htmlSafe: typeof Ember.String.htmlSafe; + var loc: typeof Ember.String.loc; + var underscore: typeof Ember.String.underscore; + var w: typeof Ember.String.w; + } + var TEMPLATES: typeof Ember.TEMPLATES; + class TargetActionSupport extends Ember.TargetActionSupport { } + class Test extends Ember.Test { } + class TextArea extends Ember.TextArea { } + class TextField extends Ember.TextField { } + class TextSupport extends Ember.TextSupport { } + var VERSION: typeof Ember.VERSION; + class View extends Ember.View { } + class ViewTargetActionSupport extends Ember.ViewTargetActionSupport { } + var ViewUtils: typeof Ember.ViewUtils; + var addBeforeObserver: typeof Ember.addBeforeObserver; + var addListener: typeof Ember.addListener; + var addObserver: typeof Ember.addObserver; + var alias: typeof Ember.alias; + var aliasMethod: typeof Ember.aliasMethod; + var anyUnprocessedMixins: typeof Ember.anyUnprocessedMixins; + var assert: typeof Ember.assert; + var beforeObserver: typeof Ember.beforeObserver; + var beforeObserversFor: typeof Ember.beforeObserversFor; + var beginPropertyChanges: typeof Ember.beginPropertyChanges; + var bind: typeof Ember.bind; + var cacheFor: typeof Ember.cacheFor; + var canInvoke: typeof Ember.canInvoke; + var changeProperties: typeof Ember.changeProperties; + var compare: typeof Ember.compare; + var computed: typeof Ember.computed; + var config: typeof Ember.config; + var controllerFor: typeof Ember.controllerFor; + var copy: typeof Ember.copy; + var create: typeof Ember.create; + var debug: typeof Ember.debug; + var defineProperty: typeof Ember.defineProperty; + var deprecate: typeof Ember.deprecate; + var deprecateFunc: typeof Ember.deprecateFunc; + var destroy: typeof Ember.destroy; + var empty: typeof deprecateFunc; + var endPropertyChanges: typeof Ember.endPropertyChanges; + var exports: typeof Ember.exports; + var finishChains: typeof Ember.finishChains; + var flushPendingChains: typeof Ember.flushPendingChains; + var generateController: typeof Ember.generateController; + var generateGuid: typeof Ember.generateGuid; + var get: typeof Ember.get; + var getMeta: typeof Ember.getMeta; + var getPath: typeof Ember.getPath; + var getWithDefault: typeof Ember.getWithDefault; + var guidFor: typeof Ember.guidFor; + var handleErrors: typeof Ember.handleErrors; + var hasListeners: typeof Ember.hasListeners; + var hasOwnProperty: typeof Ember.hasOwnProperty; + var immediateObserver: typeof Ember.immediateObserver; + var imports: typeof Ember.imports; + var inspect: typeof Ember.inspect; + var instrument: typeof Ember.instrument; + var isArray: typeof Ember.isArray; + var isEmpty: typeof Ember.isEmpty; + var isEqual: typeof Ember.isEqual; + var isGlobalPath: typeof Ember.isGlobalPath; + var isNamespace: typeof Ember.isNamespace; + var isNone: typeof Ember.isNone; + var isPrototypeOf: typeof Ember.isPrototypeOf; + var isWatching: typeof Ember.isWatching; + var keys: typeof Ember.keys; + var listenersDiff: typeof Ember.listenersDiff; + var listenersFor: typeof Ember.listenersFor; + var listenersUnion: typeof Ember.listenersUnion; + var lookup: typeof Ember.lookup; + var makeArray: typeof Ember.makeArray; + var merge: typeof Ember.merge; + var meta: typeof Ember.meta; + var metaPath: typeof Ember.metaPath; + var mixin: typeof Ember.mixin; + var none: typeof Ember.none; + var normalizeTuple: typeof Ember.normalizeTuple; + var observer: typeof Ember.observer; + var observersFor: typeof Ember.observersFor; + var onLoad: typeof Ember.onLoad; + var oneWay: typeof Ember.oneWay; + var onError: typeof Ember.onError; + var overrideChains: typeof Ember.overrideChains; + var platform: typeof Ember.platform; + var propertyDidChange: typeof Ember.propertyDidChange; + var propertyIsEnumerable: typeof Ember.propertyIsEnumerable; + var propertyWillChange: typeof Ember.propertyWillChange; + var removeBeforeObserver: typeof Ember.removeBeforeObserver; + var removeChainWatcher: typeof Ember.removeChainWatcher; + var removeListener: typeof Ember.removeListener; + var removeObserver: typeof Ember.removeObserver; + var required: typeof Ember.required; + var rewatch: typeof Ember.rewatch; + var run: typeof Ember.run; + var runLoadHooks: typeof Ember.runLoadHooks; + var sendEvent: typeof Ember.sendEvent; + var set: typeof Ember.set; + var setMeta: typeof Ember.setMeta; + var setPath: typeof Ember.setPath; + var setProperties: typeof Ember.setProperties; + var subscribe: typeof Ember.subscribe; + var toLocaleString: typeof Ember.toLocaleString; + var toString: typeof Ember.toString; + var tryCatchFinally: typeof Ember.tryCatchFinally; + var tryFinally: typeof Ember.tryFinally; + var tryInvoke: typeof Ember.tryInvoke; + var trySet: typeof Ember.trySet; + var trySetPath: typeof Ember.trySetPath; + var typeOf: typeof Ember.typeOf; + var unwatch: typeof Ember.unwatch; + var unwatchKey: typeof Ember.unwatchKey; + var unwatchPath: typeof Ember.unwatchPath; + var uuid: typeof Ember.uuid; + var valueOf: typeof Ember.valueOf; + var warn: typeof Ember.warn; + var watch: typeof Ember.watch; + var watchKey: typeof Ember.watchKey; + var watchPath: typeof Ember.watchPath; + var watchedEvents: typeof Ember.watchedEvents; + var wrap: typeof Ember.wrap; +} + +/** + * External ambient module - to allow "import Ember = require('Ember');" to work correctly + */ + +declare module "Ember" { + + var $: typeof Ember.$; + var A: typeof Ember.A; + class ActionHandlerMixin extends Ember.ActionHandlerMixin { } + class Application extends Ember.Application { } + class Array extends Ember.Array { } + class ArrayController extends Ember.ArrayController { } + var ArrayPolyfills: typeof Ember.ArrayPolyfills; + class ArrayProxy extends Ember.ArrayProxy { } + var BOOTED: typeof Ember.BOOTED; + class Binding extends Ember.Binding { } + class Button extends Ember.Button { } + class Checkbox extends Ember.Checkbox { } + class CollectionView extends Ember.CollectionView { } + class Comparable extends Ember.Comparable { } + class Component extends Ember.Component { } + class ComputedProperty extends Ember.ComputedProperty { } + class Container extends Ember.Container { } + class ContainerView extends Ember.ContainerView { } + class Controller extends Ember.Controller { } + class ControllerMixin extends Ember.ControllerMixin { } + class Copyable extends Ember.Copyable { } + class CoreObject extends Ember.CoreObject { } + class CoreView extends Ember.CoreView { } + class DAG extends Ember.DAG { } + var DEFAULT_GETTER_FUNCTION: typeof Ember.DEFAULT_GETTER_FUNCTION; + class DefaultResolver extends Ember.DefaultResolver { } + class Deffered extends Ember.Deferred { } + class DeferredMixin extends Ember.DeferredMixin { } + class Descriptor extends Ember.Descriptor { } + var EMPTY_META: typeof Ember.EMPTY_META; + var ENV: typeof Ember.ENV; + var EXTEND_PROTOTYPES: typeof Ember.EXTEND_PROTOTYPES; + class EachProxy extends Ember.EachProxy { } + class Enumerable extends Ember.Enumerable { } + var EnumerableUtils: typeof Ember.EnumerableUtils; + var Error: typeof Ember.Error; + class EventDispatcher extends Ember.EventDispatcher { } + class Evented extends Ember.Evented { } + var FROZEN_ERROR: typeof Ember.FROZEN_ERROR; + class Freezable extends Ember.Freezable { } + var GUID_KEY: typeof Ember.GUID_KEY; + namespace Handlebars { + var compile: typeof Ember.Handlebars.compile; + var get: typeof Ember.Handlebars.get; + var helper: typeof Ember.Handlebars.helper; + class helpers extends Ember.Handlebars.helpers { } + var precompile: typeof Ember.Handlebars.precompile; + var registerBoundHelper: typeof Ember.Handlebars.registerBoundHelper; + class Compiler extends Ember.Handlebars.Compiler { } + class JavaScriptCompiler extends Ember.Handlebars.JavaScriptCompiler { } + var registerHelper: typeof Ember.Handlebars.registerHelper; + var registerPartial: typeof Ember.Handlebars.registerPartial; + var K: typeof Ember.Handlebars.K; + var createFrame: typeof Ember.Handlebars.createFrame; + var Exception: typeof Ember.Handlebars.Exception; + class SafeString extends Ember.Handlebars.SafeString { } + var parse: typeof Ember.Handlebars.parse; + var print: typeof Ember.Handlebars.print; + var logger: typeof Ember.Handlebars.logger; + var log: typeof Ember.Handlebars.log; + } + class HashLocation extends Ember.HashLocation { } + class HistoryLocation extends Ember.HistoryLocation { } + var IS_BINDING: typeof Ember.IS_BINDING; + class Instrumentation extends Ember.Instrumentation { } + var K: typeof Ember.K; + var LOG_BINDINGS: typeof Ember.LOG_BINDINGS; + var LOG_STACKTRACE_ON_DEPRECATION: typeof Ember.LOG_STACKTRACE_ON_DEPRECATION; + var LOG_VERSION: typeof Ember.LOG_VERSION; + class LinkView extends Ember.LinkView { } + class Location extends Ember.Location { } + var Logger: typeof Ember.Logger; + var MANDATORY_SETTER_FUNCTION: typeof Ember.MANDATORY_SETTER_FUNCTION; + var META_KEY: typeof Ember.META_KEY; + class Map extends Ember.Map { } + class MapWithDefault extends Ember.MapWithDefault { } + class Mixin extends Ember.Mixin { } + class MutableArray extends Ember.MutableArray { } + class MutableEnumerable extends Ember.MutableEnumberable { } + var NAME_KEY: typeof Ember.NAME_KEY; + class Namespace extends Ember.Namespace { } + class NativeArray extends Ember.NativeArray { } + class NoneLocation extends Ember.NoneLocation { } + var ORDER_DEFINITION: typeof Ember.ORDER_DEFINITION; + class Object extends Ember.Object { } + class ObjectController extends Ember.ObjectController { } + class ObjectProxy extends Ember.ObjectProxy { } + class Observable extends Ember.Observable { } + class OrderedSet extends Ember.OrderedSet { } + namespace RSVP { + interface PromiseResolve extends Ember.RSVP.PromiseResolve { } + interface PromiseReject extends Ember.RSVP.PromiseReject { } + interface PromiseResolverFunction extends Ember.RSVP.PromiseResolverFunction { } + class Promise extends Ember.RSVP.Promise { } + } + class RenderBuffer extends Ember.RenderBuffer { } + class Route extends Ember.Route { } + class Router extends Ember.Router { } + class RouterDSL extends Ember.RouterDSL { } + var SHIM_ES5: typeof Ember.SHIM_ES5; + var STRINGS: typeof Ember.STRINGS; + class Select extends Ember.Select { } + class SelectOption extends Ember.SelectOption { } + class Set extends Ember.Set { } + class SortableMixin extends Ember.SortableMixin { } + class State extends Ember.State { } + class StateManager extends Ember.StateManager { } + namespace String { + var camelize: typeof Ember.String.camelize; + var capitalize: typeof Ember.String.capitalize; + var classify: typeof Ember.String.classify; + var dasherize: typeof Ember.String.dasherize; + var decamelize: typeof Ember.String.decamelize; + var fmt: typeof Ember.String.fmt; + var htmlSafe: typeof Ember.String.htmlSafe; + var loc: typeof Ember.String.loc; + var underscore: typeof Ember.String.underscore; + var w: typeof Ember.String.w; + } + var TEMPLATES: typeof Ember.TEMPLATES; + class TargetActionSupport extends Ember.TargetActionSupport { } + class Test extends Ember.Test { } + class TextArea extends Ember.TextArea { } + class TextField extends Ember.TextField { } + class TextSupport extends Ember.TextSupport { } + var VERSION: typeof Ember.VERSION; + class View extends Ember.View { } + class ViewTargetActionSupport extends Ember.ViewTargetActionSupport { } + var ViewUtils: typeof Ember.ViewUtils; + var addBeforeObserver: typeof Ember.addBeforeObserver; + var addListener: typeof Ember.addListener; + var addObserver: typeof Ember.addObserver; + var alias: typeof Ember.alias; + var aliasMethod: typeof Ember.aliasMethod; + var anyUnprocessedMixins: typeof Ember.anyUnprocessedMixins; + var assert: typeof Ember.assert; + var beforeObserver: typeof Ember.beforeObserver; + var beforeObserversFor: typeof Ember.beforeObserversFor; + var beginPropertyChanges: typeof Ember.beginPropertyChanges; + var bind: typeof Ember.bind; + var cacheFor: typeof Ember.cacheFor; + var canInvoke: typeof Ember.canInvoke; + var changeProperties: typeof Ember.changeProperties; + var compare: typeof Ember.compare; + var computed: typeof Ember.computed; + var config: typeof Ember.config; + var controllerFor: typeof Ember.controllerFor; + var copy: typeof Ember.copy; + var create: typeof Ember.create; + var debug: typeof Ember.debug; + var defineProperty: typeof Ember.defineProperty; + var deprecate: typeof Ember.deprecate; + var deprecateFunc: typeof Ember.deprecateFunc; + var destroy: typeof Ember.destroy; + var empty: typeof Ember.deprecateFunc; + var endPropertyChanges: typeof Ember.endPropertyChanges; + var exports: typeof Ember.exports; + var finishChains: typeof Ember.finishChains; + var flushPendingChains: typeof Ember.flushPendingChains; + var generateController: typeof Ember.generateController; + var generateGuid: typeof Ember.generateGuid; + var get: typeof Ember.get; + var getMeta: typeof Ember.getMeta; + var getPath: typeof Ember.getPath; + var getWithDefault: typeof Ember.getWithDefault; + var guidFor: typeof Ember.guidFor; + var handleErrors: typeof Ember.handleErrors; + var hasListeners: typeof Ember.hasListeners; + var hasOwnProperty: typeof Ember.hasOwnProperty; + var immediateObserver: typeof Ember.immediateObserver; + var imports: typeof Ember.imports; + var inspect: typeof Ember.inspect; + var instrument: typeof Ember.instrument; + var isArray: typeof Ember.isArray; + var isEmpty: typeof Ember.isEmpty; + var isEqual: typeof Ember.isEqual; + var isGlobalPath: typeof Ember.isGlobalPath; + var isNamespace: typeof Ember.isNamespace; + var isNone: typeof Ember.isNone; + var isPrototypeOf: typeof Ember.isPrototypeOf; + var isWatching: typeof Ember.isWatching; + var keys: typeof Ember.keys; + var listenersDiff: typeof Ember.listenersDiff; + var listenersFor: typeof Ember.listenersFor; + var listenersUnion: typeof Ember.listenersUnion; + var lookup: typeof Ember.lookup; + var makeArray: typeof Ember.makeArray; + var merge: typeof Ember.merge; + var meta: typeof Ember.meta; + var metaPath: typeof Ember.metaPath; + var mixin: typeof Ember.mixin; + var none: typeof Ember.none; + var normalizeTuple: typeof Ember.normalizeTuple; + var observer: typeof Ember.observer; + var observersFor: typeof Ember.observersFor; + var onLoad: typeof Ember.onLoad; + var oneWay: typeof Ember.oneWay; + var onError: typeof Ember.onError; + var overrideChains: typeof Ember.overrideChains; + var platform: typeof Ember.platform; + var propertyDidChange: typeof Ember.propertyDidChange; + var propertyIsEnumerable: typeof Ember.propertyIsEnumerable; + var propertyWillChange: typeof Ember.propertyWillChange; + var removeBeforeObserver: typeof Ember.removeBeforeObserver; + var removeChainWatcher: typeof Ember.removeChainWatcher; + var removeListener: typeof Ember.removeListener; + var removeObserver: typeof Ember.removeObserver; + var required: typeof Ember.required; + var rewatch: typeof Ember.rewatch; + var run: typeof Ember.run; + var runLoadHooks: typeof Ember.runLoadHooks; + var sendEvent: typeof Ember.sendEvent; + var set: typeof Ember.set; + var setMeta: typeof Ember.setMeta; + var setPath: typeof Ember.setPath; + var setProperties: typeof Ember.setProperties; + var subscribe: typeof Ember.subscribe; + var toLocaleString: typeof Ember.toLocaleString; + var toString: typeof Ember.toString; + var tryCatchFinally: typeof Ember.tryCatchFinally; + var tryFinally: typeof Ember.tryFinally; + var tryInvoke: typeof Ember.tryInvoke; + var trySet: typeof Ember.trySet; + var trySetPath: typeof Ember.trySetPath; + var typeOf: typeof Ember.typeOf; + var unwatch: typeof Ember.unwatch; + var unwatchKey: typeof Ember.unwatchKey; + var unwatchPath: typeof Ember.unwatchPath; + var uuid: typeof Ember.uuid; + var valueOf: typeof Ember.valueOf; + var warn: typeof Ember.warn; + var watch: typeof Ember.watch; + var watchKey: typeof Ember.watchKey; + var watchPath: typeof Ember.watchPath; + var watchedEvents: typeof Ember.watchedEvents; + var wrap: typeof Ember.wrap; +} diff --git a/ember/ember-tests.ts b/ember/ember-tests.ts index 33ff6be0b2..5924dbd0ae 100644 --- a/ember/ember-tests.ts +++ b/ember/ember-tests.ts @@ -93,9 +93,6 @@ App.wife.get('householdIncome'); App.user = Em.Object.create({ fullName: 'Kara Gates' }); -App.userView = Em.View.create({ - userNameBinding: Em.Binding.oneWay('App.user.fullName') -}); App.user.set('fullName', 'Krang Gates'); App.userView.set('userName', 'Truckasaurus Gates'); App.user.get('fullName'); @@ -104,26 +101,6 @@ App = Em.Application.create({ rootElement: '#sidebar' }); -var view = Em.View.create({ - templateName: 'say-hello', - name: 'Bob' -}); -view.appendTo('#container'); -view.append(); -view.remove(); - -App.AlertView = Em.View.extend({ - priority: 'p4', - isUrgent: true -}); - -App.ListingView = Em.View.extend({ - templateName: 'listing', - edit: (event: any) => { - event.view.set('isEditing', true); - } -}); - App.userController = Em.Object.create({ content: Em.Object.create({ firstName: 'Albert', @@ -134,32 +111,10 @@ App.userController = Em.Object.create({ }); Handlebars.registerHelper('highlight', function(property: string, options: any) { - var value = Em.Handlebars.get(this, property, options); - return new Handlebars.SafeString('' + value + ''); + return new Handlebars.SafeString('' + "some value" + ''); }); -App.MyText = Em.TextField.extend({ - formBlurredBinding: 'App.adminController.formBlurred', - change: function() { - this.set('formBlurred', true); - } -}); - -var textArea = Em.TextArea.create({ - valueBinding: 'TestObject.value' -}); - -App.ClickableView = Em.View.extend({ - click: () => { - alert('ClickableView was clicked!'); - } -}); - -var container = Em.ContainerView.create(); -container.append(); -var coolView = App.CoolView.create(), - childViews = container.get('childViews'); -childViews.pushObject(coolView); +var coolView = App.CoolView.create(); var Person2 = Em.Object.extend({ sayHello: function() { @@ -194,8 +149,8 @@ people2.some((person: Em.Object) => { people2.everyProperty('isHappy', true); people2.someProperty('isHappy', true); -// Examples taken from http://emberjs.com/api/classes/Ember.RSVP.Promise.html -var promise = new Ember.RSVP.Promise(function(resolve: Function, reject: Function) { +// Examples taken from http://emberjs.com/api/classes/Em.RSVP.Promise.html +var promise = new Em.RSVP.Promise(function(resolve: Function, reject: Function) { // on success resolve('ok!'); diff --git a/ember/ember.d.ts b/ember/ember.d.ts index c24661d763..20328feef8 100644 --- a/ember/ember.d.ts +++ b/ember/ember.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Ember.js 1.11.3 +// Type definitions for Ember.js 2.7 // Project: http://emberjs.com/ // Definitions by: Jed Mao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -448,7 +448,6 @@ declare namespace Ember { static metaForProperty(key: string): {}; static isClass: boolean; static isMethod: boolean; - static initializer(args?: ApplicationInitializerArguments): void; /** Call advanceReadiness after any asynchronous setup logic has completed. Each call to deferReadiness must be matched by a call to advanceReadiness @@ -530,6 +529,7 @@ declare namespace Ember { Application's router. **/ Router: Router; + registry: Registry; } /** This module implements Observer-friendly Array-like behavior. This mixin is picked up by the @@ -594,50 +594,6 @@ declare namespace Ember { length: number; } /** - Provides a way for you to publish a collection of objects so that you can easily bind to the - collection from a Handlebars #each helper, an Ember.CollectionView, or other controllers. - **/ - class ArrayController extends ArrayProxy implements SortableMixin, ControllerMixin { - static detect(obj: any): boolean; - static detectInstance(obj: any): boolean; - /** - Iterate over each computed property for the class, passing its name and any - associated metadata (see metaForProperty) to the callback. - **/ - static eachComputedProperty(callback: Function, binding: {}): void; - /** - Returns the original hash that was passed to meta(). - @param key property name - **/ - static metaForProperty(key: string): {}; - static isClass: boolean; - static isMethod: boolean; - lookupItemController(object: any): string; - arrangedContent: any; - itemController: string; - sortAscending: boolean; - sortFunction: Comparable; - sortProperties: any[]; - replaceRoute(name: string, ...args: any[]): void; - transitionToRoute(name: string, ...args: any[]): void; - controllers: {}; - needs: string[]; - target: any; - model: any; - queryParams: any; - send(name: string, ...args: any[]): void; - actions: {}; - - } - /** - Array polyfills to support ES5 features in older browsers. - **/ - var ArrayPolyfills: { - map: typeof Array.prototype.map; - forEach: typeof Array.prototype.forEach; - indexOf: typeof Array.prototype.indexOf; - }; - /** An ArrayProxy wraps any other object that implements Ember.Array and/or Ember.MutableArray, forwarding all requests. This makes it very useful for a number of binding use cases or other cases where being able to swap out the underlying array is useful. @@ -741,14 +697,13 @@ declare namespace Ember { constructor(toPath: string, fromPath: string); connect(obj: any): Binding; copy(): Binding; - disconnect(obj: any): Binding; + disconnect(): Binding; from(path: string): Binding; - static oneWay(from: string, flag?: boolean): Binding; to(path: string): Binding; to(pathTuple: any[]): Binding; toString(): string; } - class Button extends View implements TargetActionSupport { + class Button extends Component implements TargetActionSupport { static detect(obj: any): boolean; static detectInstance(obj: any): boolean; /** @@ -769,7 +724,7 @@ declare namespace Ember { The internal class used to create text inputs when the {{input}} helper is used with type of checkbox. See Handlebars.helpers.input for usage details. **/ - class Checkbox extends View { + class Checkbox extends Component { static detect(obj: any): boolean; static detectInstance(obj: any): boolean; /** @@ -786,23 +741,6 @@ declare namespace Ember { static isMethod: boolean; } /** - An Ember.View descendent responsible for managing a collection (an array or array-like object) - by maintaining a child view object and associated DOM representation for each item in the array - and ensuring that child views and their associated rendered HTML are updated when items in the - array are added, removed, or replaced. - **/ - class CollectionView extends ContainerView { - arrayDidChange(content: any[], start: number, removed: number, added: number): void; - arrayWillChange(content: any[], start: number, removed: number): void; - createChildView(viewClass: {}, attrs?: {}): CollectionView; - destroy(): CollectionView; - init(): void; - static CONTAINER_MAP: {}; - content: any[]; - emptyView: View; - itemViewClass: View; - } - /** Implements some standard methods for comparing objects. Add this mixin to any class you create that can compare its instances. **/ @@ -814,7 +752,7 @@ declare namespace Ember { and actions are targeted at the view object. There is no access to the surrounding context or outer controller; all contextual information is passed in. **/ - class Component extends View { + class Component { static detect(obj: any): boolean; static detectInstance(obj: any): boolean; /** @@ -839,7 +777,6 @@ declare namespace Ember { This will force the cached result to be recomputed if the dependencies are modified. **/ class ComputedProperty { - cacheable(aFlag?: boolean): ComputedProperty; get(keyName: string): any; meta(meta: {}): ComputedProperty; property(...args: string[]): ComputedProperty; @@ -853,8 +790,10 @@ declare namespace Ember { constructor(parent: Container); parent: Container; children: any[]; + owner: any; + ownerInjection(): any; resolver: Function; - registry: {}; + registry: Registry; cache: {}; typeInjections: {}; injections: {}; @@ -865,42 +804,13 @@ declare namespace Ember { @param fullName type:name (e.g., 'model:user') @param factory (e.g., App.Person) **/ - register(fullName: string, factory: Function, options?: {}): void; - unregister(fullName: string): void; - resolve(fullName: string): Function; describe(fullName: string): string; - normalize(fullName: string): string; makeToString(factory: any, fullName: string): Function; lookup(fullName: string, options?: {}): any; - lookupFactory(fullName: string): any; - has(fullName: string): boolean; - optionsForType(type: string, options: {}): void; - options(type: string, options: {}): void; - injection(factoryName: string, property: string, injectionName: string): void; - factoryInjection(factoryName: string, property: string, injectionName: string): void; + lookupFactory(fullName: string, options?: {}): any; destroy(): void; reset(): void; } - /** - An Ember.View subclass that implements Ember.MutableArray allowing programatic - management of its child views. - **/ - class ContainerView extends View { - static detect(obj: any): boolean; - static detectInstance(obj: any): boolean; - /** - Iterate over each computed property for the class, passing its name and any - associated metadata (see metaForProperty) to the callback. - **/ - static eachComputedProperty(callback: Function, binding: {}): void; - /** - Returns the original hash that was passed to meta(). - @param key property name - **/ - static metaForProperty(key: string): {}; - static isClass: boolean; - static isMethod: boolean; - } class Controller extends Object implements ControllerMixin { replaceRoute(name: string, ...args: any[]): void; transitionToRoute(name: string, ...args: any[]): void; @@ -1079,30 +989,6 @@ declare namespace Ember { **/ static eachComputedProperty(callback: Function, binding: {}): void; } - /** - An abstract class that exists to give view-like behavior to both Ember's main view class Ember.View - and other classes like Ember._SimpleMetamorphView that don't need the fully functionaltiy of Ember.View. - Unless you have specific needs for CoreView, you will use Ember.View in your applications. - **/ - class CoreView extends Object implements ActionHandlerMixin { - static detect(obj: any): boolean; - static detectInstance(obj: any): boolean; - /** - Iterate over each computed property for the class, passing its name and any - associated metadata (see metaForProperty) to the callback. - **/ - static eachComputedProperty(callback: Function, binding: {}): void; - /** - Returns the original hash that was passed to meta(). - @param key property name - **/ - static metaForProperty(key: string): {}; - static isClass: boolean; - static isMethod: boolean; - send(name: string, ...args: any[]): void; - actions: ActionsHash; - parentView: CoreView; - } class DAG { add(name: string): any; map(name: string, value: any): void; @@ -1124,25 +1010,25 @@ declare namespace Ember { resolve(fullName: string): {}; namespace: Application; } - class Deferred { - reject(value: any): void; - resolve(value: any): void; - then(resolve: Function, reject: Function): void; - } - class DeferredMixin extends Mixin { - reject(value: any): void; - resolve(value: any): void; - then(resolve: Function, reject: Function): void; - } /** Objects of this type can implement an interface to respond to requests to get and set. The default implementation handles simple properties. You generally won't need to create or subclass this directly. **/ class Descriptor { } - var EMPTY_META: {}; // TODO: define interface - var ENV: {}; - var EXTEND_PROTOTYPES: boolean; + namespace ENV { + export var EXTEND_PROTOTYPES: typeof Ember.EXTEND_PROTOTYPES; + export var LOG_BINDINGS: boolean; + export var LOG_STACKTRACE_ON_DEPRECATION: boolean; + export var LOG_VERSION: boolean; + export var MODEL_FACTORY_INJECTIONS: boolean; + export var RAISE_ON_DEPRECATION: boolean; + } + namespace EXTEND_PROTOTYPES { + export var Array: boolean; + export var Function: boolean; + export var String: boolean; + } /** This is the object instance returned when you get the @each property on an array. It uses the unknownProperty handler to automatically create EachArray instances for property names. @@ -1217,7 +1103,6 @@ declare namespace Ember { hasEnumerableObservers: boolean; lastObject: any; } - var EnumerableUtils: {}; // TODO: define interface /** A subclass of the JavaScript Error object for use in Ember. **/ @@ -1264,38 +1149,9 @@ declare namespace Ember { var GUID_KEY: string; namespace Handlebars { function compile(string: string): Function; - function get(root: any, path: string, options?: {}): any; - function helper(name: string, func: Function, dependentKeys?: string): void; - function helper(name: string, view: View, dependentKeys?: string): void; - class helpers { - action(actionName: string, context: any, options?: {}): void; - bindAttr(options?: {}): string; - connectOutlet(outletName: string, view: {}): void; - control(path: string, modelPath: string, options?: {}): string; - debugger(property: string): void; - disconnectOutlet(outletName: string): void; - each(name: string, path: string, options?: {}): void; - if(context: Function, options?: {}): string; - init(): void; - input(options?: {}): void; - linkTo(routeName: string, context: any, options?: {}): string; - loc(str: string): void; - log(property: string): void; - outlet(property: string): string; - partial(partialName: string): void; - render(name: string, context?: string, options?: {}): string; - textarea(options?: {}): void; - unbound(property: string): string; - unless(context: Function, options?: {}): string; - view(path: string, options?: {}): string; - with(context: Function, options?: {}): string; - yield(options?: {}): string; - } - function precompile(string: string): void; - function registerBoundHelper(name: string, func: Function, dependentKeys?: string): void; + function precompile(string: string, options: any): void; class Compiler { } class JavaScriptCompiler { } - function registerHelper(name: string, fn: Function, inverse?: boolean): void; function registerPartial(name: string, str: any): void; function K(): any; function createFrame(objec: any): any; @@ -1356,38 +1212,6 @@ declare namespace Ember { var LOG_BINDINGS: boolean; var LOG_STACKTRACE_ON_DEPRECATION: boolean; var LOG_VERSION: boolean; - class LinkView extends View { - static detect(obj: any): boolean; - static detectInstance(obj: any): boolean; - /** - Iterate over each computed property for the class, passing its name and any - associated metadata (see metaForProperty) to the callback. - **/ - static eachComputedProperty(callback: Function, binding: {}): void; - /** - Returns the original hash that was passed to meta(). - @param key property name - **/ - static metaForProperty(key: string): {}; - static isClass: boolean; - static isMethod: boolean; - init(): void; - active: any; - activeClass: string; - attributeBindings: any; - classNameBindings: string[]; - disabled: any; - disabledClass: string; - eventName: string; - href: any; - loading: any; - loadingClass: string; - loadingHref: string; - rel: any; - replace: boolean; - title: any; - click: Function; - } class Location { create(options?: {}): any; registerImplementation(name: string, implementation: any): void; @@ -1408,7 +1232,6 @@ declare namespace Ember { forEach(callback: Function, self: any): void; get(key: any): any; has(key: any): boolean; - remove(key: any): boolean; set(key: any, value: any): void; length: number; } @@ -1716,17 +1539,6 @@ declare namespace Ember { setProperties(hash: {}): Observable; toggleProperty(keyName: string): any; } - class ObjectController extends ObjectProxy implements ControllerMixin { - replaceRoute(name: string, ...args: any[]): void; - transitionToRoute(name: string, ...args: any[]): void; - controllers: Object; - needs: string[]; - target: any; - model: any; - queryParams: any; - send(name: string, ...args: any[]): void; - actions: {}; - } class ObjectProxy extends Object { static detect(obj: any): boolean; static detectInstance(obj: any): boolean; @@ -1779,9 +1591,12 @@ declare namespace Ember { forEach(fn: Function, self: any): void; has(obj: any): boolean; isEmpty(): boolean; - remove(obj: any): void; toArray(): any[]; } + class Registry { + constructor (options: any); + static set: typeof Ember.set; + } // FYI - RSVP source comes from https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/promise.js namespace RSVP { @@ -1848,25 +1663,6 @@ declare namespace Ember { finally(callback: Function, label?: string): Promise; } } - class RenderBuffer { - addClass(className: string): RenderBuffer; - attr(name: string, value: any): any; - element(): HTMLElement; - id(id: string): RenderBuffer; - prop(name: string, value: string): any; - push(string: string): RenderBuffer; - removeAttr(name: string): RenderBuffer; - removeProp(name: string): RenderBuffer; - string(): string; - style(name: string, value: string): RenderBuffer; - classes: any[]; - elementAttributes: {}; - elementId: string; - elementProperties: {}; - elementStyle: {}; - elementTag: string; - parentBuffer: RenderBuffer; - } /** The `Ember.Route` class is used to define individual routes. Refer to @@ -2413,170 +2209,11 @@ declare namespace Ember { resource(name: string, options?: {}, callback?: Function): void; resource(name: string, callback: Function): void; route(name: string, options?: {}): void; + explicitIndex: boolean; + router: Router; + options: any; } - var SHIM_ES5: boolean; var STRINGS: boolean; - class Select extends View { - static detect(obj: any): boolean; - static detectInstance(obj: any): boolean; - /** - Iterate over each computed property for the class, passing its name and any - associated metadata (see metaForProperty) to the callback. - **/ - static eachComputedProperty(callback: Function, binding: {}): void; - /** - Returns the original hash that was passed to meta(). - @param key property name - **/ - static metaForProperty(key: string): {}; - static isClass: boolean; - static isMethod: boolean; - content: any[]; - groupView: View; - multiple: boolean; - optionGroupPath: string; - optionLabelPath: string; - optionValuePath: string; - optionView: View; - prompt: string; - selection: any; - value: string; - } - class SelectOption extends View { - static detect(obj: any): boolean; - static detectInstance(obj: any): boolean; - /** - Iterate over each computed property for the class, passing its name and any - associated metadata (see metaForProperty) to the callback. - **/ - static eachComputedProperty(callback: Function, binding: {}): void; - /** - Returns the original hash that was passed to meta(). - @param key property name - **/ - static metaForProperty(key: string): {}; - static isClass: boolean; - static isMethod: boolean; - } - class Set extends CoreObject implements MutableEnumberable, Copyable, Freezable { - addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Set; - addObject(object: any): any; - addObjects(objects: Enumerable): Set; - any(callback: Function, target?: any): boolean; - anyBy(key: string, value?: string): boolean; - someProperty(key: string, value?: string): boolean; - compact(): any[]; - contains(obj: any): boolean; - enumerableContentDidChange(start: number, removing: number, adding: number): any; - enumerableContentDidChange(start: number, removing: Enumerable, adding: number): any; - enumerableContentDidChange(start: number, removing: number, adding: Enumerable): any; - enumerableContentDidChange(start: number, removing: Enumerable, adding: Enumerable): any; - enumerableContentDidChange(removing: number, adding: number): any; - enumerableContentDidChange(removing: Enumerable, adding: number): any; - enumerableContentDidChange(removing: number, adding: Enumerable): any; - enumerableContentDidChange(removing: Enumerable, adding: Enumerable): any; - enumerableContentWillChange(removing: number, adding: number): Set; - enumerableContentWillChange(removing: Enumerable, adding: number): Set; - enumerableContentWillChange(removing: number, adding: Enumerable): Set; - enumerableContentWillChange(removing: Enumerable, adding: Enumerable): Set; - every(callback: Function, target?: any): boolean; - everyBy(key: string, value?: string): boolean; - everyProperty(key: string, value?: string): boolean; - filter(callback: Function, target: any): any[]; - filterBy(key: string, value?: string): any[]; - find(callback: Function, target: any): any; - findBy(key: string, value?: string): any; - forEach(callback: Function, target?: any): any; - getEach(key: string): any[]; - invoke(methodName: string, ...args: any[]): any[]; - map: ItemIndexEnumerableCallbackTarget; - mapBy(key: string): any[]; - nextObject(index: number, previousObject: any, context: any): any; - reduce(callback: ReduceCallback, initialValue: any, reducerProperty: string): any; - reject: ItemIndexEnumerableCallbackTarget; - rejectBy(key: string, value?: string): any[]; - removeEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Set; - removeObject(object: any): any; - removeObjects(objects: Enumerable): Set; - setEach(key: string, value?: any): any; - some(callback: Function, target?: any): boolean; - toArray(): any[]; - uniq(): Set; - without(value: any): Set; - '[]': any[]; - firstObject: any; - hasEnumerableObservers: boolean; - lastObject: any; - copy(deep: boolean): Set; - frozenCopy(): Set; - freeze(): Set; - isFrozen: boolean; - add(obj: any): Set; - addEach(...args: any[]): Set; - clear(): Set; - isEqual(obj: Set): boolean; - pop(): any; - push(obj: any): Set; - remove(obj: any): Set; - removeEach(...args: any[]): Set; - shift(): any; - unshift(obj: any): Set; - length: number; - } - class SortableMixin implements MutableEnumberable { - addEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; - addObject(object: any): any; - addObjects(objects: Enumerable): MutableEnumberable; - any(callback: Function, target?: any): boolean; - anyBy(key: string, value?: string): boolean; - someProperty(key: string, value?: string): boolean; - compact(): any[]; - contains(obj: any): boolean; - enumerableContentDidChange(start: number, removing: number, adding: number): any; - enumerableContentDidChange(start: number, removing: Enumerable, adding: number): any; - enumerableContentDidChange(start: number, removing: number, adding: Enumerable): any; - enumerableContentDidChange(start: number, removing: Enumerable, adding: Enumerable): any; - enumerableContentDidChange(removing: number, adding: number): any; - enumerableContentDidChange(removing: Enumerable, adding: number): any; - enumerableContentDidChange(removing: number, adding: Enumerable): any; - enumerableContentDidChange(removing: Enumerable, adding: Enumerable): any; - enumerableContentWillChange(removing: number, adding: number): Enumerable; - enumerableContentWillChange(removing: Enumerable, adding: number): Enumerable; - enumerableContentWillChange(removing: number, adding: Enumerable): Enumerable; - enumerableContentWillChange(removing: Enumerable, adding: Enumerable): Enumerable; - every(callback: Function, target?: any): boolean; - everyBy(key: string, value?: string): boolean; - everyProperty(key: string, value?: string): boolean; - filter(callback: Function, target: any): any[]; - filterBy(key: string, value?: string): any[]; - find(callback: Function, target: any): any; - findBy(key: string, value?: string): any; - forEach(callback: Function, target?: any): any; - getEach(key: string): any[]; - invoke(methodName: string, ...args: any[]): any[]; - map: ItemIndexEnumerableCallbackTarget; - mapBy(key: string): any[]; - nextObject(index: number, previousObject: any, context: any): any; - reduce(callback: ReduceCallback, initialValue: any, reducerProperty: string): any; - reject: ItemIndexEnumerableCallbackTarget; - rejectBy(key: string, value?: string): any[]; - removeEnumerableObserver(target: any, opts: EnumerableConfigurationOptions): Enumerable; - removeObject(object: any): any; - removeObjects(objects: Enumerable): MutableEnumberable; - setEach(key: string, value?: any): any; - some(callback: Function, target?: any): boolean; - toArray(): any[]; - uniq(): Enumerable; - without(value: any): Enumerable; - '[]': any[]; - arrangedContent: any; - firstObject: any; - hasEnumerableObservers: boolean; - lastObject: any; - sortAscending: boolean; - sortFunction: Comparable; - sortProperties: any[]; - } class State extends Object implements Evented { static detect(obj: any): boolean; static detectInstance(obj: any): boolean; @@ -2659,25 +2296,30 @@ declare namespace Ember { class TargetActionSupport { triggerAction(opts: {}): boolean; } - class Test { - click(selector: string): RSVP.Promise; - fillin(selector: string, text: string): RSVP.Promise; - find(selector: string): JQuery; - findWithAssert(selector: string): JQuery; - injectTestHelpers(): void; - keyEvent(selector: string, type: string, keyCode: number): RSVP.Promise; - static oninjectHelpers(callback: Function): void; - static promise(resolver: Function): RSVP.Promise; - static registerHelper(name: string, helperMethod: Function): void; - removeTestHelpers(): void; - setupForTesting(): void; - static unregisterHelper(name: string): void; - visit(url: string): RSVP.Promise; - wait(value: any): RSVP.Promise; - static adapter: Object; - testHelpers: {}; + namespace Test { + class Adapter extends Ember.Object { + constructor (); + } + class Promise extends Ember.RSVP.Promise { + constructor (); + } + function oninjectHelpers(callback: Function): void; + function promise(resolver: Function, label: string): Ember.Test.Promise; + function unregisterHelper(name: string): void; + function registerHelper(name: string, helperMethod: Function): void; + function registerAsyncHelper(name: string, helperMethod: Function): void; + + var adapter: Object; + var QUnitAdapter: Object; + + function registerWaiter(callback: Function): void; + function registerWaiter(context: any, callback: Function): void; + function unregisterWaiter(callback: Function): void; + function unregisterWaiter(context: any, callback: Function): void; + + function resolve(result: any): Ember.Test.Promise; } - class TextArea extends View implements TextSupport { + class TextArea extends Component implements TextSupport { static detect(obj: any): boolean; static detectInstance(obj: any): boolean; /** @@ -2701,7 +2343,7 @@ declare namespace Ember { bubbles: boolean; onEvent: string; } - class TextField extends View implements TextSupport { + class TextField extends Component implements TextSupport { static detect(obj: any): boolean; static detectInstance(obj: any): boolean; /** @@ -2740,76 +2382,11 @@ declare namespace Ember { onEvent: string; } var VERSION: string; - class View extends CoreView { - static detect(obj: any): boolean; - static detectInstance(obj: any): boolean; - /** - Iterate over each computed property for the class, passing its name and any - associated metadata (see metaForProperty) to the callback. - **/ - static eachComputedProperty(callback: Function, binding: {}): void; - /** - Returns the original hash that was passed to meta(). - @param key property name - **/ - static metaForProperty(key: string): {}; - static isClass: boolean; - static isMethod: boolean; - $(): JQuery; - append(): View; - // ReSharper disable InconsistentNaming - appendTo(A: string): View; - appendTo(A: HTMLElement): View; - appendTo(A: JQuery): View; - // ReSharper restore InconsistentNaming - createChildView(viewClass: {}, attrs?: {}): View; - createChildView(viewClass: string, attrs?: {}): View; - createElement(): View; - destroy(): View; - destroyElement(): View; - findElementInParentElement(parentElement: HTMLElement): HTMLElement; - remove(): View; - removeAllChildren(): View; - removeChild(view: View): View; - removeFromParent(): View; - render(buffer: RenderBuffer): void; - // ReSharper disable InconsistentNaming - replaceIn(A: string): View; - replaceIn(A: HTMLElement): View; - replaceIn(A: JQuery): View; - // ReSharper restore InconsistentNaming - rerender(): void; - ariaRole: string; - attributeBindings: any; - classNameBindings: string[]; - classNames: string[]; - context: any; - controller: any; - element: HTMLElement; - isView: boolean; - isVisible: boolean; - layout: Function; - layoutName: string; - nearestChildOf: View; - nearestOfType: View; - nearestWithProperty: View; - tagName: string; - template: Function; - templateName: string; - templates: {}; - views: {}; - didInsertElement: Function; - parentViewDidChange: Function; - willClearRender: Function; - willDestroyElement: Function; - willInsertElement: Function; - } class ViewTargetActionSupport extends Mixin { target: any; actionContext: any; } var ViewUtils: {}; // TODO: define interface - function addBeforeObserver(obj: any, path: string, target: any, method: Function): any; function addListener(obj: any, eventName: string, target: any, method: Function, once?: boolean): void; function addListener(obj: any, eventName: string, target: any, method: string, once?: boolean): void; function addListener(obj: any, eventName: string, func: Function, method: Function, once?: boolean): void; @@ -2820,10 +2397,7 @@ declare namespace Ember { **/ var alias: typeof deprecateFunc; function aliasMethod(methodName: string): Descriptor; - var anyUnprocessedMixins: boolean; function assert(desc: string, test: boolean): void; - function beforeObserver(func: Function, propertyName: string): Function; - function beforeObserversFor(obj: any, path: string): string[]; function beginPropertyChanges(): void; function bind(obj: any, to: string, from: string): Binding; function cacheFor(obj: any, key: string): any; @@ -2852,8 +2426,6 @@ declare namespace Ember { oneWay(dependentKey: string): ComputedProperty; or(...args: string[]): ComputedProperty; }; - // ReSharper disable DuplicatingLocalDeclaration - var config: {}; // ReSharper restore DuplicatingLocalDeclaration function controllerFor(container: Container, controllerName: string, lookupOptions?: {}): Controller; function copy(obj: any, deep: boolean): any; @@ -2873,14 +2445,10 @@ declare namespace Ember { // ReSharper disable once DuplicatingLocalDeclaration var empty: typeof deprecateFunc; function endPropertyChanges(): void; - // ReSharper disable once DuplicatingLocalDeclaration - var exports: {}; function finishChains(obj: any): void; - function flushPendingChains(): void; function generateController(container: Container, controllerName: string, context: any): Controller; function generateGuid(obj: any, prefix?: string): string; function get(obj: any, keyName: string): any; - function getMeta(obj: any, property: string): any; /** getPath is deprecated since get now supports paths. **/ @@ -2891,7 +2459,6 @@ declare namespace Ember { function hasListeners(context: any, name: string): boolean; function hasOwnProperty(prop: string): boolean; function immediateObserver(func: Function, ...propertyNames: any[]): Function; - var imports: {}; function inspect(obj: any): string; function instrument(name: string, payload: any, callback: Function, binding: any): void; function isArray(obj: any): boolean; @@ -2910,33 +2477,25 @@ declare namespace Ember { var lookup: {}; // TODO: define interface function makeArray(obj: any): any[]; function merge(original: any, updates: any): any; - function meta(obj: any, writable?: boolean): {}; - function metaPath(obj: any, path: string, writable?: boolean): any; + function meta(obj: any): {}; function mixin(obj: any, ...args: any[]): any; /** Ember.none is deprecated. Please use Ember.isNone instead. **/ var none: typeof deprecateFunc; - function normalizeTuple(target: any, path: string): any[]; function observer(...args: any[]): Function; function observersFor(obj: any, path: string): any[]; function onLoad(name: string, callback: Function): void; - function oneWay(obj: any, to: string, from: string): Binding; var onError: Error; function overrideChains(obj: any, keyName: string, m: any): boolean; // ReSharper disable once DuplicatingLocalDeclaration var platform: { - addBeforeObserver: ModifyObserver; - addObserver: ModifyObserver; - defineProperty(obj: any, keyName: string, desc: {}): void; - removeBeforeObserver: ModifyObserver; - removeObserver: ModifyObserver; + defineProperty: boolean; hasPropertyAccessors: boolean; }; function propertyDidChange(obj: any, keyName: string): void; function propertyIsEnumerable(prop: string): boolean; function propertyWillChange(obj: any, keyName: string): void; - function removeBeforeObserver(obj: any, path: string, target: any, method: Function): any; function removeChainWatcher(obj: any, keyName: string, node: any): void; function removeListener(obj: any, eventName: string, target: any, method: Function): void; function removeListener(obj: any, eventName: string, target: any, method: string): void; @@ -2972,7 +2531,6 @@ declare namespace Ember { function runLoadHooks(name: string, object: any): void; function sendEvent(obj: any, eventName: string, params?: any[], actions?: any[]): boolean; function set(obj: any, keyName: string, value: any): any; - function setMeta(obj: any, property: string, value: any): void; /** setPath is deprecated since set now supports paths. **/ @@ -2982,7 +2540,6 @@ declare namespace Ember { function toLocaleString(): string; function toString(): string; function tryCatchFinally(tryable: Function, catchable: Function, finalizer: Function, binding?: any): any; - function tryFinally(tryable: Function, finalizer: Function, binding?: any): any; function tryInvoke(obj: any, methodName: string, args?: any[]): any; function trySet(obj: any, path: string, value: any): void; /** @@ -3002,48 +2559,42 @@ declare namespace Ember { function watchPath(obj: any, keyPath: string): void; function watchedEvents(obj: {}): any[]; function wrap(func: Function, superFunc: Function): Function; + var _ContainerProxyMixin : Mixin; + var _RegistryProxyMixin: Mixin; + function getOwner(object: any): any; + function setOwner(object: any, owner: any): void; + var testing : boolean; + var MODEL_FACTORY_INJECTIONS : boolean; + function assign(original: any, ...sources: any[]): any; } -// ReSharper disable DuplicatingLocalDeclaration declare namespace Em { - /** - Alias for jQuery. - **/ var $: typeof Ember.$; var A: typeof Ember.A; - class ActionHandlerMixin extends Ember.ActionHandlerMixin { } + class ActionHandlerMixin extends Ember.ActionHandlerMixin { } class Application extends Ember.Application { } class Array extends Ember.Array { } - class ArrayController extends Ember.ArrayController { } - var ArrayPolyfills: typeof Ember.ArrayPolyfills; class ArrayProxy extends Ember.ArrayProxy { } var BOOTED: typeof Ember.BOOTED; class Binding extends Ember.Binding { } class Button extends Ember.Button { } class Checkbox extends Ember.Checkbox { } - class CollectionView extends Ember.CollectionView { } class Comparable extends Ember.Comparable { } class Component extends Ember.Component { } class ComputedProperty extends Ember.ComputedProperty { } class Container extends Ember.Container { } - class ContainerView extends Ember.ContainerView { } class Controller extends Ember.Controller { } class ControllerMixin extends Ember.ControllerMixin { } - class Copyable extends Ember.Copyable { } + class Copyable extends Ember.Copyable {} class CoreObject extends Ember.CoreObject { } - class CoreView extends Ember.CoreView { } - class DAG extends Ember.DAG { } - var DEFAULT_GETTER_FUNCTION: typeof Ember.DEFAULT_GETTER_FUNCTION; - class DefaultResolver extends Ember.DefaultResolver { } - class Deffered extends Ember.Deferred { } - class DeferredMixin extends Ember.DeferredMixin { } + class DAG extends Ember.DAG {} + var DEFAULT_GETTER_FUNCTION : typeof Ember.DEFAULT_GETTER_FUNCTION; + class DefaultResolver extends Ember.DefaultResolver { } class Descriptor extends Ember.Descriptor { } - var EMPTY_META: typeof Ember.EMPTY_META; var ENV: typeof Ember.ENV; var EXTEND_PROTOTYPES: typeof Ember.EXTEND_PROTOTYPES; class EachProxy extends Ember.EachProxy { } class Enumerable extends Ember.Enumerable { } - var EnumerableUtils: typeof Ember.EnumerableUtils; var Error: typeof Ember.Error; class EventDispatcher extends Ember.EventDispatcher { } class Evented extends Ember.Evented { } @@ -3052,14 +2603,9 @@ declare namespace Em { var GUID_KEY: typeof Ember.GUID_KEY; namespace Handlebars { var compile: typeof Ember.Handlebars.compile; - var get: typeof Ember.Handlebars.get; - var helper: typeof Ember.Handlebars.helper; - class helpers extends Ember.Handlebars.helpers { } var precompile: typeof Ember.Handlebars.precompile; - var registerBoundHelper: typeof Ember.Handlebars.registerBoundHelper; class Compiler extends Ember.Handlebars.Compiler { } - class JavaScriptCompiler extends Ember.Handlebars.JavaScriptCompiler { } - var registerHelper: typeof Ember.Handlebars.registerHelper; + class JavaScriptCompiler extends Ember.Handlebars.JavaScriptCompiler{ } var registerPartial: typeof Ember.Handlebars.registerPartial; var K: typeof Ember.Handlebars.K; var createFrame: typeof Ember.Handlebars.createFrame; @@ -3078,8 +2624,7 @@ declare namespace Em { var LOG_BINDINGS: typeof Ember.LOG_BINDINGS; var LOG_STACKTRACE_ON_DEPRECATION: typeof Ember.LOG_STACKTRACE_ON_DEPRECATION; var LOG_VERSION: typeof Ember.LOG_VERSION; - class LinkView extends Ember.LinkView { } - class Location extends Ember.Location { } + class Location extends Ember.Location {} var Logger: typeof Ember.Logger; var MANDATORY_SETTER_FUNCTION: typeof Ember.MANDATORY_SETTER_FUNCTION; var META_KEY: typeof Ember.META_KEY; @@ -3087,66 +2632,57 @@ declare namespace Em { class MapWithDefault extends Ember.MapWithDefault { } class Mixin extends Ember.Mixin { } class MutableArray extends Ember.MutableArray { } - class MutableEnumerable extends Ember.MutableEnumberable { } + class MutableEnumberable extends Ember.MutableEnumberable { } var NAME_KEY: typeof Ember.NAME_KEY; class Namespace extends Ember.Namespace { } class NativeArray extends Ember.NativeArray { } class NoneLocation extends Ember.NoneLocation { } var ORDER_DEFINITION: typeof Ember.ORDER_DEFINITION; class Object extends Ember.Object { } - class ObjectController extends Ember.ObjectController { } class ObjectProxy extends Ember.ObjectProxy { } class Observable extends Ember.Observable { } class OrderedSet extends Ember.OrderedSet { } + class Registry extends Ember.Registry { } namespace RSVP { interface PromiseResolve extends Ember.RSVP.PromiseResolve { } interface PromiseReject extends Ember.RSVP.PromiseReject { } interface PromiseResolverFunction extends Ember.RSVP.PromiseResolverFunction { } class Promise extends Ember.RSVP.Promise { } } - class RenderBuffer extends Ember.RenderBuffer { } - class Route extends Ember.Route { } + class Route extends Ember.Route {} class Router extends Ember.Router { } class RouterDSL extends Ember.RouterDSL { } - var SHIM_ES5: typeof Ember.SHIM_ES5; var STRINGS: typeof Ember.STRINGS; - class Select extends Ember.Select { } - class SelectOption extends Ember.SelectOption { } - class Set extends Ember.Set { } - class SortableMixin extends Ember.SortableMixin { } class State extends Ember.State { } class StateManager extends Ember.StateManager { } - namespace String { - var camelize: typeof Ember.String.camelize; - var capitalize: typeof Ember.String.capitalize; - var classify: typeof Ember.String.classify; - var dasherize: typeof Ember.String.dasherize; - var decamelize: typeof Ember.String.decamelize; - var fmt: typeof Ember.String.fmt; - var htmlSafe: typeof Ember.String.htmlSafe; - var loc: typeof Ember.String.loc; - var underscore: typeof Ember.String.underscore; - var w: typeof Ember.String.w; - } + var String : typeof Ember.String; var TEMPLATES: typeof Ember.TEMPLATES; - class TargetActionSupport extends Ember.TargetActionSupport { } - class Test extends Ember.Test { } + class TargetActionSupport extends Ember.TargetActionSupport {} + namespace Test { + class Adapter extends Ember.Test.Adapter { } + class Promise extends Ember.Test.Promise { } + var oninjectHelpers: typeof Ember.Test.oninjectHelpers; + var promise: typeof Ember.Test.promise; + var unregisterHelper: typeof Ember.Test.unregisterHelper; + var registerHelper: typeof Ember.Test.registerHelper; + var registerAsyncHelper: typeof Ember.Test.registerAsyncHelper; + var adapter: typeof Ember.Test.adapter; + var QUnitAdapter: typeof Ember.Test.QUnitAdapter; + var registerWaiter: typeof Ember.Test.registerWaiter; + var unregisterWaiter: typeof Ember.Test.unregisterWaiter + var resolve: typeof Ember.Test.resolve; + } class TextArea extends Ember.TextArea { } class TextField extends Ember.TextField { } class TextSupport extends Ember.TextSupport { } var VERSION: typeof Ember.VERSION; - class View extends Ember.View { } class ViewTargetActionSupport extends Ember.ViewTargetActionSupport { } var ViewUtils: typeof Ember.ViewUtils; - var addBeforeObserver: typeof Ember.addBeforeObserver; var addListener: typeof Ember.addListener; var addObserver: typeof Ember.addObserver; var alias: typeof Ember.alias; var aliasMethod: typeof Ember.aliasMethod; - var anyUnprocessedMixins: typeof Ember.anyUnprocessedMixins; var assert: typeof Ember.assert; - var beforeObserver: typeof Ember.beforeObserver; - var beforeObserversFor: typeof Ember.beforeObserversFor; var beginPropertyChanges: typeof Ember.beginPropertyChanges; var bind: typeof Ember.bind; var cacheFor: typeof Ember.cacheFor; @@ -3154,24 +2690,20 @@ declare namespace Em { var changeProperties: typeof Ember.changeProperties; var compare: typeof Ember.compare; var computed: typeof Ember.computed; - var config: typeof Ember.config; var controllerFor: typeof Ember.controllerFor; var copy: typeof Ember.copy; var create: typeof Ember.create; var debug: typeof Ember.debug; var defineProperty: typeof Ember.defineProperty; var deprecate: typeof Ember.deprecate; - var deprecateFunc: typeof Ember.deprecateFunc; + var deprecateFunc: typeof Ember.deprecateFunc var destroy: typeof Ember.destroy; - var empty: typeof deprecateFunc; + var empty: typeof Ember.empty; var endPropertyChanges: typeof Ember.endPropertyChanges; - var exports: typeof Ember.exports; var finishChains: typeof Ember.finishChains; - var flushPendingChains: typeof Ember.flushPendingChains; var generateController: typeof Ember.generateController; var generateGuid: typeof Ember.generateGuid; var get: typeof Ember.get; - var getMeta: typeof Ember.getMeta; var getPath: typeof Ember.getPath; var getWithDefault: typeof Ember.getWithDefault; var guidFor: typeof Ember.guidFor; @@ -3179,7 +2711,6 @@ declare namespace Em { var hasListeners: typeof Ember.hasListeners; var hasOwnProperty: typeof Ember.hasOwnProperty; var immediateObserver: typeof Ember.immediateObserver; - var imports: typeof Ember.imports; var inspect: typeof Ember.inspect; var instrument: typeof Ember.instrument; var isArray: typeof Ember.isArray; @@ -3198,21 +2729,17 @@ declare namespace Em { var makeArray: typeof Ember.makeArray; var merge: typeof Ember.merge; var meta: typeof Ember.meta; - var metaPath: typeof Ember.metaPath; var mixin: typeof Ember.mixin; var none: typeof Ember.none; - var normalizeTuple: typeof Ember.normalizeTuple; var observer: typeof Ember.observer; var observersFor: typeof Ember.observersFor; var onLoad: typeof Ember.onLoad; - var oneWay: typeof Ember.oneWay; var onError: typeof Ember.onError; var overrideChains: typeof Ember.overrideChains; var platform: typeof Ember.platform; var propertyDidChange: typeof Ember.propertyDidChange; var propertyIsEnumerable: typeof Ember.propertyIsEnumerable; var propertyWillChange: typeof Ember.propertyWillChange; - var removeBeforeObserver: typeof Ember.removeBeforeObserver; var removeChainWatcher: typeof Ember.removeChainWatcher; var removeListener: typeof Ember.removeListener; var removeObserver: typeof Ember.removeObserver; @@ -3222,14 +2749,12 @@ declare namespace Em { var runLoadHooks: typeof Ember.runLoadHooks; var sendEvent: typeof Ember.sendEvent; var set: typeof Ember.set; - var setMeta: typeof Ember.setMeta; var setPath: typeof Ember.setPath; var setProperties: typeof Ember.setProperties; var subscribe: typeof Ember.subscribe; var toLocaleString: typeof Ember.toLocaleString; var toString: typeof Ember.toString; var tryCatchFinally: typeof Ember.tryCatchFinally; - var tryFinally: typeof Ember.tryFinally; var tryInvoke: typeof Ember.tryInvoke; var trySet: typeof Ember.trySet; var trySetPath: typeof Ember.trySetPath; @@ -3245,6 +2770,13 @@ declare namespace Em { var watchPath: typeof Ember.watchPath; var watchedEvents: typeof Ember.watchedEvents; var wrap: typeof Ember.wrap; + var _ContainerProxyMixin : typeof Ember._ContainerProxyMixin; + var _RegistryProxyMixin: typeof Ember._RegistryProxyMixin; + var getOwner: typeof Ember.getOwner; + var setOwner: typeof Ember.setOwner; + var testing: typeof Ember.testing; + var MODEL_FACTORY_INJECTIONS: typeof Ember.MODEL_FACTORY_INJECTIONS; + var assign: typeof Ember.assign; } /** @@ -3252,241 +2784,5 @@ declare namespace Em { */ declare module "Ember" { - - var $: typeof Ember.$; - var A: typeof Ember.A; - class ActionHandlerMixin extends Ember.ActionHandlerMixin { } - class Application extends Ember.Application { } - class Array extends Ember.Array { } - class ArrayController extends Ember.ArrayController { } - var ArrayPolyfills: typeof Ember.ArrayPolyfills; - class ArrayProxy extends Ember.ArrayProxy { } - var BOOTED: typeof Ember.BOOTED; - class Binding extends Ember.Binding { } - class Button extends Ember.Button { } - class Checkbox extends Ember.Checkbox { } - class CollectionView extends Ember.CollectionView { } - class Comparable extends Ember.Comparable { } - class Component extends Ember.Component { } - class ComputedProperty extends Ember.ComputedProperty { } - class Container extends Ember.Container { } - class ContainerView extends Ember.ContainerView { } - class Controller extends Ember.Controller { } - class ControllerMixin extends Ember.ControllerMixin { } - class Copyable extends Ember.Copyable { } - class CoreObject extends Ember.CoreObject { } - class CoreView extends Ember.CoreView { } - class DAG extends Ember.DAG { } - var DEFAULT_GETTER_FUNCTION: typeof Ember.DEFAULT_GETTER_FUNCTION; - class DefaultResolver extends Ember.DefaultResolver { } - class Deffered extends Ember.Deferred { } - class DeferredMixin extends Ember.DeferredMixin { } - class Descriptor extends Ember.Descriptor { } - var EMPTY_META: typeof Ember.EMPTY_META; - var ENV: typeof Ember.ENV; - var EXTEND_PROTOTYPES: typeof Ember.EXTEND_PROTOTYPES; - class EachProxy extends Ember.EachProxy { } - class Enumerable extends Ember.Enumerable { } - var EnumerableUtils: typeof Ember.EnumerableUtils; - var Error: typeof Ember.Error; - class EventDispatcher extends Ember.EventDispatcher { } - class Evented extends Ember.Evented { } - var FROZEN_ERROR: typeof Ember.FROZEN_ERROR; - class Freezable extends Ember.Freezable { } - var GUID_KEY: typeof Ember.GUID_KEY; - namespace Handlebars { - var compile: typeof Ember.Handlebars.compile; - var get: typeof Ember.Handlebars.get; - var helper: typeof Ember.Handlebars.helper; - class helpers extends Ember.Handlebars.helpers { } - var precompile: typeof Ember.Handlebars.precompile; - var registerBoundHelper: typeof Ember.Handlebars.registerBoundHelper; - class Compiler extends Ember.Handlebars.Compiler { } - class JavaScriptCompiler extends Ember.Handlebars.JavaScriptCompiler { } - var registerHelper: typeof Ember.Handlebars.registerHelper; - var registerPartial: typeof Ember.Handlebars.registerPartial; - var K: typeof Ember.Handlebars.K; - var createFrame: typeof Ember.Handlebars.createFrame; - var Exception: typeof Ember.Handlebars.Exception; - class SafeString extends Ember.Handlebars.SafeString { } - var parse: typeof Ember.Handlebars.parse; - var print: typeof Ember.Handlebars.print; - var logger: typeof Ember.Handlebars.logger; - var log: typeof Ember.Handlebars.log; - } - class HashLocation extends Ember.HashLocation { } - class HistoryLocation extends Ember.HistoryLocation { } - var IS_BINDING: typeof Ember.IS_BINDING; - class Instrumentation extends Ember.Instrumentation { } - var K: typeof Ember.K; - var LOG_BINDINGS: typeof Ember.LOG_BINDINGS; - var LOG_STACKTRACE_ON_DEPRECATION: typeof Ember.LOG_STACKTRACE_ON_DEPRECATION; - var LOG_VERSION: typeof Ember.LOG_VERSION; - class LinkView extends Ember.LinkView { } - class Location extends Ember.Location { } - var Logger: typeof Ember.Logger; - var MANDATORY_SETTER_FUNCTION: typeof Ember.MANDATORY_SETTER_FUNCTION; - var META_KEY: typeof Ember.META_KEY; - class Map extends Ember.Map { } - class MapWithDefault extends Ember.MapWithDefault { } - class Mixin extends Ember.Mixin { } - class MutableArray extends Ember.MutableArray { } - class MutableEnumerable extends Ember.MutableEnumberable { } - var NAME_KEY: typeof Ember.NAME_KEY; - class Namespace extends Ember.Namespace { } - class NativeArray extends Ember.NativeArray { } - class NoneLocation extends Ember.NoneLocation { } - var ORDER_DEFINITION: typeof Ember.ORDER_DEFINITION; - class Object extends Ember.Object { } - class ObjectController extends Ember.ObjectController { } - class ObjectProxy extends Ember.ObjectProxy { } - class Observable extends Ember.Observable { } - class OrderedSet extends Ember.OrderedSet { } - namespace RSVP { - interface PromiseResolve extends Ember.RSVP.PromiseResolve { } - interface PromiseReject extends Ember.RSVP.PromiseReject { } - interface PromiseResolverFunction extends Ember.RSVP.PromiseResolverFunction { } - class Promise extends Ember.RSVP.Promise { } - } - class RenderBuffer extends Ember.RenderBuffer { } - class Route extends Ember.Route { } - class Router extends Ember.Router { } - class RouterDSL extends Ember.RouterDSL { } - var SHIM_ES5: typeof Ember.SHIM_ES5; - var STRINGS: typeof Ember.STRINGS; - class Select extends Ember.Select { } - class SelectOption extends Ember.SelectOption { } - class Set extends Ember.Set { } - class SortableMixin extends Ember.SortableMixin { } - class State extends Ember.State { } - class StateManager extends Ember.StateManager { } - namespace String { - var camelize: typeof Ember.String.camelize; - var capitalize: typeof Ember.String.capitalize; - var classify: typeof Ember.String.classify; - var dasherize: typeof Ember.String.dasherize; - var decamelize: typeof Ember.String.decamelize; - var fmt: typeof Ember.String.fmt; - var htmlSafe: typeof Ember.String.htmlSafe; - var loc: typeof Ember.String.loc; - var underscore: typeof Ember.String.underscore; - var w: typeof Ember.String.w; - } - var TEMPLATES: typeof Ember.TEMPLATES; - class TargetActionSupport extends Ember.TargetActionSupport { } - class Test extends Ember.Test { } - class TextArea extends Ember.TextArea { } - class TextField extends Ember.TextField { } - class TextSupport extends Ember.TextSupport { } - var VERSION: typeof Ember.VERSION; - class View extends Ember.View { } - class ViewTargetActionSupport extends Ember.ViewTargetActionSupport { } - var ViewUtils: typeof Ember.ViewUtils; - var addBeforeObserver: typeof Ember.addBeforeObserver; - var addListener: typeof Ember.addListener; - var addObserver: typeof Ember.addObserver; - var alias: typeof Ember.alias; - var aliasMethod: typeof Ember.aliasMethod; - var anyUnprocessedMixins: typeof Ember.anyUnprocessedMixins; - var assert: typeof Ember.assert; - var beforeObserver: typeof Ember.beforeObserver; - var beforeObserversFor: typeof Ember.beforeObserversFor; - var beginPropertyChanges: typeof Ember.beginPropertyChanges; - var bind: typeof Ember.bind; - var cacheFor: typeof Ember.cacheFor; - var canInvoke: typeof Ember.canInvoke; - var changeProperties: typeof Ember.changeProperties; - var compare: typeof Ember.compare; - var computed: typeof Ember.computed; - var config: typeof Ember.config; - var controllerFor: typeof Ember.controllerFor; - var copy: typeof Ember.copy; - var create: typeof Ember.create; - var debug: typeof Ember.debug; - var defineProperty: typeof Ember.defineProperty; - var deprecate: typeof Ember.deprecate; - var deprecateFunc: typeof Ember.deprecateFunc; - var destroy: typeof Ember.destroy; - var empty: typeof Ember.deprecateFunc; - var endPropertyChanges: typeof Ember.endPropertyChanges; - var exports: typeof Ember.exports; - var finishChains: typeof Ember.finishChains; - var flushPendingChains: typeof Ember.flushPendingChains; - var generateController: typeof Ember.generateController; - var generateGuid: typeof Ember.generateGuid; - var get: typeof Ember.get; - var getMeta: typeof Ember.getMeta; - var getPath: typeof Ember.getPath; - var getWithDefault: typeof Ember.getWithDefault; - var guidFor: typeof Ember.guidFor; - var handleErrors: typeof Ember.handleErrors; - var hasListeners: typeof Ember.hasListeners; - var hasOwnProperty: typeof Ember.hasOwnProperty; - var immediateObserver: typeof Ember.immediateObserver; - var imports: typeof Ember.imports; - var inspect: typeof Ember.inspect; - var instrument: typeof Ember.instrument; - var isArray: typeof Ember.isArray; - var isEmpty: typeof Ember.isEmpty; - var isEqual: typeof Ember.isEqual; - var isGlobalPath: typeof Ember.isGlobalPath; - var isNamespace: typeof Ember.isNamespace; - var isNone: typeof Ember.isNone; - var isPrototypeOf: typeof Ember.isPrototypeOf; - var isWatching: typeof Ember.isWatching; - var keys: typeof Ember.keys; - var listenersDiff: typeof Ember.listenersDiff; - var listenersFor: typeof Ember.listenersFor; - var listenersUnion: typeof Ember.listenersUnion; - var lookup: typeof Ember.lookup; - var makeArray: typeof Ember.makeArray; - var merge: typeof Ember.merge; - var meta: typeof Ember.meta; - var metaPath: typeof Ember.metaPath; - var mixin: typeof Ember.mixin; - var none: typeof Ember.none; - var normalizeTuple: typeof Ember.normalizeTuple; - var observer: typeof Ember.observer; - var observersFor: typeof Ember.observersFor; - var onLoad: typeof Ember.onLoad; - var oneWay: typeof Ember.oneWay; - var onError: typeof Ember.onError; - var overrideChains: typeof Ember.overrideChains; - var platform: typeof Ember.platform; - var propertyDidChange: typeof Ember.propertyDidChange; - var propertyIsEnumerable: typeof Ember.propertyIsEnumerable; - var propertyWillChange: typeof Ember.propertyWillChange; - var removeBeforeObserver: typeof Ember.removeBeforeObserver; - var removeChainWatcher: typeof Ember.removeChainWatcher; - var removeListener: typeof Ember.removeListener; - var removeObserver: typeof Ember.removeObserver; - var required: typeof Ember.required; - var rewatch: typeof Ember.rewatch; - var run: typeof Ember.run; - var runLoadHooks: typeof Ember.runLoadHooks; - var sendEvent: typeof Ember.sendEvent; - var set: typeof Ember.set; - var setMeta: typeof Ember.setMeta; - var setPath: typeof Ember.setPath; - var setProperties: typeof Ember.setProperties; - var subscribe: typeof Ember.subscribe; - var toLocaleString: typeof Ember.toLocaleString; - var toString: typeof Ember.toString; - var tryCatchFinally: typeof Ember.tryCatchFinally; - var tryFinally: typeof Ember.tryFinally; - var tryInvoke: typeof Ember.tryInvoke; - var trySet: typeof Ember.trySet; - var trySetPath: typeof Ember.trySetPath; - var typeOf: typeof Ember.typeOf; - var unwatch: typeof Ember.unwatch; - var unwatchKey: typeof Ember.unwatchKey; - var unwatchPath: typeof Ember.unwatchPath; - var uuid: typeof Ember.uuid; - var valueOf: typeof Ember.valueOf; - var warn: typeof Ember.warn; - var watch: typeof Ember.watch; - var watchKey: typeof Ember.watchKey; - var watchPath: typeof Ember.watchPath; - var watchedEvents: typeof Ember.watchedEvents; - var wrap: typeof Ember.wrap; + export = Ember; } diff --git a/enzyme/enzyme-tests.tsx b/enzyme/enzyme-tests.tsx index 805201e53a..67dccafeaf 100644 --- a/enzyme/enzyme-tests.tsx +++ b/enzyme/enzyme-tests.tsx @@ -44,11 +44,21 @@ namespace ShallowWrapperTest { stringVal: String, elementWrapper: ShallowWrapper + function test_shallow_options() { + shallow(, { + context: { + test: "a", + }, + lifecycleExperimental: true + }); + } + function test_find() { elementWrapper = shallowWrapper.find('.selector'); shallowWrapper = shallowWrapper.find(MyComponent); shallowWrapper.find(MyStatelessComponent).props().stateless; shallowWrapper.find(MyStatelessComponent).shallow(); + shallowWrapper.find({ prop: 'value' }); } function test_findWhere() { @@ -59,6 +69,7 @@ namespace ShallowWrapperTest { function test_filter() { elementWrapper = shallowWrapper.filter('.selector'); shallowWrapper = shallowWrapper.filter(MyComponent).shallow(); + shallowWrapper.filter({ prop: 'val' }); } function test_filterWhere() { @@ -108,6 +119,7 @@ namespace ShallowWrapperTest { function test_children() { shallowWrapper = shallowWrapper.children(); shallowWrapper.children(MyStatelessComponent).props().stateless; + shallowWrapper.children({ prop: 'myprop' }); } function test_childAt() { @@ -135,6 +147,7 @@ namespace ShallowWrapperTest { function test_closest() { elementWrapper = shallowWrapper.closest('.selector'); shallowWrapper = shallowWrapper.closest(MyComponent); + shallowWrapper = shallowWrapper.closest({ prop: 'myprop' }); } function test_shallow() { @@ -277,6 +290,10 @@ namespace ShallowWrapperTest { function test_everyWhere() { boolVal = shallowWrapper.everyWhere((aShallowWrapper: ShallowWrapper) => true); } + + function test_isEmptyRender() { + boolVal = shallowWrapper.isEmptyRender(); + } } @@ -297,30 +314,38 @@ namespace ReactWrapperTest { function test_mount() { reactWrapper = reactWrapper.mount(); + + mount(, { + attachTo: document.getElementById('test'), + context: { + a: "b" + } + }); } function test_ref() { reactWrapper = reactWrapper.ref('refName'); - + interface TmpType1 { foo: string } - + interface TmpType2 { bar: string } - + const tmp: ReactWrapper = reactWrapper.ref('refName'); } - + function test_detach() { reactWrapper.detach(); } - + function test_find() { elementWrapper = reactWrapper.find('.selector'); reactWrapper = reactWrapper.find(MyComponent); reactWrapper.find(MyStatelessComponent).props().stateless; + reactWrapper.find({ prop: 'myprop' }); } function test_findWhere() { @@ -331,6 +356,7 @@ namespace ReactWrapperTest { function test_filter() { elementWrapper = reactWrapper.filter('.selector'); reactWrapper = reactWrapper.filter(MyComponent); + reactWrapper = reactWrapper.filter({ prop: 'myprop' }); } function test_filterWhere() { @@ -406,6 +432,7 @@ namespace ReactWrapperTest { function test_closest() { elementWrapper = reactWrapper.closest('.selector'); reactWrapper = reactWrapper.closest(MyComponent); + reactWrapper = reactWrapper.closest({ prop: 'myprop' }); } function test_text() { @@ -535,6 +562,9 @@ namespace ReactWrapperTest { function test_everyWhere() { boolVal = reactWrapper.everyWhere((aReactWrapper: ReactWrapper) => true); } + function test_isEmptyRender() { + boolVal = reactWrapper.isEmptyRender(); + } } // CheerioWrapper @@ -552,6 +582,7 @@ namespace CheerioWrapperTest { elementWrapper = cheerioWrapper.find('.selector'); cheerioWrapper = cheerioWrapper.find(MyComponent); cheerioWrapper.find(MyStatelessComponent).props().stateless; + cheerioWrapper.find({ prop: 'myprop' }); } function test_findWhere() { @@ -562,6 +593,7 @@ namespace CheerioWrapperTest { function test_filter() { elementWrapper = cheerioWrapper.filter('.selector'); cheerioWrapper = cheerioWrapper.filter(MyComponent); + cheerioWrapper = cheerioWrapper.filter({ prop: 'myprop' }); } function test_filterWhere() { @@ -637,6 +669,7 @@ namespace CheerioWrapperTest { function test_closest() { elementWrapper = cheerioWrapper.closest('.selector'); cheerioWrapper = cheerioWrapper.closest(MyComponent); + cheerioWrapper = cheerioWrapper.closest({ prop: 'myprop' }); } function test_text() { diff --git a/enzyme/enzyme.d.ts b/enzyme/enzyme.d.ts index 2698fd366b..31ffce8923 100644 --- a/enzyme/enzyme.d.ts +++ b/enzyme/enzyme.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Enzyme v2.3.0 +// Type definitions for Enzyme v2.4.1 // Project: https://github.com/airbnb/enzyme // Definitions by: Marian Palkus , Cap3 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -19,8 +19,11 @@ declare module "enzyme" { * 1. A Valid CSS Selector * 2. A React Component Constructor * 3. A React Component's displayName + * 4. A React Stateless component + * 5. A React component property map */ - export type EnzymeSelector = String | typeof ElementClass; + export type EnzymeSelector = string | StatelessComponent | ComponentClass | {[key: string]: any}; + export type EnzymePropSelector = { [key: string]: any }; interface CommonWrapper { /** @@ -29,13 +32,14 @@ declare module "enzyme" { */ find(component: ComponentClass): CommonWrapper; find(statelessComponent: StatelessComponent): CommonWrapper; + find(props: EnzymePropSelector): CommonWrapper; find(selector: string): CommonWrapper; /** * Finds every node in the render tree that returns true for the provided predicate function. * @param predicate */ - findWhere(predicate: (wrapper: CommonWrapper) => Boolean): CommonWrapper; + findWhere(predicate: (wrapper: CommonWrapper) => boolean): CommonWrapper; /** * Removes nodes in the current wrapper that do not match the provided selector. @@ -43,59 +47,60 @@ declare module "enzyme" { */ filter(component: ComponentClass): CommonWrapper; filter(statelessComponent: StatelessComponent): CommonWrapper; + filter(props: EnzymePropSelector): CommonWrapper; filter(selector: string): CommonWrapper; /** * Returns a new wrapper with only the nodes of the current wrapper that, when passed into the provided predicate function, return true. * @param predicate */ - filterWhere(predicate: (wrapper: this) => Boolean): this; + filterWhere(predicate: (wrapper: this) => boolean): this; /** * Returns whether or not the current wrapper has a node anywhere in it's render tree that looks like the one passed in. * @param node */ - contains(node: ReactElement): Boolean; + contains(node: ReactElement): boolean; /** * Returns whether or not a given react element exists in the shallow render tree. * @param node */ - containsMatchingElement(node: ReactElement): Boolean; + containsMatchingElement(node: ReactElement): boolean; /** * Returns whether or not all the given react elements exists in the shallow render tree * @param nodes */ - containsAllMatchingElements(nodes: ReactElement[]): Boolean; + containsAllMatchingElements(nodes: ReactElement[]): boolean; /** * Returns whether or not one of the given react elements exists in the shallow render tree. * @param nodes */ - containsAnyMatchingElements(nodes: ReactElement[]): Boolean; + containsAnyMatchingElements(nodes: ReactElement[]): boolean; /** * Returns whether or not the current render tree is equal to the given node, based on the expected value. */ - equals(node: ReactElement): Boolean; + equals(node: ReactElement): boolean; /** * Returns whether or not a given react element matches the shallow render tree. */ - matchesElement(node: ReactElement): Boolean; + matchesElement(node: ReactElement): boolean; /** * Returns whether or not the current node has a className prop including the passed in class name. * @param className */ - hasClass(className: String): Boolean; + hasClass(className: string): boolean; /** * Returns whether or not the current node matches a provided selector. * @param selector */ - is(selector: EnzymeSelector): Boolean; + is(selector: EnzymeSelector): boolean; /** * Returns a new wrapper with only the nodes of the current wrapper that don't match the provided selector. @@ -111,6 +116,7 @@ declare module "enzyme" { */ children(component: ComponentClass): CommonWrapper; children(statelessComponent: StatelessComponent): CommonWrapper; + children(props: EnzymePropSelector): CommonWrapper; children(selector: string): CommonWrapper; children(): CommonWrapper; @@ -118,8 +124,8 @@ declare module "enzyme" { * Returns a new wrapper with child at the specified index. * @param index */ - childAt(index: Number): CommonWrapper; - childAt(index: Number): CommonWrapper; + childAt(index: number): CommonWrapper; + childAt(index: number): CommonWrapper; /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the @@ -130,6 +136,7 @@ declare module "enzyme" { */ parents(component: ComponentClass): CommonWrapper; parents(statelessComponent: StatelessComponent): CommonWrapper; + parents(props: EnzymePropSelector): CommonWrapper; parents(selector: string): CommonWrapper; parents(): CommonWrapper; @@ -147,6 +154,7 @@ declare module "enzyme" { */ closest(component: ComponentClass): CommonWrapper; closest(statelessComponent: StatelessComponent): CommonWrapper; + closest(props: EnzymePropSelector): CommonWrapper; closest(selector: string): CommonWrapper; /** @@ -156,14 +164,14 @@ declare module "enzyme" { * * Note: can only be called on a wrapper of a single node. */ - text(): String; + text(): string; /** * Returns a string of the rendered HTML markup of the current render tree. * * Note: can only be called on a wrapper of a single node. */ - html(): String; + html(): string; /** * Returns the node at a given index of the current wrapper. @@ -191,14 +199,14 @@ declare module "enzyme" { * Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. * @param [key] */ - state(key?: String): any; - state(key?: String): T; + state(key?: string): any; + state(key?: string): T; /** * Returns the context hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. */ - context(key?: String): any; - context(key?: String): T; + context(key?: string): any; + context(key?: string): T; /** * Returns the props hash for the current node of the wrapper. @@ -213,14 +221,14 @@ declare module "enzyme" { * NOTE: can only be called on a wrapper of a single node. * @param key */ - prop(key: String): any; - prop(key: String): T; + prop(key: string): any; + prop(key: string): T; /** * Returns the key value for the node of the current wrapper. * NOTE: can only be called on a wrapper of a single node. */ - key(): String; + key(): string; /** * Simulate events. @@ -286,7 +294,7 @@ declare module "enzyme" { * Returns an html-like string of the wrapper for debugging purposes. Useful to print out to the console when * tests are not passing when you expect them to. */ - debug(): String; + debug(): string; /** * Returns the type of the current node of this wrapper. If it's a composite component, this will be the @@ -294,12 +302,12 @@ declare module "enzyme" { * * Note: can only be called on a wrapper of a single node. */ - type(): String | Function; + type(): string | Function; /** * Returns the name of the current node of the wrapper. */ - name(): String; + name(): string; /** * Iterates through each node of the current wrapper and executes the provided function with a wrapper around @@ -341,25 +349,25 @@ declare module "enzyme" { * Returns whether or not any of the nodes in the wrapper match the provided selector. * @param selector */ - some(selector: EnzymeSelector): Boolean; + some(selector: EnzymeSelector): boolean; /** * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. * @param fn */ - someWhere(fn: (wrapper: this) => Boolean): Boolean; + someWhere(fn: (wrapper: this) => boolean): boolean; /** * Returns whether or not all of the nodes in the wrapper match the provided selector. * @param selector */ - every(selector: EnzymeSelector): Boolean; + every(selector: EnzymeSelector): boolean; /** * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. * @param fn */ - everyWhere(fn: (wrapper: this) => Boolean): Boolean; + everyWhere(fn: (wrapper: this) => boolean): boolean; length: number; } @@ -375,6 +383,7 @@ declare module "enzyme" { */ find(component: ComponentClass): ShallowWrapper; find(statelessComponent: (props: P2) => JSX.Element): ShallowWrapper; + find(props: EnzymePropSelector): ShallowWrapper; find(selector: string): ShallowWrapper; /** @@ -383,13 +392,14 @@ declare module "enzyme" { */ filter(component: ComponentClass): ShallowWrapper; filter(statelessComponent: StatelessComponent): ShallowWrapper; + filter(props: EnzymePropSelector): ShallowWrapper; filter(selector: string): ShallowWrapper; /** * Finds every node in the render tree that returns true for the provided predicate function. * @param predicate */ - findWhere(predicate: (wrapper: CommonWrapper) => Boolean): ShallowWrapper; + findWhere(predicate: (wrapper: CommonWrapper) => boolean): ShallowWrapper; /** * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector @@ -398,6 +408,7 @@ declare module "enzyme" { */ children(component: ComponentClass): ShallowWrapper; children(statelessComponent: StatelessComponent): ShallowWrapper; + children(props: EnzymePropSelector): ShallowWrapper; children(selector: string): ShallowWrapper; children(): ShallowWrapper; @@ -405,8 +416,8 @@ declare module "enzyme" { * Returns a new wrapper with child at the specified index. * @param index */ - childAt(index: Number): ShallowWrapper; - childAt(index: Number): ShallowWrapper; + childAt(index: number): ShallowWrapper; + childAt(index: number): ShallowWrapper; /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the @@ -417,6 +428,7 @@ declare module "enzyme" { */ parents(component: ComponentClass): ShallowWrapper; parents(statelessComponent: StatelessComponent): ShallowWrapper; + parents(props: EnzymePropSelector): ShallowWrapper; parents(selector: string): ShallowWrapper; parents(): ShallowWrapper; @@ -429,33 +441,40 @@ declare module "enzyme" { */ closest(component: ComponentClass): ShallowWrapper; closest(statelessComponent: StatelessComponent): ShallowWrapper; + closest(props: EnzymePropSelector): ShallowWrapper; closest(selector: string): ShallowWrapper; /** * Returns a wrapper with the direct parent of the node in the current wrapper. */ parent(): ShallowWrapper; + + /** + * Returns true if renderer returned null + */ + isEmptyRender(): boolean; } export interface ReactWrapper extends CommonWrapper { unmount(): ReactWrapper; mount(): ReactWrapper; + render(): CheerioWrapper; /** * Returns a wrapper of the node that matches the provided reference name. - * + * * NOTE: can only be called on a wrapper instance that is also the root instance. */ - ref(refName: String): ReactWrapper; - ref(refName: String): ReactWrapper; + ref(refName: string): ReactWrapper; + ref(refName: string): ReactWrapper; /** * Detaches the react tree from the DOM. Runs ReactDOM.unmountComponentAtNode() under the hood. - * + * * This method will most commonly be used as a "cleanup" method if you decide to use the attachTo option in mount(node, options). - * + * * The method is intentionally not "fluent" (in that it doesn't return this) because you should not be doing anything with this wrapper after this method is called. - * + * * Using the attachTo is not generally recommended unless it is absolutely necessary to test something. It is your responsibility to clean up after yourself at the end of the test if you do decide to use it, though. */ detach() : void; @@ -466,13 +485,14 @@ declare module "enzyme" { */ find(component: ComponentClass): ReactWrapper; find(statelessComponent: (props: P2) => JSX.Element): ReactWrapper; + find(props: EnzymePropSelector): ReactWrapper; find(selector: string): ReactWrapper; /** * Finds every node in the render tree that returns true for the provided predicate function. * @param predicate */ - findWhere(predicate: (wrapper: CommonWrapper) => Boolean): ReactWrapper; + findWhere(predicate: (wrapper: CommonWrapper) => boolean): ReactWrapper; /** * Removes nodes in the current wrapper that do not match the provided selector. @@ -480,6 +500,7 @@ declare module "enzyme" { */ filter(component: ComponentClass): ReactWrapper; filter(statelessComponent: StatelessComponent): ReactWrapper; + filter(props: EnzymePropSelector): ReactWrapper; filter(selector: string): ReactWrapper; /** @@ -489,6 +510,7 @@ declare module "enzyme" { */ children(component: ComponentClass): ReactWrapper; children(statelessComponent: StatelessComponent): ReactWrapper; + children(props: EnzymePropSelector): ReactWrapper; children(selector: string): ReactWrapper; children(): ReactWrapper; @@ -496,8 +518,8 @@ declare module "enzyme" { * Returns a new wrapper with child at the specified index. * @param index */ - childAt(index: Number): ReactWrapper; - childAt(index: Number): ReactWrapper; + childAt(index: number): ReactWrapper; + childAt(index: number): ReactWrapper; /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the @@ -508,6 +530,7 @@ declare module "enzyme" { */ parents(component: ComponentClass): ReactWrapper; parents(statelessComponent: StatelessComponent): ReactWrapper; + parents(props: EnzymePropSelector): ReactWrapper; parents(selector: string): ReactWrapper; parents(): ReactWrapper; @@ -520,32 +543,64 @@ declare module "enzyme" { */ closest(component: ComponentClass): ReactWrapper; closest(statelessComponent: StatelessComponent): ReactWrapper; + closest(props: EnzymePropSelector): ReactWrapper; closest(selector: string): ReactWrapper; /** * Returns a wrapper with the direct parent of the node in the current wrapper. */ parent(): ReactWrapper; + + /** + * Returns true if renderer returned null + */ + isEmptyRender(): boolean; } export interface CheerioWrapper extends CommonWrapper { } + export interface ShallowRendererProps { + /** + * Enable experimental support for full react lifecycle methods + */ + lifecycleExperimental?: boolean; + /** + * Context to be passed into the component + */ + context?: {}; + } + + export interface MountRendererProps { + /** + * Context to be passed into the component + */ + context?: {}; + /** + * DOM Element to attach the component to + */ + attachTo?: HTMLElement; + /** + * Merged contextTypes for all children of the wrapper + */ + childContextTypes?: {}; + } + /** * Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that * your tests aren't indirectly asserting on behavior of child components. * @param node * @param [options] */ - export function shallow(node: ReactElement

      , options?: any): ShallowWrapper; + export function shallow(node: ReactElement

      , options?: ShallowRendererProps): ShallowWrapper; /** * Mounts and renders a react component into the document and provides a testing wrapper around it. * @param node * @param [options] */ - export function mount(node: ReactElement

      , options?: any): ReactWrapper; + export function mount(node: ReactElement

      , options?: MountRendererProps): ReactWrapper; /** * Render react components to static HTML and analyze the resulting HTML structure. @@ -554,7 +609,7 @@ declare module "enzyme" { */ export function render(node: ReactElement

      , options?: any): CheerioWrapper; - export function describeWithDOM(description: String, fn: Function): void; + export function describeWithDOM(description: string, fn: Function): void; export function spyLifecycle(component: typeof Component): void; -} \ No newline at end of file +} diff --git a/epub/epub-tests.ts b/epub/epub-tests.ts new file mode 100644 index 0000000000..6e61a26634 --- /dev/null +++ b/epub/epub-tests.ts @@ -0,0 +1,9 @@ +/// +import EPub = require("epub"); + +var epub = new EPub("./file.epub"); +epub.on("end", function(){ + epub.getChapter("chapter_id", function(err: Error, text: string) {}); +}); + +epub.parse(); diff --git a/epub/epub.d.ts b/epub/epub.d.ts new file mode 100644 index 0000000000..7c813e003d --- /dev/null +++ b/epub/epub.d.ts @@ -0,0 +1,66 @@ +// Type definitions for epub +// Project: https://github.com/julien-c/epub +// Definitions by: Julien Chaumond +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** + * new EPub(fname[, imageroot][, linkroot]) + * - fname (String): filename for the ebook + * - imageroot (String): URL prefix for images + * - linkroot (String): URL prefix for links + * + * Creates an Event Emitter type object for parsing epub files + * + * var epub = new EPub("book.epub"); + * epub.on("end", function () { + * console.log(epub.spine); + * }); + * epub.on("error", function (error) { ... }); + * epub.parse(); + * + * Image and link URL format is: + * + * imageroot + img_id + img_zip_path + * + * So an image "logo.jpg" which resides in "OPT/" in the zip archive + * and is listed in the manifest with id "logo_img" will have the + * following url (providing that imageroot is "/images/"): + * + * /images/logo_img/OPT/logo.jpg + **/ +declare module "epub" { + + import {EventEmitter} from "events"; + + interface TocElement { + level: number; + order: number; + title: string; + id: string; + href?: string; + } + + class EPub extends EventEmitter { + constructor(epubfile: string, imagewebroot?: string, chapterwebroot?: string); + + metadata: Object; + manifest: Object; + spine: Object; + flow: Array; + toc: Array; + + parse(): void; + + getChapter(chapterId: string, callback: (error: Error, text: string) => void): void; + + getChapterRaw(chapterId: string, callback: (error: Error, text: string) => void): void; + + getImage(id: string, callback: (error: Error, data: Buffer, mimeType: string) => void): void; + + getFile(id: string, callback: (error: Error, data: Buffer, mimeType: string) => void): void; + } + + export = EPub; +} diff --git a/esprima-walk/esprima-walk-tests.ts b/esprima-walk/esprima-walk-tests.ts new file mode 100644 index 0000000000..4588ebb615 --- /dev/null +++ b/esprima-walk/esprima-walk-tests.ts @@ -0,0 +1,25 @@ +/// +/// + +import * as walk from 'esprima-walk' + +var program: ESTree.Program +var string: string +var node: ESTree.Node + +walk(program, _node => { + string = node.type + node = _node +}) + +walk.walk(program, _node => { + string = node.type + node = _node +}) + +walk.walkAddParent(program, _node => { + node = _node + node = _node.parent + string = node.type +}) + diff --git a/esprima-walk/esprima-walk.d.ts b/esprima-walk/esprima-walk.d.ts new file mode 100644 index 0000000000..d18cf96bb1 --- /dev/null +++ b/esprima-walk/esprima-walk.d.ts @@ -0,0 +1,40 @@ +// Type definitions for esprima-walk v0.1.0 +// Project: https://github.com/jrajav/esprima-walk +// Definitions by: tswaters +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "esprima-walk" { + + interface NodeWithParent extends ESTree.Node { + parent?: ESTree.Node + } + + /** + * Walk the provided AST; fn is called once for each node with a `type` + * @param {ESTree.Program} ast program to walk + * @param {function} fn function invoked for each node with type + */ + function walk (ast: ESTree.Program, fn:(node: ESTree.Node)=>void) :void + + namespace walk { + /** + * Walk the provided AST; fn is called once for each node with a `type` + * @param {ESTree.Program} ast program to walk + * @param {function} fn function invoked for each node + */ + export function walk (ast: ESTree.Program, fn:(node: ESTree.Node)=>void) :void + + /** + * Walk the provided AST; fn is called once for each node with a `type`. + * Adds a parent property prior to invoking fn when applicable + * @param {ESTree.Program} ast program to walk + * @param {function} fn function invoked for each node + */ + export function walkAddParent (ast: ESTree.Program, fn:(node: NodeWithParent)=>void) :void + } + + export = walk +} + diff --git a/esprima/esprima-tests.ts b/esprima/esprima-tests.ts index f1a0f7ad92..2bca0d5e54 100644 --- a/esprima/esprima-tests.ts +++ b/esprima/esprima-tests.ts @@ -12,6 +12,7 @@ var string: string; string = esprima.version; program = esprima.parse('code'); program = esprima.parse('code', {range: true}); +program = esprima.parse('import * as code from "code"', {sourceType: 'module'}) token = esprima.tokenize('code')[0]; token = esprima.tokenize('code', {range: true})[0]; diff --git a/esprima/esprima.d.ts b/esprima/esprima.d.ts index 30fe9512bf..64a9333fa3 100644 --- a/esprima/esprima.d.ts +++ b/esprima/esprima.d.ts @@ -30,6 +30,7 @@ declare namespace esprima { attachComment?: boolean; tolerant?: boolean; source?: boolean; + sourceType?: 'script' | 'module'; } const Syntax: { diff --git a/eventemitter2/eventemitter2.d.ts b/eventemitter2/eventemitter2.d.ts index 39a349c6b6..de1be0d064 100644 --- a/eventemitter2/eventemitter2.d.ts +++ b/eventemitter2/eventemitter2.d.ts @@ -43,7 +43,7 @@ declare class EventEmitter2 { * @param event * @param listener */ - on(event: string, listener: Function): EventEmitter2; + on(event: string | string[], listener: Function): EventEmitter2; /** * Adds a listener that will be fired when any event is emitted. @@ -128,7 +128,7 @@ declare class EventEmitter2 { * @param event * @param args */ - emit(event: string, ...args: any[]): boolean; + emit(event: string | string[], ...args: any[]): boolean; /** * Execute each of the listeners that may be listening for the specified event name in order with the list of arguments. @@ -156,7 +156,7 @@ declare module "eventemitter2" { * @param event * @param listener */ - on(event: string, listener: Function): EventEmitter2; + on(event: string | string[], listener: Function): EventEmitter2; /** * Adds a listener that will be fired when any event is emitted. @@ -241,7 +241,7 @@ declare module "eventemitter2" { * @param event * @param args */ - emit(event: string, ...args: any[]): boolean; + emit(event: string | string[], ...args: any[]): boolean; /** * Execute each of the listeners that may be listening for the specified event name in order with the list of arguments. diff --git a/express-brute/express-brute.d.ts b/express-brute/express-brute.d.ts index 37df68af64..c194f5b69a 100644 --- a/express-brute/express-brute.d.ts +++ b/express-brute/express-brute.d.ts @@ -49,15 +49,15 @@ declare module "express-brute" { * @interface */ interface ExpressBruteOptions { - freeRetries: number; - proxyDepth: number; - attachResetToRequest: boolean; - refreshTimeoutOnRequest: boolean; - minWait: number; - maxWait: number; - lifetime: number; - failCallback: (req: express.Request, res: express.Response, next: Function, nextValidRequestDate: any) => void; - handleStoreError: any; + freeRetries?: number; + proxyDepth?: number; + attachResetToRequest?: boolean; + refreshTimeoutOnRequest?: boolean; + minWait?: number; + maxWait?: number; + lifetime?: number; + failCallback?: (req: express.Request, res: express.Response, next: Function, nextValidRequestDate: any) => void; + handleStoreError?: any; } /** @@ -70,7 +70,7 @@ class ExpressBrute { * @constructor * @param {any} store The store. */ - constructor(store: any); + constructor(store: any, options?: ExpressBruteOptions); /** * @summary Generates middleware that will bounce requests with the same key and IP address that happen faster than the current wait time by calling failCallback. diff --git a/express-jwt/express-jwt.d.ts b/express-jwt/express-jwt.d.ts index 1aec6606fe..dadf833f67 100644 --- a/express-jwt/express-jwt.d.ts +++ b/express-jwt/express-jwt.d.ts @@ -12,21 +12,30 @@ declare module "express-jwt" { function jwt(options: jwt.Options): jwt.RequestHandler; - interface IDoneCallback { - (err: Error, result: T): void; - } - - type ICallback = (req: express.Request, payload: T, done: IDoneCallback) => void; - namespace jwt { + + export type secretType = string | Buffer + export interface SecretCallback { + (req: express.Request, header:any, payload: any, done: (err: any, secret?: boolean) => void): void; + (req: express.Request, payload: any, done: (err: any, secret?: secretType) => void):void; + } + + export interface IsRevokedCallback { + (req: express.Request, payload: any, done: (err: any, revoked?: boolean) => void): void; + } + + export interface GetTokenCallback { + (req: express.Request): any; + } + export interface Options { - secret: string|Buffer|ICallback; + secret: secretType|SecretCallback; userProperty?: string; skip?: string[]; credentialsRequired?: boolean; - isRevoked?: boolean; + isRevoked?: IsRevokedCallback; requestProperty?: string; - getToken?: ICallback; + getToken?: GetTokenCallback; [property: string]: any; } export interface RequestHandler extends express.RequestHandler { @@ -34,4 +43,4 @@ declare module "express-jwt" { } } export = jwt; -} +} \ No newline at end of file diff --git a/express-serve-static-core/express-serve-static-core.d.ts b/express-serve-static-core/express-serve-static-core.d.ts index 0b7ee8126e..e80ffa85a9 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Express 4.x +// Type definitions for Express 4.x // Project: http://expressjs.com // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -17,26 +17,33 @@ declare namespace Express { declare module "express-serve-static-core" { import * as http from "http"; - type RequestHandlerParams = RequestHandler | RequestHandler[]; - - interface IRoute { - path: string; - stack: any; - all(...handler: RequestHandlerParams[]): IRoute; - get(...handler: RequestHandlerParams[]): IRoute; - post(...handler: RequestHandlerParams[]): IRoute; - put(...handler: RequestHandlerParams[]): IRoute; - delete(...handler: RequestHandlerParams[]): IRoute; - patch(...handler: RequestHandlerParams[]): IRoute; - options(...handler: RequestHandlerParams[]): IRoute; - head(...handler: RequestHandlerParams[]): IRoute; + interface NextFunction { + (err?: any): void; } + interface RequestHandler { + (req: Request, res: Response, next?: NextFunction): any; + } + + interface ErrorRequestHandler { + (err: any, req: Request, res: Response, next: NextFunction): any; + } + + type PathParams = string | RegExp | (string | RegExp)[]; + + type RequestHandlerParams = RequestHandler | ErrorRequestHandler | (RequestHandler | ErrorRequestHandler)[]; + interface IRouterMatcher { - (name: string | RegExp, ...handlers: RequestHandlerParams[]): T; + (path: PathParams, ...handlers: RequestHandler[]): T; + (path: PathParams, ...handlers: RequestHandlerParams[]): T; } - interface IRouter extends RequestHandler { + interface IRouterHandler { + (...handlers: RequestHandler[]): T; + (...handlers: RequestHandlerParams[]): T; + } + + interface IRouter extends RequestHandler { /** * Map the given param placeholder `name`(s) to the given callback(s). * @@ -66,11 +73,10 @@ declare module "express-serve-static-core" { * @param name * @param fn */ - param(name: string, handler: RequestParamHandler): T; - param(name: string, matcher: RegExp): T; - param(name: string, mapper: (param: any) => any): T; + param(name: string, handler: RequestParamHandler): this; // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API - param(callback: (name: string, matcher: RegExp) => RequestParamHandler): T; + // deprecated since express 4.11.0 + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; /** * Special-cased "all" method, applying the given route `path`, @@ -79,39 +85,43 @@ declare module "express-serve-static-core" { * @param path * @param fn */ - all: IRouterMatcher; - get: IRouterMatcher; - post: IRouterMatcher; - put: IRouterMatcher; - delete: IRouterMatcher; - patch: IRouterMatcher; - options: IRouterMatcher; - head: IRouterMatcher; + all: IRouterMatcher; + get: IRouterMatcher; + post: IRouterMatcher; + put: IRouterMatcher; + delete: IRouterMatcher; + patch: IRouterMatcher; + options: IRouterMatcher; + head: IRouterMatcher; - route(path: string | RegExp): IRoute; + use: IRouterHandler & IRouterMatcher; - use(...handler: RequestHandlerParams[]): T; - use(handler: ErrorRequestHandler | RequestHandlerParams): T; - use(path: string, ...handler: RequestHandlerParams[]): T; - use(path: string, handler: ErrorRequestHandler | RequestHandlerParams): T; - use(path: string[], ...handler: RequestHandlerParams[]): T; - use(path: string[], handler: ErrorRequestHandler): T; - use(path: RegExp, ...handler: RequestHandlerParams[]): T; - use(path: RegExp, handler: ErrorRequestHandler): T; - use(path: string, router: Router): T; + route(prefix: PathParams): IRoute; } + interface IRoute { + path: string; + stack: any; + all: IRouterHandler; + get: IRouterHandler; + post: IRouterHandler; + put: IRouterHandler; + delete: IRouterHandler; + patch: IRouterHandler; + options: IRouterHandler; + head: IRouterHandler; + } - export interface Router extends IRouter { } + export interface Router extends IRouter { } interface CookieOptions { maxAge?: number; signed?: boolean; - expires?: Date; + expires?: Date | boolean; httpOnly?: boolean; path?: string; domain?: string; - secure?: boolean; + secure?: boolean | 'auto'; } interface Errback { (err: Error): void; } @@ -182,40 +192,50 @@ declare module "express-serve-static-core" { * req.accepts('html, json'); * // => "json" */ - accepts(type: string): string; - - accepts(type: string[]): string; + accepts(): string[]; + accepts(type: string): string | boolean; + accepts(type: string[]): string | boolean; + accepts(...type: string[]): string | boolean; /** * Returns the first accepted charset of the specified character sets, - * based on the request’s Accept-Charset HTTP header field. + * based on the request's Accept-Charset HTTP header field. * If none of the specified charsets is accepted, returns false. * * For more information, or if you have issues or concerns, see accepts. * @param charset */ - acceptsCharsets(charset?: string | string[]): string[]; + acceptsCharsets(): string[]; + acceptsCharsets(charset: string): string | boolean; + acceptsCharsets(charset: string[]): string | boolean; + acceptsCharsets(...charset: string[]): string | boolean; /** * Returns the first accepted encoding of the specified encodings, - * based on the request’s Accept-Encoding HTTP header field. + * based on the request's Accept-Encoding HTTP header field. * If none of the specified encodings is accepted, returns false. * * For more information, or if you have issues or concerns, see accepts. * @param encoding */ - acceptsEncodings(encoding?: string | string[]): string[]; + acceptsEncodings(): string[]; + acceptsEncodings(encoding: string): string | boolean; + acceptsEncodings(encoding: string[]): string | boolean; + acceptsEncodings(...encoding: string[]): string | boolean; /** * Returns the first accepted language of the specified languages, - * based on the request’s Accept-Language HTTP header field. + * based on the request's Accept-Language HTTP header field. * If none of the specified languages is accepted, returns false. * * For more information, or if you have issues or concerns, see accepts. * * @param lang */ - acceptsLanguages(lang?: string | string[]): string[]; + acceptsLanguages(): string[]; + acceptsLanguages(lang: string): string | boolean; + acceptsLanguages(lang: string[]): string | boolean; + acceptsLanguages(...lang: string[]): string | boolean; /** * Parse Range header field, @@ -243,6 +263,8 @@ declare module "express-serve-static-core" { accepted: MediaType[]; /** + * @deprecated Use either req.params, req.body or req.query, as applicable. + * * Return the value of param `name` when present or `defaultValue`. * * - Checks route placeholders, ex: _/user/:id_ @@ -374,10 +396,6 @@ declare module "express-serve-static-core" { params: any; - user: any; - - authenticatedUser: any; - /** * Clear cookie `name`. * @@ -782,24 +800,24 @@ declare module "express-serve-static-core" { locals: any; charset: string; - } - interface NextFunction { - (err?: any): void; + /** + * Adds the field to the Vary response header, if it is not there already. + * Examples: + * + * res.vary('User-Agent').render('docs'); + * + */ + vary(field: string): Response; } - interface ErrorRequestHandler { - (err: any, req: Request, res: Response, next: NextFunction): any; - } - - interface Handler extends RequestHandler { } interface RequestParamHandler { - (req: Request, res: Response, next: NextFunction, param: any): any; + (req: Request, res: Response, next: NextFunction, value: any, name: string): any; } - interface Application extends IRouter, Express.Application { + interface Application extends IRouter, Express.Application { /** * Initialize the server. * @@ -860,10 +878,11 @@ declare module "express-serve-static-core" { * @param val */ set(setting: string, val: any): Application; - get: { - (name: string): any; // Getter - (name: string | RegExp, ...handlers: RequestHandlerParams[]): Application; - }; + get: {(name: string): any;} & IRouterMatcher; + + param(name: string | string[], handler: RequestParamHandler): this; + // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; /** * Return the app's absolute pathname @@ -1008,8 +1027,6 @@ declare module "express-serve-static-core" { listen(path: string, callback?: Function): http.Server; listen(handle: any, listeningListener?: Function): http.Server; - route(path: string | RegExp): IRoute; - router: string; settings: any; @@ -1029,6 +1046,11 @@ declare module "express-serve-static-core" { * simply by removing them from this object. */ routes: any; + + /** + * Using to all registered routes in Express Application + */ + _router: any; } interface Express extends Application { @@ -1057,8 +1079,4 @@ declare module "express-serve-static-core" { response: Response; } - - interface RequestHandler { - (req: Request, res: Response, next: NextFunction): any; - } } diff --git a/express-session/express-session-tests.ts b/express-session/express-session-tests.ts index 1e1f909b14..0b8460214f 100644 --- a/express-session/express-session-tests.ts +++ b/express-session/express-session-tests.ts @@ -6,7 +6,8 @@ import session = require('express-session'); var app = express(); app.use(session({ - secret: 'keyboard cat' + secret: 'keyboard cat', + cookie: { secure: 'auto' } })); app.use(session({ secret: 'keyboard cat', diff --git a/express-session/express-session.d.ts b/express-session/express-session.d.ts index 156e9404fc..90e1ed07cc 100644 --- a/express-session/express-session.d.ts +++ b/express-session/express-session.d.ts @@ -30,7 +30,7 @@ declare namespace Express { secure?: boolean; httpOnly: boolean; domain?: string; - expires: Date; + expires: Date | boolean; serialize: (name: string, value: string) => string; } } diff --git a/express-validator/express-validator-tests.ts b/express-validator/express-validator-tests.ts index 74bd277e46..ebd61d6cfc 100644 --- a/express-validator/express-validator-tests.ts +++ b/express-validator/express-validator-tests.ts @@ -15,19 +15,23 @@ app.post('/:urlparam', function(req: express.Request, res: express.Response) { // Similarly checkParams only checks in req.params (URL params) and // checkQuery only checks req.query (GET params). req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt(); - req.checkParams('urlparam', 'Invalid urlparam').isAlpha(); + req.checkParams('urlparam', 'Invalid urlparam').isAlpha().matches(/test?/i).matches('test?', 'i'); req.checkQuery('getparam', 'Invalid getparam').isInt(); - req.checkHeader('testHeader', 'Invalid testHeader').isLowercase().isUppercase(); - req.checkFiles('testFiles', 'Invalid testFiles').isUrl(); - + req.checkHeaders('testHeader', 'Invalid testHeader').isLowercase().isUppercase(); + req.checkFiles('testFiles', 'Invalid testFiles').isURL(); // OR assert can be used to check on all 3 types of params. // req.assert('postparam', 'Invalid postparam').notEmpty().isInt(); // req.assert('urlparam', 'Invalid urlparam').isAlpha(); // req.assert('getparam', 'Invalid getparam').isInt(); - req.sanitize('postparam').toBoolean(); req.filter('postparam').toBoolean(); + req.sanitize('postparam').blacklist('t').blacklist(['']).whitelist('hello').whitelist(['h', 'e', 'l']); + req.sanitizeBody('postvar').trim().stripLow().escape(); + req.sanitizeQuery('queryvar').toDate(); + req.sanitizeParams('urlparam').toFloat().toInt().toInt(10); + req.sanitizeHeaders('header').normalizeEmail(); + var errors = req.validationErrors(); var mappedErrors = req.validationErrors(true); diff --git a/express-validator/express-validator.d.ts b/express-validator/express-validator.d.ts index 52792a391f..3599b9b79b 100644 --- a/express-validator/express-validator.d.ts +++ b/express-validator/express-validator.d.ts @@ -1,9 +1,10 @@ -// Type definitions for express-validator 2.9.0 +// Type definitions for express-validator 2.20.4 // Project: https://github.com/ctavan/express-validator -// Definitions by: Nathan Ridley , Jonathan Häberle +// Definitions by: Nathan Ridley , Jonathan Häberle , Peter Harris // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/// // Add RequestValidation Interface on to Express's Request Interface. declare namespace Express { @@ -31,25 +32,33 @@ declare namespace ExpressValidator { param: string; } - interface ValidatorFunction { (item: string, message: string): Validator; } + interface ValidatorFunction { (item: string | {}, message?: string): Validator; } + interface ValidatorExtraFunction extends ValidatorFunction { (matchIndex: number, message?: string): Validator; } interface SanitizerFunction { (item: string): Sanitizer; } interface Dictionary { [key: string]: T; } export interface RequestValidation { - assert: ValidatorFunction; - check: ValidatorFunction; + assert: ValidatorExtraFunction; + validate: ValidatorExtraFunction; + check: ValidatorExtraFunction; checkBody: ValidatorFunction; checkFiles: ValidatorFunction; - checkHeader: ValidatorFunction; + checkHeaders: ValidatorFunction; checkParams: ValidatorFunction; checkQuery: ValidatorFunction; - validate: ValidatorFunction; - + filter: SanitizerFunction; sanitize: SanitizerFunction; - + sanitizeBody: SanitizerFunction; + sanitizeQuery: SanitizerFunction; + sanitizeParams: SanitizerFunction; + sanitizeHeaders: SanitizerFunction; + onValidationError(errback: (msg: string) => void): void; - validationErrors(mapped?: boolean): Dictionary | any[]; + validationErrors(mapped?: boolean): Dictionary | MappedError[]; + validationErrors(mapped?: boolean): Dictionary | T[]; + asyncValidationErrors(mapped?: boolean): Promise>; + asyncValidationErrors(mapped?: boolean): Promise>; } export interface Validator { @@ -61,12 +70,13 @@ declare namespace ExpressValidator { * Alias for notRegex() */ not(): Validator; - isEmail(): Validator; + isEmail(options?:{}): Validator; /** * Accepts http, https, ftp */ - isUrl(): Validator; - + isURL(): Validator; + isFQDN(options?: MinMaxOptions): Validator; + /** * Combines isIPv4 and isIPv6 */ @@ -74,8 +84,21 @@ declare namespace ExpressValidator { isIPv4(): Validator; isIPv6(): Validator; isMACAddress(): Validator; - isAlpha(): Validator; - isAlphanumeric(): Validator; + isISBN(version?: number): Validator; + isISIN(): Validator; + isISO8601(): Validator; + isMobilePhone(locale: string): Validator; + isMongoId(): Validator; + isMultibyte(): Validator; + isAlpha(locale?: string): Validator; + isAlphanumeric(locale?: string): Validator; + isAscii(): Validator; + isBase64(): Validator; + isBoolean(): Validator; + isByteLength(options: MinMaxOptions): Validator; + isCurrency(options: {}): Validator; + isDataURI(): Validator; + isDivisibleBy(num: number): Validator; isNumeric(): Validator; isHexadecimal(): Validator; /** @@ -85,7 +108,7 @@ declare namespace ExpressValidator { /** * isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't */ - isInt(): Validator; + isInt(options?: MinMaxOptions): Validator; isLowercase(): Validator; isUppercase(): Validator; isDecimal(): Validator; @@ -93,10 +116,12 @@ declare namespace ExpressValidator { * Alias for isDecimal */ isFloat(): Validator; + isFullWidth(): Validator; + isHalfWidth(): Validator; + isVariableWidth(): Validator; /** * Check if length is 0 */ - notNull(): Validator; isNull(): Validator; /** * Not just whitespace (input.trim().length !== 0) @@ -104,12 +129,13 @@ declare namespace ExpressValidator { notEmpty(): Validator; equals(equals:any): Validator; contains(str:string): Validator; - notContains(str:string): Validator; + /** - * Usage: regex(/[a-z]/i) or regex('[a-z]','i') + * Usage: matches(/[a-z]/i) or matches('[a-z]','i') */ - regex(pattern:string, modifiers:string): Validator; - notRegex(pattern:string, modifiers:string): Validator; + matches(pattern:string, modifiers?:string): Validator; + matches(pattern: RegExp): Validator; + /** * max is optional */ @@ -117,7 +143,7 @@ declare namespace ExpressValidator { /** * Version can be 3, 4 or 5 or empty, see http://en.wikipedia.org/wiki/Universally_unique_identifier */ - isUUID(version:number): Validator; + isUUID(version?:number): Validator; /** * Alias for isUUID(3) */ @@ -137,17 +163,20 @@ declare namespace ExpressValidator { /** * Argument is optional and defaults to today. Comparison is non-inclusive */ - isAfter(date:Date): Validator; + isAfter(date?:Date): Validator; /** * Argument is optional and defaults to today. Comparison is non-inclusive */ - isBefore(date:Date): Validator; + isBefore(date?:Date): Validator; isIn(options:string): Validator; isIn(options:string[]): Validator; notIn(options:string): Validator; notIn(options:string[]): Validator; max(val:string): Validator; min(val:string): Validator; + isJSON(): Validator; + isLength(options: MinMaxOptions): Validator; + isWhitelisted(chars: string): Validator; /** * Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats */ @@ -155,7 +184,10 @@ declare namespace ExpressValidator { /** * Check an input only when the input exists */ - optional(): Validator; + isSurrogatePar(): Validator; + + optional(options?: { checkFalsy?: boolean }): Validator; + withMessage(message: string): Validator; } interface Sanitizer { @@ -165,40 +197,49 @@ declare namespace ExpressValidator { trim(...chars:string[]): Sanitizer; ltrim(...chars:string[]): Sanitizer; rtrim(...chars:string[]): Sanitizer; - ifNull(replace:any): Sanitizer; + stripLow(keep_new_lines?: boolean): Sanitizer; toFloat(): Sanitizer; - toInt(): Sanitizer; + toInt(radix?: number): Sanitizer; /** - * True unless str = '0', 'false', or str.length == 0 - */ - toBoolean(): Sanitizer; - /** - * False unless str = '1' or 'true' - */ - toBooleanStrict(): Sanitizer; - /** - * Decode HTML entities + * True unless str = '0', 'false', or str.length == 0. In strict mode only '1' and 'true' return true. */ + toBoolean(strict?: boolean): Sanitizer; /** - * Convert the input string to a date, or null if the input is not a date. - */ - toDate(): Sanitizer; - - entityDecode(): Sanitizer; - entityEncode(): Sanitizer; + * Convert the input string to a date, or null if the input is not a date. + */ + toDate(): Sanitizer; + /** * Escape &, <, >, and " */ escape(): Sanitizer; + /** - * Remove common XSS attack vectors from user-supplied HTML + * Replaces HTML encoded entities with <, >, &, ', " and /. */ - xss(): Sanitizer; + unescape(): Sanitizer; + + blacklist(chars: string): Sanitizer; + blacklist(chars: string[]): Sanitizer; + whitelist(chars: string): Sanitizer; + whitelist(chars: string[]): Sanitizer; + + normalizeEmail(options?: { lowercase?: boolean; remove_dots?: boolean; remove_extensions?: boolean }): Sanitizer; + /** - * Remove common XSS attack vectors from images + * !!! XSS sanitization was removed from the library (see: https://github.com/chriso/validator.js#xss-sanitization) */ - xss(fromImages:boolean): Sanitizer; } - + + interface MappedError { + param: string; + msg: string; + value: string; + } + + interface MinMaxOptions { + min?: number; + max?: number; + } } diff --git a/express/express-tests.ts b/express/express-tests.ts index 11f8fd44fd..92cef00b85 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -1,73 +1,114 @@ /// - +/// import * as express from 'express'; -var app = express(); - -app.engine('jade', require('jade').__express); -app.engine('html', require('ejs').renderFile); - -express.static.mime.define({ - 'application/fx': ['fx'] -}); -app.use('/static', express.static(__dirname + '/public')); - -// simple logger -app.use(function(req, res, next){ - console.log('%s %s', req.method, req.url); - next(); -}); - -app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) { - console.error(err); - next(err); -}); -app.get('/', function(req, res){ - res.send('hello world'); -}); +namespace express_tests { -const router = express.Router(); + var app = express(); + app.engine('jade', require('jade').__express); + app.engine('html', require('ejs').renderFile); -const pathStr : string = 'test'; -const pathRE : RegExp = /test/; -const path = true? pathStr : pathRE; + express.static.mime.define({ + 'application/fx': ['fx'] + }); + app.use('/static', express.static(__dirname + '/public')); -router.get(path); -router.put(path) -router.post(path); -router.delete(path); -router.get(pathStr); -router.put(pathStr) -router.post(pathStr); -router.delete(pathStr); -router.get(pathRE); -router.put(pathRE) -router.post(pathRE); -router.delete(pathRE); - -router.use((req, res, next) => { next(); }) -router.route('/users') - .get((req, res, next) => { - res.send(req.query['token']); + // simple logger + app.use(function(req, res, next) { + console.log('%s %s', req.method, req.url); + next(); }); -router.get('/user/:id', function(req, res, next) { - if (req.params.id == 0) next('route'); - else next(); -}, function(req, res, next) { - res.render('regular'); -}); + app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) { + console.error(err); + next(err); + }); -app.use((req, res, next) => { - // hacky trick, router is just a handler - router(req, res, next); -}); -app.use(router); + app.get('/', function(req, res) { + res.send('hello world'); + }); -app.listen(3000); + const router = express.Router(); -const next: express.NextFunction = () => {}; -const nextWithArgument: express.NextFunction = (err: any) => {}; + + const pathStr: string = 'test'; + const pathRE: RegExp = /test/; + const path = true ? pathStr : pathRE; + + router.get(path); + router.put(path) + router.post(path); + router.delete(path); + router.get(pathStr); + router.put(pathStr) + router.post(pathStr); + router.delete(pathStr); + router.get(pathRE); + router.put(pathRE) + router.post(pathRE); + router.delete(pathRE); + + router.use((req, res, next) => { next(); }) + router.route('/users') + .get((req, res, next) => { + let types: string[] = req.accepts(); + let type: string | boolean = req.accepts('json'); + type = req.accepts(['json', 'text']); + type = req.accepts('json', 'text'); + + let charsets: string[] = req.acceptsCharsets(); + let charset: string | boolean = req.acceptsCharsets('utf-8'); + charset = req.acceptsCharsets(['utf-8', 'utf-16']); + charset = req.acceptsCharsets('utf-8', 'utf-16'); + + let encodings: string[] = req.acceptsEncodings(); + let encoding: string | boolean = req.acceptsEncodings('gzip'); + encoding = req.acceptsEncodings(['gzip', 'deflate']); + encoding = req.acceptsEncodings('gzip', 'deflate'); + + let languages: string[] = req.acceptsLanguages(); + let language: string | boolean = req.acceptsLanguages('en'); + language = req.acceptsLanguages(['en', 'ja']); + language = req.acceptsLanguages('en', 'ja'); + + res.send(req.query['token']); + }); + + router.get('/user/:id', function(req, res, next) { + if (req.params.id == 0) next('route'); + else next(); + }, function(req, res, next) { + res.render('regular'); + }); + + app.use((req, res, next) => { + // hacky trick, router is just a handler + router(req, res, next); + }); + + app.use(router); + + app.listen(3000); + + const next: express.NextFunction = () => { }; +} + +/*************************** + * * + * Test with other modules * + * * + ***************************/ +import * as http from 'http'; + + +namespace node_tests { + + { + // http.createServer can take express application + const app: express.Application = express(); + http.createServer(app).listen(5678); + } +} diff --git a/express/express.d.ts b/express/express.d.ts index 4ab7eb1c90..5f65b60519 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -38,8 +38,9 @@ declare module "express" { interface Express extends core.Express { } interface Handler extends core.Handler { } interface IRoute extends core.IRoute { } - interface IRouter extends core.IRouter { } + interface IRouter extends core.IRouter { } interface IRouterMatcher extends core.IRouterMatcher { } + interface IRouterHandler extends core.IRouterHandler { } interface MediaType extends core.MediaType { } interface NextFunction extends core.NextFunction { } interface Request extends core.Request { } diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index 727cb57f23..08fcdb6ec3 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -333,7 +333,6 @@ declare namespace fabric { on(eventName: {[key:string] : Function}): T; /** * Fires event with an optional options object - * @deprecated `fire` deprecated since 1.0.7 (use `trigger` instead) * @param {String} eventName Event name to fire * @param {Object} [options] Options object */ @@ -341,7 +340,6 @@ declare namespace fabric { /** * Stops event observing for a particular event handler. Calling this method * without arguments removes all handlers for all events - * @deprecated `stopObserving` deprecated since 0.8.34 (use `off` instead) * @param eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler}) * @param handler Function to be deleted from EventListeners */ diff --git a/facebook-js-sdk/facebook-js-sdk-tests.ts b/facebook-js-sdk/facebook-js-sdk-tests.ts index 49e615f529..41c0eaff40 100644 --- a/facebook-js-sdk/facebook-js-sdk-tests.ts +++ b/facebook-js-sdk/facebook-js-sdk-tests.ts @@ -14,6 +14,12 @@ FB.getLoginStatus(function(response: fb.AuthResponse) { console.log(response.authResponse.accessToken); }); +FB.getLoginStatus(function(response: fb.AuthResponse) { + console.log(response); + console.log(response.status); + console.log(response.authResponse.accessToken); +}, true); + FB.getAuthResponse(function(response: fb.AuthResponse) { console.log(response); console.log(response.status); diff --git a/facebook-js-sdk/facebook-js-sdk.d.ts b/facebook-js-sdk/facebook-js-sdk.d.ts index 5353353911..bee34f0a2c 100644 --- a/facebook-js-sdk/facebook-js-sdk.d.ts +++ b/facebook-js-sdk/facebook-js-sdk.d.ts @@ -8,10 +8,11 @@ declare var FB: fb.FacebookStatic; declare namespace facebook { interface FacebookStatic { - // api: any; - // AppEvents: any; - // Canvas: any; - // Event: any; + api: any; + AppEvents: any; + Canvas: any; + Event: any; + /** * The method FB.getAuthResponse() is a synchronous accessor for the current authResponse. * The synchronous nature of this method is what sets it apart from the other login methods. @@ -25,7 +26,7 @@ declare namespace facebook { * * @param callback function to handle the response. */ - getLoginStatus(callback: (response: AuthResponse) => void): void; + getLoginStatus(callback: (response: AuthResponse) => void, roundtrip?: boolean ): void; /** * The method FB.init() is used to initialize and setup the SDK. * @@ -49,8 +50,9 @@ declare namespace facebook { * @param callback function to handle the response */ logout(callback: (response: AuthResponse) => void): void; - // ui: any; - // XFBML: any; + + ui: any; + XFBML: any; } interface InitParams { diff --git a/fast-json-patch/fast-json-patch-tests.ts b/fast-json-patch/fast-json-patch-tests.ts new file mode 100644 index 0000000000..e7ecc249ac --- /dev/null +++ b/fast-json-patch/fast-json-patch-tests.ts @@ -0,0 +1,43 @@ +/// +import * as jsonpatch from 'fast-json-patch' + +var myobj:{ + firstName:string, + contactDetails: { + phoneNumbers:string[] + } +} = { firstName:"Albert", contactDetails: { phoneNumbers: [ ] } }; +var patches = [ + {op:"replace", path:"/firstName", value:"Joachim" }, + {op:"add", path:"/lastName", value:"Wester" }, + {op:"add", path:"/contactDetails/phoneNumbers/0", value:{ number:"555-123" } } + ]; +jsonpatch.apply( myobj, patches ); + +var myobj2 = { firstName:"Joachim", lastName:"Wester", contactDetails: { phoneNumbers: [ { number:"555-123" }] } }; +var observer = jsonpatch.observe( myobj2 ); +myobj2.firstName = "Albert"; +myobj2.contactDetails.phoneNumbers[0].number = "123"; +myobj2.contactDetails.phoneNumbers.push({number:"456"}); +var patches2 = jsonpatch.generate(observer); + +var objA = {user: {firstName: "Albert", lastName: "Einstein"}}; +var objB = {user: {firstName: "Albert", lastName: "Collins"}}; +var diff = jsonpatch.compare(objA, objB); + +var obj = {user: {firstName: "Albert"}}; +var patches3 = [{op: "replace", path: "/user/firstName", value: "Albert"}, {op: "replace", path: "/user/lastName", value: "Einstein"}]; +var errors = jsonpatch.validate(patches, obj); +if (errors.length == 0) { + //there are no errors! +} +else { + for (var i=0; i < errors.length; i++) { + if (!errors[i]) { + console.log("Valid patch at index", i, patches[i]); + } + else { + console.error("Invalid patch at index", i, errors[i], patches[i]); + } + } +} diff --git a/fast-json-patch/fast-json-patch.d.ts b/fast-json-patch/fast-json-patch.d.ts new file mode 100644 index 0000000000..9a4496b00c --- /dev/null +++ b/fast-json-patch/fast-json-patch.d.ts @@ -0,0 +1,67 @@ +// Type definitions for JSON-Patch v1.0.0 +// Project: https://github.com/Starcounter-Jack/JSON-Patch/releases +// Definitions by: Francis OBrien +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace fastjsonpatch { + + + interface JsonPatch { + /** + * Applies an array of patch instructions to an object + */ + apply(object:any, patches:Patch[], validate?:boolean):boolean + + /** + * Observes changes made to an object, which can then be retieved using generate + */ + observe(object:T, callback?:()=>void):Observer + + /** + * Detach an observer from an object + */ + unobserve(object:T, observer:Observer):void + + /** + * Generate an array of patches from an observer + */ + generate(observer:Observer):Patch[] + + /** + * Create an array of patches from the differences in two objects + */ + compare(object1:any, object2:any):Patch[] + + /** + * Ensure a set of patch instructions is valid + */ + validate(patches:Patch[], tree?:any):JsonPatchError[] + } + + interface Observer { + object:T + patches:Patch[] + unobserve():void + } + + interface Patch { + op:string + path:string + value?:any + from?:string + } + + interface JsonPatchError { + name:string + message:string + index:number + operation:any + tree:any + } +} + +declare var jsonpatch: fastjsonpatch.JsonPatch; + +declare module "fast-json-patch" { + export = jsonpatch +} \ No newline at end of file diff --git a/fbsdk/fbsdk.d.ts b/fbsdk/fbsdk.d.ts index 79c710f8f7..286eb86b8e 100644 --- a/fbsdk/fbsdk.d.ts +++ b/fbsdk/fbsdk.d.ts @@ -67,11 +67,28 @@ interface PayDialogParams { test_currency?: string; } +interface FeedDialogParams { + method: string; // "feed" + app_id: string; + redirect_uri?: string; + display?: string; + from?: string; + to?: string; + link?: string; + picture?: string; + source?: string; + name: string; + caption?: string; + description?: string; + ref?: any; +} + declare type FBUIParams = ShareDialogParams | PageTabDialogParams | RequestsDialogParams | SendDialogParams - | PayDialogParams; + | PayDialogParams + | FeedDialogParams; interface FBLoginOptions{ auth_type?: string; diff --git a/fetch-mock/fetch-mock-tests.ts b/fetch-mock/fetch-mock-tests.ts new file mode 100644 index 0000000000..b630668e18 --- /dev/null +++ b/fetch-mock/fetch-mock-tests.ts @@ -0,0 +1,44 @@ +/// + +import * as fetchMock from "fetch-mock"; + +fetchMock.mock("http://test.com", 200); +fetchMock.mock(/test\.com/, 200); +fetchMock.mock(() => true, 200); +fetchMock.mock((url, opts) => true, 200); + +fetchMock.mock(/test/, "test").mock(/test/, { a: "b" }); +fetchMock.mock(/test/, { + status: 200, + headers: { + "test": "test" + }, + body: { + a: "b" + } +}); + +fetchMock.restore().reset(); + +(fetchMock.calls().matched[0][1] as RequestInit).body; +fetchMock.calls().unmatched[0][0].toUpperCase(); +fetchMock.calls("http://test.com")[0][0].toUpperCase(); +(fetchMock.calls("http://test.com")[0][1] as RequestInit).body; + +fetchMock.called("http://test.com"); + +(fetchMock.lastCall()[1] as RequestInit).body; +fetchMock.lastUrl(); +fetchMock.lastOptions(); + +fetchMock.get("http://test.com", 200) +fetchMock.post("http://test.com", 200) +fetchMock.put("http://test.com", 200) +fetchMock.delete("http://test.com", 200) +fetchMock.head("http://test.com", 200) + +fetchMock.get("http://test.com", 200, {method: "GET"}) +fetchMock.post("http://test.com", 200, {method: "POST"}) +fetchMock.put("http://test.com", 200, {method: "PUT"}) +fetchMock.delete("http://test.com", 200, {method: "DELETE"}) +fetchMock.head("http://test.com", 200, {method: "HEAD"}) diff --git a/fetch-mock/fetch-mock.d.ts b/fetch-mock/fetch-mock.d.ts new file mode 100644 index 0000000000..47c31e4c64 --- /dev/null +++ b/fetch-mock/fetch-mock.d.ts @@ -0,0 +1,277 @@ +// Type definitions for fetch-mock 5.0.0 +// Project: https://github.com/wheresrhys/fetch-mock +// Definitions by: Alexey Svetliakov , Tamir Duberstein +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + +declare module "fetch-mock" { + type MockRequest = Request | RequestInit; + + /** + * Mock matcher function + * @param url + * @param opts + */ + type MockMatcherFunction = (url: string, opts: MockRequest) => boolean + /** + * Mock matcher. Can be one of following: + * string: Either + * an exact url to match e.g. 'http://www.site.com/page.html' + * if the string begins with a `^`, the string following the `^` must + begin the url e.g. '^http://www.site.com' would match + 'http://www.site.com' or 'http://www.site.com/page.html' + * '*' to match any url + * RegExp: A regular expression to test the url against + * Function(url, opts): A function (returning a Boolean) that is passed the + url and opts fetch() is called with (or, if fetch() was called with one, + the Request instance) + */ + type MockMatcher = string | RegExp | MockMatcherFunction; + + /** + * Mock response object + */ + interface MockResponseObject { + /** + * Set the response body + */ + body?: string | {}; + /** + * Set the response status + * @default 200 + */ + status?: number; + /** + * Set the response headers. + */ + headers?: { [key: string]: string }; + /** + * If this property is present then a Promise rejected with the value + of throws is returned + */ + throws?: boolean; + /** + * This property determines whether or not the request body should be + JSON.stringified before being sent + * @default true + */ + sendAsJson?: boolean; + } + /** + * Response: A Response instance - will be used unaltered + * number: Creates a response with this status + * string: Creates a 200 response with the string as the response body + * object: As long as the object is not a MockResponseObject it is + converted into a json string and returned as the body of a 200 response + * If MockResponseObject was given then it's used to configure response + * Function(url, opts): A function that is passed the url and opts fetch() + is called with and that returns any of the responses listed above + */ + type MockResponse = Response | Promise + | number | Promise + | string | Promise + | Object | Promise + | MockResponseObject | Promise; + /** + * Mock response function + * @param url + * @param opts + */ + type MockResponseFunction = (url: string, opts: MockRequest) => MockResponse; + + /** + * Mock options object + */ + interface MockOptions { + /** + * A unique string naming the route. Used to subsequently retrieve + references to the calls, grouped by name. + * @default matcher.toString() + * + * Note: If a non-unique name is provided no error will be thrown + (because names are optional, auto-generated ones may legitimately + clash) + */ + name?: string; + /** + * http method to match + */ + method?: string; + /** + * as specified above + */ + matcher?: MockMatcher; + /** + * as specified above + */ + response?: MockResponse | MockResponseFunction; + } + + type MockCall = [string, MockRequest]; + + interface MatchedRoutes { + matched: Array; + unmatched: Array; + } + + interface MockOptionsMethodGet extends MockOptions { + method: 'GET' + } + + interface MockOptionsMethodPost extends MockOptions { + method: 'POST' + } + + interface MockOptionsMethodPut extends MockOptions { + method: 'PUT' + } + + interface MockOptionsMethodDelete extends MockOptions { + method: 'DELETE' + } + + interface MockOptionsMethodHead extends MockOptions { + method: 'HEAD' + } + + interface FetchMockStatic { + /** + * Replaces fetch() with a stub which records its calls, grouped by + route, and optionally returns a mocked Response object or passes the + call through to fetch(). Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + */ + mock(matcher: MockMatcher, response: MockResponse | MockResponseFunction): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + route, and optionally returns a mocked Response object or passes the + call through to fetch(). Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param options Additional properties defining the route to mock + */ + mock(matcher: MockMatcher, response: MockResponse | MockResponseFunction, options: MockOptions): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + route, and optionally returns a mocked Response object or passes the + call through to fetch(). Calls to .mock() can be chained. + * @param options The route to mock + */ + mock(options: MockOptions): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + route, and optionally returns a mocked Response object or passes the + call through to fetch(). Shorthand for mock() restricted to the GET + method. Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + get(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodGet): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + route, and optionally returns a mocked Response object or passes the + call through to fetch(). Shorthand for mock() restricted to the POST + method. Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + post(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodPost): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + route, and optionally returns a mocked Response object or passes the + call through to fetch(). Shorthand for mock() restricted to the PUT + method. Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + put(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodPut): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + route, and optionally returns a mocked Response object or passes the + call through to fetch(). Shorthand for mock() restricted to the + DELETE method. Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + delete(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodDelete): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + route, and optionally returns a mocked Response object or passes the + call through to fetch(). Shorthand for mock() restricted to the HEAD + method. Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param [options] Additional properties defining the route to mock + */ + head(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodHead): this; + /** + * Chainable method that restores fetch() to its unstubbed state and + clears all data recorded for its calls. + */ + restore(): this; + /** + * Chainable method that clears all data recorded for fetch()'s calls + */ + reset(): this; + /** + * Returns all calls to fetch, grouped by whether fetch-mock matched + them or not. + */ + calls(): MatchedRoutes; + /** + * Returns all calls to fetch matching matcherName. + */ + calls(matcherName?: string): Array; + /** + * Returns a Boolean indicating whether fetch was called and a route + was matched. + */ + called(): boolean; + /** + * Returns a Boolean indicating whether fetch was called and a route + named matcherName was matched. + */ + called(matcherName?: string): boolean; + /** + * Returns the arguments for the last matched call to fetch + */ + lastCall(): MockCall; + /** + * Returns the arguments for the last call to fetch matching + matcherName + */ + lastCall(matcherName?: string): MockCall; + /** + * Returns the url for the last matched call to fetch + */ + lastUrl(): string; + /** + * Returns the url for the last call to fetch matching matcherName + */ + lastUrl(matcherName?: string): string; + /** + * Returns the options for the last matched call to fetch + */ + lastOptions(): MockRequest; + /** + * Returns the options for the last call to fetch matching matcherName + */ + lastOptions(matcherName?: string): MockRequest; + /** + * Set some global config options, which include + * sendAsJson [default `true`] - by default fetchMock will + convert objects to JSON before sending. This is overrideable + for each call but for some scenarios, e.g. when dealing with a + lot of array buffers, it can be useful to default to `false` + */ + configure(opts: Object): void; + } + + var fetchMock: FetchMockStatic; + export = fetchMock; +} diff --git a/file-type/file-type-tests.ts b/file-type/file-type-tests.ts new file mode 100644 index 0000000000..ebbee83783 --- /dev/null +++ b/file-type/file-type-tests.ts @@ -0,0 +1,7 @@ +/// + +"use strict"; + +import fileType = require("file-type") + +fileType(new Buffer([0xFF, 0xD8, 0xFF])) diff --git a/file-type/file-type.d.ts b/file-type/file-type.d.ts new file mode 100644 index 0000000000..58c449ca3c --- /dev/null +++ b/file-type/file-type.d.ts @@ -0,0 +1,17 @@ +// Type definitions for file-type +// Project: https://github.com/sindresorhus/file-type +// Definitions by: KIM Jaesuck a.k.a. gim tcaesvk +// Definitions: https://github.com/DefinitelyType/DefinitelyTyped + +/// + +declare module "file-type" { + interface FileTypeResult { + ext: string + mime: string + } + + function FileType(buf: Buffer): FileTypeResult + + export = FileType +} diff --git a/fill-pdf/fill-pdf-tests.ts b/fill-pdf/fill-pdf-tests.ts new file mode 100644 index 0000000000..e5b34cd943 --- /dev/null +++ b/fill-pdf/fill-pdf-tests.ts @@ -0,0 +1,17 @@ +/// + +import * as fillPdf from 'fill-pdf'; + +var formData: fillPdf.FormData = { FieldName: 'Text to put into form field' }; +var pdfTemplatePath = 'templates.pdf'; +var extendArgs: string[] = []; + +fillPdf.generatePdf(formData, pdfTemplatePath, extendArgs, (err: Error, output: Buffer) => { + if ( !err ) { + console.log('Success!'); + // output is a buffer + } +}); + +var result = fillPdf.generateFdf(formData); +// result is a buffer diff --git a/fill-pdf/fill-pdf.d.ts b/fill-pdf/fill-pdf.d.ts new file mode 100644 index 0000000000..d35057f934 --- /dev/null +++ b/fill-pdf/fill-pdf.d.ts @@ -0,0 +1,16 @@ +// Type definitions for fill-pdf v0.5.0 +// Project: https://github.com/dommmel/fill-pdf +// Definitions by: Seth Westphal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'fill-pdf' { + + export interface FormData { + [name: string]: string; + } + + export function generatePdf(data: FormData, templatePath: string, extendArgs: string[], callback?: (err: Error, output: Buffer) => void): void; + export function generateFdf(data: FormData): Buffer; +} diff --git a/fluent-ffmpeg/fluent-ffmpeg-tests.ts b/fluent-ffmpeg/fluent-ffmpeg-tests.ts new file mode 100644 index 0000000000..8b1031ff58 --- /dev/null +++ b/fluent-ffmpeg/fluent-ffmpeg-tests.ts @@ -0,0 +1,7 @@ +/// + +import ffmpeg = require("fluent-ffmpeg") + +let source: string, format: string, output: string + +ffmpeg({ source: source }).format(format).save(output) diff --git a/fluent-ffmpeg/fluent-ffmpeg.d.ts b/fluent-ffmpeg/fluent-ffmpeg.d.ts new file mode 100644 index 0000000000..92e1a33891 --- /dev/null +++ b/fluent-ffmpeg/fluent-ffmpeg.d.ts @@ -0,0 +1,315 @@ +// Type definitions for node-fluent-ffmpeg +// Project: https://github.com/fluent-ffmpeg/node-fluent-ffmpeg +// Definitions by: KIM Jaesuck a.k.a. gim tcaesvk +// Definitions: https://github.com/DefinitelyType/DefinitelyTyped + +/// + +declare module "fluent-ffmpeg" { + import * as events from "events" + import * as stream from "stream" + + interface FfmpegCommandLogger { + error(...data: any[]): void + warning(...data: any[]): void + info(...data: any[]): void + debug(...data: any[]): void + } + + interface FfmpegCommandOptions { + logger?: FfmpegCommandLogger + niceness?: number + priority?: number + presets?: string + preset?: string + stdoutLines?: number + timeout?: number + source?: string | stream.Readable + } + + interface FilterSpecification { + filter: string + inputs: string | string[] + outputs: string | string[] + options?: Object | string | any[] + } + + interface GetPreset { + (command: FfmpegCommand): string + } + + interface Filter { + description: string + input: string + multipleInputs: boolean + output: string + multipleOutputs: boolean + } + interface Filters { + [key: string]: Filter + } + interface FiltersCallback { + (err: Error, filters: Filters): void + } + + interface Codec { + type: string + description: string + canDecode: boolean + canEncode: boolean + drawHorizBand?: boolean + directRendering?: boolean + weirdFrameTruncation?: boolean + intraFrameOnly?: boolean + isLossy?: boolean + isLossless?: boolean + } + interface Codecs { + [key: string]: Codec + } + interface CodecsCallback { + (err: Error, codecs: Codecs): void + } + + interface Encoder { + type: string + description: string + frameMT: boolean + sliceMT: boolean + experimental: boolean + drawHorizBand: boolean + directRendering: boolean + } + interface Encoders { + [key: string]: Encoder + } + interface EncodersCallback { + (err: Error, encoders: Encoders): void + } + + interface Format { + description: string + canDemux: boolean + canMux: boolean + } + interface Formats { + [key: string]: Format + } + interface FormatsCallback { + (err: Error, formats: Formats): void + } + + interface FfprobeData { + stream: any[] + format: any + chapters: any[] + } + + interface ScreenshotsConfig { + count?: number + folder?: string + filename?: string + timemarks?: number[] | string[] + timestamps?: number[] | string[] + fastSeek?: boolean + size?: string + } + + interface FfmpegCommand extends events.EventEmitter { + constructor(): FfmpegCommand + constructor(options: FfmpegCommandOptions): FfmpegCommand + constructor(input: string | stream.Readable, options: FfmpegCommandOptions): FfmpegCommand + + // options/inputs + mergeAdd(source: string | stream.Readable): FfmpegCommand + addInput(source: string | stream.Readable): FfmpegCommand + input(source: string | stream.Readable): FfmpegCommand + withInputFormat(format: string): FfmpegCommand + inputFormat(format: string): FfmpegCommand + fromFormat(format: string): FfmpegCommand + withInputFps(fps: number): FfmpegCommand + withInputFPS(fps: number): FfmpegCommand + withFpsInput(fps: number): FfmpegCommand + withFPSInput(fps: number): FfmpegCommand + inputFPS(fps: number): FfmpegCommand + inputFps(fps: number): FfmpegCommand + fpsInput(fps: number): FfmpegCommand + FPSInput(fps: number): FfmpegCommand + nativeFramerate(): FfmpegCommand + withNativeFramerate(): FfmpegCommand + native(): FfmpegCommand + setStartTime(seek: string | number): FfmpegCommand + seekInput(seek: string | number): FfmpegCommand + loop(duration: string | number): FfmpegCommand + + // options/audio + withNoAudio(): FfmpegCommand + noAudio(): FfmpegCommand + withAudioCodec(codec: string): FfmpegCommand + audioCodec(codec: string): FfmpegCommand + withAudioBitrate(bitrate: string | number): FfmpegCommand + audioBitrate(bitrate: string | number): FfmpegCommand + withAudioChannels(channels: number): FfmpegCommand + audioChannels(channels: number): FfmpegCommand + withAudioFrequency(freq: number): FfmpegCommand + audioFrequency(freq: number): FfmpegCommand + withAudioQuality(quality: number): FfmpegCommand + audioQuality(quality: number): FfmpegCommand + withAudioFilter(filters: { filter: string, options: any }): FfmpegCommand + withAudioFilters(filters: { filter: string, options: any }): FfmpegCommand + audioFilter(filters: { filter: string, options: any }): FfmpegCommand + audioFilters(filters: { filter: string, options: any }): FfmpegCommand + + // options/video + withNoVideo(): FfmpegCommand + noVideo(): FfmpegCommand + withVideoCodec(codec: string): FfmpegCommand + videoCodec(codec: string): FfmpegCommand + withVideoBitrate(bitrate: string | number): FfmpegCommand + videoBitrate(bitrate: string | number): FfmpegCommand + withVideoFilter(filters: { filter: string, options: any }): FfmpegCommand + withVideoFilters(filters: { filter: string, options: any }): FfmpegCommand + videoFilter(filters: { filter: string, options: any }): FfmpegCommand + videoFilters(filters: { filter: string, options: any }): FfmpegCommand + withOutputFps(fps: number): FfmpegCommand + withOutputFPS(fps: number): FfmpegCommand + withFpsOutput(fps: number): FfmpegCommand + withFPSOutput(fps: number): FfmpegCommand + withFps(fps: number): FfmpegCommand + withFPS(fps: number): FfmpegCommand + outputFPS(fps: number): FfmpegCommand + outputFps(fps: number): FfmpegCommand + fpsOutput(fps: number): FfmpegCommand + FPSOutput(fps: number): FfmpegCommand + fps(fps: number): FfmpegCommand + FPS(fps: number): FfmpegCommand + takeFrames(frames: number): FfmpegCommand + withFrames(frames: number): FfmpegCommand + frames(frames: number): FfmpegCommand + + // options/videosize + keepPixelAspect(): FfmpegCommand + keepDisplayAspect(): FfmpegCommand + keepDisplayAspectRatio(): FfmpegCommand + keepDAR(): FfmpegCommand + withSize(size: string): FfmpegCommand + setSize(size: string): FfmpegCommand + size(size: string): FfmpegCommand + withAspect(aspect: string | number): FfmpegCommand + withAspectRatio(aspect: string | number): FfmpegCommand + setAspect(aspect: string | number): FfmpegCommand + setAspectRatio(aspect: string | number): FfmpegCommand + aspect(aspect: string | number): FfmpegCommand + aspectRatio(aspect: string | number): FfmpegCommand + applyAutopadding(pad: boolean, color: string): FfmpegCommand + applyAutoPadding(pad: boolean, color: string): FfmpegCommand + applyAutopad(pad: boolean, color: string): FfmpegCommand + applyAutoPad(pad: boolean, color: string): FfmpegCommand + withAutopadding(pad: boolean, color: string): FfmpegCommand + withAutoPadding(pad: boolean, color: string): FfmpegCommand + withAutopad(pad: boolean, color: string): FfmpegCommand + withAutoPad(pad: boolean, color: string): FfmpegCommand + autoPad(pad: boolean, color: string): FfmpegCommand + autopad(pad: boolean, color: string): FfmpegCommand + + // options/output + addOutput(target: string | stream.Writable, pipeopts?: { end?: boolean }): FfmpegCommand + output(target: string | stream.Writable, pipeopts?: { end?: boolean }): FfmpegCommand + seekOutput(seek: string | number): FfmpegCommand + seek(seek: string | number): FfmpegCommand + withDuration(duration: string | number): FfmpegCommand + setDuration(duration: string | number): FfmpegCommand + duration(duration: string | number): FfmpegCommand + toFormat(format: string): FfmpegCommand + withOutputFormat(format: string): FfmpegCommand + outputFormat(format: string): FfmpegCommand + format(format: string): FfmpegCommand + map(spec: string): FfmpegCommand + updateFlvMetadata(): FfmpegCommand + flvmeta(): FfmpegCommand + + // options/custom + addInputOption(options: string[]): FfmpegCommand + addInputOption(...options: string[]): FfmpegCommand + addInputOptions(options: string[]): FfmpegCommand + addInputOptions(...options: string[]): FfmpegCommand + withInputOption(options: string[]): FfmpegCommand + withInputOption(...options: string[]): FfmpegCommand + withInputOptions(options: string[]): FfmpegCommand + withInputOptions(...options: string[]): FfmpegCommand + inputOption(options: string[]): FfmpegCommand + inputOption(...options: string[]): FfmpegCommand + inputOptions(options: string[]): FfmpegCommand + inputOptions(...options: string[]): FfmpegCommand + addOutputOption(options: string[]): FfmpegCommand + addOutputOption(...options: string[]): FfmpegCommand + addOutputOptions(options: string[]): FfmpegCommand + addOutputOptions(...options: string[]): FfmpegCommand + addOption(options: string[]): FfmpegCommand + addOption(...options: string[]): FfmpegCommand + addOptions(options: string[]): FfmpegCommand + addOptions(...options: string[]): FfmpegCommand + withOutputOption(options: string[]): FfmpegCommand + withOutputOption(...options: string[]): FfmpegCommand + withOutputOptions(options: string[]): FfmpegCommand + withOutputOptions(...options: string[]): FfmpegCommand + withOption(options: string[]): FfmpegCommand + withOption(...options: string[]): FfmpegCommand + withOptions(options: string[]): FfmpegCommand + withOptions(...options: string[]): FfmpegCommand + outputOption(options: string[]): FfmpegCommand + outputOption(...options: string[]): FfmpegCommand + outputOptions(options: string[]): FfmpegCommand + outputOptions(...options: string[]): FfmpegCommand + filterGraph(spec: string | FilterSpecification[], map: string[]): FfmpegCommand + complexFilter(spec: string | FilterSpecification[], map: string[]): FfmpegCommand + + // options/misc + usingPreset(proset: string | GetPreset): FfmpegCommand + pnreset(proset: string | GetPreset): FfmpegCommand + + // processor + renice(niceness: number): FfmpegCommand + kill(signal: string): FfmpegCommand + + // capabilities + setFfmpegPath(path: string): FfmpegCommand + setFfprobePath(path: string): FfmpegCommand + setFlvtoolPath(path: string): FfmpegCommand + availableFilters(callback: FiltersCallback): void + getAvailableFilters(callback: FiltersCallback): void + availableCodecs(callback: CodecsCallback): void + getAvailableCodecs(callback: CodecsCallback): void + availableEncoders(callback: EncodersCallback): void + getAvailableEncoders(callback: EncodersCallback): void + availableFormats(callback: FormatsCallback): void + getAvailableFormats(callback: FormatsCallback): void + + // ffprobe + ffprobe(callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void + ffprobe(index: number, callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void + ffprobe(options: string[], callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void + ffprobe(index: number, options: string[], callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void + + // recipes + saveToFile(output: string): FfmpegCommand + save(output: string): FfmpegCommand + writeToStream(stream: stream.Writable, options?: { end?: boolean }): stream.Writable + pipe(stream: stream.Writable, options?: { end?: boolean }): stream.Writable + stream(stream: stream.Writable, options?: { end?: boolean }): stream.Writable + takeScreenshots(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand + thumbnail(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand + thumbnails(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand + screenshot(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand + screenshots(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand + mergeToFile(target: string | stream.Writable, options?: { end?: boolean }): FfmpegCommand + concatenate(target: string | stream.Writable, options?: { end?: boolean }): FfmpegCommand + concat(target: string | stream.Writable, options?: { end?: boolean }): FfmpegCommand + } + + function Ffmpeg(): FfmpegCommand + function Ffmpeg(options: FfmpegCommandOptions): FfmpegCommand + function Ffmpeg(input: string | stream.Readable, options: FfmpegCommandOptions): FfmpegCommand + + export = Ffmpeg +} diff --git a/form-data/form-data-tests.ts b/form-data/form-data-tests.ts index 641a368749..180986ed99 100644 --- a/form-data/form-data-tests.ts +++ b/form-data/form-data-tests.ts @@ -1,8 +1,135 @@ /// +/// +/// +/// +import FormData = require('form-data'); +import fs = require('fs'); +import http = require('http'); +import request = require('request'); -import formData = require('form-data'); +import * as ImportUsingES6Syntax from 'form-data'; -var value: any; -var fd = new formData.FormData(); -var obj: Object = fd.getHeaders(); -value = fd.pipe(value); +() => { + var form = new FormData(); + form.append('my_field', 'my value'); + form.append('my_buffer', new Buffer(10)); + form.append('my_file', fs.createReadStream('/foo/bar.jpg')); +} + +() => { + var form = new FormData(); + + http.request('http://nodejs.org/images/logo.png', function (response) { + form.append('my_field', 'my value'); + form.append('my_buffer', new Buffer(10)); + form.append('my_logo', response); + }); +} + +() => { + var form = new FormData(); + + form.append('my_field', 'my value'); + form.append('my_buffer', new Buffer(10)); + form.append('my_logo', request('http://nodejs.org/images/logo.png')); +} + +() => { + var form = new FormData(); + form.submit('http://example.org/', function (err, res) { + // res – response object (http.IncomingMessage) // + res.resume(); + }); +} + + +() => { + var form = new FormData(); + var request = http.request({ + method: 'post', + host: 'example.org', + path: '/upload', + headers: form.getHeaders() + }); + + form.pipe(request); + + request.on('response', function (res: any) { + console.log(res.statusCode); + }); +} + + +() => { + var form = new FormData(); + form.submit('example.org/upload', function (err, res) { + console.log(res.statusCode); + }); +} + +() => { + var CRLF = '\r\n'; + var form = new FormData(); + var buffer = new Buffer(''); + + var options = { + header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF, + knownLength: 1 + }; + + form.append('my_buffer', buffer, options); + + form.submit('http://example.com/', function (err, res) { + if (err) throw err; + console.log('Done'); + }); +} + +() => { + var form = new FormData(); + form.submit({ + host: 'example.com', + path: '/probably.php?extra=params', + auth: 'username:password' + }, function (err, res) { + console.log(res.statusCode); + }); +} + +() => { + var form = new FormData(); + form.submit({ + host: 'example.com', + path: '/surelynot.php', + headers: { 'x-test-header': 'test-header-value' } + }, function (err, res) { + console.log(res.statusCode); + }); +} + +() => { + var formData = { + my_field: 'my_value', + my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), + }; + + request.post({ url: 'http://service.com/upload', formData: formData }, function (err, httpResponse, body) { + if (err) { + return console.error('upload failed:', err); + } + console.log('Upload successful! Server responded with:', body); + }); +} + +() => { + var form = new FormData(); + + form.append('a', 1); + + fetch('http://example.com', { method: 'POST', body: form }) + .then(function (res) { + return res.json(); + }).then(function (json) { + console.log(json); + }); +} diff --git a/form-data/form-data.d.ts b/form-data/form-data.d.ts index f3a19b16f7..e285d774af 100644 --- a/form-data/form-data.d.ts +++ b/form-data/form-data.d.ts @@ -1,16 +1,25 @@ // Type definitions for form-data // Project: https://github.com/felixge/node-form-data -// Definitions by: Carlos Ballesteros Velasco +// Definitions by: Carlos Ballesteros Velasco , Leon Yu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Imported from: https://github.com/soywiz/typescript-node-definitions/form-data.d.ts declare module "form-data" { - export class FormData { - append(key: string, value: any, options?: any): FormData; - getHeaders(): Object; - // TODO expand pipe - pipe(to: any): any; - submit(params: string|Object, callback: (error: any, response: any) => void): any; - } -} + class FormData { + append(key: string, value: any, options?: any): void; + getHeaders(): FormData.Dictionary; + // TODO expand pipe + pipe(to: any): any; + submit(params: string | Object, callback: (error: any, response: any) => void): any; + getBoundary(): string; + } + + namespace FormData { + interface Dictionary { + [key: string]: T; + } + } + + export = FormData; +} \ No newline at end of file diff --git a/fs-extra/fs-extra.d.ts b/fs-extra/fs-extra.d.ts index 39656ce685..7061f08746 100644 --- a/fs-extra/fs-extra.d.ts +++ b/fs-extra/fs-extra.d.ts @@ -79,8 +79,9 @@ declare module "fs-extra" { export interface CopyOptions { clobber?: boolean preserveTimestamps?: boolean - dereference?: boolean + dereference?: boolean filter?: CopyFilter + recursive?: boolean } export interface OpenOptions { diff --git a/fullCalendar/fullCalendar.d.ts b/fullCalendar/fullCalendar.d.ts index 65df012185..81ce91d119 100644 --- a/fullCalendar/fullCalendar.d.ts +++ b/fullCalendar/fullCalendar.d.ts @@ -25,15 +25,17 @@ declare namespace FullCalendar { end: moment.Moment; } + export interface Header { + left: string; + center: string; + right: string; + } + export interface Options extends AgendaOptions, EventDraggingResizingOptions, DroppingExternalElementsOptions, SelectionOptions { // General display - http://fullcalendar.io/docs/display/ - header?: { - left: string; - center: string; - right: string; - } - theme?: boolean + header?: boolean | Header; + theme?: boolean; buttonIcons?: { prev: string; next: string; @@ -50,7 +52,7 @@ declare namespace FullCalendar { contentHeight?: number; aspectRatio?: number; handleWindowResize?: boolean; - views?: ViewSpecificOptions; + views?: ViewSpecificOptions; viewRender?: (view: ViewObject, element: JQuery) => void; viewDestroy?: (view: ViewObject, element: JQuery) => void; dayRender?: (date: Date, cell: HTMLTableDataCellElement) => void; @@ -318,7 +320,7 @@ interface JQuery { /** * Moves the calendar to an arbitrary date. */ - fullCalendar(method: 'gotoDate', date: Date | string): void; + fullCalendar(method: 'gotoDate', date: moment.Moment | Date | string): void; /** * Moves the calendar forward/backward an arbitrary amount of time. @@ -403,4 +405,4 @@ interface JQuery { interface JQueryStatic { fullCalendar: FullCalendar.Calendar; -} \ No newline at end of file +} diff --git a/geojson2osm/geojson2osm-tests.ts b/geojson2osm/geojson2osm-tests.ts new file mode 100644 index 0000000000..c7bfc05b85 --- /dev/null +++ b/geojson2osm/geojson2osm-tests.ts @@ -0,0 +1,47 @@ +/// +/// + +import { geojson2osm } from 'geojson2osm' + +const features: GeoJSON.FeatureCollection = { + type: 'FeatureCollection', + features: [{ + type: 'Feature', + properties: { + 'building:colour': '#9F8169', + 'building:levels': 21, + building: 'yes', + height: 57, + }, + geometry: { + type: 'Polygon', + coordinates: [ + [ + [ + -434.2249470949173, + -13.15996269397843, + ], + [ + -434.2249470949173, + -13.159751140560356, + ], + [ + -434.2242631316185, + -13.159751140560356, + ], + [ + -434.2242631316185, + -13.15996269397843, + ], + [ + -434.2249470949173, + -13.15996269397843, + ], + ], + ], + }, + }, + ], +} + +geojson2osm(features) diff --git a/geojson2osm/geojson2osm.d.ts b/geojson2osm/geojson2osm.d.ts new file mode 100644 index 0000000000..58393411f1 --- /dev/null +++ b/geojson2osm/geojson2osm.d.ts @@ -0,0 +1,15 @@ +// Type definitions for geojson2osm 0.0.5 +// Project: https://github.com/Rub21/geojson2osm +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'geojson2osm' { + /** + * Converts GeoJSON features to OpenStreetMap XML. + * @param features Input features + * @returns OpenStreetMap XML + */ + export function geojson2osm(features: GeoJSON.Feature | GeoJSON.FeatureCollection): any +} diff --git a/get-port/get-port-tests.ts b/get-port/get-port-tests.ts new file mode 100644 index 0000000000..d414742230 --- /dev/null +++ b/get-port/get-port-tests.ts @@ -0,0 +1,7 @@ +/// + +import * as getPort from "get-port"; + +getPort().then(port => { + console.log(port); +}); diff --git a/get-port/get-port.d.ts b/get-port/get-port.d.ts new file mode 100644 index 0000000000..673c547f1c --- /dev/null +++ b/get-port/get-port.d.ts @@ -0,0 +1,9 @@ +// Type definitions for ajv +// Project: https://github.com/sindresorhus/get-port +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "get-port" { + var getPort: () => PromiseLike + export = getPort; +} diff --git a/github-electron/electron-prebuilt-tests.ts b/github-electron/electron-tests.ts similarity index 56% rename from github-electron/electron-prebuilt-tests.ts rename to github-electron/electron-tests.ts index 771fd06016..00b34d60b1 100644 --- a/github-electron/electron-prebuilt-tests.ts +++ b/github-electron/electron-tests.ts @@ -1,7 +1,7 @@ -/// +/// /// -import electron = require('electron-prebuilt'); +import electron = require('electron'); import child_process = require('child_process'); child_process.spawn(electron); diff --git a/github-electron/electron-prebuilt.d.ts b/github-electron/electron.d.ts similarity index 53% rename from github-electron/electron-prebuilt.d.ts rename to github-electron/electron.d.ts index d6b6dffc0e..5e331b3e47 100644 --- a/github-electron/electron-prebuilt.d.ts +++ b/github-electron/electron.d.ts @@ -1,9 +1,9 @@ -// Type definitions for electron-prebuilt 0.30.1 -// Project: https://github.com/mafintosh/electron-prebuilt +// Type definitions for electron 1.3.3 +// Project: https://github.com/electron-userland/electron-prebuilt // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'electron-prebuilt' { +declare module 'electron' { var electron: string; export = electron; } diff --git a/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts index 9a75f9699e..966465ed3a 100644 --- a/github-electron/github-electron-main-tests.ts +++ b/github-electron/github-electron-main-tests.ts @@ -20,7 +20,7 @@ import { shell, session, systemPreferences, - hideInternalModules + webContents } from 'electron'; import * as path from 'path'; @@ -96,6 +96,7 @@ app.on('ready', () => { mainWindow.webContents.executeJavaScript('return true;', true); mainWindow.webContents.executeJavaScript('return true;', true, (result: boolean) => console.log(result)); mainWindow.webContents.insertText('blah, blah, blah'); + mainWindow.webContents.startDrag({file: '/path/to/img.png', icon: nativeImage.createFromPath('/path/to/icon.png')}); mainWindow.webContents.findInPage('blah'); mainWindow.webContents.findInPage('blah', { forward: true, @@ -133,6 +134,12 @@ app.on('ready', () => { }); mainWindow.webContents.debugger.sendCommand("Network.enable"); + mainWindow.webContents.capturePage(image => { + console.log(image.toDataURL()); + }); + mainWindow.webContents.capturePage({x: 0, y: 0, width: 100, height: 200}, image => { + console.log(image.toPNG()); + }); }); app.commandLine.appendSwitch('enable-web-bluetooth'); @@ -220,6 +227,7 @@ app.dock.setBadge('foo'); var id = app.dock.bounce('informational'); app.dock.cancelBounce(id); app.dock.setIcon('/path/to/icon.png'); +app.dock.setBadgeCount(app.dock.getBadgeCount() + 1); app.setUserTasks([ { @@ -233,6 +241,69 @@ app.setUserTasks([ ]); app.setUserTasks([]); +app.setJumpList([ + { + type: 'custom', + name: 'Recent Projects', + items: [ + { type: 'file', path: 'C:\\Projects\\project1.proj' }, + { type: 'file', path: 'C:\\Projects\\project2.proj' } + ] + }, + { // has a name so type is assumed to be "custom" + name: 'Tools', + items: [ + { + type: 'task', + title: 'Tool A', + program: process.execPath, + args: '--run-tool-a', + iconPath: process.execPath, + iconIndex: 0, + description: 'Runs Tool A' + }, + { + type: 'task', + title: 'Tool B', + program: process.execPath, + args: '--run-tool-b', + iconPath: process.execPath, + iconIndex: 0, + description: 'Runs Tool B' + }] + }, + { + type: 'frequent' + }, + { // has no name and no type so type is assumed to be "tasks" + items: [ + { + type: 'task', + title: 'New Project', + program: process.execPath, + args: '--new-project', + description: 'Create a new project.' + }, + { + type: 'separator' + }, + { + type: 'task', + title: 'Recover Project', + program: process.execPath, + args: '--recover-project', + description: 'Recover Project' + }] + } +]); + +if (app.isUnityRunning()) { +} +if (app.isAccessibilitySupportEnabled()) { +} +app.setLoginItemSettings({openAtLogin: true, openAsHidden: false}); +console.log(app.getLoginItemSettings().wasOpenedAtLogin); + var window = new BrowserWindow(); window.setProgressBar(0.5); window.setRepresentedFilename('/etc/passwd'); @@ -247,6 +318,7 @@ app.on('ready', () => { onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false }); onlineStatusWindow.loadURL(`file://${__dirname}/online-status.html`); }); +app.on('accessibility-support-changed', (_, enabled) => console.log('accessibility: ' + enabled)); ipcMain.on('online-status-changed', (event: any, status: any) => { console.log(status); @@ -269,7 +341,6 @@ app.on('ready', () => { app.commandLine.appendSwitch('remote-debugging-port', '8315'); app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1'); -app.commandLine.appendSwitch('v', -1); app.commandLine.appendSwitch('vmodule', 'console=0'); // systemPreferences @@ -429,6 +500,14 @@ ipcMain.on('synchronous-message', (event: Electron.IpcMainEvent, arg: any) => { event.returnValue = 'pong'; }); +var winWindows = new BrowserWindow({ + width: 800, + height: 600, + show: false, + thickFrame: false, + type: 'toolbar', +}); + // menu-item // https://github.com/atom/electron/blob/master/docs/api/menu-item.md @@ -555,6 +634,42 @@ var template = [ focusedWindow.webContents.toggleDevTools(); } } + }, + { + type: 'separator' + }, + { + label: 'Actual Size', + accelerator: 'CmdOrCtrl+0', + click: (item, focusedWindow) => { + if (focusedWindow) { + focusedWindow.webContents.setZoomLevel(0) + } + } + }, + { + label: 'Zoom In', + accelerator: 'CmdOrCtrl+Plus', + click: (item, focusedWindow) => { + if (focusedWindow) { + const { webContents } = focusedWindow; + webContents.getZoomLevel((zoomLevel) => { + webContents.setZoomLevel(zoomLevel + 0.5) + }); + } + } + }, + { + label: 'Zoom Out', + accelerator: 'CmdOrCtrl+-', + click: (item, focusedWindow) => { + if (focusedWindow) { + const { webContents } = focusedWindow; + webContents.getZoomLevel((zoomLevel) => { + webContents.setZoomLevel(zoomLevel - 0.5) + }); + } + } } ] }, @@ -700,8 +815,11 @@ app.on('ready', () => { clipboard.writeText('Example String'); clipboard.writeText('Example String', 'selection'); +clipboard.writeBookmark('foo', 'http://example.com'); +clipboard.writeBookmark('foo', 'http://example.com', 'selection'); console.log(clipboard.readText('selection')); console.log(clipboard.availableFormats()); +console.log(clipboard.readBookmark().title); clipboard.clear(); clipboard.write({ @@ -740,6 +858,8 @@ let image2 = nativeImage.createFromPath('/Users/somebody/images/icon.png'); // process // https://github.com/electron/electron/blob/master/docs/api/process.md +console.log(process.versions.electron); +console.log(process.versions.chrome); console.log(process.type); console.log(process.resourcesPath); console.log(process.mas); @@ -800,6 +920,8 @@ shell.openExternal('https://github.com', { shell.beep(); +shell.writeShortcutLink('/home/user/Desktop/shortcut.lnk', 'update', shell.readShortcutLink('/home/user/Desktop/shortcut.lnk')); + // session // https://github.com/atom/electron/blob/master/docs/api/session.md @@ -833,6 +955,7 @@ session.defaultSession.cookies.set(cookie, (error) => { session.defaultSession.on('will-download', (event, item, webContents) => { // Set the save path, making Electron not to prompt a save dialog. item.setSavePath('/tmp/save.pdf'); + console.log(item.getSavePath()); console.log(item.getMimeType()); console.log(item.getFilename()); console.log(item.getTotalBytes()); @@ -913,3 +1036,21 @@ app.on('ready', function () { } }) }); + +// webContents +// https://github.com/electron/electron/blob/master/docs/api/web-contents.md + +console.log(webContents.getAllWebContents()); +console.log(webContents.getFocusedWebContents()); + +var win = new BrowserWindow({ + webPreferences: { + offscreen: true + } +}); + +win.webContents.on('paint', (event, dirty, image) => { + console.log(dirty, image.getBitmap()); +}); + +win.loadURL('http://github.com'); diff --git a/github-electron/github-electron-renderer-tests.ts b/github-electron/github-electron-renderer-tests.ts index eecec65752..b7292e3ac5 100644 --- a/github-electron/github-electron-renderer-tests.ts +++ b/github-electron/github-electron-renderer-tests.ts @@ -250,6 +250,7 @@ webview.addEventListener('ipc-message', function(event) { console.log(event.channel); // Prints "pong" }); webview.send('ping'); +webview.capturePage((image) => { console.log(image); }); // In guest page. ipcRenderer.on('ping', function() { diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index b5cd642811..64b7cf6a02 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v1.2.5 +// Type definitions for Electron v1.3.6 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,7 +7,7 @@ declare namespace Electron { - class EventEmitter implements NodeJS.EventEmitter { + class EventEmitter extends NodeJS.EventEmitter { addListener(event: string, listener: Function): this; on(event: string, listener: Function): this; once(event: string, listener: Function): this; @@ -25,6 +25,23 @@ declare namespace Electron { sender: EventEmitter; } + type Point = { + x: number; + y: number; + } + + type Size = { + width: number; + height: number; + } + + type Rectangle = { + x: number; + y: number; + width: number; + height: number; + } + // https://github.com/electron/electron/blob/master/docs/api/app.md /** @@ -45,7 +62,7 @@ declare namespace Electron { /** * Emitted when Electron has finished initialization. */ - on(event: 'ready', listener: Function): this; + on(event: 'ready', listener: (event: Event, launchInfo: Object) => void): this; /** * Emitted when all windows have been closed. * @@ -160,6 +177,12 @@ declare namespace Electron { * Emitted when the gpu process crashes. */ on(event: 'gpu-process-crashed', listener: Function): this; + /** + * Emitted when Chrome's accessibility support changes. + * + * Note: This API is only available on macOS and Windows. + */ + on(event: 'accessibility-support-changed', listener: (event: Event, accessibilitySupportEnabled: boolean) => void): this; on(event: string, listener: Function): this; /** * Try to close all windows. The before-quit event will first be emitted. @@ -176,7 +199,7 @@ declare namespace Electron { * All windows will be closed immediately without asking user * and the before-quit and will-quit events will not be emitted. */ - exit(exitCode: number): void; + exit(exitCode?: number): void; /** * Relaunches the app when current instance exits. * @@ -195,6 +218,10 @@ declare namespace Electron { args?: string[], execPath?: string }): void; + /** + * @returns Whether Electron has finished initializing. + */ + isReady(): boolean; /** * On Linux, focuses on the first visible window. * On macOS, makes the application the active app. @@ -273,28 +300,56 @@ declare namespace Electron { * Once registered, all links with your-protocol:// will be opened with the current executable. * The whole link, including protocol, will be passed to your application as a parameter. * + * On Windows you can provide optional parameters path, the path to your executable, + * and args, an array of arguments to be passed to your executable when it launches. + * + * @param protocol The name of your protocol, without ://. + * @param path Defaults to process.execPath. + * @param args Defaults to an empty array. + * * Note: This is only implemented on macOS and Windows. * On macOS, you can only register protocols that have been added to your app's info.plist. */ - setAsDefaultProtocolClient(protocol: string): void; + setAsDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean; /** * Removes the current executable as the default handler for a protocol (aka URI scheme). * + * @param protocol The name of your protocol, without ://. + * @param path Defaults to process.execPath. + * @param args Defaults to an empty array. + * * Note: This is only implemented on macOS and Windows. */ - removeAsDefaultProtocolClient(protocol: string): void; + removeAsDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean; /** + * @param protocol The name of your protocol, without ://. + * @param path Defaults to process.execPath. + * @param args Defaults to an empty array. + * * @returns Whether the current executable is the default handler for a protocol (aka URI scheme). * * Note: This is only implemented on macOS and Windows. */ - isDefaultProtocolClient(protocol: string): boolean; + isDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean; /** * Adds tasks to the Tasks category of JumpList on Windows. * * Note: This API is only available on Windows. */ - setUserTasks(tasks: Task[]): void; + setUserTasks(tasks: Task[]): boolean; + /** + * Note: This API is only available on Windows. + */ + getJumpListSettings(): JumpListSettings; + /** + * Sets or removes a custom Jump List for the application. + * + * If categories is null the previously set custom Jump List (if any) will be replaced + * by the standard Jump List for the app (managed by Windows). + * + * Note: This API is only available on Windows. + */ + setJumpList(categories: JumpListCategory[]): SetJumpListResult; /** * This method makes your application a Single Instance Application instead of allowing * multiple instances of your app to run, this will ensure that only a single instance @@ -326,6 +381,8 @@ declare namespace Electron { getCurrentActivityType(): string; /** * Changes the Application User Model ID to id. + * + * Note: This is only implemented on Windows. */ setAppUserModelId(id: string): void; /** @@ -341,6 +398,33 @@ declare namespace Electron { * This method can only be called before app is ready. */ disableHardwareAcceleration(): void; + /** + * @returns whether current desktop environment is Unity launcher. (Linux) + * + * Note: This API is only available on Linux. + */ + isUnityRunning(): boolean; + /** + * Returns a Boolean, true if Chrome's accessibility support is enabled, false otherwise. + * This API will return true if the use of assistive technologies, such as screen readers, + * has been detected. + * See https://www.chromium.org/developers/design-documents/accessibility for more details. + * + * Note: This API is only available on macOS and Windows. + */ + isAccessibilitySupportEnabled(): boolean; + /** + * @returns an Object with the login item settings of the app. + * + * Note: This API is only available on macOS and Windows. + */ + getLoginItemSettings(): LoginItemSettings; + /** + * Set the app's login item settings. + * + * Note: This API is only available on macOS and Windows. + */ + setLoginItemSettings(settings: LoginItemSettings): void; commandLine: CommandLine; /** * Note: This API is only available on macOS. @@ -368,7 +452,7 @@ declare namespace Electron { * Note: This will not affect process.argv, and is mainly used by developers * to control some low-level Chromium behaviors. */ - appendSwitch(_switch: string, value?: string|number): void; + appendSwitch(_switch: string, value?: string): void; /** * Append an argument to Chromium's command line. The argument will quoted properly. * @@ -414,6 +498,20 @@ declare namespace Electron { * Note: This API is only available on macOS. */ getBadge(): string; + /** + * Sets the counter badge for current app. Setting the count to 0 will hide the badge. + * + * @returns True when the call succeeded, otherwise returns false. + * + * Note: This API is only available on macOS and Linux. + */ + setBadgeCount(count: number): boolean; + /** + * @returns The current value displayed in the counter badge. + * + * Note: This API is only available on macOS and Linux. + */ + getBadgeCount(): number; /** * Hides the dock icon. * @@ -426,6 +524,13 @@ declare namespace Electron { * Note: This API is only available on macOS. */ show(): void; + /** + * @returns Whether the dock icon is visible. + * The app.dock.show() call is asynchronous so this method might not return true immediately after that call. + * + * Note: This API is only available on macOS. + */ + isVisible(): boolean; /** * Sets the application dock menu. * @@ -472,6 +577,115 @@ declare namespace Electron { iconIndex?: number; } + /** + * ok - Nothing went wrong. + * error - One or more errors occured, enable runtime logging to figure out the likely cause. + * invalidSeparatorError - An attempt was made to add a separator to a custom category in the Jump List. + * Separators are only allowed in the standard Tasks category. + * fileTypeRegistrationError - An attempt was made to add a file link to the Jump List + * for a file type the app isn't registered to handle. + * customCategoryAccessDeniedError - Custom categories can't be added to the Jump List + * due to user privacy or group policy settings. + */ + type SetJumpListResult = 'ok' | 'error' | 'invalidSeparatorError' | 'fileTypeRegistrationError' | 'customCategoryAccessDeniedError'; + + interface JumpListSettings { + /** + * The minimum number of items that will be shown in the Jump List. + */ + minItems: number; + /** + * Items that the user has explicitly removed from custom categories in the Jump List. + */ + removedItems: JumpListItem[]; + } + + interface JumpListCategory { + /** + * tasks - Items in this category will be placed into the standard Tasks category. + * frequent - Displays a list of files frequently opened by the app, the name of the category and its items are set by Windows. + * recent - Displays a list of files recently opened by the app, the name of the category and its items are set by Windows. + * custom - Displays tasks or file links, name must be set by the app. + */ + type?: 'tasks' | 'frequent' | 'recent' | 'custom'; + /** + * Must be set if type is custom, otherwise it should be omitted. + */ + name?: string; + /** + * Array of JumpListItem objects if type is tasks or custom, otherwise it should be omitted. + */ + items?: JumpListItem[]; + } + + interface JumpListItem { + /** + * task - A task will launch an app with specific arguments. + * separator - Can be used to separate items in the standard Tasks category. + * file - A file link will open a file using the app that created the Jump List. + */ + type: 'task' | 'separator' | 'file'; + /** + * Path of the file to open, should only be set if type is file. + */ + path?: string; + /** + * Path of the program to execute, usually you should specify process.execPath which opens the current program. + * Should only be set if type is task. + */ + program?: string; + /** + * The command line arguments when program is executed. Should only be set if type is task. + */ + args?: string; + /** + * The text to be displayed for the item in the Jump List. Should only be set if type is task. + */ + title?: string; + /** + * Description of the task (displayed in a tooltip). Should only be set if type is task. + */ + description?: string; + /** + * The absolute path to an icon to be displayed in a Jump List, which can be an arbitrary + * resource file that contains an icon (e.g. .ico, .exe, .dll). + * You can usually specify process.execPath to show the program icon. + */ + iconPath?: string; + /** + * The index of the icon in the resource file. If a resource file contains multiple icons + * this value can be used to specify the zero-based index of the icon that should be displayed + * for this task. If a resource file contains only one icon, this property should be set to zero. + */ + iconIndex?: number; + } + + interface LoginItemSettings { + /** + * True if the app is set to open at login. + */ + openAtLogin: boolean; + /** + * True if the app is set to open as hidden at login. This setting is only supported on macOS. + */ + openAsHidden: boolean; + /** + * True if the app was opened at login automatically. This setting is only supported on macOS. + */ + wasOpenedAtLogin?: boolean; + /** + * True if the app was opened as a hidden login item. This indicates that the app should not + * open any windows at startup. This setting is only supported on macOS. + */ + wasOpenedAsHidden?: boolean; + /** + * True if the app was opened as a login item that should restore the state from the previous session. + * This indicates that the app should restore the windows that were open the last time the app was closed. + * This setting is only supported on macOS. + */ + restoreState?: boolean; + } + // https://github.com/electron/electron/blob/master/docs/api/auto-updater.md /** @@ -504,6 +718,10 @@ declare namespace Electron { * Set the url and initialize the auto updater. */ setFeedURL(url: string, requestHeaders?: Headers): void; + /** + * @returns The current update feed URL. + */ + getFeedURL(): string; /** * Ask the server whether there is an update, you have to call setFeedURL * before using this API @@ -527,7 +745,7 @@ declare namespace Electron { * Emitted when the document changed its title, * calling event.preventDefault() would prevent the native window’s title to change. */ - on(event: 'page-title-updated', listener: (event: Event) => void): this; + on(event: 'page-title-updated', listener: (event: Event, title: string) => void): this; /** * Emitted when the window is going to be closed. It’s emitted before the beforeunload * and unload event of the DOM. Calling event.preventDefault() will cancel the close. @@ -629,6 +847,9 @@ declare namespace Electron { */ on(event: 'swipe', listener: (event: Event, direction: SwipeDirection) => void): this; on(event: string, listener: Function): this; + /** + * Creates a new BrowserWindow with native properties as set by the options. + */ constructor(options?: BrowserWindowOptions); /** * @returns All opened browser windows. @@ -703,6 +924,10 @@ declare namespace Electron { * @returns Whether the window is focused. */ isFocused(): boolean; + /** + * @returns Whether the window is destroyed. + */ + isDestroyed(): boolean; /** * Shows and gives focus to the window. */ @@ -764,7 +989,7 @@ declare namespace Electron { * * Note: This API is available only on macOS. */ - setAspectRatio(aspectRatio: number, extraSize?: Dimension): void; + setAspectRatio(aspectRatio: number, extraSize?: Size): void; /** * Resizes and moves the window to width, height, x, y. */ @@ -773,6 +998,14 @@ declare namespace Electron { * @returns The window's width, height, x and y values. */ getBounds(): Rectangle; + /** + * Resizes and moves the window's client area (e.g. the web page) to width, height, x, y. + */ + setContentBounds(options: Rectangle, animate?: boolean): void; + /** + * @returns The window's client area (e.g. the web page) width, height, x and y values. + */ + getContentBounds(): Rectangle; /** * Resizes the window to width and height. */ @@ -968,6 +1201,13 @@ declare namespace Electron { * @param callback Supplies the image that stores data of the snapshot. */ capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void; + /** + * Captures the snapshot of page within rect, upon completion the callback + * will be called. Omitting the rect would capture the whole visible page. + * Note: Be sure to read documents on remote buffer in remote if you are going + * to use this API in renderer process. + * @param callback Supplies the image that stores data of the snapshot. + */ capturePage(callback: (image: NativeImage) => void): void; /** * Same as webContents.loadURL(url). @@ -990,7 +1230,13 @@ declare namespace Electron { * @param progress Valid range is [0, 1.0]. If < 0, the progress bar is removed. * If greater than 0, it becomes indeterminate. */ - setProgressBar(progress: number): void; + setProgressBar(progress: number, options?: { + /** + * Mode for the progress bar. + * Note: This is only implemented on Windows. + */ + mode: 'none' | 'normal' | 'indeterminate' | 'error' | 'paused' + }): void; /** * Sets a 16px overlay onto the current Taskbar icon, usually used to convey * some sort of application status or to passively notify the user. @@ -1014,8 +1260,23 @@ declare namespace Electron { * Add a thumbnail toolbar with a specified set of buttons to the thumbnail image * of a window in a taskbar button layout. * @returns Whether the thumbnail has been added successfully. + * + * Note: This API is available only on Windows. */ setThumbarButtons(buttons: ThumbarButton[]): boolean; + /** + * Sets the region of the window to show as the thumbnail image displayed when hovering + * over the window in the taskbar. You can reset the thumbnail to be the entire window + * by specifying an empty region: {x: 0, y: 0, width: 0, height: 0}. + * + * Note: This API is available only on Windows. + */ + setThumbnailClip(region: Rectangle): boolean; + /** + * Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar. + * Note: This API is available only on Windows. + */ + setThumbnailToolTip(toolTip: string): boolean; /** * Same as webContents.showDefinitionForSelection(). * Note: This API is available only on macOS. @@ -1110,6 +1371,12 @@ declare namespace Electron { } interface WebPreferences { + /** + * Whether to enable DevTools. + * If it is set to false, can not use BrowserWindow.webContents.openDevTools() to open DevTools. + * Default: true. + */ + devTools?: boolean; /** * Whether node integration is enabled. * Default: true. @@ -1258,12 +1525,17 @@ declare namespace Electron { defaultEncoding?: string; /** * Whether to throttle animations and timers when the page becomes background. - * Default: true + * Default: true. */ backgroundThrottling?: boolean; + /** + * Whether to enable offscreen rendering for the browser window. + * Default: false. + */ + offscreen?: boolean; } - interface BrowserWindowOptions extends Rectangle { + interface BrowserWindowOptions { /** * Window’s width in pixels. * Default: 800. @@ -1458,22 +1730,20 @@ declare namespace Electron { * The style of window title bar. */ titleBarStyle?: 'default' | 'hidden' | 'hidden-inset'; + /** + * Use WS_THICKFRAME style for frameless windows on Windows + */ + thickFrame?: boolean; /** * Settings of web page’s features. */ webPreferences?: WebPreferences; } - type BrowserWindowType = BrowserWindowTypeLinux | BrowserWindowTypeMac; + type BrowserWindowType = BrowserWindowTypeLinux | BrowserWindowTypeMac | BrowserWindowTypeWindows; type BrowserWindowTypeLinux = 'desktop' | 'dock' | 'toolbar' | 'splash' | 'notification'; type BrowserWindowTypeMac = 'desktop' | 'textured'; - - interface Rectangle { - x?: number; - y?: number; - width?: number; - height?: number; - } + type BrowserWindowTypeWindows = 'toolbar'; // https://github.com/electron/electron/blob/master/docs/api/clipboard.md @@ -1541,10 +1811,27 @@ declare namespace Electron { html?: string; image?: NativeImage; }, type?: ClipboardType): void; + /** + * @returns An Object containing title and url keys representing the bookmark in the clipboard. + * + * Note: This API is available on macOS and Windows. + */ + readBookmark(): Bookmark; + /** + * Writes the title and url into the clipboard as a bookmark. + * + * Note: This API is available on macOS and Windows. + */ + writeBookmark(title: string, url: string, type?: ClipboardType): void; } type ClipboardType = '' | 'selection'; + interface Bookmark { + title: string; + url: string; + } + // https://github.com/electron/electron/blob/master/docs/api/content-tracing.md /** @@ -1680,7 +1967,7 @@ declare namespace Electron { interface CrashReporterStartOptions { /** - * Default: Electron + * Default: app.getName() */ productName?: string; companyName: string; @@ -1734,7 +2021,7 @@ declare namespace Electron { * The suggested size that thumbnail should be scaled. * Default: {width: 150, height: 150} */ - thumbnailSize?: Dimension; + thumbnailSize?: Size; } interface DesktopCapturerSource { @@ -1836,7 +2123,7 @@ declare namespace Electron { /** * Contains which features the dialog should use. */ - properties?: ('openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory')[]; + properties?: ('openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory' | 'showHiddenFiles')[]; } interface SaveDialogOptions { @@ -1920,6 +2207,11 @@ declare namespace Electron { * routine to determine the save path (Usually prompts a save dialog). */ setSavePath(path: string): void; + /** + * @returns The save path of the download item. + * This will be either the path set via downloadItem.setSavePath(path) or the path selected from the shown save dialog. + */ + getSavePath(): string; /** * Pauses the download. */ @@ -2125,8 +2417,8 @@ declare namespace Electron { } type MenuItemType = 'normal' | 'separator' | 'submenu' | 'checkbox' | 'radio'; - type MenuItemRole = 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'pasteandmatchstyle' | 'selectall' | 'delete' | 'minimize' | 'close' | 'quit' | 'togglefullscreen'; - type MenuItemRoleMac = 'about' | 'hide' | 'hideothers' | 'unhide' | 'front' | 'zoom' | 'window' | 'help' | 'services'; + type MenuItemRole = 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'pasteandmatchstyle' | 'selectall' | 'delete' | 'minimize' | 'close' | 'quit' | 'togglefullscreen' | 'resetzoom' | 'zoomin' | 'zoomout'; + type MenuItemRoleMac = 'about' | 'hide' | 'hideothers' | 'unhide' | 'startspeaking' | 'stopspeaking' | 'front' | 'zoom' | 'window' | 'help' | 'services'; interface MenuItemOptions { /** @@ -2309,13 +2601,25 @@ declare namespace Electron { */ static createFromDataURL(dataURL: string): NativeImage; /** - * @returns Buffer Contains the image's PNG encoded data. + * @returns Buffer that contains the image's PNG encoded data. */ toPNG(): Buffer; /** - * @returns Buffer Contains the image's JPEG encoded data. + * @returns Buffer that contains the image's JPEG encoded data. */ toJPEG(quality: number): Buffer; + /** + * @returns Buffer that contains a copy of the image's raw bitmap pixel data. + */ + toBitmap(): Buffer; + /** + * @returns Buffer that contains the image's raw bitmap pixel data. + * + * The difference between getBitmap() and toBitmap() is, getBitmap() does not copy the bitmap data, + * so you have to use the returned Buffer immediately in current event loop tick, + * otherwise the data might be changed or destroyed. + */ + getBitmap(): Buffer; /** * @returns string The data URL of the image. */ @@ -2333,7 +2637,7 @@ declare namespace Electron { /** * @returns {} The size of the image. */ - getSize(): Dimension; + getSize(): Size; /** * Marks the image as template image. */ @@ -2556,10 +2860,10 @@ declare namespace Electron { * Unique identifier associated with the display. */ id: number; - bounds: Bounds; - workArea: Bounds; - size: Dimension; - workAreaSize: Dimension; + bounds: Rectangle; + workArea: Rectangle; + size: Size; + workAreaSize: Size; /** * Output device’s pixel scale factor. */ @@ -2571,23 +2875,6 @@ declare namespace Electron { touchSupport: 'available' | 'unavailable' | 'unknown'; } - type Bounds = { - x: number; - y: number; - width: number; - height: number; - } - - type Dimension = { - width: number; - height: number; - } - - type Point = { - x: number; - y: number; - } - type DisplayMetrics = 'bounds' | 'workArea' | 'scaleFactor' | 'rotation'; /** @@ -2627,7 +2914,7 @@ declare namespace Electron { /** * @returns The display that most closely intersects the provided bounds. */ - getDisplayMatching(rect: Bounds): Display; + getDisplayMatching(rect: Rectangle): Display; } // https://github.com/electron/electron/blob/master/docs/api/session.md @@ -2641,7 +2928,7 @@ declare namespace Electron { /** * @returns a new Session instance from partition string. */ - static fromPartition(partition: string): Session; + static fromPartition(partition: string, options?: FromPartitionOptions): Session; /** * @returns the default session object of the app. */ @@ -2680,7 +2967,7 @@ declare namespace Electron { /** * Sets the proxy settings. */ - setProxy(config: string, callback: Function): void; + setProxy(config: ProxyConfig, callback: Function): void; /** * Resolves the proxy information for url. */ @@ -2741,6 +3028,13 @@ declare namespace Electron { type Permission = 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal'; + interface FromPartitionOptions { + /** + * Whether to enable cache. + */ + cache?: boolean; + } + interface ClearStorageDataOptions { /** * Should follow window.location.origin’s representation scheme://host:port. @@ -2756,21 +3050,40 @@ declare namespace Electron { quotas?: ('temporary' | 'persistent' | 'syncable')[]; } + interface ProxyConfig { + /** + * The URL associated with the PAC file. + */ + pacScript: string; + /** + * Rules indicating which proxies to use. + */ + proxyRules: string; + /** + * Rules indicating which URLs should bypass the proxy settings. + */ + proxyBypassRules: string; + } + interface NetworkEmulationOptions { /** * Whether to emulate network outage. + * Default: false. */ offline?: boolean; /** * RTT in ms. + * Default: 0, which will disable latency throttling. */ latency?: number; /** * Download rate in Bps. + * Default: 0, which will disable download throttling. */ downloadThroughput?: number; /** * Upload rate in Bps. + * Default: 0, which will disable upload throttling. */ uploadThroughput?: number; } @@ -3089,16 +3402,18 @@ declare namespace Electron { interface Shell { /** * Show the given file in a file manager. If possible, select the file. + * @returns Whether the item was successfully shown. */ - showItemInFolder(fullPath: string): void; + showItemInFolder(fullPath: string): boolean; /** * Open the given file in the desktop's default manner. + * @returns Whether the item was successfully shown. */ - openItem(fullPath: string): void; + openItem(fullPath: string): boolean; /** * Open the given external protocol URL in the desktop's default manner * (e.g., mailto: URLs in the default mail user agent). - * @returns true if an application was available to open the URL, false otherwise. + * @returns Whether an application was available to open the URL. */ openExternal(url: string, options?: { /** @@ -3109,13 +3424,69 @@ declare namespace Electron { }): boolean; /** * Move the given file to trash. - * @returns boolean status for the operation. + * @returns Whether the item was successfully moved to the trash. */ moveItemToTrash(fullPath: string): boolean; /** * Play the beep sound. */ beep(): void; + /** + * Creates or updates a shortcut link at shortcutPath. + * + * Note: This API is available only on Windows. + */ + writeShortcutLink(shortcutPath: string, options: ShortcutLinkOptions): boolean; + /** + * Creates or updates a shortcut link at shortcutPath. + * + * Note: This API is available only on Windows. + */ + writeShortcutLink(shortcutPath: string, operation: 'create' | 'update' | 'replace', options: ShortcutLinkOptions): boolean; + /** + * Resolves the shortcut link at shortcutPath. + * An exception will be thrown when any error happens. + * + * Note: This API is available only on Windows. + */ + readShortcutLink(shortcutPath: string): ShortcutLinkOptions; + } + + interface ShortcutLinkOptions { + /** + * The target to launch from this shortcut. + */ + target: string; + /** + * The working directory. + * Default: empty. + */ + cwd?: string; + /** + * The arguments to be applied to target when launching from this shortcut. + * Default: empty. + */ + args?: string; + /** + * The description of the shortcut. + * Default: empty. + */ + description?: string; + /** + * The path to the icon, can be a DLL or EXE. icon and iconIndex have to be set together. + * Default: empty, which uses the target's icon. + */ + icon?: string; + /** + * The resource ID of icon when icon is a DLL or EXE. + * Default: 0. + */ + iconIndex?: number; + /** + * The Application User Model ID. + * Default: empty. + */ + appUserModelId?: string; } // https://github.com/electron/electron/blob/master/docs/api/system-preferences.md @@ -3130,6 +3501,26 @@ declare namespace Electron { * Note: This is only implemented on macOS. */ isDarkMode(): boolean; + /** + * @returns If the Swipe between pages setting is on. + * + * Note: This is only implemented on macOS. + */ + isSwipeTrackingFromScrollEventsEnabled(): boolean; + /** + * Posts event as native notifications of macOS. + * The userInfo contains the user information dictionary sent along with the notification. + * + * Note: This is only implemented on macOS. + */ + postNotification(event: string, userInfo: Object): void; + /** + * Posts event as native notifications of macOS. + * The userInfo contains the user information dictionary sent along with the notification. + * + * Note: This is only implemented on macOS. + */ + postLocalNotification(event: string, userInfo: Object): void; /** * Subscribes to native notifications of macOS, callback will be called when the corresponding event happens. * The id of the subscriber is returned, which can be used to unsubscribe the event. @@ -3177,17 +3568,17 @@ declare namespace Electron { * Emitted when the tray icon is clicked. * Note: The bounds payload is only implemented on macOS and Windows. */ - on(event: 'click', listener: (modifiers: Modifiers, bounds: Bounds) => void): this; + on(event: 'click', listener: (modifiers: Modifiers, bounds: Rectangle) => void): this; /** * Emitted when the tray icon is right clicked. * Note: This is only implemented on macOS and Windows. */ - on(event: 'right-click', listener: (modifiers: Modifiers, bounds: Bounds) => void): this; + on(event: 'right-click', listener: (modifiers: Modifiers, bounds: Rectangle) => void): this; /** * Emitted when the tray icon is double clicked. * Note: This is only implemented on macOS and Windows. */ - on(event: 'double-click', listener: (modifiers: Modifiers, bounds: Bounds) => void): this; + on(event: 'double-click', listener: (modifiers: Modifiers, bounds: Rectangle) => void): this; /** * Emitted when the tray balloon shows. * Note: This is only implemented on Windows. @@ -3213,6 +3604,11 @@ declare namespace Electron { * Note: This is only implemented on macOS */ on(event: 'drop-files', listener: (event: Event, files: string[]) => void): this; + /** + * Emitted when dragged text is dropped in the tray icon. + * Note: This is only implemented on macOS + */ + on(event: 'drop-text', listener: (event: Event, text: string) => void): this; /** * Emitted when a drag operation enters the tray icon. * Note: This is only implemented on macOS @@ -3255,10 +3651,10 @@ declare namespace Electron { */ setTitle(title: string): void; /** - * Sets whether the tray icon is highlighted when it is clicked. + * Sets when the tray's icon background becomes highlighted. * Note: This is only implemented on macOS. */ - setHighlightMode(highlight: boolean): void; + setHighlightMode(mode: 'selection' | 'always' | 'never'): void; /** * Displays a tray balloon. * Note: This is only implemented on Windows. @@ -3282,7 +3678,7 @@ declare namespace Electron { /** * @returns The bounds of this tray icon. */ - getBounds(): Bounds; + getBounds(): Rectangle; } interface Modifiers { @@ -3292,8 +3688,35 @@ declare namespace Electron { metaKey: boolean; } + interface DragItem { + /** + * The absolute path of the file to be dragged + */ + file: string; + /** + * The image showing under the cursor when dragging. + */ + icon: NativeImage; + } + // https://github.com/electron/electron/blob/master/docs/api/web-contents.md + interface WebContentsStatic { + /** + * @returns An array of all WebContents instances. This will contain web contents for all windows, + * webviews, opened devtools, and devtools extension background pages. + */ + getAllWebContents(): WebContents[]; + /** + * @returns The web contents that is focused in this application, otherwise returns null. + */ + getFocusedWebContents(): WebContents; + /** + * Find a WebContents instance according to its ID. + */ + fromId(id: number): WebContents; + } + /** * A WebContents is responsible for rendering and controlling a web page. */ @@ -3395,7 +3818,7 @@ declare namespace Electron { * navigation outside of the page. Examples of this occurring are when anchor links * are clicked or when the DOM hashchange event is triggered. */ - on(event: 'did-navigate-in-page', listener: (event: Event, url: string) => void): this; + on(event: 'did-navigate-in-page', listener: (event: Event, url: string, isMainFrame: boolean) => void): this; /** * Emitted when the renderer process has crashed. */ @@ -3472,9 +3895,9 @@ declare namespace Electron { /** * Emitted when the cursor’s type changes. * If the type parameter is custom, the image parameter will hold the custom cursor image - * in a NativeImage, and the scale will hold scaling information for the image. + * in a NativeImage, and scale, size and hotspot will hold additional information about the custom cursor. */ - on(event: 'cursor-changed', listener: (event: Event, type: CursorType, image?: NativeImage, scale?: number) => void): this; + on(event: 'cursor-changed', listener: (event: Event, type: CursorType, image?: NativeImage, scale?: number, size?: Size, hotspot?: Point) => void): this; /** * Emitted when there is a new context menu that needs to be handled. */ @@ -3487,6 +3910,10 @@ declare namespace Electron { * passing empty string to callback will cancel the request. */ on(event: 'select-bluetooth-device', listener: (event: Event, deviceList: BluetoothDevice[], callback: (deviceId: string) => void) => void): this; + /** + * Emitted when a new frame is generated. Only the dirty area is passed in the buffer. + */ + on(event: 'paint', listener: (event: Event, dirtyRect: Rectangle, image: NativeImage) => void): this; on(event: string, listener: Function): this; /** * Loads the url in the window. @@ -3597,47 +4024,74 @@ declare namespace Electron { */ isAudioMuted(): boolean; /** - * Executes Edit -> Undo command in page. + * Changes the zoom factor to the specified factor. + * Zoom factor is zoom percent divided by 100, so 300% = 3.0. + */ + setZoomFactor(factor: number): void; + /** + * Sends a request to get current zoom factor. + */ + getZoomFactor(callback: (zoomFactor: number) => void): void; + /** + * Changes the zoom level to the specified level. + * The original size is 0 and each increment above or below represents + * zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. + */ + setZoomLevel(level: number): void; + /** + * Sends a request to get current zoom level. + */ + getZoomLevel(callback: (zoomLevel: number) => void): void; + /** + * Sets the maximum and minimum zoom level. + */ + setZoomLevelLimits(minimumLevel: number, maximumLevel: number): void; + /** + * Executes the editing command undo in web page. */ undo(): void; /** - * Executes Edit -> Redo command in page. + * Executes the editing command redo in web page. */ redo(): void; /** - * Executes Edit -> Cut command in page. + * Executes the editing command cut in web page. */ cut(): void; /** - * Executes Edit -> Copy command in page. + * Executes the editing command copy in web page. */ copy(): void; /** - * Executes Edit -> Paste command in page. + * Copy the image at the given position to the clipboard. + */ + copyImageAt(x: number, y: number): void; + /** + * Executes the editing command paste in web page. */ paste(): void; /** - * Executes Edit -> Paste and Match Style in page. + * Executes the editing command pasteAndMatchStyle in web page. */ pasteAndMatchStyle(): void; /** - * Executes Edit -> Delete command in page. + * Executes the editing command delete in web page. */ delete(): void; /** - * Executes Edit -> Select All command in page. + * Executes the editing command selectAll in web page. */ selectAll(): void; /** - * Executes Edit -> Unselect command in page. + * Executes the editing command unselect in web page. */ unselect(): void; /** - * Executes Edit -> Replace command in page. + * Executes the editing command replace in web page. */ replace(text: string): void; /** - * Executes Edit -> Replace Misspelling command in page. + * Executes the editing command replaceMisspelling in web page. */ replaceMisspelling(text: string): void; /** @@ -3739,16 +4193,12 @@ declare namespace Electron { * Begin subscribing for presentation events and captured frames, * The callback will be called when there is a presentation event. */ - beginFrameSubscription(callback: ( - /** - * The frameBuffer is a Buffer that contains raw pixel data. - * On most machines, the pixel data is effectively stored in 32bit BGRA format, - * but the actual representation depends on the endianness of the processor - * (most modern processors are little-endian, on machines with big-endian - * processors the data is in 32bit ARGB format). - */ - frameBuffer: Buffer - ) => void): void; + beginFrameSubscription(onlyDirty: boolean, callback: BeginFrameSubscriptionCallback): void; + /** + * Begin subscribing for presentation events and captured frames, + * The callback will be called when there is a presentation event. + */ + beginFrameSubscription(callback: BeginFrameSubscriptionCallback): void; /** * End subscribing for frame presentation events. */ @@ -3762,6 +4212,43 @@ declare namespace Electron { * Note: This API is available only on macOS. */ showDefinitionForSelection(): void; + /** + * @returns Whether offscreen rendering is enabled. + */ + isOffscreen(): boolean; + /** + * If offscreen rendering is enabled and not painting, start painting. + */ + startPainting(): void; + /** + * If offscreen rendering is enabled and painting, stop painting. + */ + stopPainting(): void; + /** + * If offscreen rendering is enabled returns whether it is currently painting. + */ + isPainting(): boolean; + /** + * If offscreen rendering is enabled sets the frame rate to the specified number. + * Only values between 1 and 60 are accepted. + */ + setFrameRate(fps: number): void; + /** + * If offscreen rendering is enabled returns the current frame rate. + */ + getFrameRate(): number; + /** + * Sets the item as dragging item for current drag-drop operation. + */ + startDrag(item: DragItem): void; + /** + * Captures a snapshot of the page within rect. + */ + capturePage(callback: (image: NativeImage) => void): void; + /** + * Captures a snapshot of the page within rect. + */ + capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void; /** * @returns The unique ID of this WebContents. */ @@ -3786,6 +4273,24 @@ declare namespace Electron { debugger: Debugger; } + interface BeginFrameSubscriptionCallback { + ( + /** + * The frameBuffer is a Buffer that contains raw pixel data. + * On most machines, the pixel data is effectively stored in 32bit BGRA format, + * but the actual representation depends on the endianness of the processor + * (most modern processors are little-endian, on machines with big-endian + * processors the data is in 32bit ARGB format). + */ + frameBuffer: Buffer, + /** + * The dirtyRect is an object with x, y, width, height properties that describes which part of the page was repainted. + * If onlyDirty is set to true, frameBuffer will only contain the repainted area. onlyDirty defaults to false. + */ + dirtyRect?: Rectangle + ): void + } + interface ContextMenuParams { /** * x coordinate @@ -3825,76 +4330,76 @@ declare namespace Electron { */ mediaFlags: { /** - * Wether the media element has crashed. + * Whether the media element has crashed. */ inError: boolean; /** - * Wether the media element is paused. + * Whether the media element is paused. */ isPaused: boolean; /** - * Wether the media element is muted. + * Whether the media element is muted. */ isMuted: boolean; /** - * Wether the media element has audio. + * Whether the media element has audio. */ hasAudio: boolean; /** - * Wether the media element is looping. + * Whether the media element is looping. */ isLooping: boolean; /** - * Wether the media element's controls are visible. + * Whether the media element's controls are visible. */ isControlsVisible: boolean; /** - * Wether the media element's controls are toggleable. + * Whether the media element's controls are toggleable. */ canToggleControls: boolean; /** - * Wether the media element can be rotated. + * Whether the media element can be rotated. */ canRotate: boolean; } /** - * Wether the context menu was invoked on an image which has non-empty contents. + * Whether the context menu was invoked on an image which has non-empty contents. */ hasImageContents: boolean; /** - * Wether the context is editable. + * Whether the context is editable. */ isEditable: boolean; /** - * These flags indicate wether the renderer believes it is able to perform the corresponding action. + * These flags indicate whether the renderer believes it is able to perform the corresponding action. */ editFlags: { /** - * Wether the renderer believes it can undo. + * Whether the renderer believes it can undo. */ canUndo: boolean; /** - * Wether the renderer believes it can redo. + * Whether the renderer believes it can redo. */ canRedo: boolean; /** - * Wether the renderer believes it can cut. + * Whether the renderer believes it can cut. */ canCut: boolean; /** - * Wether the renderer believes it can copy + * Whether the renderer believes it can copy */ canCopy: boolean; /** - * Wether the renderer believes it can paste. + * Whether the renderer believes it can paste. */ canPaste: boolean; /** - * Wether the renderer believes it can delete. + * Whether the renderer believes it can delete. */ canDelete: boolean; /** - * Wether the renderer believes it can select all. + * Whether the renderer believes it can select all. */ canSelectAll: boolean; } @@ -3986,7 +4491,7 @@ declare namespace Electron { * Specify page size of the generated PDF. * Default: A4. */ - pageSize?: 'A3' | 'A4' | 'A5' | 'Legal' | 'Letter' | 'Tabloid' | Dimension; + pageSize?: 'A3' | 'A4' | 'A5' | 'Legal' | 'Letter' | 'Tabloid' | Size; /** * Whether to print CSS backgrounds. * Default: false. @@ -4006,10 +4511,33 @@ declare namespace Electron { interface Certificate { /** - * PEM encoded data + * PEM encoded data. + */ + data: string; + /** + * Issuer's Common Name. */ - data: Buffer; issuerName: string; + /** + * Subject's Common Name. + */ + subjectName: string; + /** + * Hex value represented string. + */ + serialNumber: string; + /** + * Start date of the certificate being valid in seconds. + */ + validStart: number; + /** + * End date of the certificate being valid in seconds. + */ + validExpiry: number; + /** + * Fingerprint of the certificate. + */ + fingerprint: string; } interface LoginRequest { @@ -4068,7 +4596,7 @@ declare namespace Electron { /** * Coordinates of first match region. */ - selectionArea?: Bounds; + selectionArea?: Rectangle; } interface DeviceEmulationParameters { @@ -4080,7 +4608,7 @@ declare namespace Electron { /** * Set the emulated screen size (screenPosition == mobile) */ - screenSize?: Dimension; + screenSize?: Size; /** * Position the view on the screen (screenPosition == mobile) * Default: {x: 0, y: 0} @@ -4094,7 +4622,7 @@ declare namespace Electron { /** * Set the emulated view size (empty means no override). */ - viewSize?: Dimension; + viewSize?: Size; /** * Whether emulated view should be scaled down if necessary to fit into available space * Default: false @@ -4139,7 +4667,7 @@ declare namespace Electron { wheelTicksY?: number; accelerationRatioX?: number; accelerationRatioY?: number; - hasPreciseScrollingDeltas?: number; + hasPreciseScrollingDeltas?: boolean; canScroll?: boolean; } @@ -4365,6 +4893,14 @@ declare namespace Electron { * @returns The title of guest page. */ getTitle(): string; + /** + * @returns Whether the web page is destroyed. + */ + isDestroyed(): boolean; + /** + * @returns Whether the web page is focused. + */ + isFocused(): boolean; /** * @returns Whether guest page is still loading resources. */ @@ -4416,7 +4952,7 @@ declare namespace Electron { /** * Navigates to the specified offset from the "current entry". */ - goToOffset(offset: boolean): void; + goToOffset(offset: number): void; /** * @returns Whether the renderer process has crashed. */ @@ -4547,6 +5083,17 @@ declare namespace Electron { * See webContents.sendInputEvent for detailed description of event object. */ sendInputEvent(event: SendInputEvent): void + /** + * Changes the zoom factor to the specified factor. + * Zoom factor is zoom percent divided by 100, so 300% = 3.0. + */ + setZoomFactor(factor: number): void; + /** + * Changes the zoom level to the specified level. + * The original size is 0 and each increment above or below represents + * zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. + */ + setZoomLevel(level: number): void; /** * Shows pop-up dictionary that searches the selected word on the page. * Note: This API is available only on macOS. @@ -4556,6 +5103,14 @@ declare namespace Electron { * @returns The WebContents associated with this webview. */ getWebContents(): WebContents; + /** + * Captures a snapshot of the webview's page. Same as webContents.capturePage([rect, ]callback). + */ + capturePage(callback: (image: NativeImage) => void): void; + /** + * Captures a snapshot of the webview's page. Same as webContents.capturePage([rect, ]callback). + */ + capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void; /** * Fired when a load has committed. This includes navigation within the current document * as well as subframe document-level loads, but does not include asynchronous resource loads. @@ -4634,14 +5189,14 @@ declare namespace Electron { * * Calling event.preventDefault() does NOT have any effect. */ - addEventListener(type: 'will-navigate', listener: (event: WebViewElement.NavigateEvent) => void, useCapture?: boolean): void; + addEventListener(type: 'will-navigate', listener: (event: WebViewElement.WillNavigateEvent) => void, useCapture?: boolean): void; /** * Emitted when a navigation is done. * * This event is not emitted for in-page navigations, such as clicking anchor links * or updating the window.location.hash. Use did-navigate-in-page event for this purpose. */ - addEventListener(type: 'did-navigate', listener: (event: WebViewElement.NavigateEvent) => void, useCapture?: boolean): void; + addEventListener(type: 'did-navigate', listener: (event: WebViewElement.DidNavigateEvent) => void, useCapture?: boolean): void; /** * Emitted when an in-page navigation happened. * @@ -4649,7 +5204,7 @@ declare namespace Electron { * navigation outside of the page. Examples of this occurring are when anchor links * are clicked or when the DOM hashchange event is triggered. */ - addEventListener(type: 'did-navigate-in-page', listener: (event: WebViewElement.NavigateEvent) => void, useCapture?: boolean): void; + addEventListener(type: 'did-navigate-in-page', listener: (event: WebViewElement.DidNavigateInPageEvent) => void, useCapture?: boolean): void; /** * Fired when the guest page attempts to close itself. */ @@ -4773,10 +5328,19 @@ declare namespace Electron { options: BrowserWindowOptions; } - interface NavigateEvent extends Event { + interface WillNavigateEvent extends Event { url: string; } + interface DidNavigateEvent extends Event { + url: string; + } + + interface DidNavigateInPageEvent extends Event { + url: string; + isMainFrame: boolean; + } + interface IpcMessageEvent extends Event { channel: string; args: any[]; @@ -4856,7 +5420,7 @@ declare namespace Electron { session: typeof Electron.Session; systemPreferences: Electron.SystemPreferences; Tray: Electron.Tray; - hideInternalModules(): void; + webContents: Electron.WebContentsStatic; } interface ElectronMainAndRenderer extends CommonElectron { @@ -4896,6 +5460,18 @@ interface File { // https://github.com/electron/electron/blob/master/docs/api/process.md declare namespace NodeJS { + + interface ProcessVersions { + /** + * Electron's version string. + */ + electron: string; + /** + * Chrome's version string. + */ + chrome: string; + } + interface Process { /** * Setting this to true can disable the support for asar archives in Node's built-in modules. diff --git a/gl-matrix/gl-matrix-legacy-tests.ts b/gl-matrix/gl-matrix-legacy-tests.ts new file mode 100644 index 0000000000..5cfa9a1c3a --- /dev/null +++ b/gl-matrix/gl-matrix-legacy-tests.ts @@ -0,0 +1,362 @@ +/// + +// common +var result: number = glMatrix.toRadian(180); + +var out: GLM.IArray; +var outVal: number; +var outStr: string; + +// vec2 +var vecA: GLM.IArray, vecB: GLM.IArray, matA: GLM.IArray; +var vecArray: GLM.IArray; + +vecA = [1, 2]; +vecB = new Float32Array([3, 4]); +out = [0, 0]; +matA = [1, 2, 3, 4, 5, 6]; +vecArray = [1, 2, 3, 4, 0, 0]; + +out = vec2.create(); +out = vec2.clone(vecA); +out = vec2.fromValues(1, 2); +out = vec2.copy(out, vecA); +out = vec2.set(out, 1, 2); +out = vec2.add(out, vecA, vecB); +out = vec2.subtract(out, vecA, vecB); +out = vec2.sub(out, vecA, vecB); +out = vec2.multiply(out, vecA, vecB); +out = vec2.mul(out, vecA, vecB); +out = vec2.divide(out, vecA, vecB); +out = vec2.div(out, vecA, vecB); +out = vec2.min(out, vecA, vecB); +out = vec2.max(out, vecA, vecB); +out = vec2.scale(out, vecA, 2); +out = vec2.scaleAndAdd(out, vecA, vecB, 0.5); +outVal = vec2.distance(vecA, vecB); +outVal = vec2.dist(vecA, vecB); +outVal = vec2.squaredDistance(vecA, vecB); +outVal = vec2.sqrDist(vecA, vecB); +outVal = vec2.length(vecA); +outVal = vec2.len(vecA); +outVal = vec2.squaredLength(vecA); +outVal = vec2.sqrLen(vecA); +out = vec2.negate(out, vecA); +out = vec2.inverse(out, vecA); +out = vec2.normalize(out, vecA); +outVal = vec2.dot(vecA, vecB); +out = vec2.cross(out, vecA, vecB); +out = vec2.lerp(out, vecA, vecB, 0.5); +out = vec2.random(out); +out = vec2.random(out, 5.0); +out = vec2.transformMat2(out, vecA, matA); +out = vec2.transformMat2d(out, vecA, matA); +out = vec2.transformMat3(out, vecA, matA); +out = vec2.transformMat4(out, vecA, matA); +out = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); +outStr = vec2.str(vecA); + +// vec3 +var matr: GLM.IArray; +var q: GLM.IArray; + +vecA = [1, 2, 3]; +vecB = new Float32Array([4, 5, 6]); +out = [0, 0, 0]; +vecArray = [1, 2, 3, 4, 5, 6, 0, 0, 0]; +matr = [1, 0, 0, 0, 1, 0, 0, 0, 1 ]; + +out = vec3.create(); +out = vec3.clone(vecA); +out = vec3.fromValues(1, 2, 3); +out = vec3.copy(out, vecA); +out = vec3.set(out, 1, 2, 3); +out = vec3.add(out, vecA, vecB); +out = vec3.subtract(out, vecA, vecB); +out = vec3.sub(out, vecA, vecB); +out = vec3.multiply(out, vecA, vecB); +out = vec3.mul(out, vecA, vecB); +out = vec3.divide(out, vecA, vecB); +out = vec3.div(out, vecA, vecB); +out = vec3.min(out, vecA, vecB); +out = vec3.max(out, vecA, vecB); +out = vec3.scale(out, vecA, 2); +out = vec3.scaleAndAdd(out, vecA, vecB, 0.5); +outVal = vec3.distance(vecA, vecB); +outVal = vec3.dist(vecA, vecB); +outVal = vec3.squaredDistance(vecA, vecB); +outVal = vec3.sqrDist(vecA, vecB); +outVal = vec3.length(vecA); +outVal = vec3.len(vecA); +outVal = vec3.squaredLength(vecA); +outVal = vec3.sqrLen(vecA); +out = vec3.negate(out, vecA); +out = vec3.inverse(out, vecA); +out = vec3.normalize(out, vecA); +outVal = vec3.dot(vecA, vecB); +out = vec3.cross(out, vecA, vecB); +out = vec3.lerp(out, vecA, vecB, 0.5); +out = vec3.random(out); +out = vec3.random(out, 5.0); +out = vec3.rotateX(out, vecA, vecB, Math.PI); +out = vec3.rotateY(out, vecA, vecB, Math.PI); +out = vec3.rotateZ(out, vecA, vecB, Math.PI); +out = vec3.transformMat3(out, vecA, matr); + +matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; +out = vec3.transformMat4(out, vecA, matr); + +q = [1, 2, 3, 4]; +out = vec3.transformQuat(out, vecA, matr); + +out = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); +outVal = vec3.angle(vecA, vecB); +outStr = vec3.str(vecA); + +// vec4 +var q: GLM.IArray; + +vecA = [1, 2, 3, 4]; +vecB = new Float32Array([5, 6, 7, 8]); +out = [0, 0, 0, 0]; +q = [1, 2, 3, 4]; + +out = vec4.create(); +out = vec4.clone(vecA); +out = vec4.fromValues(1, 2, 3, 4); +out = vec4.copy(out, vecA); +out = vec4.set(out, 1, 2, 3, 4); +out = vec4.add(out, vecA, vecB); +out = vec4.subtract(out, vecA, vecB); +out = vec4.sub(out, vecA, vecB); +out = vec4.multiply(out, vecA, vecB); +out = vec4.mul(out, vecA, vecB); +out = vec4.divide(out, vecA, vecB); +out = vec4.div(out, vecA, vecB); +out = vec4.min(out, vecA, vecB); +out = vec4.max(out, vecA, vecB); +out = vec4.scale(out, vecA, 2); +out = vec4.scaleAndAdd(out, vecA, vecB, 0.5); +outVal = vec4.distance(vecA, vecB); +outVal = vec4.dist(vecA, vecB); +outVal = vec4.squaredDistance(vecA, vecB); +outVal = vec4.sqrDist(vecA, vecB); +outVal = vec4.length(vecA); +outVal = vec4.len(vecA); +outVal = vec4.squaredLength(vecA); +outVal = vec4.sqrLen(vecA); +out = vec4.negate(out, vecA); +out = vec4.inverse(out, vecA); +out = vec4.normalize(out, vecA); +outVal = vec4.dot(vecA, vecB); +out = vec4.lerp(out, vecA, vecB, 0.5); +out = vec4.random(out); +out = vec4.random(out, 5.0); + +matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] +out = vec4.transformMat4(out, vecA, matr); +out = vec4.transformQuat(out, vecA, q); + +vecArray = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0]; +out = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); +outStr = vec4.str(vecA); + +// mat2 +var matB: GLM.IArray, identity: GLM.IArray; + +matA = [1, 2, 3, 4]; +matB = new Float32Array([5, 6, 7, 8]); +out = [0, 0, 0, 0]; +identity = [1, 0, 0, 1]; + +out = mat2.create(); +out = mat2.clone(matA); +out = mat2.copy(out, matA); +out = mat2.identity(out); +out = mat2.transpose(out, matA); +out = mat2.invert(out, matA); +out = mat2.adjoint(out, matA); +outVal = mat2.determinant(matA); +out = mat2.multiply(out, matA, matB); +out = mat2.mul(out, matA, matB); +out = mat2.rotate(out, matA, Math.PI * 0.5); + +vecA = [2, 3]; +out = mat2.scale(out, matA, vecA); +outStr = mat2.str(matA); +outVal = mat2.frob(matA); + +var L = mat2.create(); +var D = mat2.create(); +var U = mat2.create(); +out = mat2.LDU(L, D, U, [4,3,6,3]); + +// mat2d +matA = [1, 2, 3, 4, 5, 6]; +matB = [7, 8, 9, 10, 11, 12]; +out = [0, 0, 0, 0, 0, 0]; +identity = [1, 0, 0, 1, 0, 0]; + +out = mat2d.create(); +out = mat2d.clone(matA); +out = mat2d.copy(out, matA); +out = mat2d.identity(out); +out = mat2d.invert(out, matA); +outVal = mat2d.determinant(matA); +out = mat2d.multiply(out, matA, matB); +out = mat2d.mul(out, matA, matB); +out = mat2d.rotate(out, matA, Math.PI * 0.5); + +vecA = [2, 3]; +out = mat2d.scale(out, matA, vecA); +out = mat2d.translate(out, matA, vecA); +outStr = mat2d.str(matA); +outVal = mat2d.frob(matA); + +// mat3 +matA = [1, 0, 0, 0, 1, 0, 1, 2, 1]; +matB = [1, 0, 0, 0, 1, 0, 3, 4, 1]; +out = [0, 0, 0, 0, 0, 0, 0, 0, 0]; +identity = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + +out = mat3.create(); +out = mat3.clone(matA); +out = mat3.copy(out, matA); +out = mat3.identity(out); +out = mat3.transpose(out, matA); +out = mat3.invert(out, matA); +out = mat3.adjoint(out, matA); +outVal = mat3.determinant(matA); +out = mat3.multiply(out, matA, matB); +out = mat3.mul(out, matA, matB); +outStr = mat3.str(matA); +outVal = mat3.frob(matA); + +matA = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]; +out = mat3.normalFromMat4(out, matA); + +q = [ 0, -0.7071067811865475, 0, 0.7071067811865475 ]; +out = mat3.fromQuat(out, q); + +out = mat3.normalFromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); +out = mat3.fromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); +out = mat3.scale(out, matA, [2,2]); +out = mat3.fromMat2d(out, [1, 2, 3, 4, 5, 6]); + +out = mat3.translate(out, matA, [1, 2, 3]); +out = mat3.rotate(out, matA, Math.PI/2); + +// mat4 +matA = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 1, 2, 3, 1]; + +matB = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 4, 5, 6, 1]; + +out = [0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0]; + +identity = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]; + +out = mat4.create(); +out = mat4.clone(matA); +out = mat4.copy(out, matA); +out = mat4.identity(out); +out = mat4.transpose(out, matA); +out = mat4.invert(out, matA); +out = mat4.adjoint(out, matA); +outVal = mat4.determinant(matA); +out = mat4.multiply(out, matA, matB); +out = mat4.mul(out, matA, matB); +out = mat4.translate(out, matA, [4, 5, 6]); +out = mat4.scale(out, matA, [4, 5, 6]); + +var rad = Math.PI * 0.5; +var axis = [1, 0, 0]; +out = mat4.rotate(out, matA, rad, axis); +out = mat4.rotateX(out, matA, rad); +out = mat4.rotateY(out, matA, rad); +out = mat4.rotateZ(out, matA, rad); + +out = mat4.frustum(out, -1, 1, -1, 1, -1, 1); + +var fovy = Math.PI * 0.5; +out = mat4.perspective(out, fovy, 1, 0, 1); +out = mat4.ortho(out, -1, 1, -1, 1, -1, 1); + +var eye = [0, 0, 1]; +var center = [0, 0, -1]; +var up = [0, 1, 0]; +out = mat4.lookAt(out, eye, center, up); + +outStr = mat4.str(matA); +outVal = mat4.frob(matA); + +q = [0, 0, 0, 1]; +out = mat4.fromRotationTranslation(out, q, [1, 2, 3]); +out = mat4.fromQuat(out, q); + +q = [0, 0, 0, 1]; +out = mat4.fromRotationTranslationScale(out, q, [1, 2, 3], [1, 2, 3]); +out = mat4.fromQuat(out, q); + + +// quat +var quatA = [1, 2, 3, 4]; +var quatB = [5, 6, 7, 8]; +out = [0, 0, 0, 0]; +var vec = [1, 1, -1]; +var id = [0, 0, 0, 1]; +var deg90 = Math.PI / 2; + +out = quat.create(); +out = quat.clone(quatA); +out = quat.fromValues(1, 2, 3, 4); +out = quat.copy(out, quatA); +out = quat.set(out, 1, 2, 3, 4); +out = quat.identity(out); +out = quat.setAxisAngle(out, [1, 0, 0], Math.PI * 0.5); +out = quat.add(out, quatA, quatB); +out = quat.multiply(out, quatA, quatB); +out = quat.mul(out, quatA, quatB); +out = quat.scale(out, quatA, 2); +outVal = quat.length(quatA); +outVal = quat.len(quatA); +outVal = quat.squaredLength(quatA); +outVal = quat.sqrLen(quatA); +out = quat.normalize(out, quatA); +outVal = quat.dot(out, quatA, quatB); +out = quat.lerp(out, quatA, quatB, 0.5); +out = quat.slerp(out, quatA, quatB, 0.5); +out = quat.invert(out, quatA); +out = quat.conjugate(out, quatA); +outStr = quat.str(quatA); +out = quat.rotateX(out, id, deg90); +out = quat.rotateY(out, id, deg90); +out = quat.rotateZ(out, id, deg90); + +matr = [ 1, 0, 0, + 0, 0, -1, + 0, 1, 0 ]; +out = quat.fromMat3(out, matr); + +var view = [-1, 0, 0]; +up = [ 0, 1, 0]; +var right= [ 0, 0,-1]; +out = quat.setAxes([], view, right, up); + +out = quat.rotationTo(out, [0, 1, 0], [1, 0, 0]); +out = quat.calculateW(out, quatA); + diff --git a/gl-matrix/gl-matrix-legacy.d.ts b/gl-matrix/gl-matrix-legacy.d.ts new file mode 100644 index 0000000000..16366f263a --- /dev/null +++ b/gl-matrix/gl-matrix-legacy.d.ts @@ -0,0 +1,2163 @@ +// Type definitions for gl-matrix 2.2.2 +// Project: https://github.com/toji/gl-matrix +// Definitions by: Tat +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace GLM { + interface IArray + { + /** + * Must be indexable like an array + */ + [index: number]: number; + } +} + +// Common +declare namespace glMatrix { + /** + * Convert Degree To Radian + * + * @param a Angle in Degrees + */ + export function toRadian(a: number): number; +} + +// vec2 +declare namespace vec2 { + /** + * Creates a new, empty vec2 + * + * @returns a new 2D vector + */ + export function create(): GLM.IArray; + + /** + * Creates a new vec2 initialized with values from an existing vector + * + * @param a a vector to clone + * @returns a new 2D vector + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new vec2 initialized with the given values + * + * @param x X component + * @param y Y component + * @returns a new 2D vector + */ + export function fromValues(x: number, y: number): GLM.IArray; + + /** + * Copy the values from one vec2 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set the components of a vec2 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @returns out + */ + export function set(out: GLM.IArray, x: number, y: number): GLM.IArray; + + /** + * Adds two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the minimum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the maximum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Scales a vec2 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Adds two vec2's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function distance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function dist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Negates the components of a vec2 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns the inverse of the components of a vec2 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Normalize a vec2 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the dot product of two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + export function dot(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Computes the cross product of two vec2's + * Note that the cross product must by definition produce a 3D vector + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Performs a linear interpolation between two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + export function random(out: GLM.IArray): GLM.IArray; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + export function random(out: GLM.IArray, scale: number): GLM.IArray; + + /** + * Transforms the vec2 with a mat2 + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat2(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec2 with a mat2d + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat2d(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec2 with a mat3 + * 3rd vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec2 with a mat4 + * 3rd vector component is implicitly '0' + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + */ + export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + */ + export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + + /** + * Returns a string representation of a vector + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; +} + +// vec3 +declare namespace vec3 { + + /** + * Creates a new, empty vec3 + * + * @returns a new 3D vector + */ + export function create(): GLM.IArray; + + /** + * Creates a new vec3 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 3D vector + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new vec3 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @returns a new 3D vector + */ + export function fromValues(x: number, y: number, z: number): GLM.IArray; + + /** + * Copy the values from one vec3 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set the components of a vec3 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @returns out + */ + export function set(out: GLM.IArray, x: number, y: number, z: number): GLM.IArray; + + /** + * Adds two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the minimum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the maximum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Scales a vec3 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Adds two vec3's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function distance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function dist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Negates the components of a vec3 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns the inverse of the components of a vec3 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Normalize a vec3 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the dot product of two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + export function dot(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Computes the cross product of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Performs a linear interpolation between two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + export function random(out: GLM.IArray): GLM.IArray; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + export function random(out: GLM.IArray, scale: number): GLM.IArray; + + /** + * Rotate a 3D vector around the x-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + export function rotateX(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + + /** + * Rotate a 3D vector around the y-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + export function rotateY(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + + /** + * Rotate a 3D vector around the z-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + export function rotateZ(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + + /** + * Transforms the vec3 with a mat3. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m the 3x3 matrix to transform with + * @returns out + */ + export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec3 with a mat4. + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec3 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + export function transformQuat(out: GLM.IArray, a: GLM.IArray, q: GLM.IArray): GLM.IArray; + + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + + /** + * Get the angle between two 3D vectors + * @param a The first operand + * @param b The second operand + * @returns The angle in radians + */ + export function angle(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Returns a string representation of a vector + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; +} + +// vec4 +declare namespace vec4 { + + /** + * Creates a new, empty vec4 + * + * @returns a new 4D vector + */ + export function create(): GLM.IArray; + + /** + * Creates a new vec4 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 4D vector + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new vec4 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new 4D vector + */ + export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Copy the values from one vec4 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set the components of a vec4 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + */ + export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Adds two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the minimum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the maximum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Scales a vec4 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Adds two vec4's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function distance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function dist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Negates the components of a vec4 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns the inverse of the components of a vec4 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Normalize a vec4 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the dot product of two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + export function dot(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Performs a linear interpolation between two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + export function random(out: GLM.IArray): GLM.IArray; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + export function random(out: GLM.IArray, scale: number): GLM.IArray; + + /** + * Transforms the vec4 with a mat4. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat4(out: GLM.IArray, a: GLM.IArray, mat: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec4 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + export function transformQuat(out: GLM.IArray, a: GLM.IArray, quat: GLM.IArray): GLM.IArray; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param additional argument to pass to fn + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + callback: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + callback: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + + /** + * Returns a string representation of a vector + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; +} + +// mat2 +declare namespace mat2 { + + /** + * Creates a new identity mat2 + * + * @returns a new 2x2 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat2 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x2 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat2 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat2 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Transpose the values of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the adjugate of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat2 + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Rotates a mat2 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Scales the mat2 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat2 + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(a: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat2 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; + + /** + * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix + * @param L the lower triangular matrix + * @param D the diagonal matrix + * @param U the upper triangular matrix + * @param a the input matrix to factorize + */ + export function LDU(L: GLM.IArray, D: GLM.IArray, U: GLM.IArray, a: GLM.IArray): GLM.IArray; +} + +// mat2d +declare namespace mat2d { + + /** + * Creates a new identity mat2d + * + * @returns a new 2x3 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat2d initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x3 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat2d to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat2d to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat2d + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat2d + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Rotates a mat2d by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Scales the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Translates the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to translate the matrix by + * @returns out + **/ + export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat2d + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(a: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat2d + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; +} + +// mat3 +declare namespace mat3 { + + /** + * Creates a new identity mat3 + * + * @returns a new 3x3 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat3 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 3x3 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat3 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat3 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Transpose the values of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the adjugate of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat3 + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat3 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(mat: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat3 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; + + /** + * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix + * + * @param out mat3 receiving operation result + * @param a Mat4 to derive the normal matrix from + * + * @returns out + */ + export function normalFromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates a 3x3 matrix from the given quaternion + * + * @param out mat3 receiving operation result + * @param q Quaternion to create matrix from + * + * @returns out + */ + export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; + + /** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param out the receiving 3x3 matrix + * @param a the source 4x4 matrix + * @returns out + */ + export function fromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Copies the values from a mat2d into a mat3 + * + * @param out the receiving matrix + * @param {mat2d} a the matrix to copy + * @returns out + **/ + export function fromMat2d(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Translate a mat3 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Rotates a mat3 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; +} + +// mat4 +declare namespace mat4 { + + /** + * Creates a new identity mat4 + * + * @returns a new 4x4 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 4x4 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat4 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat4 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(a: GLM.IArray): GLM.IArray; + + /** + * Transpose the values of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the adjugate of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat4 + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Translate a mat4 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Scales the mat4 by the dimensions in the given vec3 + * + * @param out the receiving matrix + * @param a the matrix to scale + * @param v the vec3 to scale the matrix by + * @returns out + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Rotates a mat4 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @param axis the axis to rotate around + * @returns out + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number, axis: GLM.IArray): GLM.IArray; + + /** + * Rotates a matrix by the given angle around the X axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Rotates a matrix by the given angle around the Y axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Rotates a matrix by the given angle around the Z axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Generates a frustum matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + export function frustum(out: GLM.IArray, left: number, right: number, + bottom: number, top: number, near: number, far: number): GLM.IArray; + + /** + * Generates a perspective projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param fovy Vertical field of view in radians + * @param aspect Aspect ratio. typically viewport width/height + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + export function perspective(out: GLM.IArray, fovy: number, aspect: number, + near: number, far: number): GLM.IArray; + + /** + * Generates a orthogonal projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + export function ortho(out: GLM.IArray, left: number, right: number, + bottom: number, top: number, near: number, far: number): GLM.IArray; + + /** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param out mat4 frustum matrix will be written into + * @param eye Position of the viewer + * @param center Point the viewer is looking at + * @param up vec3 pointing up + * @returns out + */ + export function lookAt(out: GLM.IArray, eye: GLM.IArray, + center: GLM.IArray, up: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat4 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(mat: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat4 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; + + /** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @returns out + */ + export function fromRotationTranslation(out: GLM.IArray, q: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale. + * + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @param s Scale vector + * @returns out + */ + export function fromRotationTranslationScale(out: GLM.IArray, q: GLM.IArray, v: GLM.IArray, s: GLM.IArray): GLM.IArray + + /** + * Creates a matrix from a quaternion + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @returns out + */ + export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; +} + +// quat +declare namespace quat { + + /** + * Creates a new identity quat + * + * @returns a new quaternion + */ + export function create(): GLM.IArray; + + /** + * Creates a new quat initialized with values from an existing quaternion + * + * @param a quaternion to clone + * @returns a new quaternion + * @function + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new quat initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new quaternion + * @function + */ + export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Copy the values from one quat to another + * + * @param out the receiving quaternion + * @param a the source quaternion + * @returns out + * @function + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set the components of a quat to the given values + * + * @param out the receiving quaternion + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + * @function + */ + export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Set a quat to the identity quaternion + * + * @param out the receiving quaternion + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Sets a quat from the given angle and rotation axis, + * then returns it. + * + * @param out the receiving quaternion + * @param axis the axis around which to rotate + * @param rad the angle in radians + * @returns out + **/ + export function setAxisAngle(out: GLM.IArray, axis: GLM.IArray, rad: number): GLM.IArray; + + /** + * Adds two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + * @function + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Scales a quat by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + * @function + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Normalize a quat + * + * @param out the receiving quaternion + * @param a quaternion to normalize + * @returns out + * @function + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the dot product of two quat's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + * @function + */ + export function dot(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): number; + + /** + * Performs a linear interpolation between two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + * @function + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Performs a spherical linear interpolation between two quat + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + export function slerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Calculates the inverse of a quat + * + * @param out the receiving quaternion + * @param a quat to calculate inverse of + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the conjugate of a quat + * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. + * + * @param out the receiving quaternion + * @param a quat to calculate conjugate of + * @returns out + */ + export function conjugate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a quatenion + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; + + /** + * Rotates a quaternion by the given angle about the X axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Rotates a quaternion by the given angle about the Y axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Rotates a quaternion by the given angle about the Z axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Creates a quaternion from the given 3x3 rotation matrix. + * + * NOTE: The resultant quaternion is not normalized, so you should be sure + * to renormalize the quaternion yourself where necessary. + * + * @param out the receiving quaternion + * @param m rotation matrix + * @returns out + * @function + */ + export function fromMat3(out: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param view the vector representing the viewing direction + * @param right the vector representing the local "right" direction + * @param up the vector representing the local "up" direction + * @returns out + */ + export function setAxes(out: GLM.IArray, view: GLM.IArray, right: GLM.IArray, + up: GLM.IArray): GLM.IArray; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param out the receiving quaternion. + * @param a the initial vector + * @param b the destination vector + * @returns out + */ + export function rotationTo(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Calculates the W component of a quat from the X, Y, and Z components. + * Assumes that quaternion is 1 unit in length. + * Any existing W component will be ignored. + * + * @param out the receiving quaternion + * @param a quat to calculate W component of + * @returns out + */ + export function calculateW(out: GLM.IArray, a: GLM.IArray): GLM.IArray; +} diff --git a/gl-matrix/gl-matrix-tests.ts b/gl-matrix/gl-matrix-tests.ts index ce5251edad..984ca3d1c3 100644 --- a/gl-matrix/gl-matrix-tests.ts +++ b/gl-matrix/gl-matrix-tests.ts @@ -1,357 +1,347 @@ /// // common -var result: number = glMatrix.toRadian(180); +import {vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat} from "./gl-matrix"; -var out: GLM.IArray; var outVal: number; +var outBool: boolean; var outStr: string; +let vecArray = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); + +let vec2A = vec2.fromValues(1, 2); +let vec2B = vec2.fromValues(3, 4); +let vec3A = vec3.fromValues(1, 2, 3); +let vec3B = vec3.fromValues(3, 4, 5); +let vec4A = vec4.fromValues(1, 2, 3, 4); +let vec4B = vec4.fromValues(3, 4, 5, 6); +let mat2A = mat2.fromValues(1, 2, 3, 4); +let mat2B = mat2.fromValues(1, 2, 3, 4); +let mat2dA = mat2d.fromValues(1, 2, 3, 4, 5, 6); +let mat2dB = mat2d.fromValues(1, 2, 3, 4, 5, 6); +let mat3A = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +let mat3B = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +let mat4A = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +let mat4B = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +let quatA = quat.fromValues(1, 2, 3, 4); +let quatB = quat.fromValues(5, 6, 7, 8); + +let outVec2 = vec2.create(); +let outVec3 = vec3.create(); +let outVec4 = vec4.create(); +let outMat2 = mat2.create(); +let outMat2d = mat2d.create(); +let outMat3 = mat3.create(); +let outMat4 = mat4.create(); +let outQuat = quat.create(); + // vec2 -var vecA: GLM.IArray, vecB: GLM.IArray, matA: GLM.IArray; -var vecArray: GLM.IArray; - -vecA = [1, 2]; -vecB = new Float32Array([3, 4]); -out = [0, 0]; -matA = [1, 2, 3, 4, 5, 6]; -vecArray = [1, 2, 3, 4, 0, 0]; - -out = vec2.create(); -out = vec2.clone(vecA); -out = vec2.fromValues(1, 2); -out = vec2.copy(out, vecA); -out = vec2.set(out, 1, 2); -out = vec2.add(out, vecA, vecB); -out = vec2.subtract(out, vecA, vecB); -out = vec2.sub(out, vecA, vecB); -out = vec2.multiply(out, vecA, vecB); -out = vec2.mul(out, vecA, vecB); -out = vec2.divide(out, vecA, vecB); -out = vec2.div(out, vecA, vecB); -out = vec2.min(out, vecA, vecB); -out = vec2.max(out, vecA, vecB); -out = vec2.scale(out, vecA, 2); -out = vec2.scaleAndAdd(out, vecA, vecB, 0.5); -outVal = vec2.distance(vecA, vecB); -outVal = vec2.dist(vecA, vecB); -outVal = vec2.squaredDistance(vecA, vecB); -outVal = vec2.sqrDist(vecA, vecB); -outVal = vec2.length(vecA); -outVal = vec2.len(vecA); -outVal = vec2.squaredLength(vecA); -outVal = vec2.sqrLen(vecA); -out = vec2.negate(out, vecA); -out = vec2.inverse(out, vecA); -out = vec2.normalize(out, vecA); -outVal = vec2.dot(vecA, vecB); -out = vec2.cross(out, vecA, vecB); -out = vec2.lerp(out, vecA, vecB, 0.5); -out = vec2.random(out); -out = vec2.random(out, 5.0); -out = vec2.transformMat2(out, vecA, matA); -out = vec2.transformMat2d(out, vecA, matA); -out = vec2.transformMat3(out, vecA, matA); -out = vec2.transformMat4(out, vecA, matA); -out = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); -outStr = vec2.str(vecA); +outVec2 = vec2.create(); +outVec2 = vec2.clone(vec2A); +outVec2 = vec2.fromValues(1, 2); +outVec2 = vec2.copy(outVec2, vec2A); +outVec2 = vec2.set(outVec2, 1, 2); +outVec2 = vec2.add(outVec2, vec2A, vec2B); +outVec2 = vec2.subtract(outVec2, vec2A, vec2B); +outVec2 = vec2.sub(outVec2, vec2A, vec2B); +outVec2 = vec2.multiply(outVec2, vec2A, vec2B); +outVec2 = vec2.mul(outVec2, vec2A, vec2B); +outVec2 = vec2.divide(outVec2, vec2A, vec2B); +outVec2 = vec2.div(outVec2, vec2A, vec2B); +outVec2 = vec2.ceil(outVec2, vec2A); +outVec2 = vec2.floor(outVec2, vec2A); +outVec2 = vec2.min(outVec2, vec2A, vec2B); +outVec2 = vec2.max(outVec2, vec2A, vec2B); +outVec2 = vec2.round(outVec2, vec2A); +outVec2 = vec2.scale(outVec2, vec2A, 2); +outVec2 = vec2.scaleAndAdd(outVec2, vec2A, vec2B, 0.5); +outVal = vec2.distance(vec2A, vec2B); +outVal = vec2.dist(vec2A, vec2B); +outVal = vec2.squaredDistance(vec2A, vec2B); +outVal = vec2.sqrDist(vec2A, vec2B); +outVal = vec2.length(vec2A); +outVal = vec2.len(vec2A); +outVal = vec2.squaredLength(vec2A); +outVal = vec2.sqrLen(vec2A); +outVec2 = vec2.negate(outVec2, vec2A); +outVec2 = vec2.inverse(outVec2, vec2A); +outVec2 = vec2.normalize(outVec2, vec2A); +outVal = vec2.dot(vec2A, vec2B); +outVec2 = vec2.cross(outVec2, vec2A, vec2B); +outVec2 = vec2.lerp(outVec2, vec2A, vec2B, 0.5); +outVec2 = vec2.random(outVec2); +outVec2 = vec2.random(outVec2, 5.0); +outVec2 = vec2.transformMat2(outVec2, vec2A, mat2A); +outVec2 = vec2.transformMat2d(outVec2, vec2A, mat2dA); +outVec2 = vec2.transformMat3(outVec2, vec2A, mat3A); +outVec2 = vec2.transformMat4(outVec2, vec2A, mat4A); +vecArray = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); +outStr = vec2.str(vec2A); +outBool = vec2.exactEquals(vec2A, vec2B); +outBool = vec2.equals(vec2A, vec2B); +outVec2 = vec2.add(outVec2, [0, 1], [2, 3]); // test one method with number array input // vec3 -var matr: GLM.IArray; -var q: GLM.IArray; - -vecA = [1, 2, 3]; -vecB = new Float32Array([4, 5, 6]); -out = [0, 0, 0]; -vecArray = [1, 2, 3, 4, 5, 6, 0, 0, 0]; -matr = [1, 0, 0, 0, 1, 0, 0, 0, 1 ]; - -out = vec3.create(); -out = vec3.clone(vecA); -out = vec3.fromValues(1, 2, 3); -out = vec3.copy(out, vecA); -out = vec3.set(out, 1, 2, 3); -out = vec3.add(out, vecA, vecB); -out = vec3.subtract(out, vecA, vecB); -out = vec3.sub(out, vecA, vecB); -out = vec3.multiply(out, vecA, vecB); -out = vec3.mul(out, vecA, vecB); -out = vec3.divide(out, vecA, vecB); -out = vec3.div(out, vecA, vecB); -out = vec3.min(out, vecA, vecB); -out = vec3.max(out, vecA, vecB); -out = vec3.scale(out, vecA, 2); -out = vec3.scaleAndAdd(out, vecA, vecB, 0.5); -outVal = vec3.distance(vecA, vecB); -outVal = vec3.dist(vecA, vecB); -outVal = vec3.squaredDistance(vecA, vecB); -outVal = vec3.sqrDist(vecA, vecB); -outVal = vec3.length(vecA); -outVal = vec3.len(vecA); -outVal = vec3.squaredLength(vecA); -outVal = vec3.sqrLen(vecA); -out = vec3.negate(out, vecA); -out = vec3.inverse(out, vecA); -out = vec3.normalize(out, vecA); -outVal = vec3.dot(vecA, vecB); -out = vec3.cross(out, vecA, vecB); -out = vec3.lerp(out, vecA, vecB, 0.5); -out = vec3.random(out); -out = vec3.random(out, 5.0); -out = vec3.rotateX(out, vecA, vecB, Math.PI); -out = vec3.rotateY(out, vecA, vecB, Math.PI); -out = vec3.rotateZ(out, vecA, vecB, Math.PI); -out = vec3.transformMat3(out, vecA, matr); - -matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; -out = vec3.transformMat4(out, vecA, matr); - -q = [1, 2, 3, 4]; -out = vec3.transformQuat(out, vecA, matr); - -out = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); -outVal = vec3.angle(vecA, vecB); -outStr = vec3.str(vecA); +outVec3 = vec3.create(); +outVec3 = vec3.clone(vec3A); +outVec3 = vec3.fromValues(1, 2, 3); +outVec3 = vec3.copy(outVec3, vec3A); +outVec3 = vec3.set(outVec3, 1, 2, 3); +outVec3 = vec3.add(outVec3, vec3A, vec3B); +outVec3 = vec3.subtract(outVec3, vec3A, vec3B); +outVec3 = vec3.sub(outVec3, vec3A, vec3B); +outVec3 = vec3.multiply(outVec3, vec3A, vec3B); +outVec3 = vec3.mul(outVec3, vec3A, vec3B); +outVec3 = vec3.divide(outVec3, vec3A, vec3B); +outVec3 = vec3.div(outVec3, vec3A, vec3B); +outVec3 = vec3.ceil(outVec3, vec3A); +outVec3 = vec3.floor(outVec3, vec3A); +outVec3 = vec3.min(outVec3, vec3A, vec3B); +outVec3 = vec3.max(outVec3, vec3A, vec3B); +outVec3 = vec3.round(outVec3, vec3A); +outVec3 = vec3.scale(outVec3, vec3A, 2); +outVec3 = vec3.scaleAndAdd(outVec3, vec3A, vec3B, 0.5); +outVal = vec3.distance(vec3A, vec3B); +outVal = vec3.dist(vec3A, vec3B); +outVal = vec3.squaredDistance(vec3A, vec3B); +outVal = vec3.sqrDist(vec3A, vec3B); +outVal = vec3.length(vec3A); +outVal = vec3.len(vec3A); +outVal = vec3.squaredLength(vec3A); +outVal = vec3.sqrLen(vec3A); +outVec3 = vec3.negate(outVec3, vec3A); +outVec3 = vec3.inverse(outVec3, vec3A); +outVec3 = vec3.normalize(outVec3, vec3A); +outVal = vec3.dot(vec3A, vec3B); +outVec3 = vec3.cross(outVec3, vec3A, vec3B); +outVec3 = vec3.lerp(outVec3, vec3A, vec3B, 0.5); +outVec3 = vec3.hermite(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); +outVec3 = vec3.bezier(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); +outVec3 = vec3.random(outVec3); +outVec3 = vec3.random(outVec3, 5.0); +outVec3 = vec3.transformMat3(outVec3, vec3A, mat3A); +outVec3 = vec3.transformMat4(outVec3, vec3A, mat4A); +outVec3 = vec3.transformQuat(outVec3, vec3A, quatA); +outVec3 = vec3.rotateX(outVec3, vec3A, vec3B, Math.PI); +outVec3 = vec3.rotateY(outVec3, vec3A, vec3B, Math.PI); +outVec3 = vec3.rotateZ(outVec3, vec3A, vec3B, Math.PI); +vecArray = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); +outVal = vec3.angle(vec3A, vec3B); +outStr = vec3.str(vec3A); +outBool = vec3.exactEquals(vec3A, vec3B); +outBool = vec3.equals(vec3A, vec3B); +outVec3 = vec3.add(outVec3, [0, 1, 2], [3, 4, 5]); // test one method with number array input // vec4 -var q: GLM.IArray; - -vecA = [1, 2, 3, 4]; -vecB = new Float32Array([5, 6, 7, 8]); -out = [0, 0, 0, 0]; -q = [1, 2, 3, 4]; - -out = vec4.create(); -out = vec4.clone(vecA); -out = vec4.fromValues(1, 2, 3, 4); -out = vec4.copy(out, vecA); -out = vec4.set(out, 1, 2, 3, 4); -out = vec4.add(out, vecA, vecB); -out = vec4.subtract(out, vecA, vecB); -out = vec4.sub(out, vecA, vecB); -out = vec4.multiply(out, vecA, vecB); -out = vec4.mul(out, vecA, vecB); -out = vec4.divide(out, vecA, vecB); -out = vec4.div(out, vecA, vecB); -out = vec4.min(out, vecA, vecB); -out = vec4.max(out, vecA, vecB); -out = vec4.scale(out, vecA, 2); -out = vec4.scaleAndAdd(out, vecA, vecB, 0.5); -outVal = vec4.distance(vecA, vecB); -outVal = vec4.dist(vecA, vecB); -outVal = vec4.squaredDistance(vecA, vecB); -outVal = vec4.sqrDist(vecA, vecB); -outVal = vec4.length(vecA); -outVal = vec4.len(vecA); -outVal = vec4.squaredLength(vecA); -outVal = vec4.sqrLen(vecA); -out = vec4.negate(out, vecA); -out = vec4.inverse(out, vecA); -out = vec4.normalize(out, vecA); -outVal = vec4.dot(vecA, vecB); -out = vec4.lerp(out, vecA, vecB, 0.5); -out = vec4.random(out); -out = vec4.random(out, 5.0); - -matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] -out = vec4.transformMat4(out, vecA, matr); -out = vec4.transformQuat(out, vecA, q); - -vecArray = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0]; -out = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); -outStr = vec4.str(vecA); +outVec4 = vec4.create(); +outVec4 = vec4.clone(vec4A); +outVec4 = vec4.fromValues(1, 2, 3, 4); +outVec4 = vec4.copy(outVec4, vec4A); +outVec4 = vec4.set(outVec4, 1, 2, 3, 4); +outVec4 = vec4.add(outVec4, vec4A, vec4B); +outVec4 = vec4.subtract(outVec4, vec4A, vec4B); +outVec4 = vec4.sub(outVec4, vec4A, vec4B); +outVec4 = vec4.multiply(outVec4, vec4A, vec4B); +outVec4 = vec4.mul(outVec4, vec4A, vec4B); +outVec4 = vec4.divide(outVec4, vec4A, vec4B); +outVec4 = vec4.div(outVec4, vec4A, vec4B); +outVec4 = vec4.ceil(outVec4, vec4A); +outVec4 = vec4.floor(outVec4, vec4A); +outVec4 = vec4.min(outVec4, vec4A, vec4B); +outVec4 = vec4.max(outVec4, vec4A, vec4B); +outVec4 = vec4.scale(outVec4, vec4A, 2); +outVec4 = vec4.scaleAndAdd(outVec4, vec4A, vec4B, 0.5); +outVal = vec4.distance(vec4A, vec4B); +outVal = vec4.dist(vec4A, vec4B); +outVal = vec4.squaredDistance(vec4A, vec4B); +outVal = vec4.sqrDist(vec4A, vec4B); +outVal = vec4.length(vec4A); +outVal = vec4.len(vec4A); +outVal = vec4.squaredLength(vec4A); +outVal = vec4.sqrLen(vec4A); +outVec4 = vec4.negate(outVec4, vec4A); +outVec4 = vec4.inverse(outVec4, vec4A); +outVec4 = vec4.normalize(outVec4, vec4A); +outVal = vec4.dot(vec4A, vec4B); +outVec4 = vec4.lerp(outVec4, vec4A, vec4B, 0.5); +outVec4 = vec4.random(outVec4); +outVec4 = vec4.random(outVec4, 5.0); +outVec4 = vec4.transformMat4(outVec4, vec4A, mat4A); +outVec4 = vec4.transformQuat(outVec4, vec4A, quatA); +vecArray = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); +outStr = vec4.str(vec4A); +outBool = vec4.exactEquals(vec4A, vec4B); +outBool = vec4.equals(vec4A, vec4B); +outVec4 = vec4.add(outVec4, [0, 1, 2, 3], [4, 5, 6, 7]); // test one method with number array input // mat2 -var matB: GLM.IArray, identity: GLM.IArray; - -matA = [1, 2, 3, 4]; -matB = new Float32Array([5, 6, 7, 8]); -out = [0, 0, 0, 0]; -identity = [1, 0, 0, 1]; - -out = mat2.create(); -out = mat2.clone(matA); -out = mat2.copy(out, matA); -out = mat2.identity(out); -out = mat2.transpose(out, matA); -out = mat2.invert(out, matA); -out = mat2.adjoint(out, matA); -outVal = mat2.determinant(matA); -out = mat2.multiply(out, matA, matB); -out = mat2.mul(out, matA, matB); -out = mat2.rotate(out, matA, Math.PI * 0.5); - -vecA = [2, 3]; -out = mat2.scale(out, matA, vecA); -outStr = mat2.str(matA); -outVal = mat2.frob(matA); - -var L = mat2.create(); -var D = mat2.create(); +outMat2 = mat2.create(); +outMat2 = mat2.clone(mat2A); +outMat2 = mat2.copy(outMat2, mat2A); +outMat2 = mat2.identity(outMat2); +outMat2 = mat2.fromValues(1, 2, 3, 4); +outMat2 = mat2.set(outMat2, 1, 2, 3, 4); +outMat2 = mat2.transpose(outMat2, mat2A); +outMat2 = mat2.invert(outMat2, mat2A); +outMat2 = mat2.adjoint(outMat2, mat2A); +outVal = mat2.determinant(mat2A); +outMat2 = mat2.multiply(outMat2, mat2A, mat2B); +outMat2 = mat2.mul(outMat2, mat2A, mat2B); +outMat2 = mat2.rotate(outMat2, mat2A, Math.PI * 0.5); +outMat2 = mat2.scale(outMat2, mat2A, vec2A); +outMat2 = mat2.fromRotation(outMat2, 0.5); +outMat2 = mat2.fromScaling(outMat2, vec2A); +outStr = mat2.str(mat2A); +outVal = mat2.frob(mat2A); +var L = mat2.create(); +var D = mat2.create(); var U = mat2.create(); -out = mat2.LDU(L, D, U, [4,3,6,3]); +outMat2 = mat2.LDU(L, D, U, mat2A); +outMat2 = mat2.add(outMat2, mat2A, mat2B); +outMat2 = mat2.subtract(outMat2, mat2A, mat2B); +outMat2 = mat2.sub(outMat2, mat2A, mat2B); +outBool = mat2.exactEquals(mat2A, mat2B); +outBool = mat2.equals(mat2A, mat2B); +outMat2 = mat2.multiplyScalar (outMat2, mat2A, 2); +outMat2 = mat2.multiplyScalarAndAdd (outMat2, mat2A, mat2B, 2); // mat2d -matA = [1, 2, 3, 4, 5, 6]; -matB = [7, 8, 9, 10, 11, 12]; -out = [0, 0, 0, 0, 0, 0]; -identity = [1, 0, 0, 1, 0, 0]; - -out = mat2d.create(); -out = mat2d.clone(matA); -out = mat2d.copy(out, matA); -out = mat2d.identity(out); -out = mat2d.invert(out, matA); -outVal = mat2d.determinant(matA); -out = mat2d.multiply(out, matA, matB); -out = mat2d.mul(out, matA, matB); -out = mat2d.rotate(out, matA, Math.PI * 0.5); - -vecA = [2, 3]; -out = mat2d.scale(out, matA, vecA); -out = mat2d.translate(out, matA, vecA); -outStr = mat2d.str(matA); -outVal = mat2d.frob(matA); +outMat2d = mat2d.create(); +outMat2d = mat2d.clone(mat2dA); +outMat2d = mat2d.copy(outMat2d, mat2dA); +outMat2d = mat2d.identity(outMat2d); +outMat2d = mat2d.fromValues(1, 2, 3, 4, 5, 6); +outMat2d = mat2d.set(outMat2d, 1, 2, 3, 4, 5, 6); +outMat2d = mat2d.invert(outMat2d, mat2dA); +outVal = mat2d.determinant(mat2dA); +outMat2d = mat2d.multiply(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.mul(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.rotate(outMat2d, mat2dA, Math.PI * 0.5); +outMat2d = mat2d.scale(outMat2d, mat2dA, vec2A); +outMat2d = mat2d.translate(outMat2d, mat2dA, vec2A); +outMat2d = mat2d.fromRotation(outMat2d, 0.5); +outMat2d = mat2d.fromScaling(outMat2d, vec2A); +outMat2d = mat2d.fromTranslation(outMat2d, vec2A); +outStr = mat2d.str(mat2dA); +outVal = mat2d.frob(mat2dA); +outMat2d = mat2d.add(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.subtract(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.sub(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.multiplyScalar (outMat2d, mat2dA, 2); +outMat2d = mat2d.multiplyScalarAndAdd (outMat2d, mat2dA, mat2dB, 2); +outBool = mat2d.exactEquals(mat2dA, mat2dB); +outBool = mat2d.equals(mat2dA, mat2dB); // mat3 -matA = [1, 0, 0, 0, 1, 0, 1, 2, 1]; -matB = [1, 0, 0, 0, 1, 0, 3, 4, 1]; -out = [0, 0, 0, 0, 0, 0, 0, 0, 0]; -identity = [1, 0, 0, 0, 1, 0, 0, 0, 1]; - -out = mat3.create(); -out = mat3.clone(matA); -out = mat3.copy(out, matA); -out = mat3.identity(out); -out = mat3.transpose(out, matA); -out = mat3.invert(out, matA); -out = mat3.adjoint(out, matA); -outVal = mat3.determinant(matA); -out = mat3.multiply(out, matA, matB); -out = mat3.mul(out, matA, matB); -outStr = mat3.str(matA); -outVal = mat3.frob(matA); +outMat3 = mat3.create(); +outMat3 = mat3.fromMat4(outMat3, mat4A); +outMat3 = mat3.clone(mat3A); +outMat3 = mat3.copy(outMat3, mat3A); +outMat3 = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +outMat3 = mat3.set(outMat3, 1, 2, 3, 4, 5, 6, 7, 8, 9); +outMat3 = mat3.identity(outMat3); +outMat3 = mat3.transpose(outMat3, mat3A); +outMat3 = mat3.invert(outMat3, mat3A); +outMat3 = mat3.adjoint(outMat3, mat3A); +outVal = mat3.determinant(mat3A); +outMat3 = mat3.multiply(outMat3, mat3A, mat3B); +outMat3 = mat3.mul(outMat3, mat3A, mat3B); +outMat3 = mat3.translate(outMat3, mat3A, vec3A); +outMat3 = mat3.rotate(outMat3, mat3A, Math.PI/2); +outMat3 = mat3.scale(outMat3, mat3A, vec2A); +outMat3 = mat3.fromTranslation(outMat3, vec2A); +outMat3 = mat3.fromRotation(outMat3, Math.PI); +outMat3 = mat3.fromScaling(outMat3, vec2A); +outMat3 = mat3.fromMat2d(outMat3, mat2dA); +outMat3 = mat3.fromQuat(outMat3, quatA); +outMat3 = mat3.normalFromMat4(outMat3, mat4A); +outStr = mat3.str(mat3A); +outVal = mat3.frob(mat3A); +outMat3 = mat3.add(outMat3, mat3A, mat3B); +outMat3 = mat3.subtract(outMat3, mat3A, mat3B); +outMat3 = mat3.sub(outMat3, mat3A, mat3B); +outMat3 = mat3.multiplyScalar (outMat3, mat3A, 2); +outMat3 = mat3.multiplyScalarAndAdd (outMat3, mat3A, mat3B, 2); +outBool = mat3.exactEquals(mat3A, mat3B); +outBool = mat3.equals(mat3A, mat3B); -matA = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]; -out = mat3.normalFromMat4(out, matA); - -q = [ 0, -0.7071067811865475, 0, 0.7071067811865475 ]; -out = mat3.fromQuat(out, q); - -out = mat3.normalFromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); -out = mat3.fromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); -out = mat3.scale(out, matA, [2,2]); -out = mat3.fromMat2d(out, [1, 2, 3, 4, 5, 6]); - -out = mat3.translate(out, matA, [1, 2, 3]); -out = mat3.rotate(out, matA, Math.PI/2); - -// mat4 -matA = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 1, 2, 3, 1]; - -matB = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 4, 5, 6, 1]; - -out = [0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0]; - -identity = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]; - -out = mat4.create(); -out = mat4.clone(matA); -out = mat4.copy(out, matA); -out = mat4.identity(out); -out = mat4.transpose(out, matA); -out = mat4.invert(out, matA); -out = mat4.adjoint(out, matA); -outVal = mat4.determinant(matA); -out = mat4.multiply(out, matA, matB); -out = mat4.mul(out, matA, matB); -out = mat4.translate(out, matA, [4, 5, 6]); -out = mat4.scale(out, matA, [4, 5, 6]); - -var rad = Math.PI * 0.5; -var axis = [1, 0, 0]; -out = mat4.rotate(out, matA, rad, axis); -out = mat4.rotateX(out, matA, rad); -out = mat4.rotateY(out, matA, rad); -out = mat4.rotateZ(out, matA, rad); - -out = mat4.frustum(out, -1, 1, -1, 1, -1, 1); - -var fovy = Math.PI * 0.5; -out = mat4.perspective(out, fovy, 1, 0, 1); -out = mat4.ortho(out, -1, 1, -1, 1, -1, 1); - -var eye = [0, 0, 1]; -var center = [0, 0, -1]; -var up = [0, 1, 0]; -out = mat4.lookAt(out, eye, center, up); - -outStr = mat4.str(matA); -outVal = mat4.frob(matA); - -q = [0, 0, 0, 1]; -out = mat4.fromRotationTranslation(out, q, [1, 2, 3]); -out = mat4.fromQuat(out, q); +//mat4 +outMat4 = mat4.create(); +outMat4 = mat4.clone(mat4A); +outMat4 = mat4.copy(outMat4, mat4A); +outMat4 = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +outMat4 = mat4.set(outMat4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +outMat4 = mat4.identity(outMat4); +outMat4 = mat4.transpose(outMat4, mat4A); +outMat4 = mat4.invert(outMat4, mat4A); +outMat4 = mat4.adjoint(outMat4, mat4A); +outVal = mat4.determinant(mat4A); +outMat4 = mat4.multiply(outMat4, mat4A, mat4B); +outMat4 = mat4.mul(outMat4, mat4A, mat4B); +outMat4 = mat4.translate(outMat4, mat4A, vec3A); +outMat4 = mat4.scale(outMat4, mat4A, vec3A); +outMat4 = mat4.rotate(outMat4, mat4A, Math.PI, vec3A); +outMat4 = mat4.rotateX(outMat4, mat4A, Math.PI); +outMat4 = mat4.rotateY(outMat4, mat4A, Math.PI); +outMat4 = mat4.rotateZ(outMat4, mat4A, Math.PI); +outMat4 = mat4.fromTranslation(outMat4, vec3A); +outMat4 = mat4.fromRotation(outMat4, Math.PI, vec3A); +outMat4 = mat4.fromScaling(outMat4, vec3A); +outMat4 = mat4.fromXRotation(outMat4, Math.PI); +outMat4 = mat4.fromYRotation(outMat4, Math.PI); +outMat4 = mat4.fromZRotation(outMat4, Math.PI); +outMat4 = mat4.fromRotationTranslation(outMat4, quatA, vec3A); +outVec3 = mat4.getTranslation(outVec3, mat4A) +outQuat = mat4.getRotation(outQuat, mat4A) +outMat4 = mat4.fromRotationTranslationScale(outMat4, quatA, vec3A, vec3B); +outMat4 = mat4.fromRotationTranslationScaleOrigin(outMat4, quatA, vec3A, vec3B, vec3A); +outMat4 = mat4.fromQuat(outMat4, quatB); +outMat4 = mat4.frustum(outMat4, -1, 1, -1, 1, -1, 1); +outMat4 = mat4.perspective(outMat4, Math.PI, 1, 0, 1); +outMat4 = mat4.perspectiveFromFieldOfView(outMat4, {upDegrees:Math.PI, downDegrees:-Math.PI, leftDegrees:-Math.PI, rightDegrees:Math.PI}, 1, 0); +outMat4 = mat4.ortho(outMat4, -1, 1, -1, 1, -1, 1); +outMat4 = mat4.lookAt(outMat4, vec3A, vec3B, vec3A); +outStr = mat4.str(mat4A); +outVal = mat4.frob(mat4A); +outMat4 = mat4.add(outMat4, mat4A, mat4B); +outMat4 = mat4.subtract(outMat4, mat4A, mat4B); +outMat4 = mat4.sub(outMat4, mat4A, mat4B); +outMat4 = mat4.multiplyScalar (outMat4, mat4A, 2); +outMat4 = mat4.multiplyScalarAndAdd (outMat4, mat4A, mat4B, 2); +outBool = mat4.exactEquals(mat4A, mat4B); +outBool = mat4.equals(mat4A, mat4B); // quat -var quatA = [1, 2, 3, 4]; -var quatB = [5, 6, 7, 8]; -out = [0, 0, 0, 0]; -var vec = [1, 1, -1]; -var id = [0, 0, 0, 1]; var deg90 = Math.PI / 2; - -out = quat.create(); -out = quat.clone(quatA); -out = quat.fromValues(1, 2, 3, 4); -out = quat.copy(out, quatA); -out = quat.set(out, 1, 2, 3, 4); -out = quat.identity(out); -out = quat.setAxisAngle(out, [1, 0, 0], Math.PI * 0.5); -out = quat.add(out, quatA, quatB); -out = quat.multiply(out, quatA, quatB); -out = quat.mul(out, quatA, quatB); -out = quat.scale(out, quatA, 2); +outQuat = quat.create(); +outQuat = quat.clone(quatA); +outQuat = quat.fromValues(1, 2, 3, 4); +outQuat = quat.copy(outQuat, quatA); +outQuat = quat.set(outQuat, 1, 2, 3, 4); +outQuat = quat.identity(outQuat); +outQuat = quat.rotationTo(outQuat, vec3A, vec3B); +outQuat = quat.setAxes(outQuat, vec3A, vec3B, vec3A); +outQuat = quat.setAxisAngle(outQuat, vec3A, Math.PI * 0.5); +outVal = quat.getAxisAngle (outVec3, quatA); +outQuat = quat.add(outQuat, quatA, quatB); +outQuat = quat.multiply(outQuat, quatA, quatB); +outQuat = quat.mul(outQuat, quatA, quatB); +outQuat = quat.scale(outQuat, quatA, 2); outVal = quat.length(quatA); outVal = quat.len(quatA); outVal = quat.squaredLength(quatA); outVal = quat.sqrLen(quatA); -out = quat.normalize(out, quatA); -outVal = quat.dot(out, quatA, quatB); -out = quat.lerp(out, quatA, quatB, 0.5); -out = quat.slerp(out, quatA, quatB, 0.5); -out = quat.invert(out, quatA); -out = quat.conjugate(out, quatA); +outQuat = quat.normalize(outQuat, quatA); +outVal = quat.dot(quatA, quatB); +outQuat = quat.lerp(outQuat, quatA, quatB, 0.5); +outQuat = quat.slerp(outQuat, quatA, quatB, 0.5); +outQuat = quat.invert(outQuat, quatA); +outQuat = quat.conjugate(outQuat, quatA); outStr = quat.str(quatA); -out = quat.rotateX(out, id, deg90); -out = quat.rotateY(out, id, deg90); -out = quat.rotateZ(out, id, deg90); - -matr = [ 1, 0, 0, - 0, 0, -1, - 0, 1, 0 ]; -out = quat.fromMat3(out, matr); - -var view = [-1, 0, 0]; -up = [ 0, 1, 0]; -var right= [ 0, 0,-1]; -out = quat.setAxes([], view, right, up); - -out = quat.rotationTo(out, [0, 1, 0], [1, 0, 0]); -out = quat.calculateW(out, quatA); - +outQuat = quat.rotateX(outQuat, quatA, deg90); +outQuat = quat.rotateY(outQuat, quatA, deg90); +outQuat = quat.rotateZ(outQuat, quatA, deg90); +outQuat = quat.fromMat3(outQuat, mat3A); +outQuat = quat.calculateW(outQuat, quatA); +outBool = quat.exactEquals(quatA, quatB); +outBool = quat.equals(quatA, quatB); diff --git a/gl-matrix/gl-matrix.d.ts b/gl-matrix/gl-matrix.d.ts index b5dcdf3f1d..2edbbd8bb5 100644 --- a/gl-matrix/gl-matrix.d.ts +++ b/gl-matrix/gl-matrix.d.ts @@ -1,36 +1,18 @@ // Type definitions for gl-matrix 2.2.2 // Project: https://github.com/toji/gl-matrix -// Definitions by: Tat +// Definitions by: Mattijs Kneppers , based on definitions by Tat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace GLM { - interface IArray - { - /** - * Must be indexable like an array - */ - [index: number]: number; - } -} - -// Common -declare namespace glMatrix { - /** - * Convert Degree To Radian - * - * @param a Angle in Degrees - */ - export function toRadian(a: number): number; -} - // vec2 -declare namespace vec2 { +export class vec2 extends Float32Array { + private typeVec2: number; + /** * Creates a new, empty vec2 * * @returns a new 2D vector */ - export function create(): GLM.IArray; + public static create(): vec2; /** * Creates a new vec2 initialized with values from an existing vector @@ -38,7 +20,7 @@ declare namespace vec2 { * @param a a vector to clone * @returns a new 2D vector */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: vec2 | number[]): vec2; /** * Creates a new vec2 initialized with the given values @@ -47,7 +29,7 @@ declare namespace vec2 { * @param y Y component * @returns a new 2D vector */ - export function fromValues(x: number, y: number): GLM.IArray; + public static fromValues(x: number, y: number): vec2; /** * Copy the values from one vec2 to another @@ -56,7 +38,7 @@ declare namespace vec2 { * @param a the source vector * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: vec2, a: vec2 | number[]): vec2; /** * Set the components of a vec2 to the given values @@ -66,7 +48,7 @@ declare namespace vec2 { * @param y Y component * @returns out */ - export function set(out: GLM.IArray, x: number, y: number): GLM.IArray; + public static set(out: vec2, x: number, y: number): vec2; /** * Adds two vec2's @@ -76,7 +58,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static add(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Subtracts vector b from vector a @@ -86,7 +68,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static subtract(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Subtracts vector b from vector a @@ -96,7 +78,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static sub(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Multiplies two vec2's @@ -106,7 +88,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Multiplies two vec2's @@ -116,7 +98,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Divides two vec2's @@ -126,7 +108,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static divide(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Divides two vec2's @@ -136,7 +118,25 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static div(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + + /** + * Math.ceil the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to ceil + * @returns {vec2} out + */ + public static ceil(out: vec2, a: vec2 | number[]): vec2; + + /** + * Math.floor the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to floor + * @returns {vec2} out + */ + public static floor (out: vec2, a: vec2 | number[]): vec2; /** * Returns the minimum of two vec2's @@ -146,7 +146,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static min(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Returns the maximum of two vec2's @@ -156,7 +156,17 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static max(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + + /** + * Math.round the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to round + * @returns {vec2} out + */ + public static round(out: vec2, a: vec2 | number[]): vec2; + /** * Scales a vec2 by a scalar number @@ -166,7 +176,7 @@ declare namespace vec2 { * @param b amount to scale the vector by * @returns out */ - export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + public static scale(out: vec2, a: vec2 | number[], b: number): vec2; /** * Adds two vec2's after scaling the second operand by a scalar value @@ -177,7 +187,7 @@ declare namespace vec2 { * @param scale the amount to scale b by before adding * @returns out */ - export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + public static scaleAndAdd(out: vec2, a: vec2 | number[], b: vec2 | number[], scale: number): vec2; /** * Calculates the euclidian distance between two vec2's @@ -186,7 +196,7 @@ declare namespace vec2 { * @param b the second operand * @returns distance between a and b */ - export function distance(a: GLM.IArray, b: GLM.IArray): number; + public static distance(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the euclidian distance between two vec2's @@ -195,7 +205,7 @@ declare namespace vec2 { * @param b the second operand * @returns distance between a and b */ - export function dist(a: GLM.IArray, b: GLM.IArray): number; + public static dist(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the squared euclidian distance between two vec2's @@ -204,7 +214,7 @@ declare namespace vec2 { * @param b the second operand * @returns squared distance between a and b */ - export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + public static squaredDistance(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the squared euclidian distance between two vec2's @@ -213,7 +223,7 @@ declare namespace vec2 { * @param b the second operand * @returns squared distance between a and b */ - export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + public static sqrDist(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the length of a vec2 @@ -221,7 +231,7 @@ declare namespace vec2 { * @param a vector to calculate length of * @returns length of a */ - export function length(a: GLM.IArray): number; + public static length(a: vec2 | number[]): number; /** * Calculates the length of a vec2 @@ -229,7 +239,7 @@ declare namespace vec2 { * @param a vector to calculate length of * @returns length of a */ - export function len(a: GLM.IArray): number; + public static len(a: vec2 | number[]): number; /** * Calculates the squared length of a vec2 @@ -237,7 +247,7 @@ declare namespace vec2 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function squaredLength(a: GLM.IArray): number; + public static squaredLength(a: vec2 | number[]): number; /** * Calculates the squared length of a vec2 @@ -245,7 +255,7 @@ declare namespace vec2 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function sqrLen(a: GLM.IArray): number; + public static sqrLen(a: vec2 | number[]): number; /** * Negates the components of a vec2 @@ -254,7 +264,7 @@ declare namespace vec2 { * @param a vector to negate * @returns out */ - export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static negate(out: vec2, a: vec2 | number[]): vec2; /** * Returns the inverse of the components of a vec2 @@ -263,7 +273,7 @@ declare namespace vec2 { * @param a vector to invert * @returns out */ - export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static inverse(out: vec2, a: vec2 | number[]): vec2; /** * Normalize a vec2 @@ -272,7 +282,7 @@ declare namespace vec2 { * @param a vector to normalize * @returns out */ - export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static normalize(out: vec2, a: vec2 | number[]): vec2; /** * Calculates the dot product of two vec2's @@ -281,7 +291,7 @@ declare namespace vec2 { * @param b the second operand * @returns dot product of a and b */ - export function dot(a: GLM.IArray, b: GLM.IArray): number; + public static dot(a: vec2 | number[], b: vec2 | number[]): number; /** * Computes the cross product of two vec2's @@ -292,7 +302,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static cross(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Performs a linear interpolation between two vec2's @@ -303,7 +313,7 @@ declare namespace vec2 { * @param t interpolation amount between the two inputs * @returns out */ - export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static lerp(out: vec2, a: vec2 | number[], b: vec2 | number[], t: number): vec2; /** * Generates a random unit vector @@ -311,7 +321,7 @@ declare namespace vec2 { * @param out the receiving vector * @returns out */ - export function random(out: GLM.IArray): GLM.IArray; + public static random(out: vec2): vec2; /** * Generates a random vector with the given scale @@ -320,7 +330,7 @@ declare namespace vec2 { * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned * @returns out */ - export function random(out: GLM.IArray, scale: number): GLM.IArray; + public static random(out: vec2, scale: number): vec2; /** * Transforms the vec2 with a mat2 @@ -330,7 +340,7 @@ declare namespace vec2 { * @param m matrix to transform with * @returns out */ - export function transformMat2(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat2(out: vec2, a: vec2 | number[], m: mat2): vec2; /** * Transforms the vec2 with a mat2d @@ -340,7 +350,7 @@ declare namespace vec2 { * @param m matrix to transform with * @returns out */ - export function transformMat2d(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat2d(out: vec2, a: vec2 | number[], m: mat2d): vec2; /** * Transforms the vec2 with a mat3 @@ -351,7 +361,7 @@ declare namespace vec2 { * @param m matrix to transform with * @returns out */ - export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat3(out: vec2, a: vec2 | number[], m: mat3): vec2; /** * Transforms the vec2 with a mat4 @@ -363,7 +373,7 @@ declare namespace vec2 { * @param m matrix to transform with * @returns out */ - export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat4(out: vec2, a: vec2 | number[], m: mat4): vec2; /** * Perform some operation over an array of vec2s. @@ -376,8 +386,8 @@ declare namespace vec2 { * @param arg additional argument to pass to fn * @returns a */ - export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, - fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec2 | number[], b: vec2 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec2s. @@ -389,27 +399,46 @@ declare namespace vec2 { * @param fn Function to call for each vector in the array * @returns a */ - export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, - fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec2 | number[], b: vec2 | number[]) => void): Float32Array; /** * Returns a string representation of a vector * - * @param vec vector to represent as a string + * @param a vector to represent as a string * @returns string representation of the vector */ - export function str(a: GLM.IArray): string; + public static str(a: vec2 | number[]): string; + + /** + * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a: vec2 | number[], b: vec2 | number[]): boolean; + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a: vec2 | number[], b: vec2 | number[]): boolean; } // vec3 -declare namespace vec3 { +export class vec3 extends Float32Array { + private typeVec3: number; /** * Creates a new, empty vec3 * * @returns a new 3D vector */ - export function create(): GLM.IArray; + public static create(): vec3; /** * Creates a new vec3 initialized with values from an existing vector @@ -417,7 +446,7 @@ declare namespace vec3 { * @param a vector to clone * @returns a new 3D vector */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: vec3 | number[]): vec3; /** * Creates a new vec3 initialized with the given values @@ -427,7 +456,7 @@ declare namespace vec3 { * @param z Z component * @returns a new 3D vector */ - export function fromValues(x: number, y: number, z: number): GLM.IArray; + public static fromValues(x: number, y: number, z: number): vec3; /** * Copy the values from one vec3 to another @@ -436,7 +465,7 @@ declare namespace vec3 { * @param a the source vector * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: vec3, a: vec3 | number[]): vec3; /** * Set the components of a vec3 to the given values @@ -447,7 +476,7 @@ declare namespace vec3 { * @param z Z component * @returns out */ - export function set(out: GLM.IArray, x: number, y: number, z: number): GLM.IArray; + public static set(out: vec3, x: number, y: number, z: number): vec3; /** * Adds two vec3's @@ -457,7 +486,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static add(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Subtracts vector b from vector a @@ -467,7 +496,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static subtract(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Subtracts vector b from vector a @@ -477,7 +506,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray + public static sub(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3 /** * Multiplies two vec3's @@ -487,7 +516,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Multiplies two vec3's @@ -497,7 +526,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Divides two vec3's @@ -507,7 +536,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static divide(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Divides two vec3's @@ -517,7 +546,25 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static div(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Math.ceil the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to ceil + * @returns {vec3} out + */ + public static ceil (out: vec3, a: vec3 | number[]): vec3; + + /** + * Math.floor the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to floor + * @returns {vec3} out + */ + public static floor (out: vec3, a: vec3 | number[]): vec3; /** * Returns the minimum of two vec3's @@ -527,7 +574,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static min(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Returns the maximum of two vec3's @@ -537,7 +584,16 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static max(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Math.round the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to round + * @returns {vec3} out + */ + public static round (out: vec3, a: vec3 | number[]): vec3 /** * Scales a vec3 by a scalar number @@ -547,7 +603,7 @@ declare namespace vec3 { * @param b amount to scale the vector by * @returns out */ - export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + public static scale(out: vec3, a: vec3 | number[], b: number): vec3; /** * Adds two vec3's after scaling the second operand by a scalar value @@ -558,7 +614,7 @@ declare namespace vec3 { * @param scale the amount to scale b by before adding * @returns out */ - export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + public static scaleAndAdd(out: vec3, a: vec3 | number[], b: vec3 | number[], scale: number): vec3; /** * Calculates the euclidian distance between two vec3's @@ -567,7 +623,7 @@ declare namespace vec3 { * @param b the second operand * @returns distance between a and b */ - export function distance(a: GLM.IArray, b: GLM.IArray): number; + public static distance(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the euclidian distance between two vec3's @@ -576,7 +632,7 @@ declare namespace vec3 { * @param b the second operand * @returns distance between a and b */ - export function dist(a: GLM.IArray, b: GLM.IArray): number; + public static dist(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the squared euclidian distance between two vec3's @@ -585,7 +641,7 @@ declare namespace vec3 { * @param b the second operand * @returns squared distance between a and b */ - export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + public static squaredDistance(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the squared euclidian distance between two vec3's @@ -594,7 +650,7 @@ declare namespace vec3 { * @param b the second operand * @returns squared distance between a and b */ - export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + public static sqrDist(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the length of a vec3 @@ -602,7 +658,7 @@ declare namespace vec3 { * @param a vector to calculate length of * @returns length of a */ - export function length(a: GLM.IArray): number; + public static length(a: vec3 | number[]): number; /** * Calculates the length of a vec3 @@ -610,7 +666,7 @@ declare namespace vec3 { * @param a vector to calculate length of * @returns length of a */ - export function len(a: GLM.IArray): number; + public static len(a: vec3 | number[]): number; /** * Calculates the squared length of a vec3 @@ -618,7 +674,7 @@ declare namespace vec3 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function squaredLength(a: GLM.IArray): number; + public static squaredLength(a: vec3 | number[]): number; /** * Calculates the squared length of a vec3 @@ -626,7 +682,7 @@ declare namespace vec3 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function sqrLen(a: GLM.IArray): number; + public static sqrLen(a: vec3 | number[]): number; /** * Negates the components of a vec3 @@ -635,7 +691,7 @@ declare namespace vec3 { * @param a vector to negate * @returns out */ - export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static negate(out: vec3, a: vec3 | number[]): vec3; /** * Returns the inverse of the components of a vec3 @@ -644,7 +700,7 @@ declare namespace vec3 { * @param a vector to invert * @returns out */ - export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static inverse(out: vec3, a: vec3 | number[]): vec3; /** * Normalize a vec3 @@ -653,7 +709,7 @@ declare namespace vec3 { * @param a vector to normalize * @returns out */ - export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static normalize(out: vec3, a: vec3 | number[]): vec3; /** * Calculates the dot product of two vec3's @@ -662,7 +718,7 @@ declare namespace vec3 { * @param b the second operand * @returns dot product of a and b */ - export function dot(a: GLM.IArray, b: GLM.IArray): number; + public static dot(a: vec3 | number[], b: vec3 | number[]): number; /** * Computes the cross product of two vec3's @@ -672,7 +728,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static cross(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Performs a linear interpolation between two vec3's @@ -683,7 +739,33 @@ declare namespace vec3 { * @param t interpolation amount between the two inputs * @returns out */ - export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static lerp(out: vec3, a: vec3 | number[], b: vec3 | number[], t: number): vec3; + + /** + * Performs a hermite interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {number} t interpolation amount between the two inputs + * @returns {vec3} out + */ + public static hermite (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; + + /** + * Performs a bezier interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {number} t interpolation amount between the two inputs + * @returns {vec3} out + */ + public static bezier (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; /** * Generates a random unit vector @@ -691,46 +773,16 @@ declare namespace vec3 { * @param out the receiving vector * @returns out */ - export function random(out: GLM.IArray): GLM.IArray; + public static random(out: vec3): vec3; /** * Generates a random vector with the given scale * * @param out the receiving vector - * @param [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @param [scale] Length of the resulting vector. If omitted, a unit vector will be returned * @returns out */ - export function random(out: GLM.IArray, scale: number): GLM.IArray; - - /** - * Rotate a 3D vector around the x-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - export function rotateX(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; - - /** - * Rotate a 3D vector around the y-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - export function rotateY(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; - - /** - * Rotate a 3D vector around the z-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - export function rotateZ(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + public static random(out: vec3, scale: number): vec3; /** * Transforms the vec3 with a mat3. @@ -740,7 +792,7 @@ declare namespace vec3 { * @param m the 3x3 matrix to transform with * @returns out */ - export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat3(out: vec3, a: vec3 | number[], m: mat3): vec3; /** * Transforms the vec3 with a mat4. @@ -751,9 +803,9 @@ declare namespace vec3 { * @param m matrix to transform with * @returns out */ - export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat4(out: vec3, a: vec3 | number[], m: mat4): vec3; - /** + /** * Transforms the vec3 with a quat * * @param out the receiving vector @@ -761,9 +813,39 @@ declare namespace vec3 { * @param q quaternion to transform with * @returns out */ - export function transformQuat(out: GLM.IArray, a: GLM.IArray, q: GLM.IArray): GLM.IArray; + public static transformQuat(out: vec3, a: vec3 | number[], q: quat): vec3; + /** + * Rotate a 3D vector around the x-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateX(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; + + /** + * Rotate a 3D vector around the y-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateY(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; + + /** + * Rotate a 3D vector around the z-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateZ(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; + /** * Perform some operation over an array of vec3s. * @@ -776,8 +858,8 @@ declare namespace vec3 { * @returns a * @function */ - export function forEach(out: GLM.IArray, string: number, offset: number, count: number, - fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec3 | number[], b: vec3 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec3s. @@ -790,8 +872,8 @@ declare namespace vec3 { * @returns a * @function */ - export function forEach(out: GLM.IArray, string: number, offset: number, count: number, - fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec3 | number[], b: vec3 | number[]) => void): Float32Array; /** * Get the angle between two 3D vectors @@ -799,26 +881,45 @@ declare namespace vec3 { * @param b The second operand * @returns The angle in radians */ - export function angle(a: GLM.IArray, b: GLM.IArray): number; + public static angle(a: vec3 | number[], b: vec3 | number[]): number; /** * Returns a string representation of a vector * - * @param vec vector to represent as a string + * @param a vector to represent as a string * @returns string representation of the vector */ - export function str(a: GLM.IArray): string; + public static str(a: vec3 | number[]): string; + + /** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a: vec3 | number[], b: vec3 | number[]): boolean + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a: vec3 | number[], b: vec3 | number[]): boolean } // vec4 -declare namespace vec4 { +export class vec4 extends Float32Array { + private typeVec3: number; /** * Creates a new, empty vec4 * * @returns a new 4D vector */ - export function create(): GLM.IArray; + public static create(): vec4; /** * Creates a new vec4 initialized with values from an existing vector @@ -826,7 +927,7 @@ declare namespace vec4 { * @param a vector to clone * @returns a new 4D vector */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: vec4 | number[]): vec4; /** * Creates a new vec4 initialized with the given values @@ -837,7 +938,7 @@ declare namespace vec4 { * @param w W component * @returns a new 4D vector */ - export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + public static fromValues(x: number, y: number, z: number, w: number): vec4; /** * Copy the values from one vec4 to another @@ -846,7 +947,7 @@ declare namespace vec4 { * @param a the source vector * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: vec4, a: vec4 | number[]): vec4; /** * Set the components of a vec4 to the given values @@ -858,7 +959,7 @@ declare namespace vec4 { * @param w W component * @returns out */ - export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + public static set(out: vec4, x: number, y: number, z: number, w: number): vec4; /** * Adds two vec4's @@ -868,7 +969,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static add(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Subtracts vector b from vector a @@ -878,7 +979,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static subtract(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Subtracts vector b from vector a @@ -888,7 +989,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static sub(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Multiplies two vec4's @@ -898,7 +999,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Multiplies two vec4's @@ -908,7 +1009,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Divides two vec4's @@ -918,7 +1019,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static divide(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Divides two vec4's @@ -928,7 +1029,25 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static div(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Math.ceil the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to ceil + * @returns {vec4} out + */ + public static ceil (out: vec4, a: vec4 | number[]): vec4; + + /** + * Math.floor the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to floor + * @returns {vec4} out + */ + public static floor (out: vec4, a: vec4 | number[]): vec4; /** * Returns the minimum of two vec4's @@ -938,7 +1057,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static min(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Returns the maximum of two vec4's @@ -948,7 +1067,16 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static max(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Math.round the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to round + * @returns {vec4} out + */ + public static round (out: vec4, a: vec4 | number[]): vec4; /** * Scales a vec4 by a scalar number @@ -958,7 +1086,7 @@ declare namespace vec4 { * @param b amount to scale the vector by * @returns out */ - export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + public static scale(out: vec4, a: vec4 | number[], b: number): vec4; /** * Adds two vec4's after scaling the second operand by a scalar value @@ -969,7 +1097,7 @@ declare namespace vec4 { * @param scale the amount to scale b by before adding * @returns out */ - export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + public static scaleAndAdd(out: vec4, a: vec4 | number[], b: vec4 | number[], scale: number): vec4; /** * Calculates the euclidian distance between two vec4's @@ -978,7 +1106,7 @@ declare namespace vec4 { * @param b the second operand * @returns distance between a and b */ - export function distance(a: GLM.IArray, b: GLM.IArray): number; + public static distance(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the euclidian distance between two vec4's @@ -987,7 +1115,7 @@ declare namespace vec4 { * @param b the second operand * @returns distance between a and b */ - export function dist(a: GLM.IArray, b: GLM.IArray): number; + public static dist(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the squared euclidian distance between two vec4's @@ -996,7 +1124,7 @@ declare namespace vec4 { * @param b the second operand * @returns squared distance between a and b */ - export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + public static squaredDistance(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the squared euclidian distance between two vec4's @@ -1005,7 +1133,7 @@ declare namespace vec4 { * @param b the second operand * @returns squared distance between a and b */ - export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + public static sqrDist(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the length of a vec4 @@ -1013,7 +1141,7 @@ declare namespace vec4 { * @param a vector to calculate length of * @returns length of a */ - export function length(a: GLM.IArray): number; + public static length(a: vec4 | number[]): number; /** * Calculates the length of a vec4 @@ -1021,7 +1149,7 @@ declare namespace vec4 { * @param a vector to calculate length of * @returns length of a */ - export function len(a: GLM.IArray): number; + public static len(a: vec4 | number[]): number; /** * Calculates the squared length of a vec4 @@ -1029,7 +1157,7 @@ declare namespace vec4 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function squaredLength(a: GLM.IArray): number; + public static squaredLength(a: vec4 | number[]): number; /** * Calculates the squared length of a vec4 @@ -1037,7 +1165,7 @@ declare namespace vec4 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function sqrLen(a: GLM.IArray): number; + public static sqrLen(a: vec4 | number[]): number; /** * Negates the components of a vec4 @@ -1046,7 +1174,7 @@ declare namespace vec4 { * @param a vector to negate * @returns out */ - export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static negate(out: vec4, a: vec4 | number[]): vec4; /** * Returns the inverse of the components of a vec4 @@ -1055,7 +1183,7 @@ declare namespace vec4 { * @param a vector to invert * @returns out */ - export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static inverse(out: vec4, a: vec4 | number[]): vec4; /** * Normalize a vec4 @@ -1064,7 +1192,7 @@ declare namespace vec4 { * @param a vector to normalize * @returns out */ - export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static normalize(out: vec4, a: vec4 | number[]): vec4; /** * Calculates the dot product of two vec4's @@ -1073,7 +1201,7 @@ declare namespace vec4 { * @param b the second operand * @returns dot product of a and b */ - export function dot(a: GLM.IArray, b: GLM.IArray): number; + public static dot(a: vec4 | number[], b: vec4 | number[]): number; /** * Performs a linear interpolation between two vec4's @@ -1084,7 +1212,7 @@ declare namespace vec4 { * @param t interpolation amount between the two inputs * @returns out */ - export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static lerp(out: vec4, a: vec4 | number[], b: vec4 | number[], t: number): vec4; /** * Generates a random unit vector @@ -1092,16 +1220,16 @@ declare namespace vec4 { * @param out the receiving vector * @returns out */ - export function random(out: GLM.IArray): GLM.IArray; + public static random(out: vec4): vec4; /** * Generates a random vector with the given scale * * @param out the receiving vector - * @param Length of the resulting vector. If ommitted, a unit vector will be returned + * @param scale length of the resulting vector. If ommitted, a unit vector will be returned * @returns out */ - export function random(out: GLM.IArray, scale: number): GLM.IArray; + public static random(out: vec4, scale: number): vec4; /** * Transforms the vec4 with a mat4. @@ -1111,7 +1239,7 @@ declare namespace vec4 { * @param m matrix to transform with * @returns out */ - export function transformMat4(out: GLM.IArray, a: GLM.IArray, mat: GLM.IArray): GLM.IArray; + public static transformMat4(out: vec4, a: vec4 | number[], m: mat4): vec4; /** * Transforms the vec4 with a quat @@ -1121,7 +1249,8 @@ declare namespace vec4 { * @param q quaternion to transform with * @returns out */ - export function transformQuat(out: GLM.IArray, a: GLM.IArray, quat: GLM.IArray): GLM.IArray; + + public static transformQuat(out: vec4, a: vec4 | number[], q: quat): vec4; /** * Perform some operation over an array of vec4s. @@ -1131,12 +1260,12 @@ declare namespace vec4 { * @param offset Number of elements to skip at the beginning of the array * @param count Number of vec4s to iterate over. If 0 iterates over entire array * @param fn Function to call for each vector in the array - * @param additional argument to pass to fn + * @param arg additional argument to pass to fn * @returns a * @function */ - export function forEach(out: GLM.IArray, string: number, offset: number, count: number, - callback: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec4 | number[], b: vec4 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec4s. @@ -1149,27 +1278,46 @@ declare namespace vec4 { * @returns a * @function */ - export function forEach(out: GLM.IArray, string: number, offset: number, count: number, - callback: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec4 | number[], b: vec4 | number[]) => void): Float32Array; /** * Returns a string representation of a vector * - * @param vec vector to represent as a string + * @param a vector to represent as a string * @returns string representation of the vector */ - export function str(a: GLM.IArray): string; + public static str(a: vec4 | number[]): string; + + /** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a: vec4 | number[], b: vec4 | number[]): boolean; + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a: vec4 | number[], b: vec4 | number[]): boolean; } // mat2 -declare namespace mat2 { +export class mat2 extends Float32Array { + private typeMat2: number; /** * Creates a new identity mat2 * * @returns a new 2x2 matrix */ - export function create(): GLM.IArray; + public static create(): mat2; /** * Creates a new mat2 initialized with values from an existing matrix @@ -1177,7 +1325,7 @@ declare namespace mat2 { * @param a matrix to clone * @returns a new 2x2 matrix */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: mat2): mat2; /** * Copy the values from one mat2 to another @@ -1186,7 +1334,7 @@ declare namespace mat2 { * @param a the source matrix * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: mat2, a: mat2): mat2; /** * Set a mat2 to the identity matrix @@ -1194,7 +1342,30 @@ declare namespace mat2 { * @param out the receiving matrix * @returns out */ - export function identity(out: GLM.IArray): GLM.IArray; + public static identity(out: mat2): mat2; + + /** + * Create a new mat2 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m10 Component in column 1, row 0 position (index 2) + * @param {number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out A new 2x2 matrix + */ + public static fromValues(m00: number, m01: number, m10: number, m11: number): mat2; + + /** + * Set the components of a mat2 to the given values + * + * @param {mat2} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m10 Component in column 1, row 0 position (index 2) + * @param {number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out + */ + public static set(out: mat2, m00: number, m01: number, m10: number, m11: number): mat2; /** * Transpose the values of a mat2 @@ -1203,7 +1374,7 @@ declare namespace mat2 { * @param a the source matrix * @returns out */ - export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static transpose(out: mat2, a: mat2): mat2; /** * Inverts a mat2 @@ -1212,7 +1383,7 @@ declare namespace mat2 { * @param a the source matrix * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: mat2, a: mat2): mat2; /** * Calculates the adjugate of a mat2 @@ -1221,7 +1392,7 @@ declare namespace mat2 { * @param a the source matrix * @returns out */ - export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static adjoint(out: mat2, a: mat2): mat2; /** * Calculates the determinant of a mat2 @@ -1229,7 +1400,7 @@ declare namespace mat2 { * @param a the source matrix * @returns determinant of a */ - export function determinant(a: GLM.IArray): number; + public static determinant(a: mat2): number; /** * Multiplies two mat2's @@ -1239,7 +1410,7 @@ declare namespace mat2 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: mat2, a: mat2, b: mat2): mat2; /** * Multiplies two mat2's @@ -1249,7 +1420,7 @@ declare namespace mat2 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: mat2, a: mat2, b: mat2): mat2; /** * Rotates a mat2 by the given angle @@ -1259,7 +1430,7 @@ declare namespace mat2 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotate(out: mat2, a: mat2, rad: number): mat2; /** * Scales the mat2 by the dimensions in the given vec2 @@ -1269,7 +1440,33 @@ declare namespace mat2 { * @param v the vec2 to scale the matrix by * @returns out **/ - export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static scale(out: mat2, a: mat2, v: vec2 | number[]): mat2; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.rotate(dest, dest, rad); + * + * @param {mat2} out mat2 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ + public static fromRotation(out: mat2, rad: number): mat2; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.scale(dest, dest, vec); + * + * @param {mat2} out mat2 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2} out + */ + public static fromScaling(out: mat2, v: vec2 | number[]): mat2; /** * Returns a string representation of a mat2 @@ -1277,7 +1474,7 @@ declare namespace mat2 { * @param a matrix to represent as a string * @returns string representation of the matrix */ - export function str(a: GLM.IArray): string; + public static str(a: mat2): string; /** * Returns Frobenius norm of a mat2 @@ -1285,7 +1482,7 @@ declare namespace mat2 { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - export function frob(a: GLM.IArray): number; + public static frob(a: mat2): number; /** * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix @@ -1294,18 +1491,91 @@ declare namespace mat2 { * @param U the upper triangular matrix * @param a the input matrix to factorize */ - export function LDU(L: GLM.IArray, D: GLM.IArray, U: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static LDU(L: mat2, D: mat2, U: mat2, a: mat2): mat2; + + /** + * Adds two mat2's + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static add(out: mat2, a: mat2, b: mat2): mat2; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static subtract (out: mat2, a: mat2, b: mat2): mat2; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static sub (out: mat2, a: mat2, b: mat2): mat2; + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat2, b: mat2): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat2, b: mat2): boolean; + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat2} out + */ + public static multiplyScalar (out: mat2, a: mat2, b: number): mat2 + + /** + * Adds two mat2's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2} out the receiving vector + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat2} out + */ + public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale: number): mat2 + + + } // mat2d -declare namespace mat2d { +export class mat2d extends Float32Array { + private typeMat2d: number; /** * Creates a new identity mat2d * * @returns a new 2x3 matrix */ - export function create(): GLM.IArray; + public static create(): mat2d; /** * Creates a new mat2d initialized with values from an existing matrix @@ -1313,7 +1583,7 @@ declare namespace mat2d { * @param a matrix to clone * @returns a new 2x3 matrix */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: mat2d): mat2d; /** * Copy the values from one mat2d to another @@ -1322,7 +1592,7 @@ declare namespace mat2d { * @param a the source matrix * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: mat2d, a: mat2d): mat2d; /** * Set a mat2d to the identity matrix @@ -1330,7 +1600,35 @@ declare namespace mat2d { * @param out the receiving matrix * @returns out */ - export function identity(out: GLM.IArray): GLM.IArray; + public static identity(out: mat2d): mat2d; + + /** + * Create a new mat2d with the given values + * + * @param {number} a Component A (index 0) + * @param {number} b Component B (index 1) + * @param {number} c Component C (index 2) + * @param {number} d Component D (index 3) + * @param {number} tx Component TX (index 4) + * @param {number} ty Component TY (index 5) + * @returns {mat2d} A new mat2d + */ + public static fromValues (a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d + + + /** + * Set the components of a mat2d to the given values + * + * @param {mat2d} out the receiving matrix + * @param {number} a Component A (index 0) + * @param {number} b Component B (index 1) + * @param {number} c Component C (index 2) + * @param {number} d Component D (index 3) + * @param {number} tx Component TX (index 4) + * @param {number} ty Component TY (index 5) + * @returns {mat2d} out + */ + public static set (out: mat2d, a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d /** * Inverts a mat2d @@ -1339,7 +1637,7 @@ declare namespace mat2d { * @param a the source matrix * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: mat2d, a: mat2d): mat2d; /** * Calculates the determinant of a mat2d @@ -1347,7 +1645,7 @@ declare namespace mat2d { * @param a the source matrix * @returns determinant of a */ - export function determinant(a: GLM.IArray): number; + public static determinant(a: mat2d): number; /** * Multiplies two mat2d's @@ -1357,7 +1655,7 @@ declare namespace mat2d { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: mat2d, a: mat2d, b: mat2d): mat2d; /** * Multiplies two mat2d's @@ -1367,7 +1665,7 @@ declare namespace mat2d { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: mat2d, a: mat2d, b: mat2d): mat2d; /** * Rotates a mat2d by the given angle @@ -1377,7 +1675,7 @@ declare namespace mat2d { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotate(out: mat2d, a: mat2d, rad: number): mat2d; /** * Scales the mat2d by the dimensions in the given vec2 @@ -1387,7 +1685,7 @@ declare namespace mat2d { * @param v the vec2 to scale the matrix by * @returns out **/ - export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static scale(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; /** * Translates the mat2d by the dimensions in the given vec2 @@ -1397,7 +1695,46 @@ declare namespace mat2d { * @param v the vec2 to translate the matrix by * @returns out **/ - export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static translate(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.rotate(dest, dest, rad); + * + * @param {mat2d} out mat2d receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat2d} out + */ + public static fromRotation (out: mat2d, rad: number): mat2d; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.scale(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2d} out + */ + public static fromScaling (out: mat2d, v: vec2 | number[]): mat2d; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.translate(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {vec2} v Translation vector + * @returns {mat2d} out + */ + public static fromTranslation (out: mat2d, v: vec2 | number[]): mat2d /** * Returns a string representation of a mat2d @@ -1405,7 +1742,7 @@ declare namespace mat2d { * @param a matrix to represent as a string * @returns string representation of the matrix */ - export function str(a: GLM.IArray): string; + public static str(a: mat2d): string; /** * Returns Frobenius norm of a mat2d @@ -1413,18 +1750,97 @@ declare namespace mat2d { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - export function frob(a: GLM.IArray): number; + public static frob(a: mat2d): number; + + /** + * Adds two mat2d's + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static add (out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static subtract(out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static sub(out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat2d} out + */ + public static multiplyScalar (out: mat2d, a: mat2d, b: number): mat2d; + + /** + * Adds two mat2d's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2d} out the receiving vector + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat2d} out + */ + public static multiplyScalarAndAdd (out: mat2d, a: mat2d, b: mat2d, scale: number): mat2d + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2d} a The first matrix. + * @param {mat2d} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat2d, b: mat2d): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2d} a The first matrix. + * @param {mat2d} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat2d, b: mat2d): boolean } // mat3 -declare namespace mat3 { +export class mat3 extends Float32Array { + private typeMat3: number; /** * Creates a new identity mat3 * * @returns a new 3x3 matrix */ - export function create(): GLM.IArray; + public static create(): mat3; + + /** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param {mat3} out the receiving 3x3 matrix + * @param {mat4} a the source 4x4 matrix + * @returns {mat3} out + */ + public static fromMat4(out: mat3, a: mat4): mat3 /** * Creates a new mat3 initialized with values from an existing matrix @@ -1432,7 +1848,7 @@ declare namespace mat3 { * @param a matrix to clone * @returns a new 3x3 matrix */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: mat3): mat3; /** * Copy the values from one mat3 to another @@ -1441,7 +1857,41 @@ declare namespace mat3 { * @param a the source matrix * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: mat3, a: mat3): mat3; + + /** + * Create a new mat3 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m10 Component in column 1, row 0 position (index 3) + * @param {number} m11 Component in column 1, row 1 position (index 4) + * @param {number} m12 Component in column 1, row 2 position (index 5) + * @param {number} m20 Component in column 2, row 0 position (index 6) + * @param {number} m21 Component in column 2, row 1 position (index 7) + * @param {number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} A new mat3 + */ + public static fromValues(m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3; + + + /** + * Set the components of a mat3 to the given values + * + * @param {mat3} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m10 Component in column 1, row 0 position (index 3) + * @param {number} m11 Component in column 1, row 1 position (index 4) + * @param {number} m12 Component in column 1, row 2 position (index 5) + * @param {number} m20 Component in column 2, row 0 position (index 6) + * @param {number} m21 Component in column 2, row 1 position (index 7) + * @param {number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} out + */ + public static set(out: mat3, m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3 /** * Set a mat3 to the identity matrix @@ -1449,7 +1899,7 @@ declare namespace mat3 { * @param out the receiving matrix * @returns out */ - export function identity(out: GLM.IArray): GLM.IArray; + public static identity(out: mat3): mat3; /** * Transpose the values of a mat3 @@ -1458,7 +1908,7 @@ declare namespace mat3 { * @param a the source matrix * @returns out */ - export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static transpose(out: mat3, a: mat3): mat3; /** * Inverts a mat3 @@ -1467,7 +1917,7 @@ declare namespace mat3 { * @param a the source matrix * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: mat3, a: mat3): mat3; /** * Calculates the adjugate of a mat3 @@ -1476,7 +1926,7 @@ declare namespace mat3 { * @param a the source matrix * @returns out */ - export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static adjoint(out: mat3, a: mat3): mat3; /** * Calculates the determinant of a mat3 @@ -1484,7 +1934,7 @@ declare namespace mat3 { * @param a the source matrix * @returns determinant of a */ - export function determinant(a: GLM.IArray): number; + public static determinant(a: mat3): number; /** * Multiplies two mat3's @@ -1494,7 +1944,7 @@ declare namespace mat3 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: mat3, a: mat3, b: mat3): mat3; /** * Multiplies two mat3's @@ -1504,71 +1954,8 @@ declare namespace mat3 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: mat3, a: mat3, b: mat3): mat3; - /** - * Returns a string representation of a mat3 - * - * @param mat matrix to represent as a string - * @returns string representation of the matrix - */ - export function str(mat: GLM.IArray): string; - - /** - * Returns Frobenius norm of a mat3 - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - export function frob(a: GLM.IArray): number; - - /** - * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix - * - * @param out mat3 receiving operation result - * @param a Mat4 to derive the normal matrix from - * - * @returns out - */ - export function normalFromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; - - /** - * Calculates a 3x3 matrix from the given quaternion - * - * @param out mat3 receiving operation result - * @param q Quaternion to create matrix from - * - * @returns out - */ - export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; - - /** - * Copies the upper-left 3x3 values into the given mat3. - * - * @param out the receiving 3x3 matrix - * @param a the source 4x4 matrix - * @returns out - */ - export function fromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; - - /** - * Scales the mat3 by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param v the vec2 to scale the matrix by - * @returns out - **/ - export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; - - /** - * Copies the values from a mat2d into a mat3 - * - * @param out the receiving matrix - * @param {mat2d} a the matrix to copy - * @returns out - **/ - export function fromMat2d(out: GLM.IArray, a: GLM.IArray): GLM.IArray; /** * Translate a mat3 by the given vector @@ -1578,7 +1965,7 @@ declare namespace mat3 { * @param v vector to translate by * @returns out */ - export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static translate(out: mat3, a: mat3, v: vec3 | number[]): mat3; /** * Rotates a mat3 by the given angle @@ -1588,18 +1975,182 @@ declare namespace mat3 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotate(out: mat3, a: mat3, rad: number): mat3; + + /** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + public static scale(out: mat3, a: mat3, v: vec2 | number[]): mat3; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.translate(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Translation vector + * @returns {mat3} out + */ + public static fromTranslation(out: mat3, v: vec2 | number[]): mat3 + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.rotate(dest, dest, rad); + * + * @param {mat3} out mat3 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ + public static fromRotation(out: mat3, rad: number): mat3 + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.scale(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat3} out + */ + public static fromScaling(out: mat3, v: vec2 | number[]): mat3 + + /** + * Copies the values from a mat2d into a mat3 + * + * @param out the receiving matrix + * @param {mat2d} a the matrix to copy + * @returns out + **/ + public static fromMat2d(out: mat3, a: mat2d): mat3; + + /** + * Calculates a 3x3 matrix from the given quaternion + * + * @param out mat3 receiving operation result + * @param q Quaternion to create matrix from + * + * @returns out + */ + public static fromQuat(out: mat3, q: quat): mat3; + + /** + * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix + * + * @param out mat3 receiving operation result + * @param a Mat4 to derive the normal matrix from + * + * @returns out + */ + public static normalFromMat4(out: mat3, a: mat4): mat3; + + /** + * Returns a string representation of a mat3 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(mat: mat3): string; + + /** + * Returns Frobenius norm of a mat3 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a: mat3): number; + + /** + * Adds two mat3's + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static add(out: mat3, a: mat3, b: mat3): mat3 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static subtract(out: mat3, a: mat3, b: mat3): mat3 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static sub(out: mat3, a: mat3, b: mat3): mat3 + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat3} out + */ + public static multiplyScalar(out: mat3, a: mat3, b: number): mat3 + + /** + * Adds two mat3's after multiplying each element of the second operand by a scalar value. + * + * @param {mat3} out the receiving vector + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat3} out + */ + public static multiplyScalarAndAdd(out: mat3, a: mat3, b: mat3, scale: number): mat3 + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals(a: mat3, b: mat3): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals(a: mat3, b: mat3): boolean } // mat4 -declare namespace mat4 { +export class mat4 extends Float32Array { + private typeMat4: number; /** * Creates a new identity mat4 * * @returns a new 4x4 matrix */ - export function create(): GLM.IArray; + public static create(): mat4; /** * Creates a new mat4 initialized with values from an existing matrix @@ -1607,7 +2158,7 @@ declare namespace mat4 { * @param a matrix to clone * @returns a new 4x4 matrix */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: mat4): mat4; /** * Copy the values from one mat4 to another @@ -1616,7 +2167,55 @@ declare namespace mat4 { * @param a the source matrix * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: mat4, a: mat4): mat4; + + + /** + * Create a new mat4 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m03 Component in column 0, row 3 position (index 3) + * @param {number} m10 Component in column 1, row 0 position (index 4) + * @param {number} m11 Component in column 1, row 1 position (index 5) + * @param {number} m12 Component in column 1, row 2 position (index 6) + * @param {number} m13 Component in column 1, row 3 position (index 7) + * @param {number} m20 Component in column 2, row 0 position (index 8) + * @param {number} m21 Component in column 2, row 1 position (index 9) + * @param {number} m22 Component in column 2, row 2 position (index 10) + * @param {number} m23 Component in column 2, row 3 position (index 11) + * @param {number} m30 Component in column 3, row 0 position (index 12) + * @param {number} m31 Component in column 3, row 1 position (index 13) + * @param {number} m32 Component in column 3, row 2 position (index 14) + * @param {number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} A new mat4 + */ + public static fromValues(m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; + + /** + * Set the components of a mat4 to the given values + * + * @param {mat4} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m03 Component in column 0, row 3 position (index 3) + * @param {number} m10 Component in column 1, row 0 position (index 4) + * @param {number} m11 Component in column 1, row 1 position (index 5) + * @param {number} m12 Component in column 1, row 2 position (index 6) + * @param {number} m13 Component in column 1, row 3 position (index 7) + * @param {number} m20 Component in column 2, row 0 position (index 8) + * @param {number} m21 Component in column 2, row 1 position (index 9) + * @param {number} m22 Component in column 2, row 2 position (index 10) + * @param {number} m23 Component in column 2, row 3 position (index 11) + * @param {number} m30 Component in column 3, row 0 position (index 12) + * @param {number} m31 Component in column 3, row 1 position (index 13) + * @param {number} m32 Component in column 3, row 2 position (index 14) + * @param {number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} out + */ + public static set(out: mat4, m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; /** * Set a mat4 to the identity matrix @@ -1624,7 +2223,7 @@ declare namespace mat4 { * @param out the receiving matrix * @returns out */ - export function identity(a: GLM.IArray): GLM.IArray; + public static identity(out: mat4): mat4; /** * Transpose the values of a mat4 @@ -1633,7 +2232,7 @@ declare namespace mat4 { * @param a the source matrix * @returns out */ - export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static transpose(out: mat4, a: mat4): mat4; /** * Inverts a mat4 @@ -1642,7 +2241,7 @@ declare namespace mat4 { * @param a the source matrix * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: mat4, a: mat4): mat4; /** * Calculates the adjugate of a mat4 @@ -1651,7 +2250,7 @@ declare namespace mat4 { * @param a the source matrix * @returns out */ - export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static adjoint(out: mat4, a: mat4): mat4; /** * Calculates the determinant of a mat4 @@ -1659,7 +2258,7 @@ declare namespace mat4 { * @param a the source matrix * @returns determinant of a */ - export function determinant(a: GLM.IArray): number; + public static determinant(a: mat4): number; /** * Multiplies two mat4's @@ -1669,7 +2268,7 @@ declare namespace mat4 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: mat4, a: mat4, b: mat4): mat4; /** * Multiplies two mat4's @@ -1679,7 +2278,7 @@ declare namespace mat4 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: mat4, a: mat4, b: mat4): mat4; /** * Translate a mat4 by the given vector @@ -1689,7 +2288,7 @@ declare namespace mat4 { * @param v vector to translate by * @returns out */ - export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static translate(out: mat4, a: mat4, v: vec3 | number[]): mat4; /** * Scales the mat4 by the dimensions in the given vec3 @@ -1699,7 +2298,7 @@ declare namespace mat4 { * @param v the vec3 to scale the matrix by * @returns out **/ - export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static scale(out: mat4, a: mat4, v: vec3 | number[]): mat4; /** * Rotates a mat4 by the given angle @@ -1710,7 +2309,7 @@ declare namespace mat4 { * @param axis the axis to rotate around * @returns out */ - export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number, axis: GLM.IArray): GLM.IArray; + public static rotate(out: mat4, a: mat4, rad: number, axis: vec3 | number[]): mat4; /** * Rotates a matrix by the given angle around the X axis @@ -1720,7 +2319,7 @@ declare namespace mat4 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateX(out: mat4, a: mat4, rad: number): mat4; /** * Rotates a matrix by the given angle around the Y axis @@ -1730,7 +2329,7 @@ declare namespace mat4 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateY(out: mat4, a: mat4, rad: number): mat4; /** * Rotates a matrix by the given angle around the Z axis @@ -1740,78 +2339,87 @@ declare namespace mat4 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateZ(out: mat4, a: mat4, rad: number): mat4; /** - * Generates a frustum matrix with the given bounds + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): * - * @param out mat4 frustum matrix will be written into - * @param left Left bound of the frustum - * @param right Right bound of the frustum - * @param bottom Bottom bound of the frustum - * @param top Top bound of the frustum - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out + * mat4.identity(dest); + * mat4.translate(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Translation vector + * @returns {mat4} out */ - export function frustum(out: GLM.IArray, left: number, right: number, - bottom: number, top: number, near: number, far: number): GLM.IArray; + public static fromTranslation(out: mat4, v: vec3 | number[]): mat4 /** - * Generates a perspective projection matrix with the given bounds + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): * - * @param out mat4 frustum matrix will be written into - * @param fovy Vertical field of view in radians - * @param aspect Aspect ratio. typically viewport width/height - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out + * mat4.identity(dest); + * mat4.scale(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Scaling vector + * @returns {mat4} out */ - export function perspective(out: GLM.IArray, fovy: number, aspect: number, - near: number, far: number): GLM.IArray; + public static fromScaling(out: mat4, v: vec3 | number[]): mat4 /** - * Generates a orthogonal projection matrix with the given bounds + * Creates a matrix from a given angle around a given axis + * This is equivalent to (but much faster than): * - * @param out mat4 frustum matrix will be written into - * @param left Left bound of the frustum - * @param right Right bound of the frustum - * @param bottom Bottom bound of the frustum - * @param top Top bound of the frustum - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out + * mat4.identity(dest); + * mat4.rotate(dest, dest, rad, axis); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @param {vec3} axis the axis to rotate around + * @returns {mat4} out */ - export function ortho(out: GLM.IArray, left: number, right: number, - bottom: number, top: number, near: number, far: number): GLM.IArray; + public static fromRotation(out: mat4, rad: number, axis: vec3 | number[]): mat4 /** - * Generates a look-at matrix with the given eye position, focal point, and up axis + * Creates a matrix from the given angle around the X axis + * This is equivalent to (but much faster than): * - * @param out mat4 frustum matrix will be written into - * @param eye Position of the viewer - * @param center Point the viewer is looking at - * @param up vec3 pointing up - * @returns out + * mat4.identity(dest); + * mat4.rotateX(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out */ - export function lookAt(out: GLM.IArray, eye: GLM.IArray, - center: GLM.IArray, up: GLM.IArray): GLM.IArray; + public static fromXRotation(out: mat4, rad: number): mat4 /** - * Returns a string representation of a mat4 + * Creates a matrix from the given angle around the Y axis + * This is equivalent to (but much faster than): * - * @param mat matrix to represent as a string - * @returns string representation of the matrix + * mat4.identity(dest); + * mat4.rotateY(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out */ - export function str(mat: GLM.IArray): string; + public static fromYRotation(out: mat4, rad: number): mat4 + /** - * Returns Frobenius norm of a mat4 + * Creates a matrix from the given angle around the Z axis + * This is equivalent to (but much faster than): * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm + * mat4.identity(dest); + * mat4.rotateZ(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out */ - export function frob(a: GLM.IArray): number; + public static fromZRotation(out: mat4, rad: number): mat4 /** * Creates a matrix from a quaternion rotation and vector translation @@ -1828,28 +2436,247 @@ declare namespace mat4 { * @param v Translation vector * @returns out */ - export function fromRotationTranslation(out: GLM.IArray, q: GLM.IArray, - v: GLM.IArray): GLM.IArray; + public static fromRotationTranslation(out: mat4, q: quat, v: vec3 | number[]): mat4; /** - * Creates a matrix from a quaternion + * Returns the translation vector component of a transformation + * matrix. If a matrix is built with fromRotationTranslation, + * the returned vector will be the same as the translation vector + * originally supplied. + * @param {vec3} out Vector to receive translation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ + public static getTranslation(out: vec3, mat: mat4): vec3; + + /** + * Returns a quaternion representing the rotational component + * of a transformation matrix. If a matrix is built with + * fromRotationTranslation, the returned quaternion will be the + * same as the quaternion originally supplied. + * @param {quat} out Quaternion to receive the rotation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {quat} out + */ + public static getRotation(out: quat, mat: mat4): quat; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) * * @param out mat4 receiving operation result * @param q Rotation quaternion + * @param v Translation vector + * @param s Scaling vector * @returns out */ - export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; + public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[]): mat4; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * mat4.translate(dest, origin); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * mat4.translate(dest, negativeOrigin); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Rotation quaternion + * @param {vec3} v Translation vector + * @param {vec3} s Scaling vector + * @param {vec3} o The origin vector around which to scale and rotate + * @returns {mat4} out + */ + public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[], o: vec3 | number[]): mat4 + + /** + * Calculates a 4x4 matrix from the given quaternion + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Quaternion to create matrix from + * + * @returns {mat4} out + */ + public static fromQuat(out: mat4, q: quat): mat4 + + /** + * Generates a frustum matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static frustum(out: mat4, left: number, right: number, + bottom: number, top: number, near: number, far: number): mat4; + + /** + * Generates a perspective projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param fovy Vertical field of view in radians + * @param aspect Aspect ratio. typically viewport width/height + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static perspective(out: mat4, fovy: number, aspect: number, + near: number, far: number): mat4; + + /** + * Generates a perspective projection matrix with the given field of view. + * This is primarily useful for generating projection matrices to be used + * with the still experimental WebVR API. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + public static perspectiveFromFieldOfView(out: mat4, + fov:{upDegrees: number, downDegrees: number, leftDegrees: number, rightDegrees: number}, + near: number, far: number): mat4 + + /** + * Generates a orthogonal projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static ortho(out: mat4, left: number, right: number, + bottom: number, top: number, near: number, far: number): mat4; + + /** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param out mat4 frustum matrix will be written into + * @param eye Position of the viewer + * @param center Point the viewer is looking at + * @param up vec3 pointing up + * @returns out + */ + public static lookAt(out: mat4, eye: vec3 | number[], center: vec3 | number[], up: vec3 | number[]): mat4; + + /** + * Returns a string representation of a mat4 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(mat: mat4): string; + + /** + * Returns Frobenius norm of a mat4 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a: mat4): number; + + /** + * Adds two mat4's + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static add(out: mat4, a: mat4, b: mat4): mat4 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static subtract(out: mat4, a: mat4, b: mat4): mat4 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static sub(out: mat4, a: mat4, b: mat4): mat4 + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat4} out + */ + public static multiplyScalar(out: mat4, a: mat4, b: number): mat4 + + /** + * Adds two mat4's after multiplying each element of the second operand by a scalar value. + * + * @param {mat4} out the receiving vector + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat4} out + */ + public static multiplyScalarAndAdd (out: mat4, a: mat4, b: mat4, scale: number): mat4 + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat4, b: mat4): boolean + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat4, b: mat4): boolean + } // quat -declare namespace quat { +export class quat extends Float32Array { + private typeQuat: number; /** * Creates a new identity quat * * @returns a new quaternion */ - export function create(): GLM.IArray; + public static create(): quat; /** * Creates a new quat initialized with values from an existing quaternion @@ -1858,7 +2685,7 @@ declare namespace quat { * @returns a new quaternion * @function */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: quat): quat; /** * Creates a new quat initialized with the given values @@ -1870,7 +2697,7 @@ declare namespace quat { * @returns a new quaternion * @function */ - export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + public static fromValues(x: number, y: number, z: number, w: number): quat; /** * Copy the values from one quat to another @@ -1880,7 +2707,7 @@ declare namespace quat { * @returns out * @function */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: quat, a: quat): quat; /** * Set the components of a quat to the given values @@ -1893,7 +2720,7 @@ declare namespace quat { * @returns out * @function */ - export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + public static set(out: quat, x: number, y: number, z: number, w: number): quat; /** * Set a quat to the identity quaternion @@ -1901,7 +2728,34 @@ declare namespace quat { * @param out the receiving quaternion * @returns out */ - export function identity(out: GLM.IArray): GLM.IArray; + public static identity(out: quat): quat; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param {quat} out the receiving quaternion. + * @param {vec3} a the initial vector + * @param {vec3} b the destination vector + * @returns {quat} out + */ + public static rotationTo (out: quat, a: vec3 | number[], b: vec3 | number[]): quat; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {vec3} view the vector representing the viewing direction + * @param {vec3} right the vector representing the local "right" direction + * @param {vec3} up the vector representing the local "up" direction + * @returns {quat} out + */ + public static setAxes (out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat + + /** * Sets a quat from the given angle and rotation axis, @@ -1912,7 +2766,22 @@ declare namespace quat { * @param rad the angle in radians * @returns out **/ - export function setAxisAngle(out: GLM.IArray, axis: GLM.IArray, rad: number): GLM.IArray; + public static setAxisAngle(out: quat, axis: vec3 | number[], rad: number): quat; + + /** + * Gets the rotation axis and angle for a given + * quaternion. If a quaternion is created with + * setAxisAngle, this method will return the same + * values as providied in the original parameter list + * OR functionally equivalent values. + * Example: The quaternion formed by axis [0, 0, 1] and + * angle -90 is the same as the quaternion formed by + * [0, 0, 1] and 270. This method favors the latter. + * @param {vec3} out_axis Vector receiving the axis of rotation + * @param {quat} q Quaternion to be decomposed + * @return {number} Angle, in radians, of the rotation + */ + public static getAxisAngle (out_axis: vec3 | number[], q: quat): number /** * Adds two quat's @@ -1923,7 +2792,7 @@ declare namespace quat { * @returns out * @function */ - export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static add(out: quat, a: quat, b: quat): quat; /** * Multiplies two quat's @@ -1933,7 +2802,7 @@ declare namespace quat { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: quat, a: quat, b: quat): quat; /** * Multiplies two quat's @@ -1943,7 +2812,7 @@ declare namespace quat { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: quat, a: quat, b: quat): quat; /** * Scales a quat by a scalar number @@ -1954,7 +2823,7 @@ declare namespace quat { * @returns out * @function */ - export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + public static scale(out: quat, a: quat, b: number): quat; /** * Calculates the length of a quat @@ -1963,7 +2832,7 @@ declare namespace quat { * @returns length of a * @function */ - export function length(a: GLM.IArray): number; + public static length(a: quat): number; /** * Calculates the length of a quat @@ -1972,7 +2841,7 @@ declare namespace quat { * @returns length of a * @function */ - export function len(a: GLM.IArray): number; + public static len(a: quat): number; /** * Calculates the squared length of a quat @@ -1981,7 +2850,7 @@ declare namespace quat { * @returns squared length of a * @function */ - export function squaredLength(a: GLM.IArray): number; + public static squaredLength(a: quat): number; /** * Calculates the squared length of a quat @@ -1990,7 +2859,7 @@ declare namespace quat { * @returns squared length of a * @function */ - export function sqrLen(a: GLM.IArray): number; + public static sqrLen(a: quat): number; /** * Normalize a quat @@ -2000,7 +2869,7 @@ declare namespace quat { * @returns out * @function */ - export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static normalize(out: quat, a: quat): quat; /** * Calculates the dot product of two quat's @@ -2010,7 +2879,7 @@ declare namespace quat { * @returns dot product of a and b * @function */ - export function dot(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): number; + public static dot(a: quat, b: quat): number; /** * Performs a linear interpolation between two quat's @@ -2022,7 +2891,7 @@ declare namespace quat { * @returns out * @function */ - export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static lerp(out: quat, a: quat, b: quat, t: number): quat; /** * Performs a spherical linear interpolation between two quat @@ -2033,7 +2902,20 @@ declare namespace quat { * @param t interpolation amount between the two inputs * @returns out */ - export function slerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static slerp(out: quat, a: quat, b: quat, t: number): quat; + + /** + * Performs a spherical linear interpolation with two control points + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @param {quat} c the third operand + * @param {quat} d the fourth operand + * @param {number} t interpolation amount + * @returns {quat} out + */ + public static sqlerp(out: quat, a: quat, b: quat, c: quat, d: quat, t: number): quat; /** * Calculates the inverse of a quat @@ -2042,7 +2924,7 @@ declare namespace quat { * @param a quat to calculate inverse of * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: quat, a: quat): quat; /** * Calculates the conjugate of a quat @@ -2052,15 +2934,15 @@ declare namespace quat { * @param a quat to calculate conjugate of * @returns out */ - export function conjugate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static conjugate(out: quat, a: quat): quat; /** - * Returns a string representation of a quatenion + * Returns a string representation of a quaternion * - * @param vec vector to represent as a string - * @returns string representation of the vector + * @param a quat to represent as a string + * @returns string representation of the quat */ - export function str(a: GLM.IArray): string; + public static str(a: quat): string; /** * Rotates a quaternion by the given angle about the X axis @@ -2070,7 +2952,7 @@ declare namespace quat { * @param rad angle (in radians) to rotate * @returns out */ - export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateX(out: quat, a: quat, rad: number): quat; /** * Rotates a quaternion by the given angle about the Y axis @@ -2080,7 +2962,7 @@ declare namespace quat { * @param rad angle (in radians) to rotate * @returns out */ - export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateY(out: quat, a: quat, rad: number): quat; /** * Rotates a quaternion by the given angle about the Z axis @@ -2090,7 +2972,7 @@ declare namespace quat { * @param rad angle (in radians) to rotate * @returns out */ - export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateZ(out: quat, a: quat, rad: number): quat; /** * Creates a quaternion from the given 3x3 rotation matrix. @@ -2103,20 +2985,20 @@ declare namespace quat { * @returns out * @function */ - export function fromMat3(out: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static fromMat3(out: quat, m: mat3): quat; /** * Sets the specified quaternion with values corresponding to the given * axes. Each axis is a vec3 and is expected to be unit length and * perpendicular to all other specified axes. * + * @param out the receiving quat * @param view the vector representing the viewing direction * @param right the vector representing the local "right" direction * @param up the vector representing the local "up" direction * @returns out */ - export function setAxes(out: GLM.IArray, view: GLM.IArray, right: GLM.IArray, - up: GLM.IArray): GLM.IArray; + public static setAxes(out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat; /** * Sets a quaternion to represent the shortest rotation from one @@ -2129,7 +3011,7 @@ declare namespace quat { * @param b the destination vector * @returns out */ - export function rotationTo(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static rotationTo(out: quat, a: vec3 | number[], b: vec3 | number[]): quat; /** * Calculates the W component of a quat from the X, Y, and Z components. @@ -2140,5 +3022,23 @@ declare namespace quat { * @param a quat to calculate W component of * @returns out */ - export function calculateW(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static calculateW(out: quat, a: quat): quat; + + /** + * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {boolean} True if the quaternions are equal, false otherwise. + */ + public static exactEquals (a: quat, b: quat): boolean; + + /** + * Returns whether or not the quaternions have approximately the same elements in the same position. + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {boolean} True if the quaternions are equal, false otherwise. + */ + public static equals (a: quat, b: quat): boolean; } diff --git a/globalize-compiler/globalize-compiler-tests.ts b/globalize-compiler/globalize-compiler-tests.ts new file mode 100644 index 0000000000..f4fc934d1f --- /dev/null +++ b/globalize-compiler/globalize-compiler-tests.ts @@ -0,0 +1,36 @@ +/// + +import globalizeCompiler = require("globalize-compiler"); +const globalize: GlobalizeStatic = null; + +let extractsArray: GlobalizeCompiler.FormatterOrParserFunction[]; + +const templateFunction: (options: GlobalizeCompiler.CompileTemplateOptions) => string = + (options: GlobalizeCompiler.CompileTemplateOptions): string => { + const deps: string[] = options.dependencies; + const code: string = options.code; + return `${deps.join(';')}${code}`; + }; + +let compileOutput: string; +compileOutput = globalizeCompiler.compile(extractsArray); +compileOutput = globalizeCompiler.compile({ x: () => "test", y: (x: string) => x }); +compileOutput = globalizeCompiler.compile(extractsArray, { template: templateFunction }); +compileOutput = globalizeCompiler.compile({ x: () => "test", y: (x: string) => x }, { template: templateFunction }); + +let extractOutput: GlobalizeCompiler.ExtractFunction; +extractOutput = globalizeCompiler.extract("path"); + +const ast: ESTree.Program = undefined; +extractOutput = globalizeCompiler.extract(ast); + +extractsArray = extractOutput(globalize); + +compileOutput = globalizeCompiler.compileExtracts({ extracts: extractOutput, defaultLocale: "en" }); +compileOutput = globalizeCompiler.compileExtracts({ extracts: extractOutput, defaultLocale: "en", messages: {} }); +compileOutput = globalizeCompiler.compileExtracts({ extracts: extractOutput, defaultLocale: "en", template: templateFunction }); +compileOutput = globalizeCompiler.compileExtracts({ extracts: extractOutput, defaultLocale: "en", messages: {}, template: templateFunction }); +compileOutput = globalizeCompiler.compileExtracts({ extracts: extractOutput, defaultLocale: "en", cldr: {} }); +compileOutput = globalizeCompiler.compileExtracts({ extracts: extractOutput, defaultLocale: "en", cldr: {}, messages: {} }); +compileOutput = globalizeCompiler.compileExtracts({ extracts: extractOutput, defaultLocale: "en", cldr: {}, template: templateFunction }); +compileOutput = globalizeCompiler.compileExtracts({ extracts: extractOutput, defaultLocale: "en", cldr: {}, messages: {}, template: templateFunction }); diff --git a/globalize-compiler/globalize-compiler.d.ts b/globalize-compiler/globalize-compiler.d.ts new file mode 100644 index 0000000000..3959924412 --- /dev/null +++ b/globalize-compiler/globalize-compiler.d.ts @@ -0,0 +1,106 @@ +// Type definitions for globalize-compiler v0.2.0 +// Project: https://github.com/jquery-support/globalize-compiler +// Definitions by: Ian Clanton-Thuon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace GlobalizeCompiler { + interface CompileTemplateOptions { + /** + * the source of the compiled formatters and parsers. + */ + code: string; + + /** + * a list of globalize runtime modules that the compiled code depends on, e.g. globalize-runtime/number. + */ + dependencies: string[]; + } + + interface CompileOptions { + /** + * A function that replaces the default template. + */ + template?: (options: CompileTemplateOptions) => string; + } + + interface FormatterOrParserFunction { + (...arguments: any[]): any; + } + + interface ExtractFunction { + /** + * @param {globalize} the globalize object. + * + * @returns an Array with the formatters and parsers created using the passed Globalize. + */ + (globalize: GlobalizeStatic): FormatterOrParserFunction[]; + } + + interface CompileExtractsAttributes extends CompileOptions { + /** + * an Array of extracts obtained by @see{GlobalizeCompilerStatic.extract} + */ + extracts: ExtractFunction; + + /** + * a locale to be used as Globalize.locale(defaultLocale) when generating the extracted formatters and parsers. + */ + defaultLocale: string; + + /** + * an Object with CLDR data (in the JSON format) or a Function taking one argument: locale, a String; returning + * an Object with the CLDR data for the passed locale. Defaults to the entire supplemental data plus the entire + * main data for the defaultLocale. + */ + cldr?: Object | ((locale: string) => Object); + + /** + * an Object with messages data (in the JSON format) or a Function taking one argument: locale, a String; returning + * an Object with the messages data for the passed locale. Defaults to {}. + */ + messages?: Object | ((locale: string) => Object); + } + + interface GlobalizeCompilerStatic { + /** + * Generates a JavaScript bundle containing the specified globalize formatters and parsers. + * + * @param {formattersAndParsers} an Array or an Object containing formatters and/or parsers. + * @param {options} compiler options. + * + * @returns a String with the generated JavaScript bundle (UMD wrapped) including the compiled formatters and + * parsers. + */ + compile(formattersAndParsers: FormatterOrParserFunction[] | { [key: string]: FormatterOrParserFunction }, + options?: CompileOptions): string; + + /** + * Creates an extract function from a source file. + * + * @param {input} a String with a filename, or a String with the file content, or an AST Object. + * + * @returns an extract. An extract is a Function taking one argument: Globalize, the Globalize Object; + * and returning an Array with the formatters and parsers created using the passed Globalize. + */ + extract(input: string | ESTree.Program): ExtractFunction; + + /** + * Generates a JavaScript bundle containing the specified globalize formatters and parsers. + * + * @param {options} compiler attributes. + * + * @returns a String with the generated JavaScript bundle (UMD wrapped) including the compiled formatters and + * parsers. + */ + compileExtracts(attributes: CompileExtractsAttributes): string; + } +} + +declare module "globalize-compiler" { + var globalizeCompiler: GlobalizeCompiler.GlobalizeCompilerStatic; + + export = globalizeCompiler; +} diff --git a/google-earth/google-earth-tests.ts b/google-earth/google-earth-tests.ts new file mode 100644 index 0000000000..6c9d4df1bf --- /dev/null +++ b/google-earth/google-earth-tests.ts @@ -0,0 +1,131 @@ +/// + +google.load("earth", "1", {"other_params":"sensor=true_or_false"}); + +google.earth.createInstance("map3d", initCB, failureCB); + +function failureCB(error: any) {} + +function initCB(ge: google.earth.GEPlugin) { + + ge.getWindow().setVisibility(true); + + + // Create the placemark. + var placemark = ge.createPlacemark(''); + placemark.setName("placemark"); + + // Set the placemark's location. + var point = ge.createPoint(''); + point.setLatitude(12.345); + point.setLongitude(54.321); + placemark.setGeometry(point); + + // Create a style map. + var styleMap = ge.createStyleMap(''); + + // Create normal style for style map. + var normalStyle = ge.createStyle(''); + var normalIcon = ge.createIcon(''); + normalIcon.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png'); + normalStyle.getIconStyle().setIcon(normalIcon); + + // Create highlight style for style map. + var highlightStyle = ge.createStyle(''); + var highlightIcon = ge.createIcon(''); + highlightIcon.setHref('http://google-maps-icons.googlecode.com/files/girlfriend.png'); + highlightStyle.getIconStyle().setIcon(highlightIcon); + highlightStyle.getIconStyle().setScale(5.0); + + styleMap.setNormalStyle(normalStyle); + styleMap.setHighlightStyle(highlightStyle); + + // Apply stylemap to a placemark. + placemark.setStyleSelector(styleMap); + + //Add the placemark to Earth. + ge.getFeatures().appendChild(placemark); + + + // balloons + var balloon = ge.createHtmlDivBalloon(''); + balloon.setFeature(placemark); + var div = document.createElement('DIV'); + div.innerHTML = 'Any HTML, CSS, or JavaScript goes here.'; + balloon.setContentDiv(div); + ge.setBalloon(balloon); + + // Create the ScreenOverlay + var screenOverlay = ge.createScreenOverlay(''); + + // Specify a path to the image and set as the icon + var icon = ge.createIcon(''); + icon.setHref('http://www.google.com/intl/en_ALL/images/logo.gif'); + screenOverlay.setIcon(icon); + + // Set the ScreenOverlay's position in the window + screenOverlay.getOverlayXY().setXUnits(ge.UNITS_PIXELS); + screenOverlay.getOverlayXY().setYUnits(ge.UNITS_PIXELS); + screenOverlay.getOverlayXY().setX(200); + screenOverlay.getOverlayXY().setY(200); + + // Set the overlay's size in pixels + screenOverlay.getSize().setXUnits(ge.UNITS_PIXELS); + screenOverlay.getSize().setYUnits(ge.UNITS_PIXELS); + screenOverlay.getSize().setX(250); + screenOverlay.getSize().setY(75); + + // Specify the point in the image around which to rotate + screenOverlay.getRotationXY().setXUnits(ge.UNITS_FRACTION); + screenOverlay.getRotationXY().setYUnits(ge.UNITS_FRACTION); + screenOverlay.getRotationXY().setX(0.5); + screenOverlay.getRotationXY().setY(0.5); + + // Rotate the overlay + screenOverlay.setRotation(25); + + // Add the ScreenOverlay to Earth + ge.getFeatures().appendChild(screenOverlay); + + + // network link + var link = ge.createLink(''); + var href = 'http://code.google.com/' + + 'apis/earth/documentation/samples/kml_example.kml' + link.setHref(href); + + var networkLink = ge.createNetworkLink(''); + networkLink.set(link, true, true); // Sets the link, refreshVisibility, and flyToView + + ge.getFeatures().appendChild(networkLink); + + // Get the current view. + var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND); + + // Set new latitude and longitude values. + lookAt.setLatitude(36.584207); + lookAt.setLongitude(-121.754322); + + // Update the view in Google Earth. + ge.getView().setAbstractView(lookAt); + + // time + ge.getTime().getControl().setVisibility(ge.VISIBILITY_SHOW); + ge.getTime().setHistoricalImageryEnabled(true); + var extents = ge.getTime().getControl().getExtents(); + var begin = extents.getBegin().get(); + var end = extents.getEnd().get(); + + // tour + ge.getTourPlayer().play(); + + + // controls + ge.getNavigationControl().getScreenXY().setXUnits(ge.UNITS_INSET_PIXELS); + ge.getNavigationControl().getScreenXY().setYUnits(ge.UNITS_PIXELS); + + + // sky + ge.getOptions().setMapType(ge.MAP_TYPE_SKY); + ge.getOptions().setMapType(ge.MAP_TYPE_EARTH); +} diff --git a/google-earth/google-earth.d.ts b/google-earth/google-earth.d.ts new file mode 100644 index 0000000000..d0adc8c04e --- /dev/null +++ b/google-earth/google-earth.d.ts @@ -0,0 +1,3978 @@ +// Type definitions for Google Earth Plugin +// Project: https://developers.google.com/earth/ +// Definitions by: Ilia Choly +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace google { + + export function load( + moduleName: string, + moduleVersion: string, + optionalSettings?: any + ): void; +} + +declare namespace google.earth { + + /** + * Specifies the current stage of the flow of events. + */ + export type GEEventPhaseEnum = any; + + /** + * Specifies how a feature should be displayed in a list view. + */ + export type KmlListItemTypeEnum = any; + + /** + * Specifies which color mode effect to apply to the base color. + */ + export type KmlColorModeEnum = any; + + /* + * Specifies how the altitude property is interpreted. + */ + export type KmlAltitudeModeEnum = any; + + /** + * Specifies how the link is refreshed. + */ + export type KmlRefreshModeEnum = any; + + /** + * Specifies how the link is refreshed when the viewport changes. + */ + export type KmlViewRefreshModeEnum = any; + + /** + * Specifies which units a value is specified in. + */ + type KmlUnitsEnum = any; + + /** + * Specifies if the map type is Earth or sky mode. + */ + type GEMapTypeEnum = any; + + /** + * Specifies if a control is always visible, always hidden, + * or visible only when the user intends to use the control. + */ + type GEVisibilityEnum = any; + + /** + * Specifies what to sample when performing a hit test. + */ + type GEHitTestModeEnum = any; + + /** + * Specifies the size of the navigation control. + */ + type GENavigationControlEnum = any; + + /** + * Specifies the state of viewer options, including sunlight, + * Street View, and historical imagery. + */ + type GEViewerOptionsValueEnum = any; + + /* + * Specifies the viewer option types. + */ + type GEViewerOptionsTypeEnum = any; + + /** + * Whether or not the Google Earth Browser Plug-in and API are supported on the current browser and operating system. + */ + export function isSupported(): boolean; + + /** + * Whether or not the Google Earth Browser Plug-in is currently installed on the user's machine. + * + * Note: if the plug-in is not installed, the user will be presented with a 'download' link upon calls to google.earth.createInstance(). + */ + export function isInstalled(): boolean; + + /** + * Attempts to create an instance of the plugin under the given web browser HTML DOM node. + * Upon success, calls the function passed in as the initCallback argument. + * Upon failure, calls the function passed in as the failureCallback argument and displays an error message to the user in place of the plug-in object. + * + * Note: + * + * The HTML DOM must be loaded before this function can be called. + * Common usage is to call this function upon the 's load event, or to use google.setOnLoadCallback. + */ + export function createInstance( + domNode: string|Element, + initCallback: (plugin: GEPlugin) => void, + failureCallback: (error: any) => void, + options?: any + ): void; + + /** + * Attaches a listener to a given object for a specific event; when the event occurs on the object, the given callback is invoked. + */ + export function addEventListener( + targetObject: any, + eventID: string, + listenerCallback: (event: KmlEvent) => void, + useCapture?: boolean + ): void; + + /** + * Removes an event listener previously added using google.earth.addEventListener() from the event chain. + * + * Note: + * + * You must pass in the exact same function object as was passed to addEventListener. + * If you are using an anonymous function callback, it will need to be refactored into its own variable. + */ + export function removeEventListener( + targetObject: any, + eventID: string, + listenerCallback: (event: KmlEvent) => void, + useCapture?: boolean + ): void; + + /** + * Retrieves and parses a KML or KMZ file at the given URL and returns an instance of a KmlFeature-derived class representing the parsed KML object model. + * + * Note: This function does not display the feature on the Earth. See below for more information. + */ + export function fetchKml( + pluginInstance: GEPlugin, + url: string, + completionCallback: (feature: KmlFeature) => void + ): void; + + /** + * Efficiently executes an arbitrary, user-defined function (the batch function), minimizing the amount of overhead incurred during cross-process communication between the web browser and Google Earth Plugin. + * This method is useful for batching together a large set of calls to the Earth API, for example, a large number of consecutive calls to KmlCoordArray.pushLatLngAlt. + */ + export function executeBatch(pluginInstance: GEPlugin, batchFunction: Function): void; + + /** + * Sets the language to be used for new instances of the plugin. + * Needs to be called before google.earth.createInstance(). + * Affects road and border labels, the error message displayed when the plugin fails to load, as well as the language of the Terms of Use page linked from the plugin. + */ + export function setLanguage(languageCode: string): void; + + /** + * This interface enables programmatic and user-driven interaction with photo overlays in the Google Earth Plugin. + * + * Note: This interface is still under development. + */ + export class GEPhotoOverlayViewer { + + /** + * Enters the given photo overlay object, exiting any other currently active photo overlay. + * If the argument is null, then any currently active photo overlay is exited and normal global navigation is enabled. + */ + setPhotoOverlay(photoOverlay: KmlPhotoOverlay): void; + } + + /** + * Used to manipulate the navigation controls in Google Earth. + */ + export class GENavigationControl { + + /** + * Whether the control is always visible, always hidden, or visible only when the user intends to use the control. + * + * See also: + * + * * GEPlugin.VISIBILITY_SHOW + * * GEPlugin.VISIBILITY_HIDE + * * GEPlugin.VISIBILITY_AUTO + */ + getVisibility(): GEVisibilityEnum; + + /** + * Whether the control is always visible, always hidden, or visible only when the user intends to use the control. + * + * See also: + * + * * GEPlugin.VISIBILITY_SHOW + * * GEPlugin.VISIBILITY_HIDE + * * GEPlugin.VISIBILITY_AUTO + */ + setVisibility(visibility: GEVisibilityEnum): void; + + /** + * Specifies the size of the navigation control. + * + * See also: + * + * * GEPlugin.NAVIGATION_CONTROL_LARGE + * * GEPlugin.NAVIGATION_CONTROL_SMALL + */ + getControlType(): GENavigationControlEnum; + + /** + * Specifies the size of the navigation control. + * + * See also: + * + * * GEPlugin.NAVIGATION_CONTROL_LARGE + * * GEPlugin.NAVIGATION_CONTROL_SMALL + */ + setControlType(controlType: GENavigationControlEnum): void; + + /** + * The position of the navigation controls in Google Earth + */ + getScreenXY(): KmlVec2; + + /** + * Enables or disables user-initiated entry to Street View imagery. + * When true, the Pegman icon is present in the navigation controls, allowing a user to drag the Pegman onto a street to initiate Street View. + * Users can also zoom down to ground level to enter Street View when this is set to true. + */ + setStreetViewEnabled(streetViewEnabled: boolean): void; + + /** + * Whether Street View is enabled in the navigation controls. + */ + getStreetViewEnabled(): boolean; + } + + /** + * Defines a tour, which is a playlist of scripted camera and update events. + * + * Note: This interface is still under development. + */ + export class KmlTour extends KmlFeature {} + + /** + * This interface enables programmatic and user-driven interaction with KML tours in the Google Earth Plugin. + * + * Note: This interface is still under development. + */ + export class GETourPlayer { + + /** + * Enters the given tour object, exiting any other currently active tour. + * This method does not automatically begin playing the tour. + * If the argument is null, then any currently active tour is exited and normal globe navigation is enabled. + */ + setTour(tour: KmlTour): void; + + /** + * Plays the currently active tour. + */ + play(): void; + + /** + * Pauses the currently active tour. + */ + pause(): void; + + /** + * Resets the currently active tour, stopping playback and rewinding to the start of the tour. + */ + reset(): void; + + /** + * The current elapsed playing time of the active tour, in seconds. + */ + getCurrentTime(): number; + + /** + * The current elapsed playing time of the active tour, in seconds. + */ + setCurrentTime(currentTime: number): void; + + /** + * The total duration of the active tour, in seconds. If no tour is loaded, the behavior of this method is undefined. + */ + getDuration(): number; + } + + /** + * This interface contains result information obtained by calling GEView's hitTest method. + * + * See also: + * + * * GEView.hitTest + */ + export class GEHitTestResult { + + /** + * Latitude of sampled point. + */ + getLatitude(): number; + + /** + * Latitude of sampled point. + */ + setLatitude(latitude: number): void; + + /** + * Longitude of sampled point. + */ + getLongitude(): number; + + /** + * Longitude of sampled point. + */ + setLongitude(longitude: number): void; + + /** + * Altitude of sampled point. + */ + getAltitude(): number; + + /** + * Altitude of sampled point. + */ + setAltitude(altitude: number): void; + } + + /** + * Maps between two different icon styles. + * Typically this interface is used to provide separate normal and highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon. + */ + export class KmlStyleMap extends KmlStyleSelector { + + /** + * Sets both URLs for the placemark style. + */ + setUrl(normalStyleUrl: string, highlightStyleUrl: string): void; + + /** + * Sets both placemark styles. + */ + setStyle(normalStyle: KmlStyle, highlightStyle: KmlStyle): void; + + /** + * Defines a normal style for a placemark. + */ + getNormalStyleUrl(): string; + + /** + * Defines a normal style for a placemark. + */ + setNormalStyleUrl(normalStyleUrl: string): void; + + /** + * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + getHighlightStyleUrl(): string; + + /** + * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + setHighlightStyleUrl(highlightStyleUrl: string): void; + + /** + * Defines a normal style for a placemark. + */ + getNormalStyle(): KmlStyle; + + /** + * Defines a normal style for a placemark. + */ + setNormalStyle(normalStyle: KmlStyle): void; + + /** + * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + getHighlightStyle(): KmlStyle; + + /** + * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + setHighlightStyle(highlightStyle: KmlStyle): void; + } + + /** + * References a KML file or KMZ archive on a remote network. + * Use the Link property to specify the location of the KML file. + * Within that property, you can define the refresh options for updating the file, based on time and camera change. + * NetworkLinks can be used in combination with Regions to handle very large datasets efficiently. + */ + export class KmlNetworkLink extends KmlFeature { + + /** + * Sets the link, refreshVisibility, and flyToView for the network link. + */ + set(link: KmlLink, refreshVisibility: boolean, flyToView: boolean): void; + + /** + * Specifies the location of any of the following: + * + * * KML files fetched by network links + * * Image files used by icons in icon styles, ground overlays, and screen overlays + * * Model files used in the Model object + */ + getLink(): KmlLink; + + /** + * Specifies the location of any of the following: + * + * * KML files fetched by network links + * * Image files used by icons in icon styles, ground overlays, and screen overlays + * * Model files used in the Model object + */ + setLink(link: KmlLink): void; + + /** + * A value of 0 leaves the visibility of features within the control of the Google Earth user. + * Set the value to 1 to reset the visibility of features each time the NetworkLink is refreshed. + * For example, suppose a Placemark within the linked KML file has visibility set to 1 and the NetworkLink has refreshVisibility set to 1. + * When the file is first loaded into Google Earth, the user can clear the check box next to the item to turn off display in the 3D viewer. + * However, when the NetworkLink is refreshed, the Placemark will be made visible again, since its original visibility state was TRUE. + */ + getRefreshVisibility(): boolean; + + /** + * A value of 0 leaves the visibility of features within the control of the Google Earth user. + * Set the value to 1 to reset the visibility of features each time the NetworkLink is refreshed. + * For example, suppose a Placemark within the linked KML file has visibility set to 1 and the NetworkLink has refreshVisibility set to 1. + * When the file is first loaded into Google Earth, the user can clear the check box next to the item to turn off display in the 3D viewer. + * However, when the NetworkLink is refreshed, the Placemark will be made visible again, since its original visibility state was TRUE. + */ + setRefreshVisibility(refreshVisibility: boolean): void; + + /** + * A value of 1 causes Google Earth to fly to the view of the LookAt or Camera in the NetworkLinkControl (if it exists). + */ + getFlyToView(): boolean; + + /** + * A value of 1 causes Google Earth to fly to the view of the LookAt or Camera in the NetworkLinkControl (if it exists). + */ + setFlyToView(flyToView: boolean): void; + } + + /** + * Draws an image overlay fixed to the screen. + * Sample uses for ScreenOverlays are compasses, logos, and heads-up displays. + * ScreenOverlay sizing is determined by the size element. + * Positioning of the overlay is handled by mapping a point in the image specified by screenXY to a point on the screen specified by overlayXY. + * Then the image is rotated by rotation degrees about a point relative to the screen specified by rotationXY. + * + * Note: + * + * screenXY and overlayXY behave opposite to their corresponding behaviors in KML. + * This is due to a bug in the Earth API that will intentionally remain unfixed until a major version change. + */ + export class KmlScreenOverlay extends KmlOverlay { + + /** + * Specifies a point on (or outside of) the overlay image that is mapped to the screen coordinate. + * It requires x and y values, and the units for those values. + * + * Note: + * + * screenXY and overlayXY behave opposite to their corresponding behaviors in KML. + * This is due to a bug in the Earth API that will intentionally remain unfixed until a major version change. + */ + getScreenXY(): KmlVec2; + + /** + * Specifies a point relative to the screen origin that the overlay image is mapped to. + * The x and y values can be specified in three different ways: as pixels ("pixels"), as fractions of the screen ("fraction"), or as inset pixels ("insetPixels"), which is an offset in pixels from the upper right corner of the screen. + * The x and y positions can be specified in different ways - for example, x can be in pixels and y can be a fraction. + * The origin of the coordinate system is in the lower left corner of the screen. + * + * Note: + * + * screenXY and overlayXY behave opposite to their corresponding behaviors in KML. + * This is due to a bug in the Earth API that will intentionally remain unfixed until a major version change. + */ + getOverlayXY(): KmlVec2; + + /** + * Point relative to the screen about which the screen overlay is rotated. + */ + getRotationXY(): KmlVec2; + + /** + * Specifies the size of the image for the screen overlay, as follows: + * + * * A value of -1 indicates to use the native dimension + * * A value of 0 indicates to maintain the aspect ratio + * * A value of n sets the value of the dimension + */ + getSize(): KmlVec2; + + /** + * Adjusts how the image is placed inside the field of view. + * This element is useful if your image has been rotated and deviates slightly from a desired horizontal view. + */ + getRotation(): number; + + /** + * Adjusts how the image is placed inside the field of view. + * This element is useful if your image has been rotated and deviates slightly from a desired horizontal view. + */ + setRotation(rotation: number): void; + } + + /** + * Defines a photo overlay, which is a geographically located photograph of the Earth. + * Photo overlays can be drawn onto 2D rectangles in three dimensional space, or in the case of panoramic photos, onto partial or full cylinders, or even spheres. + * + * Note: This interface is still under development. + */ + export class KmlPhotoOverlay extends KmlOverlay {} + + /** + * Draws an image overlay draped onto the terrain. + * The href child of Icon specifies the image to be used as the overlay. + * If this object is omitted or contains no href, a rectangle is drawn using the color defined by the overlay. + */ + export class KmlGroundOverlay extends KmlOverlay { + + /** + * Specifies the distance above the earth's surface. + */ + getAltitude(): number; + + /** + * Specifies the distance above the earth's surface. + */ + setAltitude(altitude: number): void; + + /** + * Specifies how the altitude property is interpreted. + * + * See also: + * + * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how the altitude property is interpreted. + * + * See also: + * + * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; + + /** + * The bounding box of the ground overlay. + */ + getLatLonBox(): KmlLatLonBox; + + /** + * The bounding box of the ground overlay. + */ + setLatLonBox(latLonBox: KmlLatLonBox): void; + } + + /** + * The KmlOverlay object is an abstract object and cannot be used directly in a KML file. + * Overlay is the base type for image overlays drawn on the planet surface or on the screen. + * Icon specifies the image to use and can be configured to reload images based on a timer or by camera changes. + * This object also includes specifications for stacking order of multiple overlays and for adding color and transparency values to the base image. + */ + export class KmlOverlay extends KmlFeature { + + /** + * Specifies the color values. + */ + getColor(): KmlColor; + + /** + * Defines the stacking order for the images in overlapping overlays. + * Overlays with higher drawOrder values are drawn on top of overlays with lower drawOrder values. + */ + getDrawOrder(): number; + + /** + * Defines the stacking order for the images in overlapping overlays. + * Overlays with higher drawOrder values are drawn on top of overlays with lower drawOrder values. + */ + setDrawOrder(drawOrder: number): void; + + /** + * Defines the image associated with the Overlay. + */ + getIcon(): KmlIcon; + + /** + * Defines the image associated with the Overlay. + */ + setIcon(icon: KmlIcon): void; + } + + /** + * This class controls the display of sunlight, historical imagery, and Street View panoramas in the plugin. + * The KmlViewerOptions object is passed to KmlAbstractView.setViewerOptions() + */ + export class KmlViewerOptions extends KmlObject { + + /** + * Returns the current state of the specified viewer option type. + * + * See also: + * + * * GEPlugin.OPTION_STREET_VIEW + * * GEPlugin.OPTION_SUNLIGHT + * * GEPlugin.OPTION_HISTORICAL_IMAGERY + * * GEPlugin.OPTION_STATE_DEFAULT + * * GEPlugin.OPTION_STATE_ENABLED + * * GEPlugin.OPTION_STATE_DISABLED + */ + setOption(type: GEViewerOptionsTypeEnum, state: GEViewerOptionsValueEnum): void; + + /** + * Set the state of viewer options, including sunlight, Street View, and historical imagery. + * + * See also: + * + * * GEPlugin.OPTION_STREET_VIEW + * * GEPlugin.OPTION_SUNLIGHT + * * GEPlugin.OPTION_HISTORICAL_IMAGERY + * * GEPlugin.OPTION_STATE_DEFAULT + * * GEPlugin.OPTION_STATE_ENABLED + * * GEPlugin.OPTION_STATE_DISABLED + */ + getOption(type: GEViewerOptionsValueEnum): GEViewerOptionsValueEnum; + } + + /** + * Describes rotation of a 3D model's coordinate system to position the object in Google Earth. + */ + export class KmlOrientation extends KmlObject { + + /** + * Sets the heading, tilt, and roll of a model. + */ + set(heading: number, tilt: number, roll: number): void; + + /** + * Rotation about the z axis (normal to the Earth's surface). + * A value of 0 (the default) equals North. + * A positive rotation is clockwise around the z axis and specified in degrees from 0 to 360. + */ + getHeading(): number; + + /** + * Rotation about the z axis (normal to the Earth's surface). + * A value of 0 (the default) equals North. + * A positive rotation is clockwise around the z axis and specified in degrees from 0 to 360. + */ + setHeading(heading: number): void; + + /** + * Rotation about the x axis. + * A positive rotation is clockwise around the x axis and specified in degrees from 0 to 360. + */ + getTilt(): number; + + /** + * Rotation about the x axis. + * A positive rotation is clockwise around the x axis and specified in degrees from 0 to 360. + */ + setTilt(tilt: number): void; + + /** + * Rotation about the y axis. + * A positive rotation is clockwise around the y axis and specified in degrees from 0 to 360. + */ + getRoll(): number; + + /** + * Rotation about the y axis. + * A positive rotation is clockwise around the y axis and specified in degrees from 0 to 360. + */ + setRoll(roll: number): void; + } + + /** + * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. + * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. + * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. + */ + export class KmlLocation extends KmlObject { + + /** + * Sets the latitude, longitude, and altitude of the Model. + */ + setLatLngAlt(lat: number, lng: number, alt: number): void; + + /** + * Longitude of the Model's location. + * Angular distance in degrees, relative to the Prime Meridian. + * Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + getLongitude(): number; + + /** + * Longitude of the Model's location. + * Angular distance in degrees, relative to the Prime Meridian. + * Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + setLongitude(longitude: number): void; + + /** + * Latitude of the camera location. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + getLatitude(): number; + + /** + * Latitude of the camera location. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + setLatitude(latitude: number): void; + + /** + * Specifies the distance above the earth's surface. + */ + getAltitude(): number; + + /** + * Specifies the distance above the earth's surface. + */ + setAltitude(altitude: number): void; + } + + /** + * Scales a model along the x, y, and z axes in the model's coordinate space. + */ + export class KmlScale extends KmlObject { + + /** + * Sets the x, y, and z coordinates for a model. + */ + set(x: number, y: number, z: number): void; + + /** + * Indicates the x coordinate. + */ + getX(): number; + + /** + * Indicates the x coordinate. + */ + setX(x: number): void; + + /** + * Indicates the y coordinate. + */ + getY(): number; + + /** + * Indicates the y coordinate. + */ + setY(y: number): void; + + /** + * Indicates the z coordinate. + */ + getZ(): number; + + /** + * Indicates the z coordinate. + */ + setZ(z: number): void; + } + + /** + * A single tuple consisting of floating point values for longitude, latitude, and altitude (in that order). + * Longitude and latitude values are in degrees. + * + * * longitude = -180 and <= 180 + * * latitude = -90 and = 90 + * * altitude values (optional) are in meters above sea level + */ + export class KmlCoord { + + /** + * Sets the latitude, longitude, altitude. + */ + setLatLngAlt(latitude: number, longitude: number, altitude: number): void; + + /** + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + getLatitude(): number; + + /** + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + setLatitude(latitude: number): void; + + /** + * Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + getLongitude(): number; + + /** + * Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + setLongitude(longitude: number): void; + + /** + * Distance from the earth's surface. + */ + getAltitude(): number; + + /** + * Distance from the earth's surface. + */ + setAltitude(altitude: number): void; + } + + /** + * The KmlCoordArray object defines an array of coordinates. + */ + export class KmlCoordArray { + + /** + * Returns the coordinates at the given index. + */ + get(index: number): KmlCoord; + + /** + * Sets the coordinates at the given index.. + */ + set(index: number, coord: KmlCoord): void; + + /** + * Sets the latitude, longitude, and altitude. + */ + setLatLngAlt( + index: number, + latitude: number, + longitude: number, + altitude: number + ): void; + + /** + * Appends one or more new elements to the end of an array and returns the new length of the array. + */ + pushLatLngAlt( + latitude: number, + longitude: number, + altitude: number + ): void; + + /** + * Appends one or more new elements to the end of an array and returns the new length of the array. + */ + push(coordOrList: KmlCoord): void; + + /** + * Deletes the last element of an array, decrements the array length, and returns the value that is removed. + */ + pop(): KmlCoord; + + /** + * Adds an element or elements to the beginning of an array. + */ + unshift(coordOrList: KmlCoord): number; + + /** + * Adds an element or elements to the beginning of an array. + */ + unshiftLatLngAlt( + latitude: number, + longitude: number, + altitude: number + ): void; + + /** + * Removes and returns the first element of the array. + */ + shift(): KmlCoord; + + /** + * Reverses the order of the elements in the array. + */ + reverse(): void; + + /** + * Clears all of the elements in the array + */ + clear(): void; + + /** + * Specifies the length of the index array. + */ + getLength(): number; + } + + /** + * The object corresponding to the retangular region in which Google Earth is displayed. + */ + export class GEWindow extends GEEventEmitter { + + /** + * Gives the Google Earth object focus. + */ + focus(): void; + + /** + * Removes focus from the Google Earth object. + */ + blur(): void; + + /** + * Toggles the overall visibility of Google Earth inside the browser. + */ + getVisibility(): boolean; + + /** + * Toggles the overall visibility of Google Earth inside the browser. + */ + setVisibility(visibility: boolean): void; + } + + /** + * The GEGlobe class encapsulates the Google Earth globe to determine access and event behavior. + */ + export class GEGlobe extends KmlObject { + + /** + * Returns the altitude for a given location on the globe. + * If the altitude data for the location has not yet been loaded, the return value is 0. + */ + getGroundAltitude(lat: number, lon: number): number; + + /** + * The top-level features currently in the Earth instance. + */ + getFeatures(): GEFeatureContainer; + } + + /** + * Controls the behavior of the camera that views the scene in Google Earth. + */ + export class GEView { + + /** + * Returns the screen x,y coordinates of a given point on the globe. + * + * Tip: project() is the inverse of hitTest(). + * + * See also: + * + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + project( + lat: number, + lng: number, + alt: number, + altitudeMode: KmlAltitudeModeEnum + ): KmlVec2; + + /** + * Sets the camera that views the scene in Google Earth. + */ + setAbstractView(view: KmlAbstractView): void; + + /** + * Creates and returns a new KmlLookAt object, initialized to the current camera position and orientation. + * Use 'altitudeMode' to specify the altitude mode of the looked-at point. + * + * See also: + * + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + copyAsLookAt(altitudeMode: KmlAltitudeModeEnum): KmlLookAt; + + /** + * Creates and returns a new KmlCamera object, initialized to the current camera position and orientation. + * Use 'altitudeMode' to specify the altitude mode of the new camera. + * + * See also: + * + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + copyAsCamera(altitudeMode: KmlAltitudeModeEnum): KmlCamera; + + /** + * Returns a bounding box that completely contains the region of the globe that is currently visible. + * The returned box will be larger than what is strictly visible, if that is necessary to include everything that is visible. + */ + getViewportGlobeBounds(): KmlLatLonBox; + + /** + * Given a point on the screen in pixel coordinates, returns a GEHitTestResult with information about the geographic location corresponding to the point on the screen. + * Tip: hitTest() is the inverse of project(). + * + * See also: + * + * * GEPlugin.UNITS_PIXELS + * * GEPlugin.UNITS_INSET_PIXELS + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.HIT_TEST_GLOBE + * * GEPlugin.HIT_TEST_TERRAIN + * * GEPlugin.HIT_TEST_BUILDINGS + */ + hitTest( + x: number, + xUnits: KmlUnitsEnum, + y: number, + yUnits: KmlUnitsEnum, + mode: GEHitTestModeEnum + ): GEHitTestResult; + } + + /** + * Defines an image associated with an Icon style or overlay. + */ + export class KmlIcon extends KmlLink { + + /** + * Gets the offset from the left (), in pixels, of the icon. + */ + getX(): number; + + /** + * Specifies the icon's offset (), in pixels from the left side of its icon palette, if a palette has been specified in the element. + */ + setX(x: number): number; + + /** + * Gets the offset from the bottom (), in pixels, of the icon. + */ + getY(): number; + + /** + * Specifies the offset (), in pixels from the bottom of its icon palette, if a palette has been specified in the element. + */ + setY(y: number): void; + + /** + * Gets the width (), in pixels, of the icon. + */ + getW(): number; + + /** + * Specifies the width (), in pixels, of the icon to use. + */ + setW(w: number): void; + + /** + * Gets the height (), in pixels, of the icon. + */ + getH(): number; + + /** + * Specifies the height (), in pixels, of the icon to use. + */ + setH(h: number): void; + } + + /** + * Specifies the location of any KML files fetched by network links, image files used by icons in icon styles, ground overlays, and screen overlays, or model files used in the Model object. + */ + export class KmlLink extends KmlObject { + + /** + * A URL (either an HTTP address or a local file specification). + * When the parent of Link is a NetworkLink, href is a KML file. + * When the parent of Link is a Model, href is a COLLADA file. + * When the parent of Link is an Overlay, href is an image. + */ + getHref(): string; + + /** + * A URL (either an HTTP address or a local file specification). + * When the parent of Link is a NetworkLink, href is a KML file. + * When the parent of Link is a Model, href is a COLLADA file. + * When the parent of Link is an Overlay, href is an image. + */ + setHref(href: string): void; + + /** + * Specifies to use a time-based refresh mode. + * + * See also: + * + * * GEPlugin.REFRESH_ON_CHANGE + * * GEPlugin.REFRESH_ON_INTERVAL + * * GEPlugin.REFRESH_ON_EXPIRE + */ + getRefreshMode(): KmlRefreshModeEnum; + + /** + * Specifies to use a time-based refresh mode. + * + * See also: + * + * * GEPlugin.REFRESH_ON_CHANGE + * * GEPlugin.REFRESH_ON_INTERVAL + * * GEPlugin.REFRESH_ON_EXPIRE + */ + setRefreshMode(refreshMode: KmlRefreshModeEnum): void; + + /** + * Indicates to refresh the file every n seconds. + */ + getRefreshInterval(): number; + + /** + * Indicates to refresh the file every n seconds. + */ + setRefreshInterval(refreshInterval: number): void; + + /** + * Specifies how the link is refreshed when the viewport changes. + * + * See also: + * + * * GEPlugin.VIEW_REFRESH_NEVER + * * GEPlugin.VIEW_REFRESH_ON_STOP + * * GEPlugin.VIEW_REFRESH_ON_REGION + */ + getViewRefreshMode(): KmlViewRefreshModeEnum; + + /** + * Specifies how the link is refreshed when the viewport changes. + * + * See also: + * + * * GEPlugin.VIEW_REFRESH_NEVER + * * GEPlugin.VIEW_REFRESH_ON_STOP + * * GEPlugin.VIEW_REFRESH_ON_REGION + */ + setViewRefreshMode(viewRefreshMode: KmlViewRefreshModeEnum): void; + + /** + * Specifies how the link is refreshed when the camera changes. + */ + getViewRefreshTime(): number; + + /** + * Specifies how the link is refreshed when the camera changes. + */ + setViewRefreshTime(viewRefreshTime: number): void; + + /** + * Scales the BBOX parameters before sending them to the server. + * A value less than 1 specifies to use less than the full view (screen). + * A value greater than 1 specifies to fetch an area that extends beyond the edges of the current view. + */ + getViewBoundScale(): number; + + /** + * Scales the BBOX parameters before sending them to the server. + * A value less than 1 specifies to use less than the full view (screen). + * A value greater than 1 specifies to fetch an area that extends beyond the edges of the current view. + */ + setViewBoundScale(viewBoundScale: number): void; + + /** + * Specifies the format of the query string that is appended to the Link's href before the file is fetched. + * (If the href specifies a local file, this element is ignored.) + */ + getViewFormat(): string; + + /** + * Specifies the format of the query string that is appended to the Link's href before the file is fetched. + * (If the href specifies a local file, this element is ignored.) + */ + setViewFormat(viewFormat: string): void; + } + + /** + * Controls time in the plugin. + */ + export class GETime { + + /** + * Set the plugin's clock rate. + * A value of 1 corresponds with real time; to pass one year in the plugin for every real second, set the rate to 31536000 (60 times 60 times 24 times 365). + */ + setRate(rate: number): void; + + /** + * Get the current plugin clock rate. + */ + getRate(): number; + + /** + * Returns the current computer clock time as a KmlTimeStamp object. + */ + getSystemTime(): KmlTimeStamp; + + /** + * Returns the GETimeControl object; this is the time slider. + */ + getControl(): GETimeControl; + + /** + * Whether or not historical imagery is enabled. + */ + getHistoricalImageryEnabled(): boolean; + + /** + * Turn historical imagery on or off. + * For more information, read the Time chapter of the Developer's Guide. + */ + setHistoricalImageryEnabled(historicalImageryEnabled: boolean): void; + + /** + * Get the current plugin time as a KmlTimeStamp or KmlTimeSpan. + */ + getTimePrimitive(): KmlTimePrimitive; + + /** + * Sets the current plugin time. + */ + setTimePrimitive(timePrimitive: KmlTimePrimitive): void; + } + + /** + * Used to manipulate the behavior of the Google Earth options such as, navigation, flyToSpeed, scroll wheel speed and so on. + */ + export class GEOptions { + + /** + * Sets the map type to Earth or sky mode. + */ + setMapType(type: GEMapTypeEnum): void; + + /** + * Speed of zoom when user rolls the mouse wheel. Default is 1. + * Set to a negative number to reverse the zoom direction. + */ + getScrollWheelZoomSpeed(): number; + + /** + * Speed of zoom when user rolls the mouse wheel. Default is 1. + * Set to a negative number to reverse the zoom direction. + */ + setScrollWheelZoomSpeed(scrollWheelZoomSpeed: number): void; + + /** + * Specifies the speed at which the camera moves (0 to 5.0). + * Set to SPEED_TELEPORT to immediately appear at selected destination. + * + * See also: + * + * * GEPlugin.SPEED_TELEPORT + */ + getFlyToSpeed(): number; + + /** + * Specifies the speed at which the camera moves (0 to 5.0). + * Set to SPEED_TELEPORT to immediately appear at selected destination. + * + * See also: + * + * * GEPlugin.SPEED_TELEPORT + */ + setFlyToSpeed(flyToSpeed: number): void; + + /** + * Show or hide the status bar. Disabled by default. + */ + getStatusBarVisibility(): boolean; + + /** + * Show or hide the status bar. Disabled by default. + */ + setStatusBarVisibility(statusBarVisibility: boolean): void; + + /** + * Show or hide the grid. Disabled by default. + */ + getGridVisibility(): boolean; + + /** + * Show or hide the grid. Disabled by default. + */ + setGridVisibility(gridVisibility: boolean): void; + + /** + * Show or hide the overview map. Disabled by default. + */ + getOverviewMapVisibility(): boolean; + + /** + * Show or hide the overview map. Disabled by default. + */ + setOverviewMapVisibility(overviewMapVisibility: boolean): void; + + /** + * Show or hide the scale legend. Disabled by default. + */ + getScaleLegendVisibility(): boolean; + + /** + * Show or hide the scale legend. Disabled by default. + */ + setScaleLegendVisibility(scaleLegendVisibility: boolean): void; + + /** + * Show or hide the blue atmosphere that appears around the perimeter of the Earth. + * On by default. + */ + getAtmosphereVisibility(): boolean; + + /** + * Show or hide the blue atmosphere that appears around the perimeter of the Earth. + * On by default. + */ + setAtmosphereVisibility(atmosphereVisibility: boolean): void; + + /** + * Enable or disable user panning and zooming of the map. Enabled by default. + * + * Note: This also enables and disables keyboard navigation (arrow keys, page-up/page-down, etc). + */ + getMouseNavigationEnabled(): boolean; + + /** + * Enable or disable user panning and zooming of the map. Enabled by default. + * + * Note: This also enables and disables keyboard navigation (arrow keys, page-up/page-down, etc). + */ + setMouseNavigationEnabled(mouseNavigationEnabled: boolean): void; + + /** + * Returns true if the animation of features as they are added or removed from the globe has been enabled. + */ + getFadeInOutEnabled(): boolean; + + /** + * Enable or disable the animation of a feature when it is added or removed from the Google Earth plugin. + * The animation consists of a slight change of scale. Default is true. + */ + setFadeInOutEnabled(fadeInOutEnabled: boolean): void; + + /** + * Returns true if display units are set to imperial units (feet and miles). + * False denotes metric units (meters and kilometers). + */ + getUnitsFeetMiles(): boolean; + + /** + * Set display units to imperial (feet and miles) or metric (meters and kilometers). + * This setting affects only the values displayed in the status bar and the scale bar. + * The values passed and returned with an object's getters and setters are always metric. + */ + setUnitsFeetMiles(unitsFeetMiles: boolean): void; + + /** + * Enables or disables building selection. + * If enabled, clicking a building will pop a feature balloon containing information from the Google 3D Warehouse database. + */ + setBuildingSelectionEnabled(buildingSelectionEnabled: boolean): void; + + /** + * Whether or not building selection is enabled. + */ + getBuildingSelectionEnabled(): boolean; + + /** + * Returns true if building highlighting is enabled. + */ + getBuildingHighlightingEnabled(): boolean; + + /** + * Enables or disables building highlighting. + * When enabled, buildings will be highlighted when they are moused over. + */ + setBuildingHighlightingEnabled(buildingHighlightingEnabled: boolean): void; + + /** + * Returns the terrain exaggeration value. Valid values are in the range of 1.0 through 3.0. + */ + getTerrainExaggeration(): number; + + /** + * Set the terrain exaggeration value. Valid values are in the range of 1.0 through 3.0. + * Attempting to set outside of this range will result in the value being clamped. + */ + setTerrainExaggeration(terrainExaggeration: number): void; + + /** + * When enabled, the view will change to 'ground level view' when the camera reaches ground level. + * This view provides pan and lookAt controls, but no zoom slider. + * The tilt will be set to 90, or parallel with level ground. + */ + setAutoGroundLevelViewEnabled(autoGroundLevelViewEnabled: boolean): void; + + /** + * Whether automatic ground level view is enabled. + */ + getAutoGroundLevelViewEnabled(): boolean; + } + + /** + * Adds a node to the end of the list of children of a specified feature. + * Returns the appended object. + */ + export class GESchemaObjectContainer { + + /** + * Adds a node to the end of the list of children of a specified feature. + * Returns the appended object. + */ + appendChild(object: T): void; + + /** + * Removes a node from the list of children of a specified object. + */ + removeChild(oldChild: T): void; + + /** + * Inserts a child before the referenced child in the list of objects. + */ + insertBefore(newChild: T, refChild: T): void; + + /** + * Replaces existing child in the list of features. + * Returns the old child. + */ + replaceChild(newChild: T, oldChild: T): void; + + /** + * Returns true if the container is not empty. + */ + hasChildNodes(): boolean; + + /** + * First child in the list of objects. + */ + getFirstChild(): T; + + /** + * Last child in the list of objects. + */ + getLastChild(): T; + + /** + * List of features (for KmlContainer), or list of features, styles, and schemas (for KmlDocument). + * Returns true if there are any child nodes. + */ + getChildNodes(): KmlObjectList; + } + + /** + * A container class that holds one or more features and allows the creation of nested hierarchies. + */ + export class GEFeatureContainer extends GESchemaObjectContainer {} + + /** + * A container object that contains an array of geometries, typically the children of a multi-geometry. + */ + export class GEGeometryContainer extends GESchemaObjectContainer {} + + /** + * A container object that contains an array of closed line strings, typically the outer boundary of a Polygon. + * Optionally, a LinearRing can also be used as the inner boundary of a Polygon to create holes in the Polygon. + * A Polygon can contain multiple LinearRing objects used as inner boundaries. + */ + export class GELinearRingContainer extends GESchemaObjectContainer {} + + /** + * A container that holds a collection of KmlStyle and KmlStyleMap objects. + * The KmlStyleMap object selects a style based on the current mode of the Placemark. + * An object derived from KmlStyleSelector is uniquely identified by its ID and its URL. + */ + export class GEStyleSelectorContainer extends GESchemaObjectContainer {} + + /** + * Defines the x and y coordinates of a 2D vector. + */ + export class KmlVec2 { + + /** + * Sets the coordinates of the vector. + */ + set( + x: number, + xUnits: KmlUnitsEnum, + y: number, + yUnits: KmlUnitsEnum + ): void; + + /** + * Indicates the x coordinate. + */ + getX(): number; + + /** + * Indicates the x coordinate. + */ + setX(x: number): void; + + /** + * Indicates the y coordinate. + */ + getY(): number; + + /** + * Indicates the y coordinate. + */ + setY(y: number): void; + + /** + * Units in which the x value is specified. + * + * See also: + * + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.UNITS_PIXELS + * * GEPlugin.UNITS_INSET_PIXELS + */ + getXUnits(): KmlUnitsEnum; + + /** + * Units in which the x value is specified. + * + * See also: + * + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.UNITS_PIXELS + * * GEPlugin.UNITS_INSET_PIXELS + */ + setXUnits(xUnits: KmlUnitsEnum): void; + + /** + * Units in which the y value is specified. + * + * See also: + * + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.UNITS_PIyELS + * * GEPlugin.UNITS_INSET_PIyELS + */ + getYUnits(): KmlUnitsEnum; + + /** + * Units in which the y value is specified. + * + * See also: + * + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.UNITS_PIyELS + * * GEPlugin.UNITS_INSET_PIyELS + */ + setYUnits(xUnits: KmlUnitsEnum): void; + } + + /** + * The GESun class controls the dawn to dusk views. + */ + export class GESun { + + /** + * Specifies whether the feature is drawn in the 3D viewer when it is initially loaded. + * In order for a feature to be visible, the visibility property and all of its ancestors must also be set to 1. + */ + getVisibility(): boolean; + + /** + * Specifies whether the feature is drawn in the 3D viewer when it is initially loaded. + * In order for a feature to be visible, the visibility property and all of its ancestors must also be set to 1. + */ + setVisibility(visibility: boolean): void; + } + + /** + * The KmlColor object values are expressed in hexadecimal notation. + * The range of values for any one color component is 0 to 255 (00 to ff). + * For alpha, 00 is fully transparent and ff is fully opaque. + * The order of expression is aabbggrr, where aa=alpha (00 to ff); bb=blue (00 to ff); gg=green (00 to ff); rr=red (00 to ff). + * For example, if you want to apply a blue color with 50 percent opacity to an overlay, + * you would specify the following when setting color value: 7fff0000, where alpha=0x7f, blue=0xff, green=0x00, and red=0x00. + */ + export class KmlColor { + + /** + * Set the color of an object. + */ + set(color: string): void; + + /** + * Returns the color of an object. + */ + get(): string; + + /** + * red numerical value + */ + getR(): number; + + /** + * red numerical value + */ + setR(r: number): void; + + /** + * green numerical value + */ + getG(): number; + + /** + * green numerical value + */ + setG(g: number): void; + + /** + * blue numerical value + */ + getB(): number; + + /** + * blue numerical value + */ + setB(b: number): void; + + /** + * opacity value + */ + getA(): number; + + /** + * opacity value + */ + setA(a: number): void; + } + + /** + * The event object used with all KMLObjects. + * For more information about events, see the Document Object Model Events specification at http: + */ + export class KmlEvent { + + /** + * Cancels the default action of the event. + * For example, calling this method in a placemark click handler prevents the placemark's default balloon from popping up. + */ + preventDefault(): void; + + /** + * Prevents event propagation. + * For example, if click event handlers are set up on both the GEGlobe and GEWindow objects, + * and stopPropagation is called in the GEGlobe click event handler, the GEWindow event handler will not be triggered when the globe is clicked. + */ + stopPropagation(): void; + + /** + * The object to which the KMLEvent was originally dispatched. + */ + getTarget(): GEEventEmitter; + + /** + * The target whose event listeners are currently being processed. + */ + getCurrentTarget: GEEventEmitter; + + /** + * The current stage of the flow of events. + */ + getEventPhase(): GEEventPhaseEnum; + + /** + * Indicates whether or not an event is a bubbling event. + */ + getBubbles(): boolean; + + /** + * Indicates whether the event can be cancelled. + * + * Note: Currently, cancelable has no effect. + */ + getCancelable(): boolean; + } + + /** + * Represents a mouse input event. + */ + export class KmlMouseEvent extends KmlEvent { + + /** + * The button on the mouse was pressed. + * Possible values include 0, 1, 2, where 0 is left, 1 is middle, and 2 is right mouse key. + */ + getButton(): number; + + /** + * The x coordinate at which the event occurred, measured in pixels from the left edge of the plug-in window. + */ + getClientX(): number; + + /** + * The y coordinate at which the event occurred, measured in pixels from the top edge of the plug-in window. + */ + getClientY(): number; + + /** + * The x coordinate at which the event occurred, measured in pixels from the left edge of the computer screen. + */ + getScreenX(): number; + + /** + * The y coordinate at which the event occurred, measured in pixels from the top edge of the computer screen. + */ + getScreenY(): number; + + /** + * The latitude at which the event occurred, in decimal degrees. + */ + getLatitude(): number; + + /** + * The longitude at which the event occurred, in decimal degrees. + */ + getLongitude(): number; + + /** + * The altitude at which the event occurred, in meters. + */ + getAltitude(): number; + + /** + * Indicates whether a mouse action occurred while on the Google Earth globe. + */ + getDidHitGlobe(): boolean; + + /** + * Indicates whether the ALT key was held down when an event occurred. + */ + getAltKey(): boolean; + + /** + * Indicates whether the CTRL key was held down when an event occurred. + */ + getCtrlKey(): boolean; + + /** + * Indicates whether the SHIFT key was held down when an event occurred. + */ + getShiftKey(): boolean; + + /** + * Used with the mouseover and mouseout events to specify a secondary target. + * For mouseover, it specifies the object that the mouse was over. + * For mouseout, it specifies the new object that the mouse is over. + */ + getRelatedTarget(): GEEventEmitter; + + /** + * Returns the timestamp of the event, in Unix time. + */ + getTimeStamp(): number; + } + + /** + * Defines when and how an event gets passed in and triggered from the Google Earth Plug-in. + */ + export class GEEventEmitter { + + /** + * Triggers an event when the user clicks a location in Google Earth with the mouse. + */ + click(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user double clicks a location in Google Earth with the mouse. + */ + dblclick(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user moves the mouse pointer over a location in Google Earth. + */ + mouseover(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user presses the mouse button over a location in Google Earth. + */ + mousedown(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user releases the mouse button over a location in Google Earth. + */ + mouseup(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user moves the mouse off of the object in Google Earth. + */ + mouseout(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user moves the mouse inside Google Earth. + */ + mousemove(event: KmlMouseEvent): void; + } + + /** + * The base class for all the other objects in the Google Earth Plug-in. + * The methods and behavior of KMLObject are inherited by all other objects. + * This is an abstract base class and cannot be used directly. + * It provides the id attribute, which allows unique identification of an object. + */ + export class KmlObject extends GEEventEmitter { + + /** + * The interface name (i.e. 'KmlPlacemark') of the object. + */ + getType(): string; + + /** + * Test whether this object is the same as another object. + * Useful for Chrome and Safari, where the comparison a==b sometimes fails for plugin objects. + */ + equals(compareTo: KmlObject): boolean; + + /** + * The unique ID of the KML object. + */ + getId(): string; + + /** + * The unique URL of the KML object. + * This is the base address joined with the ID using the # character. + * + * For example: http://www.google.com/bar.kml#atlantis + */ + getUrl(): string; + + /** + * The parent node of the KML object. + */ + getParentNode(): KmlObject; + + /** + * The document that owns the KML object. + */ + getOwnerDocument(): KmlDocument; + + /** + * Permanently deletes an object, allowing its ID to be reused. + * Attempting to access the object once it is released will result in an error. + */ + release(): void; + } + + /** + * A collection of KmlObjects. + */ + export class KmlObjectList { + + /** + * Gets an item from the object list. For example, list.item(0) returns the first object in the list. + */ + item(index: number): T; + + /** + * Number of objects in collection. + */ + getLength(): number; + } + + /** + * The base class for KmlStyle and KmlStyleMap. + */ + export class KmlStyleSelector extends KmlObject {} + + /** + * Defines the icon, label, line, list, polygon, and balloon styles. + */ + export class KmlStyle extends KmlStyleSelector { + + /** + * Specifies how icons for point placemarks are drawn in Google Earth. + */ + getIconStyle(): KmlIconStyle; + + /** + * Specifies how the name of a feature is drawn in the 3D viewer. + * A custom color, color mode, and scale for the label (name) can be specified. + */ + getLabelStyle(): KmlLabelStyle; + + /** + * Specifies the drawing style (color, color mode, and line width) for line geometry. + * Line geometry includes the outlines of outlined polygons and the extruded tether of Placemark icons (if extrusion is enabled). + */ + getLineStyle(): KmlLineStyle; + + /** + * Specifies the style for list geometry. + */ + getListStyle(): KmlListStyle; + + /** + * Specifies the drawing style for polygons, including polygon extrusions (which look like the walls of buildings) and line extrusions (which look like solid fences). + */ + getPolyStyle(): KmlPolyStyle; + + /** + * Specifies the drawing style for balloons. + */ + getBalloonStyle(): KmlBalloonStyle; + } + + /** + * The KmlColorStyle object is an abstract object. + * It specifies the color and color mode of extended style types. + */ + export class KmlColorStyle extends KmlObject { + + /** + * Color and opacity (alpha) values. + */ + getColor(): KmlColor; + + /** + * Specifies which color mode effect to apply to the base color. + * + * See also: + * + * * GEPlugin.COLOR_NORMAL + * * GEPlugin.COLOR_INHERIT + * * GEPlugin.COLOR_RANDOM + */ + getColorMode(): KmlColorModeEnum; + + /** + * Specifies which color mode effect to apply to the base color. + * + * See also: + * + * * GEPlugin.COLOR_NORMAL + * * GEPlugin.COLOR_INHERIT + * * GEPlugin.COLOR_RANDOM + */ + setColorMode(colorMode: KmlColorModeEnum): void; + } + + /** + * Specifies how icons for point placemarks are drawn in Google Earth. + * The icon property specifies the icon image. + * The scale property specifies the x, y scaling of the icon. + * The color specified in the color property of KmlIconStyle is blended with the color of the Icon. + */ + export class KmlIconStyle extends KmlColorStyle { + + /** + * Resizes the icon. + */ + getScale(): number; + + /** + * Resizes the icon. + */ + setScale(scale: number): void; + + /** + * The direction that icons are set to point, clockwise, and in degrees. + */ + getHeading(): number; + + /** + * The direction that icons are set to point, clockwise, and in degrees. + */ + setHeading(heading: number): void; + + /** + * A custom Icon. In KmlIconStyle, the only child element of KmlIcon is href and href is an HTTP address or a local file specification used to load an icon. + */ + getIcon(): KmlIcon; + + /** + * A custom Icon. In KmlIconStyle, the only child element of KmlIcon is href and href is an HTTP address or a local file specification used to load an icon. + */ + setIcon(icon: KmlIcon): void; + + /** + * Specifies the position within the Icon that is anchored to the point specified in the placemark. + * The x and y values can be specified in three different ways: as pixels, as fractions of the icon, or as inset pixels, which is an offset in pixels from the upper right corner of the icon. + * The x and y positions can be specified in different ways. + * For example, x can be in pixels and y can be a fraction. + * The origin of the coordinate system is in the lower left corner of the icon. + */ + getHotSpot(): KmlVec2; + } + + /** + * Specifies how the name of a feature is drawn in the 3D viewer. + * A custom color, color mode, and scale for the label (name) can be specified. + */ + export class KmlLabelStyle extends KmlColorStyle { + + /** + * Resizes the label. + */ + getScale(): number; + + /** + * Resizes the label. + */ + setScale(scale: number): void; + } + + /** + * The KmlLineStyle object specifies the drawing style (color, color mode, and line width) for all line geometry. + * Line geometry includes the outlines of outlined polygons and the extruded "tether" of Placemark icons (if extrusion is enabled). + */ + export class KmlLineStyle extends KmlColorStyle { + + /** + * Width of the line, in pixels. + */ + getWidth(): number; + + /** + * Width of the line, in pixels. + */ + setWidth(width: number): void; + } + + /** + * Specifies the drawing style for all polygons, including polygon extrusions (which look like the walls of buildings) and line extrusions (which look like solid fences). + */ + export class KmlPolyStyle extends KmlColorStyle { + + /** + * Specifies whether or not to fill the polygon. Possible values 1 (fill) and 0 (no fill). + */ + getFill(): boolean; + + /** + * Specifies whether or not to fill the polygon. Possible values 1 (fill) and 0 (no fill). + */ + setFill(fill: boolean): void; + + /** + * Specifies whether to outline the polygon. Polygon outlines use the current KmlLineStyle. + */ + getOutline(): boolean; + + /** + * Specifies whether to outline the polygon. Polygon outlines use the current KmlLineStyle. + */ + setOutline(outline: boolean): void; + } + + /** + * Specifies how a feature is displayed in the list view. + */ + export class KmlListStyle extends KmlObject { + + /** + * Background color for the Snippet. + */ + getBgColor(): KmlColor; + + /** + * Maximum number of lines of text for the Snippet. + */ + getMaxSnippetLines(): number; + + /** + * Maximum number of lines of text for the Snippet. + */ + setMaxSnippetLines(maxSnippetLines: number): void; + + /** + * Specifies how a feature should be displayed in a list view. + */ + getListItemType(): KmlListItemTypeEnum; + } + + /** + * Specifies how the description balloon for placemarks is drawn. + */ + export class KmlBalloonStyle extends KmlObject { + + /** + * Background color of the balloon (optional). + */ + getBgColor(): KmlColor; + + /** + * Foreground color for text. The default is black (ff000000). + */ + getTextColor(): KmlColor; + + /** + * The text contained in the balloon. + */ + getText(): string; + + /** + * The text contained in the balloon. + */ + setText(text: string): void; + } + + /** + * Specifies the top, bottom, right, and left sides of a bounding box on the Earth's surface. + */ + export class KmlLatLonBox extends KmlObject { + + /** + * Sets the north, south, east, and west edges of the bounding box, as well as the rotation of the overlay. + */ + setBox( + north: number, + south: number, + east: number, + west: number, + rotation: number + ): void; + + /** + * Specifies the latitude of the north edge of the bounding box, in decimal degrees from -90 to 90. + */ + getNorth(): number; + + /** + * Specifies the latitude of the north edge of the bounding box, in decimal degrees from -90 to 90. + */ + setNorth(north: number): void; + + /** + * Specifies the latitude of the south edge of the bounding box, in decimal degrees from -90 to 90. + */ + getSouth(): number; + + /** + * Specifies the latitude of the south edge of the bounding box, in decimal degrees from -90 to 90. + */ + setSouth(south: number): void; + + /** + * Specifies the longitude of the east edge of the bounding box, in decimal degrees from -180 to 180. + * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) + */ + getEast(): number; + + /** + * Specifies the longitude of the east edge of the bounding box, in decimal degrees from -180 to 180. + * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) + */ + setEast(east: number): void; + + /** + * Specifies the longitude of the west edge of the bounding box, in decimal degrees from -180 to 180. + * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) + */ + getWest(): number; + + /** + * Specifies the longitude of the west edge of the bounding box, in decimal degrees from -180 to 180. + * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) + */ + setWest(west: number): void; + + /** + * Specifies a rotation of the overlay about its center, in degrees. + * Values can be +/-180. The default is 0 (north). + * Rotations are specified in a counterclockwise direction. + */ + getRotation(): number; + + /** + * Specifies a rotation of the overlay about its center, in degrees. + * Values can be +/-180. The default is 0 (north). + * Rotations are specified in a counterclockwise direction. + */ + setRotation(rotation: number): void; + } + + /** + * Specifies a bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + export class KmlLatLonAltBox extends KmlLatLonBox { + + /** + * Sets the north, south, east, west, rotation, minAltitude, maxAltitude, and altitudeMode of bounding box. + */ + setAltBox( + north: number, + south: number, + east: number, + west: number, + rotation: number, + minAltitude: number, + maxAltitude: number, + altitudeMode: KmlAltitudeModeEnum + ): void; + + /** + * Minimum altitude, specified in meters above sea level. + */ + getMinAltitude(): number; + + /** + * Minimum altitude, specified in meters above sea level. + */ + setMinAltitude(minAltitude: number): void; + + /** + * Maximim altitude, specified in meters above sea level. + */ + getMaxAltitude(): number; + + /** + * Maximim altitude, specified in meters above sea level. + */ + setMaxAltitude(maxAltitude: number): void; + + /** + * Specifies how the altitude property is interpreted. + * + * See also: + * + * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how the altitude property is interpreted. + * + * See also: + * + * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): number; + } + + /** + * The KmlLod or level of detail, describes the size of the projected region on the screen that is required in order for the region to be considered active. + * Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). + */ + export class KmlLod extends KmlObject { + + /** + * Sets the minLodPixels, maxLodPixels, minFadeExtent, and maxFadeExtent for the projected region on the screen. + */ + set( + minLodPixels: number, + maxLodPixels: number, + minFadeExtent: number, + maxFadeExtent: number + ): void; + + /** + * Specifies measurement in screen pixels that represents the minimum limit of the visibility range for a given Region. + * Google Earth calculates the size of the region when projected onto screen space. + * Then it computes the square root of the region's area (if, for example, the Region is square and the viewpoint is directly above the Region, and the Region is not tilted, this measurement is equal to the width of the projected Region). + * If this measurement falls within the limits defined by minLodPixels and maxLodPixels (and if the LatLonAltBox is in view), the region is active. + * If this limit is not reached, the associated geometry is considered to be too far from the user's viewpoint to be drawn. + */ + getMinLodPixels(): number; + + /** + * Specifies measurement in screen pixels that represents the minimum limit of the visibility range for a given Region. + * Google Earth calculates the size of the region when projected onto screen space. + * Then it computes the square root of the region's area (if, for example, the Region is square and the viewpoint is directly above the Region, and the Region is not tilted, this measurement is equal to the width of the projected Region). + * If this measurement falls within the limits defined by minLodPixels and maxLodPixels (and if the LatLonAltBox is in view), the region is active. + * If this limit is not reached, the associated geometry is considered to be too far from the user's viewpoint to be drawn. + */ + setMinLodPixels(minLodPixels: number): void; + + /** + * Measurement in screen pixels that represents the maximum limit of the visibility range for a given Region. + * A value of -1, the default, indicates "active to infinite size." + */ + getMaxLodPixels(): number; + + /** + * Measurement in screen pixels that represents the maximum limit of the visibility range for a given Region. + * A value of -1, the default, indicates "active to infinite size." + */ + setMaxLodPixels(maxLogPixels: number): void; + + /** + * Distance over which the geometry fades, from fully opaque to fully transparent. + * This ramp value, expressed in screen pixels, is applied at the minimum end of the LOD (visibility) limits. + */ + getMinFadeExtent(): number; + + /** + * Distance over which the geometry fades, from fully opaque to fully transparent. + * This ramp value, expressed in screen pixels, is applied at the minimum end of the LOD (visibility) limits. + */ + setMinFadeExtent(minFadeExtent: number): void; + + /** + * Distance over which the geometry fades, from fully transparent to fully opaque. + * This ramp value, expressed in screen pixels, is applied at the maximum end of the LOD (visibility) limits. + */ + getMaxFadeExtent(): number; + + /** + * Distance over which the geometry fades, from fully transparent to fully opaque. + * This ramp value, expressed in screen pixels, is applied at the maximum end of the LOD (visibility) limits. + */ + setMaxFadeExtent(maxFadeExtent: number): void; + } + + /** + * The KmlRegion object is used to set region objects and their properties. + * A region contains a bounding box (LatLonAltBox) that describes an area of interest defined by geographic coordinates and altitudes. + * In addition, a Region contains an LOD (level of detail) extent that defines a validity range of the associated Region in terms of projected screen size. + * A Region is said to be "active" when the bounding box is within the user's view and the LOD requirements are met. + * Objects associated with a Region are drawn only when the Region is active. + * When the viewRefreshMode is onRegion, the Link or Icon is loaded only when the Region is active. + */ + export class KmlRegion extends KmlObject { + + /** + * Sets the latLonAltBox and lod for the region. + */ + set(latLonAltBox: KmlLatLonAltBox, lod: KmlLod): void; + + /** + * A bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + getLatLonAltBox(): KmlLatLonAltBox; + + /** + * A bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + setLatLonAltBox(latLonAltBox: KmlLatLonAltBox): void; + + /** + * LOD is an abbreviation for Level of Detail. + * Lod describes the size of the projected region on the screen that is required in order for the region to be considered "active. + * " Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). + */ + getLod(): KmlLod; + + /** + * LOD is an abbreviation for Level of Detail. + * Lod describes the size of the projected region on the screen that is required in order for the region to be considered "active. + * " Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). + */ + setLod(lod: KmlLod): void; + } + + /** + * Represents a specific point in time. + * The plugin accepts time in this format only; it does not accept JavaScript date or time objects. + */ + export class KmlDateTime { + + /** + * Set the date. Accepts only XML Schema time (see XML Schema Part 2: Datatypes Second Edition). + * The value can be expressed as yyyy-mm-ddThh:mm:sszzzzzz, where T is the separator between the date and the time, + * and the time zone is either Z(for UTC) or zzzzzz, which represents +/-hh:mm in relation to UTC. + * Additionally, the value can be expressed as a date only. + */ + set(date: string): void; + + /** + * Returns the date and time in XML Schema time format. + */ + get(): string; + } + + /** + * An abstract object and cannot be used directly in a JavaScript file. + * This element is extended by the TimeSpan and TimeStamp objects. + */ + export class KmlTimePrimitive extends KmlObject {} + + /** + * Represents a single moment in time. + * This is a simple element and contains no children. + * Its value is a dateTime, specified in XML time. + * The precision of the TimeStamp is dictated by the dateTime value in the when property. + */ + export class KmlTimeStamp extends KmlTimePrimitive { + + /** + * Represents a single moment in time. + * This is a simple element and contains no children. + * Its value is a dateTime, specified in XML time. + * The precision of the TimeStamp is dictated by the dateTime value in the when property. + * + * * dateTime gives second resolution + * * date gives day resolution + * * gYearMonth gives month resolution + * * gYear gives year resolution + */ + getWhen(): KmlDateTime; + } + + /** + * Represents an extent in time bounded by begin and end dateTimes. + */ + export class KmlTimeSpan extends KmlTimePrimitive { + + /** + * Describes the beginning instant of a time period. + * If absent, the beginning of the period is unbounded. + */ + getBegin(): KmlDateTime; + + /** + * Describes the ending instant of a time period. + * If absent, the end of the period is unbounded. + */ + getEnd(): KmlDateTime; + } + + /** + * This is an abstract class and cannot be created directly. + * This class is extended by KmlCamera and KmlLookAt. + */ + export class KmlAbstractView extends KmlObject { + + /** + * Creates a new KmlLookAt object that matches as closely as possible this KmlAbstractView. + * KmlLookAt is unable to represent roll, so roll values in the current view will not be passed to the new KmlLookAt object. + * + * If this view is already a KmlLookAt, this function returns a new KmlLookAt representing the same view. + */ + copyAsLookAt(): KmlLookAt; + + /** + * Creates a new KmlCamera object that matches this KmlAbstractView. + * + * If this view is already a KmlCamera, this function returns a new KmlCamera representing the same view. + */ + copyAsCamera(): KmlCamera; + + /** + * Returns the KmlTimeStamp or KmlTimeSpan object associated with this view. + */ + getTimePrimitive(): KmlTimePrimitive; + + /** + * Associate a KmlTimeStamp or KmlTimeSpan object with this view. + */ + setTimePrimitive(timePrimitive: KmlTimePrimitive): void; + + /** + * Returns the viewer options on the current view. + * + * See also: + * + * * GEPlugin.OPTION_STREET_VIEW + * * GEPlugin.OPTION_SUNLIGHT + * * GEPlugin.OPTION_HISTORICAL_IMAGERY + */ + getViewerOptions(): KmlViewerOptions; + + /** + * Sets the viewer options on the current view. + * + * See also: + * + * * GEPlugin.OPTION_STREET_VIEW + * * GEPlugin.OPTION_SUNLIGHT + * * GEPlugin.OPTION_HISTORICAL_IMAGERY + */ + setViewerOptions(viewerOptions: KmlViewerOptions): void; + } + + /** + * Defines a camera that is associated with anything derived from feature. + * The LookAt element positions the "camera" in relation to the object that is being viewed. + * This class either positions the relative to a feature, or you can manually change the view, using ge.getView().setAbstractView(). + */ + export class KmlLookAt extends KmlAbstractView { + + /** + * Sets the latitude, longitude, altitude, altitudeMode, heading, tilt, and range for the camera. + */ + set ( + latitude: number, + longitude: number, + altitude: number, + altitudeMode: KmlAltitudeModeEnum, + heading: number, + tilt: number, + range: number + ): void; + + /** + * Latitude of the point the camera is looking at. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + getLatitude(): number; + + /** + * Latitude of the point the camera is looking at. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + setLatitude(latitude: number): void; + + /** + * Latitude of the point the camera is looking at. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + getLongitude(): number; + + /** + * Latitude of the point the camera is looking at. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + setLongitude(longitude: number): void; + + /** + * The distance in meters from the point specified by longitude, latitude, and altitude for the LookAt position. + */ + getRange(): number; + + /** + * The distance in meters from the point specified by longitude, latitude, and altitude for the LookAt position. + */ + setRange(range: number): void; + + /** + * Angle between the direction of the LookAt position and the normal to the surface of the earth. + * Values range from 0 to 90 degrees. Values for tilt cannot be negative. + * A tilt value of 0 degrees indicates viewing from directly above. + * A tilt value of 90 degrees indicates viewing along the horizon. + */ + getTilt(): number; + + /** + * Angle between the direction of the LookAt position and the normal to the surface of the earth. + * Values range from 0 to 90 degrees. Values for tilt cannot be negative. + * A tilt value of 0 degrees indicates viewing from directly above. + * A tilt value of 90 degrees indicates viewing along the horizon. + */ + setTilt(tilt: number): void; + + /** + * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. + */ + getHeading(): number; + + /** + * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. + */ + setHeading(heading: number): void; + + /** + * Distance from the earth's surface, in meters. + */ + getAltitude(): number; + + /** + * Distance from the earth's surface, in meters. + */ + setAltitude(altitude: number): void; + + /** + * Specifies how altitude components in the coordinates element are interpreted. + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how altitude components in the coordinates element are interpreted. + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; + } + + /** + * Defines the camera that views the scene. + * This element defines the position of the camera relative to the Earth's surface as well as the viewing direction of the camera. + * The camera position is defined by longitude, latitude, altitude, and altitudeMode. + * The viewing direction of the camera is defined by heading, tilt, and roll. + * Camera can be a child element of any feature. + */ + export class KmlCamera extends KmlAbstractView { + + /** + * Sets the latitude, longitude, altitude, alitudeMode, heading, tilt, and roll values. + */ + set( + latitude: number, + longitude: number, + altitude: number, + altitudeMode: KmlAltitudeModeEnum, + heading: number, + tilt: number, + roll: number + ): void; + + /** + * Latitude of the camera location. Degrees north or south of the Equator (0 degrees). Values range from -90 degrees to 90 degrees. + */ + getLatitude(): number; + + /** + * Latitude of the camera location. Degrees north or south of the Equator (0 degrees). Values range from -90 degrees to 90 degrees. + */ + setLatitude(latitude: number): void; + + /** + * Longitude of the camera location. Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + getLongitude(): number; + + /** + * Longitude of the camera location. Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + setLongitude(longitude: number): void; + + /** + * Distance from the earth's surface. + */ + getAltitude(): number; + + /** + * Distance from the earth's surface. + */ + setAltitude(altitude: number): void; + + /** + * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. + */ + getHeading(): number; + + /** + * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. + */ + setHeading(heading: number): void; + + /** + * Angle between the direction of the camera position and the normal to the surface of the earth. Values range from 0 to 360 degrees. + * A tilt value of 0 degrees indicates viewing from directly above, 90 degrees indicates viewing along the horizon, and 180 degrees indicates viewing straight up at the sky. + */ + getTilt(): number; + + /** + * Angle between the direction of the camera position and the normal to the surface of the earth. Values range from 0 to 360 degrees. + * A tilt value of 0 degrees indicates viewing from directly above, 90 degrees indicates viewing along the horizon, and 180 degrees indicates viewing straight up at the sky. + */ + setTilt(tilt: number): void; + + /** + * Rotation, in degrees, of the camera around the Z axis. Values range from -180 to +180 degrees. + */ + getRoll(): number; + + /** + * Rotation, in degrees, of the camera around the Z axis. Values range from -180 to +180 degrees. + */ + setRoll(roll: number): void; + + /** + * Specifies how altitude components in the coordinates are interpreted. + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how altitude components in the coordinates are interpreted. + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; + } + + /** + * The KmlGeometry object is an abstract object and cannot be used directly. + * It provides a placeholder object for all derived Geometry objects. + */ + export class KmlGeometry extends KmlObject {} + + /** + * Specifies an AltitudeMode for derived classes. + */ + export class KmlAltitudeGeometry extends KmlGeometry { + + /** + * Specifies how altitude components in the geometry coordinates are interpreted. + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how altitude components in the geometry coordinates are interpreted. + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; + } + + /** + * A 3D object described in a referenced COLLADA file. + * COLLADA files have a .dae file extension. + * Models are created in their own coordinate space and then located, positioned, and scaled in Google Earth. + * Google Earth supports the COLLADA common profile, with the following exceptions: + * + * * Google Earth supports only triangles and lines as primitive types. The maximum number of triangles allowed is 21845. + * * Google Earth does not support animation or skinning. + * * Google Earth does not support external geometry references. + */ + export class KmlModel extends KmlAltitudeGeometry { + + /** + * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. + * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. + * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. + */ + getLocation(): KmlLocation; + + /** + * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. + * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. + * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. + */ + setLocation(location: KmlLocation): void; + + /** + * Describes rotation of a 3D model's coordinate system to position the object in Google Earth. + */ + getOrientation(): KmlOrientation; + + /** + * Describes rotation of a 3D model's coordinate system to position the object in Google Earth. + */ + setOrientation(orientation: KmlOrientation): void; + + /** + * Scales a model along the x, y, and z axes in the model's coordinate space + */ + getScale(): KmlScale; + + /** + * Scales a model along the x, y, and z axes in the model's coordinate space + */ + setScale(scale: KmlScale): void; + + /** + * Returns the link of the collada model. + */ + getLink(): KmlLink; + + /** + * Sets the link of the collada model. + */ + setLink(link: KmlLink): void; + } + + /** + * A container for zero or more geometry primitives associated with the same feature. + */ + export class KmlMultiGeometry extends KmlGeometry { + + /** + * The collection of geometries that are children of this multi-geometry. + */ + getGeometries(): GEGeometryContainer; + } + + /** + * Specifies the behavior of the object's geometry. + */ + export class KmlExtrudableGeometry extends KmlAltitudeGeometry { + + /** + * Specifies whether to connect the geometry to the ground. + */ + getExtrude(): boolean; + + /** + * Specifies whether to connect the geometry to the ground. + */ + setExtrude(extrude: boolean): void; + + /** + * Specifies whether to allow the geometry to follow the terrain elevation. + */ + getTessellate(): boolean; + + /** + * Specifies whether to allow the geometry to follow the terrain elevation. + */ + setTessellate(tessellate: boolean): void; + } + + /** + * A Polygon is defined by an outer boundary and 0 or more inner boundaries. + * The boundaries, in turn, are defined by LinearRings. + * When a Polygon is extruded, its boundaries are connected to the ground to form additional polygons, which gives the appearance of a building or a box. + * Extruded Polygons use PolyStyle for their color, color mode, and fill. + */ + export class KmlPolygon extends KmlExtrudableGeometry { + + /** + * Contains a LinearRing element. + */ + getOuterBoundary(): KmlLinearRing; + + /** + * Contains a LinearRing element. + */ + setOuterBoundary(outerBoundary: KmlLinearRing): void; + + /** + * Contains a LinearRing element. + * You can specify multiple innerBoundary properties, which create multiple cut-outs inside the Polygon. + */ + getInnerBoundaries(): GELinearRingContainer; + } + + /** + * A geographic location defined by longitude, latitude, and (optional) altitude. + * When a Point is contained by a Placemark, the point itself determines the position of the Placemark's name and icon. + * When a Point is extruded, it is connected to the ground with a line. This tether uses the current LineStyle. + */ + export class KmlPoint extends KmlExtrudableGeometry { + + /** + * Sets altitudeMode, extrude, tessellate, latitude, longitude, and altitude values. + */ + set( + latitude: number, + longitude: number, + altitude: number, + altitudeMode: KmlAltitudeModeEnum, + extrude: boolean, + tessellate: boolean + ): void; + + /** + * Sets the latitude and longitude. + */ + setLatLng(latitude: number, longitude: number): void; + + /** + * Sets the latitude, longitude, and altitide. + */ + setLatLngAlt(latitude: number, longitude: number, altitude: number): void; + + /** + * The point's latitude, in degrees. + */ + getLatitude(): number; + + /** + * The point's latitude, in degrees. + */ + setLatitude(latitude: number): void; + + /** + * The point's longitude, in degrees. + */ + getLongitude(): number; + + /** + * The point's longitude, in degrees. + */ + setLongitude(longitude: number): void; + + /** + * The point's altitude, in meters. + */ + getAltitude(): number; + + /** + * The point's altitude, in meters. + */ + setAltitude(altitude: number): void; + } + + /** + * Defines a connected set of line segments. + * Use KmlLineStyle to specify the color, color mode, and width of the line. + * When a LineString is extruded, the line is extended to the ground, forming a polygon that looks somewhat like a wall or fence. + * For extruded LineStrings, the line itself uses the current LineStyle, and the extrusion uses the current PolyStyle. + */ + export class KmlLineString extends KmlExtrudableGeometry { + + /** + * Two or more coordinate tuples, each consisting of floating point values for longitude, latitude, and altitude. + * The altitude component is optional. + */ + getCoordinates(): KmlCoordArray; + + /** + * Added to the altitude values for all points on the line string. + * Adjusts the altitude of the feature as a whole, without the need to update each coordinate set. + */ + setAltitudeOffset(altitudeOffset: number): void; + + /** + * Returns the altitudeOffset, or 0 if not set. + */ + getAltitudeOffset(): number; + } + + /** + * Defines a closed line string, typically the outer boundary of a Polygon. + * Optionally, a LinearRing can also be used as the inner boundary of a Polygon to create holes in the Polygon. + * A Polygon can contain multiple LinearRing elements used as inner boundaries. + * You do not need to connect the first and last points. + */ + export class KmlLinearRing extends KmlLineString {} + + + /** + * The KmlFeature object is an abstract object and is the base for all feature types (for example Placemarks, Overlays, and NetworkLinks). + */ + export class KmlFeature extends KmlObject { + + /** + * Retrieves the contents of the feature's element. + * The retrieved contents are scrubbed to remove JavaScript; CSS; and iframe, embed, and object tags. + * + * It should be safe to insert the resulting HTML into your page without concern for malicious content embedded in the feature data; + * however any feature depending on CSS or Javascript will not work. + */ + getBalloonHtml(): string; + + /** + * Retrieves the contents of the feature's element. The contents are not scrubbed. + * Use this method only if you trust the source of the feature data. + */ + getBalloonHtmlUnsafe(): string; + + /** + * User-defined text displayed in the plugin as the label for the object (for example, for a Placemark). + */ + getName(): string; + + /** + * User-defined text displayed in the plugin as the label for the object (for example, for a Placemark). + */ + setName(name: string): void; + + /** + * Specifies whether the feature is drawn in the plugin. + * In order for a feature to be visible, the visibility of all its ancestors must also be set to true. + * In the Google Earth List View, each feature has a checkbox that allows the user to control visibility of the feature. + */ + getVisibility(): boolean; + + /** + * Specifies whether the feature is drawn in the plugin. + * In order for a feature to be visible, the visibility of all its ancestors must also be set to true. + * In the Google Earth List View, each feature has a checkbox that allows the user to control visibility of the feature. + */ + setVisibility(visibility: boolean): void; + + /** + * Default state of left panel. + */ + getOpen(): boolean; + + /** + * Default state of left panel. + */ + setOpen(open: boolean): void; + + /** + * Specifies a value representing an unstructured address written as a standard street, city, state address, and/or as a postal code. + */ + getAddress(): string; + + /** + * Specifies a value representing an unstructured address written as a standard street, city, state address, and/or as a postal code. + */ + setAddress(address: string): void; + + /** + * Specifies a short description of the feature. + */ + getSnippet(): string; + + /** + * Specifies a short description of the feature. + */ + setSnippet(snippet: string): void; + + /** + * User-supplied text that appears in the description balloon. + */ + getDescription(): string; + + /** + * User-supplied text that appears in the description balloon. + */ + setDescription(description: string): void; + + /** + * Stores either the lookAt or camera view. + */ + getAbstractView(): KmlAbstractView; + + /** + * Stores either the lookAt or camera view. + */ + setAbstractView(abstractView: KmlAbstractView): void; + + /** + * URI of a Style or StyleMap defined in a Document. + * It refers to a Plug-in intitiated object. + */ + getStyleUrl(): string; + + /** + * URI of a Style or StyleMap defined in a Document. + * It refers to a Plug-in intitiated object. + */ + setStyleUrl(styleUrl: string): void; + + /** + * The style based on the current mode of the Placemark. + */ + getStyleSelector(): KmlStyleSelector; + + /** + * The style based on the current mode of the Placemark. + */ + setStyleSelector(styleSelector: KmlStyleSelector): void; + + /** + * Specifies region objects and their properties. + * A region contains a bounding box (LatLonAltBox) that describes an area of interest defined by geographic coordinates and altitudes. + */ + getRegion(): KmlRegion; + + /** + * Specifies region objects and their properties. + * A region contains a bounding box (LatLonAltBox) that describes an area of interest defined by geographic coordinates and altitudes. + */ + setRegion(region: KmlRegion): void; + + /** + * Returns the KML for a feature. + */ + getKml(): string; + + /** + * Returns previous sibling node within the container. + */ + getPreviousSibling(): KmlFeature; + + /** + * Returns the next sibling node within the container. + */ + getNextSibling(): KmlFeature; + + /** + * Returns the KmlTimeStamp or KmlTimeSpan object associated with this feature. + */ + getTimePrimitive(): KmlTimePrimitive; + + /** + * Attach a KmlTimeStamp or KmlTimeSpan object to this feature. + */ + setTimePrimitive(timePrimitive: KmlTimePrimitive): void; + + /** + * Returns the computed style of a feature, merging any inline styles with styles imported from setHref() or a StyleUrl. + * + * Note: Modifying the returned KmlStyle object is undefined and not recommended. + */ + getComputedStyle(): KmlStyle; + + /** + * Experimental Feature — this is an experimental feature and can change (or even be removed) at any time. + * The opacity of a feature, ranging from 0 (completely transparent) to 1 (complete opaque). + * The opacity of a folder or document will influence the opacity of child features. + * Thus, if a folder has an opacity of 0.5 and a child ground overlay in the folder also has an opacity of 0.5, the overlay will be drawn with an opacity of 0.25. + */ + getOpacity(): number; + + /** + * Experimental Feature — this is an experimental feature and can change (or even be removed) at any time. + * The opacity of a feature, ranging from 0 (completely transparent) to 1 (complete opaque). + * The opacity of a folder or document will influence the opacity of child features. + * Thus, if a folder has an opacity of 0.5 and a child ground overlay in the folder also has an opacity of 0.5, the overlay will be drawn with an opacity of 0.25. + */ + setOpacity(opacity: number): void; + } + + /** + * An abstract object and cannot be used directly. + * A KmlContainer object holds one or more features and allows the creation of nested hierarchies. + */ + export class KmlContainer extends KmlFeature { + + /** + * Get an element by ID. + * This is functionally equivalent to getElementByUrl with an unspecified base URL. + * + * For example: getElementByUrl('#foo'). + * + * Usage is when finding objects created with JavaScript, which have unspecified base URLs. + * The object must be a descendant of the container before it can be found. + */ + getElementById(id: string): KmlObject; + + /** + * Get an element by URL. A URL consists of the base address and ID, joined with the # character. + * + * For example: http://www.google.com/bar.kml#here_be_monsters + * + * This applies to objects that are fetched. + * In the case of plugin created objects, the URL is simply #foo. + * The object must be a descendant of the container before it can be found. + */ + getElementByUrl(url: string): KmlObject; + + /** + * Get an element by type. + */ + getElementsByType(type: string): KmlObjectList; + + /** + * A collection of features, such as name, description, and so on. + */ + getFeatures(): GEFeatureContainer; + } + + /** + * A Folder is used to arrange other features hierarchically (Folders, Placemarks, NetworkLinks, or Overlays). + * A feature is visible only if it and all of its ancestors are visible. + */ + export class KmlFolder extends KmlContainer {} + + /** + * A layer displayed in Google Earth. + */ + export class KmlLayer extends KmlFolder {} + + /** + * A container for the various layers displayed with the Google Earth Plug-in. + * It contains the same layers as Google Earth. + */ + export class KmlLayerRoot extends KmlFolder { + + /** + * Returns the layer based on the layer's ID. + */ + getLayerById(id: string): KmlLayer; + + /** + * Enables a layer based on its ID. + */ + enableLayerById(id: string, visibility: boolean): void; + + /** + * Returns the drawing order for this database. + */ + getDrawOrder(): number; + + /** + * Defines the drawing order for databases. + * Drawing order is lowest to highest. + * Google Earth Enterprise customers can add a side database and set the drawOrder to be either before or after that of the main database. + * Side databases default to a drawing order of 0. + */ + setDrawOrder(drawOrder: number): void; + } + + /** + * A KmlDocument has containers that holds features and styles. + * This container is required if you use shared styles. + * It is recommended that you use shared styles, which require the following. + * + * 1. Define all Styles in a Document. Assign a unique ID to each Style. + * 2. Within a given feature or StyleMap, reference the Style's ID using a styleUrl element. + * + * Note: Shared styles are not inherited by the features in the Document. + */ + export class KmlDocument extends KmlContainer { + + /** + * Returns a list of elements using a particular style URL. + */ + getElementsByStyleUrl(styleUrl: string): KmlObjectList; + + /** + * Returns an array containing the style selectors present in the KML document. + */ + getStyleSelectors(): GEStyleSelectorContainer; + } + + /** + * The KmlPlacemark is a feature with associated Geometry. + */ + export class KmlPlacemark extends KmlFeature { + + /** + * The geometry associated with the placemark. + */ + getGeometry(): KmlGeometry; + + /** + * The geometry associated with the placemark. + */ + setGeometry(geometry: KmlGeometry): void; + } + + /** + * The base class for the three types of balloon windows that can overlay the 3D window. + */ + export class GEAbstractBalloon { + + /** + * The ID of the balloon. + */ + getId(): string; + + /** + * The ID of the balloon. + */ + setId(id: string): void; + + /** + * Determines what the balloon is attached to. + */ + getFeature(): KmlFeature; + + /** + * Determines what the balloon is attached to. + */ + setFeature(feature: KmlFeature): void; + + /** + * Minimum width of the balloon. + */ + getMinWidth(): number; + + /** + * Minimum width of the balloon. + */ + setMinWidth(minWidth: number): void; + + /** + * Minimum height of the balloon. + */ + getMinHeight(): number; + + /** + * Minimum height of the balloon. + */ + setMinHeight(minHeight: number): void; + + /** + * Maximum width of the balloon. + */ + getMaxWidth(): number; + + /** + * Maximum width of the balloon. + */ + setMaxWidth(maxWidth: number): void; + + /** + * Maximum height of the balloon. + */ + getMaxHeight(): number; + + /** + * Maximum height of the balloon. + */ + setMaxHeight(maxHeight: number): void; + + /** + * When true, the balloon frame is displayed with a button that the user + * can click to close the balloon. When false, the balloon frame is just + * a plain frame. + * + * Default is true. + */ + getCloseButtonEnabled(): boolean; + + /** + * When true, the balloon frame is displayed with a button that the user + * can click to close the balloon. When false, the balloon frame is just + * a plain frame. + * + * Default is true. + */ + setCloseButtonEnabled(closeButtonEnabled: boolean): void; + } + + /** + * Base class for GEHtmlStringBalloon and GEHtmlDivBalloon. + */ + export class GEFeatureBalloon extends GEAbstractBalloon {} + + /** + * Creates a balloon that contains HTML. + */ + export class GEHtmlBalloon extends GEAbstractBalloon { + + /** + * The color of the text in the balloon. + * This must be set using the HTML hex format #RRGGBB. + * If not set, it is interpreted as #000000. + */ + getForegroundColor(): string; + + /** + * The color of the text in the balloon. + * This must be set using the HTML hex format #RRGGBB. + * If not set, it is interpreted as #000000. + */ + setForegroundColor(foregroundColor: string): void; + + /** + * The background color of the balloon. + * This must be set using the HTML hex format #RRGGBB. + * If not set, the default is interpreted as #FFFFFF. + */ + getBackgroundColor(): string; + + /** + * The background color of the balloon. + * This must be set using the HTML hex format #RRGGBB. + * If not set, the default is interpreted as #FFFFFF. + */ + setBackgroundColor(backgroundColor: string): void; + } + + /** + * The GEHtmlDivBalloon object creates a balloon based on the contentDiv property. + */ + export class GEHtmlDivBalloon extends GEHtmlBalloon { + + /** + * An HTMLDivElement to be used as the contents of the balloon. + * When the balloon is shown, the HTMLDivElement is attached to the balloon element in the web page. + * You can manipulate this balloon using ordinary HTML DOM techniques. + */ + getContentDiv(): HTMLDivElement; + + /** + * An HTMLDivElement to be used as the contents of the balloon. + * When the balloon is shown, the HTMLDivElement is attached to the balloon element in the web page. + * You can manipulate this balloon using ordinary HTML DOM techniques. + */ + setContentDiv(contentDiv: HTMLElement): void; + } + + /** + * The GEHtmlStringBalloon class represents a balloon based on the contentString. + */ + export class GEHtmlStringBalloon extends GEHtmlBalloon { + + /** + * You can include any HTML using the contentString property. + * When the balloon is visible, the content specified in contentString property, + * is inserted directly into the balloon element in the web page. + */ + getContentString(): string; + + /** + * You can include any HTML using the contentString property. + * When the balloon is visible, the content specified in contentString property, + * is inserted directly into the balloon element in the web page. + */ + setContentString(contentString: string): void; + } + + /** + * The base class for GETimeControl. + */ + export class GEControl {} + + /** + * Represents the time slider object. + */ + export class GETimeControl extends GEControl { + + /** + * Whether the time slider is visible or not. + */ + getVisibility(): GEVisibilityEnum; + + /** + * Specifies whether the control is visible or hidden. + */ + setVisibility(visibility: GEVisibilityEnum): void; + + /** + * Returns the clock rate that the plugin would use, if the play button on the time slider UI was pressed. + * This rate is calculated by the plugin based on the time range currently present in the slider. + */ + getCalculatedRate(): number; + + /** + * Returns a KmlTimeSpan object encompassing the earliest and latest times present in the time slider. + * For more information, refer to the Time chapter of the Developer's Guide. + */ + getExtents(): KmlTimeSpan; + + /** + * Returns an array containing the KmlTimeStamp objects associated with the historical imagery available in this view. + */ + getAvailableImageDates(): KmlObjectList; + + } + + /** + * The GEPlugin is the Google Earth Plugin's main object, and this is the object that is returned to the JavaScript application when you first create a plug-in instance. + * GEPlugin provides factory methods for ructing other objects (placemarks, and so on), and is also used to retrieve the root document objects. + */ + export class GEPlugin { + + /** + * A Specifies that altitudes are at ground level. For Ground overlays, this means that the image will be draped over the terrain. + */ + ALTITUDE_CLAMP_TO_GROUND: KmlAltitudeModeEnum; + + /** + * Specifies that altitudes are to be interpreted as meters above or below ground level (i.e. the elevation of the terrain at the location). + */ + ALTITUDE_RELATIVE_TO_GROUND: KmlAltitudeModeEnum; + + /** + * Specifies that altitudes are to be interpreted as meters above or below sea level, regardless of the actual elevation of the terrain beneath the object. + * For example, if you set the altitude of an object to 10 meters with an absolute altitude mode, the object will appear to be at ground level if the terrain beneath is also 10 meters above sea level. + * If the terrain is 3 meters above sea level, the object will appear elevated above the terrain by 7 meters. + * If, on the other hand, the terrain is 15 meters above sea level, the object may be completely invisible. + */ + ALTITUDE_ABSOLUTE: KmlAltitudeModeEnum; + + /** + * Specifies that altitudes are at sea floor level. + */ + ALTITUDE_CLAMP_TO_SEA_FLOOR: KmlAltitudeModeEnum; + + /** + * Specifies that altitudes are to be interpreted as meters above sea floor (i.e. the elevation of the sea floor at the location). + */ + ALTITUDE_RELATIVE_TO_SEA_FLOOR: KmlAltitudeModeEnum; + + /** + * Refresh when the file is loaded and whenever the Link parameters change. This refresh mode is the default. + */ + REFRESH_ON_CHANGE: KmlRefreshModeEnum; + + /** + * Refresh every n seconds (specified in refreshInterval). + */ + REFRESH_ON_INTERVAL: KmlRefreshModeEnum; + + /** + * Refresh when the expiration time is reached. + * If a fetched file has a NetworkLinkControl, the expires time takes precedence over expiration times specified in HTTP headers. + * If no expires time is specified, the HTTP max-age header is used (if present). + * If max-age is not present, the Expires HTTP header is used (if present). + */ + REFRESH_ON_EXPIRE: KmlRefreshModeEnum; + + /** + * Ignore changes in the view. Also ignore viewFormat parameters, if any. + * This view refresh mode is the default. + */ + VIEW_REFRESH_NEVER: KmlViewRefreshModeEnum; + + /** + * Refresh the file only when the user explicitly requests it. + */ + VIEW_REFRESH_ON_REQUEST: KmlViewRefreshModeEnum; + + /** + * Refresh n seconds after movement stops, where n is specified in viewRefreshTime. + */ + VIEW_REFRESH_ON_STOP: KmlViewRefreshModeEnum; + + /** + * Refresh only when the feature's Region becomes active. + */ + VIEW_REFRESH_ON_REGION: KmlViewRefreshModeEnum; + + /** + * Screen coordinates are to be interpreted as a fraction of an item, like an image or Google Earth window. + */ + UNITS_FRACTION: KmlUnitsEnum; + + /** + * Screen coordinates are to be interpreted as pixels from the left or bottom edge. + */ + UNITS_PIXELS: KmlUnitsEnum; + + /** + * Screen coordinates are to be interpreted as pixels from the top or right edge. + */ + UNITS_INSET_PIXELS: KmlUnitsEnum; + + /** + * Apply no color mode effect, i.e. use the base color as is. + */ + COLOR_NORMAL: KmlColorModeEnum; + + /** + * Apply a random linear scale to the base color. See the KML documentation for more details. + */ + COLOR_RANDOM: KmlColorModeEnum; + + /** + * Inherit the color mode from ancestor styles. + */ + COLOR_INHERIT: KmlColorModeEnum; + + /** + * The Earth map type, used with GEOptions' setMapType. + */ + MAP_TYPE_EARTH: GEMapTypeEnum; + + /** + * The Sky map type, used with GEOptions' setMapType. + */ + MAP_TYPE_SKY: GEMapTypeEnum; + + /** + * Hide the UI element. + */ + VISIBILITY_HIDE: GEVisibilityEnum; + + /** + * Show the UI element always. + */ + VISIBILITY_SHOW: GEVisibilityEnum; + + /** + * Automatically show or hide the UI element depending on user interaction. + */ + VISIBILITY_AUTO: GEVisibilityEnum; + + /** + * Specifies that fly-to should happen immediately, without a smooth transition. + */ + SPEED_TELEPORT: number; + + /** + * The Layer ID of the terrain layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_TERRAIN: string; + + /** + * The Layer ID of the roads layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_ROADS: string; + + /** + * The Layer ID of the photorealistic buildings layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_BUILDINGS: string; + + /** + * The Layer ID of the low resolution (gray) buildings layer. + * Use as an argument to getLayerById() or enableLayerById(). + * Note that as photorealistic buildings continue to be created and added to the LAYER_BUILDINGS layer, the low-resolution version of those buildings will be removed from this layer. + * This layer will therefore change over time. + */ + LAYER_BUILDINGS_LOW_RESOLUTION: string; + + /** + * The Layer ID of the borders layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_BORDERS: string; + + /** + * The Layer ID of the trees layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_TREES: string; + + /** + * When using the GEView.hitTest method, this mode samples the globe (the earth's sphere at altitude 0, without terrain or buildings). + */ + HIT_TEST_GLOBE: GEHitTestModeEnum; + + /** + * When using the GEView.hitTest method, this mode samples the earth's terrain (the ground surface, including variations in altitude). + */ + HIT_TEST_TERRAIN: GEHitTestModeEnum; + + /** + * When using the GEView.hitTest method, this mode samples 3D buildings. + */ + HIT_TEST_BUILDINGS: GEHitTestModeEnum; + + /** + * Sets the render state to its default value. Currently, sunlight, Street View, and historical imagery all default to a disabled state. + */ + OPTION_STATE_DEFAULT: GEViewerOptionsValueEnum; + + /** + * Set the render state to on. Passed to the KmlViewerOptions.setOption method. + */ + OPTION_STATE_ENABLED: GEViewerOptionsValueEnum; + + /** + * Set the render state to off. Passed to the KmlViewerOptions.setOption method. + */ + OPTION_STATE_DISABLED: GEViewerOptionsValueEnum; + + /** + * Passed to the KmlViewerOptions.setOption method, along with a GEViewerOptionsValueEnum, to specify whether the Sun option should be visible. + * Sun can also be enabled/disabled with GEPlugin.getSun. + */ + OPTION_SUNLIGHT: GEViewerOptionsTypeEnum; + + /** + * Passed to the KmlViewerOptions.setOption method, along with a GEViewerOptionsValueEnum, to specify whether historical imagery should be enabled. + */ + OPTION_HISTORICAL_IMAGERY: GEViewerOptionsTypeEnum; + + /** + * Passed to the KmlViewerOptions.setOption method, along with a GEViewerOptionsValueEnum, to specify whether Street View should be enabled when the view reaches ground level. + * Note that this applies only to programmatic movement, such as fly-tos; to control whether the user can enter Street View using manual navigation controls, call ge.getPlugin().streetViewEnabled(true). + */ + OPTION_STREET_VIEW: GEViewerOptionsTypeEnum; + + /** + * The feature's visibility is tied to its list item's checkbox state. + */ + LIST_ITEM_CHECK: KmlListItemTypeEnum; + + /** + * When specified for a folder, document or network link, prevents all items from being made visible at once—that is, the user can turn all children off but cannot turn them all on at the same time. + * This setting is useful for containers or network links containing large amounts of data. + */ + LIST_ITEM_CHECK_OFF_ONLY: KmlListItemTypeEnum; + + /** + * Use a normal checkbox for visibility but do not display children in a list view. + * The item's checkbox should allows the user to toggle visibility of the child objects in the viewport. + */ + LIST_ITEM_CHECK_HIDE_CHILDREN: KmlListItemTypeEnum; + + /** + * When specified for a container (a folder or a document), only one of the container's items should be visible at a time. + */ + LIST_ITEM_RADIO_FOLDER: KmlListItemTypeEnum; + + /** + * The large navigation control type, used with GENavigationControl.setControlType(). + */ + NAVIGATION_CONTROL_LARGE: GENavigationControlEnum; + + /** + * The small navigation control type, used with GENavigationControl.setControlType(). + */ + NAVIGATION_CONTROL_SMALL: GENavigationControlEnum; + + /** + * Parse a string of KML and return a handle to the root of the KML object structure that was created. + */ + parseKml(kml: string): KmlObject; + + /** + * Get an element by ID. This is functionally equivalent to getElementByUrl with an unspecified base URL. + * + * For example: getElementByUrl('#foo'). + * + * Usage is when finding objects created with JavaScript, which have unspecified base URLs. + * The object must be a descendant of the DOM before it can be found. + */ + getElementById(id: string): KmlObject; + + /** + * Get an element by URL. A URL consists of the base address and the ID, joined with the # character. + * + * For example: http://www.google.com/bar.kml#here_be_monsters + * + * This applies to objects that are fetched. + * In the case of plugin created objects, the URL is simply #foo. + * The object must be a descendant of the DOM before it can be found. + */ + getElementByUrl(url: string): KmlObject; + + /** + * Get a list of elements by type. + */ + getElementsByType(): KmlObjectList; + + /** + * Creates a placemark on the globe. + * A Placemark is a feature with associated Geometry. + * A Placemark with a Point has an icon associated with it that marks a point on the Earth in the 3D viewer. + * (In the Google Earth 3D viewer, a Point Placemark is the only object you can click or roll over. + * Other Geometry objects do not have an icon in the 3D viewer. + * To allow the user to click in the 3D viewer, you would need to create a MultiGeometry object that contains both a Point and the other Geometry object.) + */ + createPlacemark(id: string): KmlPlacemark; + + /** + * Creates a point on the globe. Specifies the geographic location defined by longitude, latitude, and (optional) altitude. + */ + createPoint(id: string): KmlPoint; + + /** + * Creates a line string on Google Earth. + */ + createLineString(id: string): KmlLineString; + + /** + * Creates a folder. + * A KMLFolder is used to arrange other features hierarchically (Folders, Placemarks, NetworkLinks, or Overlays). + * A feature is visible only if it and all its ancestors are visible. + */ + createFolder(id: string): KmlFolder; + + /** + * Creates level of detail (LOD). + * LOD describes the size of the projected region on the screen that is required in order for the region to be considered active. + * Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). + */ + createLod(id: string): KmlLod; + + /** + * Creates a LatLonBox, a bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + createLatLonBox(id: string): KmlLatLonBox; + + /** + * Creates a LatLonAltBox, a bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + createLatLonAltBox(id: string): KmlLatLonAltBox; + + /** + * Creates a Document. A Document is a container for features and styles. + */ + createDocument(id: string): KmlDocument; + + /** + * Creates a Region in Google Earth. + * A Region contains a bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + createRegion(id: string): KmlRegion; + + /** + * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. + * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. + * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. + */ + createLocation(id: string): KmlLocation; + + /** + * Sets the rotation of a 3D model's coordinate system to position the object in Google Earth. + */ + createOrientation(id: string): KmlOrientation; + + /** + * Sets the scale of a model along the x, y, and z axes in the model's coordinate space. + */ + createScale(id: string): KmlScale; + + /** + * Creates a model. + * A model is a 3D object described in a COLLADA file. + * COLLADA files have a .dae file extension. + * Models are created in their own coordinate space and then located, positioned, and scaled in Google Earth. + */ + createModel(id: string): KmlModel; + + /** + * A Style defines an addressable style group that can be referenced by StyleMaps and features. + */ + createStyle(id: string): KmlStyle; + + /** + * Creates a LinearRing. + * A LinearRing defines a closed line string, typically the outer boundary of a Polygon. + * Optionally, a LinearRing can also be used as the inner boundary of a Polygon to create holes in the Polygon. + */ + createLinearRing(id: string): KmlLinearRing; + + /** + * Creates a Polygon. A Polygon is defined by an outer boundary and 0 or more inner boundaries. + */ + createPolygon(id: string): KmlPolygon; + + /** + * Creates an Icon. An icon defines an image associated with an Icon style or overlay. + */ + createIcon(id: string): KmlIcon; + + /** + * Creates a Link. + * A Link specifies the location of KML files fetched by network links, image files used in any overlay, or model files used with the Model object. + */ + createLink(id: string): KmlLink; + + /** + * Creates a GroundOverlay. + * A GroundOverlay draws an image overlay draped onto the terrain. + */ + createGroundOverlay(id: string): KmlGroundOverlay; + + /** + * Creates a NetworkLink. + * A NetworkLink references a KML file or KMZ archive on a local or remote network. + */ + createNetworkLink(id: string): KmlNetworkLink; + + /** + * Creates a ScreenOverlay. + * A ScreenOverlay draws an image overlay fixed to the screen. + */ + createScreenOverlay(id: string): KmlScreenOverlay; + + /** + * Creates a container for one or more geometry primitives associated with the same feature. + */ + createMultiGeometry(id: string): KmlMultiGeometry; + + /** + * Creates a StyleMap. + * A StyleMap maps between two different icon styles. + * Typically, a StyleMap is used to provide separate normal and highlighted styles for a Placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + createStyleMap(id: string): KmlStyleMap; + + /** + * Creates a new LookAt. + * A LookAt element positions the camera view in relation to an object that is being viewed. + */ + createLookAt(id: string): KmlLookAt; + + /** + * Creates a new Camera. + * This element positions the camera relative to the Earth's surface and defines the view direction. + */ + createCamera(id: string): KmlCamera; + + /** + * Creates a new viewer options object. + */ + createViewerOptions(id: string): KmlViewerOptions; + + /** + * Create a KmlTimeStamp object. + * For more information, refer to the Time chapter of the Google Earth API developer's guide. + */ + createTimeStamp(id: string): KmlTimeStamp; + + /** + * Create a KmlTimeSpan object. + * For more information, refer to the Time chapter of the Google Earth API developer's guide. + */ + createTimeSpan(id: string): KmlTimeSpan; + + /** + * Creates a Feature balloon. + */ + createFeatureBalloon(id: string): GEFeatureBalloon; + + /** + * Creates an HTML string balloon. + */ + createHtmlStringBalloon(id: string): GEHtmlStringBalloon; + + /** + * Creates an Html Div Balloon. + */ + createHtmlDivBalloon(id: string): GEHtmlDivBalloon; + + /** + * Returns the currently active balloon, or null. + */ + getBalloon(): GEAbstractBalloon; + + /** + * Sets the given balloon as the active balloon, replacing any existing active balloon. + * If the given feature is visible, then the balloon is displayed. Otherwise, the balloon is hidden. + * + * If the argument is null, then any existing active balloon will be hidden. + */ + setBalloon(newActiveBalloon: GEAbstractBalloon): void; + + /** + * Used for debugging purposes; if this value is not equal to the value returned by getPluginVersion then there is a misconfiguration on the end user's system. + * This check is automatically done during plugin instantiation. + */ + getEarthVersion(): string; + + /** + * The version of the Google Earth Plug-in installed on the end user's machine. + */ + getPluginVersion(): string; + + /** + * The options used to manipulate the behavior of the Google Earth plugin. + */ + getOptions(): GEOptions; + + /** + * The time class used to manipulate the behavior of the Google Earth plugin time. + */ + getTime(): GETime; + + /** + * Controls the window options. + */ + getWindow(): GEWindow; + + /** + * Controls the globe behavior. + */ + getGlobe(): GEGlobe; + + /** + * Displays the dawn to dusk views. + */ + getSun(): GESun; + + /** + * Controls built-in layer behavior. + */ + getLayerRoot(): KmlLayerRoot; + + /** + * Controls the plugin viewport. + */ + getView(): GEView; + + /** + * Controls the navigation controls on the globe. + */ + getNavigationControl(): GENavigationControl; + + /** + * The top-level features currently in the Earth object. + */ + getFeatures(): GEFeatureContainer; + + /** + * Exposes functionality for interacting with KML tours. + */ + getTourPlayer(): GETourPlayer; + + /** + * Exposes functionality for interacting with photo overlays. + */ + getPhotoOverlayViewer(): GEPhotoOverlayViewer; + + /** + * Returns a number between 0 and 100 (inclusive) that indicates the progress of the streaming of imagery for the current view. + * + * A value of 100 means that the imagery is completely streamed in. + */ + getStreamingPercent(): number; + } + +} diff --git a/google.visualization/google.visualization-tests.ts b/google.visualization/google.visualization-tests.ts index a5b1352dee..3453e2124c 100644 --- a/google.visualization/google.visualization-tests.ts +++ b/google.visualization/google.visualization-tests.ts @@ -488,3 +488,25 @@ function test_formatter_PatternFormat() { table.draw(view, { allowHtml: true, showRowNumber: true, width: '100%', height: '100%' }); } + +function test_ChartsLoad() { + google.charts.load('current', {packages: ['corechart', 'table', 'sankey']}); + + function drawChart() { + // Define the chart to be drawn. + var data = new google.visualization.DataTable(); + data.addColumn('string', 'Element'); + data.addColumn('number', 'Percentage'); + data.addRows([ + ['Nitrogen', 0.78], + ['Oxygen', 0.21], + ['Other', 0.01] + ]); + + // Instantiate and draw the chart. + var chart = new google.visualization.PieChart(document.getElementById('myPieChart')); + chart.draw(data, null); + } + + google.charts.setOnLoadCallback(drawChart); +} diff --git a/google.visualization/google.visualization.d.ts b/google.visualization/google.visualization.d.ts index 9ed800798c..a4dc1b7b1a 100644 --- a/google.visualization/google.visualization.d.ts +++ b/google.visualization/google.visualization.d.ts @@ -1,6 +1,6 @@ // Type definitions for Google Visualisation Apis // Project: https://developers.google.com/chart/ -// Definitions by: Dan Ludwig +// Definitions by: Dan Ludwig , Gregory Moore // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace google { @@ -9,6 +9,12 @@ declare namespace google { function setOnLoadCallback(handler: Function): void; function setOnLoadCallback(handler: () => void): void; + // https://developers.google.com/chart/interactive/docs/basic_load_libs + namespace charts { + function load(version: string, packages: Object): void; + function setOnLoadCallback(handler: Function): void; + } + //https://developers.google.com/chart/interactive/docs/reference namespace visualization { @@ -141,6 +147,7 @@ declare namespace google { id?: string; role?: string; pattern?: string; + p?: any; } export interface DataObject { @@ -186,6 +193,42 @@ declare namespace google { function arrayToDataTable(data: any[], firstRowIsData?: boolean): DataTable; + //#endregion + //#region Query + + // https://developers.google.com/chart/interactive/docs/reference#query + export class Query { + constructor(dataSourceUrl: string, options?: QueryOptions); + + abort(): void; + + setRefreshInterval(intervalSeconds: number): void; + setTimeout(timeoutSeconds: number): void; + setQuery(queryString:string): void; + + send(callback: (response: QueryResponse) => void): void; + } + + export interface QueryOptions { + sendMethod?: string, + makeRequestParams?: Object + } + + //#endregion + //#region QueryResponse + + // https://developers.google.com/chart/interactive/docs/reference#queryresponse + export class QueryResponse { + constructor(responseObject: Object); + + getDataTable(): DataTable; + getDetailedMessage(): string; + getMessage(): string; + getReasons(): string[]; + hasWarning(): boolean; + isError(): boolean; + } + //#endregion //#region DataView diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 58ce037eea..0aef3b74a6 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -61,6 +61,7 @@ declare namespace google.maps { backgroundColor?: string; center?: LatLng|LatLngLiteral; disableDefaultUI?: boolean; + clickableIcons?: boolean; disableDoubleClickZoom?: boolean; draggable?: boolean; draggableCursor?: string; @@ -427,7 +428,7 @@ declare namespace google.maps { /** * Marker position. Required. */ - position: LatLng; + position: LatLng|LatLngLiteral; /** Image map region definition used for drag/click. */ shape?: MarkerShape; /** Rollover text. */ @@ -755,7 +756,7 @@ declare namespace google.maps { zIndex?: number; } - export interface PolyMouseEvent { + export interface PolyMouseEvent extends MouseEvent { edge?: number; path?: number; vertex?: number; @@ -1783,21 +1784,22 @@ declare namespace google.maps { } export type LatLngLiteral = { lat: number; lng: number } + export type LatLngBoundsLiteral = { east: number; north: number; south: number; west: number } export class LatLngBounds { - constructor(sw?: LatLng, ne?: LatLng); + constructor(sw?: LatLng|LatLngLiteral, ne?: LatLng|LatLngLiteral); contains(latLng: LatLng): boolean; - equals(other: LatLngBounds): boolean; + equals(other: LatLngBounds|LatLngBoundsLiteral): boolean; extend(point: LatLng): LatLngBounds; getCenter(): LatLng; getNorthEast(): LatLng; getSouthWest(): LatLng; - intersects(other: LatLngBounds): boolean; + intersects(other: LatLngBounds|LatLngBoundsLiteral): boolean; isEmpty(): boolean; toSpan(): LatLng; toString(): string; toUrlValue(precision?: number): string; - union(other: LatLngBounds): LatLngBounds; + union(other: LatLngBounds|LatLngBoundsLiteral): LatLngBounds; } export class Point { diff --git a/graphene-pk11/graphene-pk11-tests.ts b/graphene-pk11/graphene-pk11-tests.ts index 624e0c2f1e..137e05385f 100644 --- a/graphene-pk11/graphene-pk11-tests.ts +++ b/graphene-pk11/graphene-pk11-tests.ts @@ -1,8 +1,6 @@ /// import * as graphene from "graphene-pk11"; - -// Example of Hashing from README.MD let Module = graphene.Module; let lib = "/usr/local/lib/softhsm/libsofthsm2.so"; @@ -13,13 +11,44 @@ mod.initialize(); let slot = mod.getSlots(0); if (slot.flags & graphene.SlotFlag.TOKEN_PRESENT) { let session = slot.open(); + session.login("12345"); - let digest = session.createDigest("sha1"); - digest.update("simple text 1"); - digest.update("simple text 2"); - let hash = digest.final(); + // generate EC key + let keys = session.generateKeyPair(graphene.KeyGenMechanism.ECDSA, { + keyType: graphene.KeyType.ECDSA, + token: false, + derive: true, + paramsECDSA: graphene.NamedCurve.getByName("secp192r1").value + }, { + keyType: graphene.KeyType.ECDSA, + token: false, + derive: true + }); - console.log("Hash SHA1:", hash.toString("hex")); // Hash SHA1: e1dc1e52e9779cd69679b3e0af87d2e288190d34 + // derive algorithm + let alg = { + name: "ECDH1_DERIVE", + params: new graphene.EcdhParams( + graphene.EcKdf.SHA1, + null, + keys.publicKey.getAttribute({ pointEC: null }).pointEC) + }; + + // Template for derived key + let template = { + "class": graphene.ObjectClass.SECRET_KEY, + "token": false, + "keyType": graphene.KeyType.AES, + "valueLen": 256 / 8, + "encrypt": true, + "decrypt": true + }; + + // Key derivation + let dKey = session.deriveKey(alg, keys.privateKey, template); + console.log("Derived key handle:", dKey.handle); + + session.logout(); session.close(); } else { diff --git a/graphene-pk11/graphene-pk11.d.ts b/graphene-pk11/graphene-pk11.d.ts index 5c0c5c5142..b7d26bf94a 100644 --- a/graphene-pk11/graphene-pk11.d.ts +++ b/graphene-pk11/graphene-pk11.d.ts @@ -1,774 +1,454 @@ -// Type definitions for graphene-pk11 v2.0.0 +// Type definitions for graphene-pk11 v2.0.3 // Project: https://github.com/PeculiarVentures/graphene // Definitions by: Stepan Miroshin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /** * A simple layer for interacting with PKCS #11 / PKCS11 / CryptoKI for Node - * v2.0.0 + * v2.0.3 */ declare module "graphene-pk11" { - type Callback = (err: Error, rv: number) => void; - type CK_PTR = Buffer; + import * as pkcs11 from "pkcs11js" - class Pkcs11 { - lib: any; - /** - * load a library with PKCS11 interface - * @param {string} libFile path to PKCS11 library - */ - constructor(libFile: string); - protected callFunction(funcName: string, args: any[]): number; - /** - * C_Initialize initializes the Cryptoki library. - * @param pInitArgs if this is not NULL_PTR, it gets - * cast to CK_C_INITIALIZE_ARGS_PTR - * and dereferenced - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Initialize(pInitArgs?: CK_PTR): number; - C_Initialize(pInitArgs: CK_PTR, cllback: Callback): void; - /** - * C_Finalize indicates that an application is done with the Cryptoki library. - * @param pReserved reserved. Should be NULL_PTR - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Finalize(pReserved?: CK_PTR): number; - C_Finalize(pReserved: CK_PTR, callback: Callback): void; - /** - * C_GetInfo returns general information about Cryptoki. - * @param pInfo location that receives information - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetInfo(pInfo: CK_PTR): number; - C_GetInfo(pInfo: CK_PTR, callback: Callback): void; - /** - * C_GetSlotList obtains a list of slots in the system. - * @param {boolean} tokenPresent only slots with tokens? - * @param pSlotList receives array of slot IDs - * @param pulCount receives number of slots - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetSlotList(tokenPresent: boolean, pSlotList: CK_PTR, pulCount: CK_PTR): number; - C_GetSlotList(tokenPresent: boolean, pSlotList: CK_PTR, pulCount: CK_PTR, callback: Callback): void; - /** - * C_GetSlotInfo obtains information about a particular slot in - * the system. - * @param {number} slotID the ID of the slot - * @param {Buffer} pInfo receives the slot information - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetSlotInfo(slotID: number, pInfo: CK_PTR): number; - C_GetSlotInfo(slotID: number, pInfo: CK_PTR, callback: Callback): void; - /** - * C_GetTokenInfo obtains information about a particular token - * in the system. - * @param {number} slotID ID of the token's slot - * @param {Buffer} pInfo receives the token information - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetTokenInfo(slotID: number, pInfo: Buffer): number; - C_GetTokenInfo(slotID: number, pInfo: Buffer, callback: Callback): void; - /** - * C_GetMechanismList obtains a list of mechanism types - * supported by a token. - * @param {number} slotID ID of the token's slot - * @param {number} pMechanismList gets mech. array - * @param {number} pulCount gets # of mechs - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetMechanismList(slotID: number, pMechanismList: Buffer, pulCount: Buffer): number; - C_GetMechanismList(slotID: number, pMechanismList: Buffer, pulCount: Buffer, callback: Callback): void; - /** C_GetMechanismInfo obtains information about a particular - * mechanism possibly supported by a token. - * @param {number} slotID ID of the token's slot - * @param {number} type type of mechanism - * @param {Buffer} pInfo receives mechanism info - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetMechanismInfo(slotID: number, type: number, pInfo: Buffer): number; - C_GetMechanismInfo(slotID: number, type: number, pInfo: Buffer, callback: Callback): void; - /** - * C_InitToken initializes a token. - * @param {number} slotID ID of the token's slot - * @param {Buffer} pPin the SO's initial PIN - * @param {number} ulPinLen length in bytes of the PIN - * @param {number} pLabel 32-byte token label (blank padded) - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_InitToken(slotID: number, pPin: Buffer, ulPinLen: number, pLabel: Buffer): number; - C_InitToken(slotID: number, pPin: Buffer, ulPinLen: number, pLabel: Buffer, callback: Callback): void; - /** - * C_InitPIN initializes the normal user's PIN. - * @param {number} hSession the session's handle - * @param {Buffer} pPin the normal user's PIN - * @param {number} ulPinLen length in bytes of the PIN - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_InitPIN(hSession: number, pPin: Buffer, ulPinLen: number): number; - C_InitPIN(hSession: number, pPin: Buffer, ulPinLen: number, callback: Callback): void; - /** - * C_SetPIN modifies the PIN of the user who is logged in. - * @param {number} hSession the session's handle - * @param {Buffer} pOldPin the old PIN - * @param {number} ulOldLen length of the old PIN - * @param {Buffer} pNewPin the new PIN - * @param {number} ulNewLen length of the new PIN - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SetPIN(hSession: any, pOldPin: Buffer, ulOldLen: number, pNewPin: Buffer, ulNewLen: number): number; - C_SetPIN(hSession: any, pOldPin: Buffer, ulOldLen: number, pNewPin: Buffer, ulNewLen: number, callback: Callback): void; - /** - * C_OpenSession opens a session between an application and a - * token. - * @param {number} slotID ID of the token's slot - * @param {number} flags from CK_SESSION_INFO - * @param {Buffer} pApplication passed to callback - * @param {Buffer} Notify callback function - * @param {Buffer} phSession gets session handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_OpenSession(slotID: number, flags: number, pApplication?: Buffer, notify?: Buffer, phSession?: Buffer): number; - C_OpenSession(slotID: number, flags: number, pApplication: Buffer, notify: Buffer, phSession: Buffer, callback: Callback): void; - /** - * C_CloseSession closes a session between an application and a token. - * @param {number} hSession the session's handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_CloseSession(hSession: number): number; - C_CloseSession(hSession: number, callback: Callback): void; - /** - * C_CloseAllSessions closes all sessions with a token. - * @param {number} slotID ID of the token's slot - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_CloseAllSessions(slotID: number): number; - C_CloseAllSessions(slotID: number, callback: Callback): void; - /** - * C_GetSessionInfo obtains information about the session. - * @param {number} hSession the session's handle - * @param {Buffer} pInfo receives session info - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetSessionInfo(hSession: number, pInfo: Buffer): number; - C_GetSessionInfo(hSession: number, pInfo: Buffer, callback: Callback): void; - /** - * C_GetOperationState obtains the state of the cryptographic operation in a session. - * @param {number} hSession the session's handle - * @param {Buffer} pOperationState gets state - * @param {Buffer} pulOperationStateLen gets state length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetOperationState(hSession: number, pOperationState: Buffer, pulOperationStateLen: Buffer): number; - C_GetOperationState(hSession: number, pOperationState: Buffer, pulOperationStateLen: Buffer, callback: Callback): void; - /** - * C_SetOperationState restores the state of the cryptographic operation in a session. - * @param {number} hSession the session's handle - * @param {Buffer} pOperationState holds state - * @param {number} ulOperationStateLen holds holds state length - * @param {number} hEncryptionKey en/decryption key - * @param {number} hAuthenticationKey sign/verify key - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SetOperationState(hSession: number, pOperationState: Buffer, ulOperationStateLen: number, hEncryptionKey: number, hAuthenticationKey: number): number; - C_SetOperationState(hSession: number, pOperationState: Buffer, ulOperationStateLen: number, hEncryptionKey: number, hAuthenticationKey: number, callback: Callback): void; - /** - * C_Login logs a user into a token. - * @param {number} hSession the session's handle - * @param {number} userType the user type - * @param {Buffer} pPin the user's PIN - * @param {number} ulPinLen the length of the PIN - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Login(hSession: number, userType: number, pPin: Buffer, ulPinLen: number): number; - C_Login(hSession: number, userType: number, pPin: Buffer, ulPinLen: number, callback: Callback): void; - /** - * C_Logout logs a user out from a token. - * @param {number} hSession the session's handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Logout(hSession: number): number; - C_Logout(hSession: number, callback: Callback): void; - /** - * C_CreateObject creates a new object. - * @param {number} hSession the session's handle - * @param {Buffer} pTemplate the object's template - * @param {number} ulCount attributes in template - * @param {Buffer} phObject gets new object's handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_CreateObject(hSession: number, pTemplate: Buffer, ulCount: number, phObject: Buffer): number; - C_CreateObject(hSession: number, pTemplate: Buffer, ulCount: number, phObject: Buffer, callback: Callback): void; - /** - * C_CopyObject copies an object, creating a new object for the copy. - * @param {number} hSession the session's handle - * @param {number} hObject the object's handle - * @param {Buffer} pTemplate template for new object - * @param {number} ulCount attributes in template - * @param {Buffer} phNewObject receives handle of copy - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_CopyObject(hSession: number, hObject: number, pTemplate: Buffer, ulCount: number, phNewObject: Buffer): number; - C_CopyObject(hSession: number, hObject: number, pTemplate: Buffer, ulCount: number, phNewObject: Buffer, callback: Callback): void; - /** - * C_DestroyObject destroys an object. - * @param {number} hSession the session's handle - * @param {number} hObject the object's handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DestroyObject(hSession: number, hObject: number): number; - C_DestroyObject(hSession: number, hObject: number, callback: Callback): void; - /** - * C_GetObjectSize gets the size of an object in bytes. - * @param {number} hSession the session's handle - * @param {number} hObject the object's handle - * @param {Buffer} pulSize receives size of object - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetObjectSize(hSession: number, hObject: number, pulSize: Buffer): number; - C_GetObjectSize(hSession: number, hObject: number, pulSize: Buffer, callback: Callback): void; - /** - * C_GetAttributeValue obtains the value of one or more object attributes. - * @param {number} hSession the session's handle - * @param {number} hObject the object's handle - * @param {Buffer} pTemplate specifies attrs; gets vals - * @param {number} ulCount attributes in template - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetAttributeValue(hSession: number, hObject: number, pTemplate: Buffer, ulCount: number): number; - C_GetAttributeValue(hSession: number, hObject: number, pTemplate: Buffer, ulCount: number, callback: Callback): void; - /** - * C_SetAttributeValue modifies the value of one or more object attributes - * @param {number} hSession the session's handle - * @param {number} hObject the object's handle - * @param {Buffer} pTemplate specifies attrs and values - * @param {number} ulCount attributes in template - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SetAttributeValue(hSession: number, hObject: number, pTemplate: Buffer, ulCount: number): number; - C_SetAttributeValue(hSession: number, hObject: number, pTemplate: Buffer, ulCount: number, callback: Callback): void; - /** - * C_FindObjectsInit initializes a search for token and session - * objects that match a template. - * @param {number} hSession the session's handle - * @param {Buffer} pTemplate attribute values to match - * @param {number} ulCount attrs in search template - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_FindObjectsInit(hSession: number, pTemplate: Buffer, ulCount: number): number; - C_FindObjectsInit(hSession: number, pTemplate: Buffer, ulCount: number, callback: Callback): void; - /** - * C_FindObjects continues a search for token and session - * objects that match a template, obtaining additional object - * handles. - * @param {number} hSession the session's handle - * @param {Buffer} phObject gets obj. handles - * @param {number} ulMaxObjectCount max handles to get - * @param {Buffer} pulObjectCount actual # returned - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_FindObjects(hSession: number, phObject: Buffer, ulMaxObjectCount: number, pulObjectCount: Buffer): number; - C_FindObjects(hSession: number, phObject: Buffer, ulMaxObjectCount: number, pulObjectCount: Buffer, callback: Callback): void; - /** - * C_FindObjectsFinal finishes a search for token and session objects. - * @param {number} hSession the session's handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_FindObjectsFinal(hSession: number): number; - C_FindObjectsFinal(hSession: number, callback: Callback): void; - /** - * C_EncryptInit initializes an encryption operation. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism the encryption mechanism - * @param {number} hKey handle of encryption key - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_EncryptInit(hSession: number, pMechanism: Buffer, hKey: number): number; - C_EncryptInit(hSession: number, pMechanism: Buffer, hKey: number, callback: Callback): void; - /** - * C_Encrypt encrypts single-part data. - * @param {number} hSession the session's handle - * @param {Buffer} pData the plaintext data - * @param {number} ulDataLen bytes of plaintext - * @param {Buffer} pEncryptedData gets ciphertext - * @param {Buffer} pulEncryptedDataLen gets c-text size - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Encrypt(hSession: number, pData: Buffer, ulDataLen: number, pEncryptedData: Buffer, pulEncryptedDataLen: Buffer): number; - C_Encrypt(hSession: number, pData: Buffer, ulDataLen: number, pEncryptedData: Buffer, pulEncryptedDataLen: Buffer, callback: Callback): void; - /** - * C_EncryptUpdate continues a multiple-part encryption operation. - * @param {number} hSession the session's handle - * @param {Buffer} pPart the plaintext data - * @param {number} ulPartLen plaintext data len - * @param {Buffer} pEncryptedPart gets ciphertext - * @param {Buffer} pulEncryptedPartLen gets c-text size - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_EncryptUpdate(hSession: number, pPart: Buffer, ulPartLen: number, pEncryptedPart: Buffer, pulEncryptedPartLen: Buffer): number; - C_EncryptUpdate(hSession: number, pPart: Buffer, ulPartLen: number, pEncryptedPart: Buffer, pulEncryptedPartLen: Buffer, callback: Callback): void; - /** - * C_EncryptFinal finishes a multiple-part encryption operation. - * @param {number} hSession the session's handle - * @param {Buffer} pLastEncryptedPart last c-text - * @param {Buffer} pulLastEncryptedPartLen gets last size - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_EncryptFinal(hSession: number, pLastEncryptedPart: Buffer, pulLastEncryptedPartLen: Buffer): number; - C_EncryptFinal(hSession: number, pLastEncryptedPart: Buffer, pulLastEncryptedPartLen: Buffer, callback: Callback): void; - /** - * C_DecryptInit initializes a decryption operation. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism the decryption mechanism - * @param {number} hKey handle of decryption key - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DecryptInit(hSession: number, pMechanism: Buffer, hKey: number): any; - C_DecryptInit(hSession: number, pMechanism: Buffer, hKey: number, callback: Callback): void; - /** - * C_Decrypt decrypts encrypted data in a single part. - * @param {number} hSession the session's handle - * @param {Buffer} pEncryptedData ciphertext - * @param {number} ulEncryptedDataLen ciphertext length - * @param {Buffer} pData gets plaintext - * @param {number} pulDataLen gets p-text size - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Decrypt(hSession: number, pEncryptedData: Buffer, ulEncryptedDataLen: number, pData: Buffer, pulDataLen: Buffer): number; - C_Decrypt(hSession: number, pEncryptedData: Buffer, ulEncryptedDataLen: number, pData: Buffer, pulDataLen: Buffer, callback: Callback): void; - /** - * C_DecryptUpdate continues a multiple-part decryption operation. - * @param {number} hSession the session's handle - * @param {Buffer} pEncryptedPart encrypted data - * @param {number} ulEncryptedPartLen input length - * @param {Buffer} pPart gets plaintext - * @param {Buffer} pulPartLen p-text size - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DecryptUpdate(hSession: number, pEncryptedPart: Buffer, ulEncryptedPartLen: number, pPart: Buffer, pulPartLen: Buffer): number; - C_DecryptUpdate(hSession: number, pEncryptedPart: Buffer, ulEncryptedPartLen: number, pPart: Buffer, pulPartLen: Buffer, callback: Callback): void; - /** - * C_DecryptFinal finishes a multiple-part decryption operation. - * @param {number} hSession the session's handle - * @param {Buffer} pLastPart gets plaintext - * @param {Buffer} pulLastPartLen p-text size - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DecryptFinal(hSession: number, pLastPart: Buffer, pulLastPartLen: Buffer): number; - C_DecryptFinal(hSession: number, pLastPart: Buffer, pulLastPartLen: Buffer, callback: Callback): void; - /** - * C_DigestInit initializes a message-digesting operation. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism the digesting mechanism - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DigestInit(hSession: number, pMechanism: Buffer): number; - C_DigestInit(hSession: number, pMechanism: Buffer, callback: Callback): void; - /** - * C_Digest digests data in a single part. - * @param {number} hSession the session's handle - * @param {Buffer} pData data to be digested - * @param {number} ulDataLen bytes of data to digest - * @param {Buffer} pDigest gets the message digest - * @param {Buffer} pulDigestLen gets digest length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Digest(hSession: number, pData: Buffer, ulDataLen: number, pDigest: Buffer, pulDigestLen: Buffer): number; - C_Digest(hSession: number, pData: Buffer, ulDataLen: number, pDigest: Buffer, pulDigestLen: Buffer, callback: Callback): void; - /** - * C_DigestUpdate continues a multiple-part message-digesting operation. - * @param {number} hSession the session's handle - * @param {Buffer} pPart data to be digested - * @param {number} ulPartLen bytes of data to be digested - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DigestUpdate(hSession: number, pPart: Buffer, ulPartLen: number): number; - C_DigestUpdate(hSession: number, pPart: Buffer, ulPartLen: number, callback: Callback): void; - /** - * C_DigestKey continues a multi-part message-digesting operation, - * by digesting the value of a secret key as part of - * the data already digested. - * @param {number} hSession the session's handle - * @param {number} hKey secret key to digest - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DigestKey(hSession: number, hKey: number): number; - C_DigestKey(hSession: number, hKey: number, callback: Callback): void; - /** - * C_DigestFinal finishes a multiple-part message-digesting - * operation. - * @param {number} hSession the session's handle - * @param {Buffer} pDigest gets the message digest - * @param {Buffer} pulDigestLen gets byte count of digest - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DigestFinal(hSession: number, pDigest: Buffer, pulDigestLen: Buffer): number; - C_DigestFinal(hSession: number, pDigest: Buffer, pulDigestLen: Buffer, callback: Callback): void; - /** - * C_SignInit initializes a signature (private key encryption) - * operation, where the signature is (will be) an appendix to - * the data, and plaintext cannot be recovered from the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism the signature mechanism - * @param {number} hKey handle of signature key - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SignInit(hSession: number, pMechanism: Buffer, hKey: number): number; - C_SignInit(hSession: number, pMechanism: Buffer, hKey: number, callback: Callback): void; - /** - * C_Sign signs (encrypts with private key) data in a single - * part, where the signature is (will be) an appendix to the - * data, and plaintext cannot be recovered from the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pData the data to sign - * @param {number} ulDataLen count of bytes to sign - * @param {Buffer} pSignature gets the signature - * @param {Buffer} pulSignatureLen gets signature length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Sign(hSession: number, pData: Buffer, ulDataLen: number, pSignature: Buffer, pulSignatureLen: Buffer): number; - C_Sign(hSession: number, pData: Buffer, ulDataLen: number, pSignature: Buffer, pulSignatureLen: Buffer, callback: Callback): void; - /** - * C_SignUpdate continues a multiple-part signature operation, - * where the signature is (will be) an appendix to the data, - * and plaintext cannot be recovered from the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pPart the data to sign - * @param {number} ulPartLen count of bytes to sign - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SignUpdate(hSession: number, pPart: Buffer, ulPartLen: Buffer): number; - C_SignUpdate(hSession: number, pPart: Buffer, ulPartLen: Buffer, callback: Callback): void; - /** - * C_SignFinal finishes a multiple-part signature operation, - * returning the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pSignature gets the signature - * @param {Buffer} pulSignatureLen gets signature length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SignFinal(hSession: number, pSignature: Buffer, pulSignatureLen: Buffer): number; - C_SignFinal(hSession: number, pSignature: Buffer, pulSignatureLen: Buffer, callback: Callback): void; - /** - * C_SignRecoverInit initializes a signature operation, where - * the data can be recovered from the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism the signature mechanism - * @param {number} hKey handle of the signature key - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SignRecoverInit(hSession: number, pMechanism: Buffer, hKey: number): number; - C_SignRecoverInit(hSession: number, pMechanism: Buffer, hKey: number, callback: Callback): void; - /** - * C_SignRecover signs data in a single operation, where the - * data can be recovered from the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pData the data to sign - * @param {number} ulDataLen count of bytes to sign - * @param {Buffer} pSignature gets the signature - * @param {Buffer} pulSignatureLen gets signature length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SignRecover(hSession: number, pData: Buffer, ulDataLen: number, pSignature: Buffer, pulSignatureLen: Buffer): number; - C_SignRecover(hSession: number, pData: Buffer, ulDataLen: number, pSignature: Buffer, pulSignatureLen: Buffer, callback: Callback): void; - /** - * C_VerifyInit initializes a verification operation, where the - * signature is an appendix to the data, and plaintext cannot - * cannot be recovered from the signature (e.g. DSA). - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism the verification mechanism - * @param {number} hKey verification key - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_VerifyInit(hSession: number, pMechanism: Buffer, hKey: number): number; - C_VerifyInit(hSession: number, pMechanism: Buffer, hKey: number, callback: Callback): void; - /** - * C_Verify verifies a signature in a single-part operation, - * where the signature is an appendix to the data, and plaintext - * cannot be recovered from the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pData signed data - * @param {number} ulDataLen length of signed data - * @param {Buffer} pSignature signature - * @param {number} ulSignatureLen signature length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_Verify(hSession: number, pData: Buffer, ulDataLen: number, pSignature: Buffer, ulSignatureLen: Buffer): number; - C_Verify(hSession: number, pData: Buffer, ulDataLen: number, pSignature: Buffer, ulSignatureLen: Buffer, callback: Callback): void; - /** - * C_VerifyUpdate continues a multiple-part verification - * operation, where the signature is an appendix to the data, - * and plaintext cannot be recovered from the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pPart signed data - * @param {number} ulPartLen length of signed data - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_VerifyUpdate(hSession: number, pPart: Buffer, ulPartLen: number): number; - C_VerifyUpdate(hSession: number, pPart: Buffer, ulPartLen: number, callback: Callback): void; - /** - * C_VerifyFinal finishes a multiple-part verification - * operation, checking the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pSignature signature to verify - * @param {number} ulSignatureLen signature length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_VerifyFinal(hSession: number, pSignature: Buffer, ulSignatureLen: number): number; - C_VerifyFinal(hSession: number, pSignature: Buffer, ulSignatureLen: number, callback: Callback): void; - /** - * C_VerifyRecoverInit initializes a signature verification - * operation, where the data is recovered from the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism the verification mechanism - * @param {number} hKey verification key - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_VerifyRecoverInit(hSession: number, pMechanism: Buffer, hKey: number): number; - C_VerifyRecoverInit(hSession: number, pMechanism: Buffer, hKey: number, callback: Callback): void; - /** - * C_VerifyRecover verifies a signature in a single-part - * operation, where the data is recovered from the signature. - * @param {number} hSession the session's handle - * @param {Buffer} pSignature signature to verify - * @param {number} ulSignatureLen signature length - * @param {Buffer} pData gets signed data - * @param {Buffer} pulDataLen gets signed data len - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_VerifyRecover(hSession: number, pSignature: Buffer, ulSignatureLen: number, pData: Buffer, pulDataLen: Buffer): number; - C_VerifyRecover(hSession: number, pSignature: Buffer, ulSignatureLen: number, pData: Buffer, pulDataLen: Buffer, callback: Callback): void; - /** - * C_DigestEncryptUpdate continues a multiple-part digesting - * and encryption operation. - * @param {number} hSession the session's handle - * @param {Buffer} pPart the plaintext data - * @param {number} ulPartLen plaintext length - * @param {Buffer} pEncryptedPart gets ciphertext - * @param {Buffer} pulEncryptedPartLen gets c-text length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DigestEncryptUpdate(hSession: number, pPart: Buffer, ulPartLen: number, pEncryptedPart: Buffer, pulEncryptedPartLen: Buffer): number; - C_DigestEncryptUpdate(hSession: number, pPart: Buffer, ulPartLen: number, pEncryptedPart: Buffer, pulEncryptedPartLen: Buffer, callback: Callback): void; - /** - * C_DecryptDigestUpdate continues a multiple-part decryption and - * digesting operation. - * @param {number} hSession the session's handle - * @param {Buffer} pEncryptedPart ciphertext - * @param {number} ulEncryptedPartLen ciphertext length - * @param {Buffer} pPart gets plaintext - * @param {Buffer} pulPartLen gets plaintext len - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DecryptDigestUpdate(hSession: number, pEncryptedPart: Buffer, ulEncryptedPartLen: number, pPart: Buffer, pulPartLen: Buffer): number; - C_DecryptDigestUpdate(hSession: number, pEncryptedPart: Buffer, ulEncryptedPartLen: number, pPart: Buffer, pulPartLen: Buffer, callback: Callback): void; - /** - * C_SignEncryptUpdate continues a multiple-part signing and - * encryption operation. - * @param {number} hSession the session's handle - * @param {Buffer} pPart the plaintext data - * @param {number} ulPartLen plaintext length - * @param {Buffer} pEncryptedPart gets ciphertext - * @param {Buffer} pulEncryptedPartLen gets c-text length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SignEncryptUpdate(hSession: number, pPart: Buffer, ulPartLen: number, pEncryptedPart: Buffer, pulEncryptedPartLen: Buffer): number; - C_SignEncryptUpdate(hSession: number, pPart: Buffer, ulPartLen: number, pEncryptedPart: Buffer, pulEncryptedPartLen: Buffer, callback: Callback): void; - /** - * C_DecryptVerifyUpdate continues a multiple-part decryption and - * verify operation. - * @param {number} hSession the session's handle - * @param {Buffer} pEncryptedPart ciphertext - * @param {number} ulEncryptedPartLen ciphertext length - * @param {Buffer} pPart gets plaintext - * @param {Buffer} pulPartLen gets p-text length - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DecryptVerifyUpdate(hSession: number, pEncryptedPart: Buffer, ulEncryptedPartLen: number, pPart: Buffer, pulPartLen: Buffer): number; - C_DecryptVerifyUpdate(hSession: number, pEncryptedPart: Buffer, ulEncryptedPartLen: number, pPart: Buffer, pulPartLen: Buffer, callback: Callback): void; - /** - * C_GenerateKey generates a secret key, creating a new key object. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism key generation mech. - * @param {Buffer} pTemplate template for new key - * @param {number} ulCount # of attrs in template - * @param {Buffer} phKey gets handle of new key - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GenerateKey(hSession: number, pMechanism: Buffer, pTemplate: Buffer, ulCount: number, phKey: Buffer): number; - C_GenerateKey(hSession: number, pMechanism: Buffer, pTemplate: Buffer, ulCount: number, phKey: Buffer, callback: Callback): any; - /** - * C_GenerateKeyPair generates a public-key/private-key pair, - * creating new key objects. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism key-gen mech. - * @param {Buffer} pPublicKeyTemplate template for public key - * @param {number} ulPublicKeyAttributeCount public attrs - * @param {Buffer} pPrivateKeyTemplate template for private key - * @param {number} ulPrivateKeyAttributeCount private attrs - * @param {Buffer} phPublicKey gets public key handle - * @param {Buffer} phPrivateKey gets private key handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GenerateKeyPair(hSession: number, pMechanism: Buffer, pPublicKeyTemplate: Buffer, ulPublicKeyAttributeCount: number, pPrivateKeyTemplate: Buffer, ulPrivateKeyAttributeCount: number, phPublicKey: Buffer, phPrivateKey: Buffer): number; - C_GenerateKeyPair(hSession: number, pMechanism: Buffer, pPublicKeyTemplate: Buffer, ulPublicKeyAttributeCount: number, pPrivateKeyTemplate: Buffer, ulPrivateKeyAttributeCount: number, phPublicKey: Buffer, phPrivateKey: Buffer, callback: Callback): void; - /** - * C_WrapKey wraps (i.e., encrypts) a key. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism the wrapping mechanism - * @param {number} hWrappingKey wrapping key - * @param {number} hKey key to be wrapped - * @param {Buffer} pWrappedKey gets wrapped key - * @param {Buffer} pulWrappedKeyLen gets wrapped key size - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_WrapKey(hSession: number, pMechanism: Buffer, hWrappingKey: number, hKey: number, pWrappedKey: Buffer, pulWrappedKeyLen: Buffer): number; - C_WrapKey(hSession: number, pMechanism: Buffer, hWrappingKey: number, hKey: number, pWrappedKey: Buffer, pulWrappedKeyLen: Buffer, callback: Callback): void; - /** - * C_UnwrapKey unwraps (decrypts) a wrapped key, creating a new - * key object. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism unwrapping mech. - * @param {Buffer} pWrappedKey the wrapped key - * @param {number} ulWrappedKeyLen wrapped key len - * @param {Buffer} pTemplate new key template - * @param {number} ulAttributeCount template length - * @param {Buffer} pTemplate new key template - * @param {number} ulAttributeCount template length - * @param {Buffer} phKey gets new handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_UnwrapKey(hSession: number, pMechanism: Buffer, hUnwrappingKey: number, pWrappedKey: Buffer, ulWrappedKeyLen: number, pTemplate: Buffer, ulAttributeCount: number, phKey: Buffer): number; - C_UnwrapKey(hSession: number, pMechanism: Buffer, hUnwrappingKey: number, pWrappedKey: Buffer, ulWrappedKeyLen: number, pTemplate: Buffer, ulAttributeCount: number, phKey: Buffer, callback: Callback): void; - /** - * C_DeriveKey derives a key from a base key, creating a new key object. - * @param {number} hSession the session's handle - * @param {Buffer} pMechanism key deriv. mech. - * @param {number} hBaseKey base key - * @param {Buffer} pTemplate new key template - * @param {number} ulAttributeCount template length - * @param {Buffer} phKey gets new handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_DeriveKey(hSession: number, pMechanism: Buffer, hBaseKey: number, pTemplate: Buffer, ulAttributeCount: number, phKey: Buffer): number; - C_DeriveKey(hSession: number, pMechanism: Buffer, hBaseKey: number, pTemplate: Buffer, ulAttributeCount: number, phKey: Buffer, callback: Callback): void; - /** - * C_SeedRandom mixes additional seed material into the token's - * random number generator. - * @param {number} hSession the session's handle - * @param {Buffer} pSeed the seed material - * @param {number} ulSeedLen length of seed material - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_SeedRandom(hSession: number, pSeed: Buffer, ulSeedLen: number): number; - C_SeedRandom(hSession: number, pSeed: Buffer, ulSeedLen: number, callback: Callback): void; - /** - * C_GenerateRandom generates random data. - * @param {number} hSession the session's handle - * @param {Buffer} pRandomData receives the random data - * @param {number} ulRandomLen # of bytes to generate - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GenerateRandom(hSession: number, pRandomData: Buffer, ulRandomLen: number): number; - C_GenerateRandom(hSession: number, pRandomData: Buffer, ulRandomLen: number, callback: Callback): void; - /** - * C_GetFunctionStatus is a legacy function; it obtains an - * updated status of a function running in parallel with an - * application. - * @param {number} hSession the session's handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_GetFunctionStatus(hSession: number): number; - C_GetFunctionStatus(hSession: number, callback: Callback): void; - /** - * C_CancelFunction is a legacy function; it cancels a function - * running in parallel. - * @param {number} hSession the session's handle - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_CancelFunction(hSession: number): number; - C_CancelFunction(hSession: number, callback: Callback): void; - /** - * C_WaitForSlotEvent waits for a slot event (token insertion, - * removal, etc.) to occur. - * @param {number} flags blocking/nonblocking flag - * @param {Buffer} pSlot location that receives the slot ID - * @param {Buffer} pRserved reserved. Should be NULL_PTR - * @param {Callback} callback callback function with PKCS11 result value - * @returns void PKCS11 result value - */ - C_WaitForSlotEvent(flags: number, pSlot: Buffer, pRserved: Buffer): number; - C_WaitForSlotEvent(flags: number, pSlot: Buffer, pRserved: Buffer, callback: Callback): number; + type Handle = Buffer; + type CryptoData = string | Buffer; + + class Pkcs11Error extends Error { + code: number; + func: string; + constructor(code: number, func: string); + } + + class BaseObject { + protected lib: pkcs11.PKCS11; + constructor(lib?: pkcs11.PKCS11); + } + + class HandleObject extends BaseObject { + /** + * handle to pkcs11 object + */ + handle: Handle; + + constructor(handle: Handle, lib: pkcs11.PKCS11); + + protected getInfo(): void; + } + + class Collection extends BaseObject { + + protected items_: Array; + protected classType: any; + + /** + * returns length of collection + */ + length: number; + + constructor(items: Array, lib: pkcs11.PKCS11, classType: any); + + /** + * returns item from collection by index + * @param {number} index of element in collection `[0..n]` + */ + items(index: number): T; + } + + function isString(v: any): boolean; + function isNumber(v: any): boolean; + function isBoolean(v: any): boolean; + function isUndefined(v: any): boolean; + function isNull(v: any): boolean; + function isEmpty(v: any): boolean; + function isFunction(v: any): boolean; + function isObject(v: any): boolean; + function isArray(v: any): boolean; + function isFlag(v: any, fv: number): boolean; + function dateFromString(text: string): Date; + + // ========== Crypto ========== + + class Cipher extends BaseObject { + + session: Session; + + constructor(session: Session, alg: MechanismType, key: Key, lib: pkcs11.PKCS11); + + protected init(alg: MechanismType, key: Key): void; + + update(data: CryptoData): Buffer; + final(): Buffer; + once(data: CryptoData, enc: Buffer): Buffer; + once(data: CryptoData, enc: Buffer, cb: (error: Error, data: Buffer) => void): void; + } + + class Decipher extends BaseObject { + + protected session: Session; + protected blockSize: number; + + constructor(session: Session, alg: MechanismType, key: Key, blockSize: number, lib: pkcs11.PKCS11); + + protected init(alg: MechanismType, key: Key): void; + + update(data: Buffer): Buffer; + final(): Buffer; + once(data: Buffer, dec: Buffer): Buffer; + once(data: Buffer, dec: Buffer, cb: (error: Error, data: Buffer) => void): void; + } + + class Digest extends BaseObject { + + session: Session; + + constructor(session: Session, alg: MechanismType, lib: pkcs11.PKCS11); + + protected init(alg: MechanismType): void; + + update(data: CryptoData): void; + final(): Buffer; + once(data: CryptoData): Buffer; + once(data: CryptoData, cb: (error: Error, data: Buffer) => void): void; + } + + class Sign extends BaseObject { + + session: Session; + + constructor(session: Session, alg: MechanismType, key: Key, lib: pkcs11.PKCS11); + + protected init(alg: MechanismType, key: Key): void; + + update(data: CryptoData): void; + final(): Buffer; + once(data: CryptoData): Buffer; + once(data: CryptoData, cb: (error: Error, data: Buffer) => void): void; + } + + class Verify extends BaseObject { + + session: Session; + + constructor(session: Session, alg: MechanismType, key: Key, lib: pkcs11.PKCS11); + + protected init(alg: MechanismType, key: Key): void; + + update(data: CryptoData): void; + final(signature: Buffer): boolean; + once(data: CryptoData, signature: Buffer): boolean; + once(data: CryptoData, signature: Buffer, cb: (error: Error, valid: boolean) => void): void; + } + + // ========== Keys ========== + + interface IParams { + toCKI(): any; + } + + enum MechParams { + AesCBC, + AesCCM, + AesGCM, + RsaOAEP, + RsaPSS, + EcDH, + } + + // AES + + class AesCbcParams implements IParams, pkcs11.AesCBC { + /** + * initialization vector + * - must have a fixed size of 16 bytes + */ + iv: Buffer; + /** + * the data + */ + data: Buffer; + type: MechParams; + constructor(iv: Buffer, data?: Buffer); + toCKI(): Buffer; + } + + class AesCcmParams implements IParams { + /** + * length of the data where 0 <= dataLength < 2^8L + */ + dataLength: number; + /** + * the nonce + */ + nonce: Buffer; + /** + * the additional authentication data + * - This data is authenticated but not encrypted + */ + aad: Buffer; + /** + * length of authentication tag (output following cipher text) in bits. + * - Can be any value between 0 and 128 + */ + macLength: number; + type: MechParams; + constructor(dataLength: number, nonce: Buffer, aad?: Buffer, macLength?: number); + toCKI(): pkcs11.AesCCM; + } + + class AesGcmParams implements IParams { + /** + * initialization vector + * - The length of the initialization vector can be any number between 1 and 256. + * 96-bit (12 byte) IV values can be processed more efficiently, + * so that length is recommended for situations in which efficiency is critical. + */ + iv: Buffer; + /** + * pointer to additional authentication data. + * This data is authenticated but not encrypted. + */ + aad: Buffer; + /** + * length of authentication tag (output following cipher text) in bits. + * Can be any value between 0 and 128. Default 128 + */ + tagBits: number; + type: MechParams; + constructor(iv: Buffer, aad?: Buffer, tagBits?: number); + toCKI(): pkcs11.AesGCM; + } + + // EC + + interface INamedCurve { + name: string; + oid: string; + value: Buffer; + size: number; + } + + class NamedCurve { + static getByName(name: string): INamedCurve; + static getByOid(oid: string): INamedCurve; + } + + enum EcKdf { + NULL, + SHA1, + SHA224, + SHA256, + SHA384, + SHA512, + } + + class EcdhParams implements IParams, pkcs11.ECDH1 { + /** + * key derivation function used on the shared secret value + */ + kdf: EcKdf; + /** + * some data shared between the two parties + */ + sharedData: Buffer; + /** + * other party's EC public key value + */ + publicData: Buffer; + type: MechParams; + /** + * Creates an instance of EcdhParams. + * + * @param {EcKdf} kdf key derivation function used on the shared secret value + * @param {Buffer} [sharedData=null] some data shared between the two parties + * @param {Buffer} [publicData=null] other party's EC public key value + */ + constructor(kdf: EcKdf, sharedData?: Buffer, publicData?: Buffer); + toCKI(): pkcs11.ECDH1; + } + + // Rsa + + enum RsaMgf { + MGF1_SHA1, + MGF1_SHA224, + MGF1_SHA256, + MGF1_SHA384, + MGF1_SHA512, + } + + class RsaOaepParams implements IParams { + hashAlgorithm: MechanismEnum; + mgf: RsaMgf; + source: number; + sourceData: Buffer; + type: MechParams; + constructor(hashAlg?: MechanismEnum, mgf?: RsaMgf, sourceData?: Buffer); + toCKI(): pkcs11.RsaOAEP; + } + + class RsaPssParams implements IParams { + /** + * hash algorithm used in the PSS encoding; + * - if the signature mechanism does not include message hashing, + * then this value must be the mechanism used by the application to generate + * the message hash; + * - if the signature mechanism includes hashing, + * then this value must match the hash algorithm indicated + * by the signature mechanism + */ + hashAlgorithm: MechanismEnum; + /** + * mask generation function to use on the encoded block + */ + mgf: RsaMgf; + /** + * length, in bytes, of the salt value used in the PSS encoding; + * - typical values are the length of the message hash and zero + */ + saltLength: number; + type: MechParams; + constructor(hashAlg?: MechanismEnum, mgf?: RsaMgf, saltLen?: number); + toCKI(): pkcs11.RsaPSS; + } + + // ========== Objects ========== + + enum ObjectClass { + DATA, + CERTIFICATE, + PUBLIC_KEY, + PRIVATE_KEY, + SECRET_KEY, + HW_FEATURE, + DOMAIN_PARAMETERS, + MECHANISM, + OTP_KEY, + } + + class SessionObject extends HandleObject { + /** + * Session + */ + session: Session; + /** + * gets the size of an object in bytes + * + * @readonly + * @type {number} + */ + size: number; + class: ObjectClass; + + /** + * Creates an instance of SessionObject. + * + * @param {SessionObject} object + */ + constructor(object: SessionObject); + /** + * Creates an instance of SessionObject. + * + * @param {Handle} handle + * @param {Session} session + * @param {pkcs11.PKCS11} lib + */ + constructor(handle: Handle, session: Session, lib: pkcs11.PKCS11); + constructor(handle: SessionObject); + + /** + * copies an object, creating a new object for the copy + * + * @param {ITemplate} template template for the new object + * @returns {SessionObject} + */ + copy(template: ITemplate): SessionObject; + /** + * destroys an object + */ + destroy(): void; + getAttribute(attr: string): ITemplate; + getAttribute(attrs: ITemplate): ITemplate; + setAttribute(attrs: string, value: any): void; + setAttribute(attrs: ITemplate): void; + get(name: string): any; + set(name: string, value: any): void; + toType(): T; + } + + class SessionObjectCollection extends Collection { + session: Session; + + constructor(items: Array, session: Session, lib: pkcs11.PKCS11, classType?: any); + + items(index: number): SessionObject; + } + + class Storage extends SessionObject { + /** + * `true` if object is a token object; + * `false` if object is a session object. Default is `false`. + */ + token: boolean; + /** + * `true` if object is a private object; + * `false` if object is a public object. + * Default value is token-specific, and may depend on the values of other attributes of the object. + */ + private: boolean; + /** + * `true` if object can be modified. Default is `false` + */ + modifiable: boolean; + /** + * Description of the object (default empty) + */ + label: string; + } + + /** + * Data objects (object class `CKO_DATA`) hold information defined by an application. + * Other than providing access to it, Cryptoki does not attach any special meaning to a data object + * + * @export + * @class Data + * @extends {Storage} + */ + class Data extends Storage { + /** + * Description of the application that manages the object (default empty) + * + * @type {string} + */ + application: string; + /** + * DER-encoding of the object identifier indicating the data object type (default empty) + * + * @type {Buffer} + */ + objectId: Buffer; + /** + * Value of the object (default empty) + * + * @type {Buffer} + */ + value: Buffer; + } + + class DomainParameters extends Storage { + /** + * Type of key the domain parameters can be used to generate. + */ + keyType: KeyType; + /** + * `CK_TRUE` only if domain parameters were either * generated locally (i.e., on the token) + * with a `C_GenerateKey` * created with a `C_CopyObject` call as a copy of domain parameters + * which had its `CKA_LOCAL` attribute set to `CK_TRUE` + */ + local: boolean; } enum KeyType { @@ -841,6 +521,638 @@ declare module "graphene-pk11" { TWOFISH, } + /** + * Definition for the base key object class + * - defines the object class `CKO_PUBLIC_KEY`, `CKO_PRIVATE_KEY` and `CKO_SECRET_KEY` for type `CK_OBJECT_CLASS` + * as used in the `CKA_CLASS` attribute of objects + */ + class Key extends Storage { + /** + * Type of key + * - Must be specified when object is created with `C_CreateObject` + * - Must be specified when object is unwrapped with `C_UnwrapKey` + */ + type: KeyType; + /** + * Key identifier for key (default empty) + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification + * of the attribute during the course of a `C_CopyObject` call. + */ + id: Buffer; + /** + * Start date for the key (default empty) + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification + * of the attribute during the course of a `C_CopyObject` call. + */ + startDate: Date; + /** + * End date for the key (default empty) + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification + * of the attribute during the course of a `C_CopyObject` call. + */ + endDate: Date; + /** + * `CK_TRUE` if key supports key derivation + * (i.e., if other keys can be derived from this one (default `CK_FALSE`) + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification + * of the attribute during the course of a `C_CopyObject` call. + * @returns boolean + */ + derive: boolean; + /** + * `CK_TRUE` only if key was either * generated locally (i.e., on the token) + * with a `C_GenerateKey` or `C_GenerateKeyPair` call * created with a `C_CopyObject` call + * as a copy of a key which had its `CKA_LOCAL` attribute set to `CK_TRUE` + * - Must not be specified when object is created with `C_CreateObject`. + * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. + * - Must not be specified when object is unwrapped with `C_UnwrapKey`. + */ + local: boolean; + /** + * Identifier of the mechanism used to generate the key material. + * - Must not be specified when object is created with `C_CreateObject`. + * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. + * - Must not be specified when object is unwrapped with `C_UnwrapKey`. + */ + mechanism: KeyGenMechanism; + allowedMechanisms: void; + } + + /** + * Private key objects (object class `CKO_PRIVATE_KEY`) hold private keys + */ + class PrivateKey extends Key { + /** + * DER-encoding of the key subject name (default empty) + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + */ + subject: Buffer; + /** + * `CK_TRUE` if key is sensitive + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Attribute cannot be changed once set to CK_TRUE. It becomes a read only attribute. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + sensitive: boolean; + /** + * `CK_TRUE` if key supports decryption + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + decrypt: boolean; + /** + * `CK_TRUE` if key supports signatures where the signature is an appendix to the data + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + sign: boolean; + /** + * `CK_TRUE` if key supports signatures where the data can be recovered from the signature + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + signRecover: boolean; + /** + * `CK_TRUE` if key supports unwrapping (i.e., can be used to unwrap other keys) + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + unwrap: boolean; + /** + * `CK_TRUE` if key is extractable and can be wrapped + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Attribute cannot be changed once set to `CK_FALSE`. It becomes a read only attribute. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + extractable: boolean; + /** + * `CK_TRUE` if key has always had the `CKA_SENSITIVE` attribute set to `CK_TRUE` + * - Must not be specified when object is created with `C_CreateObject`. + * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. + * - Must not be specified when object is unwrapped with `C_UnwrapKey`. + */ + alwaysSensitive: boolean; + /** + * `CK_TRUE` if key has never had the `CKA_EXTRACTABLE` attribute set to `CK_TRUE` + * - Must not be specified when object is created with `C_CreateObject`. + * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. + * - Must not be specified when object is unwrapped with `C_UnwrapKey`. + */ + neverExtractable: boolean; + /** + * `CK_TRUE` if the key can only be wrapped with a wrapping key + * that has `CKA_TRUSTED` set to `CK_TRUE`. Default is `CK_FALSE`. + * - Attribute cannot be changed once set to `CK_TRUE`. It becomes a read only attribute. + */ + wrapTrusted: boolean; + /** + * For wrapping keys. The attribute template to apply to any keys unwrapped + * using this wrapping key. Any user supplied template is applied after this template + * as if the object has already been created. + */ + template: void; + alwaysAuthenticate: boolean; + } + + /** + * Public key objects (object class CKO_PUBLIC_KEY) hold public keys + */ + class PublicKey extends Key { + /** + * DER-encoding of the key subject name (default empty) + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + */ + subject: Buffer; + /** + * `CK_TRUE` if key supports encryption + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + encrypt: boolean; + /** + * `CK_TRUE` if key supports verification where the signature is an appendix to the data + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + verify: boolean; + /** + * `CK_TRUE` if key supports verification where the data is recovered from the signature + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + verifyRecover: boolean; + /** + * `CK_TRUE` if key supports wrapping (i.e., can be used to wrap other keys) + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + wrap: boolean; + /** + * The key can be trusted for the application that it was created. + * - The wrapping key can be used to wrap keys with `CKA_WRAP_WITH_TRUSTED` set to `CK_TRUE`. + * - Can only be set to CK_TRUE by the SO user. + */ + trusted: boolean; + /** + * For wrapping keys. The attribute template to match against any keys wrapped using this wrapping key. + * Keys that do not match cannot be wrapped. + */ + template: void; + } + + /** + * Secret key objects (object class `CKO_SECRET_KEY`) hold secret keys. + */ + class SecretKey extends Key { + /** + * `CK_TRUE` if key is sensitive + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Attribute cannot be changed once set to `CK_TRUE`. It becomes a read only attribute. + */ + sensitive: boolean; + /** + * `CK_TRUE` if key supports encryption + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + encrypt: boolean; + /** + * `CK_TRUE` if key supports decryption + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + decrypt: boolean; + /** + * `CK_TRUE` if key supports verification (i.e., of authentication codes) where the signature is an appendix to the data + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + verify: boolean; + /** + * `CK_TRUE` if key supports signatures (i.e., authentication codes) where the signature is an appendix to the data + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + sign: boolean; + /** + * `CK_TRUE` if key supports wrapping (i.e., can be used to wrap other keys) + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + wrap: boolean; + /** + * `CK_TRUE` if key supports unwrapping (i.e., can be used to unwrap other keys) + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + unwrap: boolean; + /** + * `CK_TRUE` if key is extractable and can be wrapped + * - May be modified after object is created with a `C_SetAttributeValue` call, + * or in the process of copying object with a `C_CopyObject` call. + * However, it is possible that a particular token may not permit modification of the attribute + * during the course of a `C_CopyObject` call. + * - Attribute cannot be changed once set to `CK_FALSE`. It becomes a read only attribute. + * - Default value is token-specific, and may depend on the values of other attributes. + */ + extractable: boolean; + /** + * `CK_TRUE` if key has always had the `CKA_SENSITIVE` attribute set to `CK_TRUE` + * - Must not be specified when object is created with `C_CreateObject`. + * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. + * - Must not be specified when object is unwrapped with `C_UnwrapKey`. + */ + alwaysSensitive: boolean; + /** + * `CK_TRUE` if key has never had the `CKA_EXTRACTABLE` attribute set to `CK_TRUE` + * - Must not be specified when object is created with `C_CreateObject`. + * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. + * - Must not be specified when object is unwrapped with `C_UnwrapKey`. + */ + neverExtractable: boolean; + /** + * Key checksum + */ + checkValue: Buffer; + /** + * `CK_TRUE` if the key can only be wrapped with a wrapping key + * that has `CKA_TRUSTED` set to `CK_TRUE`. Default is `CK_FALSE`. + * - Attribute cannot be changed once set to `CK_TRUE`. It becomes a read only attribute. + */ + wrapTrusted: boolean; + /** + * The wrapping key can be used to wrap keys with `CKA_WRAP_WITH_TRUSTED` set to `CK_TRUE`. + * - Can only be set to CK_TRUE by the SO user. + */ + trusted: boolean; + /** + * For wrapping keys. + * The attribute template to match against any keys wrapped using this wrapping key. + * Keys that do not match cannot be wrapped. + */ + wrapTemplate: void; + /** + * For wrapping keys. + * The attribute template to apply to any keys unwrapped using this wrapping key. + * Any user supplied template is applied after this template as if the object has already been created. + */ + unwrapTemplate: void; + } + + enum CertificateType { + X_509, + X_509_ATTR_CERT, + WTLS, + } + + enum CertificateCategory { + Unspecified, + TokenUser, + Authority, + OtherEntity, + } + + /** + * Certificate objects (object class CKO_CERTIFICATE) hold public-key or attribute certificates + */ + class Certificate extends Storage { + /** + * Type of certificate + */ + type: CertificateType; + /** + * The certificate can be trusted for the application that it was created. + */ + trusted: boolean; + /** + * Categorization of the certificate + */ + category: CertificateCategory; + /** + * Checksum + */ + checkValue: Buffer; + /** + * Start date for the certificate (default empty) + */ + startDate: Date; + /** + * End date for the certificate (default empty) + */ + endDate: Date; + } + + /** + * X.509 attribute certificate objects (certificate type `CKC_X_509_ATTR_CERT`) hold X.509 attribute certificates + */ + class AttributeCertificate extends Certificate { + /** + * DER-encoding of the attribute certificate's subject field. + * This is distinct from the `CKA_SUBJECT` attribute contained in `CKC_X_509` certificates + * because the `ASN.1` syntax and encoding are different. + * - Must be specified when the object is created + */ + owner: Buffer; + /** + * DER-encoding of the attribute certificate's issuer field. + * This is distinct from the `CKA_ISSUER` attribute contained in `CKC_X_509` certificates + * because the ASN.1 syntax and encoding are different. (default empty) + */ + issuer: Buffer; + /** + * DER-encoding of the certificate serial number (default empty) + */ + serialNumber: Buffer; + /** + * BER-encoding of a sequence of object identifier values corresponding + * to the attribute types contained in the certificate. + * When present, this field offers an opportunity for applications + * to search for a particular attribute certificate without fetching + * and parsing the certificate itself. (default empty) + */ + types: Buffer; + /** + * BER-encoding of the certificate + * - Must be specified when the object is created. + */ + value: Buffer; + } + + /** + * WTLS certificate objects (certificate type `CKC_WTLS`) hold WTLS public key certificates + */ + class WtlsCertificate extends Certificate { + /** + * WTLS-encoding (Identifier type) of the certificate subject + * - Must be specified when the object is created. + * - Can only be empty if `CKA_VALUE` is empty. + */ + subject: Buffer; + /** + * WTLS-encoding (Identifier type) of the certificate issuer (default empty) + */ + issuer: Buffer; + /** + * Key identifier for public/private key pair (default empty) + */ + id: Buffer; + /** + * WTLS-encoding of the certificate + * - Must be specified when the object is created. + * - Must be non-empty if `CKA_URL` is empty. + */ + value: Buffer; + /** + * If not empty this attribute gives the URL where the complete certificate + * can be obtained (default empty) + * - Must be non-empty if `CKA_VALUE` is empty + */ + url: string; + /** + * DER-encoding of the certificate serial number (default empty) + */ + serialNumber: Buffer; + /** + * SHA-1 hash of the subject public key (default empty) + * - Can only be empty if `CKA_URL` is empty. + */ + subjetcKeyIdentifier: Buffer; + /** + * SHA-1 hash of the issuer public key (default empty) + * - Can only be empty if `CKA_URL` is empty. + */ + authorityKeyIdentifier: Buffer; + } + + enum JavaMIDP { + Unspecified, + Manufacturer, + Operator, + ThirdParty, + } + + /** + * X.509 certificate objects (certificate type `CKC_X_509`) hold X.509 public key certificates + */ + class X509Certificate extends Certificate { + /** + * DER-encoding of the certificate subject name + * - Must be specified when the object is created. + * - Must be non-empty if `CKA_URL` is empty. + */ + subject: Buffer; + /** + * Key identifier for public/private key pair (default empty) + */ + id: Buffer; + /** + * DER-encoding of the certificate issuer name (default empty) + */ + issuer: Buffer; + /** + * HEX-encoding of the certificate serial number (default empty) + */ + serialNumber: string; + /** + * BER-encoding of the certificate + * - Must be specified when the object is created. + * - Must be non-empty if `CKA_URL` is empty. + */ + value: Buffer; + /** + * If not empty this attribute gives the URL where the complete certificate + * can be obtained (default empty) + * - Must be non-empty if `CKA_VALUE` is empty + */ + url: string; + /** + * SHA-1 hash of the subject public key (default empty) + * - Can only be empty if `CKA_URL` is empty. + */ + subjetcKeyIdentifier: Buffer; + /** + * SHA-1 hash of the issuer public key (default empty) + * - Can only be empty if `CKA_URL` is empty. + */ + authorityKeyIdentifier: Buffer; + /** + * Java MIDP security domain + */ + java: JavaMIDP; + } + + interface IAlgorithm { + name: string; + params: Buffer | IParams; + } + + type MechanismType = MechanismEnum | KeyGenMechanism | IAlgorithm | string; + + enum MechanismFlag { + /** + * `True` if the mechanism is performed by the device; `false` if the mechanism is performed in software + */ + HW, + /** + * `True` if the mechanism can be used with encrypt function + */ + ENCRYPT, + /** + * `True` if the mechanism can be used with decrypt function + */ + DECRYPT, + /** + * `True` if the mechanism can be used with digest function + */ + DIGEST, + /** + * `True` if the mechanism can be used with sign function + */ + SIGN, + /** + * `True` if the mechanism can be used with sign recover function + */ + SIGN_RECOVER, + /** + * `True` if the mechanism can be used with verify function + */ + VERIFY, + /** + * `True` if the mechanism can be used with verify recover function + */ + VERIFY_RECOVER, + /** + * `True` if the mechanism can be used with geberate function + */ + GENERATE, + /** + * `True` if the mechanism can be used with generate key pair function + */ + GENERATE_KEY_PAIR, + /** + * `True` if the mechanism can be used with wrap function + */ + WRAP, + /** + * `True` if the mechanism can be used with unwrap function + */ + UNWRAP, + /** + * `True` if the mechanism can be used with derive function + */ + DERIVE, + } + + class Mechanism extends BaseObject { + + protected handle: number; + protected slotHandle: Handle; + + /** + * the minimum size of the key for the mechanism + * _whether this is measured in bits or in bytes is mechanism-dependent_ + */ + minKeySize: number; + /** + * the maximum size of the key for the mechanism + * _whether this is measured in bits or in bytes is mechanism-dependent_ + */ + maxKeySize: number; + /** + * bit flag specifying mechanism capabilities + */ + flags: number; + /** + * returns string name from MechanismEnum + */ + name: string; + + constructor(handle: number, slotHandle: Handle, lib: pkcs11.PKCS11); + + protected getInfo(): void; + + static create(alg: MechanismType): pkcs11.Mechanism; + static vendor(jsonFile: string): void; + static vendor(name: string, value: number): void; + } + + class MechanismCollection extends Collection { + + protected slotHandle: Handle; + + constructor(items: Array, slotHandle: Handle, lib: pkcs11.PKCS11, classType?: typeof Mechanism); + /** + * returns item from collection by index + * @param {number} index of element in collection `[0..n]` + */ + items(index: number): Mechanism; + } + enum MechanismEnum { RSA_PKCS_KEY_PAIR_GEN, RSA_PKCS, @@ -860,6 +1172,10 @@ declare module "graphene-pk11" { DSA_KEY_PAIR_GEN, DSA, DSA_SHA1, + DSA_SHA224, + DSA_SHA256, + DSA_SHA384, + DSA_SHA512, DH_PKCS_KEY_PAIR_GEN, DH_PKCS_DERIVE, X9_42_DH_KEY_PAIR_GEN, @@ -1024,10 +1340,6 @@ declare module "graphene-pk11" { WTLS_CLIENT_KEY_AND_MAC_DERIVE, KEY_WRAP_LYNKS, KEY_WRAP_SET_OAEP, - CMS_SIG, - KIP_DERIVE, - KIP_WRAP, - KIP_MAC, CAMELLIA_KEY_GEN, CAMELLIA_ECB, CAMELLIA_CBC, @@ -1125,204 +1437,197 @@ declare module "graphene-pk11" { VENDOR_DEFINED, } - interface IParams { - toCKI(): Buffer; + enum SessionFlag { + /** + * `True` if the session is read/write; `false` if the session is read-only + */ + RW_SESSION, + /** + * This flag is provided for backward compatibility, and should always be set to `true` + */ + SERIAL_SESSION, } - interface IAlgorithm { - name: string; - params: Buffer | IParams; + enum UserType { + /** + * Security Officer + */ + SO, + /** + * User + */ + USER, + /** + * Context specific + */ + CONTEXT_SPECIFIC, } - type MechanismType = MechanismEnum | KeyGenMechanism | IAlgorithm | string; - - enum MechanismFlag { - /** - * `True` if the mechanism is performed by the device; `false` if the mechanism is performed in software - */ - HW, - /** - * `True` if the mechanism can be used with encrypt function - */ - ENCRYPT, - /** - * `True` if the mechanism can be used with decrypt function - */ - DECRYPT, - /** - * `True` if the mechanism can be used with digest function - */ - DIGEST, - /** - * `True` if the mechanism can be used with sign function - */ - SIGN, - /** - * `True` if the mechanism can be used with sign recover function - */ - SIGN_RECOVER, - /** - * `True` if the mechanism can be used with verify function - */ - VERIFY, - /** - * `True` if the mechanism can be used with verify recover function - */ - VERIFY_RECOVER, - /** - * `True` if the mechanism can be used with geberate function - */ - GENERATE, - /** - * `True` if the mechanism can be used with generate key pair function - */ - GENERATE_KEY_PAIR, - /** - * `True` if the mechanism can be used with wrap function - */ - WRAP, - /** - * `True` if the mechanism can be used with unwrap function - */ - UNWRAP, - /** - * `True` if the mechanism can be used with derive function - */ - DERIVE, + interface IKeyPair { + privateKey: PrivateKey; + publicKey: PublicKey; } - class Mechanism extends HandleObject { - protected slotHandle: number; + + /** + * provides information about a session + * + * @export + * @class Session + * @extends {core.HandleObject} + */ + class Session extends HandleObject { + + constructor(handle: Handle, slot: Slot, lib: pkcs11.PKCS11); /** - * the minimum size of the key for the mechanism - * _whether this is measured in bits or in bytes is mechanism-dependent_ + * Slot + * + * @type {Slot} */ - minKeySize: number; + slot: Slot; /** - * the maximum size of the key for the mechanism - * _whether this is measured in bits or in bytes is mechanism-dependent_ + * the state of the session + * + * @type {number} */ - maxKeySize: number; + state: number; /** - * bit flag specifying mechanism capabilities + * bit flags that define the type of session + * + * @type {number} */ flags: number; /** - * returns string name from MechanismEnum + * an error code defined by the cryptographic device. Used for errors not covered by Cryptoki + * + * @type {number} */ - name: string; - constructor(handle: number, slotHandle: number, lib: Pkcs11); + deviceError: number; + protected getInfo(): void; - static create(alg: MechanismType): Buffer; - static vendor(jsonFile: string): any; - static vendor(name: string, value: number): any; - } - class MechanismCollection extends Collection { - protected slotHandle: number; - constructor(items: Array, slotHandle: number, lib: Pkcs11, classType?: typeof Mechanism); /** - * returns item from collection by index - * @param {number} index of element in collection `[0..n]` + * closes a session between an application and a token */ - items(index: number): Mechanism; - } - - /** - * Definition for the base key object class - * - defines the object class `CKO_PUBLIC_KEY`, `CKO_PRIVATE_KEY` and `CKO_SECRET_KEY` for type `CK_OBJECT_CLASS` - * as used in the `CKA_CLASS` attribute of objects - */ - class Key extends Storage { + close(): void; /** - * Type of key - * - Must be specified when object is created with `C_CreateObject` - * - Must be specified when object is unwrapped with `C_UnwrapKey` + * initializes the normal user's PIN + * @param {string} pin the normal user's PIN */ - type: KeyType; + initPin(pin: string): void; /** - * Key identifier for key (default empty) - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification - * of the attribute during the course of a `C_CopyObject` call. + * modifies the PIN of the user who is logged in + * @param {string} oldPin + * @param {string} newPin */ - id: Buffer; + setPin(oldPin: string, newPin: string): void; /** - * Start date for the key (default empty) - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification - * of the attribute during the course of a `C_CopyObject` call. + * obtains a copy of the cryptographic operations state of a session, encoded as a string of bytes */ - startDate: Date; + getOperationState(): Buffer; /** - * End date for the key (default empty) - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification - * of the attribute during the course of a `C_CopyObject` call. + * restores the cryptographic operations state of a session + * from a string of bytes obtained with getOperationState + * @param {Buffer} state the saved state + * @param {number} encryptionKey holds key which will be used for an ongoing encryption + * or decryption operation in the restored session + * (or 0 if no encryption or decryption key is needed, + * either because no such operation is ongoing in the stored session + * or because all the necessary key information is present in the saved state) + * @param {number} authenticationKey holds a handle to the key which will be used for an ongoing signature, + * MACing, or verification operation in the restored session + * (or 0 if no such key is needed, either because no such operation is ongoing in the stored session + * or because all the necessary key information is present in the saved state) */ - endDate: Date; + setOperationState(state: Buffer, encryptionKey?: number, authenticationKey?: number): void; /** - * `CK_TRUE` if key supports key derivation - * (i.e., if other keys can be derived from this one (default `CK_FALSE`) - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification - * of the attribute during the course of a `C_CopyObject` call. - * @returns boolean + * logs a user into a token + * @param {string} pin the user's PIN. + * - This standard allows PIN values to contain any valid `UTF8` character, + * but the token may impose subset restrictions + * @param {} userType the user type. Default is `USER` */ - derive: boolean; + login(pin: string, userType?: UserType): void; /** - * `CK_TRUE` only if key was either * generated locally (i.e., on the token) - * with a `C_GenerateKey` or `C_GenerateKeyPair` call * created with a `C_CopyObject` call - * as a copy of a key which had its `CKA_LOCAL` attribute set to `CK_TRUE` - * - Must not be specified when object is created with `C_CreateObject`. - * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. - * - Must not be specified when object is unwrapped with `C_UnwrapKey`. + * logs a user out from a token */ - local: boolean; + logout(): void; /** - * Identifier of the mechanism used to generate the key material. - * - Must not be specified when object is created with `C_CreateObject`. - * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. - * - Must not be specified when object is unwrapped with `C_UnwrapKey`. + * creates a new object + * - Only session objects can be created during a read-only session. + * - Only public objects can be created unless the normal user is logged in. + * @param {ITemplate} template the object's template + * @returns {SessionObject} */ - mechanism: KeyGenMechanism; - allowedMechanisms: void; - } - - - class DomainParameters extends Storage { + create(template: ITemplate): SessionObject; /** - * Type of key the domain parameters can be used to generate. + * Copies an object, creating a new object for the copy + * @param {SessionObject} object the copied object + * @param {ITemplate} template template for new object + * @returns {SessionObject} */ - keyType: KeyType; + copy(object: SessionObject, template: ITemplate): SessionObject; /** - * `CK_TRUE` only if domain parameters were either * generated locally (i.e., on the token) - * with a `C_GenerateKey` * created with a `C_CopyObject` call as a copy of domain parameters - * which had its `CKA_LOCAL` attribute set to `CK_TRUE` + * removes all session objects matched to template + * - if template is null, removes all session objects + * - returns a number of destroied session objects + * @param {ITemplate} template template */ - local: boolean; - } - - /** - * Data objects (object class `CKO_DATA`) hold information defined by an application. - * Other than providing access to it, Cryptoki does not attach any special meaning to a data object - */ - class Data extends Storage { + destroy(template: ITemplate): number; /** - * Description of the application that manages the object (default empty) + * @param {SessionObject} object */ - application: string; + destroy(object: SessionObject): number; + destroy(): number; /** - * DER-encoding of the object identifier indicating the data object type (default empty) + * removes all session objects + * - returns a number of destroied session objects */ - objectId: Buffer; + clear(): number; /** - * Value of the object (default empty) + * returns a collection of session objects mached to template + * @param template template + * @param callback optional callback function wich is called for each founded object + * - if callback function returns false, it breaks find function. */ - value: Buffer; + find(callback?: (obj: SessionObject) => any): SessionObjectCollection; + find(template: ITemplate, callback?: (obj: SessionObject, index: number) => any): SessionObjectCollection; + /** + * Returns object from session by handle + * @param {number} handle handle of object + * @returns T + */ + getObject(handle: Handle): T; + /** + * generates a secret key or set of domain parameters, creating a new object. + * @param mechanism generation mechanism + * @param template template for the new key or set of domain parameters + */ + generateKey(mechanism: MechanismType, template?: ITemplate): SecretKey; + generateKey(mechanism: MechanismType, template: ITemplate, callback: (err: Error, key: SecretKey) => void): void; + generateKeyPair(mechanism: MechanismType, publicTemplate: ITemplate, privateTemplate: ITemplate): IKeyPair; + generateKeyPair(mechanism: MechanismType, publicTemplate: ITemplate, privateTemplate: ITemplate, callback: (err: Error, keys: IKeyPair) => void): void; + createSign(alg: MechanismType, key: Key): Sign; + createVerify(alg: MechanismType, key: Key): Verify; + createCipher(alg: MechanismType, key: Key): Cipher; + createDecipher(alg: MechanismType, key: Key, blockSize?: number): Decipher; + createDigest(alg: MechanismType): Digest; + wrapKey(alg: MechanismType, wrappingKey: Key, key: Key): Buffer; + wrapKey(alg: MechanismType, wrappingKey: Key, key: Key, callback: (err: Error, wkey: Buffer) => void): void; + unwrapKey(alg: MechanismType, unwrappingKey: Key, wrappedKey: Buffer, template: ITemplate): Key; + unwrapKey(alg: MechanismType, unwrappingKey: Key, wrappedKey: Buffer, template: ITemplate, callback: (err: Error, key: Key) => void): void; + /** + * derives a key from a base key, creating a new key object + * @param {MechanismType} alg key deriv. mech + * @param {Key} baseKey base key + * @param {ITemplate} template new key template + */ + deriveKey(alg: MechanismType, baseKey: Key, template: ITemplate): SecretKey; + deriveKey(alg: MechanismType, baseKey: Key, template: ITemplate, callback: (err: Error, key: Key) => void): void; + /** + * generates random data + * @param {number} size \# of bytes to generate + */ + generateRandom(size: number): Buffer; } interface ITemplate { @@ -1638,7 +1943,7 @@ declare module "graphene-pk11" { /** * CKA_OTP_USER_IDENTIFIER */ - OtpUserId?: any; + otpUserId?: any; /** * CKA_OTP_SERVICE_IDENTIFIER */ @@ -1724,374 +2029,10 @@ declare module "graphene-pk11" { */ allowedMechanisms?: any; } - class Attribute { - protected $value: Buffer; - type: number; - name: string; - convertType: string; - length: number; - value: any; - constructor(type: number, value?: any); - constructor(type: string, value?: any); - get(): any; - set(template: any): void; - } + class Template { - protected attrs: Attribute[]; - length: number; - constructor(template: string); - constructor(template: ITemplate); - set(v: any): Template; - ref(): Buffer; - serialize(): any; - } - - class BaseObject { - protected lib: Pkcs11; - constructor(lib?: Pkcs11); - } - class HandleObject extends BaseObject { - /** - * handle to pkcs11 object - */ - handle: number; - constructor(handle: number, lib: Pkcs11); - protected getInfo(): void; - } - - enum ObjectClass { - DATA, - CERTIFICATE, - PUBLIC_KEY, - PRIVATE_KEY, - SECRET_KEY, - HW_FEATURE, - DOMAIN_PARAMETERS, - MECHANISM, - OTP_KEY, - } - - class SessionObject extends HandleObject { - /** - * Session - */ - session: Session; - /** - * gets the size of an object in bytes - */ - size: number; - constructor(object: SessionObject); - constructor(handle: number, session: Session, lib: Pkcs11); - /** - * copies an object, creating a new object for the copy - * @param {ITemplate} template template for the new object - */ - copy(template: ITemplate): SessionObject; - /** - * destroys an object - */ - destroy(): void; - getAttribute(attr: string): ITemplate; - getAttribute(attrs: ITemplate): ITemplate; - setAttribute(attrs: string, value: any): any; - setAttribute(attrs: ITemplate): any; - protected get(name: string): any; - protected set(name: string, value: any): void; - class: ObjectClass; - toType(): T; - } - - class SessionObjectCollection extends Collection { - session: Session; - items(index: number): SessionObject; - constructor(items: Array, session: Session, lib: Pkcs11, classType?: any); - } - - /** - * Private key objects (object class `CKO_PRIVATE_KEY`) hold private keys - */ - class PrivateKey extends Key { - /** - * DER-encoding of the key subject name (default empty) - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - */ - subject: Buffer; - /** - * `CK_TRUE` if key is sensitive - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Attribute cannot be changed once set to CK_TRUE. It becomes a read only attribute. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - sensitive: boolean; - /** - * `CK_TRUE` if key supports decryption - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - decrypt: boolean; - /** - * `CK_TRUE` if key supports signatures where the signature is an appendix to the data - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - sign: boolean; - /** - * `CK_TRUE` if key supports signatures where the data can be recovered from the signature - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - signRecover: boolean; - /** - * `CK_TRUE` if key supports unwrapping (i.e., can be used to unwrap other keys) - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - unwrap: boolean; - /** - * `CK_TRUE` if key is extractable and can be wrapped - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Attribute cannot be changed once set to `CK_FALSE`. It becomes a read only attribute. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - extractable: boolean; - /** - * `CK_TRUE` if key has always had the `CKA_SENSITIVE` attribute set to `CK_TRUE` - * - Must not be specified when object is created with `C_CreateObject`. - * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. - * - Must not be specified when object is unwrapped with `C_UnwrapKey`. - */ - alwaysSensitive: boolean; - /** - * `CK_TRUE` if key has never had the `CKA_EXTRACTABLE` attribute set to `CK_TRUE` - * - Must not be specified when object is created with `C_CreateObject`. - * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. - * - Must not be specified when object is unwrapped with `C_UnwrapKey`. - */ - neverExtractable: boolean; - /** - * `CK_TRUE` if the key can only be wrapped with a wrapping key - * that has `CKA_TRUSTED` set to `CK_TRUE`. Default is `CK_FALSE`. - * - Attribute cannot be changed once set to `CK_TRUE`. It becomes a read only attribute. - */ - wrapTrusted: boolean; - /** - * For wrapping keys. The attribute template to apply to any keys unwrapped - * using this wrapping key. Any user supplied template is applied after this template - * as if the object has already been created. - */ - template: void; - alwaysAuthenticate: boolean; - } - - /** - * Public key objects (object class CKO_PUBLIC_KEY) hold public keys - */ - class PublicKey extends Key { - /** - * DER-encoding of the key subject name (default empty) - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - */ - subject: Buffer; - /** - * `CK_TRUE` if key supports encryption - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - encrypt: boolean; - /** - * `CK_TRUE` if key supports verification where the signature is an appendix to the data - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - verify: boolean; - /** - * `CK_TRUE` if key supports verification where the data is recovered from the signature - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - verifyRecover: boolean; - /** - * `CK_TRUE` if key supports wrapping (i.e., can be used to wrap other keys) - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - wrap: boolean; - /** - * The key can be trusted for the application that it was created. - * - The wrapping key can be used to wrap keys with `CKA_WRAP_WITH_TRUSTED` set to `CK_TRUE`. - * - Can only be set to CK_TRUE by the SO user. - */ - trusted: boolean; - /** - * For wrapping keys. The attribute template to match against any keys wrapped using this wrapping key. - * Keys that do not match cannot be wrapped. - */ - template: void; - } - - /** - * Secret key objects (object class `CKO_SECRET_KEY`) hold secret keys. - */ - class SecretKey extends Key { - /** - * `CK_TRUE` if key is sensitive - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Attribute cannot be changed once set to `CK_TRUE`. It becomes a read only attribute. - */ - sensitive: boolean; - /** - * `CK_TRUE` if key supports encryption - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - encrypt: boolean; - /** - * `CK_TRUE` if key supports decryption - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - decrypt: boolean; - /** - * `CK_TRUE` if key supports verification (i.e., of authentication codes) where the signature is an appendix to the data - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - verify: boolean; - /** - * `CK_TRUE` if key supports signatures (i.e., authentication codes) where the signature is an appendix to the data - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - sign: boolean; - /** - * `CK_TRUE` if key supports wrapping (i.e., can be used to wrap other keys) - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - wrap: boolean; - /** - * `CK_TRUE` if key supports unwrapping (i.e., can be used to unwrap other keys) - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - unwrap: boolean; - /** - * `CK_TRUE` if key is extractable and can be wrapped - * - May be modified after object is created with a `C_SetAttributeValue` call, - * or in the process of copying object with a `C_CopyObject` call. - * However, it is possible that a particular token may not permit modification of the attribute - * during the course of a `C_CopyObject` call. - * - Attribute cannot be changed once set to `CK_FALSE`. It becomes a read only attribute. - * - Default value is token-specific, and may depend on the values of other attributes. - */ - extractable: boolean; - /** - * `CK_TRUE` if key has always had the `CKA_SENSITIVE` attribute set to `CK_TRUE` - * - Must not be specified when object is created with `C_CreateObject`. - * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. - * - Must not be specified when object is unwrapped with `C_UnwrapKey`. - */ - alwaysSensitive: boolean; - /** - * `CK_TRUE` if key has never had the `CKA_EXTRACTABLE` attribute set to `CK_TRUE` - * - Must not be specified when object is created with `C_CreateObject`. - * - Must not be specified when object is generated with `C_GenerateKey` or `C_GenerateKeyPair`. - * - Must not be specified when object is unwrapped with `C_UnwrapKey`. - */ - neverExtractable: boolean; - /** - * Key checksum - */ - checkValue: Buffer; - /** - * `CK_TRUE` if the key can only be wrapped with a wrapping key - * that has `CKA_TRUSTED` set to `CK_TRUE`. Default is `CK_FALSE`. - * - Attribute cannot be changed once set to `CK_TRUE`. It becomes a read only attribute. - */ - wrapTrusted: boolean; - /** - * The wrapping key can be used to wrap keys with `CKA_WRAP_WITH_TRUSTED` set to `CK_TRUE`. - * - Can only be set to CK_TRUE by the SO user. - */ - trusted: boolean; - /** - * For wrapping keys. - * The attribute template to match against any keys wrapped using this wrapping key. - * Keys that do not match cannot be wrapped. - */ - wrapTemplate: void; - /** - * For wrapping keys. - * The attribute template to apply to any keys unwrapped using this wrapping key. - * Any user supplied template is applied after this template as if the object has already been created. - */ - unwrapTemplate: void; - } - - - interface ISlotInfo { - slotDescription: string; - manufacturerID: string; - flags: number; - hardwareVersion: IVersion; - firmwareVersion: IVersion; + static toPkcs11(tmpl: ITemplate): pkcs11.Attribute[]; + static fromPkcs11(tmpl: pkcs11.Template): ITemplate; } enum SlotFlag { @@ -2108,203 +2049,67 @@ declare module "graphene-pk11" { */ HW_SLOT, } + class Slot extends HandleObject { - interface IVersion { - major: number; - minor: number; - } - interface IModuleInfo { - cryptokiVersion: IVersion; + slotDescription: string; manufacturerID: string; flags: number; - libraryDescription: string; - libraryVersion: IVersion; - } + hardwareVersion: pkcs11.Version; + firmwareVersion: pkcs11.Version; + module: Module; - class Collection { - protected items_: Array; - protected classType: any; - protected lib: Pkcs11; - constructor(items: Array, lib: Pkcs11, classType: any); - /** - * returns length of collection - */ - length: number; - /** - * returns item from collection by index - * @param {number} index of element in collection `[0..n]` - */ - items(index: number): T; - } + constructor(handle: Handle, module: Module, lib: pkcs11.PKCS11); - enum SessionOpenFlag { /** - * session is r/w + * Recieve information about Slot + * + * @protected */ - RW_SESSION, - /** - * no parallel - */ - SERIAL_SESSION, - } - enum SessionFlag { - /** - * `True` if the session is read/write; `false` if the session is read-only - */ - RW_SESSION, - /** - * This flag is provided for backward compatibility, and should always be set to `true` - */ - SERIAL_SESSION, - } - enum UserType { - /** - * Security Officer - */ - SO, - /** - * User - */ - USER, - /** - * Context specific - */ - CONTEXT_SPECIFIC, - } - interface IKeyPair { - privateKey: PrivateKey; - publicKey: PublicKey; - } - /** - * provides information about a session - */ - class Session extends HandleObject { - constructor(handle: number, slot: Slot, lib: Pkcs11); - slot: Slot; - /** - * the state of the session - */ - state: number; - /** - * bit flags that define the type of session - */ - flags: number; - /** - * an error code defined by the cryptographic device. Used for errors not covered by Cryptoki - */ - deviceError: number; protected getInfo(): void; + /** - * closes a session between an application and a token + * Returns information about token + * + * @returns {Token} */ - close(): void; + getToken(): Token; /** - * initializes the normal user's PIN - * @param {string} pin the normal user's PIN + * returns list of `MechanismInfo` + * + * @returns {MechanismCollection} */ - initPin(pin: string): void; + getMechanisms(): MechanismCollection; /** - * modifies the PIN of the user who is logged in - * @param {string} oldPin - * @param {string} newPin + * initializes a token + * + * @param {string} pin the SO's initial PIN + * @returns {string} */ - setPin(oldPin: string, newPin: string): void; + initToken(pin: string): string; /** - * obtains a copy of the cryptographic operations state of a session, encoded as a string of bytes + * opens a session between an application and a token in a particular slot + * + * @param {SessionFlag} [flags=session.SessionFlag.SERIAL_SESSION] indicates the type of session + * @returns {Session} */ - getOperationState(): Buffer; + open(flags?: SessionFlag): Session; /** - * restores the cryptographic operations state of a session - * from a string of bytes obtained with getOperationState - * @param {Buffer} state the saved state - * @param {number} encryptionKey holds key which will be used for an ongoing encryption - * or decryption operation in the restored session - * (or 0 if no encryption or decryption key is needed, - * either because no such operation is ongoing in the stored session - * or because all the necessary key information is present in the saved state) - * @param {number} authenticationKey holds a handle to the key which will be used for an ongoing signature, - * MACing, or verification operation in the restored session - * (or 0 if no such key is needed, either because no such operation is ongoing in the stored session - * or because all the necessary key information is present in the saved state) + * closes all sessions an application has with a token */ - setOperationState(state: Buffer, encryptionKey?: number, authenticationKey?: number): void; - /** - * logs a user into a token - * @param {string} pin the user's PIN. - * - This standard allows PIN values to contain any valid `UTF8` character, - * but the token may impose subset restrictions - * @param {} userType the user type. Default is `USER` - */ - login(pin: string, userType?: UserType): void; - /** - * logs a user out from a token - */ - logout(): void; - /** - * creates a new object - * - Only session objects can be created during a read-only session. - * - Only public objects can be created unless the normal user is logged in. - * @param {ITemplate} template the object's template - */ - create(template: ITemplate): SessionObject; - /** - * removes all session objects matched to template - * - if template is null, removes all session objects - * - returns a number of destroied session objects - * @param {ITemplate} template template - */ - destroy(template: ITemplate): number; - /** - * @param {SessionObject} object - */ - destroy(object: SessionObject): number; - destroy(): number; - /** - * removes all session objects - * - returns a number of destroied session objects - */ - clear(): number; - /** - * returns a collection of session objects mached to template - * @param template template - * @param callback optional callback function wich is called for each founded object - * - if callback function returns false, it breaks find function. - */ - find(callback?: (obj: SessionObject) => void): SessionObjectCollection; - find(template: ITemplate, callback?: (obj: SessionObject) => void): SessionObjectCollection; - /** - * Returns object from session by handle - * @param {number} handle handle of object - * @returns T - */ - getObject(handle: number): T; - /** - * generates a secret key or set of domain parameters, creating a new object. - * @param mechanism generation mechanism - * @param template template for the new key or set of domain parameters - */ - generateKey(mechanism: MechanismType, template?: ITemplate): SecretKey; - generateKey(mechanism: MechanismType, template: ITemplate, callback: (err: Error, key: SecretKey) => void): void; - generateKeyPair(mechanism: MechanismType, publicTemplate: ITemplate, privateTemplate: ITemplate): IKeyPair; - createSign(alg: MechanismType, key: Key): Sign; - createVerify(alg: MechanismType, key: Key): Verify; - createCipher(alg: MechanismType, key: Key): Cipher; - createDecipher(alg: MechanismType, key: Key): Decipher; - createDigest(alg: MechanismType): Digest; - wrapKey(alg: MechanismType, wrappingKey: Key, key: Key): Buffer; - unwrapKey(alg: MechanismType, unwrappingKey: Key, wrappedKey: Buffer, template: ITemplate): Key; - /** - * derives a key from a base key, creating a new key object - * @param {MechanismType} alg key deriv. mech - * @param {Key} baseKey base key - * @param {ITemplate} template new key template - */ - deriveKey(alg: MechanismType, baseKey: Key, template: ITemplate): SecretKey; - /** - * generates random data - * @param {number} size \# of bytes to generate - */ - generateRandom(size: number): Buffer; + closeAll(): void; + } + + /** + * Collection of slots + * + * @export + * @class SlotCollection + * @extends {core.Collection} + */ + class SlotCollection extends Collection { + module: Module; + items(index: number): Slot; + constructor(items: Array, module: Module, lib: pkcs11.PKCS11, classType?: any); } enum TokenFlag { @@ -2327,6 +2132,7 @@ declare module "graphene-pk11" { SO_PIN_LOCKED, SO_PIN_TO_BE_CHANGED, } + class Token extends HandleObject { /** * application-defined label, assigned during token initialization. @@ -2400,64 +2206,29 @@ declare module "graphene-pk11" { /** * version number of hardware */ - hardwareVersion: IVersion; + hardwareVersion: pkcs11.Version; /** * version number of firmware */ - firmwareVersion: IVersion; + firmwareVersion: pkcs11.Version; /** * current time as a character-string of length 16, * represented in the format YYYYMMDDhhmmssxx */ utcTime: Date; - constructor(handle: number, lib: Pkcs11); + + constructor(handle: Handle, lib: pkcs11.PKCS11); + protected getInfo(): void; } - class Slot extends HandleObject implements ISlotInfo { - slotDescription: string; - manufacturerID: string; - flags: number; - hardwareVersion: IVersion; - firmwareVersion: IVersion; - module: Module; - constructor(handle: number, module: Module, lib: Pkcs11); - protected getInfo(): void; - getToken(): Token; - /** - * returns list of `MechanismInfo` - */ - getMechanisms(): MechanismCollection; - /** - * initializes a token - * @param {string} pin the SO's initial PIN - * @param {string} label label of the token - */ - initToken(pin: string, label: string): void; - /** - * opens a session between an application and a token in a particular slot - * @parsm flags indicates the type of session - */ - open(flags?: number): Session; - /** - * closes all sessions an application has with a token - */ - closeAll(): void; - } - - class SlotCollection extends Collection { - module: Module; - items(index: number): Slot; - constructor(items: Array, module: Module, lib: Pkcs11, classType?: any); - } - - class Module extends BaseObject implements IModuleInfo { + class Module extends BaseObject { libFile: string; libName: string; /** * Cryptoki interface version */ - cryptokiVersion: IVersion; + cryptokiVersion: pkcs11.Version; /** * blank padded manufacturer ID */ @@ -2473,8 +2244,8 @@ declare module "graphene-pk11" { /** * version of library */ - libraryVersion: IVersion; - constructor(lib: Pkcs11); + libraryVersion: pkcs11.Version; + constructor(lib: pkcs11.PKCS11); protected getInfo(): void; /** * initializes the Cryptoki library @@ -2496,224 +2267,11 @@ declare module "graphene-pk11" { getSlots(tokenPresent?: boolean): SlotCollection; /** * loads pkcs11 lib + * @param libFile path to PKCS11 library + * @param libName name of PKCS11 library */ static load(libFile: string, libName?: string): Module; } - class Cipher { - session: Session; - lib: Pkcs11; - constructor(session: Session, alg: MechanismType, key: Key, lib: Pkcs11); - protected init(alg: MechanismType, key: Key): void; - update(text: string): Buffer; - update(data: Buffer): Buffer; - final(): Buffer; - } - class Decipher { - session: Session; - lib: Pkcs11; - constructor(session: Session, alg: MechanismType, key: Key, lib: Pkcs11); - protected init(alg: MechanismType, key: Key): void; - update(text: string): Buffer; - update(data: Buffer): Buffer; - final(): Buffer; - } - - class Digest { - session: Session; - lib: Pkcs11; - constructor(session: Session, alg: MechanismType, lib: Pkcs11); - protected init(alg: MechanismType): void; - update(text: string): void; - update(data: Buffer): void; - final(): Buffer; - } - - class Sign { - session: Session; - lib: Pkcs11; - constructor(session: Session, alg: MechanismType, key: Key, lib: Pkcs11); - protected init(alg: MechanismType, key: Key): void; - update(text: string): void; - update(data: Buffer): void; - final(): Buffer; - } - - class Verify { - session: Session; - lib: Pkcs11; - constructor(session: Session, alg: MechanismType, key: Key, lib: Pkcs11); - protected init(alg: MechanismType, key: Key): void; - update(text: string): void; - update(data: Buffer): void; - final(signature: Buffer): boolean; - } - - /** - * - * EC - * - */ - - /** - * EcKdf is used to indicate the Key Derivation Function (KDF) - * applied to derive keying data from a shared secret. - * The key derivation function will be used by the EC key agreement schemes. - */ - enum EcKdf { - NULL, - SHA1, - SHA224, - SHA256, - SHA384, - SHA512, - } - - class EcdhParams implements IParams { - /** - * key derivation function used on the shared secret value - */ - kdf: EcKdf; - /** - * some data shared between the two parties - */ - sharedData: Buffer; - /** - * other party's EC public key value - */ - publicData: Buffer; - /** - * @param {EcKdf} kdf key derivation function used on the shared secret value - * @param {Buffer=null} sharedData some data shared between the two parties - * @param {Buffer=null} publicData other party's EC public key value - */ - constructor(kdf: EcKdf, sharedData?: Buffer, publicData?: Buffer); - toCKI(): Buffer; - } - - export interface INamedCurve { - name: string; - oid: string; - value: Buffer; - size: number; - } - - class NamedCurve { - static getByName(name: string): INamedCurve; - static getByOid(oid: string): INamedCurve; - } - - /** - * - * AES - * - */ - - class AesCbcParams implements IParams { - /** - * initialization vector - * - must have a fixed size of 16 bytes - */ - iv: Buffer; - /** - * the data - */ - data: Buffer; - constructor(iv: Buffer, data: Buffer); - toCKI(): Buffer; - } - - class AesCcmParams implements IParams { - /** - * length of the data where 0 <= dataLength < 2^8L - */ - dataLength: number; - /** - * the nonce - */ - nonce: Buffer; - /** - * the additional authentication data - * - This data is authenticated but not encrypted - */ - aad: Buffer; - /** - * length of authentication tag (output following cipher text) in bits. - * - Can be any value between 0 and 128 - */ - macLength: number; - constructor(dataLength: number, nonce: Buffer, aad?: Buffer, macLength?: number); - toCKI(): Buffer; - } - - class AesGcmParams implements IParams { - /** - * initialization vector - * - The length of the initialization vector can be any number between 1 and 256. - * 96-bit (12 byte) IV values can be processed more efficiently, - * so that length is recommended for situations in which efficiency is critical. - */ - iv: Buffer; - /** - * pointer to additional authentication data. - * This data is authenticated but not encrypted. - */ - aad: Buffer; - /** - * length of authentication tag (output following cipher text) in bits. - * Can be any value between 0 and 128. Default 128 - */ - tagBits: number; - constructor(iv: Buffer, aad?: Buffer, tagBits?: number); - toCKI(): Buffer; - } - - /** - * - * RSA - * - */ - - enum RsaMgf { - MGF1_SHA1, - MGF1_SHA224, - MGF1_SHA256, - MGF1_SHA384, - MGF1_SHA512, - } - - class RsaOaepParams implements IParams { - hashAlgorithm: MechanismEnum; - mgf: RsaMgf; - source: number; - sourceData: Buffer; - constructor(hashAlg?: MechanismEnum, mgf?: RsaMgf, sourceData?: Buffer); - toCKI(): Buffer; - } - - class RsaPssParams implements IParams { - /** - * hash algorithm used in the PSS encoding; - * - if the signature mechanism does not include message hashing, - * then this value must be the mechanism used by the application to generate - * the message hash; - * - if the signature mechanism includes hashing, - * then this value must match the hash algorithm indicated - * by the signature mechanism - */ - hashAlgorithm: MechanismEnum; - /** - * mask generation function to use on the encoded block - */ - mgf: RsaMgf; - /** - * length, in bytes, of the salt value used in the PSS encoding; - * - typical values are the length of the message hash and zero - */ - saltLength: number; - constructor(hashAlg?: MechanismEnum, mgf?: RsaMgf, saltLen?: number); - toCKI(): Buffer; - } - -} \ No newline at end of file +} \ No newline at end of file diff --git a/graphlib/graphlib-tests.ts b/graphlib/graphlib-tests.ts new file mode 100644 index 0000000000..ff9268ab0f --- /dev/null +++ b/graphlib/graphlib-tests.ts @@ -0,0 +1,24 @@ +/// + +import * as graphlib from 'graphlib'; + +function test_graph() { + var g = new graphlib.Graph(); + g.setEdge('a', 'b'); + g.setEdge('a', 'b', 1.023); + + g.edge('a', 'b'); + g.edge({v: 'a', w: 'b'}); + + graphlib.json.read(graphlib.json.write(g)); + + graphlib.alg.dijkstra(g, 'a', e => g.edge(e)); + graphlib.alg.dijkstraAll(g, e => g.edge(e)); + graphlib.alg.dijkstraAll(g); + + graphlib.alg.findCycles(g); + graphlib.alg.isAcyclic(g); + graphlib.alg.prim(g, e => g.edge(e)); + graphlib.alg.tarjan(g); + graphlib.alg.topsort(g); +} diff --git a/graphlib/graphlib.d.ts b/graphlib/graphlib.d.ts new file mode 100644 index 0000000000..1f017d5383 --- /dev/null +++ b/graphlib/graphlib.d.ts @@ -0,0 +1,291 @@ +// Type definitions for graphlib 2.1.1 +// Project: https://github.com/cpettitt/graphlib +// Definitions by: Dan Vanderkam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare module "graphlib" { + export interface GraphOptions { + directed?: boolean; // default: true. + multigraph?: boolean; // default: false. + compound?: boolean; // default: false. + } + + export interface Edge { + v: string; + w: string; + /** The name that uniquely identifies a multi-edge. */ + name?: string; + } + + // TODO: add template parameters for edge and vertex labels? + export class Graph { + constructor(options?: GraphOptions); + + /** + * Creates or updates the value for the node v in the graph. If label is supplied + * it is set as the value for the node. If label is not supplied and the node was + * created by this call then the default node label will be assigned. Returns the + * graph, allowing this to be chained with other functions. Takes O(1) time. + */ + setNode(name: string, label?: any): Graph; + + hasNode(name: string): boolean; + + /** + * Remove the node with the id v in the graph or do nothing if the node is not in + * the graph. If the node was removed this function also removes any incident + * edges. Returns the graph, allowing this to be chained with other functions. + * Takes O(|E|) time. */ + removeNode(name: string): Graph; + + nodes(): string[]; + + /** Returns the label for this node. */ + node(name: string): any; + + /** + * Creates or updates the label for the edge (v, w) with the optionally supplied + * name. If label is supplied it is set as the value for the edge. If label is not + * supplied and the edge was created by this call then the default edge label will + * be assigned. The name parameter is only useful with multigraphs. Returns the + * graph, allowing this to be chained with other functions. Takes O(1) time. + */ + setEdge(v: string, w: string, label?: any): Graph; + + edges(): Edge[]; + + /** Returns the label for this edge. */ + edge(v: string, w: string): any; + edge(e: Edge): any; + + /** + * Return all edges that point to the node v. Optionally filters those edges down to just those + * coming from node u. Behavior is undefined for undirected graphs - use nodeEdges instead. + * Returns undefined if node v is not in the graph. Takes O(|E|) time. + */ + inEdges(v: string, u?: string): Edge[]; + + /** + * Return all edges that are pointed at by node v. Optionally filters those edges down to just + * those point to w. Behavior is undefined for undirected graphs - use nodeEdges instead. + * Returns undefined if node v is not in the graph. Takes O(|E|) time. + */ + outEdges(v: string, w?: string): Edge[]; + + /** + * Returns all edges to or from node v regardless of direction. Optionally filters those edges + * down to just those between nodes v and w regardless of direction. Returns undefined if node v + * is not in the graph. Takes O(|E|) time. + */ + nodeEdges(v: string, w?: string): Edge[]; + + /** + * Return all nodes that are predecessors of the specified node or undefined if node v is not in + * the graph. Behavior is undefined for undirected graphs - use neighbors instead. Takes O(|V|) + * time. + */ + predecessors(node: string): string[]; + + /** + * Return all nodes that are successors of the specified node or undefined if node v is not in + * the graph. Behavior is undefined for undirected graphs - use neighbors instead. Takes O(|V|) + * time. + */ + successors(node: string): string[]; + + /** + * Return all nodes that are predecessors or successors of the specified node or undefined if + * node v is not in the graph. Takes O(|V|) time. + */ + neighbors(node: string): string[]; + + isDirected(): boolean; + isMultigraph(): boolean; + isCompound(): boolean; + + /** Sets the label for the graph to label. */ + setGraph(label: string): void; + + /** + * Returns the currently assigned label for the graph. If no label has been assigned, + * returns undefined. + */ + graph(): string; + + /** + * Returns the number of nodes in the graph. + */ + nodeCount(): number; + + /** + * Returns the number of edges in the graph. + */ + edgeCount(): number; + + /** Returns those nodes in the graph that have no in-edges. Takes O(|V|) time. */ + sources(): string[]; + + /** Returns those nodes in the graph that have no out-edges. Takes O(|V|) time. */ + sinks(): string[]; + } + + export namespace json { + /** + * Creates a JSONrepresentation of the graph that can be serialized to a string with + * JSON.stringify. The graph can later be restored using json.read. + */ + function write(g: Graph): Object; + + /** + * Takes JSON as input and returns the graph representation. For example, if we have + * serialized the graph in json-write to a string named str, we can restore it to a + * graph as follows: + * + * var g2 = graphlib.json.read(JSON.parse(str)); + * g2.nodes(); + * // ['a', 'b'] + * g2.edges() + * // [ { v: 'a', w: 'b' } ] + */ + function read(json: Object): Graph; + } + + export interface Path { + distance: number; + predecessor: string; + } + + export namespace alg { + /** + * Finds all connected components in a graph and returns an array of these components. + * Each component is itself an array that contains the ids of nodes in the component. + * This function takes O(|V|) time. + */ + function components(g: Graph): string[][]; + + /** + * This function is an implementation of Dijkstra's algorithm which finds the shortest + * path from source to all other nodes in g. This function returns a map of + * v -> { distance, predecessor }. The distance property holds the sum of the weights + * from source to v along the shortest path or Number.POSITIVE_INFINITY if there is no path + * from source. The predecessor property can be used to walk the individual elements of the + * path from source to v in reverse order. + * + * It takes an optional weightFn(e) which returns the weight of the edge e. If no weightFn + * is supplied then each edge is assumed to have a weight of 1. This function throws an + * Error if any of the traversed edges have a negative edge weight. + * + * It takes an optional edgeFn(v) which returns the ids of all edges incident to the node v + * for the purposes of shortest path traversal. By default this function uses the g.outEdges. + * + * It takes O((|E| + |V|) * log |V|) time. + */ + function dijkstra( + graph: Graph, + source: string, + weightFn?: (e: Edge) => number, + edgeFn?: (v: string) => Edge[] + ): {[node: string]: Path}; + + /** + * This function finds the shortest path from each node to every other reachable node in + * the graph. It is similar to alg.dijkstra, but instead of returning a single-source + * array, it returns a mapping of of source -> alg.dijksta(g, source, weightFn, edgeFn). + * + * This function takes an optional weightFn(e) which returns the weight of the edge e. + * If no weightFn is supplied then each edge is assumed to have a weight of 1. This + * function throws an Error if any of the traversed edges have a negative edge weight. + * + * This function takes an optional edgeFn(u) which returns the ids of all edges incident + * to the node u for the purposes of shortest path traversal. By default this function + * uses g.outEdges. + * + * This function takes O(|V| * (|E| + |V|) * log |V|) time. + */ + function dijkstraAll( + graph: Graph, + weightFn?: (e: Edge) => number, + edgeFn?: (v: string) => Edge[] + ): {[source: string]: {[node: string]: Path}}; + + /** + * Given a Graph, g, this function returns all nodes that are part of a cycle. As there + * may be more than one cycle in a graph this function return an array of these cycles, + * where each cycle is itself represented by an array of ids for each node involved in + * that cycle. + * + * alg.isAcyclic is more efficient if you only need to determine whether a graph has a + * cycle or not. + */ + function findCycles(graph: Graph): string[][]; + + /** + * This function is an implementation of the Floyd-Warshall algorithm, which finds the + * shortest path from each node to every other reachable node in the graph. It is similar + * to alg.dijkstraAll, but it handles negative edge weights and is more efficient for some types + * of graphs. This function returns a map of source -> { target -> { distance, predecessor }. + * The distance property holds the sum of the weights from source to target along the shortest + * path of Number.POSITIVE_INFINITY if there is no path from source. The predecessor property + * can be used to walk the individual elements of the path from source to target in reverse + * order. + * + * This function takes an optional weightFn(e) which returns the weight of the edge e. If no + * weightFunc is supplied then each edge is assumed to have a weight of 1. + * + * This function takes an optional edgeFn(v) which returns the ids of all edges incident to the + * node v for the purposes of shortest path traversal. By default this function uses the + * outEdges function on the supplied graph. + * + * This algorithm takes O(|V|^3) time. + */ + function floydWarshall( + graph: Graph, + weightFn?: (e: Edge) => number, + edgeFn?: (v: string) => Edge[] + ): {[source: string]: {[node: string]: Path}}; + + /** + * Given a Graph, g, this function returns true if the graph has no cycles and returns false if it + * does. This algorithm returns as soon as it detects the first cycle. You can use alg.findCycles + * to get the actual list of cycles in the graph. + */ + function isAcyclic(graph: Graph): boolean; + + /** + * Prim's algorithm takes a connected undirected graph and generates a minimum spanning tree. This + * function returns the minimum spanning tree as an undirected graph. This algorithm is derived + * from the description in "Introduction to Algorithms", Third Edition, Cormen, et al., Pg 634. + * + * This function takes a weightFn(e) which returns the weight of the edge e. It throws an Error if + * the graph is not connected. + * + * This function takes O(|E| log |V|) time. + */ + function prim(graph: Graph, weightFn: (e: Edge) => number): Graph; + + /** + * This function is an implementation of Tarjan's algorithm which finds all strongly connected + * components in the directed graph g. Each strongly connected component is composed of nodes that + * can reach all other nodes in the component via directed edges. A strongly connected component + * can consist of a single node if that node cannot both reach and be reached by any other + * specific node in the graph. Components of more than one node are guaranteed to have at least + * one cycle. + * + * This function returns an array of components. Each component is itself an array that contains + * the ids of all nodes in the component. + */ + function tarjan(graph: Graph): string[][]; + + /** + * An implementation of topological sorting. + * + * Given a Graph g this function returns an array of nodes such that for each edge u -> v, u + * appears before v in the array. If the graph has a cycle it is impossible to generate such a + * list and CycleException is thrown. + * + * Takes O(|V| + |E|) time. + */ + function topsort(graph: Graph): string[]; + } +} diff --git a/grecaptcha/grecaptcha-tests.ts b/grecaptcha/grecaptcha-tests.ts index cfc86e71b6..b252efb04d 100644 --- a/grecaptcha/grecaptcha-tests.ts +++ b/grecaptcha/grecaptcha-tests.ts @@ -2,8 +2,9 @@ var params: ReCaptchaV2.Parameters = { "sitekey": "mySuperSecretKey", - "theme": "black", // no type-checking here. + "theme": "light", "type": "image", + "size": "normal", "tabindex": 5, "callback": (response: string) => { }, "expired-callback": () => { }, diff --git a/grecaptcha/grecaptcha.d.ts b/grecaptcha/grecaptcha.d.ts index 8e3b744d53..c8f165a8f8 100644 --- a/grecaptcha/grecaptcha.d.ts +++ b/grecaptcha/grecaptcha.d.ts @@ -29,6 +29,10 @@ declare namespace ReCaptchaV2 getResponse(opt_widget_id?: number): string; } + type Theme = "light" | "dark"; + type Type = "image" | "audio"; + type Size = "normal" | "compact"; + interface Parameters { /** @@ -39,14 +43,23 @@ declare namespace ReCaptchaV2 * Optional. The color theme of the widget. * Accepted values: "light", "dark" * @default "light" + * @type {Theme} **/ - theme?: string; + theme?: Theme; /** * Optional. The type of CAPTCHA to serve. - * Accepted values: "audio ", "image" + * Accepted values: "audio", "image" * @default "image" + * @type {Type} **/ - type?: string; + type?: Type; + /** + * Optional. The size of the widget. + * Accepted values: "compact", "normal" + * @default "compact" + * @type {Size} + */ + size?: Size; /** * Optional. The tabindex of the widget and challenge. * If other elements in your page use tabindex, it should be set to make user navigation easier. diff --git a/gulp-angular-templatecache/gulp-angular-templatecache-tests.ts b/gulp-angular-templatecache/gulp-angular-templatecache-tests.ts new file mode 100644 index 0000000000..fd7a053ce6 --- /dev/null +++ b/gulp-angular-templatecache/gulp-angular-templatecache-tests.ts @@ -0,0 +1,36 @@ +/// +/// + +import * as gulp from 'gulp'; +import * as templateCache from 'gulp-angular-templatecache'; + +gulp.task('templatecache:no-arguments', function () { + return gulp.src('templates/**/*.html') + .pipe(templateCache()) + .pipe(gulp.dest('public')); +}); + +gulp.task('templatecache:with-filename', function () { + return gulp.src('templates/**/*.html') + .pipe(templateCache('templates.js')) + .pipe(gulp.dest('public')); +}); + +gulp.task('templatecache:with-options', function () { + return gulp.src('templates/**/*.html') + .pipe(templateCache({ + filename: 'templates.js', + standalone: true, + module: 'app.templates' + })) + .pipe(gulp.dest('public')); +}); + +gulp.task('templatecache:with-filename-and-options', function () { + return gulp.src('templates/**/*.html') + .pipe(templateCache('templates.js', { + standalone: true, + module: 'app.templates' + })) + .pipe(gulp.dest('public')); +}); \ No newline at end of file diff --git a/gulp-angular-templatecache/gulp-angular-templatecache.d.ts b/gulp-angular-templatecache/gulp-angular-templatecache.d.ts new file mode 100644 index 0000000000..34e52acc36 --- /dev/null +++ b/gulp-angular-templatecache/gulp-angular-templatecache.d.ts @@ -0,0 +1,69 @@ +// Type definitions for gulp-angular-templatecache v2.0.0 +// Project: https://github.com/miickel/gulp-angular-templatecache +// Definitions by: Aman Mahajan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "gulp-angular-templatecache" { + function templatecache(): NodeJS.ReadWriteStream; + function templatecache(filename: string): NodeJS.ReadWriteStream; + function templatecache(options: templatecache.Options): NodeJS.ReadWriteStream; + function templatecache(filename: string, options: templatecache.Options): NodeJS.ReadWriteStream; + + namespace templatecache { + interface Options { + /** + * Name to use when concatenating. + */ + filename?: string; + + /** + * Prefix for template URLs. + */ + root?: string; + + /** + * Name of AngularJS module. + */ + module?: string; + + /** + * Create a new AngularJS module, instead of using an existing. + */ + standalone?: boolean; + + /** + * Override file base path. + */ + base?: string | Function; + + /** + * Wrap the templateCache in a module system. Currently supported systems: RequireJS, Browserify, ES6 and IIFE (Immediately-Invoked Function Expression). + */ + moduleSystem?: string; + + /** + * Transform the generated URL before it's put into $templateCache. + */ + transformUrl?: Function; + + /** + * Override template header. + */ + templateHeader?: string; + + /** + * Override template body. + */ + templateBody?: string; + + /** + * Override template footer. + */ + templateFooter?: string; + } + } + + export = templatecache; +} \ No newline at end of file diff --git a/gulp-help-doc/gulp-help-doc-tests.ts b/gulp-help-doc/gulp-help-doc-tests.ts new file mode 100644 index 0000000000..f06c25e55c --- /dev/null +++ b/gulp-help-doc/gulp-help-doc-tests.ts @@ -0,0 +1,27 @@ +/// +/// +/// + +import gulp = require('gulp'); +import usage = require('gulp-help-doc'); + +/** + * Demo task + * + * @task {demo} + * @arg {env} environment + */ +gulp.task('demo', function() {}); + +let logger: { + output: string, + log(msg: string): any +} = { + output: '', + log: msg => logger.output += msg + '\n' +}; + +usage(gulp, { + logger: logger, + gulpfile: __filename +}).then(() => console.log(logger.output)); diff --git a/gulp-help-doc/gulp-help-doc.d.ts b/gulp-help-doc/gulp-help-doc.d.ts new file mode 100644 index 0000000000..80d4922774 --- /dev/null +++ b/gulp-help-doc/gulp-help-doc.d.ts @@ -0,0 +1,56 @@ +// Type definitions for gulp-help-doc +// Project: https://github.com/Mikhus/gulp-help-doc +// Definitions by: Mikhus +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module "gulp-help-doc" { + + import gulp = require('gulp'); + + namespace usage { + + interface UsageOptions { + /** + * Defines max line width for the printed output lines + * (by default is 80 characters long) + */ + lineWidth?: number, + + /** + * Defines max width of the column width tasks or args names + * (by default is 20 characters long) + */ + keysColumnWidth?: number, + + /** + * Defines number of empty characters for left-padding of the output + */ + padding?: number, + + /** + * Printing engine (by default is console). Accepted any device + * which has log() function defined to do output. + */ + logger?: { log: Function }, + + /** + * Path to a gulpfile (default is gulpfile.js) + * Normally, there is no need to change this option. It may be used + * for some special cases, like mocking gulpfile for testing. + */ + gulpfile?: string + } + + interface Usage { + (gulp: gulp.Gulp, options?: UsageOptions): Promise + } + + } + + var usage: usage.Usage; + + export = usage; +} diff --git a/gulp-insert/gulp-insert-tests.ts b/gulp-insert/gulp-insert-tests.ts new file mode 100644 index 0000000000..e420cf5e4a --- /dev/null +++ b/gulp-insert/gulp-insert-tests.ts @@ -0,0 +1,21 @@ +/// +/// + +import * as gulp from 'gulp'; +import * as insert from 'gulp-insert'; + +gulp.task('gulp-insert-tests', () => { + return gulp.src('*.js') + .pipe(insert.prepend('/* Inserted using gulp-insert prepend method */\n')) + .pipe(insert.prepend('\n/* Inserted using gulp-insert append method */')) + .pipe(insert.wrap( + '/* Inserted using gulp-insert wrap method */\n', + '\n/* Inserted using gulp-insert wrap method */' + )) + .pipe(insert.transform((contents, file) => { + var comment = '/* Local file: ' + file.path + ' */\n'; + return comment + contents; + })) + .pipe(gulp.dest('gulp-insert')); +}); + diff --git a/gulp-insert/gulp-insert.d.ts b/gulp-insert/gulp-insert.d.ts new file mode 100644 index 0000000000..9777280d5b --- /dev/null +++ b/gulp-insert/gulp-insert.d.ts @@ -0,0 +1,52 @@ +// Type definitions for gulp-insert 0.5.0 +// Project: https://github.com/rschmukler/gulp-insert +// Definitions by: Shant Marouti +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module 'gulp-insert' { + + import File = require('vinyl'); + + interface Transformer { + (contents: string, file: File): string + } + + namespace Insert { + + /** + * Prepends a string onto the contents + * @param {string} content + * @returns {NodeJS.ReadWriteStream} + */ + function prepend(content: string): NodeJS.ReadWriteStream; + + /** + * Appends a string onto the contents + * @param {string} content + * @returns {NodeJS.ReadWriteStream} + */ + function append(content: string): NodeJS.ReadWriteStream; + + /** + * Wraps the contents with two strings + * @param {string} prepend + * @param {string} append + * @returns {NodeJS.ReadWriteStream} + */ + function wrap(prepend: string, append: string): NodeJS.ReadWriteStream; + + /** + * Calls a function with the contents of the file + * @param {Transformer} transformer + * @returns {NodeJS.ReadWriteStream} + */ + function transform(transformer: Transformer): NodeJS.ReadWriteStream; + + } + + module Insert { } + export = Insert; +} \ No newline at end of file diff --git a/gulp-rename/gulp-rename-tests.ts b/gulp-rename/gulp-rename-tests.ts index 6b204a36d9..b27f0f5ba9 100644 --- a/gulp-rename/gulp-rename-tests.ts +++ b/gulp-rename/gulp-rename-tests.ts @@ -3,6 +3,9 @@ import gulp = require("gulp"); import rename = require("gulp-rename"); +// Test that new import syntax works +import * as newRename from 'gulp-rename'; + // rename via string gulp.src("./src/main/text/hello.txt") .pipe(rename("main/text/ciao/goodbye.md")) @@ -26,4 +29,4 @@ gulp.src("./src/main/text/hello.txt", { base: process.cwd() }) suffix: "-hola", extname: ".md" })) - .pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/bonjour-aloha-hola.md \ No newline at end of file + .pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/bonjour-aloha-hola.md diff --git a/gulp-rename/gulp-rename.d.ts b/gulp-rename/gulp-rename.d.ts index 11368e9698..4c68aecde7 100644 --- a/gulp-rename/gulp-rename.d.ts +++ b/gulp-rename/gulp-rename.d.ts @@ -20,5 +20,12 @@ declare module "gulp-rename" { function rename(name: string): NodeJS.ReadWriteStream; function rename(callback: (path: ParsedPath) => any): NodeJS.ReadWriteStream; function rename(opts: Options): NodeJS.ReadWriteStream; + + /** + * This is required as per: + * https://github.com/Microsoft/TypeScript/issues/5073 + */ + namespace rename {} + export = rename; -} \ No newline at end of file +} diff --git a/gulp-uglify/gulp-uglify-tests.ts b/gulp-uglify/gulp-uglify-tests.ts index 01cfb06f9e..6a1cf1281d 100644 --- a/gulp-uglify/gulp-uglify-tests.ts +++ b/gulp-uglify/gulp-uglify-tests.ts @@ -14,7 +14,7 @@ gulp.task('compress2', function() { var tsResult = gulp.src('lib/*.ts') .pipe(uglify({ mangle: false, - preserverComments: "some", + preserveComments: "some", compress: false, output: { max_line_len: 300 diff --git a/gulp-uglify/gulp-uglify.d.ts b/gulp-uglify/gulp-uglify.d.ts index 13eda63706..60cd8f11ea 100644 --- a/gulp-uglify/gulp-uglify.d.ts +++ b/gulp-uglify/gulp-uglify.d.ts @@ -32,7 +32,7 @@ declare module "gulp-uglify" { * some - Preserve comments that start with a bang (!) or include a Closure Compiler directive (@preserve, @license, @cc_on) * function - Specify your own comment preservation function. You will be passed the current node and the current comment and are expected to return either true or false. */ - preserverComments?: string|((node: any, comment: UglifyJS.Tokenizer) => boolean); + preserveComments?: string|((node: any, comment: UglifyJS.Tokenizer) => boolean); } } diff --git a/gulp/gulp.d.ts b/gulp/gulp.d.ts index 43bb5aa597..f4314bd2f2 100644 --- a/gulp/gulp.d.ts +++ b/gulp/gulp.d.ts @@ -5,9 +5,11 @@ /// /// +/// declare module "gulp" { import Orchestrator = require("orchestrator"); + import VinylFile = require("vinyl"); namespace gulp { interface Gulp extends Orchestrator { @@ -92,7 +94,7 @@ declare module "gulp" { * @param outFolder The path (output folder) to write files to. Or a function that returns it, the function will be provided a vinyl File instance. * @param opt */ - (outFolder: string|((file: string) => string), opt?: DestOptions): NodeJS.ReadWriteStream; + (outFolder: string|((file: VinylFile) => string), opt?: DestOptions): NodeJS.ReadWriteStream; } interface SrcMethod { @@ -150,6 +152,11 @@ declare module "gulp" { */ dot?: boolean; + /** + * Set to match only fles, not directories. Set this flag to prevent copying empty directories + */ + nodir?: boolean; + /** * By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid * filesystem path is returned. Set this flag to disable that behavior. diff --git a/halfred/halfred-tests.ts b/halfred/halfred-tests.ts new file mode 100644 index 0000000000..3aecf39962 --- /dev/null +++ b/halfred/halfred-tests.ts @@ -0,0 +1,13 @@ +/// + +// run test with: $ tsc --noImplicitAny --target es6 --module commonjs halfred-tests.ts +import { parse } from 'halfred'; // require('halfred'); +let resource = parse({foo: "bar", "_links": { "self": { href: "fooo" }}}); +console.log(resource); + +let allLinks = resource.allLinks(); +for (let key in allLinks) { + let link = allLinks[key]; + + console.log(link[0].href); +} diff --git a/halfred/halfred.d.ts b/halfred/halfred.d.ts new file mode 100644 index 0000000000..9c1d571a9d --- /dev/null +++ b/halfred/halfred.d.ts @@ -0,0 +1,247 @@ +// Type definitions for Halfred v1.0.0 +// Project: https://github.com/basti1302/halfred +// Definitions by: David Herges +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare module "halfred" { + + /** + * halfred.parse(object) returns a Resource object. + * + * @see https://github.com/basti1302/halfred#usage + */ + export function parse(object: any): Resource; + + /** @see https://github.com/basti1302/halfred#enabledisable-validation */ + export function enableValidation(flag: boolean): void; + + /** @see https://github.com/basti1302/halfred#enabledisable-validation */ + export function disableValidation(): void; + + /** @see https://github.com/basti1302/halfred#resource-api */ + export interface Resource { + + /** + * Returns an object which has an array for each link that was present in the source object. + * See below why each link is represented as an array. + */ + allLinkArrays(): LinkCollection; + + /** Alias for allLinkArrays() */ + allLinks(): LinkCollection; + + /** + * Returns the array of links for the given key, or null if there are no links for this key. + */ + linkArray(key: string): Link[]; + + /** + * Returns the first element of the array of links for the given key or null if there are no + * links for this key. + */ + link(key: string): Link; + + /** + * Returns an object which has an array for each embedded resource that was present in the + * source object. + * See below why each embedded resource is represented as an array. Each element of any of + * this arrays is in turn a Resource object. + */ + allEmbeddedResourceArrays(): ResourceCollection; + + /** Alias for allEmbeddedResourceArrays() */ + allEmbeddedArrays(): ResourceCollection; + + /** Alias for allEmbeddedResourceArrays() */ + allEmbeddedResources(): ResourceCollection; + + /** + * Returns the array of embedded resources for the given key, or null if there are no embedded + * resources for this key. Each element of this arrays is in turn a Resource object. + */ + embeddedResourceArray(key: string): Resource[]; + + /** Alias for embeddedResourceArray() */ + embeddedArray(key: string): Resource[]; + + /** + * Returns the first element of the array of embedded resources for the given key or null if + * there are no embedded resources for this key. The returend object is a Resource object. + */ + embeddedResource(key: string): Resource; + + /** Alias for embeddedResource(key) */ + embedded(key: string): Resource; + + /** + * Returns the unmodified, original object that was parsed to this resource. This is rather + * uninteresting for the source object you give to the parse method (because you probably + * still have a reference to the source object) but it is a convenient way to get the part of + * the source object that corresponds to an embedded resource. + */ + original(): any; + + /** + * Returns true if the resource has any CURIEs (Compact URIs). + * + * @see http://www.w3.org/TR/2010/NOTE-curie-20101216/ + */ + hasCuries(): boolean; + + /** + * Returns the array of CURIEs. Each object in the array is a link object, which means it + * can be templated etc. See below for the link object API. + */ + curieArray(): Link[]; + + /** + * Returns the curie with the given name, if any. The returned object is a link object, which + * means it can be templated etc. See below for link object API. + */ + curie(name: string): Link; + + /** + * Returns the compact URI for the given full URL, if any + */ + reverseResolveCurie(fullUrl: string): string; + + /** + * Returns all validation issues. Validation issues are only gathered if validation has been + * turned on by calling ``halfred.enableValidation()`` before calling ``halfred.parse``. + */ + validationIssues(): any; + + /** + * Alias for validationIssues() + */ + validation(): any; + + /* + XX ... think we should NOT try to represent these things in TypeScript. + + In addition to the methods mentioned here, resource has all properties of the source object. + This is also true for embedded Resource objects. The non-HAL properties (that is, any + property except _links and _embedded) are copied over to the Resource object. This is always + a shallow copy, so modifying the a non-HAL property in the Resource object might also alter + the source object and vice versa. + + The Resource object also has the properties _links and _embedded but they might differ from + the _links/_embedded properties in the source object (Halfred applies some normalization to + them). These are not intended to be accessed by clients directly, instead, use the provided + methods to work with links and embedded resources. + */ + } + + /** @see https://github.com/basti1302/halfred#links-and-embedded-resources */ + interface ResourceCollection { + [key: string]: Resource[]; + } + + /** @see https://github.com/basti1302/halfred#links-and-embedded-resources */ + interface LinkCollection { + [rel: string]: Link[] + } + + /** + * A Link Object represents a hyperlink from the containing resource to a URI. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5 + */ + interface Link { + + /** + * The "href" property is REQUIRED. + * + * Its value is either a URI [RFC3986] or a URI Template [RFC6570]. + * + * If the value is a URI Template then the Link Object SHOULD have a + * "templated" attribute whose value is true. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.1 + */ + href: string; + + /** + * The "templated" property is OPTIONAL. + * + * Its value is boolean and SHOULD be true when the Link Object's "href" + * property is a URI Template. + * + * Its value SHOULD be considered false if it is undefined or any other + * value than true. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.2 + */ + templated?: boolean; + + /** + * The "type" property is OPTIONAL. + * + * Its value is a string used as a hint to indicate the media type + * expected when dereferencing the target resource. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.3 + */ + type?: string; + + /** + * The "deprecation" property is OPTIONAL. + * + * Its presence indicates that the link is to be deprecated (i.e. + * removed) at a future date. Its value is a URL that SHOULD provide + * further information about the deprecation. + * + * A client SHOULD provide some notification (for example, by logging a + * warning message) whenever it traverses over a link that has this + * property. The notification SHOULD include the deprecation property's + * value so that a client manitainer can easily find information about + * the deprecation. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.4 + */ + deprecation?: string; + + /** + * The "name" property is OPTIONAL. + * + * Its value MAY be used as a secondary key for selecting Link Objects + * which share the same relation type. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.5 + */ + name?: string; + + /** + * The "profile" property is OPTIONAL. + * + * Its value is a string which is a URI that hints about the profile (as + * defined by [I-D.wilde-profile-link]) of the target resource. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.6 + */ + profile?: string; + + /** + * The "title" property is OPTIONAL. + * + * Its value is a string and is intended for labelling the link with a + * human-readable identifier (as defined by [RFC5988]). + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.7 + */ + title?: string; + + /** + * The "hreflang" property is OPTIONAL. + * + * Its value is a string and is intended for indicating the language of + * the target resource (as defined by [RFC5988]). + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.8 + */ + hreflang?: string; + + } + +} diff --git a/hammerjs/hammerjs.d.ts b/hammerjs/hammerjs.d.ts index bfc6e7cb4f..faba777b7a 100644 --- a/hammerjs/hammerjs.d.ts +++ b/hammerjs/hammerjs.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Hammer.js 2.0.4 +// Type definitions for Hammer.js 2.0.8 // Project: http://hammerjs.github.io/ // Definitions by: Philip Bulley , Han Lin Yap // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -11,7 +11,7 @@ declare module "hammerjs" { interface HammerStatic { - new( element:HTMLElement | SVGElement, options?:any ): HammerManager; + new( element:HTMLElement | SVGElement, options?:HammerOptions ): HammerManager; defaults:HammerDefaults; @@ -68,16 +68,22 @@ interface HammerStatic prefixed( obj:any, property:string ):string; } -interface HammerDefaults +type RecognizerTuple = + [RecognizerStatic] + | [RecognizerStatic, RecognizerOptions] + | [RecognizerStatic, RecognizerOptions, string | string[]] + | [RecognizerStatic, RecognizerOptions, string | string[], (string | Recognizer) | (string | Recognizer)[]]; + +interface HammerDefaults extends HammerOptions { domEvents:boolean; enable:boolean; - preset:any[]; + preset:RecognizerTuple[]; touchAction:string; cssProps:CssProps; - inputClass():void; - inputTarget():void; + inputClass:() => void; + inputTarget:EventTarget; } interface CssProps @@ -90,13 +96,25 @@ interface CssProps userSelect:string; } -interface HammerOptions extends HammerDefaults +interface HammerOptions { + cssProps?:CssProps; + domEvents?:boolean; + enable?:boolean | ((manager: HammerManager) => boolean); + preset?:RecognizerTuple[]; + touchAction?:string; + recognizers?:RecognizerTuple[]; + inputClass?:() => void; + inputTarget?:EventTarget; } interface HammerManagerConstructor { - new( element:HTMLElement, options?:any ):HammerManager; + new( element:EventTarget, options?:HammerOptions ):HammerManager; +} + +interface HammerListener { + (event:HammerInput): void } interface HammerManager @@ -109,8 +127,8 @@ interface HammerManager emit( event:string, data:any ):void; get( recogniser:Recognizer ):Recognizer; get( recogniser:string ):Recognizer; - off( events:string, handler?:( event:HammerInput ) => void ):void; - on( events:string, handler:( event:HammerInput ) => void ):void; + off( events:string, handler?:HammerListener ):void; + on( events:string, handler:HammerListener ):void; recognize( inputData:any ):void; remove( recogniser:Recognizer ):HammerManager; remove( recogniser:string ):HammerManager; @@ -157,7 +175,7 @@ declare class HammerInput direction:number; /** Direction moved from it's starting point. Matches the DIRECTION constants. */ - offsetDirection:string; + offsetDirection:number; /** Scaling that has been done when multi-touch. 1 on a single touch. */ scale:number; @@ -178,7 +196,7 @@ declare class HammerInput pointerType:string; /** Event type, matches the INPUT constants. */ - eventType:string; + eventType:number; /** true when the first input. */ isFirst:boolean; @@ -221,9 +239,22 @@ declare class TouchMouseInput extends HammerInput constructor( manager:HammerManager, callback:Function ); } +interface RecognizerOptions { + direction?: number; + enable?: boolean | ((recognizer: Recognizer, inputData: HammerInput) => boolean); + event?: string; + interval?: number; + pointers?: number; + posThreshold?: number; + taps?: number + threshold?: number; + time?: number; + velocity?: number; +} + interface RecognizerStatic { - new( options?:any ):Recognizer; + new( options?:RecognizerOptions ):Recognizer; } interface Recognizer @@ -246,7 +277,7 @@ interface Recognizer requireFailure( otherRecognizer:Recognizer ):Recognizer; requireFailure( otherRecognizer:string ):Recognizer; reset():void; - set( options?:any ):Recognizer; + set( options?:RecognizerOptions ):Recognizer; tryEmit( input:HammerInput ):void; } @@ -258,12 +289,12 @@ interface AttrRecognizerStatic interface AttrRecognizer extends Recognizer { - new( options?:any ):AttrRecognizer; + new( options?:RecognizerOptions ):AttrRecognizer; } interface PanRecognizerStatic { - new( options?:any ):PanRecognizer; + new( options?:RecognizerOptions ):PanRecognizer; } interface PanRecognizer extends AttrRecognizer @@ -272,7 +303,7 @@ interface PanRecognizer extends AttrRecognizer interface PinchRecognizerStatic { - new( options?:any ):PinchRecognizer; + new( options?:RecognizerOptions ):PinchRecognizer; } interface PinchRecognizer extends AttrRecognizer @@ -281,7 +312,7 @@ interface PinchRecognizer extends AttrRecognizer interface PressRecognizerStatic { - new( options?:any ):PressRecognizer; + new( options?:RecognizerOptions ):PressRecognizer; } interface PressRecognizer extends AttrRecognizer @@ -290,7 +321,7 @@ interface PressRecognizer extends AttrRecognizer interface RotateRecognizerStatic { - new( options?:any ):RotateRecognizer; + new( options?:RecognizerOptions ):RotateRecognizer; } interface RotateRecognizer extends AttrRecognizer @@ -299,7 +330,7 @@ interface RotateRecognizer extends AttrRecognizer interface SwipeRecognizerStatic { - new( options?:any ):SwipeRecognizer; + new( options?:RecognizerOptions ):SwipeRecognizer; } interface SwipeRecognizer extends AttrRecognizer @@ -308,7 +339,7 @@ interface SwipeRecognizer extends AttrRecognizer interface TapRecognizerStatic { - new( options?:any ):TapRecognizer; + new( options?:RecognizerOptions ):TapRecognizer; } interface TapRecognizer extends AttrRecognizer diff --git a/handlebars/handlebars.d.ts b/handlebars/handlebars.d.ts index 0af3d6f6e7..96b0491040 100644 --- a/handlebars/handlebars.d.ts +++ b/handlebars/handlebars.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Handlebars v3.0.3 +// Type definitions for Handlebars v4.0.5 // Project: http://handlebarsjs.com/ // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -15,14 +15,25 @@ declare namespace Handlebars { export function Exception(message: string): void; export function log(level: number, obj: any): void; export function parse(input: string): hbs.AST.Program; - export function compile(input: any, options?: any): HandlebarsTemplateDelegate; + export function compile(input: any, options?: CompileOptions): HandlebarsTemplateDelegate; + export function precompile(input: any, options?: PrecompileOptions): TemplateSpecification; + export function template(precompilation: TemplateSpecification): HandlebarsTemplateDelegate; + + export function create(): typeof Handlebars; export var SafeString: typeof hbs.SafeString; + export var escapeExpression: typeof hbs.Utils.escapeExpression; export var Utils: typeof hbs.Utils; export var logger: Logger; export var templates: HandlebarsTemplates; export var helpers: any; + export function registerDecorator(name: string, fn: Function): void; + export function registerDecorator(obj: {[name: string] : Function}): void; + export function unregisterDecorator(name: string): void; + + export function noConflict(): typeof Handlebars; + export module AST { export var helpers: hbs.AST.helpers; } @@ -32,6 +43,9 @@ declare namespace Handlebars { Program(program: hbs.AST.Program): void; BlockStatement(block: hbs.AST.BlockStatement): void; PartialStatement(partial: hbs.AST.PartialStatement): void; + PartialBlockStatement(partial: hbs.AST.PartialBlockStatement): void; + DecoratorBlock(decorator: hbs.AST.DecoratorBlock): void; + Decorator(decorator: hbs.AST.Decorator): void; MustacheStatement(mustache: hbs.AST.MustacheStatement): void; ContentStatement(content: hbs.AST.ContentStatement): void; CommentStatement(comment?: hbs.AST.CommentStatement): void; @@ -52,6 +66,9 @@ declare namespace Handlebars { Program(program: hbs.AST.Program): void; BlockStatement(block: hbs.AST.BlockStatement): void; PartialStatement(partial: hbs.AST.PartialStatement): void; + PartialBlockStatement(partial: hbs.AST.PartialBlockStatement): void; + DecoratorBlock(decorator: hbs.AST.DecoratorBlock): void; + Decorator(decorator: hbs.AST.Decorator): void; MustacheStatement(mustache: hbs.AST.MustacheStatement): void; ContentStatement(content: hbs.AST.ContentStatement): void; CommentStatement(comment?: hbs.AST.CommentStatement): void; @@ -81,6 +98,37 @@ interface HandlebarsTemplates { [index: string]: HandlebarsTemplateDelegate; } +interface TemplateSpecification { + +} + +interface CompileOptions { + data?: boolean; + compat?: boolean; + knownHelpers?: { + helperMissing?: boolean; + blockHelperMissing?: boolean; + each?: boolean; + if?: boolean; + unless?: boolean; + with?: boolean; + log?: boolean; + lookup?: boolean; + } + knownHelpersOnly?: boolean; + noEscape?: boolean; + strict?: boolean; + assumeObjects?: boolean; + preventIndent?: boolean; + ignoreStandalone?: boolean; + explicitPartialContext?: boolean; +} + +interface PrecompileOptions extends CompileOptions { + srcName?: string; + destName?: string; +} + declare namespace hbs { class SafeString { constructor(str: string); @@ -89,6 +137,12 @@ declare namespace hbs { namespace Utils { function escapeExpression(str: string): string; + function createFrame(obj: Object): Object; + function isEmpty(obj: any) : boolean; + function extend(obj: any, ...source: any[]): any; + function toString(obj: any): string; + function isArray(obj: any): boolean; + function isFunction(obj: any): boolean; } } @@ -137,6 +191,8 @@ declare namespace hbs { strip: StripFlags; } + interface Decorator extends MustacheStatement { } + interface BlockStatement extends Statement { path: PathExpression; params: Expression[]; @@ -148,6 +204,8 @@ declare namespace hbs { closeStrip: StripFlags; } + interface DecoratorBlock extends BlockStatement { } + interface PartialStatement extends Statement { name: PathExpression | SubExpression; params: Expression[]; @@ -156,6 +214,15 @@ declare namespace hbs { strip: StripFlags; } + interface PartialBlockStatement extends Statement { + name: PathExpression | SubExpression; + params: Expression[], + hash: Hash, + program: Program, + openStrip: StripFlags, + closeStrip: StripFlags + } + interface ContentStatement extends Statement { value: string; original: StripFlags; diff --git a/handsontable/handsontable.d.ts b/handsontable/handsontable.d.ts index 790eb4b087..7a82509baa 100644 --- a/handsontable/handsontable.d.ts +++ b/handsontable/handsontable.d.ts @@ -232,7 +232,7 @@ declare namespace ht { getCellMeta(row: number, col: number): Object; getCellRenderer(row: number, col: number): Function; getCellValidator(row: number, col: number): any; - getColHeader(col: number): any[]|string; + getColHeader(col?: number): any[]|string; getColWidth(col: number): number; getCoords(elem: Element): Object; getCopyableData(row: number, column: number): string; diff --git a/hapi/hapi-8.2.0.d.ts b/hapi/hapi-8.2.0.d.ts index d205ade2bc..ef81b4fba3 100644 --- a/hapi/hapi-8.2.0.d.ts +++ b/hapi/hapi-8.2.0.d.ts @@ -221,21 +221,7 @@ declare module "hapi" { defaultExtension?: string; } - /** Concludes the handler activity by setting a response and returning control over to the framework where: - erran optional error response. - resultan optional response payload. - Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. - FLOW CONTROL: - When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ - export interface IReply { - (err: Error, - result?: string|number|boolean|Buffer|stream.Stream | Promise | T, - /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ - credentialData?: any - ): IBoom; - /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ - (result?: string|number|boolean|Buffer|stream.Stream | Promise | T): Response; - + interface IReplyMethods { /** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200. * The data argument is only used for passing back authentication data and is ignored elsewhere. */ continue(credentialData?: any): void; @@ -282,8 +268,39 @@ declare module "hapi" { redirect(uri: string): Response; } + /** Concludes the handler activity by setting a response and returning control over to the framework where: + erran optional error response. + resultan optional response payload. + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: + When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ + export interface IReply extends IReplyMethods{ + (err: Error, + result?: string|number|boolean|Buffer|stream.Stream | Promise | T, + /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ + credentialData?: any + ): IBoom; + /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ + (result?: string|number|boolean|Buffer|stream.Stream | Promise | T): Response; + } + + /** Concludes the handler activity by setting a response and returning control over to the framework where: + erran optional error response. + result an optional response payload. + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: + When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ + export interface IStrictReply extends IReplyMethods { + (err: Error, + result?: Promise | T, + /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ + credentialData?: any): IBoom; + /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ + (result: Promise | T): Response; + } export interface ISessionHandler { (request: Request, reply: IReply): void; + (request: Request, reply: IStrictReply): void; } export interface IRequestHandler { (request: Request): T; @@ -868,6 +885,7 @@ declare module "hapi" { }; server.auth.scheme('custom', scheme);*/ authenticate(request: Request, reply: IReply): void; + authenticate(request: Request, reply: IStrictReply): void; /** payload(request, reply) - optional function called to authenticate the request payload where: request - the request object. reply(err, response) - is called if authentication failed where: @@ -876,6 +894,7 @@ declare module "hapi" { reply.continue() - is called if payload authentication succeeded. When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.*/ payload? (request: Request, reply: IReply): void; + payload?(request: Request, reply: IStrictReply): void; /** response(request, reply) - optional function called to decorate the response with authentication headers before the response headers or payload is written where: request - the request object. reply(err, response) - is called if an error occurred where: @@ -883,6 +902,7 @@ declare module "hapi" { response - any authentication response to send instead of the current response. Ignored if err is present, otherwise required. reply.continue() - is called if the operation succeeded.*/ response? (request: Request, reply: IReply): void; + response?(request: Request, reply: IStrictReply): void; /** an optional object */ options?: { /** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.*/ @@ -1830,6 +1850,7 @@ declare module "hapi" { server.start(); // All requests will get routed to '/test'*/ ext(event: string, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string|string[]; after: string|string[]; bind?: any }): void; + ext(event: string, method: (request: Request, reply: IStrictReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; /** server.handler(name, method) Registers a new handler type to be used in routes where: diff --git a/hapi/hapi-tests-8.2.0.ts b/hapi/hapi-tests-8.2.0.ts index c61504f0fc..e26ce193bc 100644 --- a/hapi/hapi-tests-8.2.0.ts +++ b/hapi/hapi-tests-8.2.0.ts @@ -104,5 +104,25 @@ server.route([{ } }]); +server.route([{ + method: 'GET', + path: '/hello4', + handler: function (request: Hapi.Request, reply: Hapi.IReply) { + reply('hello world2'); + } +}]); + +interface IHello { + msg: string +} + +server.route([{ + method: 'GET', + path: '/hello5', + handler: function (request: Hapi.Request, reply: Hapi.IStrictReply) { + reply({ msg: 'hello world' }) + } +}]); + // Start the server server.start(); diff --git a/hapi/hapi-tests.ts b/hapi/hapi-tests.ts index 743a4ad3ee..3288618816 100644 --- a/hapi/hapi-tests.ts +++ b/hapi/hapi-tests.ts @@ -92,6 +92,26 @@ server.route([{ } }]); +server.route([{ + method: 'GET', + path: '/hello3', + handler: function (request: Hapi.Request, reply: Hapi.IReply) { + reply('hello world2'); + } +}]); + +interface IHello { + msg: string +} + +server.route([{ + method: 'GET', + path: '/hello4', + handler: function (request: Hapi.Request, reply: Hapi.IStrictReply) { + reply({ msg: 'hello world' }) + } +}]); + // config.validate parameters should be optional server.route([{ method: 'GET', diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index 2867dd7de9..ff5e1d9fe8 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -240,21 +240,9 @@ declare module "hapi" { /** defines the default filename extension to append to template names when multiple engines are configured and not explicit extension is provided for a given template. No default value.*/ defaultExtension?: string; } - - /** Concludes the handler activity by setting a response and returning control over to the framework where: - erran optional error response. - resultan optional response payload. - Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. - FLOW CONTROL: - When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ - export interface IReply { - (err: Error, - result?: string | number | boolean | Buffer | stream.Stream | IPromise | T, - /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ - credentialData?: any): IBoom; - /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ - (result: string | number | boolean | Buffer | stream.Stream | IPromise | T): Response; - + + + interface IReplyMethods { /** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200. * The data argument is only used for passing back authentication data and is ignored elsewhere. */ continue(credentialData?: any): void; @@ -310,8 +298,39 @@ declare module "hapi" { unstate(name: string, options?: any): void; } + /** Concludes the handler activity by setting a response and returning control over to the framework where: + erran optional error response. + result an optional response payload. + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: + When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ + export interface IReply extends IReplyMethods { + (err: Error, + result?: string | number | boolean | Buffer | stream.Stream | IPromise | T, + /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ + credentialData?: any): IBoom; + /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ + (result: string | number | boolean | Buffer | stream.Stream | IPromise | T): Response; + } + + /** Concludes the handler activity by setting a response and returning control over to the framework where: + erran optional error response. + result an optional response payload. + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: + When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ + export interface IStrictReply extends IReplyMethods { + (err: Error, + result?: IPromise | T, + /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ + credentialData?: any): IBoom; + /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ + (result: IPromise | T): Response; + } + export interface ISessionHandler { (request: Request, reply: IReply): void; + (request: Request, reply: IStrictReply): void; } export interface IRequestHandler { (request: Request): T; @@ -926,6 +945,7 @@ declare module "hapi" { }; server.auth.scheme('custom', scheme);*/ authenticate(request: Request, reply: IReply): void; + authenticate(request: Request, reply: IStrictReply): void; /** payload(request, reply) - optional function called to authenticate the request payload where: request - the request object. reply(err, response) - is called if authentication failed where: @@ -934,6 +954,7 @@ declare module "hapi" { reply.continue() - is called if payload authentication succeeded. When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.*/ payload?(request: Request, reply: IReply): void; + payload?(request: Request, reply: IStrictReply): void; /** response(request, reply) - optional function called to decorate the response with authentication headers before the response headers or payload is written where: request - the request object. reply(err, response) - is called if an error occurred where: @@ -941,6 +962,7 @@ declare module "hapi" { response - any authentication response to send instead of the current response. Ignored if err is present, otherwise required. reply.continue() - is called if the operation succeeded.*/ response?(request: Request, reply: IReply): void; + response?(request: Request, reply: IStrictReply): void; /** an optional object */ options?: { /** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.*/ @@ -964,7 +986,7 @@ declare module "hapi" { payload: string; rawPayload: Buffer; raw: { - req: http.ClientRequest; + req: http.IncomingMessage; res: http.ServerResponse }; result: string; @@ -1199,7 +1221,7 @@ declare module "hapi" { query: any; /** an object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.*/ raw: { - req: http.ClientRequest; + req: http.IncomingMessage; res: http.ServerResponse; }; /** the route public interface.*/ @@ -1583,6 +1605,9 @@ declare module "hapi" { addEventListener: any; info: IServerConnectionInfo; } + + type RequestExtPoints = "onRequest" | "onPreResponse" | "onPreAuth" | "onPostAuth" | "onPreHandler" | "onPostHandler" | "onPreResponse"; + type ServerExtPoints = "onPreStart" | "onPostStart" | "onPreStop" | "onPostStop"; /** Server http://hapijs.com/api#server rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). @@ -2017,7 +2042,9 @@ declare module "hapi" { server.route({ method: 'GET', path: '/test', handler: handler }); server.start(); // All requests will get routed to '/test'*/ - ext(event: string, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + ext(event: RequestExtPoints, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + ext(event: RequestExtPoints, method: (request: Request, reply: IStrictReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + ext(event: ServerExtPoints, method: (server: Server, next: (err?: any) => void, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; /** server.handler(name, method) Registers a new handler type to be used in routes where: diff --git a/heatmap.js/heatmap.d.ts b/heatmap.js/heatmap.d.ts index 7cd14fc214..fb2b4eea3d 100644 --- a/heatmap.js/heatmap.d.ts +++ b/heatmap.js/heatmap.d.ts @@ -3,7 +3,7 @@ // Definitions by: Yang Guan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /* * Configuration object of a heatmap diff --git a/hellojs/hellojs.d.ts b/hellojs/hellojs.d.ts index 686d5c1adf..8f0a9e9caa 100644 --- a/hellojs/hellojs.d.ts +++ b/hellojs/hellojs.d.ts @@ -18,7 +18,45 @@ interface HelloJSLogoutOptions { force?: boolean; } -interface HelloJSEvent { +interface HelloJSImmediateSuccessCB { + (value: T): TP; +} + +interface HelloJSImmediateErrorCB { + (err: any): TP; +} + +interface HelloJSDeferredSuccessCB { + (value: T): HelloJSThenable; +} + +interface HelloJSDeferredErrorCB { + (error: any): HelloJSThenable; +} + +interface HelloJSThenable { + then( + successCB?: HelloJSDeferredSuccessCB, + errorCB?: HelloJSDeferredErrorCB + ): HelloJSThenable; + + then( + successCB?: HelloJSDeferredSuccessCB, + errorCB?: HelloJSImmediateErrorCB + ): HelloJSThenable; + + then( + successCB?: HelloJSImmediateSuccessCB, + errorCB?: HelloJSDeferredErrorCB + ): HelloJSThenable; + + then( + successCB?: HelloJSImmediateSuccessCB, + errorCB?: HelloJSImmediateErrorCB + ): HelloJSThenable; +} + +interface HelloJSEvent extends HelloJSThenable { on(event: string, callback: (auth: HelloJSEventArgument) => void): HelloJSStatic; off(event: string, callback: (auth: HelloJSEventArgument) => void): HelloJSStatic; findEvents(event: string, callback: (name: string, index: number) => void): void; @@ -30,15 +68,17 @@ interface HelloJSEvent { } + interface HelloJSEventArgument { network: string; authResponse?: any; } + interface HelloJSStatic extends HelloJSEvent { init(serviceAppIds: { [id: string]: string; }, options?: HelloJSLoginOptions): void; - login(network: string, options?: HelloJSLoginOptions, callback?: () => void): void; - logout(network: string, options?: HelloJSLogoutOptions, callback?: () => void): void; + login(network: string, options?: HelloJSLoginOptions, callback?: () => void): HelloJSStatic; + logout(network: string, options?: HelloJSLogoutOptions, callback?: () => void): HelloJSStatic; getAuthResponse(network: string): any; service(network: string): HelloJSServiceDef; settings: HelloJSLoginOptions; @@ -50,7 +90,7 @@ interface HelloJSStaticNamed { login(option?: HelloJSLoginOptions, callback?: () => void): void; logout(callback?: () => void): void; getAuthResponse(): any; - api(path?: string, method?: string, data?: any, callback?: (json?: any) => void): HelloJSStatic; + api(path?: string, method?: string, data?: any, callback?: (json?: any) => void): HelloJSStatic; } interface HelloJSOAuthDef { diff --git a/hellosign-embedded/hellosign-embedded-tests.ts b/hellosign-embedded/hellosign-embedded-tests.ts new file mode 100644 index 0000000000..455171942e --- /dev/null +++ b/hellosign-embedded/hellosign-embedded-tests.ts @@ -0,0 +1,39 @@ +/// + +HelloSign.init('abc123'); + +// some options +HelloSign.open({ + url: 'http://example.org', + messageListener: (e: HelloSign.MessageEvent) => { + if (e.event === HelloSign.EVENT_SIGNED) { + console.log('signed'); + } + }, + uxVersion: 2 +}); + +// all options +HelloSign.open({ + url: 'http://example.org', + redirectUrl: 'https://github.com/DefinitelyTyped/DefinitelyTyped', + allowCancel: true, + messageListener: (e: HelloSign.MessageEvent) => { + if (e.event === HelloSign.EVENT_SIGNED) { + console.log('signed'); + } + }, + userCulture: HelloSign.CULTURES.EN_US, + debug: true, + skipDomainVerification: true, + container: document.getElementById('#hellosign-container'), + height: 1326, + hideHeader: true, + uxVersion: 2, + requester: 'hellosign@example.org', + whiteLabelingOptions: { + "page_background_color": "#f7f8f9" + } +}); + +HelloSign.close(); diff --git a/hellosign-embedded/hellosign-embedded.d.ts b/hellosign-embedded/hellosign-embedded.d.ts new file mode 100644 index 0000000000..f215dac6bc --- /dev/null +++ b/hellosign-embedded/hellosign-embedded.d.ts @@ -0,0 +1,193 @@ +// Type definitions for hellosign-embedded v1.0.3 +// Project: https://github.com/HelloFax/hellosign-embedded +// Definitions by: Brian Surowiec +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module HelloSign { + interface MessageEvent { + event: string; + } + + interface ClientCultures { + /** + * English (United States) + * + * @default en_US + */ + EN_US: string; + + /** + * French (France) + * + * @default fr_FR + */ + FR_FR: string; + + /** + * German (Germany) + * + * @default de_DE + */ + DE_DE: string; + + /** + * Swedish (Sweden) + * + * @default sv_SE + */ + SV_SE: string; + + /** + * Chinese (China) + * + * @default zh_CN + */ + ZH_CN: string; + + /** + * Danish (Denmark) + * + * @default da_DK + */ + DA_DK: string; + + /** + * Dutch (The Netherlands) + * @default nl_NL + */ + NL_NL: string; + + /** + * The available client UI cultures + */ + supportedCultures: string[]; + } + + interface OpenParameters { + /** + * The url to open in the child frame + */ + url?: string; + + /** + * Where to go after the signature is completed + */ + redirectUrl?: string; + + /** + * Whether a cancel button should be displayed + * + * @default true + */ + allowCancel?: boolean; + + /** + * A listener for X-window messages coming from the child frame + */ + messageListener?: (eventData: MessageEvent) => void; + + /** + * One of the HelloSign.CULTURES.supportedCultures + * + * @default HelloSign.CULTURES.EN_US + */ + userCulture?: string; + + /** + * When true, debugging statements will be written to the console + * + * @default false + */ + debug?: boolean; + + /** + * When true, domain verification step will be skipped if and only if the Signature Request was created with test_mode=1 + * + * @default false + */ + skipDomainVerification?: boolean; + + /** + * DOM element that will contain the iframe on the page (defaults to document.body) + */ + container?: Element; + + /** + * Height of the iFrame (only applicable when a container is specified) + */ + height?: number; + + /** + * When true, the header will be hidden. + * This is only functional for customers with embedded branding enabled. + * + * @default false + */ + hideHeader?: boolean; + + /** + * The version of the embedded user experience to display to signers (1 = legacy, 2 = responsive). + * This option is only honored if your account has accessed the API prior to Nov 14, 2015. + */ + uxVersion?: number; + + /** + * The email of the person issuing a signature request. + * Required for allowing 'Me + Others' requests + */ + requester?: string; + + /** + * An associative array to be used to customize the app's signer page + */ + whiteLabelingOptions?: Object; + } + + interface HelloSignStatic { + /** + * The available client UI cultures + */ + CULTURES: ClientCultures; + + /** + * The signature request was signed + * + * @default signature_request_signed + */ + EVENT_SIGNED: string; + + /** + * The user closed the iFrame before completing + * + * @default signature_request_canceled + */ + EVENT_CANCELED: string; + + /** + * An error occurred in the iFrame + * + * @default error + */ + EVENT_ERROR: string; + + /** + * Initialize using your HelloSign API client ID. + * + * @param appClientId The API client ID the request is for. + */ + init(appClientId: string): void; + + /** + * Open the signing window. + * + * @param params The options to use when opening the signing window. + */ + open(params: OpenParameters): void; + + /** + * Close the signing window. + */ + close(): void; + } +} + +declare var HelloSign: HelloSign.HelloSignStatic; diff --git a/heremaps/heremaps-tests.ts b/heremaps/heremaps-tests.ts new file mode 100644 index 0000000000..3b2e1b5c30 --- /dev/null +++ b/heremaps/heremaps-tests.ts @@ -0,0 +1,82 @@ +// Test file for HERE Maps API for JavaScript Definition file +/// + +/** + * EXAMPLE from the HERE Maps API + * Takes a snapshot of the map. + * + * @param {Element} resultContainer Reference to DOM Element to show the captured map area + * @param {H.Map} map Reference to initialized map object + * @param {H.ui.UI} ui Reference to UI component + */ +function capture(resultContainer: HTMLElement, map: H.Map, ui: H.ui.UI) { + // Capturing area of the map is asynchronous, callback function receives HTML5 canvas + // element with desired map area rendered on it. + // We also pass an H.ui.UI reference in order to see the ScaleBar in the output. + // If dimensions are omitted, whole veiw port will be captured + map.capture((canvas: HTMLCanvasElement) => { + if (canvas) { + resultContainer.innerHTML = ''; + resultContainer.appendChild(canvas); + } else { + // For example when map is in Panorama mode + resultContainer.innerHTML = 'Capturing is not supported'; + } + }, [ui], 50, 50, 500, 200); +} + +/** + * Boilerplate map initialization code starts below: + */ +// Step 1: initialize communication with the platform +var platform = new H.service.Platform({ + app_id: 'DemoAppId01082013GAL', + app_code: 'AJKnXv84fjrb0KIHawS0Tg', + useHTTPS: true, + useCIT: true +}); + +var defaultLayers = platform.createDefaultLayers(); + +var mapContainer = document.getElementById('map'); + +// Step 2: initialize a map +var map = new H.Map(mapContainer, defaultLayers.normal.map, { + // initial center and zoom level of the map + zoom: 16, + // Champs-Elysees + center: {lat: 48.869145, lng: 2.314298} +}); + +// Step 3: make the map interactive +// MapEvents enables the event system +// Behavior implements default interactions for pan/zoom (also on mobile touch environments) +var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map)); + +// Step 4: Create the default UI +var ui = H.ui.UI.createDefault(map, defaultLayers, 'en-US'); + + +// Step 6: Create "Capture" button and place for showing the captured area +var resultContainer = document.getElementById('panel'); + +// Create container for the "Capture" button +var containerNode = document.createElement('div'); +containerNode.setAttribute('style', + 'position:absolute;top:0;left:0;background-color:#fff; padding:10px;'); +containerNode.className = 'btn-group'; + +// Create the "Capture" button +var captureBtn = document.createElement('input'); +captureBtn.value = 'Capture'; +captureBtn.type = 'button'; +captureBtn.className = 'btn btn-sm btn-default'; + +// Add both button and container to the DOM +containerNode.appendChild(captureBtn); +mapContainer.appendChild(containerNode); + +// Step 7: Handle capture button click event +captureBtn.onclick = function() { + capture(resultContainer, map, ui); +}; \ No newline at end of file diff --git a/heremaps/heremaps.d.ts b/heremaps/heremaps.d.ts new file mode 100644 index 0000000000..8d730f3ae5 --- /dev/null +++ b/heremaps/heremaps.d.ts @@ -0,0 +1,6354 @@ +// Type definitions for HERE Maps API for JavaScript v3.0.12.4 +// Project: https://developer.here.com/ +// Definitions by: Joshua Efiong +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace H { + /***** Map *****/ + /** + * Map class defines map instance in the application. By creating this object you will initialize a visible map object which is attached to the provided dom element. Map class is an entry point to all operations related to layers, map objects and geo-screen transformations. By specifying options you can initialize map with predefined view. + */ + export class Map extends H.util.EventTarget { + /** + * Constructor + * @param element {Element} - html element into which the map will be rendered + * @param baseLayer {H.map.layer.Layer} - The layer to be used as the base (bottom most) layer. + * @param opt_options {H.Map.Options=} - additional map options + */ + constructor(element: Element, baseLayer: H.map.layer.Layer, opt_options?: H.Map.Options); + + /** + * This method returns the map root html element + * @returns {Element} + */ + getElement(): Element; + + /** + * This method sets the new center on a map. + * @param center {H.geo.IPoint} - requested center to be set + * @param opt_animate {boolean=} - parameter indicates if animated transition should be applied, default is false + * @returns {H.Map} - the instance itself + */ + setCenter(center: H.geo.IPoint, opt_animate?: boolean): H.Map; + + /** + * This method returns currently rendered center of the map. + * @returns {H.geo.Point} + */ + getCenter(): H.geo.Point; + + /** + * This method sets the zoom level on the map. Every zoom level represents different scale i.e map at zoom level 2 is twice as large as the map at zoom level 1. + * @param zoom {number} - requested zoom level + * @param opt_animate {boolean=} - parameter indicates if animated transition should be applied, default is false + * @returns {H.Map} - the instance itself + */ + setZoom(zoom: number, opt_animate?: boolean): H.Map; + + /** + * This method returns currently rendered zoom level. + * @returns {number} + */ + getZoom(): number; + + /** + * This method changes the map zoom while keeping target screen coordinates specified as x,y at the same place where they were before. + * @param zoom {number} - new zoom level + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + */ + zoomAt(zoom: number, x: number, y: number): void; + + /** + * This method sets the bounding rect to be displayed by the map. Maps display the bounding rect in a way that it fits entirely in the current viewport. + * @param boundingRect {H.geo.Rect} - view bound which should be shown on map + * @param opt_animate {boolean=} - parameter indicates if animated transition should be applied, default is false + * @returns {H.Map} - the instance itself + */ + setViewBounds(boundingRect: H.geo.Rect, opt_animate?: boolean): H.Map; + + /** + * This method returns bounding rect for the current map view. Returned bounding rect defines entire currently viewable area on the screen. + * @returns {H.geo.Rect} + */ + getViewBounds(): H.geo.Rect; + + /** + * Calculates the best CameraModel to show the provided bounding rectangle + * @param rect {H.geo.Rect} - The geographical bounding rectangle to use + * @returns {H.map.ViewModel.CameraData} - The result, represented by the properties zoom (number) and position (geo.Point) + */ + getCameraDataForBounds(rect: H.geo.Rect): H.map.ViewModel.CameraData; + + /** + * This method returns current map viewport. Viewport can be used to modify padding and margin which will reflect the position of the viewport center and the amount of extra data loaded (for margin) + * @returns {H.map.ViewPort} + */ + getViewPort(): H.map.ViewPort; + + /** + * This method returns current view model. View model can be used to modify the current view or camera. H.map.ViewModel + * @returns {H.map.ViewModel} + */ + getViewModel(): H.map.ViewModel; + + /** + * This method returns the map's current layer collection. + * @returns {H.map.DataModel} + */ + getLayers(): H.map.DataModel; + + /** + * This method returns the imprint object for this map. + * @returns {H.map.Imprint} + */ + getImprint(): H.map.Imprint; + + /** + * This method captures desired region of the map and objects on it. Result is returned as an HTML5 Canvas element. Origin of coordinate system for capturing is in the top left corner of the viewport. + * @param callback {function(HTMLCanvasElement=)} - Callback function to call once result of the capturing is ready + * @param opt_capturables {Array=} - Collection of "capturable" element(s) to draw into the resulting canvas + * @param opt_x1 {number=} - The X coordinate of the left edge of the capturing rectangle defaults to 0 + * @param opt_y1 {number=} - The Y coordinate of the top edge of the capturing rectangle defaults to 0 + * @param opt_x2 {number=} - The X coordinate of the right edge of the capturing rectangle defaults to viewport width + * @param opt_y2 {number=} - The Y coordinate of the bottom edge of the capturing rectangle defaults to viewport height + */ + capture(callback?: (canvas: HTMLCanvasElement) => void, opt_capturables?: Array, opt_x1?: number, opt_y1?: number, opt_x2?: number, opt_y2?: number): void; + + /** + * This method sets the rendering engine type for the map. Rendering engine is responsible for displaying i.e tiles and data on the map. + * @param type {H.Map.EngineType} + * @returns {H.Map} - the map itself + */ + setEngineType(type: H.Map.EngineType): H.Map; + + /** + * To persistently store the content of a map layer for a given area and range of zoom levels. It can be used to enable map rendering when no internet connection is established and also to reduce the download traffic for frequently visited map areas. + * @param opt_onprogress {function(H.util.Request)=} - A callback which is invoked every time when the progress state of the returned store request changes. + * @param opt_bounds {H.geo.Rect=} - The area to store, default is the current view bounds + * @param opt_min {number=} - The minimum zoom level to store, default is the current zoom level + * @param opt_max {number=} - The maximum zoom level to store, default is the current zoom level + * @param opt_layer {H.map.layer.BaseTileLayer=} - The layer to store, default is the current base layer + * @returns {H.util.Request} - A handle to the created storage request + */ + storeContent(opt_onprogress?: (req: H.util.Request) => void, opt_bounds?: H.geo.Rect, opt_min?: number, opt_max?: number, opt_layer?: H.map.layer.BaseTileLayer): H.util.Request; + + /** + * To clear the entire stored content + * @param opt_onprogress {function(H.util.Request)=} - A callback which is invoked every time when the progress state of the returned clear request changes + * @returns {H.util.Request} - A handle to the created flush request + */ + clearContent(opt_onprogress?: (req: H.util.Request) => void): H.util.Request; + + /** + * This method adds a layer to the map. + * @param layer {H.map.layer.Layer} - The map layer to be added + * @param opt_idx {number=} - index at which the new layer should be inserted + * @returns {H.Map} - current map instance + */ + addLayer(layer: H.map.layer.Layer, opt_idx?: number): H.Map; + + /** + * This method removes layer from the map. + * @param layer {H.map.layer.Layer} - The map layer to be removed + * @returns {H.Map} - current map instance + */ + removeLayer(layer: H.map.layer.Layer): H.Map; + + /** + * This method will set provided layer as base map. The layer will be inserted as the bottom most layer in the map. + * @param layer {H.map.layer.Layer} - The layer to use as base map + * @returns {H.Map} - the instance itself + */ + setBaseLayer(layer: H.map.layer.Layer): H.Map; + + /** + * To get the current base map layer. + * @returns {?H.map.layer.Layer} + */ + getBaseLayer(): H.map.layer.Layer; + + /** + * Returns the screen coordinates according to the given geographical coordinates. This method returns a screen pixel coordinates for the provided geo point. + * @param geoPoint {H.geo.IPoint} - point on the map + * @returns {?H.math.Point} + */ + geoToScreen(geoPoint: H.geo.IPoint): H.math.Point; + + /** + * Returns the geographical coordinates according to the given screen coordinates. + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + * @returns {?H.geo.Point} + */ + screenToGeo(x: number, y: number): H.geo.Point; + + /** + * Returns the camera data according to the given screen coordinates. Method converts screen pixel coordinates to correct camera data object + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + * @returns {H.map.ViewModel.CameraData} + */ + screenToCameraData(x: number, y: number): H.map.ViewModel.CameraData; + + /** + * This method adds an map object to the map. Map object can be a marker or a spatial object like polygon or polyline. + * @param mapObject {!H.map.Object} - The map object to add + * @returns {!H.map.Object} - the added map object + */ + addObject(mapObject: H.map.Object): H.map.Object; + + /** + * This method removes previously added map object from the map. + * @param mapObject {!H.map.Object} - The map object to remove + * @returns {!H.map.Object} - the removed map object + */ + removeObject(mapObject: H.map.Object): H.map.Object; + + /** + * This method retrieves the list of all objects which have been added to the map. + * @returns {Array} - the list of all use objects which are currently on the map. + */ + getObjects(): Array; + + /** + * This method adds an array of objects or an object group to the map. + * @param mapObjects {Array} + * @returns {H.Map} - the map instance + */ + addObjects(mapObjects: Array): H.Map; + + /** + * This method removes an array of object or an object group from the map. + * @param mapObjects {(Array | H.map.Group)} + * @returns {H.Map} - the map instance + */ + removeObjects(mapObjects: (Array | H.map.Group)): H.Map; + + /** + * Returns the top most z-ordered map object found under the specific screen coordinates. Coordinates are viewport pixel coordinates starting from top left corner as (0, 0) point. + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + * @returns {?H.map.Object} - the encountered top most map object or null if no object found + */ + getObjectAt(x: number, y: number): H.map.Object; + + /** + * Returns a list of map objects in descending z-order found under the specific screen coordinates. Coordinates are viewport pixel coordinates starting from top left corner as (0, 0) point. + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + * @returns {Array} + */ + getObjectsAt(x: number, y: number): Array; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module Map { + /** + * It defines the number of lower and higher zoom levels, where cached content of the base map is rendered while content of the current zoom level is still loading. Example: if range was set to {lower: 3, higher: 2} and current level is 10 then rendering engine will try to display cached tiles from lower zoom levels 7, 8, 9 and higher levels 11 and 12. + * @property lower {number} - The number of lower zoom levels to take into account, default is 0 + * @property higher {number} - The number of higher zoom levels to take into account, default is 0 + */ + export interface BackgroundRange { + lower: number; + higher: number; + } + + /** + * Types of engines + */ + export enum EngineType { + P2D, + PANORAMA, + } + + /** + * This type defines options which can be used to initialize the map. + * @property center {H.geo.IPoint=} - The initial center of the map, default is {lat:0, lng: 0} + * @property zoom {number=} - The initial zoom level of the map, default is 0 respectively the minimal zoom level of the base map + * @property bounds {H.geo.Rect=} - The view bounds to be displayed on the map. If provided, it takes precedence over center and zoom. and zoom if provided) + * @property layers {Array=} - A list of layers to render on top of the base map + * @property engineType: {H.Map.EngineType=} - The initial engine type to use, default is P2D + * @property pixelRatio {number} - The pixelRatio to use for over-sampling in cases of high-resolution displays, default is 1 + * @property imprint {H.map.Imprint.Options=} - The imprint options or null to suppress the imprint + * @property renderBaseBackground {H.Map.BackgroundRange=} - Object describes how many cached zoom levels should be used as a base map background while base map tiles are loading. Example: {lower: 3, higher: 2} + * @property autoColor {boolean=} - Indicates whether the UI's colors should automatically adjusted to the base layer, default is true. Up to now only the copyright style will be adjusted. See H.map.layer.Layer.Options#dark + * @property margin {number=} - The size in pixel of the supplemental area to render for each side of the map + * @property padding {H.map.ViewPort.Padding=} - The padding in pixels for each side of the map + * @property fixedCenter {boolean=} - Indicates whether the center of the map should remain unchanged if the viewport's size or padding has been changed, default is true + */ + export interface Options { + center?: H.geo.IPoint; + zoom?: number; + bounds?: H.geo.Rect; + layers?: Array; + engineType?: EngineType; + pixelRatio?: number; + imprint?: H.map.Imprint.Options; + renderBaseBackground?: BackgroundRange; + autoColor?: boolean; + margin?: number; + padding?: H.map.ViewPort.Padding; + fixedCenter?: boolean; + } + } + + /***** clustering *****/ + export module clustering { + /** + * This class represents the input data structure for data points to be clustered. + * @property lat {H.geo.Latitude} - The latitude coordinate of the data point's position + * @property lng {H.geo.Longitude} - The longitude coordinate of the data point's position + * @property wt {number} - The weight of the data point + * @property data {*} - Data associated with this data point + */ + export class DataPoint implements H.geo.IPoint { + /** + * Constructor + * @param lat {H.geo.Latitude} - The latitude coordinate of the data point's position + * @param lng {H.geo.Longitude} - The longitude coordinate of the data point's position + * @param opt_weight {number=} - The weight of the data point as a positive number > 0. If not specified it , default is 1. + * @param opt_data {*=} - Optional data, which will be associated with this DataPoint + */ + constructor(lat: H.geo.Latitude, lng: H.geo.Longitude, opt_weight?: number, opt_data?: any); + + lat: H.geo.Latitude; + lng: H.geo.Longitude; + alt: H.geo.Altitude; + ctx: H.geo.AltitudeContext; + wt: number; + data: any; + } + + /** + * This interface describes a cluster of data points, which fulfill the clustering specification (i.e. data points are within the epsilon and there are enough points to form a cluster). + */ + export interface ICluster { + /** + * Returns the maximum zoom level where this cluster doesn't fall apart into sub clusters and/or noise poinst + * @returns {number} + */ + getMaxZoom(): number; + + /** + * Returns the bounding rectangle of this cluster. + * @returns {H.geo.Rect} + */ + getBounds(): H.geo.Rect; + + /** + * Invokes the specified callback for each "entry" of the cluster. That "entry" can be either a cluster which implements H.clustering.ICluster interface or a noise point which implements H.clustering.INoisePoint interface. + * @param callback {function(H.clustering.IResult)} - The callback gets the currently traversed entry as an argument, which is cluster or noise point. + */ + forEachEntry(callback: (result: H.clustering.IResult) => void): void; + + /** + * Invokes the specified callback for each data point which is part of this cluster, even indirectly. + * @param callback {function(H.clustering.INoisePoint)} - The callback gets the currently traversed noise point as argument. + */ + forEachDataPoint(callback: (noise: H.clustering.INoisePoint) => void): void; + + /** + * Returns the geographical position of this cluster result. + * @returns {H.geo.Point} + */ + getPosition(): H.geo.Point; + + /** + * Returns the weight of this cluster result. + * @returns {number} + */ + getWeight(): number; + + /** + * To indicate whether this cluster result is a cluster or noise point + * @returns {boolean} + */ + isCluster(): boolean; + + /** + * Returns the minimum zoom level where this item is not part of another cluster + * @returns {number} + */ + getMinZoom(): number; + } + + /** + * This interface represents a data point which does not belong to a cluster. + */ + export interface INoisePoint { + /** + * This method returns data which coresponds to this noise point. + * @returns {*} + */ + getData(): any; + + /** + * Returns the geographical position of this cluster result. + * @returns {H.geo.Point} + */ + getPosition(): H.geo.Point; + + /** + * Returns the weight of this cluster result. + * @returns {number} + */ + getWeight(): number; + + /** + * To indicate whether this cluster result is a cluster or noise point + * @returns {boolean} + */ + isCluster(): boolean; + + /** + * Returns the minimum zoom level where this item is not part of another cluster + * @returns {number} + */ + getMinZoom(): number; + } + + /** + * This interface represents the result item of a clustering operation. + */ + export interface IResult { + + /** + * Returns the geographical position of this cluster result. + * @returns {H.geo.Point} + */ + getPosition(): H.geo.Point; + + /** + * Returns the weight of this cluster result. + * @returns {number} + */ + getWeight(): number; + + /** + * To indicate whether this cluster result is a cluster or noise point + * @returns {boolean} + */ + isCluster(): boolean; + + /** + * Returns the minimum zoom level where this item is not part of another cluster + * @returns {number} + */ + getMinZoom(): number; + } + + /** + * Interface which specifies the methods a theme must implement. + */ + export interface ITheme { + + /** + * Function returns a cluster presentation as a map object. + * @param cluster {H.clustering.ICluster} + * @returns {H.map.Object} + */ + getClusterPresentation(cluster: H.clustering.ICluster): H.map.Object; + + /** + * Function returns noise point presentation as a map object + * @param noisePoint {H.clustering.INoisePoint} + * @returns {H.map.Object} + */ + getNoisePresentation(noisePoint: H.clustering.INoisePoint): H.map.Object; + } + + /** + * The clustering provider serves clusters and noise point representation for the map depending on the provided data set. Levels for clustering as well as custom cluster representation can be set via Options. + * @property min {number} - Minimum zoom level at which provider can cluster data + * @property max {number} - Maximum zoom level at which provider can cluster data + */ + export class Provider extends H.util.EventTarget { + /** + * Constructor + * @param dataPoints {Array} + * @param opt_options {H.clustering.Provider.Options=} + */ + constructor(dataPoints: Array, opt_options?: H.clustering.Provider.Options); + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} + * @param opt_scope {Object=} + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + /** + * This method sets new data to the provider + * @param dataPoints {Array} + */ + setDataPoints(dataPoints: Array): void; + + /** + * This method adds a data point to the provider. Beware that this method provokes reclustering of the whole data set. + * @param dataPoint {H.clustering.DataPoint} + */ + addDataPoint(dataPoint: H.clustering.DataPoint): void; + + /** + * This method adds a list of data points to the provider. Beware that this method provokes reclustering of the whole data set. + * @param dataPoints {Array} + */ + addDataPoints(dataPoints: Array): void; + + /** + * This method removes a data point from the provider. Beware that this method provokes reclustering of the whole data set. + * @param dataPoint {H.clustering.DataPoint} + */ + removeDataPoint(dataPoint: H.clustering.DataPoint): void; + + /** + * This method returns current theme used for creating cluster visualization + * @returns {H.clustering.ITheme} + */ + getTheme(): H.clustering.ITheme; + + /** + * This method sets new theme on the provider. Calling this method will change visuals for displayed clusters and noise points. + * @param theme {H.clustering.ITheme} + */ + setTheme(theme: H.clustering.ITheme): void; + + /** + * This method always returns true as we don't have information about visual representation until we have the clustering result and apply the theme. + * @returns {boolean} + */ + providesDomMarkers(): boolean; + + /** + * Returns all DomMarker cluster and noise point representations which intersect with the provided rectangular area. + * @param bounds {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestDomMarkers(bounds: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * This method always returns true as we don't have information about visual representation until we have the clustering result and apply the theme. + * @returns {boolean} + */ + providesMarkers(): boolean; + + /** + * Returns all cluster and noise point markers which intersect with the provided rectangular area. + * @param bounds {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestMarkers(bounds: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * This method always returns true as we don't have information about visual representation until we have the clustering result and apply the theme. + * @returns {boolean} + */ + providesSpatials(): boolean; + + /** + * Returns all polyline, polygon, circle and rect objects which represent cluster and noise points and intersect with the provided area. + * @param bounds {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestSpatials(bounds: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Returns the spatial objects which intersect the given tile + * @param tile {H.map.provider.SpatialTile} - The tile for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestSpatialsByTile(tile: H.map.provider.Tile, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Returns the accumulate invalidations of this provider's objects that have occurred. + * @returns {H.map.provider.Invalidations} - an invalidations object + */ + getInvalidations(): H.map.provider.Invalidations; + + /** + * To signal to this provider that a map object has been changed. The method updates the Invalidations of this provider and the given map object and triggers dispatchUpdate() + * @param mapObject {!H.map.Object} - The map object to be invalidated + * @param changes {H.math.BitMask} - The flags indicating the types of occurred changes + */ + invalidateObject(mapObject: H.map.Object, changes: H.math.BitMask): void; + + min: number; + max: number; + } + + export module Provider { + /** + * Options which are used within cluster calculations. + * @property eps {number=} - epsilon parameter for cluster calculation. For the FASTGRID strategy it must not exceed 256 and must take values that are power of 2. For the GRID and DYNAMICGRID strategies it can take values from 10 to 127. Default is 32. + * @property minWeight {number=} - the minimum points weight sum to form a cluster, default is 2 + * @property projection {H.geo.IProjection=} - projection to use for clustering, default is H.geo.mercator + * @property strategy {H.clustering.Provider.Strategy=} - clustering stretegy, defaults to H.clustering.Provider.Strategy.FASTGRID + */ + export interface ClusteringOptions { + eps?: number; + minWeight?: number; + projection?: H.geo.IProjection; + strategy?: H.clustering.Provider.Strategy; + } + + /** + * Options which are used to initialize the clustering Provider + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property clusteringOptions {H.clustering.Provider.ClusteringOptions=} - options for clustering algorithm + * @property theme {H.clustering.ITheme=} - cluster and noise point graphical representation + */ + export interface Options { + min?: number; + max?: number; + clusteringOptions?: H.clustering.Provider.ClusteringOptions; + theme?: H.clustering.ITheme; + } + + /** + * Enumeration represents possible clustering strategies. FASTGRID clustering is the efficient way to cluster large sets of data points. GRID clustering is slower but has greater precision due to the bigger range of epsilon values, this strategy suitable for clustering smaller data sets (up to 1000 data points) on desktop devices. DYNAMICGRID clustering uses the same algorithm of clustering as the GRID, but clusters on the viewport basis is meant to be used with data sets that are subject to the frequent update operations. + */ + export enum Strategy { + FASTGRID, + GRID, + DYNAMICGRID, + } + } + } + + /***** data *****/ + export module data { + /** + * An abstract reader class defines interface for data readers and has general functionality related to fetching data and reader events. + */ + export class AbstractReader extends H.util.EventTarget { + /** + * Constructor + * @param opt_url {string=} + */ + constructor(opt_url?: string); + + /** + * Method returns H.map.layer.ObjectLayer that contains parsed data, and can be added directly to the map. It returns new instance of the class with every invocation. If data hasn't been parsed it will return H.map.layer.ObjectLayer that contains partial information, and reader will add new parsed objects to the layer's provider later on. + * @returns {H.map.layer.ObjectLayer} + */ + getLayer(): H.map.layer.ObjectLayer; + + /** + * Method returns collection of currently parsed, and converted to H.map.Object data objects. Method returns only currently parsed objects if parsing is ongoing. + * @returns {Array} + */ + getParsedObjects(): Array; + + /** + * Returns URL of the current file, which is either in process of fetching/parsing or file that has been already parsed. + * @returns {(string | undefined)} - url + */ + getUrl(): string | void; + + /** + * Method sets reader's URL. Method resets current Reader's state to its initial values (clears data about last parsed objects, etc.), and throws InvalidState exception if Reader's state is not READY or ERROR. + * @param url {string} - The new URL + * @returns {H.data.AbstractReader} + */ + setUrl(url: string): H.data.AbstractReader; + + /** + * Returns the reader's processing state for possible states see H.data.AbstractReader.State + * @returns {H.data.AbstractReader.State} + */ + getState(): H.data.AbstractReader.State; + + /** + * Method launches parsing of the data file at the current url (see H.data.AbstractReader#setUrl or H.data.AbstractReader). Method uses XHR as a transport therefore same origin policy applies, or server should respond with proper CORS headers. + */ + parse(): void; + } + + export module AbstractReader { + /** + * The event class for state events that are dispatched by AbstractReader + */ + export class Event extends H.util.Event { + /** + * Constructor + * @param target {(H.data.AbstractReader | H.map.Object)} - The target that's passed to event listeners + * @param type {string} - The type of the event + * @param state {H.data.AbstractReader.State} - The state of the target firing an event + * @param message {string} - The message associated with an event + */ + constructor(target: (H.data.AbstractReader | H.map.Object), type: string, state: H.data.AbstractReader.State, message: string); + } + + /** + * The state types of an Reader. Possible states are: + */ + export enum State { + ERROR, + LOADING, + VISIT, + READY, + } + } + } + + /***** geo *****/ + export module geo { + /** + * A Geographic coordinate that specifies the height of a point in meters. A value of undefined is treated as 0. + */ + export type Altitude = number; + + /** + * Contexts for altitudes to specify the contextual origin of an altitude's value + */ + export enum AltitudeContext { + /** Ground level */ + undefined, + /** Ground level */ + GL, + /** Obstruction level */ + OL, + /** Mean sea level */ + SL, + /** Sea bed level */ + SB, + /** WGS84 ellipsoid */ + WE, + /** WGS84 geoid */ + WG, + } + + /** + * An interface to represent a geographic point. Every point in geo space is represented by three coordinates latitude, longitude and optional altitude. + * @property lat {H.geo.Latitude} - The latitude coordinate. + * @property lng {H.geo.Longitude} - The longitude coordinate. + * @property alt {H.geo.Altitude=} - The altitude coordinate. + * @property ctx {H.geo.AltitudeContext=} - The altitude context. + */ + export interface IPoint { + lat: H.geo.Latitude; + lng: Longitude; + alt?: H.geo.Altitude; + ctx?: H.geo.AltitudeContext; + } + + export interface IProjection { + latLngToPoint(lat: number, lng: number, opt_out?: H.math.Point): H.math.Point; + xyToGeo(x: number, y: number, opt_out?: H.geo.Point): H.geo.Point; + pointToGeo(point: H.math.IPoint, opt_out?: H.geo.Point): H.geo.Point; + geoToPoint(geoPoint: H.geo.IPoint, opt_out?: H.math.Point): H.math.Point; + } + + /** + * A geographic coordinate that specifies the north-south position of a point on the Earth's surface in the range from -90 to + 90 degrees, inclusive. + */ + export type Latitude = number; + + /** + * A Geographic coordinate that specifies the east-west position of a point on the Earth's surface in the range from -180 to 180 degrees, inclusive. + */ + export type Longitude = number; + + /** + * Class represents a geographical point, which is defined by the latitude, longitude and optional altitude. + * @property lat {H.geo.Latitude} - The latitude coordinate. + * @property lng {H.geo.Longitude} - The longitude coordinate. + * @property alt {H.geo.Altitude} - The altitude coordinate. + * @property ctx {H.geo.AltitudeContext} - The altitude context. + */ + export class Point implements IPoint { + /** + * Constructor + * @property lat {H.geo.Latitude} - The latitude coordinate. + * @property lng {H.geo.Longitude} - The longitude coordinate. + * @property opt_alt {H.geo.Altitude=} - The altitude coordinate. + * @property opt_ctx {H.geo.AltitudeContext=} - The altitude context. + */ + constructor(lat: H.geo.Latitude, lng: Longitude, opt_alt?: H.geo.Altitude, opt_ctx?: H.geo.AltitudeContext); + + /** + * To compare this point with a supplied other point for equality. Two points are considered equal if they have the same lat and lng as well as equivalent values for alt and ctx. + * @param other {H.geo.IPoint} + * @returns {boolean} - Whether the two points are equal. + */ + equals(other: IPoint): boolean; + + /** + * To calculate the distance between this point and the supplied other point. The method uses the Haversine formula. The altitude is not considered. + * @param other {H.geo.IPoint} + * @returns {number} - The distance between the given location and the location supplied by the caller in meters. + */ + distance(other: IPoint): number; + + /** + * This method calculates the geographic point of a destination point using the distance and bearing specified by the caller. The altitude is ignored, instead the WGS84 Mean Radius is taken. + * @param bearing {number} - The bearing to use in the calculation in degrees. + * @param distance {number} - The distance to the destination in meters. + * @param opt_overGreatCircle {boolean=} - If true the computation uses the 'Great Circle' otherwise 'Rhumb Line'. + * @returns {H.geo.Point} - The calculated point + */ + walk(bearing: number, distance: number, opt_overGreatCircle?: boolean): Point; + + /** + * This method validates the given IPoint. It checks, if lat, lng, alt and ctx have valid types. Additionally the value of the lat property is clamped into a range of -90 ... +90 and the value of the lng property is modulo into a range of -180 ... +180 plus validates the values of the alt and ctx properties + * @param point {H.geo.IPoint} - The point to validate + * @param opt_caller {Function=} - The caller to use for InvalidArgumentError. If omitted no error is thrown + * @param opt_argNr {number=} - The argument number to use for InvalidArgumentError. + * @returns {boolean} - if the given point could validate + */ + static validate(point: IPoint, opt_caller?: Function, opt_argNr?: number): boolean; + + /** + * This method creates a Point instance from a given IPoint object. + * @param iPoint {H.geo.IPoint} - The IPoint object to use + * @returns {H.geo.Point} - the created Point instance + */ + static fromIPoint(iPoint: IPoint): Point; + + lat: H.geo.Latitude; + lng: H.geo.Longitude; + alt: H.geo.Altitude; + ctx: H.geo.AltitudeContext; + } + + /** + * This class represents a rectangular geographic area. The area is defined by four geographical coordinates two (left, right) longitudes and two (top, bottom) latitudes. + */ + export class Rect { + /** + * Constructor + * @param top {H.geo.Latitude} - the northern-most latitude + * @param left {H.geo.Longitude} - the left-most longitude + * @param bottom {H.geo.Latitude} - the southern-most latitude + * @param right {H.geo.Longitude} - the right-most latitude + */ + constructor(top: H.geo.Latitude, left: H.geo.Longitude, bottom: H.geo.Latitude, right: H.geo.Longitude); + + /** + * To compare this rectangle with a supplied other rectangle for equality. + * @param other {H.geo.Rect} + * @returns {boolean} - Whether the two rectangles are equal. + */ + equals(other: H.geo.Rect): boolean; + + /** + * Toclone this rectangle. + * @returns {H.geo.Rect} + */ + clone(): H.geo.Rect; + + /** + * This method returns the top-left corner of the rectangular area. + * @returns {H.geo.Point} - the top-left corner of the area + */ + getTopLeft(): H.geo.Point; + + /** + * This method returns the bottom-right corner of the rectangular area. + * @returns {H.geo.Point} - the bottom-right corner of the area + */ + getBottomRight(): H.geo.Point; + + /** + * This method returns the north-most latitude of this rectangular area + * @returns {H.geo.Latitude} - the north-most latitude of the area + */ + getTop(): H.geo.Latitude; + + /** + * This method returns the south-most latitude of this rectangular area + * @returns {H.geo.Latitude} - the south-most latitude of the area + */ + getBottom(): H.geo.Latitude; + + /** + * This method returns the left-most longitude of this rectangular area + * @returns {H.geo.Longitude} - the left-most longitude of the area + */ + getLeft(): H.geo.Longitude; + + /** + * This method returns the right-most longitude of this rectangular area + * @returns {H.geo.Longitude} - the right-most longitude of the area + */ + getRight(): H.geo.Longitude; + + /** + * This method returns the center point of this rectangular area + * @returns {H.geo.Point} - the center point of the area + */ + getCenter(): H.geo.Point; + + /** + * Returns this width of this rectangular area in decimal degrees. + * @returns {number} - the width of this area + */ + getWidth(): number; + + /** + * Returns this height of this rectangular area in decimal degrees. + * @returns {number} - the height of this area + */ + getHeight(): number; + + /** + * Returns a boolean value indicating whether this rectangular area spans across the date border. + * @returns {boolean} - true if the area spans across the date border, otherwise false + */ + isCDB(): boolean; + + /** + * The method checks if the area enclosed by the given bounding box is 0. + * @returns {boolean} - true if the dimensions of the area a 0, otherwise false + */ + isEmpty(): boolean; + + /** + * This method checks if the latitude and longitude supplied by the caller lie within the area of this rectangular area. + * @param lat {H.geo.Latitude} - the latitude + * @param lng {H.geo.Longitude} - the longitude + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {boolean} - true if the latitude and longitude are contained in this area, otherwise false + */ + containsLatLng(lat: H.geo.Latitude, lng: H.geo.Longitude, opt_skipValidation?: boolean): boolean; + + /** + * This method checks if the point supplied by the caller lies within the area of this rectangular area. + * @param geoPoint {H.geo.IPoint} - the point + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {boolean} - true if the point is contained in this area, otherwise false + */ + containsPoint(geoPoint: H.geo.IPoint, opt_skipValidation?: boolean): boolean; + + /** + * This method checks if the rectangular area supplied by the caller is completely contained within the area of this rectangular area. + * @param geoRect {H.geo.Rect} - the rectangular area + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {boolean} - true if the rectangular area is contained in this area, otherwise false + */ + containsRect(geoRect: H.geo.Rect, opt_skipValidation?: boolean): boolean; + + /** + * This method returns the smallest bounding box that covers this rectangular area and the latitude and longitude supplied by the caller. + * @param lat {H.geo.Latitude} - the latitude + * @param lng {H.geo.Longitude} - the longitude + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - either the rectangular area passed as out parameter or a new rectangular area + */ + mergeLatLng(lat: H.geo.Latitude, lng: H.geo.Longitude, opt_skipValidation?: boolean, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method returns the smallest bounding box that covers this rectangular area and the point supplied by the caller. + * @param geoPoint {H.geo.IPoint} - the point to merge + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - either the rectangular area passed as out parameter or a new rectangular area + */ + mergePoint(geoPoint: H.geo.IPoint, opt_skipValidation?: boolean, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method returns the smallest bounding box that covers this rectangular area and the rectangular area supplied by the caller. + * @param geoRect {H.geo.Rect} - the point to merge + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - either the rectangular area passed as out parameter or a new rectangular area + */ + mergeRect(geoRect: H.geo.Rect, opt_skipValidation?: boolean, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method returns the smallest bounding box that covers this rectangular area and the rectangular area supplied by the caller. + * @param top {H.geo.Latitude} - The top latitude of the rectangle to merge + * @param left {H.geo.Longitude} - The left longitude of the rectangle to merge + * @param bottom {H.geo.Latitude} - The bottom latitude of the rectangle to merge + * @param right {H.geo.Longitude} - The right longitude of the rectangle to merge + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - either the rectangular area passed as out parameter or a new rectangular area + */ + mergeTopLeftBottomRight(top: H.geo.Latitude, left: H.geo.Longitude, bottom: H.geo.Latitude, right: H.geo.Longitude, opt_skipValidation?: boolean, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method checks if the intersection of two bounding boxes is non-empty. + * @param geoRect {H.geo.Rect} - a rectangular area to be tested for intersection with this rectangular area + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {boolean} - a boolean value indicating whether the two areas intersect + */ + intersects(geoRect: H.geo.Rect, opt_skipValidation?: boolean): boolean; + + /** + * This method merges two rects by their values. The result of the merge is a bounding rect which covers all provided rect bounds. + * @param topA {H.geo.Latitude} - the northern-most latitude + * @param leftA {H.geo.Longitude} - the left-most longitude of operand A + * @param bottomA {H.geo.Latitude} - the southern-most latitude of operand A + * @param rightA {H.geo.Longitude} - the right-most latitude of operand A + * @param topB {H.geo.Latitude} - the northern-most latitude of operand B + * @param leftB {H.geo.Longitude} - the left-most longitude of operand B + * @param bottomB {H.geo.Latitude} - the southern-most latitude of operand B + * @param rightB {H.geo.Longitude} - the right-most latitude of operand B + * @param opt_out {H.geo.Rect=} - an optional rect to store the results + * @returns {H.geo.Rect} - either the opt_out rect or a new rect + */ + static merge(topA: H.geo.Latitude, leftA: H.geo.Longitude, bottomA: H.geo.Latitude, rightA: H.geo.Longitude, topB: H.geo.Latitude, leftB: H.geo.Longitude, bottomB: H.geo.Latitude, rightB: H.geo.Longitude, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method creates a rectangular area from a top-left and bottom-right point pair. + * @param topLeft {H.geo.IPoint} - the top-left corner of the area + * @param bottomRight {H.geo.IPoint} - the bottom-right corner of the area + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {H.geo.Rect} - returns the rectangular area defined by the top-left and bottom-right corners + */ + static fromPoints(topLeft: H.geo.IPoint, bottomRight: H.geo.IPoint, opt_skipValidation?: boolean): H.geo.Rect; + + /** + * This method creates the minimum rectangular area covering all of the points in the argument array. + * @param pointArray {Array} - the array of points to cover + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {H.geo.Rect} - returns the minimum rectangular area covering the points or null if no point is covered + */ + static coverPoints(pointArray: Array, opt_skipValidation?: boolean): H.geo.Rect; + + /** + * This method creates the minimum rectangular area covering all of the coordinates in the argument array. + * @param latLngAltArray {Array} - the array of coordinates to cover + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {(H.geo.Rect | undefined)} - returns the minimum rectangular area covering the coordinates + */ + static coverLatLngAlts(latLngAltArray: Array, opt_skipValidation?: boolean): H.geo.Rect | void; + + /** + * This method creates the minimum rectangular area covering all of the rectangular areas in the argument array. + * @param rectArray {Array} - the array of points to cover + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {(H.geo.Rect | undefined)} - returns the minimum rectangular area covering the rectangular areas + */ + static coverRects(rectArray: Array, opt_skipValidation?: boolean): H.geo.Rect | void; + + /** + * This method clones the given bounding rect and resizes the clone if necessary until the location supplied by the caller is at its center. + * @param center {H.geo.IPoint} - a point which is to be the center of the resized rectangular area + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - the resized rectangular area + */ + resizeToCenter(center: H.geo.IPoint, opt_out?: H.geo.Rect): H.geo.Rect; + } + + /** + * A strip is a flat list of latitude, longitude, altitude tuples in a fixed order. + */ + export class Strip { + /** + * Constructor + * @param opt_latLngAlts {Array=} - An optional array of latitude, longitude and altitude triples to initialize the strip with. + * @param opt_ctx {H.geo.AltitudeContext=} - An optional altitude context for all altitudes contained in this strip. + */ + constructor(opt_latLngAlts?: Array, opt_ctx?: H.geo.AltitudeContext); + + /** + * This method pushes a lat, lng, alt to the end of this strip. + * @param lat {H.geo.Latitude} + * @param lng {H.geo.Longitude} + * @param alt {H.geo.Altitude} + */ + pushLatLngAlt(lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude): void; + + /** + * This method splices the strip at the provided index, removing the specified number of items at that index and inserting the lat, lng, alt array. + * @param index {number} - The index at which to splice + * @param opt_nRemove {number=} - The number of lat, lng, alt values to remove + * @param opt_latLngAlts {Array=} - The lat, lng, alt values to add + * @returns {Array} - an array of removed elements + */ + spliceLatLngAlts(index: number, opt_nRemove?: number, opt_latLngAlts?: Array): Array; + + /** + * This method inserts one set of lat, lng, alt values into the strip at the specified index. + * @param index {number} - the index at which to add the element + * @param lat {H.geo.Latitude} - the latitude to insert + * @param lng {H.geo.Longitude} - the longitude to insert + * @param alt {H.geo.Altitude} - the altitude to insert + */ + insertLatLngAlt(index: number, lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude): void; + + /** + * This method removes one set of lat, lng, alt values from the strip at the specified index. + * @param index {number} + */ + removeLatLngAlt(index: number): void; + + /** + * This method pushes the lat, lng, alt values of a H.geo.Point to the end of this strip. + * @param geoPoint {H.geo.IPoint} + */ + pushPoint(geoPoint: H.geo.IPoint): void; + + /** + * This method inserts the lat, lng, alt values of a H.geo.Point into the list at the specified index. + * @param pointIndex {number} + * @param geoPoint {H.geo.IPoint} + */ + insertPoint(pointIndex: number, geoPoint: H.geo.IPoint): void; + + /** + * This method removes one set of lat, lng, alt values from this strip at the virtual point index specified. + * @param pointIndex {number} - the virtual point index + */ + removePoint(pointIndex: number): void; + + /** + * This method extracts a H.geo.Point from this strip at the virtual point index. If the extracted point has an alt value, the strip's altitude context will be supplied to the point. + * @param pointIndex {number} - the virtual point index in the strip + * @param opt_out {H.geo.Point=} - an optional point object to store the lat, lng, alt values + * @returns {H.geo.Point} - returns either the 'opt_out' point object or a new point object. + */ + extractPoint(pointIndex: number, opt_out?: H.geo.Point): H.geo.Point; + + /** + * This method is a utility method that iterates over the lat, lng, alt array and calls the provided function for each 3 elements passing lat, lng and alt and the virtual point index as arguments. + * @param eachFn {function(H.geo.Latitude, H.geo.Longitude, H.geo.Altitude, number)} - the function to be called for each 3 elements + * @param opt_start {number=} - an optional start index to iterate from + * @param opt_end {number=} - an optional end index to iterate to + */ + eachLatLngAlt(eachFn: (lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude, n: number) => void, opt_start?: number, opt_end?: number): void; + + /** + * This method returns the number of times that legs in this strip cross the date border. + * @param opt_closed {boolean=} - indicates whether the strip is closed (i.e. whether the strip's last and first coordinates form the closing leg of a polygon) + * @returns {number} - the amount of times this strip crosses the date border. + */ + getDBCs(opt_closed?: boolean): number; + + /** + * This method return the number of points stored in this strip. + * @returns {number} - the number of points in this strip + */ + getPointCount(): number; + + /** + * This method returns the internal array keeping the lat, lng, alt values. Modifying this array directly can destroy the integrity of this strip. Use it only for read access. + * @returns {Array} - returns the raw lat, lng, alt values of this strip + */ + getLatLngAltArray(): Array; + + /** + * This method returns the bounding box of this strip. + * @returns {?H.geo.Rect} - this strip's bounding rectangle + */ + getBounds(): H.geo.Rect; + + /** + * This method checks whether two longitudes form a leg which crosses the date border. + * @param lng1 {H.geo.Longitude} - the start longitude of the leg + * @param lng2 {H.geo.Longitude} - the end longitude of the leg + * @returns {boolean} - true if the leg crosses the date border, otherwise false + */ + static isDBC(lng1: H.geo.Longitude, lng2: H.geo.Longitude): boolean; + + /** + * This method initializes a new strip with an array of lat, lng values. Arrays are expected to have an even length with the format [lat, lng, lat, lng, ...]. + * @param latLngs {Array} - the array of lat, lng value. + * @returns {H.geo.Strip} - the strip containing the lat, lng values + */ + static fromLatLngArray(latLngs: Array): H.geo.Strip; + } + } + + /***** lang *****/ + + /***** map *****/ + export module map { + /** + * This class represents marker, which offers a means of identifying a location on the map with an icon. + */ + export class AbstractMarker extends H.map.Object { + /** + * Constructor + * @param position {H.geo.IPoint} - The location of this marker + * @param opt_options {H.map.AbstractMarker.Options=} - The values to initialize this marker + */ + constructor(position: H.geo.IPoint, opt_options?: H.map.AbstractMarker.Options); + + /** + * This method returns this marker's current position. + * @returns {H.geo.Point} - current marker geo position + */ + getPosition(): H.geo.Point; + + /** + * This method sets the marker's current position. + * @param position {H.geo.IPoint} + * @returns {H.map.AbstractMarker} - the marker itself + */ + setPosition(position: H.geo.IPoint): H.map.AbstractMarker; + + /** + * Returns this marker's current icon. + * @returns {!(H.map.Icon | H.map.DomIcon)} + */ + getIcon(): (H.map.Icon | H.map.DomIcon); + + /** + * Sets the marker's current icon. + * @param icon {!(H.map.Icon | H.map.DomIcon)} - The new marker icon + * @returns {H.map.AbstractMarker} - the marker itself + */ + setIcon(icon: (H.map.Icon | H.map.DomIcon)): H.map.AbstractMarker; + } + + export module AbstractMarker { + /** + * Options used to initialize a AbstractMarker + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true. + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property icon {(H.map.Icon | H.map.DomIcon)=} - The icon to use for the visual representation, if omitted a default icon is used. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + icon?: H.map.Icon | H.map.DomIcon; + data?: any; + } + } + + /** + * This class represents style attributes for arrows to be rendered along a polyline. A ArrowStyle instance is always treated as immutable to avoid inconstiencies and must not modified. + */ + export class ArrowStyle { + /** + * Constructor + * @param opt_options {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} + */ + constructor(opt_options?: (H.map.ArrowStyle | H.map.ArrowStyle.Options)); + + /** + * This method checks value-equality with another arrow style. + * @param other {(H.map.ArrowStyle | H.map.ArrowStyle.Options)} - the arrow style to compare with + * @returns {boolean} - true if the arrow styles are value-equal, otherwise false + */ + equals(other: (H.map.ArrowStyle | H.map.ArrowStyle.Options)): boolean; + } + + export module ArrowStyle { + /** + * An object type to specify the style of arrows to render along a polyline + * @property fillColor {string=} - The CSS color value used to fill the arrow shapes. If omitted or the value evaluates to false it defaults to "rgba(255, 255, 255, 0.75)" + * @property width {number=} - The width of the arrow shape. The value is taken as a factor of the width of the line, where the arrow description is applied. If omitted or the value is <= 0 it defaults to 1.2 + * @property length {number=} - The length of the arrow shapes. The value is taken as a factor of the width of the line at the end of which the arrow is drawn. If omitted or the value is <= 0 it defaults to 1.6 + * @property frequency {number=} - The frequency of arrow shapes. The value is taken as factor of the length of the arrow. A value of 1 results in gapless arrows. If omitted or the value is false it defaults to 5 + */ + export interface Options { + fillColor?: string; + width?: number; + length?: number; + frequency?: number; + } + } + + /** + * A Polygon with a circular shape. + */ + export class Circle extends H.map.Polygon { + /** + * Constructor + * @param center {H.geo.IPoint} - The geographical coordinates of the circle's center + * @param radius {number} - The radius of the circle in meters + * @param opt_options {H.map.Circle.Options=} - An object that specifies circle options and their initial values (among these, precision has a significant impact on the shape of the circle - please see + */ + constructor(center: H.geo.IPoint, radius: number, opt_options?: H.map.Circle.Options); + + /** + * To set the geographical center point of this circle. If the specified center is an instance of H.geo.Point you must not modify this Point instance without calling setCenter immediately afterwards. + * @param center {H.geo.IPoint} + */ + setCenter(center: H.geo.IPoint): void; + + /** + * To get the center point of this circle You must not modify the returned Point instance without calling setCenter immediately afterwards. + * @returns {H.geo.Point} + */ + getCenter(): H.geo.Point; + + /** + * To set the length of the radius of the circle in meters. The value is clamped to the of {@code[0 ... 20015089.27787877]} (half WGS84 mean circumference) + * @param radius {number} + */ + setRadius(radius: number): void; + + /** + * To get the length of the radius of the circle in meters. + * @returns {number} + */ + getRadius(): number; + + /** + * To set the precision of this circle {@see H.map.Circle.Options#precision} + * @param precision {number} + */ + setPrecision(precision: number): void; + + /** + * To get the precision value of this circle + * @returns {number} + */ + getPrecision(): number; + } + + export module Circle { + /** + * @property style {H.map.SpatialStyle=} - the style to be used when tracing the polyline + * @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true + * @property precision {number=} - The precision of a circle as a number of segments to be used when rendering the circle. The value is clamped to the range between [4 ... 360], where 60 is the default. Note that the lower the value the more angular and the less circle-like the shape appears and, conversely, the higher the value the smoother and more rounded the result. Thus, starting at the extreme low end of the possible values, 4 produces a square, 6 a hexagon, while 30 results in a circle-like shape, although it appears increasingly angular as the zoom level increases (as you zoom in), and finally 360 produces a smooth circle. + * @property zIndex {number=} - The z-index value of the circle, default is 0 + * @property min {number=} - The minimum zoom level for which the circle is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the circle is visible, default is Infinity + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData + */ + export interface Options { + style?: H.map.SpatialStyle | H.map.SpatialStyle.Options; + visibility?: boolean; + precision?: number; + zIndex?: number; + min?: number; + max?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + + /** + * The class represents data model of the map. It holds list of layers that are rendered by map's RenderEngine. The class listens to 'update' events from layers and dispatches them to the RenderEngine. + */ + export class DataModel extends H.util.OList { + /** + * Constructor + * @param opt_layers {Array=} - array of layers to be added to the data model + */ + constructor(opt_layers?: Array); + } + + /** + * A visual representation of the H.map.DomMarker. + */ + export class DomIcon { + /** + * Constructor + * @param element {!(Element | string)} - The element or markup to use for this icon + * @param opt_options {H.map.DomIcon.Options=} + */ + constructor(element: (Element | string), opt_options?: H.map.DomIcon.Options); + } + + export module DomIcon { + /** + * Options used to initialize a DomIcon + * @property onAttach {function(Element, H.map.DomIcon, H.map.DomMarker)=} - A callback which is invoked before a clone of the icon's element is appended and displayed on the map. This callback can be used to setup the clone. + * @property onDetach {function(Element, H.map.DomIcon, H.map.DomMarker)=} - A callback which is invoked after a clone of the icon's element is removed from the map. This callback can be used to clean up the clone. + */ + export interface Options { + onAttach?: (el: Element, icon: H.map.DomIcon, marker: H.map.DomMarker) => void; + onDetach?: (el: Element, icon: H.map.DomIcon, marker: H.map.DomMarker) => void; + } + } + + /** + * A marker with a visual representation in the form of a full styleable and scripteable DOM element. DomMarker are predestinated if small amounts of markers with dynamic styled and/or scripted icons should be displayed om the map (e.g. animated interactive SVG). + */ + export class DomMarker extends H.map.AbstractMarker { + /** + * Constructor + * @param position {H.geo.IPoint} + * @param opt_options {H.map.DomMarker.Options=} + */ + constructor(position: H.geo.IPoint, opt_options?: H.map.DomMarker.Options); + } + + export module DomMarker { + /** + * Options used to initialize a DomMarker + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true. + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property icon {H.map.DomIcon=} - The icon to use for the visual representation, if omitted a default icon is used. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + icon?: H.map.DomIcon; + data?: any; + } + } + + /** + * This class represents a spatial shape in geographic space. It is defined by a path containing the vertices of the shape (lat, lng, alt values). + */ + export class GeoShape extends H.map.Spatial { + /** + * Constructor + * @param isClosed {boolean} - Indicates whether this geographical shape is closed (a polygon) + * @param strip {H.geo.Strip} - The strip describing the shape of the spatial object + * @param options {H.map.Spatial.Options} - The options to apply + */ + constructor(isClosed: boolean, strip: H.geo.Strip, options: H.map.Spatial.Options); + + /** + * This method returns the strip which represents the shape of the spatial object. + * @returns {H.geo.Strip} - the strip + */ + getStrip(): H.geo.Strip; + + /** + * This method sets the geo-information for the spatial object + * @param strip {?H.geo.Strip} - The strip which represents the shape of the spatial object. + * @returns {H.map.GeoShape} - the Spatial instance itself + */ + setStrip(strip: H.geo.Strip): H.map.GeoShape; + + /** + * This method returns the bounding rectangle for this object. The rectangle is the smallest rectangle which encloses all points of the spatial object. + * @returns {H.geo.Rect} + */ + getBounds(): H.geo.Rect; + } + + /** + * This class represents a map object which can contain other map objects. It's visibility, zIndex and object-order influences the contained map objects + */ + export class Group extends H.map.Object { + /** + * Constructor + * @param opt_options {H.map.Group.Options=} - an optional object containing initialization values + */ + constructor(opt_options?: H.map.Group.Options); + + /** + * + * @param callback {function(!H.map.Object, number, !H.map.Group)} + * @param opt_recursive {boolean=} - Indicates whether sub groups should be traversed recursively + * @param opt_context {*=} - The context to use as "this" within the callback + */ + forEach(callback: (object: H.map.Object, n: number, group: H.map.Group) => void, opt_recursive?: boolean, opt_context?: any): void; + + /** + * To get a list of all objects of this group. On groups with many chilren this method can cause a higher memory and CPU consumption. Alternatively you case use H.map.Group#forEach + * @param opt_recursive {boolean=} - Indicates whether objects in sub-groups are also collected . + * @returns {!Array} + */ + getObjects(opt_recursive?: boolean): Array; + + /** + * Method returns the bounding rectangle for the group. The rectangle is the smallest rectangle that covers all objects. If group doesn't contains objects method returns null. + * @returns {H.geo.Rect} - geo ractangle that covers all objects in the group + */ + getBounds(): H.geo.Rect; + + /** + * To add an object to this group. + * @param object {!H.map.Object} + * @returns {!H.map.Object} - a reference to the appended object + */ + addObject(object: H.map.Object): H.map.Object; + + /** + * Appends a list of objects to this group + * @param objects {Array} + */ + addObjects(objects: Array): void; + + /** + * Removes an object from this group. + * @param object {!H.map.Object} - The object to remove + * @returns {!H.map.Object} - a reference to the removed object + */ + removeObject(object: H.map.Object): H.map.Object; + + /** + * Removes objects from this group. + * @param objects {!Array} - The list of objects to remove + */ + removeObjects(objects: Array): void; + + /** + * Method removes all objects from the group. + */ + removeAll(): void; + } + + export module Group { + /** + * Options used to initialize a group + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + * @property objects {Array=} - A list of map objects to add initially to this group. + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + data?: any; + objects?: Array; + } + } + + /** + * This class represents an area that objects, like a marker, occupies in the screen space, meaning that object can be probed and returned by H.Map@getObjectsAt method. + */ + export class HitArea { + /** + * Constructor + * @param shapeType {H.map.HitArea.ShapeType} - The shape type of the HitArea + * @param opt_values {Array=} - The type-dependent values to define the shape of the hit area. The format for the different types are: + */ + constructor(shapeType: H.map.HitArea.ShapeType, opt_values?: Array); + } + + export module HitArea { + /** + * Enumeration represents possible shape types that HitArea can have. + */ + export enum ShapeType { + NONE, + RECT, + CIRCLE, + POLYGON, + } + } + + /** + * Control interface defines method which are used for direct view or camera manipulation + */ + export interface IControl { + + /** + * This method starts control action for camera. This action allows to control camera animation and movement according to provided values in the H.map.IControl#control function + * @param opt_kinetics {H.util.kinetics.IKinetics=} - kinetics settings + * @param opt_atX {number=} - control starts at x screen coordinate + * @param opt_atY {number=} - control starts at y screen coordinate + */ + startControl(opt_kinetics?: H.util.kinetics.IKinetics, opt_atX?: number, opt_atY?: number): void; + + /** + * This method triggers single control action on engine. This will trigger an animation which will start modification of the view's or camera's properties according to values begin set. Modification will occur at every frame. The speed values are measure by 'levels per frame' were 1 level cooresponds to a distance to next zoom level. + * @param moveX {number} - moves the view/cam in right/left direction + * @param moveY {number} - moves the view/cam in bottom/top direction + * @param moveZ {number} - moves the view/cam in depth direction (changes zoom level) + * @param angleX {number} - rotates cam over x-axis + * @param angleY {number} - rotates cam over y-axis + * @param angleZ {number} - rotates cam over z-axis + * @param zoom {number} - changes current zoom level (for view works as moveZ) + * @param opt_timestamp {number=} + */ + control(moveX: number, moveY: number, moveZ: number, angleX: number, angleY: number, angleZ: number, zoom: number, opt_timestamp?: number): void; + + /** + * This method ends current control, which will stop ongoing animation triggered by the startControl method. This method can prevent kinetics as well as it can adjust the final view if the adjust function is being passed. + * @param opt_preventKinetics {boolean=} - if set to true will prevent kinetics animation + * @param opt_adjustView {function(H.map.ViewModel.CameraData)=} - user defined function which can adjust the final view this function takes last requestedData from the view model and should return a modified H.map.ViewModel.CameraData which will be set as the final view + */ + endControl(opt_preventKinetics?: boolean, opt_adjustView?: (data: H.map.ViewModel.CameraData) => void): void; + } + + /** + * An interface to specify a copyright note + * @property label {string} - A short textual representation of the copyright note, e.g. "DigitalGlobe 2009" + * @property alt {string} - A detailed textual representation of the copyright note, e.g. "copyright 2009 DigitalGlobe, Inc." + */ + export interface ICopyright { + label: string; + alt: string; + } + + /** + * Interface describes interaction with the view port. Interaction will reflect view change depending on the interaction coordinates passed and the modifiers which specify the type of interaction. + */ + export interface IInteraction { + /** + * This method starts the interaction with the view port. Should be called every time when new interaction is started i.e mouse grab, or touch start. + * @param modifiers {number} - a bitmask which specifies what operations should performed during every interaction + * @param opt_kinetics {H.util.kinetics.IKinetics=} - specifies kinetic move at the end of interaction + */ + startInteraction(modifiers: H.math.BitMask, opt_kinetics?: H.util.kinetics.IKinetics): void; + + /** + * This method resolves direct screen (view port) interaction. This function will modify the current view according to values passed in. + * @param x {number} - viewport x coordinate + * @param y {number} - viewport y coordinate + * @param opt_bx {number=} - x coordinate for second pointer/touch if present + * @param opt_by {number=} - y coordinate for secong pointer/touch if present + * @param opt_timestamp {number=} - known timestamp which should be passed + */ + interaction(x: number, y: number, opt_bx?: number, opt_by?: number, opt_timestamp?: number): void; + + /** + * This method ends interaction and applies kinetic movement if defined by using startInteraction method + * @param opt_preventKinetics {boolean=} - if set to true will prevent kinetics behaviour at the end of interaction + */ + endInteraction(opt_preventKinetics?: boolean): void; + } + + /** + * A visual representation of the H.map.Marker. + */ + export class Icon { + /** + * Constructor + * @param bitmap {!(string | HTMLImageElement | HTMLCanvasElement)} - Either an image URL, a SVG markup, an image or a canvas. + * @param opt_options {H.map.Icon.Options=} + */ + constructor(bitmap: (string | HTMLImageElement | HTMLCanvasElement), opt_options?: H.map.Icon.Options); + + /** + * Returns the icon's bitmap loading state + * @returns {H.map.Icon.prototype.State} + */ + getState(): H.map.Icon.State; + + /** + * Returns the bitmap of this icon or null if the bitmap is not ready yet (see H.map.Icon#getState) + * @returns {?(HTMLImageElement | HTMLCanvasElement)} + */ + getBitmap(): (HTMLImageElement | HTMLCanvasElement); + + /** + * Returns the size of this icon or null if a size wasn't specified in the constructor's options and the state of this icon is not H.map.Icon.prototype.State.READY + * @returns {?H.math.Size} + */ + getSize(): H.math.Size; + + /** + * Returns the anchor point of this icon or null if an anchor wasn't specified in the constructor's options and the state of this icon is not H.map.Icon.prototype.State.READY. + * @returns {?H.math.Point} + */ + getAnchor(): H.math.Point; + + /** + * Returns the hit area of the icon. + * @returns {?H.map.HitArea} - icon's anchor point + */ + getHitArea(): H.map.HitArea; + + /** + * This method allows to listen for specific event triggered by the object. Keep in mind, that you must removeEventListener manually or dispose an object when you no longer need it. Otherwise memory leak is possible. + * @param type {string} - name of event + * @param handler {Function} - event handler function + * @param opt_capture {boolean=} - if set to true will listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - scope for the handler function + */ + addEventListener(type: string, handler: Function, opt_capture?: boolean, opt_scope?: Object): void; + + /** + * This method will removed previously added listener from the event target + * @param type {string} - name of event + * @param handler {Function} - previously added event handler + * @param opt_capture {boolean=} - if set to true will listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - scope for the handler function + */ + removeEventListener(type: string, handler: Function, opt_capture?: boolean, opt_scope?: Object): void; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module Icon { + /** + * The state types of an Icon + */ + export enum State { + ERROR, + LOADING, + READY, + } + + /** + * Options used to initialize a Icon + * @property size {H.math.ISize=} - The icon's size in pixel, default is the bitmap's natural size + * @property anchor {H.math.IPoint=} - The anchorage point in pixel, default is bottom-center + * @property hitArea {H.map.HitArea=} - The area to use for hit detection, default is the whole rectangular area + * @property asCanvas {H.map.HitArea=} - Indicates whether a non canvas bitmap is converted into a canvas, default is true. The conversion improves the rendering performance but it could also cause a higher memory consumption. + * @property crossOrigin {boolean} - Specifies whether to use anonynous Cross-Origin Resource Sharing (CORS) when fetching an image to prevent resulting canvas from tainting, default is false. The option is ignored by IE9-10. + */ + export interface Options { + size?: H.math.ISize; + anchor?: H.math.IPoint; + hitArea?: H.map.HitArea; + asCanvas?: H.map.HitArea; + crossOrigin: boolean; + } + } + + /** + * This class encapsulates the brand, copyright and terms of use elements on the map. + */ + export class Imprint { + /** + * Constructor + * @param map {H.Map} - The map where the imprint is attached to + * @param opt_options {H.map.Imprint.Options=} - The options to style the imprint + */ + constructor(map: H.Map, opt_options?: H.map.Imprint.Options); + + /** + * To set the imprint options. If no opt_options argument is defined then all values are reset to their defaults. + * @param opt_options {H.map.Imprint.Options=} - The options to style the imprint + */ + setOptions(opt_options?: H.map.Imprint.Options): void; + + /** + * This method retrieves the copyright string for the current view of the map. + * @returns {string} - The copyright string for the current map view + */ + getCopyrights(): string; + + /** + * To get the CSS style declaration of the imprint DOM element + * @returns {CSSStyleDeclaration} + */ + getStyle(): CSSStyleDeclaration; + + /** + * Method adds a callback which will be triggered when the object is disposed + * @param callback {Function} + * @param opt_scope {Object=} + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + /** + * This method is used to capture the element view + * @param canvas {HTMLCanvasElement} - HTML Canvas element to draw the view of the capturable element + * @param pixelRatio {number} - The pixelRatio to use for over-sampling in cases of high-resolution displays, default is 1 + * @param callback {function(HTMLCanvasElement=)} - Callback function to call once result of the capturing is ready + * @param opt_errback {function(string)=} - Callback function to call if error occurred during capturing + */ + capture(canvas: HTMLCanvasElement, pixelRatio: number, callback?: (canvas: HTMLCanvasElement) => void, opt_errback?: (s: string) => void): void; + } + + export module Imprint { + /** + * Options to style an imprint + * @property invert {boolean=} - Indicates whether the logo is inverted. If omitted the current value remains, default is false. + * @property font {string=} - The font of the text. If omitted the current value remains, default is "11px Arial,sans-serif". + * @property href {string=} - The URL of the "Terms of use" link. If omitted the current value remains, default is "http://here.com/terms". + */ + export interface Options { + invert?: boolean; + font?: string; + href?: string; + } + } + + /** + * A marker with a visual representation in the form of a bitmap icon. Marker are predestinated if large amounts of markers with static icons should be displayed om the map. + */ + export class Marker extends H.map.AbstractMarker { + /** + * Constructor + * @param position {H.geo.IPoint} - The location of this marker + * @param opt_options {H.map.Marker.Options=} - The values to initialize this marker + */ + constructor(position: H.geo.IPoint, opt_options?: H.map.Marker.Options); + } + + export module Marker { + /** + * Options used to initialize a Marker + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true. + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property icon {H.map.Icon=} - The icon to use for the visual representation, if omitted a default icon is used. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + icon?: H.map.Icon; + data?: any; + } + } + + /** + * This class represents the abstract base class for map objects such as polylines, polygons, markers, groups etc. + */ + export class Object extends H.util.EventTarget { + /** + * Constructor + * @param opt_options {H.map.Object.Options=} - The values to initialize this object + */ + constructor(opt_options?: H.map.Object.Options); + + /** + * Returns the ID of this object. + * @returns {*} + */ + getId(): any; + + /** + * Sets the visibility of this object. + * @param opt_visibility {boolean=} - Indicates whether this map object should be visible. + * @returns {H.map.Object} - returns this object + */ + setVisibility(opt_visibility?: boolean): H.map.Object; + + /** + * Returns the visibility of this object. + * @param opt_effective {boolean=} - Indicates that the effective visibility is requested. In this case the visibility of all possible ancestor groups is also taken into account + * @returns {boolean} + */ + getVisibility(opt_effective?: boolean): boolean; + + /** + * Returns the z-index of this object. + * @returns {(number | undefined)} + */ + getZIndex(): number | void; + + /** + * To set the-index of this object. + * @param zIndex {(number | undefined)} + * @returns {H.map.Object} - returns this object + */ + setZIndex(zIndex?: number): H.map.Object; + + /** + * Compares two objects regarding their z-order, useful to sort a list of objects via Array's sort() method + * @param first {H.map.Object} - The first object to compare + * @param second {H.map.Object} - The second object to compare + * @returns {number} - If less then 0 the first object has a lower z-order. If equal 0 booth objects have the same z-order. If greater then 0 the first object has a higher z-order. + */ + static compareZOrder(first: H.map.Object, second: H.map.Object): number; + + /** + * Returns the parent group which contains this object or null if the object is not contained by any group. + * @returns {?H.map.Group} + */ + getParentGroup(): H.map.Group; + + /** + * The root object in which this object is attached or the object itself. + * @returns {!H.map.Object} + */ + getRootGroup(): H.map.Object; + + /** + * Checks whether the given object is an inclusive descendant of this object + * @param object {*} - The object that's being compared against. + * @returns {boolean} + */ + contains(object: any): boolean; + + /** + * The current provider of this object + * @returns {?H.map.provider.ObjectProvider} - the current provider + */ + getProvider(): H.map.provider.ObjectProvider; + + /** + * Returns the invalidations of this object + * @returns {H.map.provider.Invalidations} - an invalidation object + */ + getInvalidations(): H.map.provider.Invalidations; + + /** + * This method invalidates this map object. + * @param flags {H.math.BitMask} - The flags indicating the types of occurred changes + * @returns {boolean} - indicates whether a validtion was executed (only if the object has a provider) + */ + invalidate(flags: H.math.BitMask): boolean; + + /** + * This method returns previously stored arbitrary data from this object. + * @returns {*} - the previously stored data or undefined if not data was stored. + */ + getData(): any; + + /** + * This method stores arbitrary data with this map object + * @param data {*} - the data to be stored + * @returns {H.map.Object} - returns this map object instance + */ + setData(data: any): H.map.Object; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module Object { + /** + * Options used to initialize a map object + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + data?: any; + } + + /** + * The major types of map objects + */ + export enum Type { + /** spatial object */ + ANY, + /** spatial object */ + OVERLAY, + /** spatial object */ + SPATIAL, + /** Marker object */ + MARKER, + /** DomMarker object */ + DOM_MARKER, + /** DomMarker object */ + GROUP, + } + } + + /** + * This class represents an overlay, which offers a bitmap that covers a geographical reactangular area on the map. + */ + export class Overlay extends H.map.Object { + /** + * Constructor + * @param bounds {H.geo.Rect} - The geographical reactangular area of this overlay + * @param bitmap {!(string | HTMLImageElement | HTMLCanvasElement)} - Either an image URL, a SVG markup, an image or a canvas. + * @param opt_options {H.map.Overlay.Options=} - Optional values values to initialize this overlay + */ + constructor(bounds: H.geo.Rect, bitmap: (string | HTMLImageElement | HTMLCanvasElement), opt_options?: H.map.Overlay.Options); + + /** + * This method returns this overlay's current bounds. + * @returns {H.geo.Rect} + */ + getBounds(): H.geo.Rect; + + /** + * This method sets the overlay's current bounds. + * @param bounds {H.geo.Rect} + * @returns {H.map.Overlay} - the overlay itself + */ + setBounds(bounds: H.geo.Rect): H.map.Overlay; + + /** + * Returns this overlay's current bitmap. + * @returns {?(HTMLImageElement | HTMLCanvasElement)} - the bitmap of this Overlay or null if it isn't ready yet + */ + getBitmap(): (HTMLImageElement | HTMLCanvasElement); + + /** + * Sets the overlay's current bitmap. + * @param bitmap {!(string | HTMLImageElement | HTMLCanvasElement)} - Either an image URL, a SVG markup, an image or a canvas. + * @returns {H.map.Overlay} - the overlay itself + */ + setBitmap(bitmap: (string | HTMLImageElement | HTMLCanvasElement)): H.map.Overlay; + + /** + * Returns this overlay's current opacity. + * @returns {number} + */ + getOpacity(): number; + + /** + * Sets the overlay's current opacity. + * @param opacity {number} - The opacity in range from 0 (transparent) to 1 (opaque). + * @returns {H.map.Overlay} - the overlay itself + */ + setOpacity(opacity: number): H.map.Overlay; + } + + export module Overlay { + /** + * Options used to initialize an Overlay + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property opacity {number=} - The opacity of the object in range from 0 (transparent) to 1 (opaque), default is 1. + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true. + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + min?: number; + max?: number; + opacity?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + + /** + * This class represents a polygon in geo-space. It is defined by a strip containing the vertices of a geo shape object (lat, lng, alt values) and a pen to use when rendering the polyline. Polygon represents a closed plane defined by the list of verticies, projected on the map display. List of vericies which define the polygon are is a list of geo coordinates encapsulated by the strip object H.geo.Strip + */ + export class Polygon extends H.map.GeoShape { + /** + * Constructor + * @param strip {H.geo.Strip} - the strip describing this polygon's vertices + * @param opt_options {H.map.Spatial.Options=} - optional initialization parameters + */ + constructor(strip: H.geo.Strip, opt_options?: H.map.Spatial.Options); + + /** + * To set the indicator whether this polygon covers the north pole. It's needed for Polygons whose strip is defined as lines arround the world on longitude axis (for example a circle whose center is one of the poles). In this case a additional information is needed to know if the southern or northern part of the world should be covered by the poygon. + * @param flag {boolean} - A value of true means it covers the north pole, false means south pole + * @returns {H.map.Polygon} - the Polygon instance itself + */ + setNorthPoleCovering(flag: boolean): H.map.Polygon; + + /** + * See H.map.Polygon#setNorthPoleCovering + * @returns {boolean} + */ + getNorthPoleCovering(): boolean; + } + + /** + * This class represents a polyline in geo-space. It is defined by a path containing the vertices of a polyline (lat, lng, alt values) and a pen to use when tracing the path on the map. + */ + export class Polyline extends H.map.GeoShape { + /** + * Constructor + * @param strip {H.geo.Strip} - the strip describing this polygon's vertices + * @param opt_options {H.map.Polyline.Options=} - optional initialization parameters + */ + constructor(strip: H.geo.Strip, opt_options?: H.map.Polyline.Options); + + /** + * This method clips this polyline against a rectangular area and returns the intersecting sub-lines. + * @param geoRect {H.geo.Rect} + * @returns {Array>} + */ + clip(geoRect: H.geo.Rect): Array>; + } + + export module Polyline { + /** + * Options which are used to initialize a polyline + * @property style {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - the style to be used when tracing the polyline + * @property arrows {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} - The arrows style to be used when rendering the polyline. + * @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData + */ + export interface Options { + style?: (H.map.SpatialStyle | H.map.SpatialStyle.Options); + arrows?: (H.map.ArrowStyle | H.map.ArrowStyle.Options); + visibility?: boolean; + zIndex?: number; + min?: number; + max?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + + /** + * A Polygon with a rectangular shape. + */ + export class Rect extends H.map.Polygon { + /** + * Constructor + * @param bounds {H.geo.Rect} - The geographical bounding box for this rectangle + * @param opt_options {H.map.Spatial.Options=} + */ + constructor(bounds: H.geo.Rect, opt_options?: H.map.Spatial.Options); + + /** + * To set the bounds of this rectangle. + * @param bounds {H.geo.Rect} + */ + setBounds(bounds: H.geo.Rect): void; + } + + /** + * This class represents a spatial map object which provides its projected geometry. + */ + export class Spatial extends H.map.Object { + /** + * Constructor + * @param isClosed {boolean} - Indicates whether this spatial object represents a closed shape + * @param opt_options {H.map.Spatial.Options=} - The options to apply + */ + constructor(isClosed: boolean, opt_options?: H.map.Spatial.Options); + + /** + * To get the drawing style of this object. The returned style is treated as immutable and must not be modified afterwards to prevent inconsistancies! + * @returns {H.map.SpatialStyle} + */ + getStyle(): H.map.SpatialStyle; + + /** + * To set the drawing style of this object. If the passed opt_style argument is an instance of H.map.SpatialStyle it is treated as immutable and must not be modified afterwards to prevent inconsistancies! . + * @param opt_style {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - The style to set. If it evaluates to a falsy the H.map.SpatialStyle.DEFAULT_STYLE is used. + * @returns {H.map.Spatial} - the Spatial instance itself + */ + setStyle(opt_style?: (H.map.SpatialStyle | H.map.SpatialStyle.Options)): H.map.Spatial; + + /** + * To get the arrow style of this spatial object or undefined if no style is defined. A returned arrow style is treated as immutable and must not be modified afterwards to prevent inconsistancies! + * @returns {(H.map.ArrowStyle | undefined)} + */ + getArrows(): H.map.ArrowStyle | void; + + /** + * To set the arrow style of this object. + * @param opt_arrows {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} - the arrow style to be applied + * @returns {H.map.Spatial} - the Spatial instance itself + */ + setArrows(opt_arrows?: (H.map.ArrowStyle | H.map.ArrowStyle.Options)): H.map.Spatial; + + /** + * Indicates whether this spatial object represents a closed shape + * @returns {boolean} + */ + isClosed(): boolean; + } + + export module Spatial { + /** + * Data to used as rendering hint for a label + * @property x {number} - The X coordinate of the first line's starting point + * @property y {number} - The Y coordinate of the first line's base line + * @property angle {number} - The clockwise rotation angle in radians + * @property font {string} - The CSS font-family + * @property size {number} - The CSS font-size + * @property color {string} - The CSS color + * @property text {string} - The text content, new line characters (\u000A) are interpreted as line breaks + */ + export interface Label { + x: number; + y: number; + angle: number; + font: string; + size: number; + color: string; + text: string; + } + + /** + * Options which are used to initialize spatial object object + * @property style {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - the style to be used when tracing the spatial object + * @property arrows {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} - The arrows style to be used when rendering the spatial. + * @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + style?: (H.map.SpatialStyle | H.map.SpatialStyle.Options); + arrows?: (H.map.ArrowStyle | H.map.ArrowStyle.Options); + visibility?: boolean; + zIndex?: number; + min?: number; + max?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + + /** + * The SpatialStyle class represents a style with which spatial objects like polylines and polygons are drawn. A SpatialStyle instance is always treated as immutable to avoid inconstiencies and must not modified. + * @property strokeColor {string} - The color of the stroke in CSS syntax, default is 'rgba(0, 85, 170, 0.6)'. + * @property fillColor {string} - The filling color in CSS syntax, default is 'rgba(0, 85, 170, 0.4)'. + * @property lineWidth {number} - The width of the line in pixels, default is 2. + * @property lineCap {H.map.SpatialStyle.LineCap} - The style of the end caps for a line, default is 'round'. + * @property lineJoin {H.map.SpatialStyle.LineJoin} - The type of corner created, when two lines meet, default is 'miter'. + * @property miterLimit {number} - The miter length is the distance between the inner corner and the outer corner where two lines meet. The default is 10. + * @property lineDash {Array} - The line dash pattern as an even numbered list of distances to alternately produce a line and a space. The default is [ ]. + * @property lineDashOffset {number} - The phase offset of the line dash pattern The default is 0. + * @property MAX_LINE_WIDTH {number} - This constant represents the maximum line width which can be used for rendering. + * @property DEFAULT_STYLE {H.map.SpatialStyle} - This static member defines the default style for spatial objects on the map. It's value is { strokeColor: '#05A', fillColor: 'rgba(0, 85, 170, 0.4)' lineWidth: 1, lineCap: 'round', lineJoin: 'miter', miterLimit: 10, lineDash: [ ], lineDashOffset: 0 } + */ + export class SpatialStyle { + /** + * Constructor + * @param opt_options {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - The optional style attributes + */ + constructor(opt_options?: (H.map.SpatialStyle | H.map.SpatialStyle.Options)); + + /** + * This method checks value-equality with another style. + * @param other {(H.map.SpatialStyle | H.map.SpatialStyle.Options)} - the style to compare with + * @returns {boolean} - true if the styles are value-equal, otherwise false + */ + equals(other: (H.map.SpatialStyle | H.map.SpatialStyle.Options)): boolean; + + /** + * Returns a copy of spatial style object and replaces the passed style attributes into it. + * @param opt_attributes {H.map.SpatialStyle.Options=} - The style attributes to set on the copied style instance + * @returns {H.map.SpatialStyle} + */ + getCopy(opt_attributes?: H.map.SpatialStyle.Options): H.map.SpatialStyle; + + strokeColor: string; + fillColor: string; + lineWidth: number; + lineCap: H.map.SpatialStyle.LineCap; + lineJoin: H.map.SpatialStyle.LineJoin; + miterLimit: number; + lineDash: Array; + lineDashOffset: number; + static MAX_LINE_WIDTH: number; + static DEFAULT_STYLE: H.map.SpatialStyle; + } + + export module SpatialStyle { + /** + * The style of the end caps for a line, one of 'butt', 'round' or 'square'. + */ + export type LineCap = 'butt' | 'round' | 'square'; + + /** + * The type of corner created, when two lines meet, one of 'round', 'bevel' or 'miter'. + */ + export type LineJoin = 'round' | 'bevel' | 'miter'; + + /** + * Options used to initialize a style. If a property is not set, the default value from H.map.SpatialStyle is taken. + * @property strokeColor {string=} - The color of the stroke in CSS syntax. + * @property fillColor {string=} - The color of the stroke in CSS syntax. + * @property lineWidth {number=} - The width of the line in pixels, default is 2. The maximum supported line width is 100. + * @property lineCap {H.map.SpatialStyle.LineCap=} - The style of the end caps for a line. + * @property lineJoin {H.map.SpatialStyle.LineJoin=} - The type of corner created, when two lines meet. + * @property miterLimit {number=} - The miter limit in pixel, default is 10. The maximum supported miter limit is 100 + * @property lineDash {Array} - The line dash pattern as an even numbered list of distances to alternately produce a line and a space. If the browser doesn't support this feature this style property is ignored. + * @property lineDashOffset {number=} - The phase offset of the line dash pattern + */ + export interface Options { + strokeColor?: string; + fillColor?: string; + lineWidth?: number; + lineCap?: H.map.SpatialStyle.LineCap; + lineJoin?: H.map.SpatialStyle.LineJoin; + miterLimit?: number; + lineDash?: Array; + lineDashOffset?: number; + } + } + + /** + * This class represents a view of the map. It consists of a virtual camera and a look-at point both of which have a position in geo-space and orientation angles. The view model allows to change the values of these objects in order to move or rotate the map or zoom in and out. + */ + export class ViewModel extends H.util.EventTarget implements H.map.IControl { + /** + * This method returns the camera data, which is currently rendered. + * @returns {H.map.ViewModel.CameraData} - the current rendered camera data + */ + getCameraData(): H.map.ViewModel.CameraData; + + /** + * This method sets new camera data to be processed by the renderer. + * @param data {H.map.ViewModel.CameraData} - the values to be modified + * @returns {H.map.ViewModel} - this view model object + */ + setCameraData(data: H.map.ViewModel.CameraData): H.map.ViewModel; + + /** + * This method sets a new zoom level to be processed by the renderer + * @param zoom {number} - the new zoom level + * @param animate {boolean} + */ + setZoom(zoom: number, animate: boolean): void; + + /** + * This method returns the zoom level that is currently rendered. + * @returns {number} - current zoom level (scale) + */ + getZoom(): number; + + /** + * This method returns the currently requested data. + * @returns {H.map.ViewModel.CameraData} - last requested cam/view data + */ + getRequestedCameraData(): H.map.ViewModel.CameraData; + + /** + * A method to signal the begin of a control operation. + * @param opt_kinetics {H.util.kinetics.IKinetics=} - kinetics settings + * @param opt_atX {number=} - x screen coordinate at which control has started + * @param opt_atY {number=} - y screen coordinate at which control has started + */ + startControl(opt_kinetics?: H.util.kinetics.IKinetics, opt_atX?: number, opt_atY?: number): void; + + /** + * A method to set the values for a continuously modification of the ViewModel on different axes. If the current render engine doesn't support certain modifications then they are ignored. + * @param moveX {number} - The movement on x-axis as levels per millisecond where a level correlates to the distance between camera and look-at point. + * @param moveY {number} - The movement on y-axis as levels per millisecond where a level correlates to the distance between camera and look-at point + * @param moveZ {number} - The movement on z-axis as levels per millisecond. + * @param angleX {number} - The rotation of on screen's x axis as degrees per millisecond. + * @param angleY {number} - The rotation of on screen's y axis as degrees per millisecond. + * @param angleZ {number} - The rotation of on screen's z axis as degrees per millisecond. + * @param opt_zoom {number=} - The modification of the zoom level as levels per millisecond + */ + control(moveX: number, moveY: number, moveZ: number, angleX: number, angleY: number, angleZ: number, opt_zoom?: number): void; + + /** + * A method to signal the end of a control operation. + * @param opt_preventKinetics {boolean=} - A flag to indicate whether a kinetic effect is performed + * @param opt_adjustView {function(H.map.ViewModel.CameraData)=} - An callback to adjust the final ViewModel by modifying the passed camera data. + */ + endControl(opt_preventKinetics?: boolean, opt_adjustView?: (data: H.map.ViewModel.CameraData) => void): void; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module ViewModel { + /** + * Defines camera's properties. + * @property zoom {number=} - zoom level to be used by rendering engine + * @property position {H.geo.IPoint} - the position of the virtual camera in geo-space + * @property pitch {number=} - the rotation of the virtual camera along its local x-axis + * @property yaw {number=} - the rotation of the virtual camera along its local y-axis + * @property roll {number=} - the rotation of the virtual camera along its local z-axis + * @property fov {number=} - + */ + export interface CameraData { + zoom?: number; + position: H.geo.IPoint; + pitch?: number; + yaw?: number; + roll?: number; + fov?: number; + } + + /** + * Defines currently requested view data, which will be rendered by the map. + * @property camera {H.map.ViewModel.CameraData=} - The requested camera properties + * @property zoom {number=} - The requested zoom level + * @property animate {boolean=} - indicates if the requested transition should be animated + */ + export interface RequestedData { + camera?: H.map.ViewModel.CameraData; + zoom?: number; + animate?: boolean; + } + + /** + * Update event is fired whenever view model data is changed. It contains property which hold currently requested data + * @property target {*} - Object which triggered the event + * @property currentTarget {*} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class UpdateEvent extends H.util.Event { + /** + * Constructor + * @param requested {H.map.ViewModel.RequestedData} + */ + constructor(requested: H.map.ViewModel.RequestedData); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + target: any; + currentTarget: any; + type: string; + defaultPrevented: boolean; + } + } + + /** + * ViewPort object holds information about the HTML element where the map is rendered. It contains information regarding the element (view port) size and triggers events when the element size is changed. + * @property element {Element} - This property holds the HTML element, which defines the viewport. + * @property width {number} - This property holds this viewport's current width + * @property height {number} - This property holds this viewport's current height + * @property margin {number} - This property holds this viewport's current margin value + * @property padding {H.map.ViewPort.Padding} - This property holds this viewport's current padding + * @property center {H.math.Point} - This property holds this viewport's current center point + */ + export class ViewPort extends H.util.EventTarget implements H.map.IInteraction { + /** + * Constructor + * @param element {Element} - html element were map will be rendered + * @param opt_options {H.map.ViewPort.Options=} - optional configuration parameters + */ + constructor(element: Element, opt_options?: H.map.ViewPort.Options); + + /** + * This method sets the margin on the viewPort + * @param margin {number} - margin which is used to fetch map data + */ + setMargin(margin: number): void; + + /** + * This method sets the padding on the viewport. Padding will result in shifted map center which will be the visual center of the padded area. + * @param top {number} - padding from the top + * @param right {number} - padding from the right + * @param bottom {number} - padding from the bottom + * @param left {number} - padding from the left + */ + setPadding(top: number, right: number, bottom: number, left: number): void; + + /** + * This method updates size of the viewport according to container size. It must be called whenever the HTML element changed size in order to update the map's viewport values. + */ + resize(): void; + + /** + * This method starts the interaction with the view port. Should be called every time when new interaction is started i.e mouse grab, or touch start. + * @param modifiers {number} - a bitmask which specifies what operations should performed during every interaction + * @param opt_kinetics {H.util.kinetics.IKinetics=} - specifies kinetic move at the end of interaction + */ + startInteraction(modifiers: H.math.BitMask, opt_kinetics?: H.util.kinetics.IKinetics): void; + + /** + * This method resolves direct screen (view port) interaction. This function will modify the current view according to values passed in. + * @param x {number} - viewport x coordinate + * @param y {number} - viewport y coordinate + * @param opt_bx {number=} - x coordinate for second pointer/touch if present + * @param opt_by {number=} - y coordinate for secong pointer/touch if present + * @param opt_timestamp {number=} - known timestamp which should be passed + */ + interaction(x: number, y: number, opt_bx?: number, opt_by?: number, opt_timestamp?: number): void; + + /** + * This method ends interaction and applies kinetic movement if defined by using startInteraction method + * @param opt_preventKinetics {boolean=} - if set to true will prevent kinetics behaviour at the end of interaction + */ + endInteraction(opt_preventKinetics?: boolean): void; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + element: Element; + width: number; + height: number; + margin: number; + padding: H.map.ViewPort.Padding; + center: H.math.Point; + } + + export module ViewPort { + /** + * Options which may be used to initialize new ViewPort instance + * @property margin {number=} - The size in pixel of the supplemental area to render for each side of the map + * @property padding {H.map.ViewPort.Padding=} - The padding in pixels for each side of the map + * @property fixedCenter {boolean=} - Indicates whether the center of the map should remain unchanged if the viewport's size or or padding has been changed, default is true + */ + export interface Options { + margin?: number; + padding?: H.map.ViewPort.Padding; + fixedCenter?: boolean; + } + + /** + * Represents viewport padding definition. + * @property top {number} - the padding on the top edge (in pixels) + * @property right {number} - the padding on the right edge (in pixels) + * @property bottom {number} - the padding on the bottom edge (in pixels) + * @property left {number} - the padding on the left edge (in pixels) + */ + export interface Padding { + top: number; + right: number; + bottom: number; + left: number; + } + } + + export module layer { + /** + * BaseTileLayer encapsulates funcitonailty that is common to all layers that deliver tiles, such as H.map.layer.TileLayer. The functionality includes geo bounding box to grid calculation, tile request management. + */ + export class BaseTileLayer extends H.map.layer.Layer { + /** + * Constructor + * @param provider {H.map.provider.TileProvider} - data source for the TileLayer + * @param opt_options {H.map.layer.ITileLayer.Options=} - additional options + */ + constructor(provider: H.map.provider.TileProvider, opt_options?: H.map.layer.ITileLayer.Options); + + /** + * This method returns the provider which feeds this layer with data. + * @returns {H.map.provider.TileProvider} - this layer's provider + */ + getProvider(): H.map.provider.TileProvider; + + /** + * This method transforms a geo-rectangle to geometrical projected rectangle at the current projection zoom level or at provided zoom level + * @param geoRect {H.geo.Rect} - geo bounds to be projected + * @param opt_zoom {number=} - overrides current projection zoom level + * @returns {H.math.Rect} - projected 2d space rect cooresponding to provided geo bounds + */ + geoRectToRect(geoRect: H.geo.Rect, opt_zoom?: number): H.math.Rect; + + /** + * This method returns tile grid for a bounding rectangle + * @param rectBounds {H.math.Rect} - projected rect bounds which coorespond to geo bounding box + * @param zoom {number} - current zoom level + * @returns {H.math.Rect} - rectangle which represents the tile grid bounds + */ + getTileBounds(rectBounds: H.math.Rect, zoom: number): H.math.Rect; + + /** + * This method requests a single tile according to tile coordinates. It returns either a Tile object if it is already loaded or undefined and starts loading the tile + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - The zoom level for which the tile is requested + * @param cacheOnly {boolean} - indicates whether only cached tiles are to be considered + * @returns {(H.map.provider.Tile | undefined)} - tile object corresponding to requested coordinates + */ + requestTile(x: number, y: number, z: number, cacheOnly: boolean): H.map.provider.Tile | void; + + /** + * This method cancels a previously requested tile. + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - zoom level + */ + cancelTile(x: number, y: number, z: number): void; + + /** + * This method requests tiles from the data source (provider). It can return a set of tiles which are currently loaded. All tiles which are not yet loaded will be included in response as soon as they will be available during subsequent calls. + * @param tileBounds {H.math.Rect} - bounds in tile grid + * @param isCDB {boolean} + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ITileLayer.Response} - returns an array if tile which are already loaded + */ + getProviderTiles(tileBounds: H.math.Rect, isCDB: boolean, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ITileLayer.Response; + } + + /** + * This interface describes a layer which provides marker objects to the renderer. + */ + export interface IMarkerLayer { + + /** + * This method requests marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + + /** + * This method requests dom marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestDomMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + } + + export module IMarkerLayer { + /** + * This type represents a response object returned by the H.map.layer.IMarkerLayer#requestMarkers function. + * @property total {number} - The total number of markers, inclusive markers with not ready icons + * @property markers {Array} - The marker objects for the bounding rectangle (only ready) + */ + export interface Response { + total: number; + markers: Array; + } + + /** + * This type represents a response object returned by the H.map.layer.IMarkerLayer#requestMarkers function. + * @property number {number} - of returned tiles + * @property requested {number} - number of requested tiles + * @property objects {Array} - the marker objects within requested tiled area + */ + export interface TiledResponse { + number: number; + requested: number; + objects: Array; + } + } + + /** + * This interface describes a layer which provides data partitioned in quad-tree tiles in an x, y, z fashion (where z describes the level within the tree and x and y describe the absolute column and row indeces whithin the level). + */ + export interface ITileLayer { + /** + * This method requests tiles for the current bounding rectangle at the given zoom level (z-value). + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which tiles are to be returned + * @param zoomLevel {number} - The zoom level for which the tiles are requested + * @param cacheOnly {boolean} - Indicates whether only cached tiles are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ITileLayer.Response} - a response object containing the total number of tiles requested and the tile objects that could be immediately returned + */ + requestTiles(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ITileLayer.Response; + + /** + * This method requests a single tile according to tile coordinates. It returns either a Tile object if it is already loaded or undefined and starts loading the tile + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - The zoom level for which the tile is requested + * @param cacheOnly {boolean} - indicates whether only cached tiles are to be considered + * @returns {(H.map.provider.Tile | undefined)} - tile object corresponding to requested coordinates + */ + requestTile(x: number, y: number, z: number, cacheOnly: boolean): H.map.provider.Tile | void; + + /** + * This method cancels a previously requested tile. + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - zoom level + */ + cancelTile(x: number, y: number, z: number): void; + } + + export module ITileLayer { + /** + * Options which are used to initialize a TileLayer object. + * @property projection {H.geo.IProjection=} - an optional projection to be used for this layer, default is H.geo.mercator + * @property opacity {number=} - tile layer opacity, default is 1 + */ + export interface Options { + projection?: H.geo.IProjection; + opacity?: number; + } + + /** + * A response object for a tile request. Contains total number of elements requested and an array of currently available Tiles + * @property total {number} - the total number of requested tiles + * @property tiles {Array} - the tiles which this provider can currently return synchronously + */ + export interface Response { + total: number; + tiles: Array; + } + } + + /** + * The Layer class represents an object that is evaluated by the renderer in the order in which it is added to the layers collection. It provides the basic infrastructure for dispatching update events to the renderer in case new data is available. + */ + export class Layer extends H.util.EventTarget { + /** + * Constructor + * @param opt_options {H.map.layer.Layer.Options=} - optional configuration object + */ + constructor(opt_options?: H.map.layer.Layer.Options); + + /** + * This method checks if a zoom level can be served by this layer. + * @param zoomLevel {number} - the zoom level to check + * @returns {boolean} - true if this layer can provide data for the zoom level, otherwise false + */ + isValid(zoomLevel: number): boolean; + + /** + * This method sets the minimum zoom level for which this layer will provide tiles. + * @param min {number} - The new minimum zoom level of this layer + * @returns {H.map.layer.Layer} - Returns this instance of the layer + */ + setMin(min: number): H.map.layer.Layer; + + /** + * This method sets the maximum zoom level for which this layer will provide tiles. + * @param max {number} - The new maximum zoom level of this layer + * @returns {H.map.layer.Layer} - Returns this instance of the layer + */ + setMax(max: number): H.map.layer.Layer; + + /** + * This method returns the copyright of the current data provider. + * @param bounds {H.geo.Rect} - the bounding area for which to retrieve the copyright information + * @param level {number} - the zoom level for which to retrieve the copyright information + * @returns {Array} - a list of copyright information objects for the provided area and zoom level + */ + getCopyrights(bounds: H.geo.Rect, level: number): Array; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module Layer { + /** + * Options which can be used when creating new layer object. + * @property min {number=} - The minimum zoom level for which the layer can provide data, default is 0 + * @property max {number=} - The maximum zoom level for which the layer can provide data, default is 22 + * @property dark {boolean=} - Indicates whether the content of this layer is mainly dark, default is false See also H.Map.Options#autoColor + * @property projection {H.geo.IProjection=} - The projection to be used for this layer, default is H.geo.mercator + * @property minWorldSize {number=} - The minimal world size at zoom level 0, default is 256 + */ + export interface Options { + min?: number; + max?: number; + dark?: boolean; + projection?: H.geo.IProjection; + minWorldSize?: number; + } + } + + /** + * ObjectTileLayer represents map objects which are requested on a tile basis + */ + export class MarkerTileLayer extends H.map.layer.BaseTileLayer implements H.map.layer.IMarkerLayer { + /** + * Constructor + * @param provider {H.map.provider.MarkerTileProvider} + * @param opt_options {H.map.layer.ITileLayer.Options=} + */ + constructor(provider: H.map.provider.MarkerTileProvider, opt_options?: H.map.layer.ITileLayer.Options); + + /** + * This method requests marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + + /** + * This method requests dom marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestDomMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + } + + /** + * This class represents a layer which renders map objects. Spatial objects like polygons and polylines a rendered to tiles before being passed to the enigne. Point objects like markers are provided as objects given an rectangular area. + */ + export class ObjectLayer extends H.map.layer.Layer implements H.map.layer.ITileLayer { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - the ObjectProvider which provides the map objects to this object layer. + * @param opt_options {H.map.layer.ObjectLayer.Options=} - The options for this layer + */ + constructor(provider: H.map.provider.ObjectProvider, opt_options?: H.map.layer.ObjectLayer.Options); + + /** + * This method returns current ObjectLayer's data provider + * @returns {H.map.provider.ObjectProvider} + */ + getProvider(): H.map.provider.ObjectProvider; + + /** + * To request overlay objects for the passsed bounding rectangle. It returns all overlay objects which are contained within this bounding rectangle. + * @param bounds {H.geo.Rect} - The bounding rectangle for which overlays are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ObjectLayer.OverlaysResponse} + */ + requestOverlays(bounds: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ObjectLayer.OverlaysResponse; + + /** + * This method requests tiles for the current bounding rectangle at the given zoom level (z-value). + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which tiles are to be returned + * @param zoomLevel {number} - The zoom level for which the tiles are requested + * @param cacheOnly {boolean} - Indicates whether only cached tiles are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ITileLayer.Response} - a response object containing the total number of tiles requested and the tile objects that could be immediately returned + */ + requestTiles(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ITileLayer.Response; + + /** + * This method requests a single tile according to tile coordinates. It returns either a Tile object if it is already loaded or undefined and starts loading the tile + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - The zoom level for which the tile is requested + * @param cacheOnly {boolean} - indicates whether only cached tiles are to be considered + * @returns {(H.map.provider.Tile | undefined)} - tile object corresponding to requested coordinates + */ + requestTile(x: number, y: number, z: number, cacheOnly: boolean): H.map.provider.Tile | void; + + /** + * This method cancels a previously requested tile. + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - zoom level + */ + cancelTile(x: number, y: number, z: number): void; + + /** + * This method requests marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + + /** + * This method requests dom marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestDomMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + } + + export module ObjectLayer { + /** + * Configuration object which can be use to initialize the ObjectLayer. + * @property tileSize {number=} - the size of the tiles rendered by this layer for polylines and polygons (must be power of 2, default is 256) + * @property tileCacheSize {number=} - the number of fully rendered spatial tiles that are cached for immediate reuse, default is 32 + * @property dataCacheSize {number=} - the number of tiles to cache which have render data only, default is 512 + * @property pixelRatio {number=} - The pixelRatio to use for over-sampling in cases of high-resolution displays + */ + export interface Options { + tileSize?: number; + tileCacheSize?: number; + dataCacheSize?: number; + pixelRatio?: number; + } + + /** + * A response object returned by the H.map.layer.ObjectLayer#requestOverlays function. + * @property total {number} - The total number of overlays within the requested bounds, inclusive overlays which are not ready loaded yet + * @property overlays {Array} - A list all overlays which are ready to render + */ + export interface OverlaysResponse { + total: number; + overlays: Array; + } + } + + /** + * Tile Layer, represents data shown on map on a tile basis. Can be used to show map tile images or other type of data which is partitioned into tiles. + * @event update {H.util.Event} + */ + export class TileLayer extends H.map.layer.BaseTileLayer implements H.map.layer.ITileLayer { + /** + * Constructor + * @param provider {H.map.provider.TileProvider} - data source for the TileLayer + * @param opt_options {H.map.layer.ITileLayer.Options=} - additional options + */ + constructor(provider: H.map.provider.TileProvider, opt_options?: H.map.layer.ITileLayer.Options); + + /** + * This method requests tiles for the current bounding rectangle at the given zoom level (z-value). + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which tiles are to be returned + * @param zoomLevel {number} - The zoom level for which the tiles are requested + * @param cacheOnly {boolean} - Indicates whether only cached tiles are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ITileLayer.Response} - a response object containing the total number of tiles requested and the tile objects that could be immediately returned + */ + requestTiles(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ITileLayer.Response; + + update: H.util.Event; + } + } + + export module provider { + /** + * An ImageTileProvider uses network service to provide bitmap images as tiles. + * @property tileSize {number} - Size of a tile image supported by the provider + */ + export class ImageTileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param options {H.map.provider.ImageTileProvider.Options} - configuration for tile provider + */ + constructor(options: H.map.provider.ImageTileProvider.Options); + + tileSize: number; + } + + export module ImageTileProvider { + /** + * Options to initialize an ImageTileProvider instance + * @property uri {string=} - The provider's unique resource identifier which must not contain an underscore "_". If omitted an auto-generated unique Session ID is used. If a cross sessions consistent IDs is needed (e.g. for storing provider data) this property must be specified. + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property getCopyrights {(function(H.geo.Rect, number) : ?Array)=} - A function to replace the default implementation of H.map.provider.Provider#getCopyrights + * @property tileSize {number=} - The size of a tile as edge length in pixels. It must be 2^n where n is in range [0 ... 30], default is 256 + * @property getURL {function(number, number, number)} - The function to create an URL for the specified tile. If it returns a falsy the tile is not requested. + * @property crossOrigin {(string | boolean=)} - The CORS settings to use for the crossOrigin attribute for the image, if omitted or if the value evaluates to false no CORS settings are used. + */ + export interface Options { + uri?: string; + min?: number; + max?: number; + getCopyrights?: ((rect: H.geo.Rect, n: number) => Array); + tileSize?: number; + getURL: (n1: number, n2: number, n3: number) => string; + crossOrigin?: (string | boolean); + } + } + + /** + * This class represents invalidation states of a renderable object. A renderer can optimize its rendering strategies based on the information in this object. + * @property MARK_INITIAL {H.map.provider.Invalidations.Mark} - This constant represents the initial invalidation mark an invalidations object has. + */ + export class Invalidations { + + /** + * To update invalidation marks accordingly to the given the invalidation types. + * @param mark {H.map.provider.Invalidations.Mark} - The invalidation mark to set + * @param types {H.math.BitMask} - The descrete invalidation types to update + */ + update(mark: H.map.provider.Invalidations.Mark, types: H.math.BitMask): void; + + /** + * This method returns the current invalidation mark of this invalidations object. + * @returns {H.map.provider.Invalidations.Mark} - the current invalidation mark + */ + getMark(): H.map.provider.Invalidations.Mark; + + /** + * Checks whether any change occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isAny(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether a visual change occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isVisual(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether a spatial change occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isSpatial(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether an add-operation occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isAdd(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether a remove operation occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isRemove(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether a z-order change occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isZOrder(since: H.map.provider.Invalidations.Mark): boolean; + + static MARK_INITIAL: H.map.provider.Invalidations.Mark; + } + + export module Invalidations { + /** + * This enumeration encapsulates bit flags for different invalidations of map objects. + */ + export enum Flag { + NONE, + VISUAL, + SPATIAL, + ADD, + REMOVE, + Z_ORDER, + } + + /** + * The invalidation mark represents a counter which is increased whenever an invalidation takes place. + */ + export interface Mark { } + } + + /** + * A MarkerTileProvider uses network service to provide markers on tile basis. + * @property requestTile {} - Request data on a tile basis + * @property cancelTile {} - Cancels tile from being requested using x, y, z coordinates (column, row, zoom) + * @property cancelTileByKey {} - Cancels tile from being requested using a tile-key + * @property uri {string} - This provider's unique resource identifier, if not provided at construction time it defaults to provider's uid + * @property min {number} - Minimum zoom level at which provider can serve data, set at construction time + * @property max {number} - Maximum zoom level at which provider can server data, set at construction time + * @property uid {string} - Provider instance unique identifier, generated at construction time + */ + export class MarkerTileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param options {H.map.provider.MarkerTileProvider.Options} - configuration for tile provider + */ + constructor(options: H.map.provider.MarkerTileProvider.Options); + + /** + * To signal to this provider that a map object has been changed. The method marks tile, that contains that object as invalid and triggers dispatchUpdate() + * @param marker {!H.map.AbstractMarker} - The map object to be invalidated + * @param flags {H.math.BitMask} - The flags indicating the types of occurred changes + */ + invalidateObject(marker: H.map.AbstractMarker, flags: H.math.BitMask): void; + + /** + * Checks whether this provider is currently providing H.map.DomMarker map objects. + * @returns {boolean} + */ + providesDomMarkers(): boolean; + } + + export module MarkerTileProvider { + /** + * Options which are used to initialize the MarkerTileProvider object. + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property requestData {function(number, number, number, function(Array), Function) : H.util.ICancelable} - function that fetches marker data and creates array of H.map.AbstractMarker that is passed success callback, if function fails to fetch data onError callback must be called + * @property providesDomMarkers {boolean=} - indicates if markers provided are of type H.map.DomMarker or H.map.Marker, default is H.map.Marker + */ + export interface Options { + min?: number; + max?: number; + requestData: (n1: number, n2: number, n3: number, markerCallback: (markers: Array) => void, f: Function) => H.util.ICancelable; + providesDomMarkers?: boolean; + } + } + + /** + * An abstract class to manage and provide map objects (Marker, Polyline, Polygon) + */ + export class ObjectProvider extends H.map.provider.Provider { + /** + * Constructor + * @param opt_options {H.map.provider.Provider.Options=} + */ + constructor(opt_options?: H.map.provider.Provider.Options); + + /** + * Returns the accumulate invalidations of this provider's objects that have occurred. + * @param opt_type {H.map.Object.Type=} - The type of objects to consider for the invalidations. If undefined, all types are taken into account. + * @returns {H.map.provider.Invalidations} + */ + getInvalidations(opt_type?: H.map.Object.Type): H.map.provider.Invalidations; + + /** + * To signal to this provider that a map object has been changed. The method updates the Invalidations of this provider and the given map object and triggers dispatchUpdate() + * @param mapObject {!H.map.Object} - The map object to be invalidated + * @param changes {H.math.BitMask} - The flags indicating the types of occurred changes + */ + invalidateObject(mapObject: H.map.Object, changes: H.math.BitMask): void; + + /** + * Checks whether this provider is currently providing overlay map objects. A concrete implementation of ObjectProvider must override it if it currently provides overlays. + * @returns {boolean} + */ + providesOverlays(): boolean; + + /** + * Returns all Overlay objects which intersect with the provided area. + * @param geoRect {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestOverlays(geoRect: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Checks whether this provider is currently providing spatial map objects. A concrete implementation of ObjectProvider must override it if it currently provides Spatials. + * @returns {boolean} + */ + providesSpatials(): boolean; + + /** + * Returns all polyline, polygon, circle and rect objects which intersect with the provided area. + * @param geoRect {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestSpatials(geoRect: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Returns the spatial objects which intersect the given tile + * @param tile {H.map.provider.SpatialTile} - The tile for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestSpatialsByTile(tile: H.map.provider.Tile, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Checks whether this provider is currently providing Marker map objects. A concrete implementation of ObjectProvider must override it if it currently provides Markers. + * @returns {boolean} + */ + providesMarkers(): boolean; + + /** + * Returns all Marker map objects which intersect with the provided rectangular area. + * @param geoRect {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestMarkers(geoRect: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Checks whether this provider is currently providing DomMarker map objects. A concrete implementation of ObjectProvider must override it if it currently provides Markers. + * @returns {boolean} + */ + providesDomMarkers(): boolean; + + /** + * Returns all DomMarker map objects which intersect with the provided rectangular area. + * @param geoRect {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestDomMarkers(geoRect: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + } + + /** + * A Provider defines an object which works as a database for the map. Providers can exists in different forms they can implement client side object storage or they can request data from the remote service. + * @property uri {string} - This provider's unique resource identifier, if not provided at construction time it defaults to provider's uid + * @property min {number} - Minimum zoom level at which provider can serve data, set at construction time + * @property max {number} - Maximum zoom level at which provider can server data, set at construction time + * @property uid {string} - Provider instance unique identifier, generated at construction time + */ + export class Provider extends H.util.EventTarget { + /** + * Constructor + * @param opt_options {H.map.provider.Provider.Options=} + */ + constructor(opt_options?: H.map.provider.Provider.Options); + + /** + * This method returns the copyrights of the provided content for a certain geographical area at a specified zoom level. + * @param bounds {H.geo.Rect} - The bounding area for which to retrieve the copyright information + * @param level {number} - The zoom level for which to retrieve the copyright information + * @returns {?Array} - a list of copyright information objects for the provided area and zoom level + */ + getCopyrights(bounds: H.geo.Rect, level: number): Array; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + uri: string; + min: number; + max: number; + uid: string; + } + + export module Provider { + /** + * Options to initialize a Provider instance + * @property uri {string=} - The provider's unique resource identifier which must not contain an underscore "_". If omitted an auto-generated unique Session ID is used. If a cross sessions consistent IDs is needed (e.g. for storing provider data) this property must be specified. + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property getCopyrights {(function(H.geo.Rect, number) : ?Array)=} - A function to replace the default implementation of H.map.provider.Provider#getCopyrights + */ + export interface Options { + uri?: string; + min?: number; + max?: number; + getCopyrights?: (rect: H.geo.Rect, n: number) => Array; + } + } + + /** + * RemoteTileProvider is an abstract class which should be used by classes implementing data provision on a tile basis. Every child class needs to implement 'requestInternal' (to request remote tile) and 'getCache' (to provide configured cache object were tiled data is being cached) + */ + export class RemoteTileProvider extends H.map.provider.TileProvider { + /** + * Constructor + * @param options {H.map.provider.TileProvider.Options} - The options to instantiate this TileProvider + */ + constructor(options: H.map.provider.TileProvider.Options); + + /** + * This method returns cache which should be used to store tiles + * @returns {H.util.ICache} - cache + */ + getCache(): H.util.ICache; + + /** + * This method request tile from remote service + * @param x {number} - The row number of the tile + * @param y {number} - The column number of the tile + * @param z {number} - The zoom level for which the tile is requested + * @param onResponse {function((Array | HTMLImageElement | HTMLCanvasElement | ArrayBuffer | null), *=)} - function which is called after response arrives + * @param onError {function(string=)} - function which is called in case of communication error + * @param opt_priority {H.net.Request.Priority=} - optional request priority level + * @returns {H.util.ICancelable} + */ + requestInternal( + x: number, + y: number, + z: number, + + onResponse?: ( + object: Array | HTMLImageElement | HTMLCanvasElement | ArrayBuffer, + response: any + ) => void, + + onError?: (s: string) => void, + opt_priority?: H.net.Request.Priority + ): H.util.ICancelable; + + /** + * This method instructs the provider to reload data from it's source. + * @param hard {boolean} - a boolean flag indicating whether to invalidate in hard mode (true) or in soft mode (false); + */ + reload(hard: boolean): void; + } + + /** + * Generic Tile object which represents a part of the world fiting into the Tile area represented by the Tiel coordinates (x - row, y - column) and the zoom level (z). Number of tiles at particular zoom level (which means number of areas into world is being splitted) is defined as following: numberOfRows = numberOfColumns = 2^zoomlevel + * @property key {string} - Unique tile key generated by provider + * @property data {*} - Tile data (an image for example) + * @property valid {boolean} - This property holds a boolean flag indicating whether this tile is still valid (true) or whether it should be re-fetched (false) + * @property x {number} - Tile column + * @property y {number} - Tile row + * @property z {number} - Tile zoom level + */ + export class Tile { + /** + * Constructor + * @param x {number} - x tile coordinate (row) + * @param y {number} - y tile coordinate (column) + * @param z {number} - tile zoom level + * @param data {*} - generic data object which cooresponds to the given coordinates + */ + constructor(x: number, y: number, z: number, data?: any); key: string; + + data: any; + valid: boolean; + x: number; + y: number; + z: number; + } + + /** + * TileProvider is an abstract class to provide data on a tile basis + * @property requestTile {} - Request data on a tile basis + * @property cancelTile {} - Cancels tile from being requested using x, y, z coordinates (column, row, zoom) + * @property cancelTileByKey {} - Cancels tile from being requested using a tile-key + * @property uri {string} - This provider's unique resource identifier, if not provided at construction time it defaults to provider's uid + * @property min {number} - Minimum zoom level at which provider can serve data, set at construction time + * @property max {number} - Maximum zoom level at which provider can server data, set at construction time + * @property uid {string} - Provider instance unique identifier, generated at construction time + */ + export class TileProvider extends H.map.provider.Provider { + /** + * Constructor + * @param options {H.map.provider.TileProvider.Options} - The options to instantiate this TileProvider + */ + constructor(options: H.map.provider.TileProvider.Options); + + /** + * This method creates a tile object with given parameters + * @param x {number} - x tile coordinate (row) + * @param y {number} - y tile coordinate (column) + * @param z {number} - tile coordinate (zoom) + * @param data {(HTMLImageElement | HTMLCanvasElement)} - data for the tile + * @param opt_options {Object=} - free form options object. These options are meant to be used in tile specific rendering cases + * @returns {H.map.provider.Tile} + */ + createTileInternal(x: number, y: number, z: number, data: (HTMLImageElement | HTMLCanvasElement), opt_options?: { [key: string]: any }): H.map.provider.Tile; + + /** + * This method creates a tile key consisting of the provider's uri, and the tile's x, y and z coordinates, seperated by underscores e.g.: "4711_7_42_23" + * @param x {number} - The x tile coordinate (row) + * @param y {number} - The y tile coordinate (column) + * @param z {number} - The z tile coordinate (zoom level) + * @returns {string} - string + */ + getTileKey(x: number, y: number, z: number): string; + + requestTile: any; + cancelTile: any; + cancelTileByKey: any; + uri: string; + min: number; + max: number; + uid: string; + } + + export module TileProvider { + /** + * @property uri {string=} - The provider's unique resource identifier which must not contain an underscore "_". If omitted an auto-generated unique Session ID is used. If a cross sessions consistent IDs is needed (e.g. for storing provider data) this property must be specified. + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property getCopyrights {(function(H.geo.Rect, number): Array)=} - A function to replace the default implememtation of H.map.provider.Provider#getCopyrights + * @property tileSize {number=} - The size of a tile as edge length in pixels. It must be 2^n where n is in range [0 ... 30], default is 256 + */ + export interface Options { + uri?: string; + min?: number; + max?: number; + getCopyrights?(rect: H.geo.Rect, number: number): Array; + tileSize?: number; + } + } + } + } + + /***** mapevents *****/ + export module mapevents { + /** + * Behavior class uses map events and adds behavior functionality to the map. This allows map panning and zooming via using mouse wheel + * @property DRAGGING {number} - Map responds to user dragging via mouse or touch + * @property WHEELZOOM {number} - Map zooms in or out in respond to mouse wheel events + * @property DBLTAPZOOM {number} - Map zooms in or out in response to double click or double tap. For double tap if more that one touches are on the screen map will zoom out. + */ + export class Behavior extends H.util.Disposable { + /** + * Constructor + * @param mapEvents {H.mapevents.MapEvents} - previously initialized map events instance + * @param options {H.mapevents.Behavior.Options} - additional options (i.e kinetics) + */ + constructor(mapEvents: H.mapevents.MapEvents, options?: H.mapevents.Behavior.Options); + + /** + * This method destroys all map interaction handling. Should be used when the behavior functionality is disposed. Behavior object will also be disposed (this function will be called) when attached H.mapevents.MapEvents object is dispose. + */ + dispose(): void; + + /** + * This method disables the behavior functionality for the map + * @param opt_behavior {number=} - The bitmask of behaviors to disable. If no arguments are passed, all behaviors will be disabled. + */ + disable(opt_behavior?: H.math.BitMask): void; + + /** + * This method re-enables the behavior functionality for the map. + * @param opt_behavior {number=} - The bitmask of behaviors to enable. If no arguments are passed, all behaviors will be enabled. + */ + enable(opt_behavior?: H.math.BitMask): void; + + /** + * This method checks if certain functionality is enabled + * @param behavior {number} - value like H.mapevents.Behavior.DRAGGING which the check is being performed + * @returns {boolean} + */ + isEnabled(behavior: number): boolean; + + static DRAGGING: number; + static WHEELZOOM: number; + static DBLTAPZOOM: number; + } + + export module Behavior { + /** + * Options which are used to initialize the Behavior class. + * @property kinetics {H.util.kinetics.IKinetics=} - The parameters for the kinetic movement. + * @property enable {number=} - The bitmask of behaviors to enable like H.mapevents.Behavior.DRAGGING. All are enabled by default. + */ + export interface Options { + kinetics?: H.util.kinetics.IKinetics; + enable?: H.math.BitMask; + } + } + + /** + * ContextMenuEvent should be fired, when a user right-clicks or longpresses on a map object. + * @property viewportX {Array} - Contains ContextItems, that will be used to create context menu entries. Should be filled by listeners of the "contextmenu" event + * @property viewportY {number} - Map viewport y position + * @property target {(H.map.Object | H.Map)} - Target for the event + * @property originalEvent {Event} - Original event + * @property currentTarget {(H.map.Object | H.Map)} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class ContextMenuEvent extends H.util.Event { + /** + * Constructor + * @param viewportX {number} - The x coordinate on the viewport + * @param viewportY {number} - The y coordinate on the viewport + * @param target {(H.Map | H.map.Object)} - The event's target element + * @param originalEvent {Event} - target of the event + */ + constructor(viewportX: number, viewportY: number, target: (H.Map | H.map.Object), originalEvent: Event); + + viewportX: Array; + viewportY: number; + originalEvent: Event; + } + + /** + * Custom map event. Contains list of pointers on the map, list of changed pointers and original event. Inherits from H.util.Event. + * @property pointers {Array} - Pointers which are currently on the screen + * @property changedPointers {Array} - Pointers which has changed in course of event + * @property targetPointers {Array} - Pointers which are on same target as the current pointer + * @property currentPointer {H.mapevents.Pointer} - Current pointer + * @property originalEvent {Event} - Original event fired by the browser + * @property target {(H.map.Object | H.Map)} - Object which triggered event. Can be the map object (i.e marker or polyline) or the map itself + * @property currentTarget {(H.map.Object | H.Map)} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class Event extends H.util.Event { + /** + * Constructor + * @param type {string} - type of event + * @param pointers {Array} - pointers which are currently on the screen + * @param changedPointers {Array} - pointers which changed during event + * @param targetPointers {Array} - pointers on the event target + * @param currentPointer {H.mapevents.Pointer} - pointer which triggered the event + * @param target {(H.Map | H.map.Object)} - target map object which triggered event + * @param originalEvent {Event} - original dom event + */ + constructor(type: string, pointers: Array, changedPointers: Array, targetPointers: Array, currentPointer: H.mapevents.Pointer, target: (H.Map | H.map.Object), originalEvent: Event); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + pointers: Array; + changedPointers: Array; + targetPointers: Array; + currentPointer: H.mapevents.Pointer; + originalEvent: Event; + target: (H.map.Object | H.Map); + currentTarget: (H.map.Object | H.Map); + type: string; + defaultPrevented: boolean; + } + + /** + * MapEvents enable the events functionality on the map and on the map objects. By using this extension it is possible to listen to events on map objects like markers, polylines, polygons, circles and on the map object itself. Events are triggered depending on user interaction. Please check the Events Summary section for the list of events fired by this class and by the map objects. + */ + export class MapEvents extends H.util.Disposable { + /** + * Constructor + * @param map {H.Map} - map instance which is used for firing events + */ + constructor(map: H.Map); + + /** + * This method destroys the MapEvents by removing all handlers from the map object. After calling this function mapEvents and map objects will not trigger any events. This object will be disposed automatically if the corresponding map object is disposed. + */ + dispose(): void; + + /** + * This method returns map into which events are attached + * @returns {H.Map} + */ + getAttachedMap(): H.Map; + } + + /** + * Class representing pointer on the map surface. A pointer in platform specific definition would mean either mouse, touch, pen or any pointing device which can trigger browser events. + * @property viewportX {number} - X coordinate on the map's viewport + * @property viewportY {number} - Y coordinate on the map's viewport + * @property target {(H.map.Object | H.Map)} - Map object directly under the pointer. Can be null if if pointer is out of the map viewport + * @property id {number} - Pointer unique identifier. + * @property type {string} - Pointer type can be: 'mouse', 'touch' or 'pen' + * @property dragTarget {(H.map.Object | H.Map)} - Object which is currently dragged by the pointer + * @property button {H.mapevents.Pointer.Button} - Indicates which pointer device button has changed. + */ + export class Pointer { + /** + * Constructor + * @param viewportX {number} - pointer position on x-axis + * @param viewportY {number} - pointer position on y-axis + * @param id {number} - unique pointer identifier among currently available pointers + * @param type {string} - type of pointer can be i.e 'mouse', 'touch'. 'pen' + * @param opt_button {H.mapevents.Pointer.Button=} - Indicates which pointer device button has changed. + * @param opt_buttons {number=} - Indicates which pointer device buttons are being pressed, expressed as a bitmask. Uses the same values, as "buttons" in Pointer Events spec. + */ + constructor(viewportX: number, viewportY: number, id: number, type: string, opt_button?: H.mapevents.Pointer.Button, opt_buttons?: H.math.BitMask); + static viewportX: number; + static viewportY: number; + static target: (H.map.Object | H.Map); + static id: number; + static type: string; + static dragTarget: (H.map.Object | H.Map); + static button: H.mapevents.Pointer.Button; + } + + export module Pointer { + /** + * Types of a button + */ + export enum Button { + /** No button */ + NONE, + /** Left mouse button or touch contact or pen contact */ + LEFT, + /** Middle mouse button */ + MIDDLE, + /** Right mouse button or Pen barrel button */ + RIGHT, + } + + /** + * Indicates which pointer device buttons are being pressed, expressed as a bitmask. Bit values are: + * + * - 0: No button pressed + * - 1: Left mouse button pressed, or Touch contact or Pen contact + * - 2: Right mouse button pressed, or Pen contact with barrel button pressed + * - 4: Middle mouse button pressed + */ + // TODO not sure this is the right interpretation of the docs + export type Buttons = H.math.BitMask; + } + + /** + * WheelEvent is fired when the mouse wheel is used over the map. It contains information about cursor position and the map object which resides directly under the cursor. + * @property delta {number} - Wheel move delta + * @property viewportX {number} - Map viewport x position + * @property viewportY {number} - Map viewport y position + * @property target {(H.map.Object | H.Map)} - Target for the event + * @property originalEvent {Event} - Original mouse wheel event + * @property currentTarget {(H.map.Object | H.Map)} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class WheelEvent extends H.util.Event { + /** + * Constructor + * @param deltaY {number} - The wheel move delta on y-axis + * @param viewportX {number} - The x coordinate on the viewport + * @param viewportY {number} - The y coordinate on the viewport + * @param target {(H.Map | H.map.Object)} - The event's target element + * @param originalEvent {Event} - target of the event + */ + constructor(deltaY: number, viewportX: number, viewportY: number, target: (H.Map | H.map.Object), originalEvent: Event); + + delta: number; + viewportX: number; + viewportY: number; + originalEvent: Event; + } + } + + /***** math *****/ + export module math { + /** + * A signed 32 bit integer (JS restriction) where bit operator can be applied to. The range is [-2,147,483,648 ... 2,147,483,647] or [-2^31 ... 2^31 − 1] + */ + export type BitMask = number; + + /** + * An interface for a 2-dimensional point consisting a x and y coordinate. + * @property x {number} - The point's coordinate on X-axis. + * @property y {number} - The point's coordinate on Y-axis. + */ + export interface IPoint { + x: number; + y: number; + } + + /** + * An interface for a 2-dimensional size consisting a with and a height. + * @property w {number} - The size's width. + * @property h {number} - The size's height. + */ + export interface ISize { + w: number; + h: number; + } + + /** + * Class represents a 2-dimensional point, defined by x and y coordinates. + * @property x {number} - The point's coordinate on X-axis. + * @property y {number} - The point's coordinate on Y-axis. + */ + export class Point implements IPoint { + /** + * Constructor + * @param x {number} - The point's coordinate on X-axis. + * @param y {number} - The point's coordinate on Y-axis. + */ + constructor(x: number, y: number); + + /** + * Sets the x and y coordinate of this point + * @param x {number} - The point's coordinate on X-axis. + * @param y {number} - The point's coordinate on Y-axis. + */ + set(x: number, y: number): void; + + /** + * This method creates a copy of the current point. + * @param opt_out {H.math.Point=} - An optional point to store the copied values + * @returns {H.math.Point} - The clone of the point + */ + clone(opt_out?: Point): Point; + + /** + * This method adds given point coordinates to the current one. + * @param other {H.math.IPoint} - The point to add + * @returns {H.math.Point} - the point itself after adding + */ + add(other: IPoint): Point; + + /** + * This method subtracts given point coordinates from the current point. + * @param other {H.math.IPoint} - The point to subtract + * @returns {H.math.Point} - the point itself after subtracting + */ + sub(other: IPoint): Point; + + /** + * This method scales the current point coordinates by the given factor(s). + * @param factor {number} - multiplication factor + * @param opt_factorY {number=} - If omitted, the factor argument is used + * @returns {H.math.Point} - the point itself after scaling + */ + scale(factor: number, opt_factorY?: number): Point; + + /** + * This method rounds the x and y coordinates of the point. + * @returns {H.math.Point} - the point itself after rounding + */ + round(): Point; + + /** + * Rounds the x and y coordinates to the next smaller integer values. + * @returns {H.math.Point} - the point itself after flooring + */ + floor(): Point; + + /** + * Rounds the x and y coordinates to the next greater integer values. + * @returns {H.math.Point} - the point itself after ceiling + */ + ceil(): Point; + + /** + * This method compares current point coordinates with the supplied point coordinates. + * @param other {H.math.IPoint} - The point to compare to. + * @returns {boolean} - True if the points are equal + */ + equals(other: IPoint): boolean; + + /** + * Calculates the closest point on a given line + * @param start {H.math.IPoint} - The start point of the line + * @param end {H.math.IPoint} - The end point of the line + * @returns {H.math.IPoint} - the closest point + */ + getNearest(start: IPoint, end: IPoint): IPoint; + + /** + * This method calculates the distance to a point supplied by the caller. + * @param other {H.math.IPoint} + * @returns {number} + */ + distance(other: IPoint): number; + + /** + * This method creates a Point instance from a given IPoint object. + * @param iPoint {H.math.IPoint} - The IPoint object to use + * @returns {H.math.Point} - the created Point instance + */ + static fromIPoint(iPoint: IPoint): Point; + + x: number; + y: number; + } + + /** + * Class defines a rectangle in 2-dimensional geometric space. It is used to represent the area in projected space. + */ + export class Rect { + /** + * Constructor + * @param left {number} - The rectangle's left edge x value + * @param top {number} - The rectangle's top edge y value + * @param right {number} - The rectangle's right edge x value + * @param bottom {number} - The rectangle's bottom edge y value + */ + constructor(left: number, top: number, right: number, bottom: number); + + /** + * To set all values of the rectangle's edges + * @param left {number} - The rectangle's left edge x value + * @param top {number} - The rectangle's top edge y value + * @param right {number} - The rectangle's right edge x value + * @param bottom {number} - The rectangle's bottom edge y value + */ + set(left: number, top: number, right: number, bottom: number): void; + + /** + * To get the rectangle's top-left vertex + * @returns {H.math.Point} + */ + getTopLeft(): H.math.Point; + + /** + * To get the rectangle's bottom-right vertex + * @returns {H.math.Point} + */ + getBottomRight(): H.math.Point; + + /** + * Method checks if provided coordinates lie within rectangle. + * @param x {number} - x-coordinate to check + * @param y {number} - y-coordinate to check + * @returns {boolean} - returns true if coordinates lie within rectangle, if parameters are isNaN returns false + */ + containsXY(x: number, y: number): boolean; + + /** + * To create a rectangle from a top-left and bottom-right point pair. + * @param topLeft {H.math.IPoint} - the top-left vertex of the rectanle + * @param bottomRight {H.math.IPoint} - the bottom-right vertex of the rectanle + * @returns {H.math.Rect} - returns the rectangular area defined by the top-left and bottom-right vertices + */ + static fromPoints(topLeft: H.math.IPoint, bottomRight: H.math.IPoint): H.math.Rect; + + /** + * To clone a rectangle + * @returns {H.math.Rect} + */ + clone(): H.math.Rect; + } + + /** + * Class for representing sizes consisting of a width and height. + * @property w {number} - The size's width value + * @property h {number} - The size's height value + */ + export class Size { + /** + * Constructor + * @param width {number} - Width. + * @param height {number} - Height. + */ + constructor(width: number, height: number); + w: number; + h: number; + } + } + + /***** net *****/ + export module net { + export module Request { + export enum State { + DONE = 2, + OPENED = 1, + UNSENT = 0, + } + + // TODO no idea how this interface is set up, investigate + export interface Priority { } + } + } + + /***** places *****/ + + /***** service *****/ + export module service { + /** + * Abstract rest service class + */ + export class AbstractRestService implements H.service.IConfigurable { + /** + * Constructor + * @param opt_options {H.service.AbstractRestService.Options=} + */ + constructor(opt_options?: H.service.AbstractRestService.Options); + + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + export module AbstractRestService { + export interface Options { + + } + } + + /** + * This class encapsulates Enterprise Routing REST API as a service stub. An instance of this class can be retrieved by calling the factory method on a platform instance. H.service.Platform#getEnterpriseRoutingService. + */ + export class EnterpriseRoutingService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.EnterpriseRoutingService.Options=} + */ + constructor(opt_options?: H.service.EnterpriseRoutingService.Options); + + /** + * This method sends a "calculateroute" request to Enterprise Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occurred. + * @param calculateRouteParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Enterprise Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + calculateRoute(calculateRouteParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + + /** + * This method sends a "getroute" request to Enterprise Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occurred. + * @param getRouteParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Enterprise Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + getRoute(getRouteParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + + /** + * This method sends a "getlinkinfo" request to Enterprise Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param getLinkInfoParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Enterprise Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + getLinkInfo(getLinkInfoParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + + /** + * This method sends a "calculateisoline" request to Enterprise Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occurred. + * @param calculateIsolineParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Enterprise Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + calculateIsoline(calculateIsolineParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + } + + export module EnterpriseRoutingService { + /** + * @property subDomain {string=} - The sub-domain of the routing service relative to the platform's base URL (default is 'route') + * @property path {string=} - The path of the map tile service, default is "routing/7.2" + * @property baseUrl {H.service.Url=} - The base URL of the service, defaults to the the platform's base URL if instance was created using H.service.Platform#getEnterpriseRoutingService method. + */ + export interface Options { + subDomain?: string; + path?: string; + baseUrl?: H.service.Url; + } + } + + /** + * This class encapsulates the Geocoding REST API in a service stub with calls to its various resources implemented. + */ + export class GeocodingService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.GeocodingService.Options=} + */ + constructor(opt_options?: H.service.GeocodingService.Options); + + /** + * This method sends a reverse geocoding request to Geocoder REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param geoodingParams {H.service.ServiceParameters} - the service parameters to be sent with the geocoding request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Geocoder REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + * @returns {H.service.JsonpRequestHandle} + */ + geocode(geoodingParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): H.service.JsonpRequestHandle; + + /** + * This method sends a reverse geocoding request to Geocoder REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param reverseGeocodingParams {H.service.ServiceParameters} - the service parameters to be sent with the reverse geocoding request + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Geocoder REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + * @returns {H.service.JsonpRequestHandle} + */ + reverseGeocode(reverseGeocodingParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): H.service.JsonpRequestHandle; + + /** + * This method sends a landmark search request to Geocoder REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param searchParams {H.service.ServiceParameters} - the service parameters to be sent with the reverse geocoding request + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Geocoder REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + * @returns {H.service.JsonpRequestHandle} + */ + search(searchParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): H.service.JsonpRequestHandle; + } + + export module GeocodingService { + /** + * @property subDomain {string=} - the sub-domain of the geo-coding service relative to the platform's base URL, default is 'geocoder' + * @property path {string=} - the path of the Geocoding service, default is '6.2' + */ + export interface Options { + subDomain?: string; + path?: string; + } + } + + /** + * An interface represents an object, that can be configured credentials, settings etc. by H.service.Platform + */ + export interface IConfigurable { + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + /** + * @property id {number} - the ID associated internally with this request + * @property cancel {function()} - this function cancels the request and invokes the errback function + */ + export interface JsonpRequestHandle { + id: number; + cancel: () => void; + } + + /** + * This class encapsulates a map tile end point of the HERE Map Tile API. + */ + export class MapTileService extends H.util.EventTarget implements H.service.IConfigurable { + /** + * Constructor + * @param opt_options {H.service.MapTileService.Options=} + */ + constructor(opt_options?: H.service.MapTileService.Options); + + /** + * This method returns the map tile type provided by this service. + * @returns {string} - the map tile type + */ + getType(): string; + + /** + * This method returns the map tile service's newest version hash. + * @returns {string} - meta information for this map tile service + */ + getVersion(): string; + + /** + * This method returns the map tile service's meta information. The method will return an object once the map tile service's data has been fetched. + * @returns {(H.service.MapTileService.Info | undefined)} - meta information for this map tile service + */ + getInfo(): H.service.MapTileService.Info | void; + + /** + * This method creates a tile provider which uses the specified map tiles. This provider can be used as a data source for an ImageTileLayer. + * @param tileType {string} - the tile type + * @param scheme {string} - the tile scheme + * @param tileSize {number} - the tile size + * @param format {string} - the tile image format + * @param opt_additionalParameters {H.service.ServiceParameters=} - a hash of additional parameters to be + * @param opt_options {H.service.TileProviderOptions=} - additional set of options for the provider + * @returns {H.map.provider.ImageTileProvider} - the image tile provider + */ + createTileProvider(tileType: string, scheme: string, tileSize: number, format: string, opt_additionalParameters?: H.service.ServiceParameters, opt_options?: H.service.TileProviderOptions): H.map.provider.ImageTileProvider; + + /** + * This method creates a tile layer. This layer can be used as a layer on a map's data model. + * @param tileType {string} - the tile type + * @param scheme {string} - the tile scheme + * @param tileSize {number} - the tile size + * @param format {string} - the tile image format + * @param opt_additionalParameters {H.service.ServiceParameters=} - Additional parameters for the map tile service + * @param opt_opacity {number=} - The opacity of this layer + * @param opt_dark {boolean=} - Indicates whether the content of this layer is mainly dark, default is false See also H.Map.Options#autoColor + * @param opt_options {H.service.TileProviderOptions=} - additional set of options for the provider + * @returns {H.map.layer.TileLayer} - the tile layer + */ + createTileLayer(tileType: string, scheme: string, tileSize: number, format: string, opt_additionalParameters?: H.service.ServiceParameters, opt_opacity?: number, opt_dark?: boolean, opt_options?: H.service.TileProviderOptions): H.map.layer.TileLayer; + + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + export module MapTileService { + /** + * @property maps {Object} - + * @property schemes {Object} - + * @property tiletypes {Object} - + * @property formats {Object} - + * @property resolutions {Object} - + * @property languages {Object} - + */ + export interface Info { + maps: { [key: string]: any }; + schemes: { [key: string]: any }; + tiletypes: { [key: string]: any }; + formats: { [key: string]: any }; + resolutions: { [key: string]: any }; + languages: { [key: string]: any }; + } + + /** + * @property type {string=} - the type of the map tile service to communicate with, e.g. 'base' (default), 'aerial', etc. (refer to the Map Tile REST API documentation for available types) + * @property version {string=} - the map version hash to use for retrieving tiles, default is newest and will be automatically updated + * @property subDomain {string=} - the sub-domain of the map tile service relative to the platform's base URL, default is 'maps' + * @property path {string=} - the path of the map tile service, default is 'maptile/2.1' + */ + export interface Options { + type?: string; + version?: string; + subDomain?: string; + path?: string; + } + } + + /** + * A map type is an object holding tile layers corresponding to a map type (e.g. 'normal', 'satellite' or 'terrain'). A map type contains at least a map property which defines the basic map layer for a given map type. In addition it can hold other map layers with the given style, e.g. base, xbase, traffic etc. + * @property map {H.map.layer.TileLayer} - the basic map tiles with all features and labels + * @property mapnight {H.map.layer.TileLayer} - the basic map tiles with all features and labels (night mode) + * @property xbase {H.map.layer.TileLayer=} - map tiles without features and labels + * @property xbasenight {H.map.layer.TileLayer=} - map tiles without features and labels (night mode) + * @property base {H.map.layer.TileLayer=} - map tiles without labels + * @property basenight {H.map.layer.TileLayer=} - map tiles without labels (night mode) + * @property traffic {H.map.layer.TileLayer=} - map tiles with traffic flow highlighting + * @property trafficnight {H.map.layer.TileLayer=} - map tiles with traffic flow highlighting (night mode) + * @property transit {H.map.layer.TileLayer=} - map tiles with public transit lines highlighted + * @property panorama {H.map.layer.TileLayer=} - map tiles highlighting areas with HERE StreetLevel coverage + * @property panoramanight {H.map.layer.TileLayer=} - map tiles highlighting areas with HERE StreetLevel coverage (night mode) + * @property labels {H.map.layer.TileLayer=} - transparent map tiles with labels only + */ + export interface MapType { + map: H.map.layer.TileLayer; + mapnight: H.map.layer.TileLayer; + xbase?: H.map.layer.TileLayer; + xbasenight?: H.map.layer.TileLayer; + base?: H.map.layer.TileLayer; + basenight?: H.map.layer.TileLayer; + traffic?: H.map.layer.TileLayer; + trafficnight?: H.map.layer.TileLayer; + transit?: H.map.layer.TileLayer; + panorama?: H.map.layer.TileLayer; + panoramanight?: H.map.layer.TileLayer; + labels?: H.map.layer.TileLayer; + } + + /** + * Places service implements a low level places RestApi access. Please refer to Restful API documentation for providing parameters and handling response objects. + */ + export class PlacesService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.PlacesService.Options=} + */ + constructor(opt_options?: H.service.PlacesService.Options); + + /** + * This is generic method to query places RestAPI. + * @param entryPoint {string} - can be one of available entry points H.service.PlacesService.EntryPoint i.e value of H.service.PlacesService.EntryPoint.SEARCH + * @param entryPointParams {Object} - parameter map key value pairs will be transformed into the url key=value parametes. For entry point parameters description please refer to places restful api documentation documentation for available parameters for chose entry point + * @param onResult {Function} - callback which is called when result is returned + * @param onError {Function} - callback which is called when error occured (i.e request timeout) + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + request(entryPoint: string, entryPointParams: Object, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'search' entry point. Please refer to documentation for parameter specification and response handling. + * @param searchParams {H.service.ServiceParameters} - places api search entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + search(searchParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'suggestions' entry point. Please refer to documentation for parameter specification and response handling. + * @param suggestParams {H.service.ServiceParameters} - places api suggest entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + suggest(suggestParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'explore' entry point. Please refer to documentation for parameter specification and response handling. + * @param exploreParams {H.service.ServiceParameters} - places api explore entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + explore(exploreParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'around' entry point. Please refer to documentation for parameter specification and response handling. + * @param aroundParams {H.service.ServiceParameters} - places api around entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + around(aroundParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'here' entry point. Please refer to documentation for parameter specification and response handling. + * @param hereParams {H.service.ServiceParameters} - places api here entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + here(hereParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'categories' entry point. Please refer to documentation for parameter specification and response handling. + * @param categoriesParams {H.service.ServiceParameters} - places api here entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + categories(categoriesParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * This method should be used to follow hyperlinks available in results returned by dicovery queries. + * @param hyperlink {string} + * @param onResult {Function} + * @param onError {Function} + * @param opt_additionalParameters {Object=} - additional parameters to send with request + * @returns {H.service.JsonpRequestHandle} - jsonp resquest handle + */ + follow(hyperlink: string, onResult: Function, onError: Function, opt_additionalParameters?: Object): H.service.JsonpRequestHandle; + } + + export module PlacesService { + /** + * List of available entry points + */ + export enum EntryPoint { + SEARCH, + SUGGEST, + EXPLORE, + AROUND, + HERE, + CATEGORIES, + } + + /** + * @property subDomain {string=} - the sub-domain of the places service relative to the platform's base URL, default is 'places' + * @property path {string=} - the path of the places service, default is 'places/v1' + * @property baseUrl {H.service.Url=} - an optional base URL if it differs from the platform's default base URL + */ + export interface Options { + subDomain?: string; + path?: string; + baseUrl?: H.service.Url; + } + } + + /** + * The Platform class represents central class from which all other service stubs are created. It also contains the shared settings to be passed to the individual service stubs, for example the root URL of the platform, application credentials, etc. + */ + export class Platform { + /** + * Constructor + * @param options {H.service.Platform.Options} + */ + constructor(options: H.service.Platform.Options); + + /** + * Method attempts to configure object that implements H.service.IConfigurable + * @param configurable {H.service.IConfigurable} + * @returns {H.service.IConfigurable} + */ + configure(configurable: H.service.IConfigurable): H.service.IConfigurable; + + /** + * This method enables or disables HTTPS communication with the platform + * @param useHTTPS {boolean} - a boolean value indicating whether to communicate with the platform via HTTPS + */ + setUseHTTPS(useHTTPS: boolean): void; + + /** + * This method configures whether to use the "customer integration testing" instance of the platform. + * @param useCIT {boolean} - a boolean value indicating whether the CIT platform instance is to be used + */ + setUseCIT(useCIT: boolean): void; + + /** + * This method modifies the base URL to be used when creating service stubs. + * @param baseUrl {H.service.Url} - the new base URL to use + */ + setBaseUrl(baseUrl: H.service.Url): void; + + /** + * This method returns the currently used base URL. + * @returns {H.service.Url} + */ + getBaseUrl(): H.service.Url; + + /** + * This method returns an instance of H.service.TrafficIncidentsService to query the Traffic API Traffic Incident Data + * @returns {H.service.TrafficIncidentsService} - a new places service instance + */ + getTrafficIncidentsService(): H.service.TrafficIncidentsService; + + /** + * This method returns an instance of H.service.MapTileService to query the Map Tile API. + * @param opt_options {H.service.MapTileService.Options=} + * @returns {H.service.MapTileService} + */ + getMapTileService(opt_options?: H.service.MapTileService.Options): H.service.MapTileService; + + /** + * This method returns an instance of H.service.venues.Service to query the Venue Maps API + * @param opt_params {H.service.venues.Service.Options=} - additional service parameters + * @returns {H.service.venues.Service} + */ + getVenueService(opt_params?: H.service.venues.Service.Options): H.service.venues.Service; + + /** + * This method returns an instance of H.service.metaInfo.Service to query the Map Tile API Metainfo Tiles + * @param opt_params {H.service.metaInfo.Service.Options=} - additional service parameters + * @returns {H.service.metaInfo.Service} + */ + getMetaInfoService(opt_params?: H.service.metaInfo.Service.Options): H.service.metaInfo.Service; + + /** + * This method creates a pre-configured set of HERE tile layers for convenient use with the map. + * @param opt_tileSize {(H.service.Platform.DefaultLayersOptions | number)=} - When a number – optional tile size to be queried from the HERE Map Tile API, default is 256. If the parameter is an object, then it represents options and all remaining below parameters should be omitted. + * @param opt_ppi {number=} - optional 'ppi' parameter to use when querying tiles, default is not specified + * @param opt_lang {string=} - optional primary language parameter, default is not specified + * @param opt_secondaryLang {string=} - optional secondary language parameter, default is not specified + * @param opt_style {string=} - optional 'style' parameter to use when querying map tiles, default is not specified + * @param opt_pois {(string | boolean)=} - indicates if pois are displayed on the map. Pass true to indicate that all pois should be visible. Alternatively you can specify mask for the POI Categories as described at the Map Tile API documentation POI Categories chapter. + * @returns {Object} - a set of tile layers ready to use + */ + createDefaultLayers(opt_tileSize?: (H.service.Platform.DefaultLayersOptions | number), opt_ppi?: number, opt_lang?: string, opt_secondaryLang?: string, opt_style?: string, opt_pois?: (string | boolean)): H.service.Platform.MapTypes; + + /** + * This method returns an instance of H.service.RoutingService to query the Routing API. + * @param opt_options {H.service.RoutingService.Options=} + * @returns {H.service.RoutingService} + */ + getRoutingService(opt_options?: H.service.RoutingService.Options): H.service.RoutingService; + + /** + * This method returns an instance of H.service.GeocodingService to query the Geocoder API + * @param opt_options {H.service.GeocodingService.Options=} - an optional set of options for the new geocoding service to connect to + * @returns {H.service.GeocodingService} - a new geocoding service instance + */ + getGeocodingService(opt_options?: H.service.GeocodingService.Options): H.service.GeocodingService; + + /** + * This method returns an instance of H.service.PlacesService to query the Places API. + * @returns {H.service.PlacesService} - a new places service instance + */ + getPlacesService(): H.service.PlacesService; + + /** + * This method returns an instance of H.service.EnterpriseRoutingService to query the Enterprise Routing API. + * @param opt_options {H.service.EnterpriseRoutingService.Options=} + * @returns {H.service.EnterpriseRoutingService} + */ + getEnterpriseRoutingService(opt_options?: H.service.EnterpriseRoutingService.Options): H.service.EnterpriseRoutingService; + } + + export module Platform { + /** + * Options used to create default layers + * @property tileSize {number=} - tile size to be queried from the HERE Map Tile API, default is 256 + * @property ppi {number=} - 'ppi' parameter to use when querying tiles, default is not specified + * @property lg {string=} - optional primary language parameter, default is not specified + * @property lg2 {string=} - optional secondary language parameter, default is not specified + * @property style {string=} - optional 'style' parameter to use when querying map tiles, default is not specified + * @property pois {boolean=} - indicates if pois are displayed on the map + * @property crossOrigin {(string | boolean=)} - indicates if CORS headers should be used for default layers, if false is specified, CORS headers are not set, defaults to 'anonymous'. Be aware that storing of content is not possible if crossOrigin is not set to true (see H.Map#storeContent). + */ + export interface DefaultLayersOptions { + tileSize?: number; + ppi?: number; + lg?: string; + lg2?: string; + style?: string; + pois?: boolean; + crossOrigin?: (string | boolean); + } + + /** + * @property app_id {string} - The application ID to identify the client against the platform (mandatory to provide) + * @property app_code {string} - The application code to identify the client against the platform (mandatory to provide) + * @property baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com + * @property useCIT {boolean=} - Indicates whether the Customer Integration Testing should be used, default is false + * @property useHTTPS {boolean=} - Indicates whether secure communication should be used, default is false + */ + export interface Options { + app_id: string; + app_code: string; + baseUrl?: H.service.Url; + useCIT?: boolean; + useHTTPS?: boolean; + } + + /** + * pre-configured set of HERE tile layers for convenient use with the map. + */ + export interface MapTypes { + normal?: H.service.MapType; + satellite?: H.service.MapType; + terrain?: H.service.MapType; + [key: string]: H.service.MapType; + } + } + + /** + * This class encapsulates the Routing REST API as a service stub. An instance of this class can be retrieved by calling the factory method on a platform instance. H.service.Platform#getRoutingService. + */ + export class RoutingService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.RoutingService.Options=} + */ + constructor(opt_options?: H.service.RoutingService.Options); + + /** + * This method sends a "calculateroute" request to Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param calculateRouteParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + calculateRoute(calculateRouteParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + } + + export module RoutingService { + /** + * @property subDomain {string=} - the sub-domain of the routing service relative to the platform's base URL, default is 'route' + * @property path {string=} - the path of the map tile service, default is 'routing/7.2' + * @property baseUrl {H.service.Url=} - an optional base URL if it differs from the platform's default base URL + */ + export interface Options { + subDomain?: string; + path?: string; + baseUrl?: H.service.Url; + } + } + + /** + * This type encapsulates URL parameters to be sent to a HERE platform service. + */ + export interface ServiceParameters { + [key: string]: string; + } + + /** + * This type encapsulates a response object provider by a HERE platform service. + */ + export interface ServiceResult { + [key: string]: string; + } + + /** + * Options which are used to initialize the tile provider. + * @property crossOrigin {boolean=} - The string to be set for the crossOrigin attribute for loaded images + */ + export interface TileProviderOptions { + crossOrigin?: boolean; + } + + /** + * TrafficIncindentsService provides functionality to the low level traffic incidents api Traffic API documentation where it is possible to retrieve traffic incident information on a tile basis + */ + export class TrafficIncidentsService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.TrafficIncidentsService.Options=} + */ + constructor(opt_options?: H.service.TrafficIncidentsService.Options); + + /** + * This method requests traffic incidents based on the service parameters provided. + * @param serviceParams {H.service.ServiceParameters} + * @param onResponse {function(H.service.ServiceResult)} + * @param onError {function()} + * @returns {H.service.JsonpRequestHandle} + */ + requestIncidents(serviceParams: H.service.ServiceParameters, onResponse: (result: H.service.ServiceResult) => void, onError: () => void): H.service.JsonpRequestHandle; + + /** + * This method requests traffic incident information by tile coordinates + * @param x {number} - tile column number + * @param y {number} - tile row number + * @param z {number} - zoom level + * @param onResponse {function(H.service.ServiceResult)} - callback to handle service resposne + * @param onError {function()} - callback to habdle communication error + * @param opt_serviceParams {H.service.ServiceParameters=} - optional service parameters to be added to the request + * @returns {H.service.JsonpRequestHandle} + */ + requestIncidentsByTile(x: number, y: number, z: number, onResponse: (result: H.service.ServiceResult) => void, onError: () => void, opt_serviceParams?: H.service.ServiceParameters): H.service.JsonpRequestHandle; + } + + export module TrafficIncidentsService { + /** + * @property subDomain {string=} - the sub-domain of the traffic incidents service relative to the platform's base URL, default is 'traffic' + * @property path {string=} - the path of the traffic incidents service, default is 'traffic/6.1' + * @property baseUrl {H.service.Url=} - an optional base URL if it differs from the platform's default base URL + */ + export interface Options { + subDomain?: string; + path?: string; + baseUrl?: H.service.Url; + } + } + + /** + * This class represents a URL giving access to the individual parts that make up a URL,such as the scheme, host/domain, path, etc. Use the static parse method to populate a new URL object from a URL string. Be aware that URLs with user and password like "ftp://user:password@foo.bar/" are not supported! + */ + export class Url { + /** + * Constructor + * @param scheme {string} - the URL scheme (e.g. "http" or "https" or "mailto") + * @param host {string} - the host (or domain) part of the URL + * @param opt_path {string=} - the path following the host pointing to a resource + * @param opt_params {Object=} - the query string parameters of this URL + * @param opt_port {number=} - The port of the host on which the host listens. If a string is passed it must be convertible to an integer. + * @param opt_anchor {string=} - an optional anchor part of the URL (usually preceded by '#'); + */ + constructor(scheme: string, host: string, opt_path?: string, opt_params?: Object, opt_port?: number, opt_anchor?: string); + + /** + * This function parses a URL string and returns a H.service.Url object. The URL string must contain at least a scheme and a host. + * @param url {string} - The URL string to parse. + * @param opt_baseURL {string=} - The base URL to use to resolve relative URLs. If ommited the base URL of the document which loaded the API is taken. + * @returns {H.service.Url} - the parsed URL object + */ + static parse(url: string, opt_baseURL?: string): H.service.Url; + + /** + * Clones this URL object. Optionally, mutations can be passed to this function to modify properties of the cloned object. Note that URL parameters are not replaced but merged with the parameters of this instance. + * @returns {H.service.Url} - the clone of the URL object + */ + clone(): H.service.Url; + + /** + * This function sets the scheme of this URL object. + * @param scheme {string} - the new scheme + * @returns {H.service.Url} - this URL object + */ + setScheme(scheme: string): H.service.Url; + + /** + * This function returns the scheme of this Url object. + * @returns {string} - the scheme (for example 'http') + */ + getScheme(): string; + + /** + * This function sets the host of this URL object. + * @param host {string} - the new host + * @returns {H.service.Url} - this URL object + */ + setHost(host: string): H.service.Url; + + /** + * This function returns the host name of this Url object. + * @returns {string} - the host (for example 'api.here.com') + */ + getHost(): string; + + /** + * This function sets the path of this URL object. + * @param path {(string | undefined)} - the new path or a boolean to clear the path + * @returns {H.service.Url} - this URL object + */ + setPath(path: string | boolean): H.service.Url; + + /** + * This function returns the path part of this Url object. + * @returns {(string | undefined)} - the path (for example 'myresources/resource.html') + */ + getPath(): string | void; + + /** + * This function sets the specified parameters for this URL object. Keys in this object, which are associated with undefined values will be treated as query string parameters with no value. + * @param params {(Object | undefined)} - a hash of query string parameters specifying the parameters to be set.or a boolean to clear the parameters. + * @returns {H.service.Url} - this URL object + */ + setQuery(params?: Object | boolean): H.service.Url; + + /** + * This function returns a boolean value indicating whether there are any query string parameter associated with this URL. + * @returns {boolean} - true if there are parameters, false if none are present + */ + hasQuery(): boolean; + + /** + * This function returns the query object of this Url object. + * @returns {Object} - the query object + */ + getQuery(): Object; + + /** + * This function sets the anchor of this URL object. + * @param anchor {(string | boolean | undefined)} - the new anchor or undefined to clear the anchor + * @returns {H.service.Url} - this URL object + */ + setAnchor(anchor?: string | boolean): H.service.Url; + + /** + * This function returns the anchor of this Url object. + * @returns {(string | undefined)} - the anchor + */ + getAnchor(): string | void; + + /** + * This function merges the provided parameters into this URL's existing parameters. Key-value pairs which are defined in the argument and this URL's parameters will be overwritten. Key-value pairs which are defined in the argument and are not defined in this URL's parameters will be added. Prototype properties and function properties will not be merged. + * @param other {Object} - the parmeters to be merged into this URL's query string parameters + * @returns {H.service.Url} - this URL object + */ + mergeQuery(other: Object): H.service.Url; + + /** + * This function adds a sub-domain to the host of this URL object. + * @param subDomain {string} - the sub domain (non-empty string) to be added + * @returns {H.service.Url} - this URL object + */ + addSubDomain(subDomain: string): H.service.Url; + + /** + * This function adds a sub-path to this URL's path + * @param subPath {string} - the path to be added + * @returns {H.service.Url} - this URL object + */ + addSubPath(subPath: string): H.service.Url; + + /** + * This function formats this URL object to a full URL string. + * @returns {string} - the URL's string representation + */ + toString(): string; + } + + export module metaInfo { + /** + * This class encapsulates a Metainfo Tile end point of the HERE Map Tile API. + */ + export class Service extends H.util.EventTarget implements H.service.IConfigurable { + /** + * Constructor + * @param opt_options {H.service.metaInfo.Service.Options=} - additional service parameters + */ + constructor(opt_options?: H.service.metaInfo.Service.Options); + + /** + * This method returns the meta info tile service's newest version hash. + * @returns {string} - meta information for this map tile service + */ + getVersion(): string; + + /** + * This method returns the meta info tile service's meta information. The method will return an object once the map tile service's data has been fetched. + * @returns {(H.service.metaInfo.Service.Info | undefined)} - meta information for this meta info tile service + */ + getInfo(): H.service.metaInfo.Service.Info | void; + + /** + * This method creates a tile provider which uses the meta info tile backend. This provider can be used as a data source for an TileLayer. + * @param tileSize {number} - The tile size + * @param pixelRatio {number} - The tile's pixel ratio, should be aligned with base map tile + * @param opt_categoryFilter {Array=} - A list of meta-info category names which should be suppressed. See Metainfo Tile for valid category names. + * @param opt_additionalParameters {H.service.ServiceParameters=} - Additional parameters for the meta info service + * @param opt_tileType {string=} - the tile type (default is 'maptile') + * @param opt_scheme {string=} - the scheme for which the meta info tiles a requested (default is 'normal.day') + * @returns {H.map.provider.TileProvider} - the tile provider + */ + createTileProvider(tileSize: number, pixelRatio: number, opt_categoryFilter?: Array, opt_additionalParameters?: H.service.ServiceParameters, opt_tileType?: string, opt_scheme?: string): H.map.provider.TileProvider; + + /** + * This method creates a tile layer. This layer can be used as a layer on a map's data model. + * @param tileSize {number} - The tile size + * @param pixelRatio {number} - The tile's pixel ratio, should be aligned with base map tile + * @param opt_categoryFilter {Array=} - A list of meta-info category names which should be suppressed. See Metainfo Tile for valid category names. + * @param opt_additionalParameters {H.service.ServiceParameters=} - Additional parameters for the meta info service + * @param opt_tileType {string=} - the tile type (default is 'maptile') + * @param opt_scheme {string=} - the scheme for which the meta info tiles a requested (default is 'normal.day') + * @returns {H.map.layer.TileLayer} - the tile layer + */ + createTileLayer(tileSize: number, pixelRatio: number, opt_categoryFilter?: Array, opt_additionalParameters?: H.service.ServiceParameters, opt_tileType?: string, opt_scheme?: string): H.map.layer.TileLayer; + + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + export module Service { + /** + * @property maps {Object} - + * @property schemes {Object} - + * @property tiletypes {Object} - + * @property formats {Object} - + * @property resolutions {Object} - + * @property languages {Object} - + */ + export interface Info { + maps: { [key: string]: any }; + schemes: { [key: string]: any }; + tiletypes: { [key: string]: any }; + formats: { [key: string]: any }; + resolutions: { [key: string]: any }; + languages: { [key: string]: any }; + } + + /** + * @property type {string=} - the type of the map tile service to communicate with, e.g. 'base' (default), 'aerial', etc. (refer to the Map Tile REST API documentation for available types) + * @property version {string=} - the map version hash to use for retrieving tiles, default is newest and will be automatically updated + * @property subDomain {string=} - the sub-domain of the map tile service relative to the platform's base URL, default is 'maps' + */ + export interface Options { + type?: string; + version?: string; + subDomain?: string; + } + } + + /** + * This class utilizes Metainfo Tiles functionality provided by the Map Tile API to load meta information about map objects (buildings, labels, public transport etc.). + */ + export class TileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param service {(H.service.metaInfo.Service | H.service.MapTileService)} - the tile service which holds information from about the source of the tiles + * @param opt_params {H.service.ServiceParameters=} - an additional set of URL parameters + * @param opt_options {H.service.metaInfo.TileProvider.Options=} - additional parameters + */ + constructor(service: (H.service.metaInfo.Service | H.service.MapTileService), opt_params?: H.service.ServiceParameters, opt_options?: H.service.metaInfo.TileProvider.Options); + } + + export module TileProvider { + /** + * Configuration object which can be used to initialize the TileProvider. + * @property tileType {string=} - The tile type for which to request meta info + * @property scheme {string=} - The map scheme for which to request meta info + * @property tileCacheSize {number=} - The number of fully rendered spatial tiles that are cached for immediate reuse, default is 32 + * @property tileSize {number=} - The size of the tiles rendered by this provider (must be power of 2, default is 256) + * @property pixelRatio {number=} - The pixel ratio to use for over-sampling in cases of high-resolution displays + * @property categoryFilter {Array=} - A list of meta-info category names which should be suppressed. See Metainfo Tile for valid category names. + */ + export interface Options { + tileType?: string; + scheme?: string; + tileCacheSize?: number; + tileSize?: number; + pixelRatio?: number; + categoryFilter?: Array; + } + } + } + + export module venues { + /** + * The class represents the building in the venue hiearachy (see H.service.venues.Venue) and holds floors that belong to the building. + */ + export class Building extends H.map.Group { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - The object provider of this venue building + * @param uid {string} - The unique identifier of this building + * @param minLevel {number} - The minimum floor level of this building + * @param maxLevel {number} - The maximum floor level of this building + */ + constructor(provider: H.map.provider.ObjectProvider, uid: string, minLevel: number, maxLevel: number); + + /** + * Method returns the parent object - venue (see H.service.venues.Venue) to which the building belongs to. + * @returns {H.service.venues.Venue} + */ + getVenue(): H.service.venues.Venue; + + /** + * Method returns the minimum floor level of this building. + * @returns {number} + */ + getMinLevel(): number; + + /** + * Method returns the maximum floor level of this building + * @returns {number} + */ + getMaxLevel(): number; + + /** + * Method returns the floor (see H.service.venues.Floor) if one was already loaded. This method doesn't make attempt to fetch the floor data. + * @param level {number} - floor level within minimum and maximum level boundaries for the building + * @returns {(H.service.venues.Floor | undefined)} - The floor object or undefined if floor was not loaded + */ + getFloor(level: number): H.service.venues.Floor | void; + } + + /** + * The class represents the floor object in the venue hierarchy (see H.service.venues.Venue). The class holds information about floor geometry and spaces (see H.service.venues.Space) that belong to this floor. + */ + export class Floor extends H.map.Group { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - The object provider of this venue floor + * @param data {*} - The meta data of this floor + * @param level {number} - The level of this floor + */ + constructor(provider: H.map.provider.ObjectProvider, data: any, level: number); + + /** + * Method returns the level of the floor in the building. + * @returns {number} + */ + getLevel(): number; + + /** + * Method returns map geometry that represents floor boundaries. + * @returns {(H.service.venues.Space | undefined)} + */ + getFloorSpace(): H.service.venues.Space | void; + + /** + * Method returns the H.map.Group of all spaces that belong to the floor. + * @returns {H.map.Group} + */ + getSpaces(): H.map.Group; + + /** + * Method returns parent object - building (see H.service.venues.Building) of the floor. + * @returns {H.service.venues.Building} + */ + getBuilding(): H.service.venues.Building; + + /** + * Method returns raw data associated with the floor. For more details on data format see http://developer.here.com/rest-apis/documentation/venue-maps/topics/resource-type-venue-interaction-tile-floor.html + * @returns {*} - the raw floor data object + */ + getData(): any; + + /** + * Method returns the space object with the given ID, that belongs to the floor. + * @param id {string} - The ID of the space. + * @returns {(H.service.venues.Space | undefined)} - The requested space or undefined if space not found. + */ + getSpace(id: string): H.service.venues.Space | void; + } + + /** + * This class encapsulates methods to call Venue Maps API endpoints. + */ + export class Service extends H.util.EventTarget implements H.service.IConfigurable { + /** + * Constructor + * @param opt_options {H.service.venues.Service.Options=} - additional service parameters + */ + constructor(opt_options?: H.service.venues.Service.Options); + + /** + * This method sends a discovery request to the Venue Maps API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object, or the onError callback if a communication error occured. + * @param serviceParams {H.service.ServiceParameters} - the service parameters to be sent with the discovery request + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Venue Maps API provides a response to the request + * @param onError {function(string)} - this function will be called if a communication error occurs during request and error type is passed as an argument + */ + discover(serviceParams: H.service.ServiceParameters, onResult: (res: H.service.ServiceResult) => void, onError: (s: string) => void): void; + + /** + * This method creates a tile layer which can be added to the map in order to see the venues. It uses Interaction Tile endpoint of the Venue Maps API, more at http://developer.here.com/rest-apis/documentation/venue-maps/topics/quick-start-get-interaction-tile.html. + * @param opt_options {H.service.venues.TileProvider.Options=} - Tile provider options + * @returns {H.map.layer.TileLayer} - the tile layer + */ + createTileLayer(opt_options?: H.service.venues.TileProvider.Options): H.map.layer.TileLayer; + + /** + * Method returns current state of the service. + * @returns {H.service.venues.Service.State} - State of the service + */ + getState(): H.service.venues.Service.State; + + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + export module Service { + /** + * @property subDomain {string=} - the sub-domain of the Venue Maps service relative to the platform's base URL, default is 'venue.maps' + * @property path {string=} - the path to append after host name when making requests to the Venue Maps API, default is empty + */ + export interface Options { + subDomain?: string; + path?: string; + } + + /** + * The state types of the H.service.venues.Service. Possible states are: + */ + export enum State { + ERROR, + INIT, + READY, + } + } + + /** + * Represents a spatial object for this space. Each space object contains data associated with that space and can be retrieved by using H.service.venues.Space#getData method. + */ + export class Space { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - The provider of this object. + * @param uid {string} - The unique identifier of this space + * @param data {*} - The meta data of this space + * @param opt_isFloorSpace {boolean=} - Indicates whether this space represents a floor itself, defaults to false + */ + constructor(provider: H.map.provider.ObjectProvider, uid: string, data?: any, opt_isFloorSpace?: boolean); + + /** + * The method indicates whether the spatial object represents the whole floor space or a space within a floor boundaries, that belongs to the floor. + * @returns {boolean} - True if this spatial object represents the floor space. + */ + isFloorSpace(): boolean; + + /** + * This method sets custom style to use for rendering the labels. Should be called before the first render of the space, otherwise has no any effect. Note that due to the design consistency currently it is not allowed to change the font family and the size of the labels. + * @param labelStyle {(H.map.SpatialStyle | H.map.SpatialStyle.Options)} - Custom label style + */ + initLabelStyle(labelStyle: (H.map.SpatialStyle | H.map.SpatialStyle.Options)): void; + + /** + * Method returns parent object - floor (see H.service.venues.Floor) of the space. + * @returns {H.service.venues.Floor} + */ + getFloor(): H.service.venues.Floor; + + /** + * Method returns raw data associated with the space. For more details on data format see http://developer.here.com/rest-apis/documentation/venue-maps/topics/resource-type-venue-interaction-tile-space.html + * @returns {Object} - raw space data object + */ + getData(): Object; + } + + /** + * This class represents a Venue Maps tile provider which requests venues tiles from a platform venue tile service. + */ + export class TileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param service {H.service.venues.Service} + * @param opt_options {H.service.venues.TileProvider.Options=} + */ + constructor(service: H.service.venues.Service, opt_options?: H.service.venues.TileProvider.Options); + + /** + * Method specifies which floor level of the venues must be fetched by provider. Floor level is global to all venues and defaults to 0. + * @param level {number} + */ + setCurrentLevel(level: number): void; + + /** + * Method returns the floor level that provider uses for tile fetching. + * @returns {number} - current provider's floor level + */ + getCurrentLevel(): number; + } + + export module TileProvider { + /** + * Configuration object which can be used to initialize the TileProvider. + * @property tileCacheSize {number=} - The number of fully rendered spatial tiles that are cached for immediate reuse, default is 32 + * @property pixelRatio {number=} - The pixel ratio to use for over-sampling in cases of high-resolution displays + * @property onSpaceCreated {function(H.service.venues.Space)=} - A callback function that is called on every created space (see H.service.venues.Space) object. The function can be used for space object styling. + */ + export interface Options { + tileCacheSize?: number; + pixelRatio?: number; + onSpaceCreated?: (space: H.service.venues.Space) => void; + } + } + + /** + * The class represents the venue, it is a root for the venue object heirarchy. The venue inherits from H.map.Group and holds building objects (see H.service.venues.Building). Building objects hold floor objects (see H.service.venues.Floor) and inherit from H.map.Group as well. Leaf objects are spaces (see H.service.venues.Space) that are spatial map objects and reside inside floor containers. + */ + export class Venue extends H.map.Group { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - The object provider of this venue + * @param uid {string} - The unique identifier of this venue + */ + constructor(provider: H.map.provider.ObjectProvider, uid: string); + + /** + * Method returns the building object, that belongs to the venue, with the given ID . The method doesn't attempt to fetch building data. + * @param id {string} - the ID of the building + * @returns {(H.service.venues.Building | undefined)} - The requested building or undefined if building wasn't loaded + */ + getBuilding(id: string): H.service.venues.Building | void; + + /** + * Method returns map of all loaded buildings associated with the venue. + * @returns {Object<*, H.service.venues.Building>} + */ + getBuildings(): any; + } + } + } + + /***** ui *****/ + export module ui { + /** + * This class represents the base class for UI controls on the map. + */ + export class Control extends H.ui.base.Container { + /** + * This abstract method can be overridden by deriving classes to be invoked when the UI object's unit system changes. + * @param unitSystem {H.ui.UnitSystem} - the unit system the UI currently uses + */ + onUnitSystemChange(unitSystem: H.ui.UnitSystem): void; + + /** + * This abstract method can be overridden by deriving classes to be invoked when the underlying map engine changes. + * @param engineType {H.Map.EngineType} - the engine type the map currently uses + */ + onMapEngineTypeChange(engineType: H.Map.EngineType): void; + + /** + * This method returns the map to which this control is attached. + * @returns {?H.Map} - return the map + */ + getMap(): H.Map; + + /** + * This method returns the localization object which corresponds to the UI's current locale. + * @returns {H.ui.i18n.Localization} + */ + getLocalization(): H.ui.i18n.Localization; + + /** + * This method returns this control's layout alignment. + * @returns {H.ui.LayoutAlignment} - the control's current layout alignment + */ + getAlignment(): H.ui.LayoutAlignment; + + /** + * This method sets the control's layout alignments. + * @param alignment {H.ui.LayoutAlignment} - The new alignment of the control + * @returns {H.ui.Control} - returns this control instance + */ + setAlignment(alignment: H.ui.LayoutAlignment): H.ui.Control; + } + + /** + * This class represents a distance measurement control which helps calculating distances between geographical locations indicated by the user clicks. + */ + export class DistanceMeasurement extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.DistanceMeasurement.Options=} - optional parameters to be passed to this control + */ + constructor(opt_options?: H.ui.DistanceMeasurement.Options); + } + + export module DistanceMeasurement { + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.RIGHT_BOTTOM + * @property startIcon {H.map.Icon=} - the icon to use for the first measurement point + * @property stopoverIcon {H.map.Icon=} - the icon to use for the intermediate measurement points + * @property endIcon {H.map.Icon=} - the icon to use for the last measurement point + * @property splitIcon {H.map.Icon=} - the icon to use for indicating position under pointer over the line where new point will be created once user clicks + * @property lineStyle {(H.map.SpatialStyle | H.map.SpatialStyle.Options)} - the style to use for connecting lines of the measurement points + * @property distanceFormatter {function(number)=} - Optional function used for formatting a distance. By default distance measurement tool will do the formatting according to the specified measurement unit (see H.ui.UI.Options#unitSystem) + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + startIcon?: H.map.Icon; + stopoverIcon?: H.map.Icon; + endIcon?: H.map.Icon; + splitIcon?: H.map.Icon; + lineStyle: H.map.SpatialStyle | H.map.SpatialStyle.Options; + distanceFormatter?(n: number): void; + } + } + + /** + * This class represents an information bubble bound to a geo-position on the map. + */ + export class InfoBubble extends base.Element { + /** + * Constructor + * @param position {H.geo.IPoint} - the geo-position to which this info bubble corresponds + * @param opt_options {H.ui.InfoBubble.Options=} - optional parameters to be passed to the info bubble + */ + constructor(position: H.geo.IPoint, opt_options?: InfoBubble.Options); + + /** + * This method sets the geo-position of this info bubble + * @param position {(H.geo.IPoint | H.geo.Point)} - the new geo-position of this bubble + */ + setPosition(position: H.geo.IPoint | H.geo.Point): void; + + /** + * This method returns this info bubble's current state. + * @returns {H.ui.InfoBubble.State} - this bubble's current state + */ + getState(): InfoBubble.State; + + /** + * This method sets the info bubble's state. + * @param state {H.ui.InfoBubble.State} - the new state + */ + setState(state: InfoBubble.State): void; + + /** + * This method closes the info bubble (setting its state to CLOSED) + */ + close(): void; + + /** + * This method opens the info bubble (setting its state to OPEN) + */ + open(): void; + + /** + * This method returns the bubble's content element. + * + * Note: Before adding an info bubble to a UI object the content element is null. + * @returns {?HTMLElement} - the content element of this info bubble + */ + getContentElement(): HTMLElement; + + /** + * This methods sets the content of the info bubble. This can either be a string (applied as innerHTML) to the content element of this info bubble or a HTML node which is appended to the content element. + * @param content {(string | Node)} - the content for this bubble + */ + setContent(content: string | Node): void; + } + + export module InfoBubble { + /** + * This enumeration holds the state an info bubble can have. + */ + export enum State { + /** This value represents the state where an info bubble is open and visible (value: 'open'). */ + OPEN, + /** This value represents the state where an info bubble is closed and invisible (value: 'closed') */ + CLOSED, + } + + export interface Options { + /** + * a callback to be invoked when the info bubble's state changes + * @param event {H.util.Event} + */ + onStateChange?(event: H.util.Event): void; + + /** + * content to be added to the info bubble + */ + content: string | Node; + } + } + + /** + * This enumeration holds the possible layout alignments for the UI elements. + */ + export enum LayoutAlignment { + TOP_LEFT, + TOP_CENTER, + TOP_RIGHT, + LEFT_TOP, + LEFT_MIDDLE, + LEFT_BOTTOM, + RIGHT_TOP, + RIGHT_MIDDLE, + RIGHT_BOTTOM, + BOTTOM_LEFT, + BOTTOM_CENTER, + BOTTOM_RIGHT, + } + + /** + * This class represents a menu control allowing to control which map type the map shows, etc. + */ + export class MapSettingsControl extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.MapSettingsControl.Options=} - optional parameters to be passed to this control + */ + constructor(opt_options?: H.ui.MapSettingsControl.Options); + + /** + * Sets the traffic incidents layer to be shown when activating the respective button on the map settings control. + * @param incidentsLayer {H.map.layer.Layer} - the incidents layer + */ + setIncidentsLayer(incidentsLayer: H.map.layer.Layer): void; + } + + export module MapSettingsControl { + /** + * The map type entry is an object containing a display name and a map type object to which it refers. + * @property name {string} - label which describes the map type + * @property mapType {H.service.MapType} - reference to map type + */ + export interface MapTypeEntry { + name: string; + mapType: H.service.MapType; + } + + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.BOTTOM_RIGHT + * @property entries {Array=} - the map type entries to be shown in this map settings control + * @property incidents {H.map.layer.Layer} - the traffic incidents layer to be activated by the map settings control + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + entries?: Array; + incidents: H.map.layer.Layer; + } + } + + /** + * This class represents the UI controls for panorama + */ + export class Pano extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.Pano.Options=} - optional parameters to be passed to the map. + */ + constructor(opt_options?: H.ui.Pano.Options); + } + + export module Pano { + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.RIGHT_BOTTOM + * @property mapTypes {H.service.MapTypes} - The map types to use + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + mapTypes: H.service.MapType; + } + } + + /** + * This class represents a UI element showing the current zoom scale. + */ + export class ScaleBar { + /** + * Constructor + * @param opt_options {H.ui.ScaleBar.Options=} - optional parameters to be passed to this scale bar. + */ + constructor(opt_options?: H.ui.ScaleBar.Options); + } + + export module ScaleBar { + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.BOTTOM_RIGHT + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + } + } + + /** + * This class encapsulates map UI functionality. + */ + export class UI implements H.util.ICapturable { + /** + * Constructor + * @param map {H.Map} + * @param opt_options {H.ui.UI.Options=} + */ + constructor(map: H.Map, opt_options?: UI.Options); + + /** + * This method returns this ui's root element. + * @returns {ELement} - the root element + */ + getElement(): Element; + + /** + * Returns the map instance to which this UI was added. + * @returns {H.Map} + */ + getMap(): H.Map; + + /** + * This method returns this UI object's current unit system. + * @returns {H.ui.UnitSystem} - the current unit system + */ + getUnitSystem(): UnitSystem; + + /** + * This method sets this UI object's unit system for displaying distances. + * @param unitSystem {H.ui.UnitSystem} - the unit system to use + */ + setUnitSystem(unitSystem: UnitSystem): void; + + /** + * Toggles this UI's unit system between {@link H.ui.UnitSystem.METRIC} and {@link H.ui.UnitSystem.IMPERIAL}. + */ + toggleUnitSystem(): void; + + /** + * This method adds an info bubble to the UI. + * @param bubble {H.ui.InfoBubble} - the info bubble to be added + */ + addBubble(bubble: InfoBubble): void; + + /** + * This method removes a previously added info bubble from the UI. + * @param bubble {H.ui.InfoBubble} - the info bubble to be removed + */ + removeBubble(bubble: InfoBubble): void; + + /** + * This method returns a list of info bubble objects which are currently attached to this UI. + * @returns {Array} - the list of info bubbles + */ + getBubbles(): Array; + + /** + * This method appends a control to the UI. + * @param name {string} - the name under which to register this control + * @param control {H.ui.Control} - the control to add to this UI + */ + addControl(name: string, control: Control): void; + + /** + * Removes a previously registered control from the UI object. + * @param name {string} - the name under which this control was previously registered + * @returns {H.ui.Control} - the removed control + */ + removeControl(name: string): Control; + + /** + * This method returns a UI control which was previously registered with the provided name. + * @param name {string} - the name under which the control was registered. + * @returns {H.ui.Control} - the control or undefined if the control does not exist. + */ + getControl(name: string): Control; + + /** + * This function creates the default UI including the zoom control, + * map settings control and scalebar and panorama discovery control. + * The default controls will be assigned the following values: + * + * Zoom control: + * id: 'zoom' + * alignment: 'right-middle' + * Map settings control: + * id: 'mapsettings' + * alignment: 'bottom-right' + * Scalebar: + * id: 'scalebar' + * alignment: 'bottom-right' + * Pano: + * id: 'panorama' + * alignment: 'top-right' + * + * @param map {H.Map} - The map instance to which to append the UI + * @param mapTypes {Object} - The map types to use + * @param opt_locale {(H.ui.i18n.Localization | string)=} - the language to use (or a full localization object). + * @returns {H.ui.UI} - the UI instance configured with the default controls + */ + static createDefault(map: H.Map, mapTypes: H.service.Platform.MapTypes, opt_locale?: H.ui.i18n.Localization | string): UI; + + /** + * This method is used to capture the element view + * @param canvas {HTMLCanvasElement} - HTML Canvas element to draw the view of the capturable element + * @param pixelRation {number} - The pixelRatio to use for over-sampling in cases of high-resolution displays, default is 1 + * @param callback {ICapturable~captureCallback} - Callback function to call once result of the capturing is ready + * @param opt_errback {ICapturable~errorCallback} - Callback function to call if error occurred during capturing + */ + capture(canvas: HTMLCanvasElement, pixelRation: number, callback: (canvas?: HTMLCanvasElement) => void, opt_errback?: (error: string) => void): void; + + /** + * @callback ICapturable~captureCallback + * @param canvas {HTMLCanvasElement=} + */ + + /** + * @callback ICapturable~errorCallback + * @param error {string} + */ + } + + export module UI { + /** + * Optional parameters to be passed to the UI constructor. + * @property unitSystem {H.ui.UnitSystem=} - An optional unit system to be used by the UI, default is H.ui.UnitSystem.METRIC + * @property zoom {(H.ui.ZoomControl.Options | boolean)=} - + * @property zoomrectangle {(H.ui.ZoomRectangle.Options | boolean)=} - + * @property mapsettings {(H.ui.MapSettingsControl.Options | boolean)=} - + * @property scalebar {(H.ui.ScaleBar.Options | boolean)=} - + * @property panorama {(H.ui.Pano.Options | boolean)=} - + * @property distancemeasurement {(H.ui.DistanceMeasurement.Options | boolean)=} - + * @property locale {(H.ui.i18n.Localization | string)=} - defines language in which UI can be rendered. It can be predefined H.ui.i18n.Localization object with custom translation map, or a string one of following 'en-US', 'de-DE', 'es-ES', 'fi-FI', 'fr-FR', 'it-IT', 'nl-NL', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'tr-TR', 'zh-CN'. If not defined ui will use 'en-US' by default + */ + export interface Options { + unitSystem?: H.ui.UnitSystem; + zoom?: (H.ui.ZoomControl.Options | boolean); + zoomrectangle?: (H.ui.ZoomRectangle.Options | boolean); + mapsettings?: (H.ui.MapSettingsControl.Options | boolean); + scalebar?: (H.ui.ScaleBar.Options | boolean); + panorama?: (H.ui.Pano.Options | boolean); + distancemeasurement?: (H.ui.DistanceMeasurement.Options | boolean); + locale?: (H.ui.i18n.Localization | string); + } + } + + /** + * This enumeration holds the possible unit systems for the UI to display distances. + */ + export enum UnitSystem { + /** This value represents the imperial unit system using miles and feet (value: 'imperial'). */ + IMPERIAL, + /** This value represents the metric unit system using meters and kilometers, etc (value: 'metric'). */ + METRIC, + } + + /** + * This class represents the UI controls for zooming in an out of the map. + */ + export class ZoomControl extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.ZoomControl.Options=} - optional parameters to be passed to the map. + */ + constructor(opt_options?: H.ui.ZoomControl.Options); + + /** + * This method returns the zoom speed (in levels per millisecond) which is applied when the button is pressed constantly. + * @returns {number} - the current zoom speed + */ + getZoomSpeed(): number; + } + + export module ZoomControl { + /** + * @property zoomSpeed {number=} - the speed if zooming in and out in levels per millisecond, defaults to 0.05 + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, defaults to H.ui.LayoutAlignment.RIGHT_MIDDLE + * @property slider {boolean=} - flag whether to show the slider (true) or not, defaults to false + * @property sliderSnaps {boolean=} - flag whether slider should snap to the integer values or not, defaults to false. This option has effect only if slider is enabled. + */ + export interface Options { + zoomSpeed?: number; + alignment?: H.ui.LayoutAlignment; + slider?: boolean; + sliderSnaps?: boolean; + } + } + + /** + * This class represents a zoom rectangle control element that allows zooming to the selected area on the screen. + */ + export class ZoomRectangle extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.ZoomRectangle.Options=} - optional parameters to be passed to this control + */ + constructor(opt_options?: H.ui.ZoomRectangle.Options); + } + + export module ZoomRectangle { + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.BOTTOM_RIGHT + * @property adjustZoom {function(number, H.Map) : number=} - optional function that defines how zoom level should be changed, by default zoom level is picked to fit the bounding rectangle into the view port. + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + adjustZoom?(n: number, m: H.Map): number; + } + } + + type ES6Element = Element; + + /** + * This namespace contains basic UI elements from which the UI controls are built. + */ + export module base { + export class Container extends H.util.EventTarget { + /** + * Constructor + * @param opt_elementType {string=} - the type of HTML element this UI element renders as, default is 'div' + * @param opt_className {string=} - an optional class name to be used on this element + * @param opt_children {Array=} - optional child elements to be added to this container + */ + constructor(opt_elementType?: string, opt_className?: string, opt_children?: Array); + + /** + * Adds a child element to be rendered within the container element. + * @param child {H.ui.base.Element} - the child element to be added + * @returns {H.ui.base.Container} - this container instance + */ + addChild(child: Element): Container; + + /** + * Returns the child collection of this container. + * @returns {Array} - Returns the child collection of this container. + */ + getChildren(): Array; + + /** + * Removes a child element from this container's child collection. + * @param child {H.ui.base.Element} - the child element to be removed + */ + removeChild(child: Element): void; + + /** + * This method is the concrete implementation of the UI element. This method receives the pre-rendered HTML element which may be modified by deriving classes. + * @param element {Element} - this UI element's HTML representation + * @param doc {Document} - the HTML document into which the element is currently being rendered + */ + renderInternal(element: ES6Element, doc: Document): void; + + /** + * This method returns this UI element's disabled state as a boolean value. + * @returns {boolean} - true if the element is disabled, false otherwise + */ + isDisabled(): boolean; + + /** + * This method set's the disabled state of this UI element. + * @param disabled {boolean} - true to disable the element, false to enable it + * @param opt_force {boolean=} - an optional boolean flag indicating that the value should be set and propagated even if it is the same as the current state + * @returns {H.ui.base.Element} - this element instance + */ + setDisabled(disabled: boolean, opt_force?: boolean): ES6Element; + + /** + * This method returns a previously stored arbitrary data from this element. + * @returns {*} - the previously stored data object or null if not data was stored. + */ + getData(): any; + + /** + * This method stores arbitrary data with this UI element. + * @param data {*} - the data to be stored + */ + setData(data: any): void; + + /** + * This method returns the HTML element this UI element renders. + * + * Note: Before the UI element was rendered the method returns null. + * @returns {?HTMLElement} - the element + */ + getElement(): HTMLElement; + + /** + * Sets the visibility of this element. + * @param visibility {boolean} - visibility + */ + setVisibility(visibility: boolean): void; + + /** + * Returns the visibility of this element. + * @returns {boolean} - visibility + */ + getVisibility(): boolean; + + /** + * This method adds a CSS class to this UI element (if it is not already present). + * @param className {string} - the CSS class name to add + * @returns {H.ui.base.Element} - this UI element instance + */ + addClass(className: string): Element; + + /** + * This method removes a CSS class from this UI element (if it is present). + * @param className {string} - the CSS class name to remove + * @returns {H.ui.base.Element} - this UI element instance + */ + removeClass(className: string): Element; + } + + export class Element extends H.util.EventTarget { + /** + * Constructor + * @param opt_elementType {string=} - the type of HTML element this UI element renders as, default is 'div' + * @param opt_className {string=} - an optional class name to be used on this element + */ + constructor(opt_elementType?: string, opt_className?: string); + + /** + * This method is the concrete implementation of the UI element. This method receives the pre-rendered HTML element which may be modified by deriving classes. + * @param element {Element} - this UI element's HTML representation + * @param doc {Document} - the HTML document into which the element is currently being rendered + */ + renderInternal(element: ES6Element, doc: Document): void; + + /** + * This method returns this UI element's disabled state as a boolean value. + * @returns {boolean} - true if the element is disabled, false otherwise + */ + isDisabled(): boolean; + + /** + * This method set's the disabled state of this UI element. + * @param disabled {boolean} - true to disable the element, false to enable it + * @param opt_force {boolean=} - an optional boolean flag indicating that the value should be set and propagated even if it is the same as the current state + * @returns {H.ui.base.Element} - this element instance + */ + setDisabled(disabled: boolean, opt_force?: boolean): ES6Element; + + /** + * This method returns a previously stored arbitrary data from this element. + * @returns {*} - the previously stored data object or null if not data was stored. + */ + getData(): any; + + /** + * This method stores arbitrary data with this UI element. + * @param data {*} - the data to be stored + */ + setData(data: any): void; + + /** + * This method returns the HTML element this UI element renders. + * + * Note: Before the UI element was rendered the method returns null. + * @returns {?HTMLElement} - the element + */ + getElement(): HTMLElement; + + /** + * Sets the visibility of this element. + * @param visibility {boolean} - visibility + */ + setVisibility(visibility: boolean): void; + + /** + * Returns the visibility of this element. + * @returns {boolean} - visibility + */ + getVisibility(): boolean; + + /** + * This method adds a CSS class to this UI element (if it is not already present). + * @param className {string} - the CSS class name to add + * @returns {H.ui.base.Element} - this UI element instance + */ + addClass(className: string): Element; + + /** + * This method removes a CSS class from this UI element (if it is present). + * @param className {string} - the CSS class name to remove + * @returns {H.ui.base.Element} - this UI element instance + */ + removeClass(className: string): Element; + } + } + + /** + * Namespace contains functionality related to internationalization. + */ + export module i18n { + /** + * Default available locales. UI provides default translations for this set of locale codes. + */ + export const defaultLocales: Array; + + /** + * This class is used for internationalization of UI components. + */ + export class Localization { + constructor(locale: string, opt_translationMap?: any); + + /** + * This method returns current locale code i.e 'en-US' + * @returns {string} - locale code + */ + getLocale(): string; + + /** + * This method returns translation keys for current locale. Keys from this set can be used to get translations via translate method. + * @returns {Array} + */ + getKeys(): Array; + + /** + * This method returns a boolean value indicating whether this localization object has a translation for the specified translation key. + * @param key {string} - a translation key + * @returns {boolean} - true if the key exists, otherwise false + */ + hasKey(key: string): boolean; + + /** + * This method returns translation for provided key. It throws exception if translation is not available + * @param key {string} - a translation key + * @returns {string} - a localized string corresponding to provided key + */ + translate(key: string): string; + } + } + } + + /***** util *****/ + export module util { + /** + * The cache represents a in-memory LRU-cache with a fixed size. It stores any data that is added until the cache's content exceeds a maximum size. Once the size of all content elements exceeds the maximum size the cache will drop the least recently retrieved elements until the size of the cache is within the bounds of its maximum size. Data elements are always associated with an identifier that allow to retrieve them at a later stage and their content size. + */ + export class Cache implements H.util.ICache { + /** + * Constructor + * @param maxSize {number} - the maximum size of the cache + * @param opt_onDrop {function(string, ?, number)=} - A callback to be invoked when a data element is dropped from the cache + * @param opt_filter {(function(string, ?, number) : boolean)=} - A function to filter data elements that are not to be cached + */ + constructor(maxSize: number, opt_onDrop?: (s: string, i: any, n: number) => void, opt_filter?: (s: string, i: any, n: number) => boolean); + + /** + * This method sets this cache's maximum size to a new size. If the cache's contents exceed the new size, least recently used data elements will be dropped. + * @param maxSize {number} - the new maximum size of this cache. + * @returns {H.util.Cache} - this cache + */ + setMaxSize(maxSize: number): H.util.Cache; + + /** + * This method returns the maximum size of this cache. + * @returns {number} - the maximum size of the cache + */ + getMaxSize(): number; + + /** + * This method returns the current size of this cache. + * @returns {number} - the current size of the cache + */ + getCurrentSize(): number; + + /** + * This method adds an element to the cache. + * @param id {*} - The identifier of this data element, the value is converted to a string. + * @param data {*} - the actual data to be stored + * @param size {number} - the size of the data element + * @returns {boolean} - a boolean value indicating whether the data was added + */ + add(id: any, data: any, size: number): boolean; + + /** + * This method retrieves an element from the cache. + * @param id {string} - the ID of the data element to be retrieved. + * @param opt_noUpdate {boolean=} - and optional flag to indicate that the retrieved object should not be marked as 'most recently used'. + * @returns {*} - returns the data associated with the ID or undefined if the data element is not currently in the cache. + */ + get(id: string, opt_noUpdate?: boolean): any; + + /** + * This method explicitly drops an element from the cache. + * @param id {*} - the id of the item to drop + */ + drop(id: any): void; + + /** + * This method will execute the provided callback function on each of the cache's entries. If the optional match predicate is passed to this method the callback will only be executed on those entries for which the predicated returns true. + * @param callback {function(string, ?, number)} - the callback to be invoked for each entry + * @param opt_ctx {Object=} - an optional context object to be used as this within the callback + * @param opt_matcher {(function(string, ?, number) : boolean)=} - an optional match predicate to customize on which entries the callback will be called + */ + forEach(callback: (s: string, i: any, n: number) => void, opt_ctx?: any, opt_matcher?: (s: string, i: any, n: number) => boolean): void; + + /** + * This method removes all data elements from the cache. If the optional match predicate is passed to this method only those data elements will be removed for which the predicate return true. + * @param opt_matcher {(function(string, ?, number) : boolean)=} - an optional function that receives an entries id, data and size and may return true or false to either remove it or leave the entry in the cache respectively + */ + removeAll(opt_matcher?: (s: string, i: any, n: number) => boolean): void; + + /** + * This method registers a callback that should be called each time an entry is dropped from the cache. + * @param callback {(function(string, ?, number))} - the callback to be invoked for each entry + */ + registerOnDrop(callback: (s: string, i: any, n: number) => void): void; + } + + /** + * This event indicates a change. It contains the old and the new value. + * @property target {*} - Object which triggered the event + * @property currentTarget {*} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class ChangeEvent extends H.util.Event { + /** + * Constructor + * @param type {string} - The type of the event + * @param newValue {*} - The new value of the property + * @param oldValue {*} - The previous value of the property + */ + constructor(type: string, newValue: any, oldValue: any); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + target: any; + currentTarget: any; + type: string; + defaultPrevented: boolean; + } + + /** + * This class represents a contextual information/action. + * @property SEPARATOR {H.util.ContextItem} - Separator for the context items + */ + export class ContextItem extends H.util.EventTarget { + /** + * Constructor + * @param opt_options {H.util.ContextItem.Options=} - The values to initialize this context item + */ + constructor(opt_options?: H.util.ContextItem.Options); + + /** + * This method returns label of the context item + * @returns {string} - the label of the context item + */ + getLabel(): string; + + /** + * This method changes context item label to the specified one + * @param label {string} - New label for the context item + * @returns {H.util.ContextItem} - this context item instance + */ + setLabel(label: string): H.util.ContextItem; + + /** + * This method returns disabled state of the context item. + * @returns {boolean} - true if the item is disabled, false otherwise + */ + isDisabled(): boolean; + + /** + * This method enables/disables the context item + * @param disabled {boolean} - true to disable and false to enabled it + * @returns {H.util.ContextItem} - this context item instance + */ + setDisabled(disabled: boolean): H.util.ContextItem; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + static SEPARATOR: H.util.ContextItem; + } + + export module ContextItem { + /** + * This type defines options which can be used to initialize the context item. + * @property label {string=} - the label of the context item + * @property disabled {boolean=} - flag indicatting whether context item is disabled or no, by default false + * @property callback {function(H.util.Event)=} - Optional callback function to call once context item is selected + */ + export interface Options { + label?: string; + disabled?: boolean; + callback?: (event: H.util.Event) => void; + } + } + + /** + * Object which can be safely disposed. + */ + export class Disposable { + /** + * Constructor + */ + constructor(); + + /** + * Method adds a callback which will be triggered when the object is disposed + * @param callback {Function} + * @param opt_scope {Object=} + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + /** + * Base Event class which is used for all events dispatched by any EventTarget within the api. + * @property target {*} - Object which triggered the event + * @property currentTarget {*} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class Event { + /** + * Constructor + * @param type {string} - Event Type. + * @param opt_target {Object=} - Reference to the object that is the target of this event. It has to implement the {@link EventTargetInstance} interface. + */ + constructor(type: string, opt_target?: any); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + target: any; + currentTarget: any; + type: string; + defaultPrevented: boolean; + } + + /** + * EventTarget enabled listening and dispatching events on all instances and derived classes. + */ + export class EventTarget { + /** + * Constructor + */ + constructor(); + + /** + * This method allows to listen for specific event triggered by the object. Keep in mind, that you must removeEventListener manually or dispose an object when you no longer need it. Otherwise memory leak is possible. + * @param type {string} - name of event + * @param handler {Function} - event handler function + * @param opt_capture {boolean=} - if set to true will listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - scope for the handler function + */ + addEventListener(type: string, handler: EventListenerOrEventListenerObject, opt_capture?: boolean, opt_scope?: any): void; + + /** + * This method will removed previously added listener from the event target + * @param type {string} - name of event + * @param handler {Function} - event handler function + * @param opt_capture {boolean=} - if set to true will listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - scope for the handler function + */ + removeEventListener(type: string, handler: EventListenerOrEventListenerObject, opt_capture?: boolean, opt_scope?: any): void; + + /** + * This method will dispatch event on the event target object + * @param evt {H.util.Event | string} - event object or event name + */ + dispatchEvent(evt: H.util.Event | string): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: () => void, opt_scope?: any): void; + } + + /** + * An interface definition for the generic cache. Any data elements can be stored in the cache. They are always associated with an identifier to retrieve them at a later stage and their content size. + */ + export interface ICache { + /** + * This method adds an element to the cache. + * @param id {*} - The identifier of this data element, the value is converted to a string. + * @param data {*} - the actual data to be stored + * @param size {number} - the size of the data element + * @returns {boolean} - a boolean value indicating whether the data was added + */ + add(id: any, data: any, size: number): boolean; + + /** + * This method retrieves an element from the cache. + * @param id {string} - the ID of the data element to be retrieved. + * @param opt_noUpdate {boolean=} - and optional flag to indicate that the retrieved object should not be marked as 'most recently used'. + * @returns {*} - returns the data associated with the ID or undefined if the data element is not currently in the cache. + */ + get(id: string, opt_noUpdate?: boolean): any; + + /** + * This method explicitly drops an element from the cache. + * @param id {*} - the id of the item to drop + */ + drop(id: any): void; + + /** + * This method will execute the provided callback function on each of the cache's entries. If the optional match predicate is passed to this method the callback will only be executed on those entries for which the predicated returns true. + * @param callback {function(string, ?, number)} - the callback to be invoked for each entry + * @param opt_ctx {Object=} - an optional context object to be used as this within the callback + * @param opt_matcher {(function(string, ?, number) : boolean)=} - an optional match predicate to customize on which entries the callback will be called + */ + forEach(callback: (s: string, t: any, n: number) => void, opt_ctx?: Object, opt_matcher?: ((s: string, t: any, n: number) => boolean)): void; + + /** + * This method removes all data elements from the cache. If the optional match predicate is passed to this method only those data elements will be removed for which the predicate return true. + * @param opt_matcher {(function(string, ?, number) : boolean)=} - an optional function that receives an entries id, data and size and may return true or false to either remove it or leave the entry in the cache respectively + */ + removeAll(opt_matcher?: ((s: string, t: any, n: number) => boolean)): void; + + /** + * This method registers a callback that should be called each time an entry is dropped from the cache. + * @param callback {(function(string, ?, number))} - the callback to be invoked for each entry + */ + registerOnDrop(callback: ((s: string, t: any, n: number) => void)): void; + } + + /** + * An interface to cancelable requests and actions. + */ + export interface ICancelable { + /** + * This method is used to cancel current action + */ + cancel(): void; + } + + export interface ICapturable { + /** + * This method is used to capture the element view + * @param canvas {HTMLCanvasElement} - HTML Canvas element to draw the view of the capturable element + * @param pixelRation {number} - The pixelRatio to use for over-sampling in cases of high-resolution displays, default is 1 + * @param callback {ICapturable~captureCallback} - Callback function to call once result of the capturing is ready + * @param opt_errback {ICapturable~errorCallback} - Callback function to call if error occurred during capturing + */ + capture(canvas: HTMLCanvasElement, pixelRation: number, callback: (canvas?: HTMLCanvasElement) => void, opt_errback?: (error: string) => void): void; + + /** + * @callback ICapturable~captureCallback + * @param canvas {HTMLCanvasElement=} + */ + + /** + * @callback ICapturable~errorCallback + * @param error {string} + */ + } + + /** + * This class represents an list of ordered entries which dispatches events when the list is modified. + * @event add {H.util.OList.Event} - Fired when an entry was added to the list. + * @event remove {H.util.OList.Event} - Fired when an entry was removed from the list. + * @event set {H.util.OList.Event} - Fired when an entry was set in the list. + * @event move {H.util.OList.Event} - Fired when an entry was moved within the list. + */ + export class OList extends H.util.EventTarget { + + /** + * This method inserts an entry to the list. Optionally it can place new entry at provided index. + * @param entry {?} - The entry to insert + * @param opt_idx {number=} - The index where the new entry should be inserted; if omitted or greater then the current size of the list, the entry is added at the end of the list; a negative index is treated as being relative from the end of the list + */ + add(entry: any, opt_idx?: number): void; + + /** + * This method removes an entry by a given index from the list. + * @param idx {number} - The index of the entry which should be removed; a negative index is treated as being relative from the end of the list + * @returns {?} - The removed entry + */ + removeAt(idx: number): any; + + /** + * This method removes the the first entry which is identical with the given entry. + * @param entry {?} - The entry to remove + * @returns {boolean} - signals if the entry could be found in the list and is removed + */ + remove(entry: any): boolean; + + /** + * This method replaces an entry at the given index with the given entry. + * @param idx {number} - The index of the entry which should be replaced; a negative index is treated as being relative from the end of the list + * @param entry {?} - The entry which replaces the existing one + * @returns {?} - The replaced entry + */ + set(idx: number, entry: any): any; + + /** + * This method retrieves the index of the first object in this list that is identical with the object supplied by the caller. + * @param entry {?} - The entry for which to return the index. + * @returns {number} - The index of the first matching entry in this list or -1 if the entry provided by the caller is not found in the list + */ + indexOf(entry: any): number; + + /** + * To get the entry at the specified index. + * @param idx {number} - The index of the entry to get a negative index is treated as being relative from the end of the list + * @returns {?} - The element at the given index + */ + get(idx: number): any; + + /** + * This method returns the length of the list. + * @returns {number} + */ + getLength(): number; + + /** + * This method returns all list's entries as an array. + * @returns {Array<*>} - The list as an array + */ + asArray(): Array; + + /** + * This method removes all entries from the list. + */ + flush(): void; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module OList { + /** + * The event class for events that are dispatched by OList + * @property target {*} - Object which triggered the event + * @property currentTarget {*} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class Event extends H.util.Event { + /** + * Constructor + * @param list {H.util.OList} - The OList instance which is emitting the event + * @param type {H.util.OList.prototype.EventType} - The type of the event + * @param idx {number} - The affected index within this list + * @param added {?*} - The value of the entry which was added or set + * @param removed {?*} - The value of the entry which was removed or replaced + * @param moved {?*} - The value of the entry which was moved + */ + constructor(list: H.util.OList, type: string, idx: number, added: any, removed: any, moved: any); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + target: any; + currentTarget: any; + type: string; + defaultPrevented: boolean; + } + } + + /** + * A generic class to represent a handle for any kind of asynchronous processed requests + */ + export class Request { + /** + * Constructor + * @param opt_onprogress {function(H.util.Request)=} - A callback to invoke every time when the request's progress state changes + * @param opt_total {number=} - The total number of processing steps to complete this request, default is 1 + */ + constructor(opt_onprogress?: (req: H.util.Request) => void, opt_total?: number); + + /** + * Returns the state of this request + * @returns {H.util.Request.State} + */ + getState(): H.util.Request.State; + + /** + * Returns the number of processing steps to complete this request + * @returns {number} + */ + getTotal(): number; + + /** + * Returns the number of steps which are already processed by this request + * @returns {number} + */ + getProcessed(): number; + + /** + * Returns the number of processingsteps which have been failed + * @returns {number} + */ + getFailed(): number; + } + + export module Request { + /** + * The supported states of an request + */ + export enum State { + PENDING, + PROCESSING, + COMPLETE, + CANCELLED, + ERROR, + } + } + + export module animation { + /** + * This mamespace contains easing functions used for Animation class. + */ + export class ease { + /** + * This function defines linear ease. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static LINEAR(val: number): number; + + /** + * This function defines quadratic ease in. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static EASE_IN_QUAD(val: number): number; + + /** + * This function defines quadratic ease out. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static EASE_OUT_QUAD(val: number): number; + + /** + * This function defines ease in and out with slope. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static EASE_IN_OUT_QUINT(val: number): number; + + /** + * This function defines ease out with circ function. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static EASE_OUT_CIRC(val: number): number; + } + } + + export module kinetics { + /** + * This interface defines kinetic move parameters used by map for kinetic drag. + * @property power {number} - Power multiplier. Multiplier is used to increase the speed of the kinetic move. By default map uses 1. + * @property duration {number} - Defines duration of the kinetic move. + */ + export interface IKinetics { + /** + * Easing function modifies animation progress. In example it can modify the animation in a way it starts rapidly and then slows down at the end. + * @param p {number} - current progress + * @returns {number} - modified progress + */ + ease(p: number): number; + + power: number; + duration: number; + } + } + } +} diff --git a/highcharts/highcharts-modules-exporting.d.ts b/highcharts/highcharts-modules-exporting.d.ts new file mode 100644 index 0000000000..4d3bdaa648 --- /dev/null +++ b/highcharts/highcharts-modules-exporting.d.ts @@ -0,0 +1,12 @@ +// Type definitions for Highcharts 4.2.6 (exporting module) +// Project: http://www.highcharts.com/ +// Definitions by: Maciej Suchecki +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare var HighchartsExporting: (H: HighchartsStatic) => HighchartsStatic; + +declare module "highcharts/modules/exporting" { + export = HighchartsExporting; +} diff --git a/highcharts/highcharts-modules-no-data-to-display-tests.ts b/highcharts/highcharts-modules-no-data-to-display-tests.ts new file mode 100644 index 0000000000..64b50f831f --- /dev/null +++ b/highcharts/highcharts-modules-no-data-to-display-tests.ts @@ -0,0 +1,10 @@ +/// +/// +/// + +function test_NoDataToDisplay() { + var chart = $("#container").highcharts(); + var chartHasData = chart.hasData(); + chart.hideNoData(); + chart.showNoData("Custom no data message"); +} diff --git a/highcharts/highcharts-modules-no-data-to-display.d.ts b/highcharts/highcharts-modules-no-data-to-display.d.ts new file mode 100644 index 0000000000..ab5fdd1d0d --- /dev/null +++ b/highcharts/highcharts-modules-no-data-to-display.d.ts @@ -0,0 +1,26 @@ +// Type definitions for Highcharts No Data to Display +// Project: http://www.highcharts.com/ +// Definitions by: Andrey Zolotin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// +interface HighchartsChartObject { + /** + * Returns true if there are data points within the plot area now + * @return {boolean} If chart has any data. + * @since 3.0.8 + */ + hasData(): boolean; + + /** + * Hide the 'No data to display' message added by the no-data-to-display plugin. + * @since 3.0.8 + */ + hideNoData(): void; + + /** + * Display a no-data message. + * @param {String} message An optional message to show in place of the default one + * @since 3.0.8 + */ + showNoData(message?: string): void; +} diff --git a/highcharts/highcharts-more.d.ts b/highcharts/highcharts-more.d.ts new file mode 100644 index 0000000000..1d42764b3c --- /dev/null +++ b/highcharts/highcharts-more.d.ts @@ -0,0 +1,12 @@ +// Type definitions for Highcharts 4.2.6 +// Project: http://www.highcharts.com/ +// Definitions by: Maciej Suchecki +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare var HighchartsMore: (H: HighchartsStatic) => HighchartsStatic; + +declare module "highcharts/highcharts-more" { + export = HighchartsMore; +} diff --git a/highcharts/highcharts-tests.ts b/highcharts/highcharts-tests.ts index 499dfc9494..d8b74de31e 100644 --- a/highcharts/highcharts-tests.ts +++ b/highcharts/highcharts-tests.ts @@ -2258,6 +2258,7 @@ function test_PointObject() { var point = $('#container').highcharts().get('point1'); var category = point.category; var percentage = point.percentage; + point.index; point.remove(); point.remove(false); point.remove(false, {duration: 50}); diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index 45f69a0bda..bfe5a70235 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Highcharts 4.1.9 +// Type definitions for Highcharts 4.2.5 // Project: http://www.highcharts.com/ // Definitions by: Damiano Gambarotto , Dan Lewi Harkestad // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -240,7 +240,7 @@ interface HighchartsPlotBands { * Border color for the plot band. Also requires borderWidth to be set. * @default null */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * Border width for the plot band. Also requires borderColor to be set. * @default 0 @@ -468,6 +468,10 @@ interface HighchartsAxisOptions { * @since 4.0 */ ceiling?: number; + /** + * Configure a crosshair that follows either the mouse pointer or the hovered point. + */ + crosshair?: HighchartsCrosshairObject | boolean; /** * For a datetime axis, the scale will automatically adjust to the appropriate unit. This member gives the default * string representations used for each unit. For an overview of the replacement codes, see dateFormat. @@ -552,7 +556,7 @@ interface HighchartsAxisOptions { * The color of the line marking the axis itself. * @default '#C0D0E0'. */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The width of the line marking the axis itself. * @default 1 @@ -816,7 +820,7 @@ interface HighchartsAxisOptions { interface HighchartsColorAxisDataClass { from?: number; to?: number; - color?: string; + color?: string | HighchartsGradient; name?: string; } @@ -902,7 +906,7 @@ interface HighchartsColorAxisOptions { * The color of the line marking the axis itself. * @default '#C0D0E0' */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The width of the line marking the axis itself. * @default 0 @@ -922,7 +926,7 @@ interface HighchartsColorAxisOptions { * The color of the marker. * @default 'gray' */ - color?: string; + color?: string | HighchartsGradient; }; /** * The maximum value of the axis in terms of map point values. If null, the max value is automatically calculated. @@ -1378,7 +1382,7 @@ interface HighchartsShadow { /** * @default 'black' */ - color?: string; + color?: string | HighchartsGradient; /** * @default 1 */ @@ -1487,7 +1491,7 @@ interface HighchartsChartOptions { * The color of the outer chart border. * @default '#4572A7' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The corner radius of the outer chart border. * @default 0 @@ -1717,7 +1721,7 @@ interface HighchartsChartOptions { interface HighchartsCSSObject { background?: string; border?: string; - color?: string; + color?: string | HighchartsGradient; cursor?: string; font?: string; fontFamily?: string; @@ -2425,7 +2429,7 @@ interface HighchartsLegendOptions { * The color of the drawn border around the legend. * @default '#909090' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border corner radius of the legend. * @default 0 @@ -2720,7 +2724,7 @@ interface HighchartsPaneBackground { /** * @default 'silver' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * @default 1 */ @@ -2799,7 +2803,7 @@ interface HighchartsDataLabels { * The border color for the data label. * @since 2.2.1 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border radius in pixels for the data label. * @default 0 @@ -2816,7 +2820,7 @@ interface HighchartsDataLabels { * The text color for the data labels. * @default null */ - color?: string; + color?: string | HighchartsGradient; /** * Whether to hide data labels that are outside the plot area. By default, the data label is moved inside the plot * area according to the overflow option. @@ -3062,7 +3066,7 @@ interface HighchartsMarkerState { * The color of the point marker's outline. When null, the series' or point's color is used. * @default '#FFFFFF', '#000000' for select state */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The width of the point marker's outline. * @default 0 @@ -3183,6 +3187,14 @@ interface HighchartsPointEvents { * @since 1.2.0 */ update?: (event: Event) => boolean|void; + /** + * Fires when the legend item belonging to the pie point (slice) is clicked. + * The this keyword refers to the point itself. One parameter, event, is passed to the function. + * This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. + * The default action is to toggle the visibility of the point. This can be prevented by calling event.preventDefault(). + */ + legendItemClick?: (event: Event) => boolean | void; + } interface HighchartsHalo { @@ -3264,7 +3276,7 @@ interface HighchartsAreaZone { * Defines the color of the series. * @since 4.1.0 */ - color?: string; + color?: string | HighchartsGradient; /** * A name for the dash style to use for the graph. * @since 4.1.0 @@ -3309,7 +3321,7 @@ interface HighchartsRangeDataLabels { * @default undefined * @since 2.2.1 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border radius in pixels for the data label. * @default 0 @@ -3326,7 +3338,7 @@ interface HighchartsRangeDataLabels { * The text color for the data labels. * @default null */ - color?: string; + color?: string | HighchartsGradient; /** * Whether to hide data labels that are outside the plot area. By default, the data label is moved inside the plot * area according to the overflow option. @@ -3459,7 +3471,7 @@ interface HighchartsDial { * @default 'black' * @since 2.3.0 */ - backgroundColor?: string; + backgroundColor?: string | HighchartsGradient; /** * The length of the dial's base part, relative to the total radius or length of the dial. * @default '70%'. @@ -3478,7 +3490,7 @@ interface HighchartsDial { * @default 'silver' * @since 2.3.0 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the gauge dial border in pixels. * @default 0 @@ -3512,14 +3524,14 @@ interface HighchartsPivot { * @default 'black' * @since 2.3.0 */ - backgroundColor?: string; + backgroundColor?: string | HighchartsGradient; /** * The border or stroke color of the pivot. In able to change this, the borderWidth must also be set to something * other than the default 0. * @default 'silver' * @since 2.3.0 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border or stroke width of the pivot. * @default 0 @@ -3542,7 +3554,7 @@ interface HighchartsTreeMapLevel { * Can set borderColor on all points which lies on the same level. * @since 4.1.0 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * et the dash style of the border of all the point which lies on the level. * @since 4.1.0 @@ -3557,7 +3569,7 @@ interface HighchartsTreeMapLevel { * Can set a color on all points which lies on the same level. * @since 4.1.0 */ - color?: string; + color?: string | HighchartsGradient; /** * Can set the options of dataLabels on each point which lies on the level. * @default undefined @@ -3582,7 +3594,7 @@ interface HighchartsTreeMapLevel { } /** - * General options for all series types + * General options for all series types. */ interface HighchartsSeriesChart { /** @@ -3603,7 +3615,7 @@ interface HighchartsSeriesChart { * specified. In bar type series it applies to the bars unless a color is specified per point. The default value is * pulled from the options.colors array. */ - color?: string; + color?: string | HighchartsGradient; /** * Polar charts only. Whether to connect the ends of a line series plot across the extremes. * @default true @@ -3848,7 +3860,7 @@ interface HighchartsAreaChart extends HighchartsSeriesChart { * A separate color for the graph line. By default the line takes the color of the series, but the lineColor setting * allows setting a separate color for the line without altering the fillColor. */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * A separate color for the negative part of the area. * @since 3.0 @@ -3890,7 +3902,7 @@ interface HighchartsBarChart extends HighchartsSeriesChart { * The color of the border surrounding each column or bar. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The corner radius of the border surrounding each column or bar. * @default 0 @@ -4251,7 +4263,7 @@ interface HighchartsFunnelChart extends HighchartsSeriesChart { * The color of the border surrounding each column or bar. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each column or bar. * @default 1 @@ -4373,7 +4385,7 @@ interface HighchartsHeatMapChart extends HighchartsSeriesChart { * The color of the border surrounding each column or bar. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The corner radius of the border surrounding each column or bar. * @default 0 @@ -4456,7 +4468,7 @@ interface HighchartsPieChart extends HighchartsSeriesChart { * borderless pies. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each column or bar. * @default 1 @@ -4561,7 +4573,7 @@ interface HighchartsPyramidChart extends HighchartsSeriesChart { * The color of the border surrounding each slice * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each slice * @default 1 @@ -4676,7 +4688,7 @@ interface HighchartsTreeMapChart extends HighchartsSeriesChart { * The color of the border surrounding each tree map item. * @default '#E0E0E0' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each column or bar. * @default 1 @@ -4771,7 +4783,7 @@ interface HighchartsWaterFallChart extends HighchartsBarChart { * @default '#333333' * @since 3.0 */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The color used specifically for positive point columns. When not specified, the general series color is used. */ @@ -4817,6 +4829,17 @@ interface HighchartsPlotOptions { */ interface HighchartsIndividualSeriesOptions { type?: string; + /** + * The main color or the series. In line type series it applies to the line and the point markers unless otherwise + * specified. In bar type series it applies to the bars unless a color is specified per point. The default + * value is pulled from the options.colors array. + */ + color?: string | HighchartsGradient; + /** + * You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user + * that the points and lines can be clicked. + */ + cursor?: string; /** * An array of data points for the series. For the area series type, points can be given in the following ways: * @@ -4867,6 +4890,11 @@ interface HighchartsIndividualSeriesOptions { * The name of the series as shown in the legend, tooltip etc. */ name?: string; + /** + * A pixel value specifying a fixed width for each column or bar. When null, the width is calculated from + * the pointPadding and groupPadding. + */ + pointWidth?: number; /** * This option allows grouping series in a stacked chart. The stack option can be a string or a number or anything * else, as long as the grouped series' stack options match each other. @@ -4921,7 +4949,7 @@ interface HighchartsDataPoint { * Individual color for the point. By default the color is pulled from the global colors array. * @default undefined */ - color?: string; + color?: string | HighchartsGradient; /** * Serves a purpose only if a colorAxis object is defined in the chart options. This value will decide which color * the point gets from the scale of the colorAxis. @@ -5145,7 +5173,7 @@ interface HighchartsTitleOptions { } interface HighchartsCrosshairObject { - color?: string; + color?: string | HighchartsGradient; width?: number; dashStyle?: string; //Solid ShortDash ShortDot ShortDashDot ShortDashDotDot Dot Dash LongDash DashDot LongDashDot LongDashDotDot zIndex?: number; @@ -5172,7 +5200,7 @@ interface HighchartsTooltipOptions extends HighchartsSeriesTooltipOptions { * The color of the tooltip border. When null, the border takes the color of the corresponding series or point. * @default null */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The radius of the rounded border corners. * @default 3 @@ -5472,12 +5500,12 @@ interface HighchartsOptions { * The X axis or category axis. Normally this is the horizontal axis, though if the chart is inverted this is the * vertical axis. In case of multiple axes, the xAxis node is an array of configuration objects. */ - xAxis?: HighchartsAxisOptions | HighchartsAxisOptions[]; + xAxis?: HighchartsAxisOptions[] | HighchartsAxisOptions; /** * The Y axis or value axis. Normally this is the vertical axis, though if the chart is inverted this is the * horizontal axis. In case of multiple axes, the yAxis node is an array of configuration objects. */ - yAxis?: HighchartsAxisOptions | HighchartsAxisOptions[]; + yAxis?: HighchartsAxisOptions[] | HighchartsAxisOptions; } interface HighchartsGlobalOptions extends HighchartsOptions { @@ -5574,7 +5602,7 @@ interface HighchartsAxisObject { * @param {boolean | HighchartsAnimation} animation When true, the resize will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. * @since 1.2.0 */ - setExtremes(min?: number, max?: number, redraw?: boolean, animation?: boolean | HighchartsAnimation): void; + setExtremes(min?: number, max?: number, redraw?: boolean, animation?: boolean | HighchartsAnimation, eventArguments?: any): void; /** * Update the title of the axis after render time. * @param {HighchartsAxisTitle} title The new title options on the same format as given in xAxis.title. @@ -6037,7 +6065,7 @@ interface HighchartsStatic { * throughout the page's lifetime. When a chart is destroyed, the array item becomes undefined. * @since 2.3.4 */ - charts: HighchartsChart[]; + charts: HighchartsChartObject[]; /** * Formats a JavaScript date timestamp (milliseconds since Jan 1st 1970) into a human readable date string. The * format is a subset of the formats for PHP's strftime function. Additional formats can be given in the @@ -6098,6 +6126,7 @@ interface HighchartsPointObject { */ category: string | number; name: string; + index: number; /** * The percentage for points in a stacked series or pies. * @since 1.2.0 diff --git a/howlerjs/howler.d.ts b/howlerjs/howler.d.ts index c52b9c334f..9e245a8058 100644 --- a/howlerjs/howler.d.ts +++ b/howlerjs/howler.d.ts @@ -52,20 +52,20 @@ interface Howl { onpause: Function; onplay: Function; load(): Howl; - play(sprite?: string, callback?: (soundId: number) => void): Howl; - play(callback?: (soundId: number) => void): Howl; - pause(soundId?: number): Howl; - stop(soundId?: number): Howl; - mute(soundId?: number): Howl; - unmute(soundId?: number): Howl; - fade(from: number, to: number, duration: number, callback?: Function, soundId?: number): Howl; + play(sprite?: string, callback?: (soundId: string) => void): Howl; + play(callback?: (soundId: string) => void): Howl; + pause(soundId?: string): Howl; + stop(soundId?: string): Howl; + mute(soundId?: string): Howl; + unmute(soundId?: string): Howl; + fade(from: number, to: number, duration: number, callback?: Function, soundId?: string): Howl; loop(): boolean; loop(loop: boolean): Howl; - pos(position?: number, soundId?: number): number; - pos3d(x: number, y: number, z: number, soundId?: number): any; + pos(position?: number, soundId?: string): number; + pos3d(x: number, y: number, z: number, soundId?: string): any; sprite(definition?: IHowlSoundSpriteDefinition): IHowlSoundSpriteDefinition; volume(): number; - volume(volume?: number, soundId?: number): Howl; + volume(volume?: number, soundId?: string): Howl; urls(): string[]; urls(urls: string[]): Howl; on(event: string, listener?: Function): Howl; diff --git a/html-pdf/html-pdf-tests.ts b/html-pdf/html-pdf-tests.ts new file mode 100644 index 0000000000..6a214ef231 --- /dev/null +++ b/html-pdf/html-pdf-tests.ts @@ -0,0 +1,13 @@ +/// +/// + +import * as fs from 'fs'; +import * as pdf from 'html-pdf'; + +var html = fs.readFileSync('./test/businesscard.html', 'utf8'); +var options: pdf.CreateOptions = { format: 'Letter' }; + +pdf.create(html, options).toFile('./businesscard.pdf', (err: Error, res: pdf.FileInfo) => { + if (err) return console.log(err); + console.log(res); // { filename: '/app/businesscard.pdf' } +}); diff --git a/html-pdf/html-pdf.d.ts b/html-pdf/html-pdf.d.ts new file mode 100644 index 0000000000..07c4be9f71 --- /dev/null +++ b/html-pdf/html-pdf.d.ts @@ -0,0 +1,80 @@ +// Type definitions for html-pdf v2.1.0 +// Project: https://github.com/marcbachmann/node-html-pdf +// Definitions by: Seth Westphal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'html-pdf' { + + import * as fs from 'fs'; + + export interface CreateOptions { + + // Export options + directory?: string; + + // Papersize Options: http://phantomjs.org/api/webpage/property/paper-size.html + height?: string; + width?: string; + format?: 'A3' | 'A4' | 'A5' | 'Legal' | 'Letter' | 'Tabloid'; + orientation?: 'portrait' | 'landscape'; + + // Page options + border?: string | { + top?: string; + right?: string; + bottom?: string; + left?: string; + }; + + header?: { + height?: string; + contents?: string; + }; + footer?: { + height?: string; + contents?: { + first?: string; + [page: number]: string; + default?: string; + last?: string; + }; + }; + + // Rendering options + base?: string; + + // Zooming option, can be used to scale images if `options.type` is not pdf + zoomFactor?: string; + + // File options + type?: 'png' | 'jpeg' | 'pdf'; + quality?: string; + + // Script options + phantomPath?: string; + phantomArgs?: string[]; + script?: string; + timeout?: number; + + // HTTP Headers that are used for requests + httpHeaders?: { + [header: string]: string; + }; + + } + + export interface FileInfo { + filename: string; + } + + export interface CreateResult { + toBuffer(callback: (err: Error, buffer: Buffer) => void): void; + toFile(callback: (err: Error, res: FileInfo) => void): void; + toFile(filename?: string, callback?: (err: Error, res: FileInfo) => void): void; + toStream(callback: (err: Error, stream: fs.ReadStream) => void): void; + } + + export function create(html: string, options?: CreateOptions): CreateResult; +} diff --git a/html-webpack-plugin/html-webpack-plugin-tests.ts b/html-webpack-plugin/html-webpack-plugin-tests.ts new file mode 100644 index 0000000000..9aac8c9b98 --- /dev/null +++ b/html-webpack-plugin/html-webpack-plugin-tests.ts @@ -0,0 +1,18 @@ +/// + +import {Configuration} from "webpack"; +import HtmlWebpackPlugin = require("html-webpack-plugin"); + +const a: Configuration = { + plugins: [ + new HtmlWebpackPlugin() + ] +}; + +const b: Configuration = { + plugins: [ + new HtmlWebpackPlugin({ + title: "test" + }) + ] +}; diff --git a/html-webpack-plugin/html-webpack-plugin.d.ts b/html-webpack-plugin/html-webpack-plugin.d.ts new file mode 100644 index 0000000000..59917abf62 --- /dev/null +++ b/html-webpack-plugin/html-webpack-plugin.d.ts @@ -0,0 +1,89 @@ +// Type definitions for html-webpack-plugin v2.22.2 +// Project: https://github.com/ampedandwired/html-webpack-plugin +// Definitions by: Simon Hartcher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "html-webpack-plugin" { + import {Plugin} from "webpack"; + + interface HtmlWebpackPluginConfiguration { + /** + * The title to use for the generated HTML document. + */ + title?: string; + + /** + * The file to write the HTML to. Defaults to index.html. You can specify a subdirectory here too (eg: `assets/admin.html`). + */ + filename?: string; + + /** + * Webpack require path to the template. Please see the docs for details. + */ + template?: string; + + /** + * `true | 'head' | 'body' | false` + * + * Inject all assets into the given template or templateContent - When passing true or 'body' all javascript resources will be placed at the bottom of the body element. 'head' will place the scripts in the head element. + */ + inject?: boolean | "head" | "body"; + + /** + * Adds the given favicon path to the output html. + */ + favicon?: string; + + /** + * Pass a html-minifier options object to minify the output. + * + * https://github.com/kangax/html-minifier#options-quick-reference + */ + minify?: any; + + /** + * `true | false` if `true` then append a unique webpack compilation hash to all included scripts and css files. This is useful for cache busting. + */ + hash?: boolean; + + /** + * `true | false` if `true` (default) try to emit the file only if it was changed. + */ + cache?: boolean; + + /** + * `true | false` if `true` (default) errors details will be written into the html page. + */ + showErrors?: boolean; + + /** + * Allows you to add only some chunks (e.g. only the unit-test chunk) + */ + chunks?: string[]; + + /** + * Allows to control how chunks should be sorted before they are included to the html. Allowed values: `'none' | 'auto' | 'dependency' | {function}` - default: `'auto'` + */ + chunksSortMode?: "none" | "auto" | "dependency" | Function; + + /** + * Allows you to skip some chunks (e.g. don't add the unit-test chunk) + */ + excludeChunks?: string[]; + + /** + * `true | false` If `true` render the link tags as self-closing, XHTML compliant. Default is `false` + */ + xhtml?: boolean; + } + + interface HtmlWebpackPlugin { + new (): Plugin; + new (options: HtmlWebpackPluginConfiguration): Plugin; + } + + const htmlWebpackPlugin: HtmlWebpackPlugin; + export = htmlWebpackPlugin; +} diff --git a/http-errors/http-errors-tests.ts b/http-errors/http-errors-tests.ts index 4403259008..61fb9091bf 100644 --- a/http-errors/http-errors-tests.ts +++ b/http-errors/http-errors-tests.ts @@ -6,12 +6,19 @@ import * as express from 'express'; var app = express(); +declare global { + namespace Express { + export interface Request { + user?: any + } + } +} + app.use(function (req, res, next) { if (!req.user) return next(createError(401, 'Please login to view this page.')); next(); }); - /* Examples taken from https://github.com/jshttp/http-errors/blob/1.3.1/test/test.js */ // createError(status) diff --git a/humps/humps-tests.ts b/humps/humps-tests.ts new file mode 100644 index 0000000000..66017b065c --- /dev/null +++ b/humps/humps-tests.ts @@ -0,0 +1,71 @@ +/// + +// Tests evaluated from: +// https://github.com/domchristie/humps/blob/master/README.md + +import * as humps from "humps"; + +let someObject = { attr_one: 'foo', attr_two: 'bar' }; +let someArray = [{ attr_one: 'foo' }, { attr_one: 'bar' }] + +let someOptions: humps.HumpsOptions = { + separator: '-' +}; +let someOptions2: humps.HumpsOptions = { + split: /^[A-Z0-9_]+$/ +}; +let someOptions3: humps.HumpsOptions = { + separator: '-', + process: function (key: string, convert: humps.HumpsProcessorParameter, options: humps.HumpsOptions) { + return /^[A-Z0-9_]+$/.test(key) ? key : convert(key, options); + } +}; + + +humps.camelize('hello_world') + +humps.decamelize('fooBar') +humps.decamelize('fooBarBaz', someOptions) + +humps.camelizeKeys(someObject); + +humps.camelizeKeys(someArray); + +humps.camelizeKeys(someObject, function (key, convert) { + return /^[A-Z0-9_]+$/.test(key) ? key : convert(key); +}); + +humps.decamelizeKeys(someObject, function (key, convert, options) { + return /^[A-Z0-9_]+$/.test(key) ? key : convert(key, options); +}); + + +humps.camelize('hello_world-foo bar'); + +humps.pascalize('hello_world-foo bar'); + +humps.decamelize('helloWorldFooBar'); +humps.decamelize('helloWorldFooBar', someOptions); +humps.decamelize('helloWorld1', { split: /(?=[A-Z0-9])/ }) + +humps.depascalize('helloWorldFooBar'); + +humps.camelizeKeys(someObject); +humps.pascalizeKeys(someObject); +humps.decamelizeKeys(someObject); +humps.depascalizeKeys(someObject); + +humps.camelizeKeys(someObject, someOptions); +humps.pascalizeKeys(someObject, someOptions); +humps.decamelizeKeys(someObject, someOptions); +humps.depascalizeKeys(someObject, someOptions); + +humps.camelizeKeys(someObject, someOptions2); +humps.pascalizeKeys(someObject, someOptions2); +humps.decamelizeKeys(someObject, someOptions2); +humps.depascalizeKeys(someObject, someOptions2); + +humps.camelizeKeys(someObject, someOptions3); +humps.pascalizeKeys(someObject, someOptions3); +humps.decamelizeKeys(someObject, someOptions3); +humps.depascalizeKeys(someObject, someOptions3); diff --git a/humps/humps.d.ts b/humps/humps.d.ts new file mode 100644 index 0000000000..87f3bbd991 --- /dev/null +++ b/humps/humps.d.ts @@ -0,0 +1,39 @@ +// Type definitions for humps v1.1.0 +// Project: https://github.com/domchristie/humps +// Definitions by: Niklas Mollenhauer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace humps { + + function camelize(value: string): string; + function pascalize(value: string): string; + function decamelize(value: string, optionsOrProcessor?: OptionOrProcessor): string; + function depascalize(value: string, optionsOrProcessor?: OptionOrProcessor): string; + + function camelizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object; + function pascalizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object; + function decamelizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object; + function depascalizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object; + + function camelizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[]; + function pascalizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[]; + function decamelizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[]; + function depascalizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[]; + + interface HumpsOptions { + separator?: string; + split?: RegExp; + process?: HumpsProcessor; + } + interface HumpsProcessor { + (key: string, convert: HumpsProcessorParameter, options?: HumpsOptions): string; + } + interface HumpsProcessorParameter { + (key: string, options?: HumpsOptions): string; + } + type OptionOrProcessor = HumpsOptions | HumpsProcessor; +} + +declare module "humps" { + export = humps; +} diff --git a/i18next-browser-languagedetector/i18next-browser-languagedetector.d.ts b/i18next-browser-languagedetector/i18next-browser-languagedetector.d.ts index cef510304e..a00acb2265 100644 --- a/i18next-browser-languagedetector/i18next-browser-languagedetector.d.ts +++ b/i18next-browser-languagedetector/i18next-browser-languagedetector.d.ts @@ -3,7 +3,6 @@ // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// /// declare namespace I18next { @@ -81,8 +80,6 @@ declare namespace i18nextBrowserLanguageDetector { } declare module "i18next-browser-languagedetector" { - import * as express from "express"; - import * as i18next from "i18next"; export default i18nextBrowserLanguageDetector.LngDetector; } diff --git a/i18next/i18next.d.ts b/i18next/i18next.d.ts index 5e2f8dcd20..5ced8aecdb 100644 --- a/i18next/i18next.d.ts +++ b/i18next/i18next.d.ts @@ -39,15 +39,15 @@ declare namespace I18next { count?: number; context?: any; replace?: any; - lng?:string; - lngs?:string[]; - fallbackLng?:string; - ns?:string|string[]; - keySeparator?:string; - nsSeparator?:string; - returnObjects?:boolean; - joinArrays?:string; - postProcess?:string|any[]; + lng?: string; + lngs?: string[]; + fallbackLng?: string; + ns?: string | string[]; + keySeparator?: string; + nsSeparator?: string; + returnObjects?: boolean; + joinArrays?: string; + postProcess?: string | any[]; interpolation?: InterpolationOptions; } @@ -56,10 +56,10 @@ declare namespace I18next { resources?: ResourceStore; lng?: string; fallbackLng?: string; - ns?: string|string[]; + ns?: string | string[]; defaultNS?: string; - fallbackNS?: string|string[]; - whitelist?:string[]; + fallbackNS?: string | string[]; + whitelist?: string[]; lowerCaseLng?: boolean; load?: string preload?: string[]; @@ -69,61 +69,72 @@ declare namespace I18next { contextSeparator?: string; saveMissing?: boolean; saveMissingTo?: string; - missingKeyHandler?: (lng:string, ns:string, key:string, fallbackValue:string) => void; - parseMissingKeyHandler?: (key:string) => void; + missingKeyHandler?: (lng: string, ns: string, key: string, fallbackValue: string) => void; + parseMissingKeyHandler?: (key: string) => void; appendNamespaceToMissingKey?: boolean; - postProcess?: string|any[]; + postProcess?: string | any[]; returnNull?: boolean; returnEmptyString?: boolean; returnObjects?: boolean; - returnedObjectHandler?: (key:string, value:string, options:any) => void; + returnedObjectHandler?: (key: string, value: string, options: any) => void; joinArrays?: string; - overloadTranslationOptionHandler?: (args:any[]) => TranslationOptions; + overloadTranslationOptionHandler?: (args: any[]) => TranslationOptions; interpolation?: InterpolationOptions; detection?: any; backend?: any; cache?: any; } - type TranslationFunction = (key:string, options?:TranslationOptions) => string; + type TranslationFunction = (key: string, options?: TranslationOptions) => string; class I18n { - constructor(options?:Options, callback?:(err:any, t:TranslationFunction) => void); + constructor(options?: Options, callback?: (err: any, t: TranslationFunction) => void); - init(options?:Options, callback?:(err:any, t:TranslationFunction) => void):I18n; + init(options?: Options, callback?: (err: any, t: TranslationFunction) => void): I18n; - loadResources(callback?:(err:any) => void):void; + loadResources(callback?: (err: any) => void): void; - language:string; + language: string; - languages:string[]; + languages: string[]; - use(module:any):I18n; + use(module: any): I18n; - changeLanguage(lng:string, callback?:(err:any, t:TranslationFunction) => void):void; + changeLanguage(lng: string, callback?: (err: any, t: TranslationFunction) => void): void; - getFixedT(lng?:string, ns?:string|string[]):TranslationFunction; + getFixedT(lng?: string, ns?: string | string[]): TranslationFunction; - t(key:string, options?:TranslationOptions):string|any|Array; + t(key: string, options?: TranslationOptions): string | any | Array; - exists():boolean; + exists(): boolean; - setDefaultNamespace(ns:string):void; + setDefaultNamespace(ns: string): void; - loadNamespaces(ns:string[], callback?:() => void):void; + loadNamespaces(ns: string[], callback?: () => void): void; - loadLanguages(lngs:string[], callback?:()=>void):void; + loadLanguages(lngs: string[], callback?: () => void): void; - dir(lng?:string):string; + dir(lng?: string): string; - createInstance(options?:Options, callback?:(err:any, t:TranslationFunction) => void):I18n; + createInstance(options?: Options, callback?: (err: any, t: TranslationFunction) => void): I18n; - cloneInstance(options?:Options, callback?:(err:any, t:TranslationFunction) => void):I18n; + cloneInstance(options?: Options, callback?: (err: any, t: TranslationFunction) => void): I18n; + + on(event: string, listener: () => void): void; + on(initialized: 'initialized', listener: (options: I18next.Options) => void): void; + on(loaded: 'loaded', listener: (loaded: any) => void): void; + on(failedLoading: 'failedLoading', listener: (lng: string, ns: string, msg: string) => void): void; + on(missingKey: 'missingKey', listener: (lngs: any, namespace: string, key: string, res: any) => void): void; + on(added: 'added', listener: (lng: string, ns: string) => void): void; + on(removed: 'removed', listener: (lng: string, ns: string) => void): void; + on(languageChanged: 'languageChanged', listener: (lng: string) => void): void; + + off(event: string, listener: () => void): void; } } declare module 'i18next' { - var i18n:I18next.I18n; + var i18n: I18next.I18n; export = i18n; } diff --git a/imap/imap.d.ts b/imap/imap.d.ts index 1531035152..07a7c8fe9a 100644 --- a/imap/imap.d.ts +++ b/imap/imap.d.ts @@ -236,7 +236,7 @@ declare namespace IMAP { serverSupports(capability: string): boolean; } - export class Connection implements NodeJS.EventEmitter, MessageFunctions { + export class Connection extends NodeJS.EventEmitter implements MessageFunctions { /** @constructor */ constructor(config: Config); diff --git a/incremental-dom/incremental-dom.d.ts b/incremental-dom/incremental-dom.d.ts index 56fd84542f..5a80e82d70 100644 --- a/incremental-dom/incremental-dom.d.ts +++ b/incremental-dom/incremental-dom.d.ts @@ -27,7 +27,7 @@ declare module "incremental-dom" { * @param {...*} var_args Attribute name/value pairs of the dynamic attributes * for the Element. */ - export var elementOpen: (tag: string, key?: string, statics?: any[], ...var_args: any[]) => void; + export var elementOpen: (tag: string, key?: string, statics?: any[], ...var_args: any[]) => HTMLElement; /** * Declares a virtual Element at the current location in the document. This * corresponds to an opening tag and a elementClose tag is required. This is @@ -54,11 +54,11 @@ declare module "incremental-dom" { /** * Closes an open tag started with elementOpenStart. */ - export var elementOpenEnd: () => void; + export var elementOpenEnd: () => HTMLElement; /** * Closes an open virtual Element. */ - export var elementClose: (tag: string) => void; + export var elementClose: (tag: string) => HTMLElement; /** * Declares a virtual Element at the current location in the document that has * no children. @@ -72,11 +72,11 @@ declare module "incremental-dom" { * @param {...*} var_args Attribute name/value pairs of the dynamic attributes * for the Element. */ - export var elementVoid: (tag: string, key?: string, statics?: any, ...var_args: any[]) => void; + export var elementVoid: (tag: string, key?: string, statics?: any, ...var_args: any[]) => HTMLElement; /** * Declares a virtual Text at this point in the document. * * @param {string} value The text of the Text. */ - export var text: (value: string) => void; + export var text: (value: string) => Text; } diff --git a/inline-css/inline-css.d.ts b/inline-css/inline-css.d.ts index 478f25226b..41511097c7 100644 --- a/inline-css/inline-css.d.ts +++ b/inline-css/inline-css.d.ts @@ -3,7 +3,7 @@ // Definitions by: Philip Spain // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module 'inline-css' { import Promise = require('bluebird'); diff --git a/inversify-binding-decorators/inversify-binding-decorators-tests.ts b/inversify-binding-decorators/inversify-binding-decorators-tests.ts index 9b0dff520e..8ca0acc551 100644 --- a/inversify-binding-decorators/inversify-binding-decorators-tests.ts +++ b/inversify-binding-decorators/inversify-binding-decorators-tests.ts @@ -4,51 +4,52 @@ import { inject, Kernel } from "inversify"; import { autoProvide, makeProvideDecorator, makeFluentProvideDecorator } from "inversify-binding-decorators"; module decorator { + let kernel = new Kernel(); let provide = makeProvideDecorator(kernel); - interface INinja { + interface Warrior { fight(): string; sneak(): string; } - interface IKatana { + interface Weapon { hit(): string; } - interface IShuriken { + interface ThrowableWeapon { throw(): string; } let TYPE = { - IKatana: "IKatana", - INinja: "INinja", - IShuriken: "IShuriken" + ThrowableWeapon: "ThrowableWeapon", + Warrior: "Warrior", + Weapon: "Weapon" }; - @provide(TYPE.IKatana) - class Katana implements IKatana { + @provide(TYPE.Weapon) + class Katana implements Weapon { public hit() { return "cut!"; } } - @provide(TYPE.IShuriken) - class Shuriken implements IShuriken { + @provide(TYPE.ThrowableWeapon) + class Shuriken implements ThrowableWeapon { public throw() { return "hit!"; } } - @provide(TYPE.INinja) - class Ninja implements INinja { + @provide(TYPE.Warrior) + class Ninja implements Warrior { - private _katana: IKatana; - private _shuriken: IShuriken; + private _katana: Weapon; + private _shuriken: ThrowableWeapon; public constructor( - @inject("IKatana") katana: IKatana, - @inject("IShuriken") shuriken: IShuriken + @inject(TYPE.Weapon) katana: Weapon, + @inject(TYPE.ThrowableWeapon) shuriken: ThrowableWeapon ) { this._katana = katana; this._shuriken = shuriken; @@ -59,12 +60,13 @@ module decorator { } - let ninja = kernel.get(TYPE.INinja); + let ninja = kernel.get(TYPE.Warrior); console.log(ninja); } module fluent_decorator { + let kernel = new Kernel(); let provide = makeFluentProvideDecorator(kernel); @@ -76,27 +78,27 @@ module fluent_decorator { return provide(identifier).done(); }; - interface INinja { + interface Warrior { fight(): string; sneak(): string; } - interface IKatana { + interface Weapon { hit(): string; } - interface IShuriken { + interface ThrowableWeapon { throw(): string; } let TYPE = { - IKatana: "IKatana", - INinja: "INinja", - IShuriken: "IShuriken" + ThrowableWeapon: "ThrowableWeapon", + Warrior: "Warrior", + Weapon: "Weapon" }; - @provideSingleton(TYPE.IKatana) - class Katana implements IKatana { + @provideSingleton(TYPE.Weapon) + class Katana implements Weapon { private _mark: any; public constructor() { this._mark = Math.random(); @@ -106,8 +108,8 @@ module fluent_decorator { } } - @provideTransient(TYPE.IShuriken) - class Shuriken implements IShuriken { + @provideTransient(TYPE.ThrowableWeapon) + class Shuriken implements ThrowableWeapon { private _mark: any; public constructor() { this._mark = Math.random(); @@ -117,15 +119,15 @@ module fluent_decorator { } } - @provideTransient(TYPE.INinja) - class Ninja implements INinja { + @provideTransient(TYPE.Warrior) + class Ninja implements Warrior { - private _katana: IKatana; - private _shuriken: IShuriken; + private _katana: Weapon; + private _shuriken: ThrowableWeapon; public constructor( - @inject("IKatana") katana: IKatana, - @inject("IShuriken") shuriken: IShuriken + @inject(TYPE.Weapon) katana: Weapon, + @inject(TYPE.ThrowableWeapon) shuriken: ThrowableWeapon ) { this._katana = katana; this._shuriken = shuriken; @@ -136,7 +138,7 @@ module fluent_decorator { } - let ninja = kernel.get(TYPE.INinja); + let ninja = kernel.get(TYPE.Warrior); console.log(ninja); } diff --git a/inversify-binding-decorators/inversify-binding-decorators.d.ts b/inversify-binding-decorators/inversify-binding-decorators.d.ts index 623b6c32c7..d5f92132a3 100644 --- a/inversify-binding-decorators/inversify-binding-decorators.d.ts +++ b/inversify-binding-decorators/inversify-binding-decorators.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify 1.0.0-beta.5 +// Type definitions for inversify-binding-decorators 1.0.0 // Project: https://github.com/inversify/inversify-binding-decorators // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -7,46 +7,50 @@ declare namespace inversifyBindingDecorators { - interface IProvideInSyntax extends IProvideDoneSyntax { - inSingletonScope(): IProvideWhenOnSyntax; - } + namespace interfaces { - interface IProvideDoneSyntax { - done(): (target: any) => any; - } + export interface ProvideInSyntax extends ProvideDoneSyntax { + inSingletonScope(): ProvideWhenOnSyntax; + } - interface IProvideOnSyntax extends IProvideDoneSyntax { - onActivation(fn: (context: inversify.interfaces.Context, injectable: T) => T): IProvideWhenSyntax; - } + export interface ProvideDoneSyntax { + done(): (target: any) => any; + } - interface IProvideInWhenOnSyntax extends IProvideInSyntax, IProvideWhenSyntax, IProvideOnSyntax {} + export interface ProvideOnSyntax extends ProvideDoneSyntax { + onActivation(fn: (context: inversify.interfaces.Context, injectable: T) => T): ProvideWhenSyntax; + } - interface IProvideWhenOnSyntax extends IProvideWhenSyntax, IProvideOnSyntax {} + export interface ProvideInWhenOnSyntax extends ProvideInSyntax, ProvideWhenSyntax, ProvideOnSyntax {} + + export interface ProvideWhenOnSyntax extends ProvideWhenSyntax, ProvideOnSyntax {} + + export interface ProvideWhenSyntax extends ProvideDoneSyntax { + when(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax; + whenTargetNamed(name: string): ProvideOnSyntax; + whenTargetTagged(tag: string, value: any): ProvideOnSyntax; + whenInjectedInto(parent: (Function|string)): ProvideOnSyntax; + whenParentNamed(name: string): ProvideOnSyntax; + whenParentTagged(tag: string, value: any): ProvideOnSyntax; + whenAnyAncestorIs(ancestor: (Function|string)): ProvideOnSyntax; + whenNoAncestorIs(ancestor: (Function|string)): ProvideOnSyntax; + whenAnyAncestorNamed(name: string): ProvideOnSyntax; + whenAnyAncestorTagged(tag: string, value: any): ProvideOnSyntax; + whenNoAncestorNamed(name: string): ProvideOnSyntax; + whenNoAncestorTagged(tag: string, value: any): ProvideOnSyntax; + whenAnyAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax; + whenNoAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax; + } - interface IProvideWhenSyntax extends IProvideDoneSyntax { - when(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; - whenTargetNamed(name: string): IProvideOnSyntax; - whenTargetTagged(tag: string, value: any): IProvideOnSyntax; - whenInjectedInto(parent: (Function|string)): IProvideOnSyntax; - whenParentNamed(name: string): IProvideOnSyntax; - whenParentTagged(tag: string, value: any): IProvideOnSyntax; - whenAnyAncestorIs(ancestor: (Function|string)): IProvideOnSyntax; - whenNoAncestorIs(ancestor: (Function|string)): IProvideOnSyntax; - whenAnyAncestorNamed(name: string): IProvideOnSyntax; - whenAnyAncestorTagged(tag: string, value: any): IProvideOnSyntax; - whenNoAncestorNamed(name: string): IProvideOnSyntax; - whenNoAncestorTagged(tag: string, value: any): IProvideOnSyntax; - whenAnyAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; - whenNoAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; } export function autoProvide(kernel: inversify.interfaces.Kernel, ...modules: any[]): void; export function makeProvideDecorator(kernel: inversify.interfaces.Kernel): - (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => (target: any) => any; + (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => (target: any) => any; export function makeFluentProvideDecorator(kernel: inversify.interfaces.Kernel): - (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => IProvideInWhenOnSyntax; + (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => interfaces.ProvideInWhenOnSyntax; } diff --git a/inversify-devtools/inversify-devtools-test.ts b/inversify-devtools/inversify-devtools-test.ts new file mode 100644 index 0000000000..3b99d7df93 --- /dev/null +++ b/inversify-devtools/inversify-devtools-test.ts @@ -0,0 +1,8 @@ +/// + +import render from "inversify-devtools"; +import { Kernel } from "inversify"; + +let connectKernel = render("root"); +let kernel = new Kernel(); +connectKernel(kernel); diff --git a/inversify-devtools/inversify-devtools.d.ts b/inversify-devtools/inversify-devtools.d.ts new file mode 100644 index 0000000000..841ae228c5 --- /dev/null +++ b/inversify-devtools/inversify-devtools.d.ts @@ -0,0 +1,15 @@ +// Type definitions for inversify-devtools 1.0.0 +// Project: https://github.com/inversify/inversify-devtools +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface ConnectKernel extends Function { + (kernel: inversify.interfaces.Kernel): void; +} + +declare module "inversify-devtools" { + let render: (container: string) => ConnectKernel; + export default render; +} diff --git a/inversify-express-utils/inversify-express-utils-tests.ts b/inversify-express-utils/inversify-express-utils-tests.ts index 1d421e397a..b082546448 100644 --- a/inversify-express-utils/inversify-express-utils-tests.ts +++ b/inversify-express-utils/inversify-express-utils-tests.ts @@ -1,21 +1,23 @@ /// -import { InversifyExpressServer, Controller, Get, All, Delete, Head, Put, Patch, Post, Method } from "inversify-express-utils"; +import { InversifyExpressServer, Controller, Get, All, Delete, Head, Put, Patch, Post, Method, TYPE } from "inversify-express-utils"; import * as express from "express"; import { Kernel } from "inversify"; +let kernel = new Kernel(); + module server { - let kernel = new Kernel(); + let server = new InversifyExpressServer(kernel); server - .setConfig((app) => { + .setConfig((app: express.Application) => { app.use((req: express.Request, res: express.Response, next: express.NextFunction) => { console.log("hello world"); next(); }); }) - .setErrorConfig((app) => { + .setErrorConfig((app: express.Application) => { app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => { console.error(err.stack); res.status(500).send("Something broke!"); @@ -55,6 +57,8 @@ module decorators { public testMethod() { return "METHOD:FOO"; } } + kernel.bind(TYPE.Controller).to(TestController); + function m1(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } function m2(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } function m3(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } diff --git a/inversify-express-utils/inversify-express-utils.d.ts b/inversify-express-utils/inversify-express-utils.d.ts index aa9a20d23c..f90b0cac88 100644 --- a/inversify-express-utils/inversify-express-utils.d.ts +++ b/inversify-express-utils/inversify-express-utils.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify 1.0.0-alpha.4 +// Type definitions for inversify-express-utils 1.0.0 // Project: https://github.com/inversify/inversify-express-utils // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -11,40 +11,50 @@ declare module "inversify-express-utils" { import * as express from "express"; import * as inversify from "inversify"; - interface IInversifyExpressServerConstructor { - new(kernel: inversify.interfaces.Kernel): IInversifyExpressServer; + export namespace interfaces { + + export interface InversifyExpressServerConstructor { + new(kernel: inversify.interfaces.Kernel): InversifyExpressServer; + } + + export interface InversifyExpressServer { + setConfig(fn: ConfigFunction): InversifyExpressServer; + setErrorConfig(fn: ConfigFunction): InversifyExpressServer; + build(): express.Application; + } + + export interface ConfigFunction { + (app: express.Application): void; + } + + export interface HandlerDecoratorFactory { + (path: string, ...middleware: express.RequestHandler[]): HandlerDecorator; + } + + export interface HandlerDecorator { + (target: any, key: string, value: any): void; + } + } - interface IInversifyExpressServer { - setConfig(fn: IConfigFunction): IInversifyExpressServer; - setErrorConfig(fn: IConfigFunction): IInversifyExpressServer; - build(): express.Application; + export interface Controller {} + + interface ServiceIdentifiers { + Controller: Symbol; } - interface IConfigFunction { - (app: express.Application): void; - } - - interface IHandlerDecoratorFactory { - (path: string, ...middleware: express.RequestHandler[]): IHandlerDecorator; - } - - interface IHandlerDecorator { - (target: any, key: string, value: any): void; - } - - export interface IController {} - - export var InversifyExpressServer: IInversifyExpressServerConstructor; + export var InversifyExpressServer: interfaces.InversifyExpressServerConstructor; export var Controller: (path: string, ...middleware: express.RequestHandler[]) => (target: any) => void; - export var All: IHandlerDecoratorFactory; - export var Get: IHandlerDecoratorFactory; - export var Post: IHandlerDecoratorFactory; - export var Put: IHandlerDecoratorFactory; - export var Patch: IHandlerDecoratorFactory; - export var Head: IHandlerDecoratorFactory; - export var Delete: IHandlerDecoratorFactory; - export var Method: (method: string, path: string, ...middleware: express.RequestHandler[]) => IHandlerDecorator; + export var All: interfaces.HandlerDecoratorFactory; + export var Get: interfaces.HandlerDecoratorFactory; + export var Post: interfaces.HandlerDecoratorFactory; + export var Put: interfaces.HandlerDecoratorFactory; + export var Patch: interfaces.HandlerDecoratorFactory; + export var Head: interfaces.HandlerDecoratorFactory; + export var Delete: interfaces.HandlerDecoratorFactory; + export var Method: (method: string, path: string, ...middleware: express.RequestHandler[]) => interfaces.HandlerDecorator; + export var TYPE: ServiceIdentifiers; + } diff --git a/inversify-inject-decorators/inversify-inject-decorators-tests.ts b/inversify-inject-decorators/inversify-inject-decorators-tests.ts new file mode 100644 index 0000000000..468bbaf763 --- /dev/null +++ b/inversify-inject-decorators/inversify-inject-decorators-tests.ts @@ -0,0 +1,214 @@ +/// +/// + +import getDecorators from "inversify-inject-decorators"; +import { Kernel, injectable, tagged, named } from "inversify"; + +module lazyInject { + + let kernel = new Kernel(); + let { lazyInject } = getDecorators(kernel); + let TYPES = { Weapon: "Weapon" }; + + interface Weapon { + name: string; + durability: number; + use(): void; + } + + @injectable() + class Sword implements Weapon { + public name: string; + public durability: number; + public constructor() { + this.durability = 100; + this.name = "Sword"; + } + public use() { + this.durability = this.durability - 10; + } + } + + class Warrior { + @lazyInject(TYPES.Weapon) + public weapon: Weapon; + } + + kernel.bind(TYPES.Weapon).to(Sword); + + let warrior = new Warrior(); + console.log(warrior.weapon instanceof Sword); // true + +} + +module lazyInjectNamed { + + let kernel = new Kernel(); + let { lazyInjectNamed } = getDecorators(kernel); + let TYPES = { Weapon: "Weapon" }; + + interface Weapon { + name: string; + durability: number; + use(): void; + } + + @injectable() + class Sword implements Weapon { + public name: string; + public durability: number; + public constructor() { + this.durability = 100; + this.name = "Sword"; + } + public use() { + this.durability = this.durability - 10; + } + } + + @injectable() + class Shuriken implements Weapon { + public name: string; + public durability: number; + public constructor() { + this.durability = 100; + this.name = "Shuriken"; + } + public use() { + this.durability = this.durability - 10; + } + } + + class Warrior { + + @lazyInjectNamed(TYPES.Weapon, "not-throwwable") + @named("not-throwwable") + public primaryWeapon: Weapon; + + @lazyInjectNamed(TYPES.Weapon, "throwwable") + @named("throwwable") + public secondaryWeapon: Weapon; + + } + + kernel.bind(TYPES.Weapon).to(Sword).whenTargetNamed("not-throwwable"); + kernel.bind(TYPES.Weapon).to(Shuriken).whenTargetNamed("throwwable"); + + let warrior = new Warrior(); + console.log(warrior.primaryWeapon instanceof Sword); // true + console.log(warrior.primaryWeapon instanceof Shuriken); // true + +} + +module lazyInjectTagged { + + let kernel = new Kernel(); + let { lazyInjectTagged } = getDecorators(kernel); + let TYPES = { Weapon: "Weapon" }; + + interface Weapon { + name: string; + durability: number; + use(): void; + } + + @injectable() + class Sword implements Weapon { + public name: string; + public durability: number; + public constructor() { + this.durability = 100; + this.name = "Sword"; + } + public use() { + this.durability = this.durability - 10; + } + } + + @injectable() + class Shuriken implements Weapon { + public name: string; + public durability: number; + public constructor() { + this.durability = 100; + this.name = "Shuriken"; + } + public use() { + this.durability = this.durability - 10; + } + } + + class Warrior { + + @lazyInjectTagged(TYPES.Weapon, "throwwable", false) + @tagged("throwwable", false) + public primaryWeapon: Weapon; + + @lazyInjectTagged(TYPES.Weapon, "throwwable", true) + @tagged("throwwable", true) + public secondaryWeapon: Weapon; + + } + + kernel.bind(TYPES.Weapon).to(Sword).whenTargetTagged("throwwable", false); + kernel.bind(TYPES.Weapon).to(Shuriken).whenTargetTagged("throwwable", true); + + let warrior = new Warrior(); + console.log(warrior.primaryWeapon instanceof Sword); // true + console.log(warrior.primaryWeapon instanceof Shuriken); // true + +} + +module lazyMultiInject { + + let kernel = new Kernel(); + let { lazyMultiInject } = getDecorators(kernel); + let TYPES = { Weapon: "Weapon" }; + + interface Weapon { + name: string; + durability: number; + use(): void; + } + + @injectable() + class Sword implements Weapon { + public name: string; + public durability: number; + public constructor() { + this.durability = 100; + this.name = "Sword"; + } + public use() { + this.durability = this.durability - 10; + } + } + + @injectable() + class Shuriken implements Weapon { + public name: string; + public durability: number; + public constructor() { + this.durability = 100; + this.name = "Shuriken"; + } + public use() { + this.durability = this.durability - 10; + } + } + + class Warrior { + + @lazyMultiInject(TYPES.Weapon) + public weapons: Weapon[]; + + } + + kernel.bind(TYPES.Weapon).to(Sword); + kernel.bind(TYPES.Weapon).to(Shuriken); + + let warrior = new Warrior(); + console.log(warrior.weapons[0] instanceof Sword); // true + console.log(warrior.weapons[1] instanceof Shuriken); // true + +} diff --git a/inversify-inject-decorators/inversify-inject-decorators.d.ts b/inversify-inject-decorators/inversify-inject-decorators.d.ts new file mode 100644 index 0000000000..34244c6d5e --- /dev/null +++ b/inversify-inject-decorators/inversify-inject-decorators.d.ts @@ -0,0 +1,31 @@ +// Type definitions for inversify-inject-decorators 1.0.0 +// Project: https://github.com/inversify/inversify-inject-decorators +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare namespace inversifyInjectDecorators { + + export interface InjectDecorators { + + lazyInject: (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => + (proto: any, key: string) => void; + + lazyInjectNamed: (serviceIdentifier: inversify.interfaces.ServiceIdentifier, named: string) => + (proto: any, key: string) => void; + + lazyInjectTagged: (serviceIdentifier: inversify.interfaces.ServiceIdentifier, key: string, value: any) => + (proto: any, propertyName: string) => void; + + lazyMultiInject: (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => + (proto: any, key: string) => void; + + } + +} + +declare module "inversify-inject-decorators" { + let getDecorators: (kernel: inversify.interfaces.Kernel) => inversifyInjectDecorators.InjectDecorators; + export default getDecorators; +} diff --git a/inversify-logger-middleware/inversify-logger-middleware-tests.ts b/inversify-logger-middleware/inversify-logger-middleware-tests.ts index c9c7d5c8a8..3b2119911a 100644 --- a/inversify-logger-middleware/inversify-logger-middleware-tests.ts +++ b/inversify-logger-middleware/inversify-logger-middleware-tests.ts @@ -4,23 +4,23 @@ declare var kernel: inversify.interfaces.Kernel; import { makeLoggerMiddleware, textSerializer } from "inversify-logger-middleware"; -interface ILoggerOutput { +interface LoggerOutput { entry: T; } -let makeStringRenderer = function (loggerOutput: ILoggerOutput) { - return function (entry: inversifyLoggerMiddleware.ILogEntry) { +let makeStringRenderer = function (loggerOutput: LoggerOutput) { + return function (entry: inversifyLoggerMiddleware.interfaces.LogEntry) { loggerOutput.entry = textSerializer(entry); }; }; -let makeObjRenderer = function (loggerOutput: ILoggerOutput) { - return function (entry: inversifyLoggerMiddleware.ILogEntry) { +let makeObjRenderer = function (loggerOutput: LoggerOutput) { + return function (entry: inversifyLoggerMiddleware.interfaces.LogEntry) { loggerOutput.entry = entry; }; }; -let options: inversifyLoggerMiddleware.ILoggerSettings = { +let options: inversifyLoggerMiddleware.interfaces.LoggerSettings = { request: { bindings: { activated: true, @@ -48,12 +48,12 @@ let options: inversifyLoggerMiddleware.ILoggerSettings = { let logger = makeLoggerMiddleware(); kernel.applyMiddleware(logger); -let loggerOutput1: ILoggerOutput = { entry: null }; +let loggerOutput1: LoggerOutput = { entry: null }; let stringRenderer1 = makeStringRenderer(loggerOutput1); let logger1 = makeLoggerMiddleware(options, stringRenderer1); kernel.applyMiddleware(logger1); -let loggerOutput2: ILoggerOutput = { entry: null }; +let loggerOutput2: LoggerOutput = { entry: null }; let objRenderer2 = makeObjRenderer(loggerOutput2); let logger2 = makeLoggerMiddleware(options, objRenderer2); kernel.applyMiddleware(logger2); diff --git a/inversify-logger-middleware/inversify-logger-middleware.d.ts b/inversify-logger-middleware/inversify-logger-middleware.d.ts index 3aa4ccca18..cd0037f432 100644 --- a/inversify-logger-middleware/inversify-logger-middleware.d.ts +++ b/inversify-logger-middleware/inversify-logger-middleware.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify 1.0.0-beta.6 +// Type definitions for inversify-logger-middleware 1.0.0 // Project: https://github.com/inversify/inversify-logger-middleware // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -7,50 +7,61 @@ declare namespace inversifyLoggerMiddleware { - export interface ILoggerSettings { - request?: IRequestLoggerSettings; - time?: boolean; + export namespace interfaces { + + export interface LoggerSettings { + request?: RequestLoggerSettings; + time?: boolean; + } + + export interface RequestLoggerSettings { + serviceIdentifier?: boolean; + bindings?: BindingLoggerSettings; + target?: TargetLoggerSettings; + } + + export interface BindingLoggerSettings { + activated?: boolean; + serviceIdentifier?: boolean; + implementationType?: boolean; + factory?: boolean; + provider?: boolean; + constraint?: boolean; + onActivation?: boolean; + cache?: boolean; + dynamicValue?: boolean; + scope?: boolean; + type?: boolean; + } + + export interface TargetLoggerSettings { + serviceIdentifier?: boolean; + name?: boolean; + metadata?: boolean; + } + + export interface LogEntry { + error: boolean; + exception: any; + guid: string; + multiInject: boolean; + results: any[]; + rootRequest: inversify.interfaces.Request; + serviceIdentifier: any; + target: any; + time: string; + } + } - export interface IRequestLoggerSettings { - serviceIdentifier?: boolean; - bindings?: IBindingLoggerSettings; - target?: ITargetLoggerSettings; - } + export function makeLoggerMiddleware( + settings?: interfaces.LoggerSettings, + renderer?: (out: interfaces.LogEntry) => void + ): inversify.interfaces.Middleware; - export interface IBindingLoggerSettings { - activated?: boolean; - serviceIdentifier?: boolean; - implementationType?: boolean; - factory?: boolean; - provider?: boolean; - constraint?: boolean; - onActivation?: boolean; - cache?: boolean; - dynamicValue?: boolean; - scope?: boolean; - type?: boolean; - } - - export interface ITargetLoggerSettings { - serviceIdentifier?: boolean; - name?: boolean; - metadata?: boolean; - } - - export interface ILogEntry { - error: boolean; - exception: any; - multiInject: boolean; - results: any[]; - rootRequest: inversify.interfaces.Request; - serviceIdentifier: any; - target: any; - time: string; - } - - export function makeLoggerMiddleware(settings?: ILoggerSettings, renderer?: (out: ILogEntry) => void): inversify.interfaces.Middleware; - export function textSerializer(entry: ILogEntry): string; + export function textSerializer(entry: interfaces.LogEntry): string; + export function bindingTypeFormatter(type: number): string; + export function scopeFormatter(scope: number): string; } diff --git a/inversify-restify-utils/inversify-restify-utils-tests.ts b/inversify-restify-utils/inversify-restify-utils-tests.ts new file mode 100644 index 0000000000..5ff3ddc633 --- /dev/null +++ b/inversify-restify-utils/inversify-restify-utils-tests.ts @@ -0,0 +1,91 @@ +/// + +import { + InversifyRestifyServer, Controller, Get, Options, + Delete, Head, Put, Patch, Post, Method, TYPE +} from "inversify-restify-utils"; + +import * as restify from "restify"; +import { Kernel } from "inversify"; + +let kernel = new Kernel(); + +module server { + + let server = new InversifyRestifyServer(kernel); + + server + .setConfig((app: restify.Server) => { + app.use((req: restify.Request, res: restify.Response, next: restify.Next) => { + console.log("hello world"); + next(); + }); + }) + .build() + .listen(3000, "localhost"); +} + +module decorators { + + @Controller("/") + class TestController { + + @Get("/") + public testGet() { return "GET"; } + + @Options("/") + public testAll() { return "OPTIONS"; } + + @Delete("/") + public testDelete() { return "DELETE"; } + + @Head("/") + public testHead() { return "HEAD"; } + + @Put("/") + public testPut() { return "PUT"; } + + @Patch("/") + public testPatch() { return "PATCH"; } + + @Post("/") + public testPost() { return "POST"; } + + @Method("opts", "/") + public testMethod() { return "METHOD:OPTS"; } + } + + kernel.bind(TYPE.Controller).to(TestController); + + function m1(req: restify.Request, res: restify.Response, next: restify.Next) { next(); } + function m2(req: restify.Request, res: restify.Response, next: restify.Next) { next(); } + function m3(req: restify.Request, res: restify.Response, next: restify.Next) { next(); } + + @Controller("/", m1, m2, m3) + class TestMiddlewareController { + + @Get("/", m1, m2, m3) + public testGet() { return "GET"; } + + @Options("/", m1, m2, m3) + public testAll() { return "OPTIONS"; } + + @Delete("/", m1, m2, m3) + public testDelete() { return "DELETE"; } + + @Head("/", m1, m2, m3) + public testHead() { return "HEAD"; } + + @Put("/", m1, m2, m3) + public testPut() { return "PUT"; } + + @Patch("/", m1, m2, m3) + public testPatch() { return "PATCH"; } + + @Post("/", m1, m2, m3) + public testPost() { return "POST"; } + + @Method("opts", "/", m1, m2, m3) + public testMethod() { return "METHOD:OPTS"; } + } +} diff --git a/inversify-restify-utils/inversify-restify-utils.d.ts b/inversify-restify-utils/inversify-restify-utils.d.ts new file mode 100644 index 0000000000..4f2aab5510 --- /dev/null +++ b/inversify-restify-utils/inversify-restify-utils.d.ts @@ -0,0 +1,59 @@ +// Type definitions for inversify-restify-utils 1.0.0 +// Project: https://github.com/inversify/inversify-restify-utils +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "inversify-restify-utils" { + + import * as restify from "restify"; + import * as inversify from "inversify"; + + export namespace interfaces { + + export interface InversifyRestifyServerConstructor { + new(kernel: inversify.interfaces.Kernel): InversifyRestifyServer; + } + + export interface InversifyRestifyServer { + setConfig(fn: ConfigFunction): InversifyRestifyServer; + build(): restify.Server; + } + + export interface ConfigFunction { + (app: restify.Server): void; + } + + export interface HandlerDecoratorFactory { + (path: string, ...middleware: restify.RequestHandler[]): HandlerDecorator; + } + + export interface HandlerDecorator { + (target: any, key: string, value: any): void; + } + + } + + export interface Controller {} + + interface ServiceIdentifiers { + Controller: Symbol; + } + + export var InversifyRestifyServer: interfaces.InversifyRestifyServerConstructor; + + export var Controller: (path: string, ...middleware: restify.RequestHandler[]) => (target: any) => void; + + export var Options: interfaces.HandlerDecoratorFactory; + export var Get: interfaces.HandlerDecoratorFactory; + export var Post: interfaces.HandlerDecoratorFactory; + export var Put: interfaces.HandlerDecoratorFactory; + export var Patch: interfaces.HandlerDecoratorFactory; + export var Head: interfaces.HandlerDecoratorFactory; + export var Delete: interfaces.HandlerDecoratorFactory; + export var Method: (method: string, path: string, ...middleware: restify.RequestHandler[]) => interfaces.HandlerDecorator; + export var TYPE: ServiceIdentifiers; + +} diff --git a/inversify/inversify-global-tests.ts b/inversify/inversify-global-tests.ts index e2ead555d4..53b1a522bf 100644 --- a/inversify/inversify-global-tests.ts +++ b/inversify/inversify-global-tests.ts @@ -1,6 +1,8 @@ /// /// +import * as Proxy from "harmony-proxy"; + let injectable = inversify.injectable; let inject = inversify.inject; let tagged = inversify.tagged; @@ -13,10 +15,7 @@ let traverseAncerstors = inversify.traverseAncerstors; let taggedConstraint = inversify.taggedConstraint; let namedConstraint = inversify.namedConstraint; let typeConstraint = inversify.typeConstraint; -let makePropertyMultiInjectDecorator = inversify.makePropertyMultiInjectDecorator; -let makePropertyInjectTaggedDecorator = inversify.makePropertyInjectTaggedDecorator; -let makePropertyInjectNamedDecorator = inversify.makePropertyInjectNamedDecorator; -let makePropertyInjectDecorator = inversify.makePropertyInjectDecorator; +let unmanaged = inversify.unmanaged; module external_module_test { @@ -112,7 +111,7 @@ module external_module_test { // binding types kernel.bind("Weapon").to(Katana); kernel.bind("Weapon").toConstantValue(new Katana()); - kernel.bind("Weapon").toDynamicValue(() => { return new Katana(); }); + kernel.bind("Weapon").toDynamicValue((context: inversify.interfaces.Context) => { return new Katana(); }); kernel.bind>("Weapon").toConstructor(Katana); @@ -145,6 +144,7 @@ module external_module_test { return new Proxy(katanaToBeInjected, handler); }); + @injectable() class Samurai implements Warrior { public katana: Weapon; @@ -161,8 +161,9 @@ module external_module_test { } kernel.bind("Samurai").to(Samurai); - kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); + kernel.bind("Weapon").to(Katana).whenTargetTagged("canThrow", false); kernel.bind("ThrowableWeapon").to(Shuriken).whenTargetTagged("canThrow", true); + kernel.getAllTagged("Weapon", "canThrow", false); let throwable = tagged("canThrow", true); let notThrowable = tagged("canThrow", false); @@ -200,6 +201,7 @@ module external_module_test { kernel.bind("Warrior").to(Samurai3); kernel.bind("Weapon").to(Katana).whenTargetNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenTargetNamed("weak"); + kernel.getAllNamed("Weapon", "weak"); @injectable() class Samurai4 implements Samurai { @@ -245,18 +247,18 @@ module external_module_test { // Constraint helpers kernel.bind("Weapon").to(Shuriken).whenInjectedInto(Ninja); - kernel.bind("Weapon").to(Shuriken).whenInjectedInto("INinja"); + kernel.bind("Weapon").to(Shuriken).whenInjectedInto("Ninja"); kernel.bind("Weapon").to(Shuriken).whenParentNamed("chinese"); kernel.bind("Weapon").to(Shuriken).whenParentTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenTargetNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenTargetTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs(Ninja); - kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("Ninja"); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorMatches(whenParentNamedCanThrowConstraint); kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs(Ninja); - kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("Ninja"); kernel.bind("Weapon").to(Shuriken).whenNoAncestorNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenNoAncestorTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenNoAncestorMatches(whenParentNamedCanThrowConstraint); @@ -341,103 +343,42 @@ module external_module_test { } -module property_injection { +module snapshot { let kernel = new Kernel(); - let TYPES = { Weapon: "Weapon" }; - - interface Weapon { - durability: number; - use(): void; - } - - @injectable() - class Sword implements Weapon { - public durability: number; - public constructor() { - this.durability = 100; - } - public use() { - this.durability = this.durability - 10; - } - } - - @injectable() - class WarHammer implements Weapon { - public durability: number; - public constructor() { - this.durability = 100; - } - public use() { - this.durability = this.durability - 10; - } - } - - let propertyMultiInject = makePropertyMultiInjectDecorator(kernel); - - class Warrior1 { - @propertyMultiInject(TYPES.Weapon) - public weapons: Weapon[]; - } - - let propertyInject = makePropertyInjectDecorator(kernel); - - interface Service { - count: number; - increment(): void; - } - - @injectable() - class SomeService implements Service { - public count: number; - public constructor() { - this.count = 0; - } - public increment() { - this.count = this.count + 1; - } - } - - class SomeWebComponent { - @propertyInject("Service") - private _service: Service; - public doSomething() { - let count = this._service.count; - this._service.increment(); - return count; - } - } - - let propertyInjectNammed = makePropertyInjectNamedDecorator(kernel); - - class Warrior2 { - - @propertyInjectNammed(TYPES.Weapon, "not-throwwable") - @named("not-throwwable") - public primaryWeapon: Weapon; - - @propertyInjectNammed(TYPES.Weapon, "throwwable") - @named("throwwable") - public secondaryWeapon: Weapon; - - } - - let propertyInjectTagged = makePropertyInjectTaggedDecorator(kernel); - - class Warrior3 { - - @propertyInjectTagged(TYPES.Weapon, "throwwable", false) - @tagged("throwwable", false) - public primaryWeapon: Weapon; - - @propertyInjectTagged(TYPES.Weapon, "throwwable", true) - @tagged("throwwable", true) - public secondaryWeapon: Weapon; - - } - kernel.snapshot(); kernel.restore(); + @injectable() + class Test { } + + kernel.bind(Test).toSelf(); + kernel.bind(Test).toSelf().inSingletonScope(); +} + +module unmanaged_injection { + + let kernel = new Kernel(); + + const BaseId = "Base"; + + @injectable() + class Base { + public prop: string; + public constructor(@unmanaged() arg: string) { // injected by user + this.prop = arg; + } + } + + @injectable() + class Derived extends Base { + public constructor() { + super("unmanaged-injected-value"); // user injection + } + } + + kernel.bind(BaseId).to(Derived); + console.log(kernel.get(BaseId) instanceof Base); // true + } diff --git a/inversify/inversify-tests.ts b/inversify/inversify-tests.ts index 9b5de8fa0e..6b0d4a5f12 100644 --- a/inversify/inversify-tests.ts +++ b/inversify/inversify-tests.ts @@ -6,11 +6,7 @@ import { injectable, tagged, named, targetName, inject, multiInject, traverseAncerstors, taggedConstraint, namedConstraint, typeConstraint, - makePropertyMultiInjectDecorator, - makePropertyInjectTaggedDecorator, - makePropertyInjectNamedDecorator, - makePropertyInjectDecorator, - KernelModule, interfaces + KernelModule, interfaces, unmanaged } from "inversify"; import * as Proxy from "harmony-proxy"; @@ -109,7 +105,7 @@ module external_module_test { // binding types kernel.bind("Weapon").to(Katana); kernel.bind("Weapon").toConstantValue(new Katana()); - kernel.bind("Weapon").toDynamicValue(() => { return new Katana(); }); + kernel.bind("Weapon").toDynamicValue((context: interfaces.Context) => { return new Katana(); }); kernel.bind>("Weapon").toConstructor(Katana); @@ -159,8 +155,9 @@ module external_module_test { } kernel.bind("Samurai").to(Samurai); - kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); + kernel.bind("Weapon").to(Katana).whenTargetTagged("canThrow", false); kernel.bind("ThrowableWeapon").to(Shuriken).whenTargetTagged("canThrow", true); + kernel.getAllTagged("Weapon", "canThrow", false); let throwable = tagged("canThrow", true); let notThrowable = tagged("canThrow", false); @@ -198,6 +195,7 @@ module external_module_test { kernel.bind("Warrior").to(Samurai3); kernel.bind("Weapon").to(Katana).whenTargetNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenTargetNamed("weak"); + kernel.getAllNamed("Weapon", "weak"); @injectable() class Samurai4 implements Samurai { @@ -243,18 +241,18 @@ module external_module_test { // Constraint helpers kernel.bind("Weapon").to(Shuriken).whenInjectedInto(Ninja); - kernel.bind("Weapon").to(Shuriken).whenInjectedInto("INinja"); + kernel.bind("Weapon").to(Shuriken).whenInjectedInto("Ninja"); kernel.bind("Weapon").to(Shuriken).whenParentNamed("chinese"); kernel.bind("Weapon").to(Shuriken).whenParentTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenTargetNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenTargetTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs(Ninja); - kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("Ninja"); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorMatches(whenParentNamedCanThrowConstraint); kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs(Ninja); - kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("Ninja"); kernel.bind("Weapon").to(Shuriken).whenNoAncestorNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenNoAncestorTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenNoAncestorMatches(whenParentNamedCanThrowConstraint); @@ -339,103 +337,42 @@ module external_module_test { } -module property_injection { +module snapshot { let kernel = new Kernel(); - let TYPES = { Weapon: "Weapon" }; - - interface Weapon { - durability: number; - use(): void; - } - - @injectable() - class Sword implements Weapon { - public durability: number; - public constructor() { - this.durability = 100; - } - public use() { - this.durability = this.durability - 10; - } - } - - @injectable() - class WarHammer implements Weapon { - public durability: number; - public constructor() { - this.durability = 100; - } - public use() { - this.durability = this.durability - 10; - } - } - - let propertyMultiInject = makePropertyMultiInjectDecorator(kernel); - - class Warrior1 { - @propertyMultiInject(TYPES.Weapon) - public weapons: Weapon[]; - } - - let propertyInject = makePropertyInjectDecorator(kernel); - - interface Service { - count: number; - increment(): void; - } - - @injectable() - class SomeService implements Service { - public count: number; - public constructor() { - this.count = 0; - } - public increment() { - this.count = this.count + 1; - } - } - - class SomeWebComponent { - @propertyInject("Service") - private _service: Service; - public doSomething() { - let count = this._service.count; - this._service.increment(); - return count; - } - } - - let propertyInjectNammed = makePropertyInjectNamedDecorator(kernel); - - class Warrior2 { - - @propertyInjectNammed(TYPES.Weapon, "not-throwwable") - @named("not-throwwable") - public primaryWeapon: Weapon; - - @propertyInjectNammed(TYPES.Weapon, "throwwable") - @named("throwwable") - public secondaryWeapon: Weapon; - - } - - let propertyInjectTagged = makePropertyInjectTaggedDecorator(kernel); - - class Warrior3 { - - @propertyInjectTagged(TYPES.Weapon, "throwwable", false) - @tagged("throwwable", false) - public primaryWeapon: Weapon; - - @propertyInjectTagged(TYPES.Weapon, "throwwable", true) - @tagged("throwwable", true) - public secondaryWeapon: Weapon; - - } - kernel.snapshot(); kernel.restore(); + @injectable() + class Test { } + + kernel.bind(Test).toSelf(); + kernel.bind(Test).toSelf().inSingletonScope(); +} + +module unmanaged_injection { + + let kernel = new Kernel(); + + const BaseId = "Base"; + + @injectable() + class Base { + public prop: string; + public constructor(@unmanaged() arg: string) { // injected by user + this.prop = arg; + } + } + + @injectable() + class Derived extends Base { + public constructor() { + super("unmanaged-injected-value"); // user injection + } + } + + kernel.bind(BaseId).to(Derived); + console.log(kernel.get(BaseId) instanceof Base); // true + } diff --git a/inversify/inversify.d.ts b/inversify/inversify.d.ts index 41200ae470..2f07d203e1 100644 --- a/inversify/inversify.d.ts +++ b/inversify/inversify.d.ts @@ -1,9 +1,9 @@ -// Type definitions for inversify 2.0.0-beta.9 +// Type definitions for inversify 2.0.0-rc.12 // Project: https://github.com/inversify/InversifyJS // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// interface Symbol { toString(): string; @@ -31,9 +31,9 @@ declare namespace inversify { export interface Newable { new(...args: any[]): T; } - + export type ServiceIdentifier = (string|Symbol|Newable); - + export interface Binding extends Clonable> { guid: string; moduleId: string; @@ -45,70 +45,70 @@ declare namespace inversify { constraint: (request: Request) => boolean; onActivation: (context: Context, injectable: T) => T; cache: T; - dynamicValue: () => T; + dynamicValue: (context: Context) => T; scope: number; // BindingScope type: number; // BindingType } - + export interface Factory extends Function { (...args: any[]): (((...args: any[]) => T)|T); } - + export interface FactoryCreator extends Function { (context: Context): Factory; } - + export interface Provider extends Function { (): Promise; } - + export interface ProviderCreator extends Function { (context: Context): Provider; } - + export interface PlanAndResolve { (args: PlanAndResolveArgs): T[]; } - + export interface PlanAndResolveArgs { multiInject: boolean; serviceIdentifier: ServiceIdentifier; target: Target; contextInterceptor: (contexts: Context) => Context; } - + export interface Middleware extends Function { (next: PlanAndResolve): PlanAndResolve; } - + export interface Context { guid: string; kernel: Kernel; plan: Plan; addPlan(plan: Plan): void; } - + export interface ReflectResult { [key: string]: Metadata[]; } - + export interface Metadata { key: string; value: any; } - + export interface Plan { parentContext: Context; rootRequest: Request; } - + export interface Planner { createContext(kernel: Kernel): Context; createPlan(parentContext: Context, binding: Binding, target: Target): Plan; getBindings(kernel: Kernel, serviceIdentifier: ServiceIdentifier): Binding[]; getActiveBindings(parentRequest: Request, target: Target): Binding[]; } - + export interface QueryableString { startsWith(searchString: string): boolean; endsWith(searchString: string): boolean; @@ -116,7 +116,7 @@ declare namespace inversify { equals(compareString: string): boolean; value(): string; } - + export interface Request { guid: string; serviceIdentifier: ServiceIdentifier; @@ -131,10 +131,11 @@ declare namespace inversify { target: Target ): Request; } - + export interface Target { guid: string; serviceIdentifier: ServiceIdentifier; + type: number; // TargetType name: QueryableString; metadata: Array; hasTag(key: string): boolean; @@ -145,13 +146,14 @@ declare namespace inversify { matchesNamedTag(name: string): boolean; matchesTag(key: string): (value: any) => boolean; } - + export interface Resolver { resolve(context: Context): T; } - + export interface Kernel { guid: string; + parent: Kernel; bind(serviceIdentifier: ServiceIdentifier): BindingToSyntax; unbind(serviceIdentifier: ServiceIdentifier): void; unbindAll(): void; @@ -160,6 +162,8 @@ declare namespace inversify { getNamed(serviceIdentifier: ServiceIdentifier, named: string): T; getTagged(serviceIdentifier: ServiceIdentifier, key: string, value: any): T; getAll(serviceIdentifier: ServiceIdentifier): T[]; + getAllNamed(serviceIdentifier: ServiceIdentifier, named: string): T[]; + getAllTagged(serviceIdentifier: ServiceIdentifier, key: string, value: any): T[]; load(...modules: KernelModule[]): void; unload(...modules: KernelModule[]): void; applyMiddleware(...middleware: Middleware[]): void; @@ -167,25 +171,25 @@ declare namespace inversify { snapshot(): void; restore(): void; } - + export interface Bind extends Function { (serviceIdentifier: ServiceIdentifier): BindingToSyntax; } - + export interface KernelModule { guid: string; registry: (bind: Bind) => void; } - + export interface KernelSnapshot { bindings: Lookup>; middleware: PlanAndResolve; } - + export interface Clonable { clone(): T; } - + export interface Lookup extends Clonable> { add(serviceIdentifier: ServiceIdentifier, value: T): void; get(serviceIdentifier: ServiceIdentifier): Array; @@ -193,35 +197,38 @@ declare namespace inversify { removeByModuleId(moduleId: string): void; hasKey(serviceIdentifier: ServiceIdentifier): boolean; } - + export interface KeyValuePair { serviceIdentifier: ServiceIdentifier; value: Array; + guid: string; } - + export interface BindingInSyntax { inSingletonScope(): BindingWhenOnSyntax; + inTransientScope(): BindingWhenOnSyntax; } - + export interface BindingInWhenOnSyntax extends BindingInSyntax, BindingWhenOnSyntax {} - + export interface BindingOnSyntax { onActivation(fn: (context: Context, injectable: T) => T): BindingWhenSyntax; } - + export interface BindingToSyntax { to(constructor: { new(...args: any[]): T; }): BindingInWhenOnSyntax; + toSelf(): BindingInWhenOnSyntax; toConstantValue(value: T): BindingWhenOnSyntax; - toDynamicValue(func: () => T): BindingWhenOnSyntax; + toDynamicValue(func: (context: Context) => T): BindingWhenOnSyntax; toConstructor(constructor: Newable): BindingWhenOnSyntax; toFactory(factory: FactoryCreator): BindingWhenOnSyntax; toFunction(func: T): BindingWhenOnSyntax; toAutoFactory(serviceIdentifier: ServiceIdentifier): BindingWhenOnSyntax; toProvider(provider: ProviderCreator): BindingWhenOnSyntax; } - + export interface BindingWhenOnSyntax extends BindingWhenSyntax, BindingOnSyntax {} - + export interface BindingWhenSyntax { when(constraint: (request: Request) => boolean): BindingOnSyntax; whenTargetNamed(name: string): BindingOnSyntax; @@ -238,7 +245,7 @@ declare namespace inversify { whenAnyAncestorMatches(constraint: (request: Request) => boolean): BindingOnSyntax; whenNoAncestorMatches(constraint: (request: Request) => boolean): BindingOnSyntax; } - + } export var Kernel: interfaces.KernelConstructor; @@ -248,30 +255,19 @@ declare namespace inversify { export function tagged(metadataKey: string, metadataValue: any): (target: any, targetKey: string, index?: number) => any; export function named(name: string): (target: any, targetKey: string, index?: number) => any; export function targetName(name: string): (target: any, targetKey: string, index: number) => any; + export function unmanaged(): (target: any, targetKey: string, index: number) => any; export function inject(serviceIdentifier: interfaces.ServiceIdentifier): (target: any, targetKey: string, index?: number) => any; + export function guid(): string; export function multiInject( serviceIdentifier: interfaces.ServiceIdentifier ): (target: any, targetKey: string, index?: number) => any; - export function makePropertyInjectDecorator(kernel: interfaces.Kernel): - (serviceIdentifier: (string|Symbol|interfaces.Newable)) => (proto: any, key: string) => void; - - export function makePropertyInjectNamedDecorator(kernel: interfaces.Kernel): - (serviceIdentifier: (string|Symbol|interfaces.Newable), named: string) => (proto: any, key: string) => void; - - export function makePropertyInjectTaggedDecorator(kernel: interfaces.Kernel): - (serviceIdentifier: (string|Symbol|interfaces.Newable), key: string, value: any) => (proto: any, propertyName: string) => void; - - export function makePropertyMultiInjectDecorator(kernel: interfaces.Kernel): - (serviceIdentifier: (string|Symbol|interfaces.Newable)) => (proto: any, key: string) => void; - // constraint helpers export var traverseAncerstors: (request: interfaces.Request, constraint: (request: interfaces.Request) => boolean) => boolean; export var taggedConstraint: (tag: string) => (value: any) => (request: interfaces.Request) => boolean; export var namedConstraint: (value: any) => (request: interfaces.Request) => boolean; export var typeConstraint: (type: (Function|string)) => (request: interfaces.Request) => boolean; - } declare module "inversify" { diff --git a/ionic/ionic-tests.ts b/ionic/ionic-tests.ts index d8c98ae25f..140d102a8c 100644 --- a/ionic/ionic-tests.ts +++ b/ionic/ionic-tests.ts @@ -176,6 +176,7 @@ class IonicTestController { var currentStateName: string = this.$ionicHistory.currentStateName(); this.$ionicHistory.goBack(5); + this.$ionicHistory.removeBackView(); this.$ionicHistory.clearHistory(); this.$ionicHistory.clearCache().then(() => console.log("done clearing cache!")); this.$ionicHistory.nextViewOptions({ diff --git a/ionic/ionic.d.ts b/ionic/ionic.d.ts index fae9cdbf63..1df593037b 100644 --- a/ionic/ionic.d.ts +++ b/ionic/ionic.d.ts @@ -213,6 +213,7 @@ declare namespace ionic { currentStateName(): string; goBack(backCount?: number): void; + removeBackView(): void; clearHistory(): void; clearCache(): angular.IPromise; nextViewOptions(options: IonicHistoryNextViewOptions): void; diff --git a/ioredis/ioredis.d.ts b/ioredis/ioredis.d.ts index 42a498addc..60eccd0272 100644 --- a/ioredis/ioredis.d.ts +++ b/ioredis/ioredis.d.ts @@ -41,7 +41,8 @@ declare module IORedis { } interface Redis extends NodeJS.EventEmitter, Commander { - connect(callback: Function): Promise; + status: string; + connect(callback?: Function): Promise; disconnect(): void; duplicate(): Redis; monitor(calback: (error: Error, monitor: NodeJS.EventEmitter) => void): Promise; @@ -59,6 +60,7 @@ declare module IORedis { subscribe(channel: string): any; get(args: any[], callback?: ResCallbackT): any; get(...args: any[]): any; + getBuffer(key: string, callback?: ResCallbackT): any; set(args: any[], callback?: ResCallbackT): any; set(...args: any[]): any; setnx(args: any[], callback?: ResCallbackT): any; @@ -195,6 +197,8 @@ declare module IORedis { hmget(...args: any[]): any; hincrby(args: any[], callback?: ResCallbackT): any; hincrby(...args: any[]): any; + hincrbyfloat(args: any[], callback?: ResCallbackT): any; + hincrbyfloat(...args: any[]): any; hdel(args: any[], callback?: ResCallbackT): any; hdel(...args: any[]): any; hlen(args: any[], callback?: ResCallbackT): any; @@ -230,8 +234,12 @@ declare module IORedis { renamenx(...args: any[]): any; expire(args: any[], callback?: ResCallbackT): any; expire(...args: any[]): any; + pexpire(args: any[], callback?: ResCallbackT): any; + pexpire(...args: any[]): any; expireat(args: any[], callback?: ResCallbackT): any; expireat(...args: any[]): any; + pexpireat(args: any[], callback?: ResCallbackT): any; + pexpireat(...args: any[]): any; keys(args: any[], callback?: ResCallbackT): any; keys(...args: any[]): any; dbsize(args: any[], callback?: ResCallbackT): any; @@ -472,6 +480,8 @@ declare module IORedis { hmget(...args: any[]): Pipeline; hincrby(args: any[], callback?: ResCallbackT): Pipeline; hincrby(...args: any[]): Pipeline; + hincrbyfloat(args: any[], callback?: ResCallbackT): Pipeline; + hincrbyfloat(...args: any[]): Pipeline; hdel(args: any[], callback?: ResCallbackT): Pipeline; hdel(...args: any[]): Pipeline; hlen(args: any[], callback?: ResCallbackT): Pipeline; @@ -507,8 +517,12 @@ declare module IORedis { renamenx(...args: any[]): Pipeline; expire(args: any[], callback?: ResCallbackT): Pipeline; expire(...args: any[]): Pipeline; + pexpire(args: any[], callback?: ResCallbackT): Pipeline; + pexpire(...args: any[]): Pipeline; expireat(args: any[], callback?: ResCallbackT): Pipeline; expireat(...args: any[]): Pipeline; + pexpireat(args: any[], callback?: ResCallbackT): Pipeline; + pexpireat(...args: any[]): Pipeline; keys(args: any[], callback?: ResCallbackT): Pipeline; keys(...args: any[]): Pipeline; dbsize(args: any[], callback?: ResCallbackT): Pipeline; diff --git a/is-plain-object/is-plain-object-tests.ts b/is-plain-object/is-plain-object-tests.ts new file mode 100644 index 0000000000..eb57b12434 --- /dev/null +++ b/is-plain-object/is-plain-object-tests.ts @@ -0,0 +1,25 @@ +/// + +import * as isPlainObject from 'is-plain-object'; + +isPlainObject(Object.create({})); +//=> true +isPlainObject(Object.create(Object.prototype)); +//=> true +isPlainObject({foo: 'bar'}); +//=> true +isPlainObject({}); + +isPlainObject(1); +//=> false +isPlainObject(['foo', 'bar']); +//=> false +isPlainObject([]); +//=> false +class Foo {} +isPlainObject(new Foo); +//=> false +isPlainObject(null); +//=> false +isPlainObject(Object.create(null)); +//=> false \ No newline at end of file diff --git a/is-plain-object/is-plain-object.d.ts b/is-plain-object/is-plain-object.d.ts new file mode 100644 index 0000000000..47d277f186 --- /dev/null +++ b/is-plain-object/is-plain-object.d.ts @@ -0,0 +1,10 @@ +// Type definitions for is-plain-object +// Project: https://github.com/jonschlinkert/is-plain-object +// Definitions by: Kevin Zeng +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "is-plain-object" { + namespace isPlainObject {} + function isPlainObject(obj: any): boolean; + export = isPlainObject; +} \ No newline at end of file diff --git a/iscroll/iscroll-5-tests.ts b/iscroll/iscroll-5-tests.ts index 07255e8333..b04d91c029 100644 --- a/iscroll/iscroll-5-tests.ts +++ b/iscroll/iscroll-5-tests.ts @@ -33,4 +33,10 @@ myScroll1.scrollToElement(document.getElementById('selectedElement'), 250); myScroll2.on('scrollStart', function () { console.log('scroll started'); }); var myScroll9 = new IScroll(document.getElementById('wrapper')); -var myScroll10 = new IScroll(document.getElementById('wrapper'), { scrollbarClass: 'myScrollbar' }); \ No newline at end of file +var myScroll10 = new IScroll(document.getElementById('wrapper'), { scrollbarClass: 'myScrollbar' }); + +var myScroll11 = new IScroll(document.getElementById('wrapper'), { preventDefaultException: [ /^(INPUT|TEXTAREA|BUTTON|SELECT)$/ ] }); +var myScroll12 = new IScroll(document.getElementById('wrapper'), { preventDefaultException: { tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/ } }); + +var myScroll13 = new IScroll(document.getElementById('wrapper'), { bounceEasing: 'circular' }); +var myScroll14 = new IScroll(document.getElementById('wrapper'), { bounceEasing: { style: 'cubic-bezier(0,0,1,1)', fn: function (k) { return k; } } }); diff --git a/iscroll/iscroll-5.d.ts b/iscroll/iscroll-5.d.ts index 0b972e2863..31e9acaf6c 100644 --- a/iscroll/iscroll-5.d.ts +++ b/iscroll/iscroll-5.d.ts @@ -51,10 +51,10 @@ interface IScrollOptions { bounceTime?: number; ///String or function - bounceEasing?: any; + bounceEasing?: string|{ style: string, fn: (k: any) => any }; preventDefault?: boolean; - preventDefaultException?: boolean; + preventDefaultException?: Array|Object; HWCompositing?: boolean; diff --git a/isomorphic-fetch/isomorphic-fetch-tests.ts b/isomorphic-fetch/isomorphic-fetch-tests.ts index ddf11f84fe..fefabf2080 100644 --- a/isomorphic-fetch/isomorphic-fetch-tests.ts +++ b/isomorphic-fetch/isomorphic-fetch-tests.ts @@ -1,4 +1,5 @@ /// +/// import fetchImportedViaCommonJS = require('isomorphic-fetch'); import * as fetchImportedViaES6Module from 'isomorphic-fetch'; diff --git a/isomorphic-fetch/isomorphic-fetch.d.ts b/isomorphic-fetch/isomorphic-fetch.d.ts index 19754db0f1..41b63970b3 100644 --- a/isomorphic-fetch/isomorphic-fetch.d.ts +++ b/isomorphic-fetch/isomorphic-fetch.d.ts @@ -3,48 +3,53 @@ // Definitions by: Todd Lucas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare enum RequestContext { - "audio", "beacon", "cspreport", "download", "embed", "eventsource", - "favicon", "fetch", "font", "form", "frame", "hyperlink", "iframe", - "image", "imageset", "import", "internal", "location", "manifest", - "object", "ping", "plugin", "prefetch", "script", "serviceworker", - "sharedworker", "subresource", "style", "track", "video", "worker", - "xmlhttprequest", "xslt" -} -declare enum RequestMode { "same-origin", "no-cors", "cors" } -declare enum RequestCredentials { "omit", "same-origin", "include" } -declare enum RequestCache { - "default", "no-store", "reload", "no-cache", "force-cache", - "only-if-cached" -} -declare enum ResponseType { "basic", "cors", "default", "error", "opaque" } +type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | + "track" | "video"; +type RequestDestination = "" | "document" | "embed" | "font" | "image" | + "manifest" | "media" | "object" | "report" | "script" | "serviceworker" | + "sharedworker" | "style" | "worker" | "xslt"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestCache = + "default" | "no-store" | "reload" | "no-cache" | "force-cache" | + "only-if-cached"; +type RequestRedirect = "follow" | "error" | "manual"; -declare type HeaderInit = Headers | Array; -declare type BodyInit = ArrayBuffer | ArrayBufferView | Blob | FormData | string; -declare type RequestInfo = Request | string; +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | + "opaqueredirect"; -interface RequestInit { - method?: string; - headers?: HeaderInit | { [index: string]: string }; - body?: BodyInit; - mode?: string | RequestMode; - credentials?: string | RequestCredentials; - cache?: string | RequestCache; -} +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | + "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | + "strict-origin-when-cross-origin" | "unsafe-url"; interface IHeaders { - get(name: string): string; - getAll(name: string): Array; - has(name: string): boolean; -} - -declare class Headers implements IHeaders { append(name: string, value: string): void; - delete(name: string):void; + delete(name: string): void; get(name: string): string; getAll(name: string): Array; has(name: string): boolean; set(name: string, value: string): void; + + // TODO: iterable; + forEach(callback: (value: string, index: number, headers: IHeaders) => void, thisArg?: any): void; + // NOTE: The following are supported by whatwg-fetch but not node-fetch. + // entries(): IterableIterator<[string, string]>; + // keys(): IterableIterator; + // values(): IterableIterator; +} + +type HeadersInit = Headers | Array | { [index: string]: string }; + +declare class Headers implements IHeaders { + constructor(init?: HeadersInit); + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string; + getAll(name: string): Array; + has(name: string): boolean; + set(name: string, value: string): void; + + forEach(callback: (value: string, index: number, headers: IHeaders) => void, thisArg?: any): void; } interface IBody { @@ -70,49 +75,109 @@ declare class Body implements IBody { interface IRequest extends IBody { method: string; url: string; - headers: Headers; - context: string | RequestContext; - referrer: string; - mode: string | RequestMode; - credentials: string | RequestCredentials; - cache: string | RequestCache; + headers: IHeaders; + + type: RequestType; + destination: RequestDestination; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + mode: RequestMode; + credentials: RequestCredentials; + cache: RequestCache; + redirect?: RequestRedirect; + integrity?: string; + + clone(): IRequest; } +type BodyInit = Blob | ArrayBufferView | ArrayBuffer | FormData /* | URLSearchParams */ | string; + +interface RequestInit { + method?: string; + headers?: HeadersInit; + body?: BodyInit; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + mode?: RequestMode; + credentials?: RequestCredentials; + cache?: RequestCache; + redirect?: RequestRedirect; + integrity?: string; + window?: any; // can only be set to null +} + +type RequestInfo = IRequest | string; + declare class Request extends Body implements IRequest { - constructor(input: string | Request, init?: RequestInit); + constructor(input: RequestInfo, init?: RequestInit); + method: string; url: string; - headers: Headers; - context: string | RequestContext; + headers: IHeaders; + + type: RequestType + destination: RequestDestination; referrer: string; - mode: string | RequestMode; - credentials: string | RequestCredentials; - cache: string | RequestCache; + referrerPolicy: ReferrerPolicy; + mode: RequestMode; + credentials: RequestCredentials; + cache: RequestCache; + redirect: RequestRedirect; + integrity: string; + + clone(): IRequest; } interface IResponse extends IBody { + type: ResponseType; + url: string; + redirected: boolean; status: number; statusText: string; ok: boolean; headers: IHeaders; - type: string | ResponseType; - size: number; - timeout: number; - redirect(url: string, status: number): IResponse; - error(): IResponse; + // size: number; + // timeout: number; + body: any; + trailer: Promise; + clone(): IResponse; } -interface IFetchStatic { - Promise: any; - Headers: IHeaders - Request: IRequest; - Response: IResponse; - (url: string | IRequest, init?: RequestInit): Promise; +type ResponseBodyInit = BodyInit; + +interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; } -declare var fetch: IFetchStatic; +declare class Response extends Body implements IResponse { + constructor(body?: ResponseBodyInit, init?: ResponseInit); + + static redirect(url: string, status?: number): IResponse; + static error(): IResponse; + + type: ResponseType + + url: string; + redirected: boolean; + status: number; + statusText: string; + ok: boolean; + headers: IHeaders; + body: any; + trailer: Promise; + + clone(): IResponse; +} + +interface Window { + fetch(url: RequestInfo, init?: RequestInit): Promise; +} + +declare var fetch: typeof window.fetch; declare module "isomorphic-fetch" { export = fetch; diff --git a/jake/jake.d.ts b/jake/jake.d.ts index 3174a7b94c..5766b64093 100644 --- a/jake/jake.d.ts +++ b/jake/jake.d.ts @@ -207,7 +207,7 @@ declare namespace jake{ * * @event complete */ - export class Task implements NodeJS.EventEmitter { + export class Task extends NodeJS.EventEmitter { /** * @name name The name of the Task * @param prereqs Prerequisites to be run before this task diff --git a/jasmine-ajax/jasmine-ajax.d.ts b/jasmine-ajax/jasmine-ajax.d.ts index 143b3b1a5c..0eb873e048 100644 --- a/jasmine-ajax/jasmine-ajax.d.ts +++ b/jasmine-ajax/jasmine-ajax.d.ts @@ -73,6 +73,9 @@ declare class MockAjax { stubRequest(url: RegExp, data?: string, method?: string): JasmineAjaxRequestStub; stubRequest(url: string, data?: string, method?: string): JasmineAjaxRequestStub; + + stubRequest(url: RegExp, data?: RegExp, method?: string): JasmineAjaxRequestStub; + stubRequest(url: string, data?: RegExp, method?: string): JasmineAjaxRequestStub; requests: JasmineAjaxRequestTracker; stubs: JasmineAjaxStubTracker; diff --git a/jasmine-node/jasmine-node.d.ts b/jasmine-node/jasmine-node.d.ts index f547f844f6..f535d8c3e3 100644 --- a/jasmine-node/jasmine-node.d.ts +++ b/jasmine-node/jasmine-node.d.ts @@ -7,6 +7,12 @@ declare function it(expectation:string, assertion:(done:(err?:any) => void) => void, timeout?:number):void; +declare namespace jasmine { + interface Env { + defaultTimeoutInterval: number; + } +} + declare module "jasmine-node" { interface ExecuteSpecsOptions { specFolders: string[], diff --git a/java/java-tests.ts b/java/java-tests.ts index 568bd35a8c..7f5ff7874a 100644 --- a/java/java-tests.ts +++ b/java/java-tests.ts @@ -1,5 +1,5 @@ /// -/// +/// import java = require('java'); import BluePromise = require('bluebird'); diff --git a/jest/jest-tests.ts b/jest/jest-tests.ts index f3e33c4061..b547bd40ad 100644 --- a/jest/jest-tests.ts +++ b/jest/jest-tests.ts @@ -1,4 +1,5 @@ /// +/// // Tests based on the Jest website jest.unmock('../sum'); @@ -37,8 +38,6 @@ describe('fetchCurrentUser', function() { // unmock is the recommended approach for unmocking... jest.unmock('../displayUser.js') -// ...but dontMock also still works. -jest.dontMock('jquery'); describe('displayUser', function() { it('displays a user after a click', function() { @@ -100,6 +99,157 @@ describe('CheckboxWithLabel', function() { }); }); +jest.runAllTicks(); +xdescribe('Hooks and Suits', function () { + let tested: boolean; + + beforeEach(function () { + tested = false; + }); + + afterEach(function () { + tested = true; + }); + + test('tested', function () { + expect(tested).toBeTruthy(); + expect(tested).not.toBeFalsy(); + }); + + fit('tested', function () { + expect(tested).toBeDefined(); + expect(tested).not.toBeUndefined(); + }); + + xit('expect null to be null', function () { + expect(null).toBeNull(); + }); +}); + +describe('compartion', function () { + var sum: (a: number, b: number) => number = require.requireMock('../sum'); + + it('compares is 7 + 2 greater than 3', function () { + expect(sum(7, 2)).toBeGreaterThan(3); + }); + + it('compares is 2 + 7 greater than or equal to 3', function () { + expect(sum(2, 7)).toBeGreaterThanOrEqual(3); + }); + + it('compares is 3 less than 3 + 4', function () { + expect(3).toBeLessThan(sum(3, 4)); + }); + + it('compares is 3 less than or equal to 4 + 3', function () { + expect(3).toBeLessThanOrEqual(sum(4, 3)); + }); + + it('works sanely with simple decimals', function () { + expect(0.2 + 0.1).toBeCloseTo(0.3, 5); + }); +}); + +describe('toThrow API', function () { + function throwTypeError(): void { + throw new TypeError('toThrow Definition was out of date'); + } + + it('throws', function () { + expect(throwTypeError()).toThrow(); + }); + + it('throws TypeError', function () { + expect(throwTypeError()).toThrowError(TypeError); + }); + + it('throws \'Definition was out of date\'', function () { + expect(throwTypeError()).toThrowError(/Definition was out of date/); + }); + + it('throws \'toThorow Definition was out of date\'', function () { + expect(throwTypeError()).toThrowError('toThrow Definition was out of date'); + }); +}); + +describe('missing tests', function () { + it('creates closures', function () { + class Closure { + private arg: T; + + public constructor(private fn: (arg: T) => void) { + this.fn = fn; + } + + public bind(arg: T): void { + this.arg = arg; + } + + public call(): void { + this.fn(this.arg); + } + } + + type StringClosure = (arg: string) => void; + let spy: jest.Mock = jest.fn(); + let closure: Closure = new Closure(spy); + closure.bind('jest'); + closure.call(); + expect(spy).lastCalledWith('jest'); + expect(spy).toBeCalledWith('jest'); + expect(jest.isMockFunction(spy)).toBeTruthy(); + }); + + it('tests all mising Mocks functionality', function () { + type FruitsGetter = () => Array; + let mock: jest.Mock = jest.fn(); + mock.mockImplementationOnce(() => ['Orange', 'Apple', 'Plum']) + jest.setMock('./../tesks/getFruits', mock); + const getFruits: FruitsGetter = require('./../tesks/getFruits'); + expect(getFruits()).toContain('Orange'); + mock.mockReturnValueOnce(['Apple', 'Plum']); + expect(mock()).not.toContain('Orange'); + mock.mockReturnValue([]); //Deprecated: Use jest.fn(() => value) instead. + mock.mockClear(); + let thisMock: jest.Mock = jest.fn().mockReturnThis(); + expect(thisMock()).toBe(this); + }); + + it('creates snapshoter', function () { + jest.disableAutomock(); + jest.mock('./render', () => jest.fn((): string => "{Link to: \"facebook\"}"), { virtual: true }); + const render: () => string = require('./render'); + expect(render()).toMatch(/Link/); + jest.enableAutomock(); + }); + + it('runs only pending timers', function () { + jest.useRealTimers(); + setTimeout(() => expect(1).not.toEqual(0), 3000); + jest.runOnlyPendingTimers(); + }); + + it('runs all timers', function () { + jest.clearAllTimers(); + jest.useFakeTimers(); + setTimeout(() => expect(0).not.toEqual(1), 3000); + jest.runAllTimers(); + }); + + it('cleares cache', function () { + const sum1 = require('../sum'); + jest.resetModules(); + const sum2 = require('../sum'); + expect(sum1).not.toBe(sum2); + }) +}); + +describe('toMatchSnapshot', function () { + it('compares snapshots', function () { + expect({ type: 'a', props: { href: 'https://www.facebook.com/' }, children: [ 'Facebook' ] }).toMatchSnapshot(); + }); +}); + function testInstances() { var mockFn = jest.fn(); var a = new mockFn(); @@ -123,3 +273,82 @@ function testMockImplementation() { mockFn.mock.calls[0][0] === 0; // true mockFn.mock.calls[1][0] === 1; // true } + +// Test from jest Docs: +describe('genMockFromModule', function () { + // Interfaces: + interface MockFiles { + [index: string]: string; + } + + interface MockedFS { + readdirSync: (dir: string) => string[]; + __setMockFiles: (newMockFiles: MockFiles) => void ; + } + + // ------------------------------------------------------------------------------------ + // FileSummarizer.ts + + const fs = require('fs'); + + function summarizeFilesInDirectorySync(directory: string): string[] { + return fs.readdirSync(directory).map((fileName: string) => ({ + fileName, + directory, + })); + } + + //export default summarizeFilesInDirectorySync; // For sake of compilation + + // ------------------------------------------------------------------------------------ + // __mocks__/fs.js + + const path = require('path'); + + const mockedFS: MockedFS = jest.genMockFromModule('fs'); + + let mockFiles: any = Object.create(null); + function __setMockFiles(newMockFiles: MockFiles): void { + mockFiles = Object.create(null); + for(const file in newMockFiles) { + const dir: string = path.dirname(file); + + if (!mockFiles[dir]) { + mockFiles[dir] = []; + } + mockFiles[dir].push(path.basename(file)); + } + } + + function readdirSync(directoryPath: string): string[] { + return mockFiles[directoryPath] || []; + } + + mockedFS.readdirSync = readdirSync; + mockedFS.__setMockFiles = __setMockFiles; + + //export = mockedFS; // For sake of compilation + // ------------------------------------------------------------------------------------ + // __tests__/FileSummarizer-test.js + + jest.mock('fs'); + + describe('listFilesInDirectorySync', () => { + const MOCK_FILE_INFO: MockFiles = { + '/path/to/file1.js': 'console.log("file1 contents");', + '/path/to/file2.txt': 'file2 contents', + }; + + beforeEach(() => { + // Set up some mocked out file info before each test + (require('fs') as MockedFS).__setMockFiles(MOCK_FILE_INFO); + }); + + it('includes all files in the directory in the summary', () => { + const FileSummarizer: (dir: string) => string[] = require('../FileSummarizer'); + const fileSummary = FileSummarizer('/path/to'); + + expect(fileSummary.length).toBe(2); + }); + }); +}); diff --git a/jest/jest.d.ts b/jest/jest.d.ts index 451b9abc88..d0660193f6 100644 --- a/jest/jest.d.ts +++ b/jest/jest.d.ts @@ -1,77 +1,150 @@ -// Type definitions for Jest 0.9.0 +// Type definitions for Jest 15.1.1 // Project: http://facebook.github.io/jest/ -// Definitions by: Asana +// Definitions by: Asana , Ivo Stratev , jwbay // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - -declare function afterEach(fn: jest.EmptyFunction): void; -declare function beforeEach(fn: jest.EmptyFunction): void; -declare function describe(name: string, fn: jest.EmptyFunction): void; +declare var beforeAll: jest.Lifecycle; +declare var beforeEach: jest.Lifecycle; +declare var afterAll: jest.Lifecycle; +declare var afterEach: jest.Lifecycle; +declare var describe: jest.Describe; +declare var fdescribe: jest.Describe; +declare var xdescribe: jest.Describe; declare var it: jest.It; -declare function pit(name: string, fn: jest.EmptyFunction): void; - -declare function xdescribe(name: string, fn: jest.EmptyFunction): void; -declare function xit(name: string, fn: jest.EmptyFunction): void; +declare var fit: jest.It; +declare var xit: jest.It; +declare var test: jest.It; +declare var xtest: jest.It; declare function expect(actual: any): jest.Matchers; interface NodeRequire { + /** Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. */ requireActual(moduleName: string): any; + /** Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not. */ + requireMock(moduleName: string): any; } declare namespace jest { - function addMatchers(matchers: CustomMatcherFactories): void; + function addMatchers(matchers: jasmine.CustomMatcherFactories): void; + /** Disables automatic mocking in the module loader. */ function autoMockOff(): void; + /** Enables automatic mocking in the module loader. */ function autoMockOn(): void; + /** Removes any pending timers from the timer system. If any timers have been scheduled, they will be cleared and will never have the opportunity to execute in the future. */ function clearAllTimers(): void; - function currentTestPath(): string; - function fn(implementation?: Function): Mock; + /** Indicates that the module system should never return a mocked version of the specified module, including all of the specificied module's dependencies. */ + function deepUnmock(moduleName: string): void; + /** Disables automatic mocking in the module loader. */ + function disableAutomock(): void; + /** Mocks a module with an auto-mocked version when it is being required. */ + function doMock(moduleName: string): void; + /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */ function dontMock(moduleName: string): void; - function genMockFromModule(moduleName: string): Mock; - function mock(moduleName: string, factory?: Function): void; + /** Enables automatic mocking in the module loader. */ + function enableAutomock(): void; + /** Creates a mock function. Optionally takes a mock implementation. */ + function fn(implementation?: Function): Mock; + /** Use the automatic mocking system to generate a mocked version of the given module. */ + function genMockFromModule(moduleName: string): T; + /** Returns whether the given function is a mock function. */ + function isMockFunction(fn: any): fn is Mock; + /** Mocks a module with an auto-mocked version when it is being required. */ + function mock(moduleName: string, factory?: any, options?: MockOptions): void; + /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */ + function resetModuleRegistry(): void; + /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */ + function resetModules(): void; + /** Exhausts tasks queued by setImmediate(). */ + function runAllImmediates(): void; + /** Exhausts the micro-task queue (usually interfaced in node via process.nextTick). */ function runAllTicks(): void; + /** Exhausts the macro-task queue (i.e., all tasks queued by setTimeout() and setInterval()). */ function runAllTimers(): void; + /** Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by setTimeout() or setInterval() up to this point). + * If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call. */ function runOnlyPendingTimers(): void; + /** Explicitly supplies the mock object that the module system should return for the specified module. */ function setMock(moduleName: string, moduleExports: T): void; + /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */ function unmock(moduleName: string): void; + /** Instructs Jest to use fake versions of the standard timer functions. */ + function useFakeTimers(): void; + /** Instructs Jest to use the real versions of the standard timer functions. */ + function useRealTimers(): void; + + interface MockOptions { + virtual?: boolean; + } interface EmptyFunction { (): void; } - interface Matchers { - not: Matchers; - toThrow(expected?: any): boolean; - toBe(expected: any): boolean; - toEqual(expected: any): boolean; - toBeFalsy(): boolean; - toBeTruthy(): boolean; - toBeNull(): boolean; - toBeDefined(): boolean; - toBeUndefined(): boolean; - toMatch(expected: RegExp): boolean; - toContain(expected: string): boolean; - toBeCloseTo(expected: number, delta: number): boolean; - toBeGreaterThan(expected: number): boolean; - toBeLessThan(expected: number): boolean; - toBeCalled(): boolean; - toBeCalledWith(...args: any[]): boolean; - lastCalledWith(...args: any[]): boolean; + interface DoneCallback { + (...args: any[]): any + fail(error?: string | { message: string }): any; + } + + interface ProvidesCallback { + (cb?: DoneCallback): any; + } + + interface Lifecycle { + (fn: ProvidesCallback): any; } interface It { - (name: string, fn: EmptyFunction): void; - only(name: string, fn: EmptyFunction): void; + (name: string, fn: ProvidesCallback): void; + only: It; + skip: It; } - interface Mock { + interface Describe { + (name: string, fn: EmptyFunction): void + only: Describe; + skip: Describe; + } + + interface Matchers { + not: Matchers; + lastCalledWith(...args: any[]): void; + toBe(expected: any): void; + toBeCalled(): void; + toBeCalledWith(...args: any[]): void; + toBeCloseTo(expected: number, delta: number): void; + toBeDefined(): void; + toBeFalsy(): void; + toBeGreaterThan(expected: number): void; + toBeGreaterThanOrEqual(expected: number): void; + toBeInstanceOf(expected: any): void + toBeLessThan(expected: number): void; + toBeLessThanOrEqual(expected: number): void; + toBeNull(): void; + toBeTruthy(): void; + toBeUndefined(): void; + toContain(expected: any): void; + toEqual(expected: any): void; + toHaveBeenCalled(): boolean; + toHaveBeenCalledTimes(expected: number): boolean; + toHaveBeenCalledWith(...params: any[]): boolean; + toMatch(expected: string | RegExp): void; + toMatchSnapshot(): void; + toThrow(): void; + toThrowError(error?: string | Constructable | RegExp): void; + } + + interface Constructable { + new (...args: any[]): any + } + + interface Mock extends Function { new (): T; - (...args: any[]): any; // TODO please fix this line! added for TypeScript 1.1.0-1 https://github.com/DefinitelyTyped/DefinitelyTyped/pull/2932 + (...args: any[]): any; mock: MockContext; mockClear(): void; mockImplementation(fn: Function): Mock; - mockImpl(fn: Function): Mock; + mockImplementationOnce(fn: Function): Mock; mockReturnThis(): Mock; mockReturnValue(value: any): Mock; mockReturnValueOnce(value: any): Mock; @@ -81,42 +154,138 @@ declare namespace jest { calls: any[][]; instances: T[]; } +} + +//Jest ships with a copy of Jasmine. They monkey-patch its APIs and divergence/deprecation are expected. +//Relevant parts of Jasmine's API are below so they can be changed and removed over time. +//This file can't reference jasmine.d.ts since the globals aren't compatible. + +declare function spyOn(object: any, method: string): jasmine.Spy; +/** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */ +declare function pending(reason?: string): void; +/** Fails a test when called within one. */ +declare function fail(error?: any): void; +declare namespace jasmine { + var clock: () => Clock; + function any(aclass: any): Any; + function anything(): Any; + function arrayContaining(sample: any[]): ArrayContaining; + function objectContaining(sample: any): ObjectContaining; + function createSpy(name: string, originalFn?: Function): Spy; + function createSpyObj(baseName: string, methodNames: any[]): any; + function createSpyObj(baseName: string, methodNames: any[]): T; + function pp(value: any): string; + function addCustomEqualityTester(equalityTester: CustomEqualityTester): void; + function addMatchers(matchers: CustomMatcherFactories): void; + function stringMatching(value: string | RegExp): Any; + + interface Clock { + install(): void; + uninstall(): void; + /** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */ + tick(ms: number): void; + mockDate(date?: Date): void; + } + + interface Any { + new (expectedClass: any): any; + jasmineMatches(other: any): boolean; + jasmineToString(): string; + } + + interface ArrayContaining { + new (sample: any[]): any; + asymmetricMatch(other: any): boolean; + jasmineToString(): string; + } + + interface ObjectContaining { + new (sample: any): any; + jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean; + jasmineToString(): string; + } + + interface Spy { + (...params: any[]): any; + identity: string; + and: SpyAnd; + calls: Calls; + mostRecentCall: { args: any[]; }; + argsForCall: any[]; + wasCalled: boolean; + } + + interface SpyAnd { + /** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */ + callThrough(): Spy; + /** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */ + returnValue(val: any): Spy; + /** By chaining the spy with and.returnValues, all calls to the function will return specific values in order until it reaches the end of the return values list. */ + returnValues(...values: any[]): Spy; + /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */ + callFake(fn: Function): Spy; + /** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */ + throwError(msg: string): Spy; + /** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */ + stub(): Spy; + } + + interface Calls { + /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. */ + any(): boolean; + /** By chaining the spy with calls.count(), will return the number of times the spy was called */ + count(): number; + /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index */ + argsFor(index: number): any[]; + /** By chaining the spy with calls.allArgs(), will return the arguments to all calls */ + allArgs(): any[]; + /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls */ + all(): CallInfo[]; + /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call */ + mostRecent(): CallInfo; + /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call */ + first(): CallInfo; + /** By chaining the spy with calls.reset(), will clears all tracking for a spy */ + reset(): void; + } + + interface CallInfo { + /** The context (the this) for the call */ + object: any; + /** All arguments passed to the call */ + args: any[]; + /** The return value of the call */ + returnValue: any; + } - // taken from Jasmine since addMatchers calls into the jasmine api interface CustomMatcherFactories { [index: string]: CustomMatcherFactory; } - // taken from Jasmine since addMatchers calls into the jasmine api interface CustomMatcherFactory { (util: MatchersUtil, customEqualityTesters: Array): CustomMatcher; } - // taken from Jasmine since addMatchers calls into the jasmine api interface MatchersUtil { equals(a: any, b: any, customTesters?: Array): boolean; contains(haystack: ArrayLike | string, needle: any, customTesters?: Array): boolean; buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array): string; } - // taken from Jasmine since addMatchers calls into the jasmine api interface CustomEqualityTester { (first: any, second: any): boolean; } - // taken from Jasmine since addMatchers calls into the jasmine api interface CustomMatcher { compare(actual: T, expected: T): CustomMatcherResult; compare(actual: any, expected: any): CustomMatcherResult; } - // taken from Jasmine since addMatchers calls into the jasmine api interface CustomMatcherResult { pass: boolean; - message: string; + message: string | (() => string); } - // taken from Jasmine which takes from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains() interface ArrayLike { length: number; [n: number]: T; diff --git a/joi/joi-tests.ts b/joi/joi-tests.ts index 37848203df..c75309b45e 100644 --- a/joi/joi-tests.ts +++ b/joi/joi-tests.ts @@ -752,6 +752,10 @@ schema = Joi.alternatives(schema, anySchema, boolSchema); // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- +schema = Joi.lazy(() => schema) + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + Joi.validate(value, obj); Joi.validate(value, schema); Joi.validate(value, schema, validOpts); diff --git a/joi/joi.d.ts b/joi/joi.d.ts index 3ba51d7383..b827903f9b 100644 --- a/joi/joi.d.ts +++ b/joi/joi.d.ts @@ -816,6 +816,13 @@ declare module 'joi' { export function alternatives(): AlternativesSchema; export function alternatives(types: Schema[]): AlternativesSchema; export function alternatives(type1: Schema, type2: Schema, ...types: Schema[]): AlternativesSchema; + + /** + * Generates a placeholder schema for a schema that you would provide with the fn. + * Supports the same methods of the any() type. + * This is mostly useful for recursive schemas + */ + export function lazy(cb: () => Schema): Schema; /** * Validates a value using the given schema and options. diff --git a/jqgrid/jqgrid-tests.ts b/jqgrid/jqgrid-tests.ts index 6f112d2976..b9012185bc 100644 --- a/jqgrid/jqgrid-tests.ts +++ b/jqgrid/jqgrid-tests.ts @@ -2,5 +2,25 @@ // Definitions by: Lokesh Peta // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// \ No newline at end of file +/// +/// + +var mydata: any[] = []; + +$('#jqGrid') + .jqGrid({ + datatype: 'local', + data: mydata, + loadonce: true, + gridview: true, + height: 400, + shrinkToFit: true, + width: null, + colModel: [ + { label: 'Name', name: 'id', width: 75, key: true, align: 'left' }, + { label: 'Description', name: 'description', width: 100 } + ], + viewrecords: true, // show the current page, data rang and total records on the toolbar + caption: 'Matches', + onSelectRow(id: any, status: any, e: Event) { } + }); diff --git a/jqgrid/jqgrid.d.ts b/jqgrid/jqgrid.d.ts index 82807282a0..6b7d4cb2e0 100644 --- a/jqgrid/jqgrid.d.ts +++ b/jqgrid/jqgrid.d.ts @@ -4,44 +4,337 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// + +// http://www.trirand.com/jqgridwiki/doku.php?id=wiki:colmodel_options interface JQueryJqGridColumn { - name: string; - index: string; + + /** + * Defines the alignment of the cell in the Body layer, not in header cell. Possible values: left, center, right + */ + align?: "left" | "center" | "right"; + + /** + * This function add attributes to the cell during the creation of the data - i.e dynamically. + * By example all valid attributes for the table cell can be used or a style attribute with different properties. + * @param rowId the id of the row + * @param val the value which will be added in the cell + * @param rowObject the raw object of the data row - i.e if datatype is json - array, if datatype is xml xml node. + * @param cm all the properties of this column listed in the colModel + * @param rdata the data row which will be inserted in the row. This parameter is array of type name:value, where name is the name in colModel + * @returns {} + */ + cellattr?: (rowId: any, val: any, rowObject: any, cm: any, rdata: any) => string; + + /** + * This option allow to add classes to the column. If more than one class will be used a space should be set. + * By example classes:'class1 class2' will set a class1 and class2 to every cell on that column. + * In the grid css there is a predefined class ui-ellipsis which allow to attach ellipsis to a particular row. + * Also this will work in FireFox too. + */ + classes?: string; + + /** + * Governs format of sorttype:date (when datetype is set to local) and editrules {date:true} fields. + * Determines the expected date format for that column. Uses a PHP-like date formatting. Currently "/", "-", and "." are supported as date separators. Valid formats are: + * y,Y,yyyy for four digits year + * YY, yy for two digits year + * m,mm for months + * d,dd for days. + */ + datefmt?: string; + + /** + * Defines if the field is editable. This option is used in cell, inline and form modules. + */ + editable?: boolean; + + /** + * The predefined types (string) or custom function name that controls the format of this field + * @param cellvalue is the value to be formatted + * @param options is an object containing the following element: rowId - is the id of the row colModel is the object of the properties for this column getted from colModel array of jqGrid + * @param rowObject is a row data represented in the format determined from datatype option. If we have datatype: xml/xmlstring - the rowObject is xml node,provided according to the rules from xmlReader If we have datatype: json/jsonstring - the rowObject is array, provided according to the rules from jsonReader + * @returns {} the formatted value + */ + formatter?: "integer" | "number" | "currency" | "date" | "email" | "link" | "showlink" | "checkbox" | "select" | "actions" | ((cellvalue: any, options: { rowId: any, colModel: any }, rowObject: any) => any); + + /** + * Defines if this column is hidden at initialization. + */ hidden?: boolean; - sortable?: boolean; + + /** + * Set the index name when sorting. Passed as sidx parameter. + */ + index?: string; + + /** + * Overwrite the id (defined in readers) from server. Can be set as id for the unique row id. Only one column can have this property. + * This option have higher priority as those from the readers. + * If there are more than one key set the grid finds the first one and the second is ignored. + */ + key?: boolean; + + /** + * When colNames array is empty, defines the heading for this column. + * If both the colNames array and this setting are empty, the heading for this column comes from the name property. + */ + label?: string; + + /** + * Set the unique name in the grid for the column. + * This property is required. + * As well as other words used as property/event names, the reserved words (which cannot be used for names) include subgrid, cb and rn. + */ + name: string; + + /** + * When used in search modules, disables or enables searching on that column + */ search?: boolean; + + /** + * Defines is this can be sorted + */ + sortable?: boolean; + + /** + * Set the initial width of the column, in pixels. This value currently can not be set as percentage + */ width?: number; - formatter?: (cellvalue: any, options: any, rowObject: any) => any; } interface IJqGridJsonReader { + /** + * tells jqGrid that the information for the data in the row is repeatable - i.e. the elements have the same tag cell described in cell element. Setting this option to false instructs jqGrid to search elements in the json data by name. + * This is the name from colModel or the name described with the jsonmap option in colModel + */ repeatitems: boolean; - root(obj: any): any; - page(obj: any): any; - total(obj: any): number; - records(obj: {data: any[]}): number; + + /** + * Name of the root property + * @param obj + * @returns {} + */ + root: string | ((obj: any) => any); + + /** + * current page of the query + * @param obj + * @returns {} + */ + page: string | ((obj: any) => number); + + /** + * total pages for the query + * @param obj + * @returns {} + */ + total: string | ((obj: any) => number); + + /** + * total number of records for the query + * @param obj + * @returns {} + */ + records: string | ((obj: {data: any[]}) => number); } interface JQueryJqGridOptions { - datatype?: string; - mtype?: string; + /** + * When set to true encodes (html encode) the incoming (from server) and posted data (from editing modules). + */ autoencode?: boolean; - pager?: string; - rowNum?: number; - rowList?: number[]; - colNames?: string[]; + + /** + * When set to true, the grid width is recalculated automatically to the width of the parent element. + * This is done only initially when the grid is created. + * In order to resize the grid when the parent element changes width you should apply custom code and use the setGridWidth method for this purpose + */ + autoWidth?: boolean; + + /** + * Defines the caption for the grid. This caption appears in the caption layer, which is above the header layer + */ + caption?: string; + + /** + * Array which describes the parameters of the columns. This is the most important part of the grid. + */ colModel?: JQueryJqGridColumn[]; - sortname?: string; - sortorder?: string; - multiselect?: boolean; - multiboxonly?: boolean; + + /** + * An array in which we place the names of the columns. + * This is the text that appears in the head of the grid (header layer). The names are separated with commas. + * Note that the number of elements in this array should be equal of the number elements in the colModel array. + */ + colNames?: string[]; + + /** + * An array that stores the local data passed to the grid. You can directly point to this variable in case you want to load an array data. + * It can replace the addRowData method which is slow on relative big data + */ + data?: any[]; + + /** + * Defines in what format to expect the data that fills the grid. + * Valid options are xml (we expect data in xml format), xmlstring (we expect xml data as string), json (we expect data in JSON format), + * jsonstring (we expect JSON data as a string), local (we expect data defined at client side (array data)), + * javascript (we expect javascript as data), function (custom defined function for retrieving data), + * or clientSide to manually load data via the data array + */ + datatype?: "xml" | "xmlstring" | "json" | "jsonstring" | "local" | "javascript" | Function | "clientSide"; + + /** + * If set to true, and a column's width is changed, the adjacent column (to the right) will resize so that the overall grid width is maintained + * (e.g., reducing the width of column 2 by 30px will increase the size of column 3 by 30px). In this case there is no horizontal scrollbar. + * Note: This option is not compatible with shrinkToFit option - i.e if shrinkToFit is set to false, forceFit is ignored. + */ forceFit?: boolean; - height?: number; - width?: number; - shrinkToFit?: boolean; - url?: string; + /** + * What will be the result if we insert all the data at once? + * Yes, this can be done with a help of gridview option (set it to true). + * The result is a grid that is 5 to 10 times faster. Of course, when this option is set to true we have some limitations. + * If set to true we can not use treeGrid, subGrid, or the afterInsertRow event. + * If you do not use these three options in the grid you can set this option to true and enjoy the speed. + */ + gridview?: boolean; + + /** + * The height of the grid. + * Can be set as number (in this case we mean pixels) or as percentage (only 100% is accepted) or value of auto is acceptable. + */ + height?: number | string | "auto"; + + /** + * If this flag is set to true, the grid loads the data from the server only once (using the appropriate datatype). + * After the first request, the datatype parameter is automatically changed to local and all further manipulations are done on the client side. + * The functions of the pager (if present) are disabled. + */ + loadonce?: boolean; + + /** + * An array which describes the structure of the expected json data. + */ jsonReader?: IJqGridJsonReader; - gridComplete?:()=>void; + + /** + * Defines the type of request to make ("POST" or "GET") + */ + mtype?: "GET" | "POST"; + + /** + * This option works only when the multiselect option is set to true. + * When multiselect is set to true, clicking anywhere on a row selects that row; + * when multiboxonly is also set to true, the multiselection is done only when the checkbox is clicked (Yahoo style). + * Clicking in any other row (suppose the checkbox is not clicked) deselects all rows and selects the current row. + */ + multiboxonly?: boolean; + + /** + * If this flag is set to true a multi selection of rows is enabled. A new column at left side containing checkboxes is added. + * Can be used with any datatype option + */ + multiselect?: boolean; + + /** + * Defines that we want to use a pager bar to navigate through the records. + * This must be a valid HTML element; in our example we gave the div the id of "pager", but any name is acceptable. + * Note that the navigation layer (the "pager" div) can be positioned anywhere you want, determined by your HTML; + * in our example we specified that the pager will appear after the body layer. + * The valid settings can be (in the context of our example) pager, #pager, jQuery('#pager'). + * I recommend to use the second one - #pager + */ + pager?: string; + + /** + * An array to construct a select box element in the pager in which we can change the number of the visible rows. + * When changed during the execution, this parameter replaces the rowNum parameter that is passed to the url. + * If the array is empty, this element does not appear in the pager. Typically you can set this like [10,20,30]. + * If the rowNum parameter is set to 30 then the selected value in the select box is 30 + */ + rowList?: number[]; + + /** + * Sets how many records we want to view in the grid. This parameter is passed to the url for use by the server routine retrieving the data. + * Note that if you set this parameter to 10 (i.e. retrieve 10 records) and your server return 15 then only 10 records will be loaded + */ + rowNum?: number; + + /** + * This option, if set, defines how the the width of the columns of the grid should be re-calculated, taking into consideration the width of the grid. + * If this value is true, and the width of the columns is also set, then every column is scaled in proportion to its width. + * For example, if we define two columns with widths 80 and 120 pixels, but want the grid to have a width of 300 pixels, + * then the columns will stretch to fit the entire grid, and the extra width assigned to them will depend on the width of the columns themselves and the extra width available. + * The re-calculation is done as follows: the first column gets the width (300(new width)/200(sum of all widths))*80(first column width) = 120 pixels, + * and the second column gets the width (300(new width)/200(sum of all widths))*120(second column width) = 180 pixels. + * Now the widths of the columns sum up to 300 pixels, which is the width of the grid. + * If the value is false and the value in width option is set, then no re-sizing happens whatsoever. + * So in this example, if shrinkToFit is set to false, column one will have a width of 80 pixels, + * column two will have a width of 120 pixels and the grid will retain the width of 300 pixels. + * If the value of shrinkToFit is an integer, the width is calculated according to it. + */ + shrinkToFit?: boolean | number; + + /** + * The column according to which the data is to be sorted when it is initially loaded from the server + * (note that you will have to use datatypes xml or json to load remote data). This parameter is appended to the url. + * If this value is set and the index (name) matches the name from colModel, + * then an icon indicating that the grid is sorted according to this column is added to the column header. + * This icon also indicates the sorting order - descending or ascending (see the parameter sortorder). Also see prmNames + */ + sortname?: string; + + /** + * The initial sorting order (ascending or descending) when we fetch data from the server using datatypes xml or json. + * This parameter is appended to the url - see prnNames. The two allowed values are - asc or desc. + */ + sortorder?: "asc" | "desc"; + + /** + * The url of the file that returns the data needed to populate the grid. May be set to clientArray to manualy post data to server + */ + url?: string | "clientArray"; + + /** + * If true, jqGrid displays the beginning and ending record number in the grid, out of the total number of records in the query. + * This information is shown in the pager bar (bottom right by default)in this format: "View X to Y out of Z". + * If this value is true, there are other parameters that can be adjusted, including emptyrecords and recordtext. + */ + viewrecords?: boolean; + + /** + * If this option is not set, the width of the grid is the sum of the widths of the columns defined in the colModel (in pixels). + * If this option is set, the initial width of each column is set according to the value of the shrinkToFit option. + */ + width?: number; + + // events + + /** + * This fires after all the data is loaded into the grid and all other processes are complete. + * Also the event fires independent from the datatype parameter and after sorting paging and etc. + * @returns {} + */ + gridComplete?: () => void; + + /** + * Raised immediately after row was right clicked + * @param rowid is the id of the row + * @param iRow is the index of the row (do not mix this with the rowid) + * @param iCol is the index of the cell + * @param e is the event object + * @returns {} + */ + onRightClickRow?: (rowid: any, iRow: number, iCol: number, e: Event) => void; + + /** + * Raised immediately after row was clicked. + * @param id is the id of the row + * @param status is the status of the selection + * @param e is the event object. Can be used when multiselect is set to true. true if the row is selected, false if the row is deselected. + * @returns {} + */ + onSelectRow?: (id: string, status: any, e: Event) => void; } interface JQueryJqGridStatic { @@ -60,5 +353,64 @@ interface JQueryStatic { interface JQuery { jqGrid?: JQueryJqGridStatic; + /** + * Populates a grid with the passed data (an array) + * @param data + * @returns {} + */ + addJSONData(data: any[]): void; + + /** + * Edits the row specified by rowid. + * keys is a boolean value, indicating if to use the Enter key to accept the value ane Esc to cancel the edit, or not. + * @param rowid the id of the row to edit + * @param keys when set to true we can use [Enter] key to save the row and [Esc] to cancel editing + * @returns {} + */ + editRow(rowid: any, keys?: boolean): void; + + /** + * Returns the value of the requested parameter. name is the name from the options array. If the name is not set, the entry options are returned. + * @param name + * @returns {} + */ + getGridParam(name: string): any; + + /** + * This method restores the data to original values before the editing of the row + * @param rowId the row to restore + * @param afterRestoreFunc if defined this function is called in after the row is restored. + * @returns {} + */ + restoreRow(rowId: any, afterRestoreFunc?: (response: any) => void): void; + + /** + * Saves the edited row. + * @param rowid the id of the row to save + * @param successfunc + * @param url if defined, this parameter replaces the editurl parameter from the options array. If set to 'clientArray', the data is not posted to the server but rather is saved only to the grid (presumably for later manual saving). + * @param extraparam an array of type name: value. When set these values are posted along with the other values to the server. + * @returns {} + */ + saveRow(rowid: string, successfunc?: (response: any) => boolean, url?: string, extraparam?: any): void; + + /** + * Saves the edited row. + * @param rowid the id of the row to save + * @param successfunc + * @param url + * @param extraparam + * @returns {} + */ + saveRow(rowid: string, successfunc?: boolean, url?: string, extraparam?: any): void; + + /** + * Sets a particular parameter. + * Note - for some parameters to take effect a trigger("reloadGrid") should be executed. + * Note that with this method we can override events. + * The name (in the name:value pair) is the name from options array + * @param obj + * @returns {} + */ setGridParam(obj: any): void; } \ No newline at end of file diff --git a/jquery-mockjax/jquery-mockjax-tests.ts b/jquery-mockjax/jquery-mockjax-tests.ts index 6fae52eb07..36ebd7e64c 100644 --- a/jquery-mockjax/jquery-mockjax-tests.ts +++ b/jquery-mockjax/jquery-mockjax-tests.ts @@ -9,7 +9,7 @@ class Tests { run(): void { const self = this; - var t = QUnit.test; + let t = QUnit.test; QUnit.begin(() => { @@ -36,7 +36,7 @@ class Tests { responseText: 'Hello Word' }); - var xhr = $.ajax({ + let xhr = $.ajax({ url: '/xmlhttprequest', complete: () => { } }); @@ -67,7 +67,7 @@ class Tests { }); t('Intercept asynchronized proxy calls', (assert) => { - var done = assert.async(); + let done = assert.async(); $.mockjax({ url: '/proxy', proxy: 'test_proxy.json' @@ -85,7 +85,7 @@ class Tests { }); t('Intercept and proxy (sub-ajax request)', (assert) => { - var done = assert.async(); + let done = assert.async(); $.mockjax({ url: '/proxy', @@ -104,7 +104,7 @@ class Tests { }); t('Proxy type specification', (assert) => { - var done = assert.async(); + let done = assert.async(); $.mockjax({ url: '/proxy', @@ -124,7 +124,7 @@ class Tests { }); t('Support 1.5 $.ajax(url, settings) signature.', (assert) => { - var done = assert.async(); + let done = assert.async(); $.mockjax({ url: '/resource', @@ -141,9 +141,9 @@ class Tests { }); t('Dynamic response callback', (assert) => { - var done = assert.async(); + let done = assert.async(); - var settings: MockJaxSettings = { + let settings: MockJaxSettings = { url: '/response-callback', response: (settings) => { settings.responseText = settings.data.response + ' 2'; @@ -165,8 +165,36 @@ class Tests { } }); }); + + t('Asyncronous response callback', (assert) => { + let done = assert.async(); + + let settings: MockJaxSettings = { + url: '/async-response-callback', + response: (settings, completed) => { + setTimeout(() => { + settings.responseText = settings.data.response + ' 3'; + completed(); + }, 10); + } + }; + + $.mockjax(settings); + + $.ajax({ + url: '/async-response-callback', + dataType: 'text', + data: { + response: 'Hello world' + }, + error: self._noErrorCallbackExpected, + complete: (xhr) => { + assert.equal(xhr.responseText, 'Hello world 3', 'Response Text matches'); + done(); + } + }); + }); } } -var tests = new Tests(); -tests.run(); +new Tests().run(); diff --git a/jquery-mockjax/jquery-mockjax.d.ts b/jquery-mockjax/jquery-mockjax.d.ts index 7505a30e6f..c054f33317 100644 --- a/jquery-mockjax/jquery-mockjax.d.ts +++ b/jquery-mockjax/jquery-mockjax.d.ts @@ -22,7 +22,7 @@ interface MockJaxSettings { isTimeout?: boolean; dataType?: string; contentType?: string; - response?: (settings: any) => void; + response?: (settings: any, done?: Function) => void; responseText?: string | Object; responseXml?: string; proxy?: string; diff --git a/jquery.colorbox/jquery.colorbox.d.ts b/jquery.colorbox/jquery.colorbox.d.ts index 4af0e7e87f..5437c0bf18 100644 --- a/jquery.colorbox/jquery.colorbox.d.ts +++ b/jquery.colorbox/jquery.colorbox.d.ts @@ -252,7 +252,7 @@ interface ColorboxStatic { /** * This method allows you to call Colorbox without having to assign it to an element. */ - (settings: ColorboxSettings); + (settings: ColorboxSettings): any; /** * This method moves to the next item in a group and are the same as pressing the 'next' or 'previous' buttons. */ diff --git a/jquery.contextMenu/jquery.contextMenu.d.ts b/jquery.contextMenu/jquery.contextMenu.d.ts index 030a83f9f6..4b52a0ed84 100644 --- a/jquery.contextMenu/jquery.contextMenu.d.ts +++ b/jquery.contextMenu/jquery.contextMenu.d.ts @@ -28,6 +28,7 @@ interface JQueryContextMenuOptions { items: any; reposition?: boolean; className?: string; + itemClickEvent?: string; } interface JQueryStatic { diff --git a/jquery.dataTables/jquery.dataTables-tests.ts b/jquery.dataTables/jquery.dataTables-tests.ts index 4d1d114cb4..6329861604 100644 --- a/jquery.dataTables/jquery.dataTables-tests.ts +++ b/jquery.dataTables/jquery.dataTables-tests.ts @@ -82,21 +82,21 @@ $(document).ready(function () { width: "200px" } col = - { - data: "", - orderData: [10, 11, 20], - render: "", - } + { + data: "", + orderData: [10, 11, 20], + render: "", + } col = - { - data: colDataObject, - render: colRenderObject, - } + { + data: colDataObject, + render: colRenderObject, + } col = - { - data: colDataFunc, - render: colRenderFunc, - } + { + data: colDataFunc, + render: colRenderFunc, + } //#endregion "Column" @@ -124,16 +124,16 @@ $(document).ready(function () { }; colDef = - { - targets: "2", - cellType: "th", - }; + { + targets: "2", + cellType: "th", + }; colDef = - { - targets: ["2", 5], - cellType: "th", - }; + { + targets: ["2", 5], + cellType: "th", + }; //#endregion "ColumnDef" @@ -159,7 +159,7 @@ $(document).ready(function () { var ajaxFunc: DataTables.FunctionAjax = function (data, callback, settings) { }; - var ajaxDataFunc: DataTables.FunctionAjaxData = function (data) { + var ajaxDataFunc: DataTables.FunctionAjaxData = function (data, settings) { return data; }; @@ -229,41 +229,41 @@ $(document).ready(function () { config = - { - ajax: ajaxFunc, - deferLoading: [10, 100], - lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]], - order: [0, 'asc'], - orderFixed: [[0, 'asc'], [1, 'asc']], - renderer: { - header: "bootstrap", - pageButton: "jqueryui" - }, - search: { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, - searchCols: [ - null, - { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, - { "search": "" }, - { "search": "", "smart": true }, - null - ], - }; + { + ajax: ajaxFunc, + deferLoading: [10, 100], + lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]], + order: [0, 'asc'], + orderFixed: [[0, 'asc'], [1, 'asc']], + renderer: { + header: "bootstrap", + pageButton: "jqueryui" + }, + search: { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, + searchCols: [ + null, + { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, + { "search": "" }, + { "search": "", "smart": true }, + null + ], + }; config = - { - ajax: { - data: {}, - dataSrc: "", - }, - }; + { + ajax: { + data: {}, + dataSrc: "", + }, + }; config = - { - ajax: { - data: ajaxDataFunc, - dataSrc: function (data) { }, - }, - }; + { + ajax: { + data: ajaxDataFunc, + dataSrc: function (data) { }, + }, + }; //#endregion "Settings" @@ -309,6 +309,8 @@ $(document).ready(function () { draw = dt.draw(true); draw.$(""); + var initSettings = dt.init(); + var off = dt.off("event"); off = dt.off("event", function () { }); off.$(""); @@ -385,11 +387,11 @@ $(document).ready(function () { var select = $('}) to detect when the entered key + * sequence defines the path to a file. + * + * By default, {@linkplain webdriver.WebElement WebElement's} will enter all + * key sequences exactly as entered. You may set a + * {@linkplain webdriver.WebDriver#setFileDetector file detector} on the parent + * WebDriver instance to define custom behavior for handling file elements. Of + * particular note is the {@link selenium-webdriver/remote.FileDetector}, which + * should be used when running against a remote + * [Selenium Server](http://docs.seleniumhq.org/download/). + */ + class FileDetector { + /** @constructor */ + constructor(); + + /** + * Handles the file specified by the given path, preparing it for use with + * the current browser. If the path does not refer to a valid file, it will + * be returned unchanged, otherwisee a path suitable for use with the current + * browser will be returned. + * + * This default implementation is a no-op. Subtypes may override this + * function for custom tailored file handling. + * + * @param {!webdriver.WebDriver} driver The driver for the current browser. + * @param {string} path The path to process. + * @return {!webdriver.promise.Promise} A promise for the processed + * file path. + * @package + */ + handleFile(driver: webdriver.WebDriver, path: string): webdriver.promise.Promise; + } + + /** + * Creates a new WebDriver client, which provides control over a browser. + * + * Every WebDriver command returns a {@code webdriver.promise.Promise} that + * represents the result of that command. Callbacks may be registered on this + * object to manipulate the command result or catch an expected error. Any + * commands scheduled with a callback are considered sub-commands and will + * execute before the next command in the current frame. For example: + * + * var message = []; + * driver.call(message.push, message, 'a').then(function() { + * driver.call(message.push, message, 'b'); + * }); + * driver.call(message.push, message, 'c'); + * driver.call(function() { + * alert('message is abc? ' + (message.join('') == 'abc')); + * }); + * + */ + class WebDriver { + //region Constructors + + /** + * @param {!(Session|promise.Promise)} session Either a + * known session or a promise that will be resolved to a session. + * @param {!command.Executor} executor The executor to use when sending + * commands to the browser. + * @param {promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + */ + constructor(session: Session|webdriver.promise.Promise, executor: Executor, opt_flow?: webdriver.promise.ControlFlow); + + //endregion + + //region StaticMethods + + /** + * Creates a new WebDriver client for an existing session. + * @param {!command.Executor} executor Command executor to use when querying + * for session details. + * @param {string} sessionId ID of the session to attach to. + * @param {promise.ControlFlow=} opt_flow The control flow all + * driver commands should execute under. Defaults to the + * {@link promise.controlFlow() currently active} control flow. + * @return {!WebDriver} A new client for the specified session. + */ + static attachToSession(executor: Executor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + + /** + * Creates a new WebDriver session. + * @param {!command.Executor} executor The executor to create the new session + * with. + * @param {!./capabilities.Capabilities} desiredCapabilities The desired + * capabilities for the new session. + * @param {promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under, including the initial session creation. + * Defaults to the {@link promise.controlFlow() currently active} + * control flow. + * @return {!WebDriver} The driver for the newly created session. + */ + static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + + //endregion + + //region Methods + + /** + * @return {!webdriver.promise.ControlFlow} The control flow used by this + * instance. + */ + controlFlow(): webdriver.promise.ControlFlow; + + /** + * Schedules a {@link command.Command} to be executed by this driver's + * {@link command.Executor}. + * + * @param {!command.Command} command The command to schedule. + * @param {string} description A description of the command for debugging. + * @return {!promise.Promise} A promise that will be resolved + * with the command result. + * @template T + */ + schedule(command: Command, description: string): webdriver.promise.Promise; + + + /** + * Sets the {@linkplain input.FileDetector file detector} that should be + * used with this instance. + * @param {input.FileDetector} detector The detector to use or {@code null}. + */ + setFileDetector(detector: FileDetector): void; + + + /** + * @return {!webdriver.promise.Promise.} A promise for this + * client's session. + */ + getSession(): webdriver.promise.Promise; + + + /** + * @return {!webdriver.promise.Promise.} A promise + * that will resolve with the this instance's capabilities. + */ + getCapabilities(): webdriver.promise.Promise; + + + /** + * Schedules a command to quit the current session. After calling quit, this + * instance will be invalidated and may no longer be used to issue commands + * against the browser. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the command has completed. + */ + quit(): webdriver.promise.Promise; + + /** + * Creates a new action sequence using this driver. The sequence will not be + * scheduled for execution until {@link actions.ActionSequence#perform} is + * called. Example: + * + * driver.actions(). + * mouseDown(element1). + * mouseMove(element2). + * mouseUp(). + * perform(); + * + * @return {!actions.ActionSequence} A new action sequence for this instance. + */ + actions(): ActionSequence; + + + /** + * Creates a new touch sequence using this driver. The sequence will not be + * scheduled for execution until {@link actions.TouchSequence#perform} is + * called. Example: + * + * driver.touchActions(). + * tap(element1). + * doubleTap(element2). + * perform(); + * + * @return {!actions.TouchSequence} A new touch sequence for this instance. + */ + touchActions(): TouchSequence; + + + /** + * Schedules a command to execute JavaScript in the context of the currently + * selected frame or window. The script fragment will be executed as the body + * of an anonymous function. If the script is provided as a function object, + * that function will be converted to a string for injection into the target + * window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code webdriver.WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * The script may refer to any variables accessible from the current window. + * Furthermore, the script will execute in the window's context, thus + * {@code document} may be used to refer to the current document. Any local + * variables will not be available once the script has finished executing, + * though global variables will persist. + * + * If the script has a return value (i.e. if the script contains a return + * statement), then the following steps will be taken for resolving this + * functions return value: + * + * - For a HTML element, the value will resolve to a + * {@link webdriver.WebElement} + * - Null and undefined return values will resolve to null + * - Booleans, numbers, and strings will resolve as is + * - Functions will resolve to their string representation + * - For arrays and objects, each member item will be converted according to + * the rules above + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!webdriver.promise.Promise.} A promise that will resolve to the + * scripts return value. + * @template T + */ + executeScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to execute asynchronous JavaScript in the context of the + * currently selected frame or window. The script fragment will be executed as + * the body of an anonymous function. If the script is provided as a function + * object, that function will be converted to a string for injection into the + * target window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code webdriver.WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * Unlike executing synchronous JavaScript with {@link #executeScript}, + * scripts executed with this function must explicitly signal they are finished + * by invoking the provided callback. This callback will always be injected + * into the executed function as the last argument, and thus may be referenced + * with {@code arguments[arguments.length - 1]}. The following steps will be + * taken for resolving this functions return value against the first argument + * to the script's callback function: + * + * - For a HTML element, the value will resolve to a + * {@link webdriver.WebElement} + * - Null and undefined return values will resolve to null + * - Booleans, numbers, and strings will resolve as is + * - Functions will resolve to their string representation + * - For arrays and objects, each member item will be converted according to + * the rules above + * + * __Example #1:__ Performing a sleep that is synchronized with the currently + * selected window: + * + * var start = new Date().getTime(); + * driver.executeAsyncScript( + * 'window.setTimeout(arguments[arguments.length - 1], 500);'). + * then(function() { + * console.log( + * 'Elapsed time: ' + (new Date().getTime() - start) + ' ms'); + * }); + * + * __Example #2:__ Synchronizing a test with an AJAX application: + * + * var button = driver.findElement(By.id('compose-button')); + * button.click(); + * driver.executeAsyncScript( + * 'var callback = arguments[arguments.length - 1];' + + * 'mailClient.getComposeWindowWidget().onload(callback);'); + * driver.switchTo().frame('composeWidget'); + * driver.findElement(By.id('to')).sendKeys('dog@example.com'); + * + * __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In + * this example, the inject script is specified with a function literal. When + * using this format, the function is converted to a string for injection, so it + * should not reference any symbols not defined in the scope of the page under + * test. + * + * driver.executeAsyncScript(function() { + * var callback = arguments[arguments.length - 1]; + * var xhr = new XMLHttpRequest(); + * xhr.open("GET", "/resource/data.json", true); + * xhr.onreadystatechange = function() { + * if (xhr.readyState == 4) { + * callback(xhr.responseText); + * } + * } + * xhr.send(''); + * }).then(function(str) { + * console.log(JSON.parse(str)['food']); + * }); + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!webdriver.promise.Promise.} A promise that will resolve to the + * scripts return value. + * @template T + */ + executeAsyncScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to execute a custom function. + * @param {function(...): (T|webdriver.promise.Promise.)} fn The function to + * execute. + * @param {Object=} opt_scope The object in whose scope to execute the function. + * @param {...*} var_args Any arguments to pass to the function. + * @return {!webdriver.promise.Promise.} A promise that will be resolved' + * with the function's result. + * @template T + */ + call(fn: (...var_args: any[])=>(T|webdriver.promise.Promise), opt_scope?: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to wait for a condition to hold. The condition may be + * specified by a {@link webdriver.until.Condition}, as a custom function, or + * as a {@link webdriver.promise.Promise}. + * + * For a {@link webdriver.until.Condition} or function, the wait will repeatedly + * evaluate the condition until it returns a truthy value. If any errors occur + * while evaluating the condition, they will be allowed to propagate. In the + * event a condition returns a {@link webdriver.promise.Promise promise}, the + * polling loop will wait for it to be resolved and use the resolved value for + * whether the condition has been satisified. Note the resolution time for + * a promise is factored into whether a wait has timed out. + * + * *Example:* waiting up to 10 seconds for an element to be present and visible + * on the page. + * + * var button = driver.wait(until.elementLocated(By.id('foo'), 10000); + * button.click(); + * + * This function may also be used to block the command flow on the resolution + * of a {@link webdriver.promise.Promise promise}. When given a promise, the + * command will simply wait for its resolution before completing. A timeout may + * be provided to fail the command if the promise does not resolve before the + * timeout expires. + * + * *Example:* Suppose you have a function, `startTestServer`, that returns a + * promise for when a server is ready for requests. You can block a `WebDriver` + * client on this promise with: + * + * var started = startTestServer(); + * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds'); + * driver.get(getServerUrl()); + * + * @param {!(webdriver.promise.Promise| + * webdriver.until.Condition| + * function(!webdriver.WebDriver): T)} condition The condition to + * wait on, defined as a promise, condition object, or a function to + * evaluate as a condition. + * @param {number=} opt_timeout How long to wait for the condition to be true. + * @param {string=} opt_message An optional message to use if the wait times + * out. + * @return {!webdriver.promise.Promise} A promise that will be fulfilled + * with the first truthy value returned by the condition function, or + * rejected if the condition times out. + * @template T + */ + wait(condition: webdriver.promise.Promise|webdriver.until.Condition|((driver: WebDriver)=>T), timeout?: number, opt_message?: string): webdriver.promise.Promise; + + /** + * Schedules a command to make the driver sleep for the given amount of time. + * @param {number} ms The amount of time, in milliseconds, to sleep. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the sleep has finished. + */ + sleep(ms: number): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve they current window handle. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current window handle. + */ + getWindowHandle(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current list of available window handles. + * @return {!webdriver.promise.Promise.>} A promise that will + * be resolved with an array of window handles. + */ + getAllWindowHandles(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current page's source. The page source + * returned is a representation of the underlying DOM: do not expect it to be + * formatted or escaped in the same way as the response sent from the web + * server. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current page source. + */ + getPageSource(): webdriver.promise.Promise; + + /** + * Schedules a command to close the current window. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when this command has completed. + */ + close(): webdriver.promise.Promise; + + /** + * Schedules a command to navigate to the given URL. + * @param {string} url The fully qualified URL to open. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the document has finished loading. + */ + get(url: string): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the URL of the current page. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current URL. + */ + getCurrentUrl(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current page's title. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current page's title. + */ + getTitle(): webdriver.promise.Promise; + + /** + * Schedule a command to find an element on the page. If the element cannot be + * found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned + * by the driver. Unlike other commands, this error cannot be suppressed. In + * other words, scheduling a command to find an element doubles as an assert + * that the element is present on the page. To test whether an element is + * present on the page, use {@link #isElementPresent} instead. + * + * The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements + * are equivalent: + * + * var e1 = driver.findElement(By.id('foo')); + * var e2 = driver.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input this + * instance and returns a {@link WebElement}, or a promise that will resolve + * to a WebElement. If the returned promise resolves to an array of + * WebElements, WebDriver will use the first element. For example, to find the + * first visible link on a page, you could write: + * + * var link = driver.findElement(firstVisibleLink); + * + * function firstVisibleLink(driver) { + * var links = driver.findElements(By.tagName('a')); + * return promise.filter(links, function(link) { + * return link.isDisplayed(); + * }); + * } + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!WebElementPromise} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By|Function): WebElementPromise; + + /** + * Schedules a command to test if an element is present on the page. + * + * If given a DOM element, this function will check if it belongs to the + * document the driver is currently focused on. Otherwise, the function will + * test if at least one element can be found with the given search criteria. + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise} A promise that will resolve + * with whether the element is present on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * driver.findElements(locator).then(e => !!e.length); + */ + isElementPresent(locatorOrElement: By|Function): webdriver.promise.Promise; + + /** + * Schedule a command to search for multiple elements on the page. + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By|Function): webdriver.promise.Promise; + + /** + * Schedule a command to take a screenshot. The driver makes a best effort to + * return a screenshot of the following, in order of preference: + * + * 1. Entire page + * 2. Current window + * 3. Visible portion of the current frame + * 4. The entire display containing the browser + * + * @return {!promise.Promise} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(): webdriver.promise.Promise; + + /** + * @return {!webdriver.WebDriver.Options} The options interface for this + * instance. + */ + manage(): webdriver.Options; + + /** + * @return {!webdriver.WebDriver.Navigation} The navigation interface for this + * instance. + */ + navigate(): Navigation; + + /** + * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for + * this instance. + */ + switchTo(): webdriver.TargetLocator; + + //endregion + } + + interface IWebElementId { + [ELEMENT:string]: string; + } + + /** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@code webdriver.WebDriver} instance, or by searching + * under another {@code webdriver.WebElement}: + *
      
      +     *   driver.get('http://www.google.com');
      +     *   var searchForm = driver.findElement(By.tagName('form'));
      +     *   var searchBox = searchForm.findElement(By.name('q'));
      +     *   searchBox.sendKeys('webdriver');
      +     * 
      + * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + *
      
      +     *   driver.findElement(By.id('not-there')).then(function(element) {
      +     *     alert('Found an element that was not expected to be there!');
      +     *   }, function(error) {
      +     *     alert('The element was not found, as expected');
      +     *   });
      +     * 
      + */ + interface IWebElement { + //region Methods + + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * instance. + *

      + * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + *

        + *
      • The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + *
      • + *
      • The {@code webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + *
      • + *
      • The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + *
      • + *
      + * Note: On browsers where native keyboard events are not yet + * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...string} var_args The sequence of keys to + * type. All arguments will be joined into a single sequence (var_args is + * permitted for convenience). + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: string[]): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

      + * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will be returned as thus: + * + *

      async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

      Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

        + *
      • "class" + *
      • "readonly" + *
      + * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * @return {!webdriver.promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol + */ + getId(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + + //endregion + } + + interface IWebElementFinders { + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + * + *

      The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements + * are equivalent: + *

      +         * var e1 = element.findElement(By.id('foo'));
      +         * var e2 = element.findElement({id:'foo'});
      +         * 
      + * + *

      You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link webdriver.WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + *

      +         * var link = element.findElement(firstVisibleLink);
      +         *
      +         * function firstVisibleLink(element) {
      +         *   var links = element.findElements(By.tagName('a'));
      +         *   return webdriver.promise.filter(links, function(link) {
      +         *     return links.isDisplayed();
      +         *   }).then(function(visibleLinks) {
      +         *     return visibleLinks[0];
      +         *   });
      +         * }
      +         * 
      + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By|Function): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether an element could be located on the page. + */ + isElementPresent(locator: By|Function): webdriver.promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the elements. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By|Function): webdriver.promise.Promise; + } + + /** + * Defines an object that can be asynchronously serialized to its WebDriver + * wire representation. + * + * @constructor + * @template T + */ + interface Serializable { + /** + * Returns either this instance's serialized represention, if immediately + * available, or a promise for its serialized representation. This function is + * conceptually equivalent to objects that have a {@code toJSON()} property, + * except the serialize() result may be a promise or an object containing a + * promise (which are not directly JSON friendly). + * + * @return {!(T|IThenable.)} This instance's serialized wire format. + */ + serialize(): T|webdriver.promise.IThenable; + } + + /** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@link webdriver.WebDriver} instance, or by searching + * under another WebElement: + * + * driver.get('http://www.google.com'); + * var searchForm = driver.findElement(By.tagName('form')); + * var searchBox = searchForm.findElement(By.name('q')); + * searchBox.sendKeys('webdriver'); + * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + * + * driver.findElement(By.id('not-there')).then(function(element) { + * alert('Found an element that was not expected to be there!'); + * }, function(error) { + * alert('The element was not found, as expected'); + * }); + * + * @extends {webdriver.Serializable.} + */ + class WebElement implements Serializable { + /** + * @param {!WebDriver} driver the parent WebDriver instance for this element. + * @param {(!IThenable|string)} id The server-assigned opaque ID for + * the underlying DOM element. + */ + constructor(driver: webdriver.WebDriver, id: webdriver.promise.Promise|string); + + /** + * @param {string} id The raw ID. + * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key. + * @return {!Object} The element ID for use with WebDriver's wire protocol. + */ + static buildId(id: string, opt_noLegacy?: boolean): Object; + + /** + * Extracts the encoded WebElement ID from the object. + * + * @param {?} obj The object to extract the ID from. + * @return {string} the extracted ID. + * @throws {TypeError} if the object is not a valid encoded ID. + */ + static extractId(obj: IWebElementId): string; + + /** + * @param {?} obj the object to test. + * @return {boolean} whether the object is a valid encoded WebElement ID. + */ + static isId(obj: IWebElementId): boolean; + + /** + * Compares two WebElements for equality. + * + * @param {!WebElement} a A WebElement. + * @param {!WebElement} b A WebElement. + * @return {!promise.Promise} A promise that will be + * resolved to whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; + + /** + * @return {!webdriver.WebDriver} The parent driver for this instance. + */ + getDriver(): webdriver.WebDriver; + + /** + * @return {!promise.Promise} A promise that resolves to + * the server-assigned opaque ID assigned to this element. + */ + getId(): webdriver.promise.Promise; + + /** + * @deprecated Use {@link #getId()} instead. + */ + getRawId(): any; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@link #isElementPresent} instead. + * + * The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements + * are equivalent: + * + * var e1 = element.findElement(By.id('foo')); + * var e2 = element.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link webdriver.WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + * + * var link = element.findElement(firstVisibleLink); + * + * function firstVisibleLink(element) { + * var links = element.findElements(By.tagName('a')); + * return webdriver.promise.filter(links, function(link) { + * return links.isDisplayed(); + * }).then(function(visibleLinks) { + * return visibleLinks[0]; + * }); + * } + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!WebElementPromise} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By|Function): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise} A promise that will be + * resolved with whether an element could be located on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * element.findElements(locator).then(e => !!e.length); + */ + isElementPresent(locator: By|Function): webdriver.promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By|Function): webdriver.promise.Promise; + + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * promsieinstance. + * + * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + * + * - The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + * - The {@link webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + * + * - The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + * + * If this element is a file input ({@code }), the + * specified key sequence should specify the path to the file to attach to + * the element. This is analgous to the user clicking "Browse..." and entering + * the path into the file select dialog. + * + * var form = driver.findElement(By.css('form')); + * var element = form.findElement(By.css('input[type=file]')); + * element.sendKeys('/path/to/file.txt'); + * form.submit(); + * + * For uploads to function correctly, the entered path must reference a file + * on the _browser's_ machine, not the local machine running this script. When + * running against a remote Selenium server, a {@link webdriver.FileDetector} + * may be used to transparently copy files to the remote machine before + * attempting to upload them in the browser. + * + * __Note:__ On browsers where native keyboard events are not supported + * (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...(string|!webdriver.promise.Promise)} var_args The sequence + * of keys to type. All arguments will be joined into a single sequence. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when all keys have been typed. + */ + sendKeys(...var_args: Array>): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + * + * _Warning:_ the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!promise.Promise} A promise that will be + * resolved with the requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value, even if it has been modified after + * the page has been loaded. More exactly, this method will return the value of + * the given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned (for example, the "value" property of a textarea + * element). The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will return either "true" or null: + * + * async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + * Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + * + * - "class" + * - "readonly" + * + * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the attribute's value. The returned value will always be + * either a string or null. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise.<{width: number, height: number}>} A + * promise that will be resolved with the element's size as a + * {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise.<{x: number, y: number}>} A promise that + * will be resolved to the element's location as a + * {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the `value` of this element. This command has + * no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!promise.Promise} A promise that will be resolved + * when the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Take a screenshot of the visible region encompassed by this element's + * bounding rectangle. + * + * @param {boolean=} opt_scroll Optional argument that indicates whether the + * element should be scrolled into view before taking a screenshot. + * Defaults to false. + * @return {!promise.Promise} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(opt_scroll?: boolean): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + + /** @override */ + serialize(): webdriver.promise.Promise; + } + + /** + * WebElementPromise is a promise that will be fulfilled with a WebElement. + * This serves as a forward proxy on WebElement, allowing calls to be + * scheduled without directly on this instance before the underlying + * WebElement has been fulfilled. In other words, the following two statements + * are equivalent: + *
      
      +     *     driver.findElement({id: 'my-button'}).click();
      +     *     driver.findElement({id: 'my-button'}).then(function(el) {
      +     *       return el.click();
      +     *     });
      +     * 
      + * + * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!webdriver.promise.Promise.} el A promise + * that will resolve to the promised element. + * @constructor + * @extends {webdriver.WebElement} + * @implements {webdriver.promise.Thenable.} + * @final + */ + class WebElementPromise extends WebElement implements webdriver.promise.IThenable { + /** + * @param {!WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!promise.Promise} el A promise + * that will resolve to the promised element. + */ + constructor(driver: webdriver.WebDriver, el: webdriver.promise.Promise); + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => webdriver.promise.Promise, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => R, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *
      
      +         *   // Synchronous API:
      +         *   try {
      +         *     doSynchronousWork();
      +         *   } catch (ex) {
      +         *     console.error(ex);
      +         *   }
      +         *
      +         *   // Asynchronous promise API:
      +         *   doAsynchronousWork().thenCatch(function(ex) {
      +         *     console.error(ex);
      +         *   });
      +         * 
      + * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): webdriver.promise.Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *
      
      +         *   // Synchronous API:
      +         *   try {
      +         *     doSynchronousWork();
      +         *   } finally {
      +         *     cleanUp();
      +         *   }
      +         *
      +         *   // Asynchronous promise API:
      +         *   doAsynchronousWork().thenFinally(cleanUp);
      +         * 
      + * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *
      
      +         *   try {
      +         *     throw Error('one');
      +         *   } finally {
      +         *     throw Error('two');  // Hides Error: one
      +         *   }
      +         *
      +         *   webdriver.promise.rejected(Error('one'))
      +         *       .thenFinally(function() {
      +         *         throw Error('two');  // Hides Error: one
      +         *       });
      +         * 
      + * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): webdriver.promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): webdriver.promise.Promise; + } + + /** + * Contains information about a WebDriver session. + */ + class Session { + + //region Constructors + + /** + * @param {string} id The session ID. + * @param {!(Object|webdriver.Capabilities)} capabilities The session + * capabilities. + * @constructor + */ + constructor(id: string, capabilities: Capabilities|Object); + + //endregion + + //region Methods + + /** + * @return {string} This session's ID. + */ + getId(): string; + + /** + * @return {!webdriver.Capabilities} This session's capabilities. + */ + getCapabilities(): webdriver.Capabilities; + + /** + * Retrieves the value of a specific capability. + * @param {string} key The capability to retrieve. + * @return {*} The capability value. + */ + getCapability(key: string): any; + + /** + * Returns the JSON representation of this object, which is just the string + * session ID. + * @return {string} The JSON representation of this Session. + */ + toJSON(): string; + + //endregion + } +} + +declare namespace testing { + /** + * Registers a new test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ + function describe(name: string, fn: Function): void; + + /** + * Defines a suppressed test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ + function xdescribe(name: string, fn: Function): void; + + /** + * Register a function to call after the current suite finishes. + * @param fn + */ + function after(fn: Function): void; + + /** + * Register a function to call after each test in a suite. + * @param fn + */ + function afterEach(fn: Function): void; + + /** + * Register a function to call before the current suite starts. + * @param fn + */ + function before(fn: Function): void; + + /** + * Register a function to call before each test in a suite. + * @param fn + */ + function beforeEach(fn: Function): void; + + /** + * Add a test to the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function it(name: string, fn: Function): void; + + /** + * An alias for {@link #it()} that flags the test as the only one that should + * be run within the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function iit(name: string, fn: Function): void; + + /** + * Adds a test to the current suite while suppressing it so it is not run. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function xit(name: string, fn: Function): void; +} + +declare module 'selenium-webdriver/chrome' { + export = chrome; +} + +declare module 'selenium-webdriver/executors' { + export = executors; +} + +declare module 'selenium-webdriver' { + export = webdriver; +} + +declare module 'selenium-webdriver/testing' { + export = testing; +} diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 548048b695..e1301d5b58 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1,6 +1,6 @@ // Type definitions for Selenium WebDriverJS 2.44.0 // Project: https://code.google.com/p/selenium/ -// Definitions by: Bill Armstrong , Yuki Kokubun +// Definitions by: Bill Armstrong , Yuki Kokubun , Craig Nishina // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace chrome { diff --git a/semver/semver-tests.ts b/semver/semver-tests.ts index 2078be5555..d777573857 100644 --- a/semver/semver-tests.ts +++ b/semver/semver-tests.ts @@ -27,6 +27,7 @@ str = mod.inc(str, str, loose); num = mod.major(str, loose); num = mod.minor(str, loose); num = mod.patch(str, loose); +strArr = mod.prerelease(str, loose); // Comparison bool = mod.gt(v1, v2, loose); @@ -44,6 +45,7 @@ diff = mod.diff(v1, v2, loose); str = mod.validRange(str, loose); bool = mod.satisfies(version, str, loose); str = mod.maxSatisfying(versions, str, loose); +str = mod.minSatisfying(versions, str, loose); bool = mod.gtr(version, str, loose); bool = mod.ltr(version, str, loose); bool = mod.outside(version, str, str, loose); diff --git a/semver/semver.d.ts b/semver/semver.d.ts index 20298004d5..a1ace1a134 100644 --- a/semver/semver.d.ts +++ b/semver/semver.d.ts @@ -1,4 +1,4 @@ -// Type definitions for semver v4.3.4 +// Type definitions for semver v5.3.0 // Project: https://github.com/npm/node-semver // Definitions by: Bart van der Schoor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/semver @@ -28,6 +28,10 @@ declare namespace SemVerModule { * Return the patch version number. */ function patch(v: string, loose?: boolean): number; + /** + * Returns an array of prerelease components, or null if none exist. + */ + function prerelease(v: string, loose?: boolean): string[]; // Comparison /** @@ -84,6 +88,10 @@ declare namespace SemVerModule { * Return the highest version in the list that satisfies the range, or null if none of them do. */ function maxSatisfying(versions: string[], range: string, loose?: boolean): string; + /** + * Return the lowest version in the list that satisfies the range, or null if none of them do. + */ + function minSatisfying(versions: string[], range: string, loose?: boolean): string; /** * Return true if version is greater than all the versions possible in the range. */ diff --git a/seneca/seneca-tests.ts b/seneca/seneca-tests.ts index 9bc411525f..f61279c749 100644 --- a/seneca/seneca-tests.ts +++ b/seneca/seneca-tests.ts @@ -5,8 +5,8 @@ * This file contains all of the example code that was on http://senecajs.org as of Mon June 16, 2016. */ -import SENECA = require('seneca') -var seneca = SENECA() +import * as SENECA from 'seneca' +var seneca: SENECA.Instance = SENECA() seneca.add({ cmd: 'salestax' }, function (args, callback) { var rate = 0.23 diff --git a/seneca/seneca.d.ts b/seneca/seneca.d.ts index 08fd71859d..7db8f83b6c 100644 --- a/seneca/seneca.d.ts +++ b/seneca/seneca.d.ts @@ -6,18 +6,13 @@ declare module "seneca" { - type UnknownType = any; + function SNS(options?: SNS.Options): SNS.Instance; + namespace SNS { - // function s(options?: Options): Seneca; + type UnknownType = any; - // what does seneca do about logging? - function log(): void; - - - // module s { - interface Options { [plugin_name: string]: any; tag?: string; @@ -125,8 +120,8 @@ declare module "seneca" { } interface Optioner { - set: (input: string | Options) => Options; - get: () => Options; + set: (input: string | Options) => Options; + get: () => Options; } type ExecutorWorker = (callback: any) => void; @@ -171,10 +166,11 @@ declare module "seneca" { type EntityListCallback = (error: Error, result: any[]) => void; - interface Seneca { + + + interface Instance { version: string; - (options?: Options): Seneca; options(options: Options): void; error(handler: GlobalErrorHandler): void; @@ -196,7 +192,7 @@ declare module "seneca" { make(zone: string, base: string, entity_canon: string, properties?: any): Entity; // @param name reference to plugin provided object - export(name: string): void; + export(name: string): PluginModule; pin(pattern: Pattern): void; } @@ -222,10 +218,9 @@ declare module "seneca" { remove$(id: DatabaseID | EntityDataWithQuery, callback: EntityRemoveCallback): void; list$(query: EntityDataWithQuery, callback: EntityListCallback): void; } + + } - // } - - var sen: Seneca - export = sen; - + export = SNS; } + diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts index 38072ee079..76c5f46490 100644 --- a/sequelize/sequelize.d.ts +++ b/sequelize/sequelize.d.ts @@ -6,10 +6,11 @@ // Based on original work by: samuelneff /// -/// +/// /// declare module "sequelize" { + import * as _ from "lodash"; namespace sequelize { @@ -3727,7 +3728,7 @@ declare module "sequelize" { * @return Returns the aggregate result cast to `options.dataType`, unless `options.plain` is false, in * which case the complete data result is returned. */ - aggregate( field : string, aggregateFunction : Function, options? : AggregateOptions ) : Promise; + aggregate( field : string, aggregateFunction : string, options? : AggregateOptions ) : Promise; /** * Count the number of records matching the provided where clause. @@ -4986,17 +4987,17 @@ declare module "sequelize" { /** * Maximum connections of the pool */ - maxConnections?: number; + max?: number; /** * Minimum connections of the pool */ - minConnections?: number; + min?: number; /** * The maximum time, in milliseconds, that a connection can be idle before being released. */ - maxIdleTime?: number; + idle?: number; /** * A function that validates a connection. Called with client. The default function checks that client is an diff --git a/serialport/serialport-tests.ts b/serialport/serialport-tests.ts index b820fa7a8d..79f85423eb 100644 --- a/serialport/serialport-tests.ts +++ b/serialport/serialport-tests.ts @@ -1,38 +1,38 @@ // Tests for serialport.d.ts -// Project: https://github.com/EmergingTechnologyAdvisors/node-serialport +// Project: https://github.com/EmergingTechnologyAdvisors/node-serialport // Definitions by: Jeremy Foster // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Tests taken from documentation samples. /// -import * as serialport from 'serialport'; +import * as SerialPort from 'serialport'; function test_basic_connect() { - let port = new serialport.SerialPort(""); + let port = new SerialPort(""); } function test_connect_config() { - let port = new serialport.SerialPort("", { + let port = new SerialPort("", { baudrate: 0, disconnectedCallback: function () { }, - parser: serialport.parsers.readline("\n") + parser: SerialPort.parsers.readline("\n") }); } function test_write() { - let port = new serialport.SerialPort(""); - port.write('main screen turn on', (err, bytesWritten) => { + let port = new SerialPort(""); + port.write("main screen turn on", (err, bytesWritten) => { }); } function test_events() { - let port = new serialport.SerialPort(""); - port.on('open', function () { }); + let port = new SerialPort(""); + port.on("open", function () { }); } function test_list_ports() { - serialport.list( (err:string, ports:serialport.portConfig[]) => { + SerialPort.list( (err: string, ports: SerialPort.portConfig[]) => { }); -} \ No newline at end of file +} diff --git a/serialport/serialport.d.ts b/serialport/serialport.d.ts index d8bbc03f6f..60c240bbda 100644 --- a/serialport/serialport.d.ts +++ b/serialport/serialport.d.ts @@ -1,51 +1,53 @@ -// Type definitions for serialport -// Project: https://github.com/EmergingTechnologyAdvisors/node-serialport +// Type definitions for serialport 4.0.1 +// Project: https://github.com/EmergingTechnologyAdvisors/node-serialport // Definitions by: Jeremy Foster -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'serialport' { - module parsers { - function readline(delimiter: string):void; - function raw(emitter:any, buffer:string):void - } - - export class SerialPort { - constructor(path: string, options?: Object, openImmediately?: boolean, callback?: (err:string) => void) + class SerialPort { + constructor(path: string, options?: Object, openImmediately?: boolean, callback?: (err: string) => void) isOpen: boolean; - on(event: string, callback?: (data?:any) => void):void; - open(callback?: () => void):void; - write(buffer: any, callback?: (err:string, bytesWritten:number) => void):void - pause():void; - resume():void; - disconnected(err: Error):void; - close(callback?: () => void):void; - flush(callback?: () => void):void; - set(options: setOptions, callback: () => void):void; - drain(callback?: () => void):void; - update(options: updateOptions, callback?: () => void):void; + on(event: string, callback?: (data?: any) => void): void; + open(callback?: () => void): void; + write(buffer: any, callback?: (err: string, bytesWritten: number) => void): void + pause(): void; + resume(): void; + disconnected(err: Error): void; + close(callback?: (err:any) => void): void; + flush(callback?: (err:any) => void): void; + set(options: SerialPort.setOptions, callback: () => void): void; + drain(callback?: (err:any) => void): void; + update(options: SerialPort.updateOptions, callback?: () => void): void; + static list(callback: (err: string, ports: SerialPort.portConfig[]) => void): void; + static parsers: { + readline: (delimiter: string) => void, + raw: (emitter: any, buffer: string) => void + }; } - export function list(callback: (err: string, ports:portConfig[]) => void): void; + namespace SerialPort { + interface portConfig { + comName: string; + manufacturer: string; + serialNumber: string; + pnpId: string; + locationId: string; + vendorId: string; + productId: string; + } - interface portConfig { - comName: string, - manufacturer: string, - serialNumber: string, - pnpId: string, - locationId: string, - vendorId: string, - productId: string + interface setOptions { + brk?: boolean; + cts?: boolean; + dsr?: boolean; + dtr?: boolean; + rts?: boolean; + } + + interface updateOptions { + baudRate?: number; + } } - interface setOptions { - brk?: boolean; - cts?: boolean; - dsr?: boolean; - dtr?: boolean; - rts?: boolean; - } - - interface updateOptions { - baudRate?: number - } -} \ No newline at end of file + export = SerialPort +} diff --git a/service_worker_api/service_worker_api-test.ts b/service_worker_api/service_worker_api-test.ts index e144880ba1..0d39cc509b 100644 --- a/service_worker_api/service_worker_api-test.ts +++ b/service_worker_api/service_worker_api-test.ts @@ -19,13 +19,11 @@ self.addEventListener('fetch', function(event: FetchEvent) { }); self.caches.open('v1').then(function(cache: Cache) { - cache.matchAll('/images/').then(function(response: Array) { + cache.matchAll('/images/').then(function(response: Array) { response.forEach(function(element, index, array) { - cache.delete(element); - + cache.delete(element.url); }); }); - }); self.addEventListener('install', function(event: InstallEvent) { @@ -56,7 +54,11 @@ self.addEventListener('install', function(event: InstallEvent) { }); self.addEventListener('fetch', function(event: FetchEvent) { - var cachedResponse = self.caches.match(event.request).catch(function() { + var cachedResponse = self.caches.match(event.request).then(function(response: Response) { + if (response) { + return response; + } + }).catch(function() { return self.fetch(event.request).then(function(response: Response) { return self.caches.open('v1').then(function(cache) { cache.put(event.request, response.clone()); @@ -71,8 +73,8 @@ self.addEventListener('fetch', function(event: FetchEvent) { }); self.caches.open('v1').then(function(cache) { - cache.match('/images/image.png').then(function(response) { - cache.delete(response); + cache.match('/images/image.png').then(function(response: Response) { + cache.delete(response.url); }); }); @@ -185,4 +187,4 @@ self.addEventListener('notificationclick', function(event: NotificationEvent) { if (self.clients.openWindow) return self.clients.openWindow('/'); })); -}); \ No newline at end of file +}); diff --git a/service_worker_api/service_worker_api.d.ts b/service_worker_api/service_worker_api.d.ts index 77c80b6706..6084efc4a0 100644 --- a/service_worker_api/service_worker_api.d.ts +++ b/service_worker_api/service_worker_api.d.ts @@ -3,7 +3,8 @@ // Definitions by: Tristan Caron // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +// // REMOVED third "/" so this doesn't fire. Problem with duplicate Promises +// between es6 and typescript - https://github.com/DefinitelyTyped/DefinitelyTyped/issues/5015 /** * Provides methods relating to the body of the response/request, allowing you @@ -279,16 +280,16 @@ interface Cache { * @param request The Request you are attempting to find in the Cache. * @param {CacheOptions} options */ - match(request: Request | string, options?: CacheOptions): Promise; + match(request: Request | string, options?: CacheOptions): Promise; /** - * Returns a Promise that resolves to an array of all matching requests in + * Returns a Promise that resolves to an array of all matching responses in * the Cache object. * * @param request The Request you are attempting to find in the Cache. * @param {CacheOptions} options */ - matchAll(request: Request | string, options?: CacheOptions): Promise>; + matchAll(request: Request | string, options?: CacheOptions): Promise>; /** * Returns a Promise that resolves to a new Cache entry whose key @@ -893,4 +894,4 @@ interface Window extends ServiceWorkerGlobalScope { interface NotificationEvent extends Event, ExtendableEvent { notification: any; -} \ No newline at end of file +} diff --git a/set-cookie-parser/set-cookie-parser-tests.ts b/set-cookie-parser/set-cookie-parser-tests.ts new file mode 100644 index 0000000000..8734fdfcdb --- /dev/null +++ b/set-cookie-parser/set-cookie-parser-tests.ts @@ -0,0 +1,70 @@ +/// +/// + +import * as assert from "assert"; +import * as http from "http"; +import * as setCookie from "set-cookie-parser"; + +// Call parse function on imported object +var input = "foo=bar;"; +var cookies = setCookie.parse(input); +assert.equal(cookies.length, 1); +assert.equal(cookies[0].name, "foo"); +assert.equal(cookies[0].value, "bar"); + +// Required properties only test +var requiredOnly = "foo=bar;"; +cookies = setCookie(requiredOnly); +assert.equal(cookies.length, 1); +assert.equal(cookies[0].name, "foo"); +assert.equal(cookies[0].value, "bar"); + +// Optional properties included test +var optionalIncluded = "foo=bar; Max-Age=1000; Domain=.example.com; Path=/; Expires=Tue, 01 Jul 2025 10:01:11 GMT; HttpOnly; Secure"; +cookies = setCookie(optionalIncluded); +assert.equal(cookies.length, 1); +assert.equal(cookies[0].name, "foo"); +assert.equal(cookies[0].value, "bar"); +assert.equal(cookies[0].domain, ".example.com"); +assert.equal(cookies[0].path, "/"); +assert.deepEqual(cookies[0].expires, new Date('Tue Jul 01 2025 06:01:11 GMT-0400 (EDT)')); +assert.equal(cookies[0].maxAge, 1000); +assert.equal(cookies[0].httpOnly, true); +assert.equal(cookies[0].secure, true); + +// Array of strings test +var arrayOfCookies = ["bam=baz", "foo=bar"]; +cookies = setCookie(arrayOfCookies); +assert.equal(cookies.length, 2); +assert.equal(cookies[0].name, "bam"); +assert.equal(cookies[0].value, "baz"); +assert.equal(cookies[1].name, "foo"); +assert.equal(cookies[1].value, "bar"); + +// HTTP response message test +var message = {}; +message.headers = { "set-cookie": ["bam=baz", "foo=bar"] }; +cookies = setCookie(message); +assert.equal(cookies.length, 2); +assert.equal(cookies[0].name, "bam"); +assert.equal(cookies[0].value, "baz"); +assert.equal(cookies[1].name, "foo"); +assert.equal(cookies[1].value, "bar"); + +// Create new cookie with only required properties +var requiredOnlyCookie: setCookie.Cookie = { + name: "Foo", + value: "Bar" +} + +// Create new cookie with all properties included optional ones +var optionalIncludedCookie: setCookie.Cookie = { + name: "Bam", + value: "Baz", + domain: ".example.com", + path: "/", + expires: new Date("Tue Jul 01 2025 06:01:11 GMT-0400 (EDT)"), + maxAge: 1000, + httpOnly: true, + secure: true +}; diff --git a/set-cookie-parser/set-cookie-parser.d.ts b/set-cookie-parser/set-cookie-parser.d.ts new file mode 100644 index 0000000000..3cacde6043 --- /dev/null +++ b/set-cookie-parser/set-cookie-parser.d.ts @@ -0,0 +1,29 @@ +// Type definitions for set-cookie-parser +// Project: https://github.com/nfriedly/set-cookie-parser +// Definitions by: Nick Paddock +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "set-cookie-parser" { + import http = require("http"); + + function SetCookieParser(input: string | string[] | http.IncomingMessage): SetCookieParser.Cookie[]; + + namespace SetCookieParser { + function parse(input: string | string[] | http.IncomingMessage): Cookie[]; + + interface Cookie { + name: string; + value: string; + path?: string; + expires?: Date; + maxAge?: number; + domain?: string; + secure?: boolean; + httpOnly?: boolean; + } + } + + export = SetCookieParser; +} diff --git a/shapefile/shapefile-tests.ts b/shapefile/shapefile-tests.ts new file mode 100644 index 0000000000..1a827d2706 --- /dev/null +++ b/shapefile/shapefile-tests.ts @@ -0,0 +1,19 @@ +/// +import * as shapefile from 'shapefile' + +shapefile.open('./example.shp') + .then(source => { + source.bbox + source.read() + .then(result => { + result.value + result.done + }) + }) + +shapefile.read("example.shp") + .then(result => { + result.bbox + result.features + result.type + }) diff --git a/shapefile/shapefile.d.ts b/shapefile/shapefile.d.ts new file mode 100644 index 0000000000..20a0b85c7b --- /dev/null +++ b/shapefile/shapefile.d.ts @@ -0,0 +1,31 @@ +// Type definitions for shapefile 0.5.6 +// Project: https://github.com/mbostock/shapefile +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare const shapefile: shapefile.ShapefileStatic; + +declare namespace shapefile { + interface Options { + encoding: string + highWaterMark: number + } + interface Feature { + done: boolean + value: GeoJSON.Feature + } + interface Shapefile { + bbox: Array + read(): Promise; + } + interface ShapefileStatic { + open(shp: any, dbf?: any, options?: Options): Promise; + read(shp: any, dbf?: any, options?: Options): Promise>; + } +} + +declare module "shapefile" { + export = shapefile +} diff --git a/simple-assign/simple-assign-tests.ts b/simple-assign/simple-assign-tests.ts new file mode 100644 index 0000000000..d39583bc8c --- /dev/null +++ b/simple-assign/simple-assign-tests.ts @@ -0,0 +1,78 @@ +/// +import simpleAssign = require("simple-assign"); + +interface Target { + hellow: string; +} + +interface Source1 { + source1: string; +} + +interface Result extends Target, Source1 { + +} + +interface Source2 { + source2: string; +} + +interface Result2 extends Result, Source2 { + +} + +interface Source3 { + source3: string; +} + +interface Result3 extends Result2, Source3 { + +} + +interface Source4 { + source4: string; +} + +interface Result4 extends Result3, Source4 { + +} + +interface Source5 { + source5: string; +} + +interface Result5 extends Result4, Source5 { + +} + +function assign1(): Result { + return simpleAssign({hellow: "world"}, {source1: "U"}); +} + +function assign2(): Result2 { + return simpleAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}); +} + +function assign3(): Result3 { + return simpleAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}); +} + +function assign4(): Result4 { + return simpleAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}); +} + +function assign5(): Result5 { + return simpleAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}, {source5: "R"}); +} + +function assign() { + return simpleAssign({hellow: "world"}, {source1: "U"}, {source2: "V"}, {source3: "W"}, {source4: "Q"}, {source5: "R"}, { + hellow: "hellow", + source1: "source1", + source2: "source2", + source3: "source3", + source4: "source4", + source5: "source5", + generic: "any" + }); +} diff --git a/simple-assign/simple-assign.d.ts b/simple-assign/simple-assign.d.ts new file mode 100644 index 0000000000..7c44236f4c --- /dev/null +++ b/simple-assign/simple-assign.d.ts @@ -0,0 +1,14 @@ +// Type definitions for simple-assign 0.1.0 +// Project: https://github.com/newoga/simple-assign +// Definitions by: Ivo Stratev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "simple-assign" { + function simpleAssign(target: T, source: U): T & U; + function simpleAssign(target: T, source1: U, source2: V): T & U & V; + function simpleAssign(target: T, source1: U, source2: V, source3: W): T & U & V & W; + function simpleAssign(target: T, source1: U, source2: V, source3: W, source4: Q): T & U & V & W & Q; + function simpleAssign(target: T, source1: U, source2: V, source3: W, source4: Q, source5: R): T & U & V & W & Q & R; + function simpleAssign(target: any, ...sources: any[]): any; + export = simpleAssign; +} diff --git a/simplemde/simplemde-tests.ts b/simplemde/simplemde-tests.ts new file mode 100644 index 0000000000..cf0af6e147 --- /dev/null +++ b/simplemde/simplemde-tests.ts @@ -0,0 +1,158 @@ +/// + +function testSimplemde() { + + function customMarkdownParser(markdown: string) { + return "
      " + markdown + "
      "; + } + + function testInit() { + var simplemde1 = new SimpleMDE(); + var simplemde2 = new SimpleMDE({ element: document.getElementById("MyID") }); + } + + function testAccessValue() { + var simplemde = new SimpleMDE(); + var value: string = simplemde.value(); + simplemde.value("This text will appear in the editor"); + } + + function testConfiguration() { + var simplemde: SimpleMDE; + + // Most options demonstrate the non-default behavior + simplemde = new SimpleMDE({ + autofocus: true, + autosave: { + enabled: true, + uniqueId: "MyUniqueID", + delay: 1000 + }, + blockStyles: { + bold: "__", + italic: "_" + }, + element: document.getElementById("MyID"), + forceSync: true, + hideIcons: ["guide", "heading"], + indentWithTabs: false, + initialValue: "Hello world!", + insertTexts: { + horizontalRule: ["", "\n\n-----\n\n"], + image: ["![](http://", ")"], + link: ["[", "](http://)"], + table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text | Text | Text |\n\n"] + }, + lineWrapping: false, + parsingConfig: { + allowAtxHeaderWithoutSpace: true, + strikethrough: false, + underscoresBreakWords: true + }, + placeholder: "Type here...", + previewRender: function (plainText) { + return customMarkdownParser(plainText); // Returns HTML from a custom parser + }, + promptURLs: true, + renderingConfig: { + singleLineBreaks: false, + codeSyntaxHighlighting: true + }, + shortcuts: { + drawTable: "Cmd-Alt-T" + }, + showIcons: ["code", "table"], + spellChecker: false, + status: false, + styleSelectedText: false, + tabSize: 4, + toolbar: false, + toolbarTips: false + }); + + simplemde = new SimpleMDE({ + previewRender: function (plainText, preview) { // Async method + setTimeout(function () { + preview.innerHTML = customMarkdownParser(plainText); + }, 250); + + return "Loading..."; + }, + status: ["autosave", "lines", "words", "cursor"] // Optional usage + }); + + simplemde = new SimpleMDE({ + status: ["autosave", "lines", "words", "cursor", { + className: "keystrokes", + defaultValue: function (el) { + this.keystrokes = 0; + el.innerHTML = "0 Keystrokes"; + }, + onUpdate: function (el) { + el.innerHTML = ++this.keystrokes + " Keystrokes"; + } + }] // Another optional usage, with a custom status bar item that counts keystrokes + }); + } + + function testToolbarCustomize() { + var simplemde: SimpleMDE; + + // Customize only the order of existing buttons + simplemde = new SimpleMDE({ + toolbar: ["bold", "italic", "heading", "|", "quote"] + }); + + // Customize all information and/or add your own icons + simplemde = new SimpleMDE({ + toolbar: [{ + name: "bold", + action: SimpleMDE.toggleBold, + className: "fa fa-bold", + title: "Bold" + }, + { + name: "custom", + action: function customFunction(editor) { + // Add your own code + }, + className: "fa fa-star", + title: "Custom Button" + }, + "|" // Separator + ] + }); + } + + function testKeyboardShortcuts() { + var simplemde = new SimpleMDE({ + shortcuts: { + "toggleOrderedList": "Ctrl-Alt-K", // alter the shortcut for toggleOrderedList + "toggleCodeBlock": null, // unbind Ctrl-Alt-C + "drawTable": "Cmd-Alt-T" // bind Cmd-Alt-T to drawTable action, which doesn't come with a default shortcut + } + }); + } + + function testEventHandling() { + var simplemde = new SimpleMDE(); + simplemde.codemirror.on("change", function () { + console.log(simplemde.value()); + }); + } + + function testRemoveFromTextArea() { + var simplemde = new SimpleMDE(); + simplemde.toTextArea(); + simplemde = null; + } + + function testOtherMethods() { + var simplemde = new SimpleMDE(); + var booleanVal: boolean; + booleanVal = simplemde.isPreviewActive(); // returns boolean + booleanVal = simplemde.isSideBySideActive(); // returns boolean + booleanVal = simplemde.isFullscreenActive(); // returns boolean + simplemde.clearAutosavedValue(); // no returned value + } +} diff --git a/simplemde/simplemde.d.ts b/simplemde/simplemde.d.ts new file mode 100644 index 0000000000..e08e7f11a9 --- /dev/null +++ b/simplemde/simplemde.d.ts @@ -0,0 +1,130 @@ +// Type definitions for SimpleMDE v1.11.2 +// Project: https://github.com/NextStepWebs/simplemde-markdown-editor +// Definitions by: Scalesoft +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace SimpleMDE { + interface AutoSaveOptions { + enabled?: boolean; + delay?: number; + uniqueId: string; + } + + interface BlockStyleOptions { + bold?: string; + code?: string; + italic?: string; + } + + interface InsertTextOptions { + horizontalRule?: string[]; + image?: string[]; + link?: string[]; + table?: string[]; + } + + interface ParsingOptions { + allowAtxHeaderWithoutSpace?: boolean; + strikethrough?: boolean; + underscoresBreakWords?: boolean; + } + + interface RenderingOptions { + singleLineBreaks?: boolean; + codeSyntaxHighlighting: boolean; + } + + interface ShortcutsArray { + [action: string]: string; + toggleBlockquote?: string; + toggleBold?: string; + cleanBlock?: string; + toggleHeadingSmaller?: string; + toggleItalic?: string; + drawLink?: string; + toggleUnorderedList?: string; + togglePreview?: string; + toggleCodeBlock?: string; + drawImage?: string; + toggleOrderedList?: string; + toggleHeadingBigger?: string; + toggleSideBySide?: string; + toggleFullScreen?: string; + } + + interface StatusBarItem { + className: string; + defaultValue: (element: HTMLElement) => void; + onUpdate: (element: HTMLElement) => void; + } + + interface ToolbarIcon { + name: string; + action: string|((editor: SimpleMDE) => void); + className: string; + title: string; + } + + interface Options { + autoDownloadFontAwesome?: boolean; + autofocus?: boolean; + autosave?: AutoSaveOptions; + blockStyles?: BlockStyleOptions; + element?: HTMLElement; + forceSync?: boolean; + hideIcons?: string[]; + indentWithTabs?: boolean; + initialValue?: string; + insertTexts?: InsertTextOptions; + lineWrapping?: boolean; + parsingConfig?: ParsingOptions; + placeholder?: string; + previewRender?: (markdownPlaintext: string, previewElement?: HTMLElement) => string; + promptURLs?: boolean; + renderingConfig?: RenderingOptions; + shortcuts?: ShortcutsArray; + showIcons?: string[]; + spellChecker?: boolean; + status?: boolean|Array; + styleSelectedText?: boolean; + tabSize?: number; + toolbar?: boolean|Array; + toolbarTips?: boolean; + } +} + +declare class SimpleMDE { + constructor(); + constructor(options: SimpleMDE.Options); + value(): string; + value(val: string): void; + codemirror: any; + toTextArea(): void; + isPreviewActive(): boolean; + isSideBySideActive(): boolean; + isFullscreenActive(): boolean; + clearAutosavedValue(): void; + + static toggleBold: (editor: SimpleMDE) => void; + static toggleItalic: (editor: SimpleMDE) => void; + static toggleStrikethrough: (editor: SimpleMDE) => void; + static toggleHeadingSmaller: (editor: SimpleMDE) => void; + static toggleHeadingBigger: (editor: SimpleMDE) => void; + static toggleHeading1: (editor: SimpleMDE) => void; + static toggleHeading2: (editor: SimpleMDE) => void; + static toggleHeading3: (editor: SimpleMDE) => void; + static toggleCodeBlock: (editor: SimpleMDE) => void; + static toggleBlockquote: (editor: SimpleMDE) => void; + static toggleUnorderedList: (editor: SimpleMDE) => void; + static toggleOrderedList: (editor: SimpleMDE) => void; + static cleanBlock: (editor: SimpleMDE) => void; + static drawLink: (editor: SimpleMDE) => void; + static drawImage: (editor: SimpleMDE) => void; + static drawTable: (editor: SimpleMDE) => void; + static drawHorizontalRule: (editor: SimpleMDE) => void; + static togglePreview: (editor: SimpleMDE) => void; + static toggleSideBySide: (editor: SimpleMDE) => void; + static toggleFullScreen: (editor: SimpleMDE) => void; + static undo: (editor: SimpleMDE) => void; + static redo: (editor: SimpleMDE) => void; +} \ No newline at end of file diff --git a/slate-irc/slate-irc.d.ts b/slate-irc/slate-irc.d.ts index 5f9d947bca..4bd6957a93 100644 --- a/slate-irc/slate-irc.d.ts +++ b/slate-irc/slate-irc.d.ts @@ -23,9 +23,16 @@ declare module "slate-irc" { motd: string[]; } + interface TopicEvent { + nick: string; + hostmask: string; + channel: string; + topic: string; + } + interface MessageEvent { from: string; - hostmask: any; + hostmask: string; to: string; message: string; } @@ -48,6 +55,18 @@ declare module "slate-irc" { new: string; } + interface ModeEvent { + nick: string; + target: string; + mode: string; + client: string; + } + + interface AwayEvent { + nick: string; + message: string; + } + interface QuitEvent { nick: string; hostmask: string; @@ -87,9 +106,12 @@ declare module "slate-irc" { on(event: "message", callback: (event: MessageEvent) => void): void; on(event: "notice", callback: (event: MessageEvent) => void): void; on(event: "motd", callback: (event: MOTDEvent) => void): void; + on(event: "topic", callback: (event: TopicEvent) => void): void; on(event: "join", callback: (event: JoinEvent) => void): void; on(event: "part", callback: (event: PartEvent) => void): void; on(event: "nick", callback: (event: NickEvent) => void): void; + on(event: "mode", callback: (event: ModeEvent) => void): void; + on(event: "away", callback: (event: AwayEvent) => void): void; on(event: "quit", callback: (event: QuitEvent) => void): void; } } diff --git a/sleep/sleep-tests.ts b/sleep/sleep-tests.ts new file mode 100644 index 0000000000..2d2c05c2ff --- /dev/null +++ b/sleep/sleep-tests.ts @@ -0,0 +1,6 @@ +/// + +import sleep = require("sleep"); + +sleep.sleep(1); +sleep.usleep(5000); \ No newline at end of file diff --git a/sleep/sleep.d.ts b/sleep/sleep.d.ts new file mode 100644 index 0000000000..5173e4b4ef --- /dev/null +++ b/sleep/sleep.d.ts @@ -0,0 +1,26 @@ +// Type definitions for node-scanf +// Project: https://github.com/ErikDubbelboer/node-sleep +// Definitions by: Jeongho Nam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace __node_sleep +{ + /** + * Sleep for n seconds. + * + * @param n Number of seconds to sleep. + */ + function sleep(n: number): void; + + /** + * Sleep for n microseconds. + * + * @param n Number of microseconds to sleep; 1 second is 1,000,000 microseconds. + */ + function usleep(n: number): void; +} + +declare module "sleep" +{ + export = __node_sleep; +} \ No newline at end of file diff --git a/slick-carousel/slick-carousel.d.ts b/slick-carousel/slick-carousel.d.ts index 7f470c34a0..7d79293330 100644 --- a/slick-carousel/slick-carousel.d.ts +++ b/slick-carousel/slick-carousel.d.ts @@ -38,34 +38,34 @@ interface JQuerySlickOptions { arrows?: boolean; /** - * Set the slider to be the navigation of other slider (Class or ID Name) + * Set the slider to be the navigation of other slider * Default: null */ - asNavFor?: string; + asNavFor?: Element | JQuery | string; /** * Change where the navigation arrows are attached (Selector, htmlString, Array, Element, jQuery object) * Default: $(element) */ - appendArrows?: any; + appendArrows?: Element | Element[] | JQuery | string; /** * Change where the navigation dots are attached (Selector, htmlString, Array, Element, jQuery object) * Default: $(element) */ - appendDots?: any; + appendDots?: Element | Element[] | JQuery | string; /** * Allows you to select a node or customize the HTML for the "Previous" arrow. * Default: */ - prevArrow?: string | Object; + prevArrow?: Element | JQuery | string; /** * Allows you to select a node or customize the HTML for the "Next" arrow. * Default: */ - nextArrow?: string | Object; + nextArrow?: Element | JQuery | string; /** * Enables centered view with partial prev/next slides. Use with odd numbered slidesToShow counts. diff --git a/slickgrid/SlickGrid-tests.ts b/slickgrid/SlickGrid-tests.ts index e267a85948..5221f7c19d 100644 --- a/slickgrid/SlickGrid-tests.ts +++ b/slickgrid/SlickGrid-tests.ts @@ -155,8 +155,6 @@ grid.getCellCssStyles("test")[0]["number_column"]; grid.getCellEditor(); -grid.getCellFromEvent(new Slick.Event()); - grid.getCellFromPoint(5, 10); grid.getCellNode(5, 10); @@ -210,3 +208,8 @@ columns.forEach(column => { grid.onSort.subscribe((e, args) => { var sortCol:string = args.sortCols[0].sortCol.field; }); + +grid.onMouseEnter.subscribe((e: DOMEvent, args: Slick.OnMouseEnterEventArgs) => { + let cell: Slick.Cell = args.grid.getCellFromEvent(e); + if (!cell) { return; } +}); diff --git a/slickgrid/SlickGrid.d.ts b/slickgrid/SlickGrid.d.ts index 96f91eaaf1..bae31aab21 100644 --- a/slickgrid/SlickGrid.d.ts +++ b/slickgrid/SlickGrid.d.ts @@ -92,14 +92,16 @@ declare namespace Slick { * @method subscribe * @param fn {Function} Event handler. */ - public subscribe(fn: (eventData: EventData, data: T) => any ): void; + public subscribe(fn: (e: EventData, data: T) => any): void; + public subscribe(fn: (e: DOMEvent, data: T) => any): void; /*** * Removes an event handler added with subscribe(fn). * @method unsubscribe * @param fn {Function} Event handler to be removed. */ - public unsubscribe(fn: (eventData: EventData, data: T) => any ): void; + public unsubscribe(fn: (e: EventData, data: T) => any): void; + public unsubscribe(fn: (e: DOMEvent, data: T) => any): void; /*** * Fires an event notifying all subscribers. @@ -1037,7 +1039,7 @@ declare namespace Slick { * @param e A standard W3C/jQuery event. * @return **/ - public getCellFromEvent(e: Event): Cell; // todo: !! Unsure on return type !! + public getCellFromEvent(e: DOMEvent): Cell; /** * Returns a hash containing row and cell indexes. Coordinates are relative to the top left corner of the grid beginning with the first row (not including the column headers). @@ -1045,7 +1047,7 @@ declare namespace Slick { * @param y A y coordinate. * @return **/ - public getCellFromPoint(x: number, y: number): Cell; // todo: !! Unsure on return type !! + public getCellFromPoint(x: number, y: number): Cell; /** * Returns a DOM element containing a cell at a given row and cell. diff --git a/smart-fox-server/smart-fox-server-tests.ts b/smart-fox-server/smart-fox-server-tests.ts new file mode 100644 index 0000000000..b4eb83e63b --- /dev/null +++ b/smart-fox-server/smart-fox-server-tests.ts @@ -0,0 +1,112 @@ +/// + +function test_Vec3D() { + var Vec3D: SFS2X.Entities.Data.Vec3D = new SFS2X.Entities.Data.Vec3D(0, 0, 0); + var Vec3Dalt: SFS2X.Entities.Data.Vec3D = new SFS2X.Entities.Data.Vec3D(0, 0); + + var positionX: number = Vec3D.px; + var positionY: number = Vec3D.py; + var positionZ: number = Vec3D.pz; + + var isFloat: boolean = Vec3D.isFloat(); + + return Vec3D; +}; + +function test_MatchExpression() { + + var exp = new SFS2X.Entities.Match.MatchExpression('rank', SFS2X.Entities.Match.NumberMatch.GREATER_THAN, 5) + .and('country', SFS2X.Entities.Match.StringMatch.EQUALS, 'Italy'); + + var exp = new SFS2X.Entities.Match.MatchExpression(SFS2X.Entities.Match.RoomProperties.IS_GAME, SFS2X.Entities.Match.BoolMatch.EQUALS, true) + .and(SFS2X.Entities.Match.RoomProperties.HAS_FREE_PLAYER_SLOTS, SFS2X.Entities.Match.BoolMatch.EQUALS, true) + .and('isGameStarted', SFS2X.Entities.Match.BoolMatch.EQUALS, false); + + var exp = new SFS2X.Entities.Match.MatchExpression('avatarData.shield.inUse', SFS2X.Entities.Match.BoolMatch.EQUALS, true); + + var exp = new SFS2X.Entities.Match.MatchExpression('avatarData.weapons.3.name', SFS2X.Entities.Match.StringMatch.EQUALS, "Narsil"); +} + +function test_MMOItemVariable() { + var MMOItemVar1: SFS2X.Entities.Variables.MMOItemVariable = new SFS2X.Entities.Variables.MMOItemVariable('string', 'vlaue'); + var MMOItemVar2: SFS2X.Entities.Variables.MMOItemVariable = new SFS2X.Entities.Variables.MMOItemVariable('string', 'vlaue', 2); + + var MMOItemTypeName: string = MMOItemVar1.getTypeName(1); + var MMOItemisNull: boolean = MMOItemVar1.isNull(); + var MMOItemString: string = MMOItemVar1.toString(); + + var name: string = MMOItemVar1.name; + var value: any = MMOItemVar1.value; + + return MMOItemVar1; +} + +function test_BuddyListAddBuddyRequest() { + var sfs = new SFS2X.SmartFox(); + sfs.send(new SFS2X.Requests.BuddyList.AddBuddyRequest('John')); +} + +function test_BuddyListBlockBuddyRequest() { + var sfs = new SFS2X.SmartFox(); + sfs.send(new SFS2X.Requests.BuddyList.BlockBuddyRequest('John', true)); +} + +function test_BuddyListGoOnlineRequest() { + var sfs = new SFS2X.SmartFox(); + sfs.send(new SFS2X.Requests.BuddyList.GoOnlineRequest(true)); +} + +function test_BuddyListInitBuddyListRequest() { + var sfs = new SFS2X.SmartFox(); + sfs.send(new SFS2X.Requests.BuddyList.InitBuddyListRequest()); +} + +function test_BuddyListRemoveBuddyRequest() { + var sfs = new SFS2X.SmartFox(); + sfs.send(new SFS2X.Requests.BuddyList.RemoveBuddyRequest('John')); +} + +function test_BuddyListSetBuddyVariablesRequest() { + var sfs = new SFS2X.SmartFox(); + sfs.send(new SFS2X.Requests.BuddyList.SetBuddyVariablesRequest([])); +} + +function test_GameCreateSFSGameRequest() { + var sfs = new SFS2X.SmartFox(); + var settings = new SFS2X.Requests.Game.SFSGameSettings("DartsGame"); + settings.maxUsers = 2; + settings.maxSpectators = 8; + settings.isPublic = true; + settings.minPlayersToStartGame = 2; + settings.notifyGameStarted = true; + + sfs.send(new SFS2X.Requests.Game.CreateSFSGameRequest(settings)); +} + +function test_ErrorCodes() { + SFS2X.ErrorCodes.setErrorMessage(13, "Le Groupe demandé n'est pas disponible - Salle: {0}; Groupe: {1}"); +} + +function test_SmartFoxaddEventListener() { + var sfs = new SFS2X.SmartFox(); + + function onConnection(event: SFS2X.ICONNECTION) { + if(event.success) + { + // On Success + } + }; + function onConnectionLost(event: SFS2X.ICONNECTION_LOST) { + // Print why connection was lost + console.log(event.reason); + }; + function onLoginError(event: SFS2X.ILOGIN_ERROR) { + if (event.errorCode) + { + // handle error + } + }; + sfs.addEventListener(SFS2X.SFSEvent.CONNECTION, onConnection, this); + sfs.addEventListener(SFS2X.SFSEvent.CONNECTION_LOST, onConnectionLost, this); + sfs.addEventListener(SFS2X.SFSEvent.LOGIN_ERROR, onLoginError, this); +} diff --git a/smart-fox-server/smart-fox-server.d.ts b/smart-fox-server/smart-fox-server.d.ts new file mode 100644 index 0000000000..137040b489 --- /dev/null +++ b/smart-fox-server/smart-fox-server.d.ts @@ -0,0 +1,2411 @@ +// Type definitions for SmartFoxServer Apis +// Project: http://docs2x.smartfoxserver.com/api-docs/jsdoc/ +// Definitions by: Gregory Moore +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +//#region SFX2X + +// http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.html +declare namespace SFS2X { + //#region Entities + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.html + namespace Entities { + + //#region Data + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Data.html + namespace Data { + + //#region Vec3D + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Data.Vec3D.html + export class Vec3D { + + /** @type {number} Returns the position along the X axis. */ + px: number; + /** @type {number} Returns the position along the Y axis. */ + py: number; + /** @type {number} Returns the position along the Z axis. */ + pz: number; + + /** + * Creates a new Vec3D instance. + * @param {number} px The position along the X axis. + * @param {number} py The position along the Y axis. + * @param {number} [pz] The position along the Z axis. + */ + constructor(px: number, py: number, pz?: number); + /** + * Indicates whether the position is expressed using floating point values or not. + * @return {boolean} Returns: true if the position is expressed using floating point values. + */ + isFloat(): boolean; + } + //#endregion + + } + //#endregion + //#region Invitation + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Invitation.html + namespace Invitation { + + //#region InvitationReply + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Invitation.InvitationReply.html + export class InvitationReply { + + /** @type {number} Invitation is accepted. */ + static ACCEPT: number; + /** @type {number} Invitation is refused. */ + static REFUSE: number; + + } + + //#endregion + + //#region SFSInvitation + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Invitation.SFSInvitation.html + export class SFSInvitation { + + /** @type {number} Indicates the id of the invitation. */ + id: number; + /** @type {SFSUser} Returns the SFSUser object corresponding to the user who received the invitation. */ + invitee: SFSUser; + /** @type {SFSUser} Returns the SFSUser object corresponding to the user who sent the invitation. */ + inviter: SFSUser; + /** @type {Object} Returns an object containing a custom set of parameters. */ + params: Object; + /** @type {number} Returns the number of seconds available to the invitee to reply to the invitation, after which the invitation expires. */ + secondsForAnswer: number; + + /** + * Creates a new SFSInvitation instance. + * @param {SFSUser} inviter A SFSUser object corresponding to the user who sent the invitation. + * @param {SFSUser} invitee A SFSUser object corresponding to the user who received the invitation. + * @param {number} secondsForAnswer The number of seconds available to the invitee to reply to the invitation. + * @param {Object} params An object containing a custom set of parameters representing the invitation details. + */ + constructor(inviter: SFSUser, invitee: SFSUser, secondsForAnswer: number, params: Object); + } + + //#endregion + + } + //#endregion + //#region Match + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Match.html + namespace Match { + + //#region BoolMatch + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Match.BoolMatch.html + export class BoolMatch { + + /** @type {BoolMatch} An instance of BoolMatch representing the following condition: bool1 == bool2. */ + static EQUALS: BoolMatch; + /** @type {BoolMatch} An instance of BoolMatch representing the following condition: bool1 != bool2. */ + static NOT_EQUALS: BoolMatch; + + } + + //#endregion + //#region LogicOperator + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Match.LogicOperator.html + export class LogicOperator { + + /** @type {LogicOperator} An instance of LogicOperator representing the AND logical operator. */ + static AND: LogicOperator; + /** @type {LogicOperator} An instance of LogicOperator representing the OR logical operator. */ + static OR: LogicOperator; + + } + + //#endregion + //#region MatchExpression + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Match.MatchExpression.html + export class MatchExpression { + + /** @type {(RoomProperties | UserProperties | BoolMatch | NumberMatch | StringMatch | Requests.Game.CreateSFSGameRequest | Requests.System.FindRoomsRequest | Requests.System.FindUsersRequest)} Returns the matching criteria used during values comparison among those provided by the BoolMatch, NumberMatch and StringMatch classes. */ + condition: RoomProperties | UserProperties | BoolMatch | NumberMatch | StringMatch | Requests.Game.CreateSFSGameRequest | Requests.System.FindRoomsRequest | Requests.System.FindUsersRequest; + /** @type {LogicOperator} In case of concatenated expressions, returns the current logical operator. */ + loginOp: LogicOperator; + /** @type {MatchExpression} Returns the next matching expression concatenated to the current one, if existing. */ + next: MatchExpression; + /** @type {any} Returns the value against which the variable or property corresponding to varName is compared. */ + value: any; + /** @type {string} Returns the name of the variable or property against which the comparison is made. */ + varName: string; + + /** + * Creates a new MatchExpression instance. + * @param {string} varName Name of the variable or property to match. + * @param {(RoomProperties | UserProperties | BoolMatch | NumberMatch | StringMatch | Requests.Game.CreateSFSGameRequest | Requests.System.FindRoomsRequest | Requests.System.FindUsersRequest)} condition A matching condition among those provided by the BoolMatch, NumberMatch and StringMatch classes. + * @param {any} value The value to compare against the variable or property during the matching. + */ + constructor(varName: string, condition: RoomProperties | UserProperties | BoolMatch | NumberMatch | StringMatch | Requests.Game.CreateSFSGameRequest | Requests.System.FindRoomsRequest | Requests.System.FindUsersRequest, value: any); + /** + * Concatenates the current expression with a new one using the logical AND operator. + * @param {string} varName Name of the additional variable or property to match. + * @param {(RoomProperties | UserProperties | BoolMatch | NumberMatch | StringMatch | Requests.Game.CreateSFSGameRequest | Requests.System.FindRoomsRequest | Requests.System.FindUsersRequest)} condition The additional matching condition among those provided by the BoolMatch, NumberMatch and StringMatch classes. + * @param {any} value The value to compare against the additional variable or property during the matching. + * @return {MatchExpression} A new MatchExpression resulting from the concatenation of the current expression with a new one generated from the specified parameters. + */ + and(varName: string, condition: RoomProperties | UserProperties | BoolMatch | NumberMatch | StringMatch | Requests.Game.CreateSFSGameRequest | Requests.System.FindRoomsRequest | Requests.System.FindUsersRequest, value: any): MatchExpression; + /** + * Checks if the current matching expression is concatenated to another one through a logical operator. + * @return {boolean} Returns: true if the current matching expression is concatenated to another one. + + */ + hasNext(): boolean; + /** + * Concatenates the current expression with a new one using the logical OR operator. + * @param {string} varName Name of the additional variable or property to match. + * @param {(RoomProperties | UserProperties | BoolMatch | NumberMatch | StringMatch | Requests.Game.CreateSFSGameRequest | Requests.System.FindRoomsRequest | Requests.System.FindUsersRequest)} condition The additional matching condition among those provided by the BoolMatch, NumberMatch and StringMatch classes. + * @param {any} value The value to compare against the additional variable or property during the matching. + * @return {MatchExpression} A new MatchExpression resulting from the concatenation of the current expression with a new one generated from the specified parameters. + */ + or(varName: string, condition: RoomProperties | UserProperties | BoolMatch | NumberMatch | StringMatch | Requests.Game.CreateSFSGameRequest | Requests.System.FindRoomsRequest | Requests.System.FindUsersRequest, value: any): MatchExpression; + /** + * Moves the iterator cursor to the first matching expression in the chain. + * @return {MatchExpression} The MatchExpression object at the top of the chain of matching expressions. + */ + rewind(): MatchExpression; + /** + * Returns a string representation of the matching expression. + * @return {string} The string representation of the MatchExpression object. + */ + toString(): string; + } + + //#endregion + //#region NumberMatch + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Match.NumberMatch.html + export class NumberMatch { + + /** @type {NumberMatch} An instance of NumberMatch representing the following condition: number1 == number2. */ + static EQUALS: NumberMatch; + /** @type {NumberMatch} An instance of NumberMatch representing the following condition: number1 > number2. */ + static GREATER_THAN: NumberMatch; + /** @type {NumberMatch} An instance of NumberMatch representing the following condition: number1 >= number2. */ + static GREATER_THAN_OR_EQUAL_TO: NumberMatch; + /** @type {NumberMatch} An instance of NumberMatch representing the following condition: number1 < number2. */ + static LESS_THAN: NumberMatch; + /** @type {NumberMatch} An instance of NumberMatch representing the following condition: number1 <= number2. */ + static LESS_THAN_OR_EQUAL_TO: NumberMatch; + /** @type {NumberMatch} An instance of NumberMatch representing the following condition: number1 != number2. */ + static NOT_EQUALS: NumberMatch; + + } + + //#endregion + //#region RoomProperties + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Match.RoomProperties.html + export class RoomProperties { + + /** @type {string} The name of the Group to which the Room belongs. */ + static GROUP_ID: string; + /** @type {string} The Room has at least one free player slot. */ + static HAS_FREE_PLAYER_SLOTS: string; + /** @type {string} The Room is a Game Room. */ + static IS_GAME: string; + /** @type {string} The Room is private. */ + static IS_PRIVATE: string; + /** @type {string} The Room is an SFSGame on the server-side. */ + static IS_TYPE_SFSGAME: string; + /** @type {string} The maximum number of spectators allowed in the Room (Game Rooms only). */ + static MAX_SPECTATORS: string; + /** @type {string} The maximum number of users allowed in the Room (players in Game Rooms). */ + static MAX_USERS: string; + /** @type {string} The Room name. */ + static NAME: string; + /** @type {string} The Room spectators count (Game Rooms only). */ + static SPECTATOR_COUNT: string; + /** @type {string} The Room users count (players in Game Rooms). */ + static USER_COUNT: string; + + } + + //#endregion + //#region StringMatch + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Match.StringMatch.html + export class StringMatch { + + /** @type {StringMatch} An instance of StringMatch representing the following condition: string1.indexOf(string2) != -1 */ + static CONTAINS: StringMatch; + /** @type {StringMatch} An instance of StringMatch representing the following condition: string1 ends with characters contained in string2. */ + static ENDS_WITH: StringMatch; + /** @type {StringMatch} An instance of StringMatch representing the following condition: string1 == string2. */ + static EQUALS: StringMatch; + /** @type {StringMatch} An instance of StringMatch representing the following condition: string1 != string2. */ + static NOT_EQUALS: StringMatch; + /** @type {StringMatch} An instance of StringMatch representing the following condition: string1 starts with characters contained in string2. */ + static STARTS_WITH: StringMatch; + + } + + //#endregion + //#region UserProperties + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Match.UserProperties.html + export class UserProperties { + + /** @type {string} The user joined at least one Room. */ + static IS_IN_ANY_ROOM: string; + /** @type {string} The user is a Non-Player Character (NPC). */ + static IS_NPC: string; + /** @type {string} The user is a player in a Game Room. */ + static IS_PLAYER: string; + /** @type {string} The user is a spectator in a Game Room. */ + static IS_SPECTATOR: string; + /** @type {string} The user name. */ + static NAME: string; + /** @type {string} The user privilege id. */ + static PRIVILEGE_ID: string; + + } + + //#endregion + + } + //#endregion + //#region MMOItem + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.MMOItem.html + export class MMOItem { + + /** @type {Data.Vec3D} Returns the entry point of this item in the current user's AoI. */ + aoiEnteryPoint: Data.Vec3D; + /** @type {number} Indicates the id of this item. */ + id: number; + + /** + * Creates a new MMOItem instance. + * @param {number} id The item id. + */ + constructor(id: number); + /** + * Indicates whether this item has the specified MMOItem Variable set or not. + * @param {string} varName The name of the MMOItem Variable whose existance must be checked. + * @return {boolean} Returns: true if an MMOItem Variable with the passed name is set for this item. + */ + containsVariable(varName: string): boolean; + /** + * Retrieves an MMOItem Variable from its name. + * @param {string} varName The name of the MMOItem Variable to be retrieved. + * @return {Variables.MMOItemVariable} The MMOItemVariable object, or null if no MMOItem Variable with the passed name is associated to this item. + */ + getVariable(varName: string): Variables.MMOItemVariable; + /** + * Retrieves all the MMOItem Variables of this item. + * @return {Variables.MMOItemVariable[]} The list of MMOItemVariable objects associated to this item. + */ + getVariables(): Variables.MMOItemVariable[]; + /** + * Returns a string that contains the item id. + * @return {string} Returns: The string representation of the MMOItem object. + */ + toString(): string; + + } + + //#endregion + //#region MMORoom + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.MMORoom.html + export class MMORoom extends SFSRoom { + + /** @type {Data.Vec3D} Returns the default Area of Interest (AoI) of this MMORoom. */ + defaultAOI: Data.Vec3D; + /** @type {Requests.MMO.MapLimits} Returns the higher coordinates limit of the virtual environment represented by the MMORoom along the X,Y,Z axes. If null is returned, no limits were set at Room creation time. */ + higherMapLimit: Requests.MMO.MapLimits; + /** @type {Requests.MMO.MapLimits} Returns the lower coordinates limit of the virtual environment represented by the MMORoom along the X,Y,Z axes. If null is returned, no limits were set at Room creation time. */ + lowerMapLimit: Requests.MMO.MapLimits; + + /** + * Creates a new MMORoom instance. + * @param {number} id The MMORoom id. + * @param {string} name The MMORoom name. + * @param {string} groupId The id of the Group to which the MMORoom belongs. + */ + constructor(id: number, name: string, groupId?: string); + /** + * Retrieves an MMOItem object from its id property. The item is available to the current user if it falls within his Area of Interest only. + * @param {number} id The id of the item to be retrieved. + * @return {MMOItem} Returns: An MMOItem object, or null if the item with the passed id is not in proximity of the current user. + + */ + getMMOItem(id: number): MMOItem; + /** + * Retrieves all MMOItem object in the MMORoom that fall within the current user's Area of Interest. + * @return {MMOItem[]} Returns: A list of MMOItem objects, or an empty list if no item is in proximity of the current user. + */ + getMMOItems(): MMOItem[]; + } + + //#endregion + //#region SFSBuddy + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.SFSBuddy.html + export class SFSBuddy { + + /** @type {number} Indicates the id of this buddy. */ + id: number; + /** @type {string} Indicates the name of this buddy. */ + name: string; + + /** + * Creates a new SFSBuddy instance. + * @param {number} id The buddy id. + * @param {string} name The buddy name. + * @param {boolean} [isBlocked=false] If true, the buddy is blocked by the current user. + * @param {boolean} [isTemp=false] If true, the buddy is just temporary in the current user's buddy list. + */ + constructor(id: number, name: string, isBlocked?: boolean, isTemp?: boolean); + /** + * Indicates whether this user has the specified Buddy Variable set or not. + * @param {string} varName The name of the Buddy Variable whose existance must be checked. + * @return {boolean} Returns: true if a Buddy Variable with the passed name is set for this buddy. + */ + containsVariable(varName: string): boolean; + /** + * Returns the nickname of this buddy. If the nickname is not set, null is returned. + * @return {string} Returns: The nickname of the buddy. + */ + getNickName(): string; + /** + * Retrieves the list of persistent Buddy Variables for this buddy. + * @return {Variables.SFSBuddyVariable[]} Returns: An array of SFSBuddyVariable objects. + */ + getOfflineVariables(): Variables.SFSBuddyVariable[]; + /** + * Retrieves the list of non-persistent Buddy Variables for this buddy. + * @return {Variables.SFSBuddyVariable[]} Returns: An array of SFSBuddyVariable objects. + */ + getOnlineVariables(): Variables.SFSBuddyVariable[]; + /** + * Returns the custom state of this buddy. Examples of custom states are "Available", "Busy", "Be right back", etc. If the custom state is not set, null is returned. + * @return {string} Returns: The custom state of the buddy. + */ + getState(): string; + /** + * Retrieves a Buddy Variable from its name. + * @param {string} varName The name of the Buddy Variable to be retrieved. + * @return {Variables.SFSBuddyVariable} Returns: The object representing the Buddy Variable, or null if no Buddy Variable with the passed name is associated to this buddy. + */ + getVariable(varName: string): Variables.SFSBuddyVariable; + /** + * Retrieves all the Buddy Variables of this user. + * @return {Variables.SFSBuddyVariable[]} Returns: The list of SFSBuddyVariable objects associated to the buddy. + */ + getVariables(): Variables.SFSBuddyVariable[]; + /** + * Indicates whether this buddy is blocked in the current user's buddy list or not. A buddy can be blocked by means of a BlockBuddyRequest request. + * @return {boolean} Returns: true if the buddy is blocked. + */ + isBlocked(): boolean; + /** + * Indicates whether this buddy is online in the Buddy List system or not. + * @return {boolean} Returns: true if the buddy is online. + */ + isOnline(): boolean; + /** + * Indicates whether this buddy is temporary (non-persistent) in the current user's buddy list or not. + * @return {boolean} Returns: true if the buddy is temporary. + */ + isTemp(): boolean; + /** + * Returns a string that contains the buddy id and name. + * @return {string} Returns: The string representation of the SFSBuddy object. + */ + toString(): string; + + } + + //#endregion + //#region SFSRoom + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.SFSRoom.html + export class SFSRoom { + + /** @type {string} Returns the Room Group name. */ + groupId: string; + /** @type {number} Indicates the id of this Room. */ + id: number; + /** @type {boolean} Indicates whether this is a Game Room or not. */ + isGame: boolean; + /** @type {boolean} Indicates whether this Room is hidden or not. */ + isHidden: boolean; + /** @type {boolean} Indicates whether the client joined this Room or not. */ + isJoined: boolean; + /** @type {boolean} Indicates whether this Room requires a password to be joined or not. */ + isPasswordProtected: boolean; + /** @type {number} Returns the maximum number of spectators allowed in this Room (Game Rooms only). */ + maxSpectators: number; + /** @type {number} Returns the maximum number of users allowed in this Room. */ + maxUsers: number; + /** @type {string} Indicates the name of this Room. */ + name: string; + /** @type {Object} Defines a generic utility object that can be used to store custom Room data. */ + properties: Object; + + /** + * Creates a new SFSRoom instance. + * @param {number} id The Room id. + * @param {string} name The Room name. + * @param {string} [groupId="default"] The id of the Group to which the Room belongs. + */ + constructor(id: number, name: string, groupId?: string); + /** + * Indicates whether the specified user is currently inside this Room or not. + * @param {SFSUser} user The SFSUser object representing the user whose presence in this Room must be checked. + * @return {boolean} Returns: true if the user is inside this Room; false otherwise. + */ + containsUser(user: SFSUser): boolean; + /** + * Indicates whether this Room has the specified Room Variable set or not. + * @param {string} varName The name of the Room Variable whose existance in this Room must be checked. + * @return {boolean} Returns: true if a Room Variable with the passed name exists in this Room. + */ + containsVariable(varName: string): boolean; + /** + * Returns the maximum amount of users, including spectators, that can be contained in this Room. + * @return {number} Returns: Maximum number of users that can enter the Room. + */ + getCapacity(): number; + /** + * Retrieves the list of SFSUser objects representing the players currently inside this Room (Game Rooms only). + * @return {SFSUser[]} Returns: The list of SFSUser objects representing the users who joined the Room as players. + */ + getPlayerList(): SFSUser[]; + /** + * Retrieves a reference to the Room Manager which manages this Room. + * @return {Managers.RoomManager} Returns: The Room Manager to which this Room is associated. + */ + getRoomManager(): Managers.RoomManager; + /** + * Returns the current number of spectators in this Room (Game Rooms only). + * @return {number} Returns: Current number of spectators in the Room. + */ + getSpectatorCount(): number; + /** + * Retrieves the list of SFSUser objects representing the spectators currently inside this Room (Game Rooms only). + * @return {SFSUser[]} Returns: The list of SFSUser objects representing the users who joined the Room as spectators. + */ + getSpectatorList(): SFSUser[]; + /** + * Retrieves a SFSUser object from its id property. + * @param {number} id The id of the user to be found. + * @return {SFSUser} Returns: An object representing the user, or null if no user with the passed id exists in this Room. + */ + getUserById(id: number): SFSUser; + /** + * Retrieves a SFSUser object from its name property. + * @param {string} name The name of the user to be found. + * @return {SFSUser} Returns: An object representing the user, or null if no user with the passed name exists in this Room. + */ + getUserByName(name: string): SFSUser; + /** + * Returns the current number of users in this Room. In case of Game Rooms, this is the number of players. + * @return {number} Returns: Current number of users in the Room. + */ + getUserCount(): number; + /** + * Returns the current number of users in this Room. In case of Game Rooms, this is the number of players. + * @return {SFSUser[]} Returns: Current number of users in the Room. + */ + getUserList(): SFSUser[]; + /** + * Retrieves a Room Variable from its name. + * @param {string} varName The name of the Room Variable to be retrieved. + * @return {Variables.SFSRoomVariable} Returns: The object representing the Room Variable, or null if no Room Variable with the passed name exists in this Room. + */ + getVariable(varName: string): Variables.SFSRoomVariable; + /** + * Retrieves all the Room Variables of this Room. + * @return {Variables.SFSRoomVariable[]} Returns: The list of SFSRoomVariable objects associated with this Room. + */ + getVariables(): Variables.SFSRoomVariable[]; + /** + * Returns a string that contains the Room id, name and id of the Group to which it belongs. + * @return {string} Returns: The string representation of the SFSRoom object. + */ + toString(): string; + + } + + //#endregion + //#region SFSUser + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.SFSUser.html + export class SFSUser { + + /** @type {Data.Vec3D} Returns the entry point of this user in the current user's AoI. */ + aoiEntryPoint: Data.Vec3D; + /** @type {number} Indicates the id of this user. It is unique and it is generated by the server when the user is created. */ + id: number; + /** @type {boolean} Indicates if this SFSUser object represents the current client. */ + isItMe: boolean; + /** @type {string} Indicates the name of this user. Two users in the same Zone can't have the same name. */ + name: string; + /** @type {number} Returns the id which identifies the privilege level of this user. */ + privilegeId: number; + /** @type {Object} Defines a generic utility object that can be used to store custom user data. The values added to this object are for client-side use only and are never transmitted to the server or to the other clients. */ + properties: Object; + + /** + * Creates a new SFSUser instance. + * @param {number} id The user id. + * @param {string} name The user name. + * @param {boolean} [isItMe=false] If true, the user being created corresponds to the current client. + */ + constructor(id: number, name: string, isItMe?: boolean); + /** + * Indicates whether this user has the specified User Variable set or not. + * @param {string} varName The name of the User Variable whose existance must be checked. + * @return {boolean} Returns: true if a User Variable with the passed name is set for this user. + */ + containsVariable(varName: string): boolean; + /** + * Returns the playerId value of this user in the passed Room. See the playerId property description for more informations. + * @param {SFSRoom} room The SFSRoom object representing the Room to retrieve the player id from. + * @return {number} Returns: The playerId of this user in the passed Room. + */ + getPlayerId(room: SFSRoom): number; + /** + * Returns a reference to the User Manager which manages this user. + * @return {Managers.UserManager} Returns: The User Manager to which this user is associated. + */ + getUserManager(): Managers.UserManager; + /** + * Retrieves a User Variable from its name. + * @param {string} varName The name of the User Variable to be retrieved. + * @return {Variables.SFSUserVariable} Returns: The object representing the User Variable, or null if no User Variable with the passed name is associated with this user. + */ + getVariable(varName: string): Variables.SFSUserVariable; + /** + * Retrieves all the User Variables of this user. + * @return {Variables.SFSUserVariable[]} Returns: The list of SFSUserVariable objects associated with the user. + */ + getVariables(): Variables.SFSUserVariable[]; + /** + * Indicates whether this user logged in as an administrator or not. Administrator users have the privilegeId property set to UserPrivileges.ADMINISTRATOR. + * @return {boolean} Returns: true if this user is an administrator. + */ + isAdmin(): boolean; + /** + * Indicates whether this user logged in as a guest or not. Guest users have the privilegeId property set to UserPrivileges.GUEST. + * @return {boolean} Returns: true if this user is a guest. + */ + isGuest(): boolean; + /** + * Indicates whether this user joined the passed Room or not. + * @param {SFSRoom} room The SFSRoom object representing the Room where to check the user presence. + * @return {boolean} Returns: true if this user is inside the passed Room. + */ + isJoinedInRoom(room: SFSRoom): boolean; + /** + * Indicates whether this user logged in as a moderator or not. Moderator users have the privilegeId property set to UserPrivileges.MODERATOR. + * @return {boolean} Returns: true if this user is a moderator. + */ + isModerator(): boolean; + /** + * Indicates whether this user is a player (playerId greater than 0) in the last joined Room or not. Non-Game Rooms always return false. + * @return {boolean} Returns: true if this user is a player in the last joined Room. + */ + isPlayer(): boolean; + /** + * Indicates whether this user is a player (playerId greater than 0) in the passed Room or not. Non-Game Rooms always return false. + * @param {SFSRoom} room The SFSRoom object representing the Room where to check if this user is a player. + * @return {boolean} Returns: true if this user is a player in the passed Room. + */ + isPlayerInRoom(room: SFSRoom): boolean; + /** + * Indicates whether this user is a spectator (playerId lower than 0) in the last joined Room or not. Non-Game Rooms always return false. + * @return {boolean} Returns: true if this user is a spectator in the last joined Room. + */ + isSpectator(): boolean; + /** + * Indicates whether this user is a spectator (playerId lower than 0) in the passed Room or not. Non-Game Rooms always return false. + * @param {SFSRoom} room The SFSRoom object representing the Room where to check if this user is a spectator. + * @return {boolean} Returns: true if this user is a spectator in the passed Room. + */ + isSpectatorInRoom(room: SFSRoom): boolean; + /** + * Indicates whether this user logged in as a standard user or not. Standard users have the privilegeId property set to UserPrivileges.STANDARD. + * @return {boolean} Returns: true if this user is a standard user. + */ + isStandardUser(): boolean; + /** + * Returns a string that contains the user id, name and a boolean indicating if the SFSUser object represents the current client. + * @return {string} Returns: The string representation of the SFSUser object. + */ + toString(): string; + + } + + //#endregion + //#region UserPrivileges + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.UserPrivileges.html + export class UserPrivileges { + + /** @type {number} The administrator user can send dedicated "administrator messages", kick and ban users. */ + static ADMINISTRATOR: number; + /** @type {number} The Guest user is usually the lowest level in the privilege profiles scale. */ + static GUEST: number; + /** @type {number} The moderator user can send dedicated "moderator messages", kick and ban users. */ + static MODERATOR: number; + /** @type {number} The standard user is usually registered in the application custom login system; uses a unique name and password to login. */ + static STANDARD: number; + + } + + //#endregion + //#region Variables + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Variables.html + namespace Variables { + + //#region MMOItemVariable + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Variables.MMOItemVariable.html + export class MMOItemVariable extends SFSUserVariable { + + /** + * Creates a new MMOItemVariable instance. + * @param {string} name The name of the MMOItem Variable. + * @param {any} value The value of the MMOItem Variable; valid data types are: Boolean, Number, String, Object, Array. The value can also be null. + * @param {number} [type=-1] The type id of the MMOItem Variable among those available in the VariableType class. Usually it is not necessary to pass this parameter, as the type is auto-detected from the value. + */ + constructor(name: string, value: any, type?: number); + /** + * Returns a string that contains the MMOItem Variable name, type and value. + * @return {string} Returns: The string representation of the MMOItemVariable object. + */ + toString(): string; + + } + //#endregion + //#region ReservedBuddyVariables + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Variables.ReservedBuddyVariables.html + export class ReservedBuddyVariables { + + /** @type {string} The Buddy Variable with this name stores the optional nickname of the user in a buddy list. This variable is persistent, which means that the nickname is preserved upon disconnection. */ + static BV_NICKNAME: string; + /** @type {string} The Buddy Variable with this name keeps track of the online/offline state of the user in a buddy list. This variable is persistent, which means that the online/offline state is preserved upon disconnection. */ + static BV_ONLINE: string; + /** @type {string} The Buddy Variable with this name stores the custom state of the user in a buddy list. This variable is persistent, which means that the custom state is preserved upon disconnection. */ + static BV_STATE: string; + + } + //#endregion + //#region ReservedRoomVariables + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Variables.ReservedRoomVariables.html + export class ReservedRoomVariables { + + /** @type {string} The Room Variable with this name keeps track of the state (started or stopped) of a game created with the CreateSFSGameRequest request. */ + static RV_GAME_STARTED: string; + + } + //#endregion + //#region SFSBuddyVariable + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Variables.SFSBuddyVariable.html + export class SFSBuddyVariable extends SFSUserVariable { + + /** @type {string} The prefix to be added to a Buddy Variable name to make it persistent. */ + static OFFLINE_PREFIX: string; + + /** + * Creates a new SFSBuddyVariable instance. + * @param {string} name The name of the Buddy Variable. + * @param {any} value The value of the Buddy Variable; valid data types are: Boolean, Number, String, Object, Array. The value can also be null. + * @param {number} [type=-1] The type id of the Buddy Variable among those available in the VariableType class. Usually it is not necessary to pass this parameter, as the type is auto-detected from the value. + */ + constructor(name: string, value: any, type?: number); + /** + * Indicates whether the Buddy Variable is persistent or not. + * @return {boolean} Returns: true if the Buddy Variable is persistent. + */ + isOffline(): boolean; + /** + * Returns a string that contains the Buddy Variable name, type and value. + * @return {string} Returns: The string representation of the SFSBuddyVariable object. + */ + toString(): string; + + } + //#endregion + //#region SFSRoomVariable + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Variables.SFSRoomVariable.html + export class SFSRoomVariable extends SFSUserVariable { + + /** @type {boolean} Indicates whether this Room Variable is persistent or not. */ + isPersistent: boolean; + /** @type {boolean} Indicates whether this Room Variable is private or not. */ + isPrivate: boolean; + + /** + * Creates a new SFSRoomVariable instance. + * @param {string} name The name of the Room Variable. + * @param {any} value The value of the Room Variable; valid data types are: Boolean, Number, String, Object, Array. The value can also be null. + * @param {number} [type=-1] The type id of the Room Variable among those available in the VariableType class. Usually it is not necessary to pass this parameter, as the type is auto-detected from the value. + */ + constructor(name: string, value: any, type?: number); + /** + * Returns a string that contains the Room Variable name, type, value and isPrivate flag. + * @return {string} Returns: The string representation of the SFSRoomVariable object. + */ + toString(): string; + + } + //#endregion + //#region SFSUserVariable + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Variables.SFSUserVariable.html + export class SFSUserVariable { + + /** @type {string} Indicates the name of this variable. */ + name: string; + /** @type {number} Returns the value of this variable. */ + value: number; + + /** + * Creates a new SFSUserVariable instance. + * @param {string} name The name of the User Variable. + * @param {any} value The value of the User Variable; valid data types are: Boolean, Number, String, Object, Array. The value can also be null. + * @param {number} [type=-1] The type id of the User Variable among those available in the VariableType class. Usually it is not necessary to pass this parameter, as the type is auto-detected from the value. + */ + constructor(name: string, value: any, type?: number); + /** + * Indicates the type of this variable. Possibly returned strings are: Null, Bool, Int, Double, String, Object, Array. + * @param {number} typeId The type id of the User Variable among those available in the VariableType class. + * @return {string} Returns: The variable type name. + */ + getTypeName(typeId: number): string; + /** + * Indicates if the variable is null. + * @return {boolean} Returns: true if the variable has a null value. + */ + isNull(): boolean; + /** + * Returns a string that contains the User Variable name, type and value. + * @return {string} Returns: The string representation of the SFSUserVariable object. + */ + toString(): string; + } + //#endregion + //#region VariableType + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Entities.Variables.VariableType.html + export class VariableType { + + /** @type {number} The type of the User/Room Variable is array. */ + static ARRAY: number; + /** @type {number} The type of the User/Room Variable is boolean. */ + static BOOL: number; + /** @type {number} The type of the User/Room Variable is number (specifically a double). */ + static DOUBLE: number; + /** @type {number} The type of the User/Room Variable is number (specifically an integer). */ + static INT: number; + /** @type {number} The User/Room Variable is null. */ + static NULL: number; + /** @type {number} The type of the User/Room Variable is object. */ + static OBJECT: number; + /** @type {number} The type of the User/Room Variable is string. */ + static STRING: number; + + } + //#endregion + + } + //#endregion + + } + //#endregion + //#region ErrorCodes + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.ErrorCodes.html + export class ErrorCodes { + + /** + * Sets the text of the error message corresponding to the passed error code. + * @param {number} code The code of the error message to be modified. + * @param {string} message The new error message, including the placeholders for runtime informations. + */ + static setErrorMessage(code: number, message: string): void; + + } + //#endregion + //#region Logger + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Logger.html + export class Logger { + + /** + * Sets the current logging level. + * @param {number} level The minimum logging level. + */ + setLevel(level: number): void; + + } + //#endregion + //#region LogLevel + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.LogLevel.html + export class LogLevel { + + /** @type {number} A DEBUG message is a fine-grained information on the client activity. */ + static DEBUG: number; + /** @type {number} An ERROR message contains informations on a problem that occurred during the client activities. Client operations might be compromised when an error is raised. */ + static ERROR: number; + /** @type {number} An INFO message contains informations on the standard client activities. */ + static INFO: number; + /** @type {number} A WARN message is a warning caused by an unexpected behavior of the client. Client operations are not compromised when a warning is raised. */ + static WARN: number; + + } + //#endregion + //#region Managers + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Managers.html + namespace Managers { + + //#region BuddyManager + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Managers.BuddyManager.html + export class BuddyManager { + + /** + * Creates a new BuddyManager instance. + * @param {SmartFox} sfs An instance of the SmartFoxServer 2X client API main SmartFox class. + */ + constructor(sfs: SmartFox); + /** + * Indicates whether a buddy exists in user's buddy list or not. + * @param {string} name The name of the buddy whose presence in the buddy list is to be checked. + * @return {boolean} Returns: true if the specified buddy exists in the buddy list. + */ + containsBuddy(name: string): boolean; + /** + * Retrieves a SFSBuddy object from its id property. + * @param {number} id The id of the buddy to be found. + * @return {Entities.SFSBuddy} Returns: The SFSBuddy object representing the buddy, or null if no buddy with the passed id exists in the buddy list. + */ + getBuddyById(id: number): Entities.SFSBuddy; + /** + * Retrieves a SFSBuddy object from its name property. + * @param {string} name The name of the buddy to be found. + * @return {Entities.SFSBuddy} Returns: The SFSBuddy object representing the buddy, or null if no buddy with the passed name exists in the buddy list. + */ + getBuddyByName(name: string): Entities.SFSBuddy; + /** + * Retrieves a SFSBuddy object using its getNickName method. + * @param {string} nickName The nickname of the buddy to be found. + * @return {Entities.SFSBuddy} Returns: The SFSBuddy object representing the buddy, or null if no buddy with the passed nickname exists in the buddies list. + */ + getBuddyByNickName(nickName: string): Entities.SFSBuddy; + /** + * Returns a list of SFSBuddy objects representing all the buddies in the user's buddy list. + * @return {Entities.SFSBuddy[]} Returns: A list of SFSBuddy objects representing all the buddies. + */ + getBuddyList(): Entities.SFSBuddy[]; + /** + * Returns a list of strings representing the available custom buddy states. + * @return {string[]} Returns: The list of available custom buddy states in the Buddy List system. + */ + getBuddyStates(): string[]; + /** + * Returns the current user's nickname (if set). If the nickname was never set before, null is returned. + * @return {string} Returns: The user nickname in the Buddy List system. + */ + getMyNickName(): string; + /** + * Returns the current user's online/offline state. + * @return {boolean} Returns true if the user is online in the Buddy List system. + */ + getMyOnlineState(): boolean; + /** + * Returns the current user's custom state (if set). Examples of custom states are "Available", "Busy", "Be right back", etc. If the custom state was never set before, null is returned. + * @return {string} Returns: The user state in the Buddy List system. + */ + getMyState(): string; + /** + * Retrieves a Buddy Variable set for the current user from its name. + * @param {string} varName The name of the Buddy Variable to be retrieved. + * @return {Entities.Variables.SFSBuddyVariable} Returns: The SFSBuddyVariable object representing the Buddy Variable, or null if no Buddy Variable with the passed name is associated to the current user. + */ + getMyVariable(varName: string): Entities.Variables.SFSBuddyVariable; + /** + * Returns all the Buddy Variables set for the current user. + * @return {Entities.Variables.SFSBuddyVariable[]} Returns: A list of SFSBuddyVariable objects representing all the Buddy Variables set for the user. + */ + getMyVariables(): Entities.Variables.SFSBuddyVariable[]; + /** + * Returns a list of SFSBuddy objects representing all the offline buddies in the user's buddy list. + * @return {Entities.SFSBuddy[]} Returns: A list of SFSBuddy objects representing the offline buddies. + */ + getOfflineBuddies(): Entities.SFSBuddy[]; + /** + * Returns a list of SFSBuddy objects representing all the online buddies in the user's buddy list. + * @return {Entities.SFSBuddy[]} Returns: A list of SFSBuddy objects representing the online buddies. + */ + getOnlineBuddies(): Entities.SFSBuddy[]; + /** + * Indicates whether the client's Buddy List system is initialized or not. If not, an InitBuddyListRequest request should be sent to the server in order to retrieve the persistent Buddy List data. + * @return {boolean} Returns: true if the Buddy List system is initialized in the client. + */ + isInited(): boolean; + + } + //#endregion + //#region RoomManager + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Managers.RoomManager.html + export class RoomManager { + + /** + * Creates a new RoomManager instance. + * @param {SmartFox} sfs An instance of the SmartFoxServer 2X client API main SmartFox class. + */ + constructor(sfs: SmartFox); + /** + * Indicates whether the specified Group has been subscribed by the client or not. + * @param {string} groupId The name of the Group. + * @return {boolean} Returns: true if the client subscribed the passed Group. + */ + containsGroup(groupId: string): boolean; + /** + * Indicates whether the Rooms list contains a Room belonging to the specified Group or not. + * @param {any} idOrName The id or name of the SFSRoom object whose presence in the Rooms list is to be tested. + * @return {boolean} Returns: true if the passed Room exists in the Rooms list. + */ + containsRoom(idOrName: any): boolean; + /** + * Indicates whether the Rooms list contains a Room belonging to the specified Group or not. + * @param {any} idOrName The id or name of the SFSRoom object whose presence in the Rooms list is to be tested. + * @param {string} groupId The name of the Group to which the specified Room must belong. + * @return {boolean} Returns: true if the Rooms list contains the passed Room and it belongs to the specified Group. + */ + containsRoomInGroup(idOrName: any, groupId: string): boolean; + /** + * Returns a list of Rooms currently joined by the client. + * @return {Entities.SFSRoom[]} Returns: The list of SFSRoom objects representing the Rooms currently joined by the client. + */ + getJoinedRooms(): Entities.SFSRoom[]; + /** + * Retrieves a SFSRoom object from its id. + * @param {number} id The id of the Room. + * @return {Entities.SFSRoom} Returns: The object representing the requested Room; null if no SFSRoom object with the passed id exists in the Rooms list. + */ + getRoomById(id: number): Entities.SFSRoom; + /** + * Retrieves a SFSRoom object from its name. + * @param {string} name The name of the Room. + * @return {Entities.SFSRoom} Returns: The object representing the requested Room; null if no SFSRoom object with the passed name exists in the Rooms list. + */ + getRoomByName(name: string): Entities.SFSRoom; + /** + * Returns the current number of Rooms in the Rooms list. + * @return {number} Returns: A list of Group names. + */ + getRoomCount(): number; + /** + * Returns the names of Groups currently subscribed by the client. + * @return {string[]} Returns: A list of Group names. + */ + getRoomGroups(): string[]; + /** + * Returns a list of Rooms currently "known" by the client. The list contains all the Rooms that are currently joined and all the Rooms belonging to the Room Groups that have been subscribed. + * @return {Entities.SFSRoom[]} Returns: The list of the available SFSRoom objects. + */ + getRoomList(): Entities.SFSRoom[]; + /** + * Retrieves the list of Rooms which are part of the specified Room Group. + * @param {string} groupId The name of the Group. + * @return {Entities.SFSRoom[]} Returns: The list of SFSRoom objects belonging to the passed Group. + */ + getRoomListFromGroup(groupId: string): Entities.SFSRoom[]; + /** + * Retrieves a list of Rooms joined by the specified user. The list contains only those Rooms "known" by the Room Manager; the user might have joined others the client is not aware of. + * @param {Entities.SFSUser} user A SFSUser object representing the user to look for in the current Rooms list. + * @return {Entities.SFSRoom[]} Returns: The list of Rooms joined by the passed user. + */ + getUserRooms(user: Entities.SFSUser): Entities.SFSRoom[]; + + } + //#endregion + //#region UserManager + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Managers.UserManager.html + export class UserManager { + + /** + * Creates a new UserManager instance. + * @param {SmartFox} sfs An instance of the SmartFoxServer 2X client API main SmartFox class. + */ + constructor(sfs: SmartFox); + /** + * Indicates whether a user exists in the local users list or not. + * @param {Entities.SFSUser} user The SFSUser object representing the user whose presence in the users list is to be tested. + * @return {boolean} Returns: true if the passed user exists in the users list. + */ + containsUser(user: Entities.SFSUser): boolean; + /** + * Indicates whether a user exists in the local users list or not from the id. + * @param {number} userId The id of the user whose presence in the users list is to be tested. + * @return {boolean} Returns: true if the passed user exists in the users list. + */ + containsUserId(userId: number): boolean; + /** + * Indicates whether a user exists in the local users list or not from the name. + * @param {string} userName The name of the user whose presence in the users list is to be tested. + * @return {boolean} Returns: true if the passed user exists in the users list. + */ + containsUserName(userName: string): boolean; + /** + * Retrieves a SFSUser object from its id property. + * @param {number} userId The id of the user to be found. + * @return {Entities.SFSUser} Returns: The SFSUser object representing the user, or null if no user with the passed id exists in the local users list. + */ + getUserById(userId: number): Entities.SFSUser; + /** + * Retrieves a SFSUser object from its name property. + * @param {string} userName The name of the user to be found. + * @return {Entities.SFSUser} Returns: The SFSUser object representing the user, or null if no user with the passed name exists in the local users list. + */ + getUserByName(userName: string): Entities.SFSUser; + /** + * Returns the total number of users in the local users list. + * @return {number} Returns: The number of users in the local users list. + */ + getUserCount(): number; + /** + * Get the whole list of users inside the Rooms joined by the client. + * @return {Entities.SFSUser[]} Returns: The list of SFSUser objects representing the users in the local users list. + */ + getUserList(): Entities.SFSUser[]; + + } + //#endregion + + } + //#endregion + //#region Requests + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.html + namespace Requests { + + //#region BanMode + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.BanMode.html + export class BanMode { + + /** @type {number} User is banned by IP address. */ + static BY_ADDRESS: number; + /** @type {number} User is banned by name. */ + static BY_NAME: number; + + } + //#endregion + //#region BuddyList + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.BuddyList.html + namespace BuddyList { + + //#region AddBuddyRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.BuddyList.AddBuddyRequest.html + export class AddBuddyRequest { + + /** + * Creates a new AddBuddyRequest instance. + * @param {string} buddyName The name of the user to be added as a buddy. + */ + constructor(buddyName: string); + + } + //#endregion + //#region BlockBuddyRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.BuddyList.BlockBuddyRequest.html + export class BlockBuddyRequest { + + /** + * Creates a new BlockBuddyRequest instance. + * @param {string} buddyName The name of the buddy to be removed from the user's buddy list. + * @param {boolean} blocked blocked + */ + constructor(buddyName: string, blocked: boolean); + + } + //#endregion + //#region BuddyMessageRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.BuddyList.BuddyMessageRequest.html + export class BuddyMessageRequest { + + /** + * Creates a new BuddyMessageRequest instance. + * @param {string} message The message to be sent to a buddy. + * @param {Entities.SFSBuddy} targetBuddy The SFSBuddy object corresponding to the message recipient. + * @param {Object} [parms=null] An object containing additional custom parameters (e.g. the message color, an emoticon id, etc). + */ + constructor(message: string, targetBuddy: Entities.SFSBuddy, parms?: Object); + + } + //#endregion + //#region GoOnlineRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.BuddyList.GoOnlineRequest.html + export class GoOnlineRequest { + + /** + * Creates a new GoOnlineRequest instance. + * @param {boolean} online true to make the current user available (online) in the Buddy List system; false to make him not available (offline). + */ + constructor(online: boolean); + + } + //#endregion + //#region InitBuddyListRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.BuddyList.InitBuddyListRequest.html + export class InitBuddyListRequest { + + /** + * Creates a new InitBuddyListRequest instance. + */ + constructor(); + + } + //#endregion + //#region RemoveBuddyRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.BuddyList.RemoveBuddyRequest.html + export class RemoveBuddyRequest { + + /** + * Creates a new RemoveBuddyRequest instance. + * @param {string} buddyName The name of the buddy to be removed from the user's buddy list. + */ + constructor(buddyName: string); + + } + //#endregion + //#region SetBuddyVariablesRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.BuddyList.SetBuddyVariablesRequest.html + export class SetBuddyVariablesRequest { + + /** + * Creates a new SetBuddyVariablesRequest instance. + * @param {Entities.Variables.SFSBuddyVariable[]} buddyVariables A list of SFSBuddyVariable objects representing the Buddy Variables to set. + */ + constructor(buddyVariables: Entities.Variables.SFSBuddyVariable[]); + + } + //#endregion + + } + //#endregion + //#region Game + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.Game.html + namespace Game { + + //#region CreateSFSGameRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.Game.CreateSFSGameRequest.html + export class CreateSFSGameRequest { + + /** + * Creates a new CreateSFSGameRequest instance. + * @param {SFSGameSettings} settings An object containing the Game Room configuration settings. + */ + constructor(settings: SFSGameSettings); + + } + //#endregion + //#region InvitationReplyRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.Game.InvitationReplyRequest.html + export class InvitationReplyRequest { + + /** + * Creates a new InvitationReplyRequest instance. + * @param {IINVITATION} invitation An instance of the Invitation class containing the invitation details (inviter, custom parameters, etc). + * @param {number} invitationReply The answer to be sent to the inviter, among those available as constants in the InvitationReply class. + * @param {Object} [params=null] An object containing custom parameters to be returned to the inviter together with the reply (for example a message describing the reason of refusal). + */ + constructor(invitation: IINVITATION, invitationReply: number, params?: Object); + + } + //#endregion + //#region InviteUsersRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.Game.InviteUsersRequest.html + export class InviteUsersRequest { + + /** + * Creates a new InviteUsersRequest instance. + * @param {Entities.SFSUser[]} invitedUsers A list of SFSUser objects, each representing a user to send the invitation to. + * @param {number} secondsForAnswer The number of seconds available to each invited user to reply to the invitation (recommended range: 15 to 40 seconds). + * @param {Object} [params=null] An object containing custom parameters containing additional invitation details. + */ + constructor(invitedUsers: Entities.SFSUser[], secondsForAnswer: number, params?: Object); + + } + //#endregion + //#region QuickJoinGameRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.Game.QuickJoinGameRequest.html + export class QuickJoinGameRequest { + + /** + * Creates a new QuickJoinGameRequest instance. + * @param {Entities.SFSRoom[]} whereToSearch An array of SFSRoom objects or an array of Group names to which the matching expression should be applied. The maximum number of elements that this array can contain is 32. + * @param {Entities.SFSRoom} [roomToLeave=null] A SFSRoom object representing the Room that the user should leave when joining the game. + */ + constructor(whereToSearch: Entities.SFSRoom[], roomToLeave?: Entities.SFSRoom); + /** + * Creates a new QuickJoinGameRequest instance. + * @param {Entities.Match.MatchExpression} matchExpression A matching expression that the system will use to search a Game Room where to join the current user. + * @param {Entities.SFSRoom[]} whereToSearch An array of SFSRoom objects or an array of Group names to which the matching expression should be applied. The maximum number of elements that this array can contain is 32. + * @param {Entities.SFSRoom} [roomToLeave=null] A SFSRoom object representing the Room that the user should leave when joining the game. + */ + constructor(matchExpression: Entities.Match.MatchExpression, whereToSearch: Entities.SFSRoom[], roomToLeave?: Entities.SFSRoom); + + } + //#endregion + //#region SFSGameSettings + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.Game.SFSGameSettings.html + export class SFSGameSettings extends RoomSettings { + + /** @type {number} In private games, defines the number of seconds that users have to reply to the invitation to join a game. The suggested range is 10 to 40 seconds. */ + invitationExpiryTime: number; + /** @type {Object} In private games, defines a list of SFSUser objects representing players to be invited to join the game. */ + invitiationParams: Object; + /** @type {Entities.SFSUser[]} In private games, defines a list of SFSUser objects representing players to be invited to join the game.. */ + invitiedPlayers: Entities.SFSUser[]; + /** @type {boolean} Indicates whether the game is public or private. */ + isPublic: boolean; + /** @type {boolean} In private games, indicates whether the players must leave the previous Room when joining the game or not. */ + leaveLastJoinedRoom: boolean; + /** @type {number} Defines the minimum number of players required to start the game. If the notifyGameStarted property is set to true, when this number is reached, the game start is notified. */ + minPlayersToStartGame: number; + /** @type {boolean} Indicates if a game state change must be notified when the minimum number of players is reached. */ + notifyGameStarted: boolean; + /** @type {Entities.Match.MatchExpression} Defines the game matching expression to be used to filters players. */ + playerMatchExpression: Entities.Match.MatchExpression; + /** @type {string[]} In private games, defines a list of Groups names where to search players to invite. */ + serachableRooms: string[]; // Might need any + /** @type {Entities.Match.MatchExpression} Defines the game matching expression to be used to filters spectators. */ + spectatorMatchExpression: Entities.Match.MatchExpression; + + /** + * Creates a new SFSGameSettings instance. + * @param {string} name The name of the Game Room to be created. + */ + constructor(name: string); + + } + //#endregion + + } + //#endregion + //#region MessageRecipientMode + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.MessageRecipientMode.html + export class MessageRecipientMode { + + /** @type {number} Returns the selected recipient mode. */ + mode: number; + /** @type {any} Returns the moderator/administrator message target, according to the selected recipient mode. */ + target: any; + /** @type {number} The moderator/administrator message will be sent to all the clients who subscribed a specific Room Group. */ + static TO_GROUP: number; + /** @type {number} The moderator/administrator message will be sent to all the users in a specific Room. */ + static TO_ROOM: number; + /** @type {number} The moderator/administrator message will be sent to a specific user. */ + static TO_USER: number; + /** @type {number} The moderator/administrator message will be sent to all the users in the Zone. */ + static TO_ZONE: number; + + /** + * Creates a new MessageRecipientMode instance. + * @param {number} mode One of the costants contained in this class, describing the recipient mode. + * @param {any} target The moderator/administrator message recipient/s, according to the selected recipient mode. + */ + constructor(mode: number, target: any); + + } + //#endregion + //#region MMO + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.MMO.html + namespace MMO { + + //#region MapLimits + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.MMO.MapLimits.html + export class MapLimits { + + /** @type {Entities.Data.Vec3D} Returns the higher coordinates limit of the virtual environment along the X,Y,Z axes. */ + higherLimit: Entities.Data.Vec3D; + /** @type {Entities.Data.Vec3D} Returns the lower coordinates limit of the virtual environment along the X,Y,Z axes. */ + lowerLimit: Entities.Data.Vec3D; + + /** + * Creates a new MapLimits instance. + * @param {Entities.Data.Vec3D} lowerLimit + * @param {Entities.Data.Vec3D} higherLimit + */ + constructor(lowerLimit: Entities.Data.Vec3D, higherLimit: Entities.Data.Vec3D); + + } + //#endregion + //#region MMORoomSettings + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.MMO.MMORoomSettings.html + export class MMORoomSettings { + + /** @type {Entities.Data.Vec3D} Defines the Area of Interest (AoI) for the MMORoom. */ + defaultAOI: Entities.Data.Vec3D; + /** @type {MapLimits} Defines the limits of the virtual environment represented by the MMORoom. */ + mapLimits: MapLimits; + /** @type {number} Configures the speed at which the SFSEvent.PROXIMITY_LIST_UPDATE event is sent by the server. */ + proximityListUpdateMillis: number; + /** @type {boolean} Sets if the users entry points in the current user's Area of Interest should be transmitted in the SFSEvent.PROXIMITY_LIST_UPDATE event. */ + sendAOIEntryPoint: boolean; + /** @type {number} Defines the time limit before a user without a physical position set inside the MMORoom is kicked from the Room. */ + userMaxLimboSeconds: number; + + /** + * Creates a new MMORoomSettings instance. + * @param {string} name The name of the MMORoom to be created. + */ + constructor(name: string); + + } + //#endregion + //#region SetUserPositionRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.MMO.SetUserPositionRequest.html + export class SetUserPositionRequest { + + /** + * Creates a new SetUserPositionRequest instance. + * @param {Entities.Data.Vec3D} pos The user position. + * @param {Entities.MMORoom} [targetRoom=null] The MMORoom object corresponding to the Room where the position should be set; if null, the last Room joined by the user is used. + */ + constructor(pos: Entities.Data.Vec3D, targetRoom?: Entities.MMORoom); + + } + //#endregion + + } + //#endregion + //#region RoomEvents + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.RoomEvents.html + export class RoomEvents { + + /** @type {boolean} Sets whether or not the userCountChange event should be dispatched whenever the users (or players+spectators) count changes in the Room. */ + allowUserCountChance: boolean; + /** @type {boolean} Sets whether the userEnterRoom event should be dispatched whenever a user joins the Room or not. */ + allowUserEnter: boolean; + /** @type {boolean} Sets whether the userExitRoom event should be dispatched whenever a user leaves the Room or not. */ + allowUserExit: boolean; + /** @type {boolean} Sets whether or not the userVariablesUpdate event should be dispatched whenever a user in the Room updates his User Variables */ + allowUserVariablesUpdate: boolean; + + /** + * Creates a new RoomEvents instance. + */ + constructor(); + + } + //#endregion + //#region RoomExtension + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.RoomExtension.html + export class RoomExtension { + + /** @type {string} Returns the fully qualified name of the main class of the Extension. */ + className: string; + /** @type {string} Returns the name of the Extension to be attached to the Room. */ + id: string; + /** @type {string} Sets the name of an optional properties file that should be loaded on the server-side during the Extension initialization. */ + propertiesFile: string; + + /** + * Creates a new RoomExtension instance. + * @param {string} id The name of the Extension as deployed on the server; it's the name of the folder containing the Extension classes inside the main [sfs2x-install-folder]/SFS2X/extensions folder. + * @param {string} className The fully qualified name of the main class of the Extension. + */ + constructor(id: string, className: string); + + } + //#endregion + //#region RoomPermissions + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.RoomPermissions.html + export class RoomPermissions { + + /** @type {boolean} Sets whether changing the Room name after its creation is allowed or not. */ + allowNameChange: boolean; + /** @type {boolean} Sets whether changing (or removing) the Room password after its creation is allowed or not. */ + allowPasswordStateChange: boolean; + /** @type {boolean} Sets whether users inside the Room are allowed to send public messages or not. */ + allowPublicMessages: boolean; + /** @type {boolean} Sets whether the Room capacity can be changed after its creation or not. */ + aloowResizing: boolean; + + /** + * Creates a new RoomPermissions instance. + */ + constructor(); + + } + //#endregion + //#region RoomSettings + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.RoomSettings.html + export class RoomSettings { + + /** @type {RoomEvents} Sets the flags indicating which events related to the Room are dispatched by the SmartFox client. */ + events: RoomEvents; + /** @type {RoomExtension} Sets the Extension that must be attached to the Room on the server-side, and its settings. */ + extension: RoomExtension; + /** @type {string} Sets the id of the Group to which the Room should belong. */ + groupId: string; + /** @type {boolean} Sets whether the Room is a Game Room or not. */ + isGame: boolean; + /** @type {number} Sets the maximum number of spectators allowed in the Room (only for Game Rooms). */ + maxSpectators: number; + /** @type {number} Sets the maximum number of users allowed in the Room. */ + maxUsers: number; + /** @type {number} Sets the maximum number of Room Variables allowed for the Room. */ + maxVariables: number; + /** @type {string} Defines the name of the Room. */ + name: string; + /** @type {string} Sets the password of the Room. */ + password: string; + /** @type {RoomPermissions} Sets the flags indicating which operations are permitted on the Room. */ + permissions: RoomPermissions; + /** @type {Entities.Variables.ReservedRoomVariables[]} Sets a list of SFSRooomVariable objects to be attached to the Room. */ + variables: Entities.Variables.ReservedRoomVariables[]; + + /** + * Creates a new RoomSettings instance. + * @param {string} name The name of the Room to be created. + */ + constructor(name: string); + + } + //#endregion + //#region System + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.html + namespace System { + + //#region AdminMessageRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.AdminMessageRequest.html + export class AdminMessageRequest{ + + /** + * Creates a new AdminMessageRequest instance. + * @param {string} message The message of the administrator to be sent to the target user/s defined by the recipientMode parameter. + * @param {MessageRecipientMode} recipientMode An instance of MessageRecipientMode containing the target to which the message should be delivered. + * @param {Object} [params=null] An object containing custom parameters to be sent to the recipient user/s. + */ + constructor(message: string, recipientMode: MessageRecipientMode, params?: Object); + + } + //#endregion + //#region BanUserRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.BanUserRequest.html + export class BanUserRequest{ + + /** + * Creates a new BanUserRequest instance. + * @param {number} userId The id of the user to be banned. + * @param {string} [message=null] A custom message to be delivered to the user before banning him; if null, the default message configured in the SmartFoxServer 2X Administration Tool is used. + * @param {BanMode} [banMode=BY_NAME] One of the ban modes defined in the BanMode class. + * @param {number} [delaySeconds=5] The number of seconds after which the user is banned after receiving the ban message. + * @param {number} [durationHours=24] The duration of the banishment, expressed in hours. + */ + constructor(userId: number, message?: string, banMode?: BanMode, delaySeconds?: number, durationHours?: number); + + } + //#endregion + //#region ChangeRoomCapacityRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.ChangeRoomCapacityRequest.html + export class ChangeRoomCapacityRequest{ + + /** + * Creates a new ChangeRoomCapacityRequest instance. + * @param {Entities.SFSRoom} room The Room object corresponding to the Room whose capacity should be changed. + * @param {number} newMaxUsers The new maximum number of users/players who can join the Room; the -1 value can be passed not to change the Room.maxUsers property. + * @param {number} newMaxSpect The new maximum number of spectators who can join the Room (for Game Rooms only); the -1 value can be passed not to change the Room.maxSpectators property. + */ + constructor(room: Entities.SFSRoom, newMaxUsers: number, newMaxSpect: number); + + } + //#endregion + //#region ChangeRoomNameRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.ChangeRoomNameRequest.html + export class ChangeRoomNameRequest{ + + /** + * Creates a new ChangeRoomNameRequest instance. + * @param {Entities.SFSRoom} room The SFSRoom object corresponding to the Room whose name should be changed. + * @param {string} newName The new name to be assigned to the Room. + */ + constructor(room: Entities.SFSRoom, newName: string); + + } + //#endregion + //#region ChangeRoomPasswordStateRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.ChangeRoomPasswordStateRequest.html + export class ChangeRoomPasswordStateRequest{ + + /** + * Creates a new ChangeRoomPasswordStateRequest instance. + * @param {Entities.SFSRoom} room The SFSRoom object corresponding to the Room whose password should be changed. + * @param {string} newPass The new password to be assigned to the Room; an empty string or the null value can be passed to remove the Room's password. + */ + constructor(room: Entities.SFSRoom, newPass: string); + + } + //#endregion + //#region CreateRoomRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.CreateRoomRequest.html + export class CreateRoomRequest{ + + /** + * Creates a new CreateRoomRequest instance. + * @param {RoomSettings} settings An object containing the Room configuration settings. + * @param {boolean} {autoJoin=false} If true, the Room is joined as soon as it is created. + * @param {Entities.SFSRoom} {roomToLeave=null} A SFSRoom object representing the Room that should be left if the new Room is auto-joined. + */ + constructor(settings: RoomSettings, autoJoin?: boolean, roomToLeave?: Entities.SFSRoom); + + } + //#endregion + //#region ExtensionRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.ExtensionRequest.html + export class ExtensionRequest{ + + /** + * Creates a new ExtensionRequest instance. + * @param {string} extCmd The name of the command which identifies an action that should be executed by the server-side Extension. + * @param {Object} {params=null} An object containing custom data to be sent to the Extension. Can be null if no data needs to be sent. + * @param {Entities.SFSRoom} {room=null} If null, the specified command is sent to the current Zone server-side Extension; if not null, the command is sent to the server-side Extension attached to the passed Room. + */ + constructor(extCmd: string, params?: Object, room?: Entities.SFSRoom); + + } + //#endregion + //#region FindRoomsRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.FindRoomsRequest.html + export class FindRoomsRequest{ + + /** + * Creates a new FindRoomsRequest instance. + * @param {Entities.Match.MatchExpression} expr A matching expression that the system will use to retrieve the Rooms. + * @param {string} {groupId=null} The name of the Group where to search for matching Rooms; if null, the search is performed in the whole Zone. + * @param {number} [limit=0] The maximum size of the list of Rooms that will be returned by the roomFindResult event. If 0, all the found Rooms are returned. + */ + constructor(expr: Entities.Match.MatchExpression, groupId?: string, limit?: number); + + } + //#endregion + //#region FindUsersRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.FindUsersRequest.html + export class FindUsersRequest{ + + /** + * Creates a new FindUsersRequest instance. + * @param {Entities.Match.MatchExpression} expr A matching expression that the system will use to retrieve the users. + * @param {any} [target=null] The name of a Group or a single SFSRoom object where to search for matching users; if null, the search is performed in the whole Zone. + * @param {number} [limit=0] The maximum size of the list of users that will be returned by the userFindResult event. If 0, all the found users are returned. + */ + constructor(expr: Entities.Match.MatchExpression, target?: any, limit?: number); + + } + //#endregion + //#region JoinRoomRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.JoinRoomRequest.html + export class JoinRoomRequest{ + + /** + * Creates a new JoinRoomRequest instance. + * @param {any} room The id or the name of the Room to be joined. + * @param {string} [password] The password of the Room, in case it is password protected. + * @param {number} [roomIdToLeave] The id of a previously joined Room that the user should leave when joining the new Room. By default, the last joined Room is left; if a negative number is passed, no previous Room is left. + * @param {boolean} [asSpect=false] true to join the Room as a spectator (in Game Rooms only). + */ + constructor(room: any, password?: string, roomIdToLeave?: number, asSpect?: boolean); + + } + //#endregion + //#region KickUserRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.KickUserRequest.html + export class KickUserRequest{ + + /** + * Creates a new KickUserRequest instance. + * @param {number} userId The id of the user to be kicked. + * @param {string} [message=null] A custom message to be delivered to the user before kicking him; if null, the default message configured in the SmartFoxServer 2X Administration Tool is used. + * @param {number} [delaySeconds=5] The number of seconds after which the user is kicked after receiving the kick message. + */ + constructor(userId: number, message?: string, delaySeconds?: number); + + } + //#endregion + //#region LeaveRoomRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.LeaveRoomRequest.html + export class LeaveRoomRequest{ + + /** + * Creates a new LeaveRoomRequest instance. + * @param {Entities.SFSRoom} [room=null] The SFSRoom object corresponding to the Room that the current user must leave. If null, the last Room joined by the user is left. + */ + constructor(room?: Entities.SFSRoom); + + } + //#endregion + //#region LoginRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.LoginRequest.html + export class LoginRequest{ + + /** + * Creates a new LoginRequest instance. + * @param {string} userName The name to be assigned to the user. If not passed and if the Zone allows guest users, the name is generated automatically by the server. + * @param {string} [password] The user password to access the system. SmartFoxServer doesn't offer a default authentication system, so the password must be validated implementing a custom login system in the Zone's server-side Extension. + * @param {Object} [params] An object containing custom parameters to be passed to the Zone Extension (requires a custom login system to be in place). + * @param {string} [zoneName] The name (case-sensitive) of the server Zone to login to; if a Zone name is not specified, the client will use the setting passed to the SmartFox class constructor. + */ + constructor(userName: string, password?: string, params?: Object, zoneName?: string); + + } + //#endregion + //#region LogoutRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.LogoutRequest.html + export class LogoutRequest{ + + /** + * Creates a new LogoutRequest instance. + */ + constructor(); + + } + //#endregion + //#region ModeratorMessageRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.ModeratorMessageRequest.html + export class ModeratorMessageRequest{ + + /** + * Creates a new ModeratorMessageRequest instance. + * @param {string} message The message of the moderator to be sent to the target user/s defined by the recipientMode parameter. + * @param {MessageRecipientMode} recipientMode An instance of MessageRecipientMode containing the target to which the message should be delivered. + * @param {Object} [params=null] An object containing custom parameters to be sent to the recipient user/s. + */ + constructor(message: string, recipientMode: MessageRecipientMode, params?: Object); + + } + //#endregion + //#region ObjectMessageRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.ObjectMessageRequest.html + export class ObjectMessageRequest{ + + /** + * Creates a new ObjectMessageRequest instance. + * @param {Object} obj An object containing custom parameters to be sent to the message recipients. + * @param {Entities.SFSRoom} [targetRoom=null] The SFSRoom object corresponding to the Room where the message should be dispatched; if null, the last Room joined by the user is used. + * @param {Entities.SFSUser[]} [recipients=null] A list of SFSUser objects corresponding to the message recipients; if null, the message is sent to all users in the target Room (except the sender himself). + */ + constructor(obj: Object, targetRoom?: Entities.SFSRoom, recipients?: Entities.SFSUser[]); + + } + //#endregion + //#region PlayerToSpectatorRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.PlayerToSpectatorRequest.html + export class PlayerToSpectatorRequest{ + + /** + * Creates a new SpectatorToPlayerRequest instance. + * @param {Entities.SFSRoom} [targetRoom=null] The SFSRoom object corresponding to the Room in which the spectator should be turned to player. If null, the last Room joined by the user is used. + */ + constructor(targetRoom?: Entities.SFSRoom); + + } + //#endregion + //#region PrivateMessageRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.PrivateMessageRequest.html + export class PrivateMessageRequest{ + + /** + * Creates a new PrivateMessageRequest instance. + * @param {string} message The message to be sent to to the recipient user. + * @param {number} recipientId The id of the user to which the message is to be sent. + * @param {Object} [params=null] An object containing additional custom parameters to be sent to the message recipient (for example the color of the text, etc). + */ + constructor(message: string, recipientId: number, params?: Object); + + } + //#endregion + //#region PublicMessageRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.PublicMessageRequest.html + export class PublicMessageRequest{ + + /** + * Creates a new PublicMessageRequest instance. + * @param {string} message The message to be sent to all the users in the target Room. + * @param {Object} [params=null] An object containing additional custom parameters to be sent to the message recipients (for example the color of the text, etc). + * @param {Entities.SFSRoom} [targetRoom=null] The SFSRoom object corresponding to the Room where the message should be dispatched; if null, the last Room joined by the user is used. + */ + constructor(message: string, params?: Object, targetRoom?: Entities.SFSRoom); + + } + //#endregion + //#region SetRoomVariablesRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.SetRoomVariablesRequest.html + export class SetRoomVariablesRequest{ + + /** + * Creates a new SetRoomVariablesRequest instance. + * @param {Entities.Variables.SFSRoomVariable[]} roomVariables A list of SFSRoomVariable objects representing the Room Variables to be set. + * @param {Entities.SFSRoom} [room=null] A SFSRoom object representing the Room where to set the Room Variables; if null, the last Room joined by the current user is used. + */ + constructor(roomVariables: Entities.Variables.SFSRoomVariable[], room: Entities.SFSRoom); + + } + //#endregion + //#region SetUserVariablesRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.SetUserVariablesRequest.html + export class SetUserVariablesRequest{ + + /** + * Creates a new SetUserVariablesRequest instance. + * @param {Entities.Variables.SFSUserVariable} userVariables A list of SFSUserVariable objects representing the User Variables to be set. + */ + constructor(userVariables: Entities.Variables.SFSUserVariable); + + } + //#endregion + //#region SpectatorToPlayerRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.SpectatorToPlayerRequest.html + export class SpectatorToPlayerRequest{ + + /** + * Creates a new SpectatorToPlayerRequest instance. + * @param {Entities.SFSRoom} targetRoom The SFSRoom object corresponding to the Room in which the spectator should be turned to player. If null, the last Room joined by the user is used. + */ + constructor(targetRoom: Entities.SFSRoom); + + } + //#endregion + //#region SubscribeRoomGroupRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.SubscribeRoomGroupRequest.html + export class SubscribeRoomGroupRequest{ + + /** + * Creates a new SubscribeRoomGroupRequest instance. + * @param {string} groupId The name of the Room Group to subscribe. + */ + constructor(groupId: string); + + } + //#endregion + //#region UnsubscribeRoomGroupRequest + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Requests.System.UnsubscribeRoomGroupRequest.html + export class UnsubscribeRoomGroupRequest{ + + /** + * Creates a new UnsubscribeRoomGroupRequest instance. + * @param {string} groupId The name of the Room Group to unsubscribe. + */ + constructor(groupId: string); + + } + //#endregion + + } + //#endregion + + } + //#endregion + //#region SFSBuddyEvent + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.SFSBuddyEvent.html + export class SFSBuddyEvent { + + /** @type {string} The buddyAdd event type, dispatched when a buddy is added successfully to the current user's buddy list. */ + static BUDDY_ADD: string; + /** @type {string} The buddyBlock event type, dispatched when a buddy is blocked or unblocked successfully by the current user. */ + static BUDDY_BLOCK: string; + /** @type {string} The buddyError event type, dispatched if an error occurs while executing a request related to the Buddy List system. */ + static BUDDY_ERROR: string; + /** @type {string} The buddyListInit event type, dispatched if the Buddy List system is successfully initialized. */ + static BUDDY_LIST_INIT: string; + /** @type {string} The buddyMessage event type, dispatched when a message from a buddy is received by the current user. */ + static BUDDY_MESSAGE: string; + /** @type {string} The buddyOnlineStateChange event type, dispatched when a buddy in the current user's buddy list changes his online state in the Buddy List system. */ + static BUDDY_ONLINE_STATE_CHANGE: string; + /** @type {string} The buddyRemove event type, dispatched when a buddy is removed successfully from the current user's buddy list. */ + static BUDDY_REMOVE: string; + /** @type {string} The buddyVariablesUpdate event type, dispatched when a buddy in the current user's buddies list updates one or more Buddy Variables. */ + static BUDDY_VARIABLES_UPDATE: string; + + } + + interface IBUDDY_ADD { + buddy: Entities.SFSBuddy; + } + + interface IBUDDY_BLOCK { + buddy: Entities.SFSBuddy; + } + + interface IBUDDY_ERROR { + errorMessage: string; + errorCode: number; + } + + interface IBUDDY_LIST_INIT { + buddyList: Entities.SFSBuddy[]; + myVariables: Entities.Variables.SFSBuddyVariable[]; + } + + interface IBUDDY_MESSAGE { + buddy: Entities.SFSBuddy; + isItMe: boolean; + message: string; + data: Object; + } + + interface IBUDDY_ONLINE_STATE_CHANGE { + buddy: Entities.SFSBuddy; + isItMe: boolean; + } + + interface IBUDDY_REMOVE { + buddy: Entities.SFSBuddy; + } + + interface IBUDDY_VARIABLES_UPDATE { + buddy: Entities.SFSBuddy; + isItMe: boolean; + changedVars: string[]; + } + + //#endregion + //#region SFSEvent + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.SFSEvent.html + export class SFSEvent { + + /** @type {string} The adminMessage event type, dispatched when the current user receives a message from an administrator user. */ + static ADMIN_MESSAGE: string; + /** @type {string} The connection event type, dispatched when a connection between the client and a SmartFoxServer 2X instance is attempted. */ + static CONNECTION: string; + /** @type {string} The connectionLost event type, dispatched when the connection between the client and the SmartFoxServer 2X instance is interrupted. */ + static CONNECTION_LOST: string; + /** @type {string} The extensionResponse event type, dispatched when data coming from a server-side Extension is received by the current user. */ + static EXTENSION_RESPONSE: string; + /** @type {string} The invitation event type, dispatched when the current user receives an invitation from another user. */ + static INVITATION: string; + /** @type {string} The invitationReply event type, dispatched when the current user receives a reply to an invitation he sent previously. */ + static INVITATION_REPLY: string; + /** @type {string} The invitationReplyError event type, dispatched when an error occurs while the current user is sending a reply to an invitation he received. */ + static INVITATION_REPLY_ERROR: string; + /** @type {string} The login event type, dispatched when the current user performs a successful login in a server Zone. */ + static LOGIN: string; + /** @type {string} The loginError event type, dispatched if an error occurs while the user login is being performed. */ + static LOGIN_ERROR: string; + /** @type {string} The logout event type, dispatched when the current user performs logs out of the server Zone. */ + static LOGOUT: string; + /** @type {string} The mmoItemVariablesUpdate event type, dispatched when an MMOItem Variable is updated in an MMORoom. */ + static MMOITEM_VARIABLES_UPDATE: string; + /** @type {string} The moderatorMessage event type, dispatched when the current user receives a message from a moderator user. */ + static MODERATOR_MESSAGE: string; + /** @type {string} The objectMessage event type, dispatched when an object containing custom data is received by the current user. */ + static OBJECT_MESSAGE: string; + /** @type {string} The pingPong event type, dispatched when a new lag value measurement is available. */ + static PING_PONG: string; + /** @type {string} The playerToSpectator event type, dispatched when a player is turned to a spectator inside a Game Room. */ + static PLAYER_TO_SPECTATOR: string; + /** @type {string} The playerToSpectatorError event type, dispatched when an error occurs while the current user is being turned from player to spectator in a Game Room. */ + static PLAYER_TO_SPECTATOR_ERROR: string; + /** @type {string} The privateMessage event type, dispatched when a private message is received by the current user. */ + static PRIVATE_MESSAGE: string; + /** @type {string} The proximityListUpdate event type, dispatched when one more users or one or more MMOItem objects enter/leave the current user's Area of Interest in MMORooms. */ + static PROXIMITY_LIST_UPDATE: string; + /** @type {string} The publicMessage event type, dispatched when a public message is received by the current user. */ + static PUBLIC_MESSAGE: string; + /** @type {string} The roomAdd event type, dispatched when a new Room is created inside the Zone under any of the Room Groups that the client subscribed. */ + static ROOM_ADD: string; + /** @type {string} The roomCapacityChange event type, dispatched when the capacity of a Room is changed. */ + static ROOM_CAPACITY_CHANGE: string; + /** @type {string} The roomCapacityChangeError event type, dispatched when an error occurs while attempting to change the capacity of a Room. */ + static ROOM_CAPACITY_CHANGE_ERROR: string; + /** @type {string} The roomCreationError event type, dispatched if an error occurs while creating a new Room. */ + static ROOM_CREATION_ERROR: string; + /** @type {string} The roomFindResult event type, dispatched when a Rooms search is completed. */ + static ROOM_FIND_RESULT: string; + /** @type {string} The roomGroupSubscribe event type, dispatched when a Group is subscribed by the current user. */ + static ROOM_GROUP_SUBSCRIBE: string; + /** @type {string} The roomGroupSubscribeError event type, dispatched when an error occurs while a Room Group is being subscribed. */ + static ROOM_GROUP_SUBSCRIBE_ERROR: string; + /** @type {string} The roomGroupUnsubscribe event type, dispatched when a Group is unsubscribed by the current user. */ + static ROOM_GROUP_UNSUBSCRIBE: string; + /** @type {string} The roomGroupUnsubscribeError event type, dispatched when an error occurs while a Room Group is being unsubscribed. */ + static ROOM_GROUP_UNSUBSCRIBE_ERROR: string; + /** @type {string} The roomJoin event type, dispatched when a Room is joined by the current user. */ + static ROOM_JOIN: string; + /** @type {string} The roomJoinError event type, dispatched when an error occurs while the current user is trying to join a Room. */ + static ROOM_JOIN_ERROR: string; + /** @type {string} The roomNameChange event type, dispatched when the name of a Room is changed. */ + static ROOM_NAME_CHANGE: string; + /** @type {string} The roomNameChangeError event type, dispatched when an error occurs while attempting to change the name of a Room. */ + static ROOM_NAME_CHANGE_ERROR: string; + /** @type {string} The roomPasswordStateChange event type, dispatched when the password of a Room is set, changed or removed. */ + static ROOM_PASSWORD_STATE_CHANGE: string; + /** @type {string} The roomPasswordStateChangeError event type, dispatched when an error occurs while attempting to set, change or remove the password of a Room. */ + static ROOM_PASSWORD_STATE_CHANGE_ERROR: string; + /** @type {string} The roomRemove event type, dispatched when a Room belonging to one of the Groups subscribed by the client is removed from the Zone. */ + static ROOM_REMOVE: string; + /** @type {string} The roomVariablesUpdate event type, dispatched when a Room Variable is updated. */ + static ROOM_VARIABLES_UPDATE: string; + /** @type {string} The socketError event type, dispatched when a low level socket error is detected, for example bad/inconsistent data. */ + static SOCKET_ERROR: string; + /** @type {string} The spectatorToPlayer event type, dispatched when a spectator is turned to a player inside a Game Room. */ + static SPECTATOR_TO_PLAYER: string; + /** @type {string} The spectatorToPlayerError event type, dispatched when an error occurs while the current user is being turned from spectator to player in a Game Room. */ + static SPECTATOR_TO_PLAYER_ERROR: string; + /** @type {string} The userCountChange event type, dispatched when the number of users/players or spectators inside a Room changes. */ + static USER_COUNT_CHANGE: string; + /** @type {string} The userEnterRoom event type, dispatched when one of the Rooms joined by the current user is entered by another user. */ + static USER_ENTER_ROOM: string; + /** @type {string} The userExitRoom event type, dispatched when one of the Rooms joined by the current user is left by another user, or by the current user himself. */ + static USER_EXIT_ROOM: string; + /** @type {string} The userFindResult event type, dispatched when a users search is completed. */ + static USER_FIND_RESULT: string; + /** @type {string} The userVariablesUpdate event type, dispatched when a User Variable is updated. */ + static USER_VARIABLES_UPDATE: string; + + } + + interface IADMIN_MESSAGE { + sender: Entities.SFSUser; + message: string; + data: Object; + } + + interface ICONNECTION { + success: boolean; + } + + interface ICONNECTION_LOST { + reason: string; + } + + interface IEXTENSION_RESPONSE { + cmd: string; + params: Object; + sourceRoom: number; + } + + interface IINVITATION { + invitation: Entities.Invitation.SFSInvitation; + } + + interface IINVITATION_REPLY { + invitee: Entities.SFSUser; + reply: number; + data: Object; + } + + interface IINVITATION_REPLY_ERROR { + errorMessage: string; + errorCode: number; + } + + interface ILOGIN { + user: Entities.SFSUser; + data: Object; + } + + interface ILOGIN_ERROR { + errorMessage: string; + errorCode: number; + } + + interface ILOGOUT { + + } + + interface IMMOITEM_VARIABLES_UPDATE { + room: Entities.MMORoom; + mmoItem: Entities.MMOItem; + changedVars: string[]; + } + + interface IMODERATOR_MESSAGE { + sender: Entities.SFSUser; + message: string; + data: Object; + } + + interface IOBJECT_MESSAGE { + sender: Entities.SFSUser; + message: string; + } + + interface IPING_PONG { + lagValue: number; + } + + interface IPLAYER_TO_SPECTATOR { + room: Entities.SFSRoom; + user: Entities.SFSUser; + } + + interface IPLAYER_TO_SPECTATOR_ERROR { + errorMessage: string; + errorCode: number; + } + + interface IPRIVATE_MESSAGE { + sender: Entities.SFSUser; + message: string; + data: Object; + } + + interface IPROXIMITY_LIST_UPDATE { + addedUsers: Entities.SFSUser[]; + removedUsers: Entities.SFSUser[]; + addedItems: Entities.MMOItem[]; + removedItems: Entities.MMOItem[]; + } + + interface IPUBLIC_MESSAGE { + room: Entities.SFSRoom; + sender: Entities.SFSUser; + message: string; + data: Object; + } + + interface IROOM_ADD { + room: Entities.SFSRoom; + } + + interface IROOM_CAPACITY_CHANGE { + room: Entities.SFSRoom; + } + + interface IROOM_CAPACITY_CHANGE_ERROR { + errorMessage: string; + errorCode: number; + } + + interface IROOM_CREATION_ERROR { + errorMessage: string; + errorCode: number; + } + + interface IROOM_FIND_RESULT { + rooms: Entities.SFSRoom[]; + } + + interface IROOM_GROUP_SUBSCRIBE { + groupId: string; + newRooms: Entities.SFSRoom[]; + } + + interface IROOM_GROUP_SUBSCRIBE_ERROR { + errorMessage: string; + errorCode: number; + } + + interface IROOM_GROUP_UNSUBSCRIBE { + groupId: string; + } + + interface IROOM_GROUP_UNSUBSCRIBE_ERROR { + errorMessage: string; + errorCode: number; + } + + interface IROOM_JOIN { + room: Entities.SFSRoom; + } + + interface IROOM_JOIN_ERROR { + errorMessage: string; + errorCode: number; + } + + interface IROOM_NAME_CHANGE { + room: Entities.SFSRoom; + oldName: string; + } + + interface IROOM_NAME_CHANGE_ERROR { + errorMessage: string; + errorCode: number; + } + + interface IROOM_PASSWORD_STATE_CHANGE { + room: Entities.SFSRoom; + } + + interface IROOM_PASSWORD_STATE_CHANGE_ERROR { + errorMessage: string; + errorCode: number; + } + + interface IROOM_REMOVE { + room: Entities.SFSRoom; + } + + interface IROOM_VARIABLES_UPDATE { + room: Entities.SFSRoom; + changedVars: string[]; + } + + interface ISOCKET_ERROR { + errorMessage: string; + } + + interface ISPECTATOR_TO_PLAYER { + room: Entities.SFSRoom; + user: Entities.SFSUser; + playerId: number; + } + + interface ISPECTATOR_TO_PLAYER_ERROR { + errorMessage: string; + errorCode: number; + } + + interface IUSER_COUNT_CHANGE { + room: Entities.SFSRoom; + uCount: number; + sCount: number; + } + + interface IUSER_ENTER_ROOM { + user: Entities.SFSUser; + room: Entities.SFSRoom; + } + + interface IUSER_EXIT_ROOM { + user: Entities.SFSUser; + room: Entities.SFSRoom; + } + + interface IUSER_FIND_RESULT { + users: Entities.SFSUser[]; + } + + interface IUSER_VARIABLES_UPDATE { + user: Entities.SFSUser; + changedVars: string[]; + } + //#endregion + //#region SmartFox + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.SmartFox.html + export class SmartFox { + + /** @type {Managers.BuddyManager} Returns a reference to the Buddy Manager. */ + buddyManager: Managers.BuddyManager; + /** @type {IconfigObj} Returns the client configuration object passed during the SmartFox instance creation. */ + config: IconfigObj; + /** @type {boolean} Indicates whether the client-server messages console debug is enabled or not. */ + debug: boolean; + /** @type {Entities.SFSRoom} Returns the object representing the last Room joined by the client, if any. */ + lastJoinedRoom: Entities.SFSRoom; + /** @type {Logger} Returns a reference to the internal Logger instance used by SmartFoxServer 2X. */ + logger: Logger; + /** @type {Entities.SFSUser} Returns the SFSUser object representing the client itself when connected to a SmartFoxServer 2X instance. */ + mySelf: Entities.SFSUser; + /** @type {Managers.RoomManager} Returns a reference to the Room Manager. */ + roomManager: Managers.RoomManager; + /** @type {string} Returns the unique session token of the client. */ + sessionToken: string; + /** @type {Managers.UserManager} Returns a reference to the User Manager. */ + userManager: Managers.UserManager; + /** @type {string} Returns the current version of the SmartFoxServer 2X JavaScript API. */ + version: string; + + /** + * Creates a new SmartFox instance. + * @param {IconfigObj} configObj The SmartFox instance can be configured through a configuration object with the following properties (all optional). + */ + constructor(configObj?: IconfigObj); + /** + * Registers an event listener function that will receive notification of an event. + * @param {string} evtType The type of event to listen to, among those available in the SFSevent and SFSBuddyEvent classes. + * @param {Function} listener The listener function that processes the event. This function should accept an object as its only parameter, which in turn contains the event parameters. + * @param {number} scope The object that acts as a context for the event listener: it is the object that acts as a "parent scope" for the callback function, thus providing context (i.e. access to variables and other mehtods) to the function itself. + */ + addEventListener(evtType: string, listener: Function, scope: number): void; + /** + * Establishes a connection between the client and a SmartFoxServer 2X instance. + * @param {string} [host] The address of the server to connect to. + * @param {number} [port] The TCP port to connect to. + * @param {boolean} [useSSL] Use an encrypted SSL connection. + */ + connect(host?: string, port?: number, useSSL?: boolean): void; + /** + * Closes the connection between the client and the SmartFoxServer 2X instance. + */ + disconnect(): void; + /** + * Enables the automatic realtime monitoring of the lag between the client and the server (round robin). + * @param {boolean} enabled The lag monitoring status: true to start the monitoring, false to stop it. + * @param {number} [interval=4] The amount of seconds to wait between each query (recommended 3-4s). + * @param {number} [queueSize=10] The amount of values stored temporarily and used to calculate the average lag. + */ + enableLagMonitor(enabled: boolean, interval?: number, queueSize?: number): void; + /** + * Returns a list of SFSRoom objects representing the Rooms currently joined by the client. + * @return {Entities.SFSRoom[]} Returns: The list of SFSRoom objects representing the Rooms joined by the client. + */ + getJoinedRooms(): Entities.SFSRoom[]; + /** + * Returns the maximum size of messages allowed by the server. + * @return {number} Returns: The maximum size of messages allowed by the server. + */ + getMaxMessageSize(): number; + /** + * Retrieves a SFSRoom object from its id. + * @param {number} id The id of the Room. + * @return {Entities.SFSRoom} Returns: The object representing the requested Room; null if no SFSRoom object with the passed id exists in the Rooms list. + */ + getRoomById(id: number): Entities.SFSRoom; + /** + * Retrieves a SFSRoom object from its name. + * @param {string} name The name of the Room. + * @return {Entities.SFSRoom} Returns: The object representing the requested Room; null if no SFSRoom object with the passed name exists in the Rooms list. + */ + getRoomByName(name: string): Entities.SFSRoom; + /** + * Returns the list of SFSRoom objects representing the Rooms currently "watched" by the client. + * @return {Entities.SFSRoom[]} Returns: The list of SFSRoom objects representing the Rooms available on the client. + */ + getRoomList(): Entities.SFSRoom[]; + /** + * Retrieves the list of Rooms which are part of the specified Room Group. + * @param {string} groupId The name of the Group. + * @return {Entities.SFSRoom} Returns: The list of SFSRoom objects belonging to the passed Group. + */ + getRoomListFromGroup(groupId: string): Entities.SFSRoom; + /** + * Indicates whether the client is connected to the server or not. + * @return {boolean} Returns: true if the client is connected. + */ + isConnected(): boolean; + /** + * Removes an event listener. + * @param {string} evtType The type of event to remove, among those available in the SFSevent and SFSBuddyEvent classes. + * @param {Function} listener The listener function to be removed. + */ + removeEventListener(evtType: string, listener: Function): void; + /** + * Sends a request to the server. + * @param {(Requests.BuddyList.AddBuddyRequest | Requests.BuddyList.BlockBuddyRequest | Requests.BuddyList.BuddyMessageRequest | Requests.BuddyList.GoOnlineRequest | Requests.BuddyList.InitBuddyListRequest | Requests.BuddyList.RemoveBuddyRequest | Requests.BuddyList.SetBuddyVariablesRequest | Requests.Game.CreateSFSGameRequest | Requests.Game.InvitationReplyRequest | Requests.Game.InviteUsersRequest | Requests.Game.QuickJoinGameRequest | Requests.MMO.SetUserPositionRequest | Requests.System.AdminMessageRequest | Requests.System.BanUserRequest | Requests.System.ChangeRoomCapacityRequest | Requests.System.ChangeRoomNameRequest | Requests.System.ChangeRoomPasswordStateRequest | Requests.System.CreateRoomRequest | Requests.System.ExtensionRequest | Requests.System.FindRoomsRequest | Requests.System.FindUsersRequest | Requests.System.JoinRoomRequest | Requests.System.KickUserRequest | Requests.System.LeaveRoomRequest | Requests.System.LoginRequest | Requests.System.LogoutRequest | Requests.System.ModeratorMessageRequest | Requests.System.ObjectMessageRequest | Requests.System.PlayerToSpectatorRequest | Requests.System.PrivateMessageRequest | Requests.System.PublicMessageRequest | Requests.System.SetRoomVariablesRequest | Requests.System.SetUserVariablesRequest | Requests.System.SpectatorToPlayerRequest | Requests.System.SubscribeRoomGroupRequest | Requests.System.UnsubscribeRoomGroupRequest)} request Sends a request to the server. + */ + send(request: Requests.BuddyList.AddBuddyRequest | Requests.BuddyList.BlockBuddyRequest | Requests.BuddyList.BuddyMessageRequest | Requests.BuddyList.GoOnlineRequest | Requests.BuddyList.InitBuddyListRequest | Requests.BuddyList.RemoveBuddyRequest | Requests.BuddyList.SetBuddyVariablesRequest | Requests.Game.CreateSFSGameRequest | Requests.Game.InvitationReplyRequest | Requests.Game.InviteUsersRequest | Requests.Game.QuickJoinGameRequest | Requests.MMO.SetUserPositionRequest | Requests.System.AdminMessageRequest | Requests.System.BanUserRequest | Requests.System.ChangeRoomCapacityRequest | Requests.System.ChangeRoomNameRequest | Requests.System.ChangeRoomPasswordStateRequest | Requests.System.CreateRoomRequest | Requests.System.ExtensionRequest | Requests.System.FindRoomsRequest | Requests.System.FindUsersRequest | Requests.System.JoinRoomRequest | Requests.System.KickUserRequest | Requests.System.LeaveRoomRequest | Requests.System.LoginRequest | Requests.System.LogoutRequest | Requests.System.ModeratorMessageRequest | Requests.System.ObjectMessageRequest | Requests.System.PlayerToSpectatorRequest | Requests.System.PrivateMessageRequest | Requests.System.PublicMessageRequest | Requests.System.SetRoomVariablesRequest | Requests.System.SetUserVariablesRequest | Requests.System.SpectatorToPlayerRequest | Requests.System.SubscribeRoomGroupRequest | Requests.System.UnsubscribeRoomGroupRequest): void; + /** + * Allows to specify custom client details that will be used to gather statistics about the client platform via the AdminTool's Analytics Module. + * @param {string} platformId An identification string for the client, like the browser name for example. + * @param {string} version An additional string to describe the client version, like the browser version for example. + */ + setClientDetails(platformId: string, version: string): void; + } + + export interface IconfigObj { + /** @type {string} The IP address or host name of the SmartFoxServer 2X instance to connect to. */ + host?: string; + /** @type {number} The TCP port of the SmartFoxServer 2X instance to connect to. */ + port?: number; + /** @type {boolean} Use an encrypted SSL connection. */ + useSSL?: boolean; + /** @type {string} The Zone of the SmartFoxServer 2X instance to join during the login process. */ + zone?: string; + /** @type {boolean} Indicates whether the client-server messages console debug should be enabled or not. */ + debug?: boolean; + } + //#endregion + //#region Utils + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Utils.html + namespace Utils { + + //#region ClientDisconnectionReason + + // http://docs2x.smartfoxserver.com/api-docs/jsdoc/symbols/SFS2X.Utils.ClientDisconnectionReason.html + export class ClientDisconnectionReason { + + /** @type {string} Client was banned from the server. */ + static BAN: string; + /** @type {string} Client was disconnected because it was idle for too long. */ + static IDLE: string; + /** @type {string} Client was kicked out of the server. */ + static KICK: string; + /** @type {string} The client manually disconnected from the server. */ + static MANUAL: string; + /** @type {string} A generic network error occurred, and the client is unable to determine the cause of the disconnection. */ + static UNKNOWN: string; + + } + //#endregion + + } + //#endregion + +} +//#endregion diff --git a/smoothie/smoothie.d.ts b/smoothie/smoothie.d.ts index 98f205f598..c396261c52 100644 --- a/smoothie/smoothie.d.ts +++ b/smoothie/smoothie.d.ts @@ -141,6 +141,8 @@ declare module "smoothie" */ export class SmoothieChart { + options: IChartOptions; + constructor(chartOptions?: IChartOptions); /** @@ -188,5 +190,7 @@ declare module "smoothie" updateValueRange(): void; render(canvas?: HTMLCanvasElement, time?: number): void; + + static timeFormatter(date: Date): string; } } diff --git a/soap/soap.d.ts b/soap/soap.d.ts index 6fcd1b703f..499b6422ee 100644 --- a/soap/soap.d.ts +++ b/soap/soap.d.ts @@ -11,7 +11,7 @@ declare module 'soap' { interface Security { } class WSSecurity implements Security { - constructor(username: string, password: string, options: any); + constructor(username: string, password: string, options?: any); } class ClientSSLSecurity implements Security { constructor(key: string, cert: string, ca: string, defaults: any); diff --git a/socket.io-parser/socket.io-parser-tests.ts b/socket.io-parser/socket.io-parser-tests.ts new file mode 100644 index 0000000000..917f72500f --- /dev/null +++ b/socket.io-parser/socket.io-parser-tests.ts @@ -0,0 +1,41 @@ +/// +/// + +import * as parser from 'socket.io-parser'; +var encoder = new parser.Encoder(); +var packet = { + type: parser.EVENT, + data: 'test-packet', + id: 13 +}; +encoder.encode(packet, function (encodedPackets) { + var decoder = new parser.Decoder(); + decoder.on('decoded', function (decodedPacket) { + decodedPacket.type == parser.EVENT + decodedPacket.data == 'test-packet' + decodedPacket.id == 13 + }); + + for (var i = 0; i < encodedPackets.length; i++) { + decoder.add(encodedPackets[i]); + } +}); + +var packet2 = { + type: parser.BINARY_EVENT, + data: { i: new Buffer(1234), j: new Blob([new ArrayBuffer(2)]) }, + id: 15 +}; +encoder.encode(packet2, function (encodedPackets) { + var decoder = new parser.Decoder(); + decoder.on('decoded', function (decodedPacket) { + decodedPacket.type == parser.BINARY_EVENT + Buffer.isBuffer(decodedPacket.data.i) == true + Buffer.isBuffer(decodedPacket.data.j) == true + decodedPacket.id == 15 + }); + + for (var i = 0; i < encodedPackets.length; i++) { + decoder.add(encodedPackets[i]); + } +}); diff --git a/socket.io-parser/socket.io-parser.d.ts b/socket.io-parser/socket.io-parser.d.ts new file mode 100644 index 0000000000..0c4903fda4 --- /dev/null +++ b/socket.io-parser/socket.io-parser.d.ts @@ -0,0 +1,39 @@ +// Type definitions for json-editor +// Project: https://github.com/socketio/socket.io-parser +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "socket.io-parser" { + namespace Parser { + type Packet = { + type: number, + data: any, + id: number + } + type EncodedPacket = string | Buffer | ArrayBuffer | Blob; + + var types: string[]; + + var CONNECT: number; + var DISCONNECT: number; + var EVENT: number; + var ACK: number; + var ERROR: number; + var BINARY_EVENT: number; + var BINARY_ACK: number; + + class Encoder { + encode(packet: Packet, callback: (encodedPackets: EncodedPacket[]) => void): void; + } + + class Decoder { + on(event: string, callback: (decodedPacket: Packet) => void): void; + add(encodedPacket: EncodedPacket): void; + destroy(): void; + } + } + + export = Parser; +} diff --git a/socket.io-redis/socket.io-redis.d.ts b/socket.io-redis/socket.io-redis.d.ts index b3eb44e5ec..b35472c32b 100644 --- a/socket.io-redis/socket.io-redis.d.ts +++ b/socket.io-redis/socket.io-redis.d.ts @@ -58,7 +58,7 @@ declare namespace SocketIORedis { * The optional port to connect to redis on * @default 6379 */ - port?: string; + port?: number; /** * The optional redis client to publish events on diff --git a/socket.io/socket.io.d.ts b/socket.io/socket.io.d.ts index ad95f39ef3..82e4dcacc3 100644 --- a/socket.io/socket.io.d.ts +++ b/socket.io/socket.io.d.ts @@ -47,7 +47,8 @@ interface SocketIOStatic { declare namespace SocketIO { interface Server { - + engine: { ws: any }; + /** * A dictionary of all the namespaces currently on this Server */ @@ -752,7 +753,7 @@ declare namespace SocketIO { * A dictionary of all the rooms that we have in this namespace * The rooms are made of a `sockets` key which is the dictionary of sockets per ID */ - rooms: {[room: string]: {sockets: {[id: string]: boolean }}}; + rooms: {[room: string]: {sockets: {[id: string]: boolean }, length: number }}; /** * A dictionary of all the socket ids that we're dealing with, and all diff --git a/solution-center-communicator/solution-center-communicator-tests.ts b/solution-center-communicator/solution-center-communicator-tests.ts new file mode 100644 index 0000000000..ce5981bf5b --- /dev/null +++ b/solution-center-communicator/solution-center-communicator-tests.ts @@ -0,0 +1,22 @@ +/// + +import * as ScCommunicator from 'solution-center-communicator'; + +var environment: ScCommunicator.Environment = { + NAME: 'TEST', + URL: 'https://norris.test.zalan.do', + DOMAIN: '.zalan.do', + PORT: '', + USER_SERVICE: 'https://um.norris.test.zalan.do', + TOKEN_SERVICE: 'https://tm.norris.test.zalan.do', + MODULE_SERVICE: 'https://ms.norris.test.zalan.do' +}; + +var environments: ScCommunicator.Environments; +environments.TESTING = environment; + +var environmentsProvider: ScCommunicator.ScEnvironmentsProvider; + +environmentsProvider.setCurrentEnvironment(environment); +environmentsProvider.getCurrentEnvironment(); +environmentsProvider.getSpecificEnvironment('TESTING'); diff --git a/solution-center-communicator/solution-center-communicator.d.ts b/solution-center-communicator/solution-center-communicator.d.ts new file mode 100644 index 0000000000..5351e7f72e --- /dev/null +++ b/solution-center-communicator/solution-center-communicator.d.ts @@ -0,0 +1,125 @@ +// Type definitions for Solution Center Communicator 2.2.0 +// Project: https://github.com/zalando-incubator/solution-center-communicator +// Definitions by: Damián García +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace ScCommunicator { + + interface Environment { + /** + * Name of the environment + */ + NAME: string; + + /** + * URL where to reach the frontend of the environment + */ + URL: string; + + /** + * Domain where to set a cookie in case it's needed for that environment + */ + DOMAIN: string; + + /** + * In case that the domain is localhost, a port can be also specified + */ + PORT?: string; + + /** + * URL where to reach the user management service API + */ + USER_SERVICE?: string; + + /** + * URL where to reach the token management service API + */ + TOKEN_SERVICE?: string; + + /** + * URL where to reach the merchant management service API + */ + MERCHANT_SERVICE?: string; + + /** + * URL where to reach the GoodData service API + */ + GOODDATA_SERVICE?: string; + + /** + * URL where to reach the module service API + */ + MODULE_SERVICE?: string; + } + + interface Environments { + /** + * Production environment + */ + PRODUCTION: Environment; + + /** + * Stage environment + */ + STAGE: Environment; + + /** + * Integration environment + */ + INTEGRATION: Environment; + + /** + * Development environment + */ + DEVELOPMENT: Environment; + + /** + * Local environment + */ + LOCAL: Environment; + + /** + * Testing environment + */ + TESTING: Environment; + } + + interface ScEnvironmentsProvider { + + /** + * Get current environment + * If environment was not previously configured, use default environment + * + * @public + * @returns {Object} Current or default environment + */ + getCurrentEnvironment(): Environment; + + /** + * Get specific environment + * + * @public + * @param {string} name - Environment name + * @returns {Object} Specific or default environment + */ + getSpecificEnvironment(name: string): Environment; + + /** + * Set current environment + * + * @public + * @param {string|Object} env - Environment name or custom environment object + * @returns {Object} Named or custom environment + */ + setCurrentEnvironment(env: any): Environment; + + /** + * Access to the public methods of the service + */ + $get(): any; + } +} + +declare module "solution-center-communicator" { + export = ScCommunicator; +} diff --git a/sortablejs/sortablejs.d.ts b/sortablejs/sortablejs.d.ts index 1348a57fbb..87ca56e7c3 100644 --- a/sortablejs/sortablejs.d.ts +++ b/sortablejs/sortablejs.d.ts @@ -202,7 +202,7 @@ declare namespace Sortablejs { import Sortable = Sortablejs.Sortable; -declare module 'Sortable' { +declare module 'sortablejs' { import Sortable = Sortablejs.Sortable; export = Sortable; } diff --git a/spectacle/spectacle-tests.tsx b/spectacle/spectacle-tests.tsx new file mode 100644 index 0000000000..f8c84b6455 --- /dev/null +++ b/spectacle/spectacle-tests.tsx @@ -0,0 +1,114 @@ +/// +/// + +/** + * Spectacle Test Examples + * + */ + +import * as React from 'react'; +import { + Appear, + BlockQuote, + Cite, + Deck, + Fill, + Heading, + Layout, + Link, + ListItem, + List, + Quote, + Slide, + Spectacle, + Text +} from "spectacle"; + +export class SpectacleTest extends React.Component { + callback() { + alert('Callback: ' + JSON.stringify(arguments)); + } + + public render() { + return ( + + + + Spectacle + + + A ReactJS Presentation Library + + + Where You Can Write Your Decks In JSX + + + View on Github + + Hit Your Right Arrow To Begin! + + + + Wait what? + + + + + + Full Width + + + + + Adjustable Darkness + + + + + Background Imagery + + + + + Flexible Layouts + + + + Left + + + + + Right + + + + + +
      + Wonderfully formatted quotes + Ken Wheeler +
      +
      + + + Smooth + + + Combinable Transitions + + + + + Inline style based theme system + Autofit text + Flexbox layout system + React-Router navigation + PDF export + And... + + +
      +
      ); + } +} diff --git a/spectacle/spectacle.d.ts b/spectacle/spectacle.d.ts new file mode 100644 index 0000000000..05f8d9d528 --- /dev/null +++ b/spectacle/spectacle.d.ts @@ -0,0 +1,148 @@ +// Type definitions for Spectacle 1.1.1 +// Project: https://github.com/FormidableLabs/victory +// Definitions by: Zachary Maybury +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +declare module "spectacle" { + import * as React from "react"; + + /** + * Transition Types for Spectacle + */ + type transitionType = "slide"|"zoom"|"fade"|"spin"; + + /** + * Progress Types for Spectacle + */ + type progressType = "pacman"|"bar"|"number"|"none"; + + /** + * Alignment Types for Spectacle + */ + type alignType = + "flex-start flex-start"|"flex-start center"|"flex-start flex-end"| + "center flex-start"|"center center"|"center flex-end"| + "flex-end flex-start"|"flex-end center"|"flex-end flex-end"; + + /** + * Base props for many Spectacle components + */ + export interface BaseProps { + italic?:boolean, + bold?:boolean, + caps?:boolean, + margin?:number|string, + padding?:number|string, + textColor?:string, + textSize?:string, + textAlign?:string, + textFont?:string, + bgColor?:string, + bgImage?:string, + bgDarken?:number + } + + export interface SpectacleProps { + theme?:{ [key: string ]: string | number } + } + + export interface DeckProps { + transition?:transitionType[], + transitionDuration?:number, + progress?:progressType, + controls?:boolean + } + + export interface SlideProps extends BaseProps { + align?:alignType, + transition?:transitionType[], + transitionDuration?:number, + notes?:string, + id?:string + } + + export interface MarkdownProps { + source?:string, + mdastConfig?:{ [key: string ]: string | number } + } + + export interface CodePaneProps extends BaseProps { + lang?:string, + source?:string + } + + export interface HeadingProps extends BaseProps { + fit?:boolean, + lineHeight?:number + size?:number; + } + + export interface ImageProps extends BaseProps { + display?:string, + height?:number, + src?:string, + width?:number|string + } + + export interface LinkProps extends BaseProps { + href?:string + } + + export interface SProps extends BaseProps { + type?:string + } + + export interface TextProps extends BaseProps { + fit?:boolean, + lineHeight?:number + } + + export class Spectacle extends React.Component {} + + export class Deck extends React.Component {} + + export class Slide extends React.Component {} + + export class Layout extends React.Component {} + + export class Fit extends React.Component {} + + export class Fill extends React.Component {} + + export class Markdown extends React.Component {} + + export class Appear extends React.Component {} + + export class BlockQuote extends React.Component {} + + export class Quote extends React.Component {} + + export class Cite extends React.Component {} + + export class CodePane extends React.Component {} + + export class Code extends React.Component {} + + export class Heading extends React.Component {} + + export class Image extends React.Component {} + + export class Link extends React.Component {} + + export class List extends React.Component {} + + export class ListItem extends React.Component {} + + export class S extends React.Component {} + + export class Table extends React.Component {} + + export class TableRow extends React.Component {} + + export class TableHeaderItem extends React.Component {} + + export class TableItem extends React.Component {} + + export class Text extends React.Component {} +} \ No newline at end of file diff --git a/spin/spin.d.ts b/spin/spin.d.ts index 0dc877c953..ea9ca7aae7 100644 --- a/spin/spin.d.ts +++ b/spin/spin.d.ts @@ -48,3 +48,7 @@ declare class Spinner { lines(el:HTMLElement, o:SpinnerOptions):HTMLElement; opacity(el:HTMLElement, i:number, val:number, o:SpinnerOptions):void; } + +declare module "spin.js" { + export = Spinner; +} diff --git a/sql.js/sql.js-tests.ts b/sql.js/sql.js-tests.ts index 40fceb8fbd..ece6e536e4 100644 --- a/sql.js/sql.js-tests.ts +++ b/sql.js/sql.js-tests.ts @@ -1,8 +1,8 @@ /// /// -import fs = require("fs"); -import SQL = require("sql.js"); +import * as fs from "fs"; +import * as SQL from "sql.js"; var DB_PATH = "data.db"; @@ -34,6 +34,8 @@ db.run(insertRecordStatement, { "@content": "Content 2" }); +var n = db.getRowsModified(); + try { // This query will throw exception: primary key constraint failed. db.run(insertRecordStatement, { @@ -79,3 +81,14 @@ function dbAccessDone(): void { // Finally, close the database connection and release the resources in memory. db.close(); } + +// Create a database +var db2 = new SQL.Database(); + +// You can also use javascript functions inside your SQL code +// Create the js function you need +function add(a: number, b: number): number {return a+b;} +// Specifies the SQL function's name, the number of it's arguments, and the js function to use +db2.create_function("add_js", add); +// Run a query in which the function is used +db2.run("INSERT INTO hello VALUES (add_js(7, 3), add_js('Hello ', 'world'));"); // Inserts 10 and 'Hello world' diff --git a/sql.js/sql.js.d.ts b/sql.js/sql.js.d.ts index 67f0a183c2..c5ebb67023 100644 --- a/sql.js/sql.js.d.ts +++ b/sql.js/sql.js.d.ts @@ -8,6 +8,7 @@ declare module "sql.js" { class Database { + constructor(); constructor(data: Buffer); constructor(data: Uint8Array); constructor(data: number[]); @@ -29,6 +30,10 @@ declare module "sql.js" { export(): Uint8Array; close(): void; + + getRowsModified(): number; + + create_function(name: string, func: Function): void; } class Statement { diff --git a/sqlite3/sqlite3-tests.ts b/sqlite3/sqlite3-tests.ts index 7059a439af..1905b9efac 100644 --- a/sqlite3/sqlite3-tests.ts +++ b/sqlite3/sqlite3-tests.ts @@ -32,10 +32,17 @@ function readAllRows() { rows.forEach(function (row) { console.log(row.id + ": " + row.info); }); - closeDb(); + readSomeRows(); }); } +function readSomeRows() { + console.log("readAllRows lorem"); + db.each("SELECT rowid AS id, info FROM lorem WHERE rowid < ? ", 5, function(err, row) { + console.log(row.id + ": " + row.info); + }, closeDb); +} + function closeDb() { console.log("closeDb"); db.close(); @@ -64,7 +71,7 @@ db.serialize(function() { db.serialize(function() { // These two queries will run sequentially. db.run("CREATE TABLE foo (num)"); - db.run("INSERT INTO foo VALUES (?)", 1, function() { + db.run("INSERT INTO foo VALUES (?)", 1, function(err) { // These queries will run in parallel and the second query will probably // fail because the table might not exist yet. db.run("CREATE TABLE bar (num)"); @@ -83,6 +90,9 @@ db.run("UPDATE tbl SET name = $name WHERE id = $id", { $id: 2, $name: "bar" }); +db.run("UPDATE tbl SET name = $name WHERE id = $id", { $id: 2, $name: "bar" }, + function(err) { } +); db.run("UPDATE tbl SET name = ?5 WHERE id = ?", { 1: 2, diff --git a/sqlite3/sqlite3.d.ts b/sqlite3/sqlite3.d.ts index dbc205cc0e..d4f4225689 100644 --- a/sqlite3/sqlite3.d.ts +++ b/sqlite3/sqlite3.d.ts @@ -31,15 +31,19 @@ declare module "sqlite3" { public finalize(callback?: (err: Error) => void): Statement; public run(callback?: (err: Error) => void): Statement; + public run(params: any, callback?: (err: Error) => void): Statement; public run(...params: any[]): Statement; public get(callback?: (err: Error, row: any) => void): Statement; + public get(params: any, callback?: (err: Error, row: any) => void): Statement; public get(...params: any[]): Statement; public all(callback?: (err: Error, rows: any[]) => void): Statement; + public all(params: any, callback?: (err: Error, rows: any[]) => void): Statement; public all(...params: any[]): Statement; public each(callback?: (err: Error, row: any) => void, complete?: (err: Error, count: number) => void): Statement; + public each(params: any, callback?: (err: Error, row: any) => void, complete?: (err: Error, count: number) => void): Statement; public each(...params: any[]): Statement; } @@ -50,20 +54,25 @@ declare module "sqlite3" { public close(callback?: (err: Error) => void): void; public run(sql: string, callback?: (err: Error) => void): Database; + public run(sql: string, params: any, callback?: (err: Error) => void): Database; public run(sql: string, ...params: any[]): Database; public get(sql: string, callback?: (err: Error, row: any) => void): Database; + public get(sql: string, params: any, callback?: (err: Error, row: any) => void): Database; public get(sql: string, ...params: any[]): Database; public all(sql: string, callback?: (err: Error, rows: any[]) => void): Database; + public all(sql: string, params: any, callback?: (err: Error, rows: any[]) => void): Database; public all(sql: string, ...params: any[]): Database; public each(sql: string, callback?: (err: Error, row: any) => void, complete?: (err: Error, count: number) => void): Database; + public each(sql: string, params: any, callback?: (err: Error, row: any) => void, complete?: (err: Error, count: number) => void): Database; public each(sql: string, ...params: any[]): Database; public exec(sql: string, callback?: (err: Error) => void): Database; public prepare(sql: string, callback?: (err: Error) => void): Statement; + public prepare(sql: string, params: any, callback?: (err: Error) => void): Statement; public prepare(sql: string, ...params: any[]): Statement; public serialize(callback?: () => void): void; diff --git a/ssh2-sftp-client/ssh2-sftp-client-tests.ts b/ssh2-sftp-client/ssh2-sftp-client-tests.ts new file mode 100644 index 0000000000..0c2709bf61 --- /dev/null +++ b/ssh2-sftp-client/ssh2-sftp-client-tests.ts @@ -0,0 +1,27 @@ +/// + +import * as Client from 'ssh2-sftp-client'; +var client = new Client(); + +client.connect({ + host: 'asdb', + port: 1234, + privateKey: 'my private key rsa in openssh format', + readyTimeout: 1000, +}).then(() => null); + +client.list('/remote/path').then(() => null); + +client.get('/remote/path').then(stream => stream.read(0)); + +client.put('/local/path', '/remote/path').then(() => null); + +client.put(new Buffer('content'), '/remote/path').then(() => null); + +client.mkdir('/remote/path/dir', true).then(() => null); + +client.delete('remote/path').then(() => null); + +client.remove('/remote/from', '/remote/to').then(() => null); + +client.end().then(() => null); \ No newline at end of file diff --git a/ssh2-sftp-client/ssh2-sftp-client.d.ts b/ssh2-sftp-client/ssh2-sftp-client.d.ts new file mode 100644 index 0000000000..1676ad0077 --- /dev/null +++ b/ssh2-sftp-client/ssh2-sftp-client.d.ts @@ -0,0 +1,47 @@ +// Type definitions for ssh2-sftp-client v1.0.5 +// Project: https://www.npmjs.com/package/ssh2-sftp-client +// Definitions by: igrayson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "ssh2-sftp-client" { + import * as ssh2 from 'ssh2'; + + namespace sftp { + + interface FileInfo { + type:string; + name:string; + size:number; + modifyTime:number; + accessTime:number; + rights:{ + user:string; + group:string; + other:string; + }; + owner:number; + group:number; + } + + interface Client { + new():Client; + connect(options:ssh2.ConnectConfig):Promise; + list(remoteFilePath:string):Promise>; + get(remoteFilePath:string, useCompression?:boolean):Promise; + put(localFilePath:string, remoteFilePath:string, useCompression?:boolean):Promise; + put(buffer:Buffer, remoteFilePath:string, useCompression?:boolean):Promise; + put(stream:NodeJS.ReadableStream, remoteFilePath:string, useCompression?:boolean):Promise; + mkdir(remoteFilePath:string, recursive?:boolean):Promise; + delete(remoteFilePath:string):Promise; + remove(remoteSourcePath:string, remoteDestPath:string):Promise; + end():Promise; + } + } + + var sftp:sftp.Client; + + export = sftp; +} + diff --git a/stamplay-js-sdk/stamplay-js-sdk.d.ts b/stamplay-js-sdk/stamplay-js-sdk.d.ts index 952ed78ea0..1f2ec68500 100644 --- a/stamplay-js-sdk/stamplay-js-sdk.d.ts +++ b/stamplay-js-sdk/stamplay-js-sdk.d.ts @@ -3,7 +3,7 @@ // Definitions by: Riderman de Sousa Barbosa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Stamplay { diff --git a/state-machine/state-machine-tests.ts b/state-machine/state-machine-tests.ts index 7c7c705e31..b70d139b04 100644 --- a/state-machine/state-machine-tests.ts +++ b/state-machine/state-machine-tests.ts @@ -28,3 +28,5 @@ var fsm: StateMachineTest = StateMachine.create({ //fsm.panic("ERROR ALERT"); // transition from yellow to red //fsm.calm(); // transition from red to yellow //fsm.clear("All clear"); // transition from yellow to green + +let transitions: Array = fsm.transitions(); diff --git a/state-machine/state-machine.d.ts b/state-machine/state-machine.d.ts index b3f5446531..5ece36c4c1 100644 --- a/state-machine/state-machine.d.ts +++ b/state-machine/state-machine.d.ts @@ -35,7 +35,7 @@ interface StateMachineStatic { VERSION: string; // = "2.3.5" WILDCARD: string; // = '*' - ASYNC: string; // = 'async' + ASYNC: string; // = 'async' Result: { SUCCEEDED: number; // = 1, the event transitioned successfully from one state to another @@ -66,6 +66,10 @@ interface StateMachineCan { (evt: string): boolean; } +interface StateMachineTransitions { + (): Array; +} + interface StateMachine { current: string; is: StateMachineIs; @@ -75,13 +79,19 @@ interface StateMachine { isFinished: StateMachineIsFinished; /* transition - only available when performing async state transitions; otherwise null. Can be a: [1] fsm.transition(); // called from async callback - [2] fsm.transition.cancel(); + [2] fsm.transition.cancel(); */ transition: StateMachineTransition; + transitions: StateMachineTransitions; } declare var StateMachine: StateMachineStatic; -declare module "state-machine" { - export = StateMachine; +declare module "state-machine" { + export = StateMachine; +} + +declare module "javascript-state-machine" { + + export let StateMachine: StateMachineStatic; } diff --git a/statsd-client/statsd-client-import-asterisk-tests.ts b/statsd-client/statsd-client-import-asterisk-tests.ts new file mode 100644 index 0000000000..b01d523042 --- /dev/null +++ b/statsd-client/statsd-client-import-asterisk-tests.ts @@ -0,0 +1,3 @@ +/// +import * as StatsdClient from 'statsd-client'; +const statsd = new StatsdClient({ debug: true }); diff --git a/statsd-client/statsd-client.d.ts b/statsd-client/statsd-client.d.ts index 2fabcfb83f..b5c8bba2ef 100644 --- a/statsd-client/statsd-client.d.ts +++ b/statsd-client/statsd-client.d.ts @@ -99,5 +99,6 @@ declare module "statsd-client" { getChildClient(name: string): StatsdClient; } + namespace StatsdClient {} export = StatsdClient; } diff --git a/steam/steam.d.ts b/steam/steam.d.ts index 6deb9f432e..fcf49fa5a4 100644 --- a/steam/steam.d.ts +++ b/steam/steam.d.ts @@ -31,7 +31,7 @@ declare namespace Steam { Kicked } - export class SteamClient implements NodeJS.EventEmitter { + export class SteamClient extends NodeJS.EventEmitter { sessionId: string; cookie: string[]; steamID: string; diff --git a/strftime/strftime-tests.ts b/strftime/strftime-tests.ts new file mode 100644 index 0000000000..3f24a53c48 --- /dev/null +++ b/strftime/strftime-tests.ts @@ -0,0 +1,37 @@ +/// + +import * as strftime from "strftime"; + +strftime('%B %d, %Y %H:%M:%S'); +strftime('%F %T', new Date(1307472705067)); + +var it_IT = { + days: ['domenica', 'lunedi', 'martedi', 'mercoledi', 'giovedi', 'venerdi', 'sabato'], + shortDays: ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab'], + months: ['gennaio', 'febbraio', 'marzo', 'aprile', 'maggio', 'giugno', 'luglio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dicembre'], + shortMonths: ['gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 'nov', 'dic'], + AM: 'AM', + PM: 'PM', + am: 'am', + pm: 'pm', + formats: { + D: '%m/%d/%y', + F: '%Y-%m-%d', + R: '%H:%M', + X: '%T', + c: '%a %b %d %X %Y', + r: '%I:%M:%S %p', + T: '%H:%M:%S', + v: '%e-%b-%Y', + x: '%D' + } +}; + +var strftimeIT = strftime.localize(it_IT); +strftimeIT('%B %d, %Y %H:%M:%S'); +strftimeIT('%B %d, %Y %H:%M:%S', new Date(1307472705067)); + +var strftimePDT = strftime.timezone(-420); +var strftimeCEST = strftime.timezone(120); +strftimePDT('%B %d, %y %H:%M:%S', new Date(1307472705067)); +strftimeCEST('%F %T', new Date(1307472705067)); \ No newline at end of file diff --git a/strftime/strftime.d.ts b/strftime/strftime.d.ts new file mode 100644 index 0000000000..4c4b8ad835 --- /dev/null +++ b/strftime/strftime.d.ts @@ -0,0 +1,72 @@ +// Type definitions for strftime 0.9.2 +// Project: https://github.com/samsonjs/strftime +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "strftime" { + type strftimeFunction = (format: string, date?: Date) => string; + + namespace strftime { + /** + * Sets locale. + * @param {Locale} locale A locale. + * @return {strftimeFunction} A strftime function. + */ + export function localize(locale: Locale): strftimeFunction; + + /** + * Sets timezone. + * @param {number|string} offset A offset. + * @return {strftimeFunction} A strftime function. + */ + export function timezone(offset: number | string): strftimeFunction; + + /** + * Locale formats. + * @interface + */ + export interface LocaleFormats { + D?: string; + F?: string; + R?: string; + T?: string; + X?: string; + c?: string; + r?: string; + v?: string; + x?: string; + } + + /** + * Locale. + * @interface + */ + export interface Locale { + days?: Array; + shortDays?: Array; + months?: Array; + shortMonths?: Array; + AM?: string; + PM?: string; + am?: string; + pm?: string; + formats: LocaleFormats + } + } + + /** + * Format a local time/date according to locale settings + * @param {string} format A format. + * @return {string} Returns a string formatted. + */ + function strftime(format: string): string; + + /** + * Format a local time/date according to locale settings + * @param {string} format A format. + * @param {Date} date A date. + * @return {string} Returns a string formatted according format using the given date or the current local time. + */ + function strftime(format: string, date: Date): string; + export = strftime; +} diff --git a/stripe-node/stripe-node.d.ts b/stripe-node/stripe-node.d.ts index 1e3d2caca7..cd2d41bf51 100644 --- a/stripe-node/stripe-node.d.ts +++ b/stripe-node/stripe-node.d.ts @@ -3,7 +3,7 @@ // Definitions by: William Johnston , Peter Harris // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// declare module 'stripe' { @@ -16,7 +16,7 @@ declare namespace StripeNode { new (apiKey: string, version?: string): Stripe; (apiKey: string, version?: string): Stripe; } - + interface StripeStatic { DEFAULT_HOST: string; DEFAULT_PORT: string; @@ -37,11 +37,11 @@ declare namespace StripeNode { resources: typeof resources; StripeResource: typeof StripeResource; } - - // Helper + + // Helper type IBankAccount = bankAccounts.IBankAccount; type ICard = cards.ICard; - + interface Stripe extends StripeStatic { accounts: resources.Accounts; balance: resources.Balance; @@ -72,11 +72,11 @@ declare namespace StripeNode { orders: resources.Orders; products: resources.Products; skus: resources.SKUs; - + setHost(host: string): void; setHost(host: string, port: string|number): void; setHost(host: string, port: string|number, protocol: string): void; - + setProtocol(protocol: string): void; setPort(port: string|number): void; setApiVersion(version?: string): void; @@ -86,274 +86,274 @@ declare namespace StripeNode { getConstant(c: string): any; getClientUserAgent(response: (userAgent: string) => void): void; } - - namespace accounts { + + namespace accounts { interface IAccount extends IResourceObject, IAccountShared { /** * Value is "account" */ object: string; - + /** * Whether or not the account can create live charges */ charges_enabled: boolean; - + /** * The country of the account */ country: string; - + /** - * Whether or not account details have been submitted yet. Standalone + * Whether or not account details have been submitted yet. Standalone * accounts cannot receive transfers before this is true. */ details_submitted: boolean; - + /** - * The display name for this account. This is used on the Stripe dashboard to + * The display name for this account. This is used on the Stripe dashboard to * help you differentiate between accounts. */ display_name: string; - + /** - * Whether or not Stripe will send automatic transfers for this account. This - * is only false when Stripe is waiting for additional information from the + * Whether or not Stripe will send automatic transfers for this account. This + * is only false when Stripe is waiting for additional information from the * account holder. */ transfers_enabled: boolean; - + /** - * The state of the account’s information requests, including what + * The state of the account’s information requests, including what * information is needed and by when it must be provided. */ verification: { /** - * A string describing the reason for this account being unable to charge - * and/or transfer, if that is the case. Possible values are "rejected.fraud", - * "rejected.terms_of_service", "rejected.listed", "rejected.other", + * A string describing the reason for this account being unable to charge + * and/or transfer, if that is the case. Possible values are "rejected.fraud", + * "rejected.terms_of_service", "rejected.listed", "rejected.other", * "fields_needed", "listed", or "other". */ disabled_reason: string; - + /** - * At what time the fields_needed must be provided. If this date is in - * the past, the account is already in bad standing, and providing - * fields_needed is necessary to re-enable transfers and prevent other - * consequences. If this date is in the future, fields_needed must be + * At what time the fields_needed must be provided. If this date is in + * the past, the account is already in bad standing, and providing + * fields_needed is necessary to re-enable transfers and prevent other + * consequences. If this date is in the future, fields_needed must be * provided to ensure the account remains in good standing. */ due_by: number; - + /** - * Field names that need to be provided for the account to remain in good - * standing. Nested fields are separated by "." (for example, + * Field names that need to be provided for the account to remain in good + * standing. Nested fields are separated by "." (for example, * "legal_entity.first_name"). */ fields_needed: Array; } } - + interface IAccountCreationOptions extends IAccountUpdateOptions { /** - * The country the account holder resides in or that the business is legally - * established in. For example, if you are in the United States and the - * business you’re creating an account for is legally represented in Canada, + * The country the account holder resides in or that the business is legally + * established in. For example, if you are in the United States and the + * business you’re creating an account for is legally represented in Canada, * you would use “CA” as the country for the account being created. */ country?: string; - + /** - * The email address of the account holder. For standalone accounts, Stripe - * will email your user with instructions for how to set up their account. For - * managed accounts, this is only to make the account easier to identify to + * The email address of the account holder. For standalone accounts, Stripe + * will email your user with instructions for how to set up their account. For + * managed accounts, this is only to make the account easier to identify to * you: Stripe will never directly reach out to your users. */ email: string; - + /** - * Whether you'd like to create a managed or standalone account. Managed - * accounts have extra parameters available to them, and require that you, - * the platform, handle all communication with the account holder. - * Standalone accounts are normal Stripe accounts: Stripe will email the - * account holder to setup a username and password, and handle all account + * Whether you'd like to create a managed or standalone account. Managed + * accounts have extra parameters available to them, and require that you, + * the platform, handle all communication with the account holder. + * Standalone accounts are normal Stripe accounts: Stripe will email the + * account holder to setup a username and password, and handle all account * management directly with them. */ managed?: boolean; } - + interface IAccountShared { business_logo?: string; - + /** * The publicly sharable name for this account */ business_name?: string; - + /** - * A CSS hex color value representing the primary branding color for this + * A CSS hex color value representing the primary branding color for this * account */ business_primary_color?: string; - + /** * The URL that best shows the service or product provided for this account */ business_url?: string; - + /** - * A boolean for whether or not Stripe should try to reclaim negative - * balances from the account holder’s bank account. See our managed + * A boolean for whether or not Stripe should try to reclaim negative + * balances from the account holder’s bank account. See our managed * account bank transfer guide for more information */ debit_negative_balances?: boolean; - + /** - * Account-level settings to automatically decline certain types of charges + * Account-level settings to automatically decline certain types of charges * regardless of the bank’s decision. */ decline_charge_on?: { /** - * Whether or not Stripe should automatically decline charges with an - * incorrect zip/postal code. This setting only applies if a card includes a + * Whether or not Stripe should automatically decline charges with an + * incorrect zip/postal code. This setting only applies if a card includes a * zip code and the bank specifically marks it as failed. */ avs_failure?: boolean; - + /** - * Whether or not Stripe should automatically decline charges with an - * incorrect CVC. This setting only applies if a card includes a CVC and the + * Whether or not Stripe should automatically decline charges with an + * incorrect CVC. This setting only applies if a card includes a CVC and the * bank specifically marks it as failed. */ cvc_failure?: boolean; }; - + /** - * Three-letter ISO currency code representing the default currency for the - * account. This must be a currency that Stripe supports in the account’s + * Three-letter ISO currency code representing the default currency for the + * account. This must be a currency that Stripe supports in the account’s * country. */ default_currency?: string; - + /** - * Email address of the account holder. For standalone accounts, this is used - * to email them asking them to claim their Stripe account. For managed - * accounts, this is only to make the account easier to identify to you: Stripe + * Email address of the account holder. For standalone accounts, this is used + * to email them asking them to claim their Stripe account. For managed + * accounts, this is only to make the account easier to identify to you: Stripe * will not email the account holder. */ email?: string; - + /** - * Information about the holder of this account, i.e. the user receiving funds + * Information about the holder of this account, i.e. the user receiving funds * from this account */ legal_entity?: {}; //TODO: Implement this type definition. - + /** - * A set of key/value pairs that you can attach to an account object. It can be - * useful for storing additional information about the account in a structured + * A set of key/value pairs that you can attach to an account object. It can be + * useful for storing additional information about the account in a structured * format. This can be unset by updating the value to null and then saving. */ metadata?: IMetadata; - + /** - * Internal-only description of the product being sold or service being - * provided by this account. It’s used by Stripe for risk and underwriting + * Internal-only description of the product being sold or service being + * provided by this account. It’s used by Stripe for risk and underwriting * purposes. */ product_description?: string; - + /** - * The text that will appear on credit card statements by default if a charge is + * The text that will appear on credit card statements by default if a charge is * being made directly on the account. */ statement_descriptor?: string; - + /** - * A publicly shareable email address that can be reached for support for this + * A publicly shareable email address that can be reached for support for this * account */ support_email?: string; - + /** - * A publicly shareable phone number that can be reached for support for + * A publicly shareable phone number that can be reached for support for * this account */ support_phone?: string; - + /** * A publicly shareable URL that can be reached for support for this account */ support_url?: string; - + /** - * Details on who accepted the Stripe terms of service, and when they - * accepted it. See our updating managed accounts guide for more + * Details on who accepted the Stripe terms of service, and when they + * accepted it. See our updating managed accounts guide for more * information */ tos_acceptance?: { /** - * The unix timestamp that Stripe’s terms of service were agreed to by the + * The unix timestamp that Stripe’s terms of service were agreed to by the * account holder */ date: number; - + /** * The IP address from which Stripe’s terms of service were agreed to by the account holder */ ip?: string; - + /** - * The user agent of the browser from which Stripe’s terms of service + * The user agent of the browser from which Stripe’s terms of service * were agreed to by the account holder */ user_agent?: string; }; - + /** - * Details on when this account will make funds from charges available, and - * when they will be paid out to the account holder’s bank account. See our + * Details on when this account will make funds from charges available, and + * when they will be paid out to the account holder’s bank account. See our * managed account bank transfer guide for more information */ transfer_schedule?: { /** - * The number of days charges for the account will be held before being - * paid out. May also be the string “minimum” for the lowest available - * value (based on country). Default is “minimum”. Does not apply when + * The number of days charges for the account will be held before being + * paid out. May also be the string “minimum” for the lowest available + * value (based on country). Default is “minimum”. Does not apply when * interval is “manual”. */ delay_days?: number | string; - + /** - * How frequently funds will be paid out. One of "manual" (for only + * How frequently funds will be paid out. One of "manual" (for only * triggered via API call), "daily", "weekly", or "monthly". Default is "daily". */ interval?: string; - + /** - * The day of the month funds will be paid out. Required and available + * The day of the month funds will be paid out. Required and available * only if interval is "monthly". */ monthly_anchor?: number; - + /** - * The day of the week funds will be paid out, of the style ‘monday’, + * The day of the week funds will be paid out, of the style ‘monday’, * ‘tuesday’, etc. Required and available only if interval is weekly. */ weekly_anchor?: string; } } - + interface IAccountUpdateOptions extends IDataOptions, IAccountShared { /** - * A card or bank account to attach to the account. You can provide either a - * token, like the ones returned by Stripe.js, or a dictionary as documented in - * the external_account parameter for either card or bank account creation. - * - * This will create a new external account object, make it the new default - * external account for its currency, and delete the old default if one exists. If - * you want to add additional external accounts instead of replacing the - * existing default for this currency, use the bank account or card creation + * A card or bank account to attach to the account. You can provide either a + * token, like the ones returned by Stripe.js, or a dictionary as documented in + * the external_account parameter for either card or bank account creation. + * + * This will create a new external account object, make it the new default + * external account for its currency, and delete the old default if one exists. If + * you want to add additional external accounts instead of replacing the + * existing default for this currency, use the bank account or card creation * API. */ external_account?: { @@ -361,241 +361,241 @@ declare namespace StripeNode { * The type of external account. Should be "bank_account". */ object: string; - + /** - * The account number for the bank account in string form. Must be a + * The account number for the bank account in string form. Must be a * checking account. */ account_number: string; - + /** * The country the bank account is in. */ country: string; - + /** - * The currency the bank account is in. This must be a country/currency + * The currency the bank account is in. This must be a country/currency * pairing that Stripe supports. */ currency: string; - + /** - * The name of the person or business that owns the bank account. This + * The name of the person or business that owns the bank account. This * field is required when attaching the bank account to a customer object. */ account_holder_name?: string; - + /** - * The type of entity that holds the account. This can be either - * "individual" or "company". This field is required when attaching the + * The type of entity that holds the account. This can be either + * "individual" or "company". This field is required when attaching the * bank account to a customer object. */ account_holder_type?: string; - + /** - * The routing number, sort code, or other country-appropriate institution - * number for the bank account. For US bank accounts, this is required - * and should be the ACH routing number, not the wire routing number. If - * you are providing an IBAN for account_number, this field is not + * The routing number, sort code, or other country-appropriate institution + * number for the bank account. For US bank accounts, this is required + * and should be the ACH routing number, not the wire routing number. If + * you are providing an IBAN for account_number, this field is not * required. */ routing_number?: string; } } - + interface IExternalAccountCreationOptions extends IDataOptionsWithMetadata { /** - * When adding a card to a customer, the parameter name is source. When - * adding to an account, the parameter name is external_account. The - * value can either be a token, like the ones returned by our Stripe.js, or a - * dictionary containing a user’s credit card details (with the options shown + * When adding a card to a customer, the parameter name is source. When + * adding to an account, the parameter name is external_account. The + * value can either be a token, like the ones returned by our Stripe.js, or a + * dictionary containing a user’s credit card details (with the options shown * below). Stripe will automatically validate the card. */ external_account: string ; - + /** - * Only applicable on accounts (not customers or recipients). If you set this to true (or if this is the first external account being added + * Only applicable on accounts (not customers or recipients). If you set this to true (or if this is the first external account being added * in this currency) this card will become the default external account for its currency. */ default_for_currency?: boolean; } - + interface IExternalAccountUpdateOptions extends IDataOptionsWithMetadata { /** * If set to true, this bank account will become the default external account for its currency. */ default_for_currency?: boolean; } - + interface IBankAccountListOptions extends IListOptions { object: "bank_account" } - + interface ICardListOptions extends IListOptions { object: "card" } - + interface IRejectReason { /** - * The reason for rejecting the account. May be one of "fraud", + * The reason for rejecting the account. May be one of "fraud", * "terms_of_service", or "other". */ reason: "fraud" | "terms_of_service" | "other" ; } } - - namespace applicationFees { + + namespace applicationFees { interface IApplicationFee extends IResourceObject { /** * Value is "application_fee" */ object: string; - + /** * ID of the Stripe account this fee was taken from. [Expandable] */ account: string | accounts.IAccount; - + /** * Amount earned, in cents/pence. */ amount: number; - + /** * Positive integer or zero */ amount_refunded: number; - + /** * ID of the Connect Application that earned the fee. [Expandable] */ application: string; //TODO: Implement IApplication interface and reference type here for expansion:- "string | IApplication" - + /** - * Balance transaction that describes the impact of this collected application + * Balance transaction that describes the impact of this collected application * fee on your account balance (not including refunds). [Expandable] */ balance_transaction: string | balance.IBalanceTransaction; - + /** * ID of the charge that the application fee was taken from. [Expandable] */ charge: string | charges.ICharge; - + created: number; - + /** * Three-letter ISO code representing the currency of the charge. */ currency: string; - + livemode: boolean; - + /** - * ID of the corresponding charge on the platform account, if this fee was the + * ID of the corresponding charge on the platform account, if this fee was the * result of a charge using the destination parameter. [Expandable] */ originating_transaction: string; - + /** - * Whether or not the fee has been fully refunded. If the fee is only partially + * Whether or not the fee has been fully refunded. If the fee is only partially * refunded, this attribute will still be false. */ refunded: boolean; - + /** * A list of refunds that have been applied to the fee. */ refunds: IApplicationFeeRefunds; } - + interface IApplicationFeeListOptions extends IListOptionsCreated { /** * Only return application fees for the charge specified by this charge ID. */ charge: string; } - + interface IApplicationFeeRefund extends IResourceObject { /** * Value is "fee_refund" */ object:string; - + /** * Amount, in cents/pence. */ amount: number; - + /** * Balance transaction that describes the impact on your account balance. */ balance_transaction: string | balance.IBalanceTransaction; - + created: number; - + /** * Three-letter ISO code representing the currency. */ currency: string; - + /** * ID of the application fee that was refunded. */ fee: string | IApplicationFee; - + /** - * A set of key/value pairs that you can attach to the object. It can be useful + * A set of key/value pairs that you can attach to the object. It can be useful * for storing additional information in a structured format. */ metadata: IMetadata; } - + interface IApplicationFeeRefunds extends IList, resources.ApplicationFeeRefunds { } - + interface IApplicationFeeRefundCreationOptions extends IDataOptions { /** - * A positive integer in pence representing how much of this fee to refund. + * A positive integer in pence representing how much of this fee to refund. * Can only refund up to the unrefunded amount remaining of the fee. - * + * * default is entire application fee */ amount?: number; - + /** - * A set of key/value pairs that you can attach to a refund object. It can be - * useful for storing additional information about the refund in a structured - * format. You can unset an individual key by setting its value to null and + * A set of key/value pairs that you can attach to a refund object. It can be + * useful for storing additional information about the refund in a structured + * format. You can unset an individual key by setting its value to null and * then saving. To clear all keys, set metadata to null, then save. */ metadata?: IMetadata; } } - + namespace balance { interface IBalance extends IObject { /** * Value is 'balance' */ object: string; - + /** - * Funds that are available to be paid out automatically by Stripe or explicitly - * via the transfers API. The available balance for each currency and payment + * Funds that are available to be paid out automatically by Stripe or explicitly + * via the transfers API. The available balance for each currency and payment * type can be found in the source_types property. */ available: Array; - + livemode: boolean; - + /** - * Funds that are not available in the balance yet, due to the 7-day rolling pay - * cycle. The pending balance for each currency and payment type can be + * Funds that are not available in the balance yet, due to the 7-day rolling pay + * cycle. The pending balance for each currency and payment type can be * found in the source_types property */ pending: Array; } - + interface ISourceType { currency: string; amount: number; @@ -606,7 +606,7 @@ declare namespace StripeNode { alipay_account?: number; } } - + interface IBalanceTransaction extends IResourceObject { /** * Value is 'balance_transaction' @@ -622,16 +622,16 @@ declare namespace StripeNode { * The date the transaction's net funds will become available in the Stripe balance. */ available_on: number; - + created: number; /** * Three-letter ISO currency code representing the currency. */ currency: string; - + description?: string; - + /** * Fee (in cents/pence) paid for this transaction */ @@ -643,14 +643,14 @@ declare namespace StripeNode { fee_details: Array<{ amount: number; application: string; - + /** * Three-letter ISO currency code representing the currency of the amount that was disputed. */ currency: string; - + description: string; - + /** * Type of the fee, one of: "application_fee", "stripe_fee"" or "tax". */ @@ -661,50 +661,50 @@ declare namespace StripeNode { * Net amount of the transaction, in cents. */ net: number; - + /** * The Stripe object this transaction is related to. [Expandable] */ source: string | IResourceObject; - + /** * The transfers (if any) for which source is a source_transaction. */ source_transfers: IList; - + /** * If the transaction's net funds are available in the Stripe balance yet. Either "available" or "pending". */ status: string; /** - * Transaction type: "adjustment", "application_fee", - * "application_fee_refund", "charge", "payment", "payment_refund", - * "refund", "transfer", "transfer_cancel", "transfer_failure", or + * Transaction type: "adjustment", "application_fee", + * "application_fee_refund", "charge", "payment", "payment_refund", + * "refund", "transfer", "transfer_cancel", "transfer_failure", or * "transfer_refund". */ type: string; } - + interface IBalanceListOptions extends IListOptions { available_on?: string | IDateFilter; currency?: string; - + /** - * Only returns transactions that are related to the specified Stripe object ID + * Only returns transactions that are related to the specified Stripe object ID * (e.g. filtering by a charge ID will return all related charge transactions). */ source?: string; - + /** - * For automatic Stripe transfers only, only returns transactions that were + * For automatic Stripe transfers only, only returns transactions that were * transferred out on the specified transfer ID. */ transfer?: string; - + /** - * Only returns transactions of the given type. One of: "charge", "refund", - * "adjustment", "application_fee", "application_fee_refund", "transfer", + * Only returns transactions of the given type. One of: "charge", "refund", + * "adjustment", "application_fee", "application_fee_refund", "transfer", * or "transfer_failure" */ type?: string; @@ -727,25 +727,25 @@ declare namespace StripeNode { * Amount charged in cents/pence, positive integer or zero. */ amount: number; - + /** - * Amount in cents/pence refunded (can be less than the amount attribute on the + * Amount in cents/pence refunded (can be less than the amount attribute on the * charge if a partial refund was issued), positive integer or zero. */ amount_refunded: number; - + /** - * The application fee (if any) for the charge. See the Connect documentation + * The application fee (if any) for the charge. See the Connect documentation * for details. [Expandable] */ application_fee?: string; - + /** - * ID of the balance transaction that describes the impact of this charge on + * ID of the balance transaction that describes the impact of this charge on * your account balance (not including refunds or disputes). [Expandable] */ balance_transaction: string | balance.IBalanceTransaction; - + /** * If the charge was created without capturing, this boolean represents whether or not it is * still uncaptured or has since been captured. @@ -755,34 +755,34 @@ declare namespace StripeNode { created: number; /** - * Three-letter ISO currency code representing the currency in which the + * Three-letter ISO currency code representing the currency in which the * charge was made. */ currency: string; - + /** * ID of the customer this charge is for if one exists. [Expandable] */ customer: string | customers.ICustomer; - + description?: string; - + /** * Details about the dispute if the charge has been disputed. */ dispute?: disputes.IDispute; - + /** * Error code explaining reason for charge failure if available (see the errors section for a list of * codes: https://stripe.com/docs/api#errors). */ failure_code: string; - + /** * Message to user further explaining reason for charge failure if available. */ failure_message: string; - + /** * Hash with information on fraud assessments for the charge. */ @@ -797,36 +797,36 @@ declare namespace StripeNode { */ stripe_report?: "fraudulent"; }; - + /** * ID of the invoice this charge is for if one exists. [Expandable] */ invoice: string | invoices.IInvoice; - + livemode: boolean; - + metadata: IMetadata; - + /** * ID of the order this charge is for if one exists. [Expandable] */ order: string | orders.IOrder; - + /** * true if the charge succeeded, or was successfully authorized for later capture. */ paid: boolean; - + /** * This is the email address that the receipt for this charge was sent to. */ receipt_email: string; - + /** * This is the transaction number that appears on email receipts sent for this charge. */ receipt_number: string; - + /** * Whether or not the charge has been fully refunded. If the charge is only partially refunded, * this attribute will still be false. @@ -837,150 +837,150 @@ declare namespace StripeNode { * A list of refunds that have been applied to the charge. */ refunds: IChargeRefunds; - + /** * Shipping information for the charge. */ shipping?: IShippingInformation; - + /** * For most Stripe users, the source of every charge is a credit or debit card. * This hash is then the card object describing that card. */ source: cards.ICard | bitcoinReceivers.IBitcoinReceiver; - + /** - * The transfer ID which created this charge. Only present if the charge came + * The transfer ID which created this charge. Only present if the charge came * from another Stripe account. See the Connect documentation for details. * [Expandable] */ source_transfer: string | transfers.ITransfer; - + /** - * Extra information about a charge. This will appear on your customer’s + * Extra information about a charge. This will appear on your customer’s * credit card statement. */ statement_descriptor: string; - + /** * The status of the payment is either "succeeded", "pending", or "failed". */ status: "succeeded" | "pending" | "failed"; - + /** - * ID of the transfer to the destination account (only applicable if the + * ID of the transfer to the destination account (only applicable if the * charge was created using the destination parameter). [Expandable] */ transfer: string | transfers.ITransfer; } - + interface IChargeCreationOptions extends IDataOptions { /** - * A positive integer in the smallest currency unit (e.g 100 cents to charge - * $1.00, or 1 to charge ¥1, a 0-decimal currency) representing how much to - * charge the card. The minimum amount is £0.50 (or equivalent in charge + * A positive integer in the smallest currency unit (e.g 100 cents to charge + * $1.00, or 1 to charge ¥1, a 0-decimal currency) representing how much to + * charge the card. The minimum amount is £0.50 (or equivalent in charge * currency). */ amount: number; - + /** * 3-letter ISO code for currency. */ currency: string; - + /** - * A fee in pence that will be applied to the charge and transferred to the - * application owner's Stripe account. To use an application fee, the request - * must be made on behalf of another account, using the Stripe-Account - * header, an OAuth key, or the destination parameter. For more + * A fee in pence that will be applied to the charge and transferred to the + * application owner's Stripe account. To use an application fee, the request + * must be made on behalf of another account, using the Stripe-Account + * header, an OAuth key, or the destination parameter. For more * information, see the application fees documentation. - * + * * Connect only. */ application_fee?: number; - + /** - * Whether or not to immediately capture the charge. When false, the charge - * issues an authorization (or pre-authorization), and will need to be - * captured later. Uncaptured charges expire in 7 days. For more information, + * Whether or not to immediately capture the charge. When false, the charge + * issues an authorization (or pre-authorization), and will need to be + * captured later. Uncaptured charges expire in 7 days. For more information, * see authorizing charges and settling later. */ capture?: boolean; - + /** - * An arbitrary string which you can attach to a charge object. It is displayed - * when in the web interface alongside the charge. Note that if you use Stripe - * to send automatic email receipts to your customers, your receipt emails + * An arbitrary string which you can attach to a charge object. It is displayed + * when in the web interface alongside the charge. Note that if you use Stripe + * to send automatic email receipts to your customers, your receipt emails * will include the description of the charge(s) that they are describing. */ description?: string; - + /** - * An account to make the charge on behalf of. If specified, the charge will be - * attributed to the destination account for tax reporting, and the funds from - * the charge will be transferred to the destination account. The ID of the - * resulting transfer will be returned in the transfer field of the response. See + * An account to make the charge on behalf of. If specified, the charge will be + * attributed to the destination account for tax reporting, and the funds from + * the charge will be transferred to the destination account. The ID of the + * resulting transfer will be returned in the transfer field of the response. See * the documentation for details. - * + * * Connect only. */ destination?: string; - + /** - * A set of key/value pairs that you can attach to a charge object. It can be - * useful for storing additional information about the customer in a - * structured format. It's often a good idea to store an email address in + * A set of key/value pairs that you can attach to a charge object. It can be + * useful for storing additional information about the customer in a + * structured format. It's often a good idea to store an email address in * metadata for tracking later. */ metadata?: IMetadata; - + /** - * The email address to send this charge's receipt to. The receipt will not be - * sent until the charge is paid. If this charge is for a customer, the email - * address specified here will override the customer's email address. - * Receipts will not be sent for test mode charges. If receipt_email is - * specified for a charge in live mode, a receipt will be sent regardless of your + * The email address to send this charge's receipt to. The receipt will not be + * sent until the charge is paid. If this charge is for a customer, the email + * address specified here will override the customer's email address. + * Receipts will not be sent for test mode charges. If receipt_email is + * specified for a charge in live mode, a receipt will be sent regardless of your * email settings. */ receipt_email?: string; - + /** - * Shipping information for the charge. Helps prevent fraud on charges for - * physical goods. For more information, see the Charge object + * Shipping information for the charge. Helps prevent fraud on charges for + * physical goods. For more information, see the Charge object * documentation. */ shipping?: IShippingInformation; - + /** * The ID of an existing customer that will be charged in this request. */ customer?: string; - + /** - * A payment source to be charged, such as a credit card. If you also pass a - * customer ID, the source must be the ID of a source belonging to the - * customer. Otherwise, if you do not pass a customer ID, the source you - * provide must either be a token, like the ones returned by Stripe.js, or a - * object containing a user's credit card details, with the options described - * below. Although not all information is required, the extra info helps + * A payment source to be charged, such as a credit card. If you also pass a + * customer ID, the source must be the ID of a source belonging to the + * customer. Otherwise, if you do not pass a customer ID, the source you + * provide must either be a token, like the ones returned by Stripe.js, or a + * object containing a user's credit card details, with the options described + * below. Although not all information is required, the extra info helps * prevent fraud. */ source?: sources.ISourceCreationOptions; - + /** - * An arbitrary string to be displayed on your customer's credit card - * statement. This may be up to 22 characters. As an example, if your - * website is RunClub and the item you're charging for is a race ticket, you - * may want to specify a statement_descriptor of - * RunClub 5K race ticket. The statement description may not include - * <>"' characters, and will appear on your customer's statement in capital - * letters. Non-ASCII characters are automatically stripped. While most - * banks display this information consistently, some may display it + * An arbitrary string to be displayed on your customer's credit card + * statement. This may be up to 22 characters. As an example, if your + * website is RunClub and the item you're charging for is a race ticket, you + * may want to specify a statement_descriptor of + * RunClub 5K race ticket. The statement description may not include + * <>"' characters, and will appear on your customer's statement in capital + * letters. Non-ASCII characters are automatically stripped. While most + * banks display this information consistently, some may display it * incorrectly or not at all. */ statement_descriptor?: string; } - + interface IChargeUpdateOptions extends IDataOptionsWithMetadata { /** * An arbitrary string which you can attach to a charge object. It is displayed when in the web interface alongside the charge. @@ -988,7 +988,7 @@ declare namespace StripeNode { * of the charge(s) that they are describing. This can be unset by updating the value to null and then saving. */ description?: string; - + /** * A set of key/value pairs you can attach to a charge giving information about its riskiness. */ @@ -1006,27 +1006,27 @@ declare namespace StripeNode { * If this field is updated, then a new email receipt will be sent to the updated address. */ receipt_email?: string; - + /** - * Shipping information for the charge. Helps prevent fraud on charges for + * Shipping information for the charge. Helps prevent fraud on charges for * physical goods. */ shipping?: IShippingInformation; } - + interface IChargeListOptions extends IListOptionsCreated { /** * Only return charges for the customer specified by this customer ID. */ customer?: string; - + /** - * A filter on the list based on the source of the charge. The value can be a + * A filter on the list based on the source of the charge. The value can be a * dictionary with the following options: */ source?: { /** - * Return charges that match this source type string. Available options are + * Return charges that match this source type string. Available options are * "all", "alipay_account", "bitcoin_receiver", or "card". */ object: "all" | "alipay_account" | "bitcoin_receiver" | "card"; @@ -1035,7 +1035,7 @@ declare namespace StripeNode { interface IChargeRefunds extends IList, resources.ChargeRefunds { } } - + namespace coupons { /** * A discount represents the actual application of a coupon to a particular customer. It contains information @@ -1046,20 +1046,20 @@ declare namespace StripeNode { * Value is 'discount' */ object: "discount"; - + /** * Hash describing the coupon applied to create this discount */ coupon: ICoupon; - + customer: string; - + /** * If the coupon has a duration of once or repeating, the date that this discount will end. If the coupon * used has a forever duration, this attribute will be null. */ end: number; - + /** * Date that the coupon was applied */ @@ -1080,36 +1080,36 @@ declare namespace StripeNode { * Value is 'coupon' */ object: "coupon"; - + /** * Amount (in the currency specified) that will be taken off the subtotal of any invoices for this customer. */ amount_off: number; - + created: number; - + /** * If amount_off has been set, the currency of the amount to take off. */ currency: string; - + /** * One of "forever", "once", and "repeating". Describes how long a customer who applies this coupon will get the discount. */ duration: "forever" | "once" | "repeating" ; - + /** * If duration is repeating, the number of months the coupon applies. Null if coupon duration is forever or once. */ duration_in_months: number; - + livemode: boolean; - + /** * Maximum number of times this coupon can be redeemed, in total, before it is no longer valid. */ max_redemptions: number; - + metadata: IMetadata; /** @@ -1133,39 +1133,39 @@ declare namespace StripeNode { */ valid: boolean; } - + interface ICouponCreationOptions extends IDataOptionsWithMetadata { /** - * Unique string of your choice that will be used to identify this coupon when applying it to a customer. This is often a specific - * code you’ll give to your customer to use when signing up (e.g. FALL25OFF). If you don’t want to specify a particular code, you + * Unique string of your choice that will be used to identify this coupon when applying it to a customer. This is often a specific + * code you’ll give to your customer to use when signing up (e.g. FALL25OFF). If you don’t want to specify a particular code, you * can leave the ID blank and we’ll generate a random code for you. */ id?: string; - + /** * Specifies how long the discount will be in effect. Can be forever, once, or repeating. */ duration: "forever" | "once" | "repeating" ; - + /** * A positive integer representing the amount to subtract from an invoice total (required if percent_off is not passed) */ amount_off?: number; - + /** * Currency of the amount_off parameter (required if amount_off is passed) */ currency?: string; - + /** - * Required only if duration is repeating, in which case it must be a positive integer that specifies the number of months + * Required only if duration is repeating, in which case it must be a positive integer that specifies the number of months * the discount will be in effect. */ duration_in_months?: number; - + /** - * A positive integer specifying the number of times the coupon can be redeemed before it’s no longer valid. - * + * A positive integer specifying the number of times the coupon can be redeemed before it’s no longer valid. + * * For example, you might have a 50% off coupon that the first 20 readers of your blog can use. */ max_redemptions?: number; @@ -1176,13 +1176,13 @@ declare namespace StripeNode { percent_off?: number; /** - * Unix timestamp specifying the last time at which the coupon can be redeemed. + * Unix timestamp specifying the last time at which the coupon can be redeemed. * After the redeem_by date, the coupon can no longer be applied to new customers. */ redeem_by?: number; } } - + namespace customers { /** * Customer objects allow you to perform recurring charges and track multiple charges that are associated @@ -1194,7 +1194,7 @@ declare namespace StripeNode { * Value is 'customer' */ object: "customer"; - + /** * Current balance, if any, being stored on the customer's account. If negative, the customer has credit to apply to * the next invoice. If positive, the customer has an amount owed that will be added to the next invoice. The balance @@ -1202,9 +1202,9 @@ declare namespace StripeNode { * to any invoice. This balance is only taken into account for recurring charges. */ account_balance?: number; - + created: number; - + /** * The currency the customer can be charged in for recurring billing purposes (subscriptions, invoices, invoice items). */ @@ -1219,40 +1219,40 @@ declare namespace StripeNode { * Whether or not the latest charge for the customer's latest invoice has failed */ delinquent: boolean; - + description?: string; - + /** * Describes the current discount active on the customer, if there is one. */ discount?: coupons.IDiscount; - + email?: string; - + livemode: boolean; - + metadata?: IMetadata; - + /** * Shipping information associated with the customer. */ shipping: IShippingInformation; - + /** * The customer’s payment sources, if any */ sources?: IList; - + cards?: resources.CustomerCards; - + /** * The customer's current subscriptions, if any */ subscriptions: ICustomerSubscriptions; } - + interface ICustomerSubscriptions extends IList, resources.CustomerSubscriptions {} - + interface ICustomerCreationOptions extends IDataOptionsWithMetadata { /** * An integer amount in cents that is the starting account balance for your customer. A negative amount represents a credit that @@ -1277,7 +1277,7 @@ declare namespace StripeNode { * This can be unset by updating the value to null and then saving. */ email?: string; - + /** * The identifier of the plan to subscribe the customer to. If provided, the returned customer object will have a list of subscriptions * that the customer is currently subscribed to. If you subscribe a customer to a plan without a free trial, the customer must have a @@ -1291,24 +1291,24 @@ declare namespace StripeNode { * (5 x 10 cents) monthly. Defaults to 1 if not set. Only applies when the plan parameter is also provided. */ quantity?: number; - + shipping?: IShippingInformation; - + /** - * The source can either be a token, like the ones returned by our Stripe.js, or + * The source can either be a token, like the ones returned by our Stripe.js, or * a dictionary containing a user’s credit card details. */ source?: sources.ISourceCreationOptionsExtended; - + /** - * A positive decimal (with at most two decimal places) between 1 and 100. - * This represents the percentage of the subscription invoice subtotal that - * will be calculated and added as tax to the final amount each billing period. - * For example, a plan which charges $10/month with a tax_percent of 20.0 + * A positive decimal (with at most two decimal places) between 1 and 100. + * This represents the percentage of the subscription invoice subtotal that + * will be calculated and added as tax to the final amount each billing period. + * For example, a plan which charges $10/month with a tax_percent of 20.0 * will charge $12 per invoice. Can only be used if a plan is provided. */ tax_percent?: number; - + /** * Unix timestamp representing the end of the trial period the customer will get before being charged. If set, trial_end will * override the default trial period of the plan the customer is being subscribed to. The special value now can be provided to @@ -1316,7 +1316,7 @@ declare namespace StripeNode { */ trial_end?: number; } - + interface ICustomerUpdateOptions extends IDataOptionsWithMetadata { /** * An integer amount in cents that is the starting account balance for your customer. A negative amount represents a credit that @@ -1329,12 +1329,12 @@ declare namespace StripeNode { * API will not have the discount. */ coupon?: string; - + /** * ID of source to make the customer’s new default for invoice payments */ default_source?: string; - + /** * An arbitrary string that you can attach to a customer object. It is displayed alongside the customer in the dashboard. This can * be unset by updating the value to null and then saving. @@ -1346,45 +1346,45 @@ declare namespace StripeNode { * This can be unset by updating the value to null and then saving. */ email?: string; - + shipping?: IShippingInformation; - + /** - * The source can either be a token, like the ones returned by our Stripe.js, or - * a dictionary containing a user’s credit card details (with the options shown - * below). Passing source will create a new source object, make it the new - * customer default source, and delete the old customer default if one exists. - * If you want to add additional sources instead of replacing the existing - * default, use the card creation API. Whenever you attach a card to a + * The source can either be a token, like the ones returned by our Stripe.js, or + * a dictionary containing a user’s credit card details (with the options shown + * below). Passing source will create a new source object, make it the new + * customer default source, and delete the old customer default if one exists. + * If you want to add additional sources instead of replacing the existing + * default, use the card creation API. Whenever you attach a card to a * customer, Stripe will automatically validate the card. */ source?: sources.ISourceCreationOptionsExtended; } - + interface ICustomerSourceCreationOptions extends IDataOptionsWithMetadata { /** - * When adding a card to a customer, the parameter name is source. When - * adding to an account, the parameter name is external_account. The - * value can either be a token, like the ones returned by our Stripe.js, or a - * dictionary containing a user’s credit card details (with the options shown + * When adding a card to a customer, the parameter name is source. When + * adding to an account, the parameter name is external_account. The + * value can either be a token, like the ones returned by our Stripe.js, or a + * dictionary containing a user’s credit card details (with the options shown * below). Stripe will automatically validate the card. */ source: sources.ISourceCreationOptions; } - + interface ICustomerCardSourceCreationOptions extends ICustomerSourceCreationOptions { source: cards.ISourceCreationOptions; } - + interface IBankAccountSourceListOptions extends IListOptions { object: "bank_account" } - + interface ICardSourceListOptions extends IListOptions { object: "card" } } - + namespace disputes { /** * A dispute occurs when a customer questions your charge with their bank or credit card company. @@ -1397,24 +1397,24 @@ declare namespace StripeNode { * Value is 'dispute' */ object: "dispute"; - + /** * Disputed amount. Usually the amount of the charge, but can differ (usually because of currency * fluctuation or because only part of the order is disputed). */ amount: number; - + /** * List of zero, one, or two balance transactions that show funds withdrawn and reinstated to your * Stripe account as a result of this dispute. */ balance_transactions: Array; - + /** * ID of the charge that was disputed. [Expandable] */ charge: string | charges.ICharge; - + /** * Date dispute was opened */ @@ -1424,12 +1424,12 @@ declare namespace StripeNode { * Three-letter ISO currency code representing the currency of the amount that was disputed. */ currency: string; - + /** * Evidence provided to respond to a dispute. Updating any field in the hash will submit all fields in the hash for review. */ evidence: IDisputeEvidence; - + /** * Information about the evidence submission. */ @@ -1439,7 +1439,7 @@ declare namespace StripeNode { * if the customer's bank or credit card company doesn't allow a response for this particular dispute. */ due_by: number; - + /** * Whether or not evidence has been saved for this dispute. */ @@ -1450,26 +1450,26 @@ declare namespace StripeNode { * if no evidence submissions have occurred. If true, then delivery of the latest evidence is not guaranteed. */ past_due: boolean; - + /** * The number of times the evidence has been submitted. You may submit evidence a maximum of 5 times */ submission_count: number; }; - + /** * If true, it is still possible to refund the disputed payment. Once the payment has been fully * refunded, no further funds will be withdrawn from your Stripe account as a result of this dispute. */ is_charge_refundable: boolean; - + livemode: boolean; metadata: IMetadata; - + /** - * Reason given by cardholder for dispute. - * Possible values are duplicate, fraudulent, subscription_canceled, product_unacceptable, - * product_not_received, unrecognized, credit_not_processed, incorrect_account_details, + * Reason given by cardholder for dispute. + * Possible values are duplicate, fraudulent, subscription_canceled, product_unacceptable, + * product_not_received, unrecognized, credit_not_processed, incorrect_account_details, * insufficient_funds, bank_cannot_process, debit_not_authorized, general. * Read more about dispute reasons: https://stripe.com/help/disputes#reasons */ @@ -1481,7 +1481,7 @@ declare namespace StripeNode { */ status: "warning_needs_response" | "warning_under_review" | "warning_closed" | "needs_response" | "response_disabled" | "under_review" | "charge_refunded" | "won" | "lost"; } - + interface IDisputeEvidence { /** * Any server or activity logs showing proof that the customer accessed or downloaded the purchased @@ -1629,7 +1629,7 @@ declare namespace StripeNode { */ uncategorized_text?: string; } - + interface IDisputeUpdateOptions extends IDataOptionsWithMetadata { /** * Evidence to upload to respond to a dispute. Updating any field in the hash will submit all fields in the hash for review. @@ -1637,108 +1637,108 @@ declare namespace StripeNode { evidence?: disputes.IDisputeEvidence; } } - + namespace events { interface IEvent extends IResourceObject { /** * Value is "event" */ object: "event"; - + /** - * The Stripe API version used to render data. + * The Stripe API version used to render data. * Note: this property is populated for events on or after October 31, 2014. */ api_version: string; - + created: number; - + /** * Hash containing data associated with the event. */ data: { /** - * describes the object the event is about. For example, an - * invoice.created event will have a full invoice object as the value of + * describes the object the event is about. For example, an + * invoice.created event will have a full invoice object as the value of * the object key. */ object: IObject; - + /** - * + * */ previous_attributes?: {}; }; - + livemode: boolean; - + /** * Number of webhooks yet to be delivered successfully (return a 20x response) to the URLs you’ve specified. - * + * * positive integer or zero */ pending_webhooks: number; - + /** - * ID of the API request that caused the event. If null, the event was - * automatic (e.g. Stripe’s automatic subscription handling). Request logs are - * available in the dashboard but currently not in the API. Note: this property + * ID of the API request that caused the event. If null, the event was + * automatic (e.g. Stripe’s automatic subscription handling). Request logs are + * available in the dashboard but currently not in the API. Note: this property * is populated for events on or after April 23, 2013. */ request?: string; - + /** * Description of the event: e.g. invoice.created, charge.refunded, etc. */ type: string; } - + interface IEventListOptions extends IListOptionsCreated { /** - * A string containing a specific event name, or group of events using * as a - * wildcard. The list will be filtered to include only events with a matching + * A string containing a specific event name, or group of events using * as a + * wildcard. The list will be filtered to include only events with a matching * event property */ type: string; } } - + namespace fileUploads { interface IFileUpdate extends IResourceObject { /** * Value is "file_upload" */ object: "file_upload"; - + created: number; - + /** - * The purpose of the uploaded file. Possible values are "business_logo", - * "dispute_evidence", "identity_document", "incorporation_article", + * The purpose of the uploaded file. Possible values are "business_logo", + * "dispute_evidence", "identity_document", "incorporation_article", * "incorporation_document". */ purpose: IPurpose; - + /** * The size in bytes of the file upload object. */ size: number; - + /** - * The type of the file returned. Returns one of the following: + * The type of the file returned. Returns one of the following: * pdf, jpg, png. */ type: "pdf" | "jpg" | "png"; - + /** - * A read-only URL where the uploaded file can be accessed. Will be nil + * A read-only URL where the uploaded file can be accessed. Will be nil * unless the uploaded file has one of the following purposes: - * business_logo, dispute_evidence, incorporation_document. + * business_logo, dispute_evidence, incorporation_document. * Also nil if retrieved with the publishable API key. */ url: string; } - + interface IFileUploadCreationOptions extends IDataOptions { purpose: IPurpose; file: { @@ -1747,18 +1747,18 @@ declare namespace StripeNode { type: string | "application/octet-stream"; } } - + interface IFileUploadListOptions extends IListOptionsCreated { /** - * The file purpose to filter queries by. If none is provided, files will not be + * The file purpose to filter queries by. If none is provided, files will not be * filtered by purpose. */ purpose: IPurpose; } - + type IPurpose = "business_logo" | "dispute_evidence" | "identity_document" | "incorporation_article" | "incorporation_document"; } - + namespace invoices { /** * Invoices are statements of what a customer owes for a particular billing period, including subscriptions, @@ -1778,7 +1778,7 @@ declare namespace StripeNode { * Value is 'invoice' */ object: "invoice"; - + /** * Final amount due at this time for this invoice. If the invoice's total is smaller than the minimum charge * amount, for example, or if there is account credit that can be applied to the invoice, the amount_due may @@ -1787,13 +1787,13 @@ declare namespace StripeNode { * specified in amount_due. */ amount_due: number; - + /** * The fee in cents that will be applied to the invoice and transferred to the application owner's * Stripe account when the invoice is paid. */ application_fee: number; - + /** * Number of payment attempts made for this invoice, from the perspective of the payment retry schedule. Any * payment attempt counts as the first attempt, and subsequently only automatic retries increment the attempt @@ -1807,30 +1807,30 @@ declare namespace StripeNode { * users. */ attempted: boolean; - + /** * ID of the latest charge generated for this invoice, if any. [Expandable] */ charge: string | charges.ICharge; - + /** * Whether or not the invoice is still trying to collect payment. An invoice is closed if it's either paid or * it has been marked closed. A closed invoice will no longer attempt to collect payment. */ closed: boolean; - + currency: string; customer: string; date: number; description: string; discount: coupons.IDiscount; - + /** * Ending customer balance after attempting to pay invoice. If the invoice has not been attempted yet, * this will be null. */ ending_balance: number; - + /** * Whether or not the invoice has been forgiven. Forgiving an invoice instructs us to update the subscription * status as if the invoice were succcessfully paid. Once an invoice has been forgiven, it cannot be unforgiven @@ -1839,20 +1839,20 @@ declare namespace StripeNode { forgiven: boolean; /** - * The individual line items that make up the invoice. - * + * The individual line items that make up the invoice. + * * lines is sorted as follows: invoice items in reverse chronological order, followed by the subscription, if any. */ lines: IList; - + livemode: boolean; metadata: IMetadata; - + /** * The time at which payment will next be attempted. */ next_payment_attempt: number; - + /** * Whether or not payment was successfully collected for this invoice. An invoice can be paid (most commonly) * with a charge or with credit from the customer's account balance. @@ -1868,56 +1868,56 @@ declare namespace StripeNode { * Start of the usage period during which invoice items were added to this invoice */ period_start: number; - + /** * This is the transaction number that appears on email receipts sent for this invoice. */ receipt_number: string; - + /** * Starting customer balance before attempting to pay invoice. If the invoice has not been attempted yet, * this will be the current customer balance. */ starting_balance: number; - + /** * Extra information about an invoice for the customer�s credit card statement. */ statement_descriptor: string; - + /** * The subscription that this invoice was prepared for, if any. */ subscription: string; - + /** * Only set for upcoming invoices that preview prorations. The time used to calculate prorations. */ subscription_proration_date: number; - + /** * Total of all subscriptions, invoice items, and prorations on the invoice before any discount is applied */ subtotal: number; - + /** * The amount of tax included in the total, calculated from tax_percent and the subtotal. If no tax_percent * is defined, this value will be null. */ tax: number; - + /** * This percentage of the subtotal has been added to the total amount of the invoice, including invoice line * items and discounts. This field is inherited from the subscription's tax_percent field, but can be changed * before the invoice is paid. This field defaults to null. */ tax_percent: number; - + /** * Total after discount */ total: number; - + /** * The time at which webhooks for this invoice were successfully delivered (if the invoice had no webhooks to * deliver, this will match date). Invoice payment is delayed until webhooks are delivered, or until all webhook @@ -1925,160 +1925,160 @@ declare namespace StripeNode { */ webhooks_delivered_at: number; } - + interface IInvoiceLineItem extends IResourceObject { /** * The ID of the source of this line item, either an invoice item or a subscription */ id: string; - + /** * Value is "line_item" */ object: "line_item"; - + /** * The amount, in cents/pence */ amount: number; - + currency: string; - + /** * A text description of the line item, if the line item is an invoice item */ description: string; - + /** * If true, discounts will apply to this line item. Always false for prorations. */ discountable: boolean; - + /** * Whether or not this is a test line item */ livemode: boolean; - + metadata: IMetadata; - + /** - * The period this line_item covers. For subscription line items, this is the subscription period. For prorations, this starts when - * the proration was calculated, and ends at the period end of the subscription. For invoice items, this is the time at which the + * The period this line_item covers. For subscription line items, this is the subscription period. For prorations, this starts when + * the proration was calculated, and ends at the period end of the subscription. For invoice items, this is the time at which the * invoice item was created, so the period start and end are the same time. */ period: IPeriod; - + /** * The plan of the subscription, if the line item is a subscription or a proration */ plan: plans.IPlan; - + /** * Whether or not this is a proration */ proration: boolean; - + /** * The quantity of the subscription, if the line item is a subscription or a proration */ quantity: number; - + /** * When type is invoiceitem, the subscription that the invoice item pertains to, if any. Left blank when * type is already subscription, as it'd be redundant with id. */ subscription: string; - + /** * A string identifying the type of the source of this line item, either an invoiceitem or a subscription */ type: "invoiceitem" | "subscription"; } - + interface IInvoiceCreationOptions extends IDataOptionsWithMetadata { customer: string; - + /** - * A fee in pence that will be applied to the invoice and transferred to the application owner’s Stripe account. - * The request must be made with an OAuth key or the Stripe-Account header in order to take an application fee. + * A fee in pence that will be applied to the invoice and transferred to the application owner’s Stripe account. + * The request must be made with an OAuth key or the Stripe-Account header in order to take an application fee. * For more information, see the application fees documentation. */ application_fee?: number; - + description?: string; - + /** * Extra information about a charge for the customer’s credit card statement. */ statement_descriptor?: string - + /** - * The ID of the subscription to invoice. If not set, the created invoice will include all pending invoice items for + * The ID of the subscription to invoice. If not set, the created invoice will include all pending invoice items for * the customer. If set, the created invoice will exclude pending invoice items that pertain to other subscriptions. */ subscription?: string; - + /** * The percent tax rate applied to the invoice, represented as a decimal number. */ tax_percent?: number; } - + interface IInvoiceUpdateOptions extends IDataOptionsWithMetadata { /** - * A fee in pence that will be applied to the invoice and transferred to the application owner’s Stripe account. - * The request must be made with an OAuth key or the Stripe-Account header in order to take an application fee. + * A fee in pence that will be applied to the invoice and transferred to the application owner’s Stripe account. + * The request must be made with an OAuth key or the Stripe-Account header in order to take an application fee. * For more information, see the application fees documentation. */ application_fee?: number; - + /** * Boolean representing whether an invoice is closed or not. To close an invoice, pass true. */ closed?: boolean; - + description?: string; - + /** - * Boolean representing whether an invoice is forgiven or not. To forgive an invoice, pass true. Forgiving an invoice - * instructs us to update the subscription status as if the invoice were successfully paid. Once an invoice has been + * Boolean representing whether an invoice is forgiven or not. To forgive an invoice, pass true. Forgiving an invoice + * instructs us to update the subscription status as if the invoice were successfully paid. Once an invoice has been * forgiven, it cannot be unforgiven or reopened. */ forgiven?: boolean; - + /** * Extra information about a charge for the customer’s credit card statement. */ statement_descriptor?: string - + /** * The percent tax rate applied to the invoice, represented as a decimal number. */ tax_percent?: number; } - + interface IInvoiceListOptions extends IListOptions { /** * The identifier of the customer whose invoices to return. If none is provided, all invoices will be returned. */ customer?: string; - + date?: IDateFilter; } - + interface IInvoiceLineItemRetrievalOptions extends IListOptions { coupon?: string; - + /** * In the case of upcoming invoices, the customer of the upcoming invoice is required. In other cases it is ignored. */ customer?: string; - + /** * In the case of upcoming invoices, the subscription of the upcoming invoice is optional. In other cases it is ignored. */ subscription?: string; - + subscription_plan?: string; subscription_prorate?: boolean; subscription_proration_date?: number; @@ -2088,53 +2088,53 @@ declare namespace StripeNode { interface IInvoiceUpcomingOptions extends IDataOptions { /** - * The code of the coupon to apply. If a subscription or subscription_plan is provided, the invoice returned will preview updating - * or creating a subscription with that coupon. Otherwise, it will preview applying that coupon to the customer for the next upcoming + * The code of the coupon to apply. If a subscription or subscription_plan is provided, the invoice returned will preview updating + * or creating a subscription with that coupon. Otherwise, it will preview applying that coupon to the customer for the next upcoming * invoice from among the customer’s subscriptions. */ coupon?: string; - + /** - * The identifier of the subscription for which you’d like to retrieve the upcoming invoice. If not provided, but a subscription_plan - * is provided, you will preview creating a subscription to that plan. If neither subscription nor subscription_plan is provided, you + * The identifier of the subscription for which you’d like to retrieve the upcoming invoice. If not provided, but a subscription_plan + * is provided, you will preview creating a subscription to that plan. If neither subscription nor subscription_plan is provided, you * will retrieve the next upcoming invoice from among the customer’s subscriptions. */ subscription?: string; - + /** - * If set, the invoice returned will preview updating the subscription given to this plan, or creating a new subscription to this plan + * If set, the invoice returned will preview updating the subscription given to this plan, or creating a new subscription to this plan * if no subscription is given. */ subscription_plan?: string; - + /** - * If previewing an update to a subscription, this decides whether the preview will show the result of applying prorations or not. If - * set, one of subscription_plan or subscription, and one of subscription_plan, subscription_quantity or subscription_trial_end are + * If previewing an update to a subscription, this decides whether the preview will show the result of applying prorations or not. If + * set, one of subscription_plan or subscription, and one of subscription_plan, subscription_quantity or subscription_trial_end are * required. */ subscription_prorate?: boolean; - + /** - * If previewing an update to a subscription, and doing proration, subscription_proration_date forces the proration to be calculated as - * though the update was done at the specified time. The time given must be within the current subscription period, and cannot be - * before the subscription was on its current plan.If set, subscription, and one of subscription_plan, subscription_quantity or + * If previewing an update to a subscription, and doing proration, subscription_proration_date forces the proration to be calculated as + * though the update was done at the specified time. The time given must be within the current subscription period, and cannot be + * before the subscription was on its current plan.If set, subscription, and one of subscription_plan, subscription_quantity or * subscription_trial_end are required. Also, subscription_proration cannot be set to false. */ subscription_proration_date?: number; - + /** - * If provided, the invoice returned will preview updating or creating a subscription with that quantity. If set, one of subscription_plan + * If provided, the invoice returned will preview updating or creating a subscription with that quantity. If set, one of subscription_plan * or subscription is required. */ subscription_quantity?: number; - + /** - * If provided, the invoice returned will preview updating or creating a subscription with that trial end. If set, one of subscription_plan + * If provided, the invoice returned will preview updating or creating a subscription with that trial end. If set, one of subscription_plan * or subscription is required. */ subscription_trial_end?: number; } - + interface IPeriod { /** * The period start date @@ -2152,109 +2152,109 @@ declare namespace StripeNode { * Value is "invoiceitem" */ object: "invoiceitem"; - + amount: number; currency: string; customer: string; date: number; description: string; - + /** * If true, discounts will apply to this invoice item. Always false for prorations. */ discountable: boolean; - + invoice: string; livemode: boolean; metadata: IMetadata; - + period: invoices.IPeriod; - + /** * If the invoice item is a proration, the plan of the subscription that the proration was computed for. */ plan: plans.IPlan; - + /** * Whether or not the invoice item was created automatically as a proration adjustment when the customer switched plans */ proration: boolean; - + /** * If the invoice item is a proration, the quantity of the subscription that the proration was computed for. */ quantity: number; - + /** * The subscription that this invoice item has been created for, if any. */ subscription: string; } - + interface InvoiceItemCreationOptions extends IDataOptionsWithMetadata { /** - * The integer amount in cents of the charge to be applied to the upcoming invoice. If you want to apply a credit to the customer’s + * The integer amount in cents of the charge to be applied to the upcoming invoice. If you want to apply a credit to the customer’s * account, pass a negative amount. */ amount: number; - + /** * 3-letter ISO code for currency. */ currency: string; - + /** * The ID of the customer who will be billed when this invoice item is billed. */ customer: string; - + /** - * An arbitrary string which you can attach to the invoice item. The description is displayed in the invoice for easy tracking. + * An arbitrary string which you can attach to the invoice item. The description is displayed in the invoice for easy tracking. * This can be unset by updating the value to null and then saving. */ description?: string; - + /** - * Controls whether discounts apply to this invoice item. Defaults to false for prorations or negative invoice items, and true for + * Controls whether discounts apply to this invoice item. Defaults to false for prorations or negative invoice items, and true for * all other invoice items. */ discountable?: boolean; - + /** - * The ID of an existing invoice to add this invoice item to. When left blank, the invoice item will be added to the next upcoming - * scheduled invoice. Use this when adding invoice items in response to an invoice.created webhook. You cannot add an invoice item + * The ID of an existing invoice to add this invoice item to. When left blank, the invoice item will be added to the next upcoming + * scheduled invoice. Use this when adding invoice items in response to an invoice.created webhook. You cannot add an invoice item * to an invoice that has already been paid, attempted or closed. */ invoice?: string; - + /** - * The ID of a subscription to add this invoice item to. When left blank, the invoice item will be be added to the next upcoming - * scheduled invoice. When set, scheduled invoices for subscriptions other than the specified subscription will ignore the invoice + * The ID of a subscription to add this invoice item to. When left blank, the invoice item will be be added to the next upcoming + * scheduled invoice. When set, scheduled invoices for subscriptions other than the specified subscription will ignore the invoice * item. Use this when you want to express that an invoice item has been accrued within the context of a particular subscription. */ subscription?: string; } - + interface InvoiceItemUpdateOptions extends IDataOptionsWithMetadata { /** - * The integer amount in cents/pence of the charge to be applied to the upcoming invoice. If you want to apply a credit to the customer's + * The integer amount in cents/pence of the charge to be applied to the upcoming invoice. If you want to apply a credit to the customer's * account, pass a negative amount. */ amount?: number; - + /** - * An arbitrary string which you can attach to the invoice item. The description is displayed in the invoice for easy tracking. This can be + * An arbitrary string which you can attach to the invoice item. The description is displayed in the invoice for easy tracking. This can be * unset by updating the value to null and then saving. */ description?: string; - + /** - * Controls whether discounts apply to this invoice item. Defaults to false for prorations or negative invoice items, and true for all other + * Controls whether discounts apply to this invoice item. Defaults to false for prorations or negative invoice items, and true for all other * invoice items. Cannot be set to true for prorations. */ discountable?: boolean; } - + interface InvoiceItemListOptions extends IListOptionsCreated { /** * The identifier of the customer whose invoice items to return. If none is provided, all invoice items will be returned. @@ -2262,79 +2262,79 @@ declare namespace StripeNode { customer?: string; } } - + namespace orders { interface IOrder extends IResourceObject { /** * Value is "order" */ object: "order"; - + /** - * A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a 0-decimal + * A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a 0-decimal * currency) representing the total amount for the order. */ amount: number; - + /** * ID of the Connect Application that created the order. */ application: string; - + application_fee: number; - + /** * The ID of the payment used to pay for the order. Present if the order status is paid, fulfilled, or refunded. [Expandable] */ charge: string | charges.ICharge; - + created: number; - + /** * 3-letter ISO code representing the currency in which the order was made. */ currency: string; - + /** * The customer used for the order. [Expandable] */ customer: string | customers.ICustomer; - + /** * The email address of the customer placing the order. */ email: string; - + external_coupon_code: string; - + /** * List of items constituting the order. */ items: Array; - + livemode: boolean; metadata: IMetadata; - + /** - * The shipping method that is currently selected for this order, if any. If present, it is equal to one of the ids of shipping methods - * in the shipping_methods array. At order creation time, if there are multiple shipping methods, Stripe will automatically selected + * The shipping method that is currently selected for this order, if any. If present, it is equal to one of the ids of shipping methods + * in the shipping_methods array. At order creation time, if there are multiple shipping methods, Stripe will automatically selected * the first method. */ selected_shipping_method: string; - + /** * The shipping address for the order. Present if the order is for goods to be shipped. */ shipping: IShippingInformation; - + /** - * A list of supported shipping methods for this order. The desired shipping method can be specified either by updating the order, or + * A list of supported shipping methods for this order. The desired shipping method can be specified either by updating the order, or * when paying it. */ shipping_methods: Array; - + status: OrderStatus; - + /** * The timestamps at which the order status was updated */ @@ -2344,225 +2344,225 @@ declare namespace StripeNode { paid: number; returned: number; }; - + updated: number; } - + interface IOrderItem extends IObject { /** * value is "order_item" */ object: "order_item"; - + /** - * A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a 0-decimal currency) + * A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a 0-decimal currency) * representing the total amount for the line item. */ amount: number; - + /** * 3-letter ISO code representing the currency of the line item. */ currency: string; - + /** * Description of the line item, meant to be displayable to the user (e.g., "Express shipping"). */ description: string; - + /** * The ID of the associated object for this line item. Expandable if not null (e.g., expandable to a SKU). [Expandable] */ parent: string | skus.ISku; - + /** - * A positive integer representing the number of instances of parent that are included in this order item. + * A positive integer representing the number of instances of parent that are included in this order item. * Applicable/present only if type is sku. */ quantity: number; - + /** * The type of line item. One of "sku", "tax", "shipping", or "discount". */ type: "sku" | "tax" | "shipping" | "discount" ; } - + interface IOrderCreationOptions extends IDataOptionsWithMetadata { /** - * 3-letter ISO code representing the currency in which the order should be made. Stripe will validate that all entries in items match + * 3-letter ISO code representing the currency in which the order should be made. Stripe will validate that all entries in items match * the currency specified here. */ currency: string; - + /** * A coupon code that represents a discount to be applied to this order. Must be one-time duration and in same currency as the order. */ coupon?: string; - + /** - * The ID of an existing customer to use for this order. If provided, the customer email and shipping address will be used to create - * the order. Subsequently, the customer will also be charged to pay the order. If email or shipping are also provided, they will + * The ID of an existing customer to use for this order. If provided, the customer email and shipping address will be used to create + * the order. Subsequently, the customer will also be charged to pay the order. If email or shipping are also provided, they will * override the values retrieved from the customer object. */ customer?: string; - + /** * The email address of the customer placing the order. */ email?: string; - + /** * List of items constituting the order. */ items?: Array; - + /** * Shipping address for the order. Required if any of the SKUs are for products that have shippable set to true. */ shipping?: IShippingInformation; } - + interface IOrderUpdateOptions extends IDataOptionsWithMetadata { /** * A coupon code that represents a discount to be applied to this order. Must be one-time duration and in same currency as the order. */ coupon?: string; - + /** - * The shipping method to select for fulfilling this order. If specified, must be one of the ids of a shipping method in the + * The shipping method to select for fulfilling this order. If specified, must be one of the ids of a shipping method in the * shipping_methods array. If specified, will overwrite the existing selected shipping method, updating items as necessary. */ selected_shipping_method?: string; - + status: OrderStatus; } - + interface IOrderPayOptions extends IDataOptionsWithMetadata { /** * The ID of an existing customer that will be charged in this request. - * + * * Either customer or source is required */ customer?: string; - + /** - * A payment source to be charged, such as a credit card. If you also pass a customer ID, the source must be the ID of a source belonging - * to the customer. Otherwise, if you do not pass a customer ID, the source you provide must either be a token, like the ones returned - * by Stripe.js, or a object containing a user's credit card details, with the options described below. Although not all information is + * A payment source to be charged, such as a credit card. If you also pass a customer ID, the source must be the ID of a source belonging + * to the customer. Otherwise, if you do not pass a customer ID, the source you provide must either be a token, like the ones returned + * by Stripe.js, or a object containing a user's credit card details, with the options described below. Although not all information is * required, the extra info helps prevent fraud. - * + * * Either source or customer is required */ source?: sources.ISourceCreationOptions; - + /** - * A fee in cents/pence that will be applied to the order and transferred to the application owner's Stripe account. To use an application - * fee, the request must be made on behalf of another account, using the Stripe-Account header or OAuth key. For more information, see + * A fee in cents/pence that will be applied to the order and transferred to the application owner's Stripe account. To use an application + * fee, the request must be made on behalf of another account, using the Stripe-Account header or OAuth key. For more information, see * the application fees documentation. */ application_fee?: number; - + /** * The email address of the customer placing the order. If a customer is specified, that customer's email address will be used. - * + * * Optional, but required if not previously specified. */ email?: string; } - + interface IOrderListOptions extends IListOptionsCreated { /** * Only return orders for the given customer */ customer?: string; - + /** * Only return orders with the given IDs */ ids?: Array; - + /** * Only return orders that have the given status. One of "created", "paid", "fulfilled", or "refunded". */ status: OrderStatus; - + /** * Filter orders based on when they were "paid", "fulfilled", "canceled", or "returned" */ status_transitions?: { /** - * A filter on the list based on the object canceled field. The value can be a string with an integer Unix timestamp, + * A filter on the list based on the object canceled field. The value can be a string with an integer Unix timestamp, * or it can be a dictionary with the following options: */ canceled?: IDateFilter; - + /** - * A filter on the list based on the object fulfilled field. The value can be a string with an integer Unix timestamp, + * A filter on the list based on the object fulfilled field. The value can be a string with an integer Unix timestamp, * or it can be a dictionary with the following options: */ fulfilled?: IDateFilter; - + /** - * A filter on the list based on the object paid field. The value can be a string with an integer Unix timestamp, + * A filter on the list based on the object paid field. The value can be a string with an integer Unix timestamp, * or it can be a dictionary with the following options: */ paid?: IDateFilter; - + /** - * A filter on the list based on the object returned field. The value can be a string with an integer Unix timestamp, + * A filter on the list based on the object returned field. The value can be a string with an integer Unix timestamp, * or it can be a dictionary with the following options: */ returned?: IDateFilter; } } - + interface IOrderItemCreationHash { /** - * A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a 0-decimal currency) + * A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a 0-decimal currency) * representing the total amount for the line item. */ amount?: number; - + /** * 3-letter ISO code representing the currency of the line item. */ currency?: string; - + /** * Description of the line item, meant to be displayable to the user (e.g., "Express shipping"). */ description?: string; - + /** * The ID of the SKU being ordered. */ parent: string; - + /** * The quantity of this order item. When type is sku, this is the number of instances of the SKU to be ordered. */ quantity?: number; - + /** * The type of line item. One of "sku", "tax", "shipping", or "discount". */ type?: "sku" | "tax" | "shipping" | "discount" ; } - + interface IShippingMethod { id: string; - + /** - * A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a 0-decimal currency) + * A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1, Japanese Yen being a 0-decimal currency) * representing the total amount for the line item. */ amount: number; - + /** * 3-letter ISO code representing the currency of the line item. */ currency: string; - + /** * The estimated delivery date for the given shipping method. Can be either a specific date or a range. */ @@ -2571,35 +2571,35 @@ declare namespace StripeNode { * If type is "exact", date will be the expected delivery date in the format YYYY-MM-DD */ date: string; - + /** * If type is "range", earliest will be be the earliest delivery date in the format YYYY-MM-DD */ earliest: string; - + /** * If type is "range", latest will be the latest delivery date in the format YYYY-MM-DD */ latest: string; - + /** * The type of estimate. Must be either "range" or "exact" */ type: "range" | "exact"; }; - + /** * Description of the line item, meant to be displayable to the user (e.g., "Express shipping"). */ description: string; } - + /** * Current order status. One of created, paid, canceled, fulfilled, or returned. More detail in the Relay API Overview. */ type OrderStatus = "created" | "paid" | "canceled" | "fulfilled" | "returned"; } - + namespace plans { /** * A subscription plan contains the pricing information for different products and feature levels on your site. @@ -2610,12 +2610,12 @@ declare namespace StripeNode { * Value is "plan" */ object: "plan"; - + /** * The amount in cents to be charged on the interval specified */ amount: number; - + created: number; /** @@ -2627,290 +2627,290 @@ declare namespace StripeNode { * One of "day", "week", "month" or "year". The frequency with which a subscription should be billed. */ interval: IntervalUnit; - + /** * The number of intervals (specified in the interval property) between each subscription billing. For example, * interval=month and interval_count=3 bills every 3 months. */ interval_count: number; - + livemode: boolean; metadata: IMetadata; - + /** * Display name of the plan */ name: string; - + /** * Extra information about a charge for the customer's credit card statement. */ statement_descriptor: string; - + /** * Number of trial period days granted when subscribing a customer to this plan. Null if the plan has no trial period. */ trial_period_days: number; } - + interface IPlanCreationOptions extends IDataOptionsWithMetadata { /** - * Unique string of your choice that will be used to identify this plan when subscribing a customer. This could be an identifier + * Unique string of your choice that will be used to identify this plan when subscribing a customer. This could be an identifier * like "gold" or a primary key from your own database. */ id: string; - + /** * A positive integer in cents/pence (or 0 for a free plan) representing how much to charge (on a recurring basis). */ amount: number; - + /** * 3-letter ISO code for currency. */ currency: string; - + /** * Specifies billing frequency. Either "day", "week", "month" or "year". */ interval: IntervalUnit; - + /** * Name of the plan, to be displayed on invoices and in the web interface. */ name: string; - + /** - * The number of intervals between each subscription billing. For example, interval=month and interval_count=3 bills every 3 months. + * The number of intervals between each subscription billing. For example, interval=month and interval_count=3 bills every 3 months. * Maximum of one year interval allowed (1 year, 12 months, or 52 weeks). */ interval_count?: number; - + /** - * An arbitrary string to be displayed on your customer’s credit card statement. This may be up to 22 characters. As an example, if your website - * is RunClub and the item you’re charging for is your Silver Plan, you may want to specify a statement_descriptor of RunClub Silver Plan. - * The statement description may not include <>"' characters, and will appear on your customer’s statement in capital letters. Non-ASCII + * An arbitrary string to be displayed on your customer’s credit card statement. This may be up to 22 characters. As an example, if your website + * is RunClub and the item you’re charging for is your Silver Plan, you may want to specify a statement_descriptor of RunClub Silver Plan. + * The statement description may not include <>"' characters, and will appear on your customer’s statement in capital letters. Non-ASCII * characters are automatically stripped. While most banks display this information consistently, some may display it incorrectly or not at all. */ statement_descriptor?: string; - + /** - * Specifies a trial period in (an integer number of) days. If you include a trial period, the customer won't be billed for the first time + * Specifies a trial period in (an integer number of) days. If you include a trial period, the customer won't be billed for the first time * until the trial period ends. If the customer cancels before the trial period is over, she'll never be billed at all. */ trial_period_days?: number; } - + interface IPlanUpdateOptions extends IDataOptionsWithMetadata { /** * Name of the plan, to be displayed on invoices and in the web interface. */ name?: string; - + /** - * An arbitrary string to be displayed on your customer’s credit card statement. This may be up to 22 characters. As an example, if your website - * is RunClub and the item you’re charging for is your Silver Plan, you may want to specify a statement_descriptor of RunClub Silver Plan. - * The statement description may not include <>"' characters, and will appear on your customer’s statement in capital letters. Non-ASCII + * An arbitrary string to be displayed on your customer’s credit card statement. This may be up to 22 characters. As an example, if your website + * is RunClub and the item you’re charging for is your Silver Plan, you may want to specify a statement_descriptor of RunClub Silver Plan. + * The statement description may not include <>"' characters, and will appear on your customer’s statement in capital letters. Non-ASCII * characters are automatically stripped. While most banks display this information consistently, some may display it incorrectly or not at all. */ statement_descriptor?: string; } - + type IntervalUnit = "day" | "week" | "month" | "year"; } - + namespace products { interface IProduct extends IResourceObject { /** * Value is "product" */ object: "product"; - + /** * Whether or not the product is currently available for purchase. */ active: boolean; - + /** * A list of up to 5 attributes that each SKU can provide values for (e.g. ["color", "size"]). */ attributes: Array; - + /** * A short one-line description of the product, meant to be displayable to the customer. */ caption: string; - + created: number; - + /** * An array of connect application identifiers that cannot purchase this product. */ deactivated_on: Array; - + /** * The product’s description, meant to be displayable to the customer. */ description: string; - + /** * A list of up to 8 URLs of images for this product, meant to be displayable to the customer. */ images: Array; - + livemode: boolean; metadata: IMetadata; - + /** * The product’s name, meant to be displayable to the customer. */ name: string; - + package_dimensions: IPackageDimensions; - + /** * Whether this product is a shipped good. */ shippable: boolean; - + /** * A sublist of active SKUs associated with this product. */ skus: IList; - + updated: number; - + /** * A URL of a publicly-accessible webpage for this product. */ url: string; } - + interface IProductCreationOptions extends IDataOptionsWithMetadata { /** * The identifier for the product. Must be unique. If not provided, an identifier will be randomly generated. */ id?: string; - + /** * The product’s name, meant to be displayable to the customer. */ name: string; - + /** * Whether or not the product is currently available for purchase. Defaults to true. */ active?: boolean; - + /** * A list of up to 5 alphanumeric attributes that each SKU can provide values for (e.g. ["color", "size"]). */ attribute?: Array; - + /** * A short one-line description of the product, meant to be displayable to the customer. */ caption?: string; - + /** * An array of Connect application names or identifiers that should not be able to order the SKUs for this product. */ deactivate_on?: Array; - + /** * The product’s description, meant to be displayable to the customer. */ description?: string; - + /** * A list of up to 8 URLs of images for this product, meant to be displayable to the customer. */ images?: Array; - + package_dimensions?: IPackageDimensions; - + /** * Whether this product is shipped (i.e. physical goods). Defaults to true. */ shippable?: boolean; - + /** * A URL of a publicly-accessible webpage for this product. */ url?: string; } - + interface IProductUpdateOptions extends IDataOptionsWithMetadata { /** - * Whether or not the product is available for purchase. Setting this to false also deactivates any active, related SKUs. Setting this to + * Whether or not the product is available for purchase. Setting this to false also deactivates any active, related SKUs. Setting this to * true does not automatically activate any deactivated, related SKUs. */ active?: boolean; - + /** * A short one-line description of the product, meant to be displayable to the customer. */ caption?: string; - + /** - * An array of Connect application names or identifiers that should not be able to order the SKUs for this product. This can be unset + * An array of Connect application names or identifiers that should not be able to order the SKUs for this product. This can be unset * by updating the value to null and then saving. */ deactivate_on?: Array; - + /** * The product’s description, meant to be displayable to the customer. */ description?: string; - + /** - * A list of up to 8 URLs of images for this product, meant to be displayable to the customer. This can be unset by updating the value to + * A list of up to 8 URLs of images for this product, meant to be displayable to the customer. This can be unset by updating the value to * null and then saving. */ images?: Array; - + /** * The product’s name, meant to be displayable to the customer. */ name?: string; - + package_dimensions?: IPackageDimensions; - + /** * Whether this product is shipped (i.e. physical goods). Defaults to true. */ shippable?: boolean; - + /** * A URL of a publicly-accessible webpage for this product. */ url?: string; } - + interface IProductListOptions extends IListOptions { /** * Only return products that are active or inactive (e.g. pass false to list all inactive products). */ active?: boolean; - + /** * Only return products with the given IDs. */ ids?: Array; - + /** * Only return products that can be shipped (i.e., physical, not digital products). */ shippable?: boolean; - + /** * Only return products with the given url */ url?: string; } - + /** - * The dimensions of this product for shipping purposes. A SKU associated with this product can override this value by having its + * The dimensions of this product for shipping purposes. A SKU associated with this product can override this value by having its * own package_dimensions */ interface IPackageDimensions { @@ -2932,277 +2932,277 @@ declare namespace StripeNode { width: number; } } - + namespace recipientCards { } - + namespace recipients { - interface IRecipient extends IResourceObject { - + interface IRecipient extends IResourceObject { + } } - + namespace skus { interface ISku extends IResourceObject { /** * Value is "sku" */ object: "sku"; - + /** * Whether or not the SKU is available for purchase. */ active: boolean; - + attributes: ISkuAttributes; created: number; - + /** * 3-letter ISO code for currency. */ currency: string; - + /** * The URL of an image for this SKU, meant to be displayable to the customer. */ image: string; - + inventory: IInventory; livemode: boolean; metadata: IMetadata; - + /** * The dimensions of this SKU for shipping purposes. */ package_dimensions: products.IPackageDimensions; - + /** - * The cost of the item as a positive integer in the smallest currency unit (that is, 100 cents to charge $1.00, or 1 to charge ¥1, + * The cost of the item as a positive integer in the smallest currency unit (that is, 100 cents to charge $1.00, or 1 to charge ¥1, * Japanese Yen being a 0-decimal currency). */ price: number; - + /** * The ID of the product this SKU is associated with. The product must be currently active. [Expandable] */ product: string | products.IProduct; - + updated: number; } - + interface ISkuCreationOptions extends IDataOptionsWithMetadata { /** * The identifier for the SKU. Must be unique. If not provided, an identifier will be randomly generated. */ id?: string; - + /** * 3-letter ISO code for currency. */ currency: string; - + inventory: IInventory; - + /** - * The cost of the item as a nonnegative integer in the smallest currency unit (that is, 100 cents to charge $1.00, or 1 to charge ¥1, + * The cost of the item as a nonnegative integer in the smallest currency unit (that is, 100 cents to charge $1.00, or 1 to charge ¥1, * Japanese Yen being a 0-decimal currency). */ price: number; - + /** * The ID of the product this SKU is associated with. */ product: string; - + /** * Whether or not the SKU is available for purchase. Default to true. */ active?: boolean; - + attributes?: ISkuAttributes; - + /** * The URL of an image for this SKU, meant to be displayable to the customer. */ image?: string; - + /** * The dimensions of this SKU for shipping purposes. */ package_dimensions?: products.IPackageDimensions; } - + interface ISkuUpdateOptions extends IDataOptionsWithMetadata { /** * Whether or not the SKU is available for purchase. */ active?: boolean; - + /** * 3-letter ISO code for currency. */ currency?: string; - + /** - * The URL of an image for this SKU, meant to be displayable to the customer. + * The URL of an image for this SKU, meant to be displayable to the customer. * This can be unset by updating the value to null and then saving. */ image?: string; - + inventory?: IInventory; - + /** * The dimensions of this SKU for shipping purposes. */ package_dimensions?: products.IPackageDimensions; - + /** - * The cost of the item as a nonnegative integer in the smallest currency unit (that is, 100 cents to charge $1.00, or 1 to charge ¥1, + * The cost of the item as a nonnegative integer in the smallest currency unit (that is, 100 cents to charge $1.00, or 1 to charge ¥1, * Japanese Yen being a 0-decimal currency). */ price?: number; - + /** * The ID of the product this SKU is associated with. */ product?: string; } - + interface ISkuListOptions extends IListOptions { /** * Only return SKUs that are active or inactive (e.g. pass false to list all inactive products). */ active?: boolean; - + /** - * Only return SKUs that have the specified key/value pairs in this partially constructed dictionary. - * Can be specified only if product is also supplied. For instance, if the associated product has - * attributes ["color", "size"], passing in attributes[color]=red returns all the SKUs for this product + * Only return SKUs that have the specified key/value pairs in this partially constructed dictionary. + * Can be specified only if product is also supplied. For instance, if the associated product has + * attributes ["color", "size"], passing in attributes[color]=red returns all the SKUs for this product * that have color set to red. */ attributes?: ISkuAttributes; - + /** * Only return SKUs with the given IDs. */ ids?: Array; - + /** - * Only return SKUs that are either in stock or out of stock (e.g. pass false to list all SKUs that are out of stock). + * Only return SKUs that are either in stock or out of stock (e.g. pass false to list all SKUs that are out of stock). * If no value is provided, all SKUs are returned. */ in_stock?: boolean; - + /** * The ID of the product whose SKUs will be retrieved. */ product?: string; } - + /** * Description of the SKU’s inventory. */ interface IInventory { /** * The count of inventory available. Will be present if and only if type is "finite". - * + * * Positive integer or zero */ quantity?: number; - + /** * Inventory type. Possible values are "finite", "bucket"" (not quantified), and "infinite". */ type: "finite" | "bucket" | "infinite" ; - + /** - * An indicator of the inventory available. Possible values are "in_stock", "limited", and "out_of_stock". + * An indicator of the inventory available. Possible values are "in_stock", "limited", and "out_of_stock". * Will be present if and only if type is "bucket". */ value?: "in_stock" | "limited" | "out_of_stock"; } - + /** - * A dictionary of attributes and values for the attributes defined by the product. - * If, for example, a product’s attributes are ["size", "gender"], + * A dictionary of attributes and values for the attributes defined by the product. + * If, for example, a product’s attributes are ["size", "gender"], * a valid SKU has the following dictionary of attributes: {"size": "Medium", "gender": "Unisex"}. */ interface ISkuAttributes {} } - - namespace tokens { + + namespace tokens { interface IToken extends ICardToken, IBankAccountToken { } - + interface ICardToken extends ITokenBase { /** * Hash describing the card used to make the charge */ card?: cards.ICardHash; } - + interface IBankAccountToken extends ITokenBase { /** * Hash describing the bank account */ bank_account?: bankAccounts.IBankAccountHash; } - + interface ITokenBase extends IResourceObject { /** * Value is "token"" */ object: "token" ; - + /** * IP address of the client that generated the token */ client_ip: string; - + created: number; livemode: boolean; - + /** * Type of the token: card or bank_account */ type: "card" | "bank_account" ; - + /** * Whether or not this token has already been used (tokens can be used only once) */ used: boolean; } - + interface ITokenCreationOptionsBase extends IDataOptions { /** - * The customer (owned by the application's account) to create a - * token for. For use with Stripe Connect only; this can only be used - * with an OAuth access token or Stripe-Account header. For more + * The customer (owned by the application's account) to create a + * token for. For use with Stripe Connect only; this can only be used + * with an OAuth access token or Stripe-Account header. For more * details, see the shared customers documentation. - * + * * Stripe connect only */ customer?: string; } - + interface ICardTokenCreationOptions extends ITokenCreationOptionsBase { /** - * The card this token will represent. If you also pass in a customer, - * the card must be the ID of a card belonging to the customer. - * Otherwise, if you do not pass a customer, a object containing a + * The card this token will represent. If you also pass in a customer, + * the card must be the ID of a card belonging to the customer. + * Otherwise, if you do not pass a customer, a object containing a * user's credit card details, with the options described below. */ card: sources.ISourceCreationOptions; } - + interface IBankAccountTokenCreationOptions extends ITokenCreationOptionsBase { /** - * The card this token will represent. If you also pass in a customer, - * the card must be the ID of a card belonging to the customer. - * Otherwise, if you do not pass a customer, a object containing a + * The card this token will represent. If you also pass in a customer, + * the card must be the ID of a card belonging to the customer. + * Otherwise, if you do not pass a customer, a object containing a * user's credit card details, with the options described below. */ bank_account: bankAccounts.ISourceCreationOptions; } - + interface IPiiTokenCreationOptions extends IDataOptions { pii: { /** @@ -3212,31 +3212,31 @@ declare namespace StripeNode { } } } - + namespace transfers { interface ITransfer extends IResourceObject { /** * Value is "transfer" */ object: "transfer"; - + /** * Amount (in cents) to be transferred to your bank account */ amount: number; - + /** * Amount in cents reversed (can be less than the amount attribute on the transfer if a partial reversal was issued). */ amount_reversed: number; - + application_fee: string; - + /** * Balance transaction that describes the impact of this transfer on your account balance. [Expandable] */ balance_transaction: string | balance.IBalanceTransaction; - + /** * Time that this record of the transfer was first created. */ @@ -3256,193 +3256,193 @@ declare namespace StripeNode { * Internal-only description of the transfer */ description: string; - + /** * ID of the bank account, card, or Stripe account the transfer was sent to. [Expandable] */ destination: string | bankAccounts.IBankAccount | cards.ICardHash | accounts.IAccount; - + /** - * If the destination is a Stripe account, this will be the ID of the + * If the destination is a Stripe account, this will be the ID of the * payment that the destination account received for the transfer. [Expandable] */ destination_payment: string; - + /** * Error code explaining reason for transfer failure if available. See Types of transfer failures for a * list of failure codes: https://stripe.com/docs/api#transfer_failures */ failure_code: string; - + /** * Message to user further explaining reason for transfer failure if available. */ failure_message: string; - + livemode: boolean; metadata: IMetadata; - + /** * A list of reversals that have been applied to the transfer. */ reversals: ITransferReversals; - + /** * Whether or not the transfer has been fully reversed. If the transfer is only partially reversed, this attribute * will still be false. */ reversed: boolean; - + /** - * ID of the charge (or other transaction) that was used to fund the - * transfer. If null, the transfer was funded from the available + * ID of the charge (or other transaction) that was used to fund the + * transfer. If null, the transfer was funded from the available * balance. [Expandable] */ source_transaction: string | charges.ICharge; - + /** - * The source balance this transfer came from. + * The source balance this transfer came from. * One of card, bank_account, bitcoin_receiver, or alipay_account */ source_type: SourceTypes; - + /** * Extra information about a transfer to be displayed on the user's bank statement. */ statement_descriptor: string; - + /** - * Current status of the transfer (paid, pending, in_transit, canceled or failed). - * A transfer will be pending until it is submitted to the bank, at which point - * it becomes in_transit. It will then change to paid if the transaction goes - * through. If it does not go through successfully, its status will change to + * Current status of the transfer (paid, pending, in_transit, canceled or failed). + * A transfer will be pending until it is submitted to the bank, at which point + * it becomes in_transit. It will then change to paid if the transaction goes + * through. If it does not go through successfully, its status will change to * failed or canceled. */ status: Statuses; - + /** * Can be card, bank_account, or stripe_account. */ type: "card" | "bank_account" | "stripe_account" ; } - + interface ITransferReversals extends IList, resources.TransferReversals {} - + interface ITransferCreationOptions extends IDataOptionsWithMetadata { /** * A positive integer in cents/pence representing how much to transfer. */ amount: number; - + /** * 3-letter ISO code for currency. */ currency: string; - + /** - * The id of a bank account or a card to send the transfer to, or the - * string "default_for_currency" to use the default external - * account for the specified currency. - * - * If you use Stripe Connect, this can be the the id of a connected - * Stripe account; see the details about when such transfers are + * The id of a bank account or a card to send the transfer to, or the + * string "default_for_currency" to use the default external + * account for the specified currency. + * + * If you use Stripe Connect, this can be the the id of a connected + * Stripe account; see the details about when such transfers are * permitted. */ destination: string; - + /** - * An arbitrary string which you can attach to a transfer object. It is + * An arbitrary string which you can attach to a transfer object. It is * displayed when in the web interface alongside the transfer. */ description?: string - + /** - * You can use this parameter to transfer funds from a charge (or - * other transaction) before they are added to your available - * balance. A pending balance will transfer immediately but the - * funds will not become available until the original charge + * You can use this parameter to transfer funds from a charge (or + * other transaction) before they are added to your available + * balance. A pending balance will transfer immediately but the + * funds will not become available until the original charge * becomes available. See the Connect documentation for details. */ source_transaction?: string; - + /** - * A string to be displayed on the recipient's bank or card - * statement. This may be at most 22 characters. Attempting to use - * a statement_descriptor longer than 22 characters will return - * an error. Note: Most banks will truncate this information and/or + * A string to be displayed on the recipient's bank or card + * statement. This may be at most 22 characters. Attempting to use + * a statement_descriptor longer than 22 characters will return + * an error. Note: Most banks will truncate this information and/or * display it inconsistently. Some may not display it at all. */ statement_descriptor?: string; - + /** - * The source balance to draw this transfer from. Balances for - * different payment sources are kept separately. You can find the - * amounts with the balances API. Valid options are: + * The source balance to draw this transfer from. Balances for + * different payment sources are kept separately. You can find the + * amounts with the balances API. Valid options are: * "alipay_account", "bank_account", "bitcoin_receiver", and "card". */ source_type?: SourceTypes; } - + interface ITransferUpdateOptions extends IDataOptionsWithMetadata { /** - * An arbitrary string which you can attach to a transfer object. It is - * displayed when in the web interface alongside the transfer. This + * An arbitrary string which you can attach to a transfer object. It is + * displayed when in the web interface alongside the transfer. This * can be unset by updating the value to null and then saving. */ description?: string; } - + interface ITransferListOptions extends IListOptionsCreated { date?: IDateFilter; - + /** - * Only return transfers for the destination specified by this + * Only return transfers for the destination specified by this * account ID. */ destination?: string; - + /** - * Only return transfers for the recipient specified by this + * Only return transfers for the recipient specified by this * recipient ID. */ recipient?: string; - + /** - * Only return transfers that have the given status: + * Only return transfers that have the given status: * pending, paid, failed, in_transit, or canceled. */ status: Statuses; } - + type SourceTypes = "alipay_account" | "bank_account" | "bitcoin_receiver" | "card"; - + type Statuses = "pending" | "paid" | "failed" | "in_transit" | "canceled"; } - + namespace transferReversals { interface IReversal extends IResourceObject { /** * Value is 'transfer_reversal' */ object: "transfer_reversal"; - + /** * Amount reversed, in cents/pence. */ amount: number; - + /** * Balance transaction that describes the impact of this reversal on your account balance. [Expandable] */ balance_transaction: string | balance.IBalanceTransaction; - + created: number; /** * Three-letter ISO currency code representing the currency. */ currency: string; - + metadata: IMetadata; /** @@ -3450,76 +3450,76 @@ declare namespace StripeNode { */ transfer: string | transfers.ITransfer; } - + interface IReversalCreationOptions extends IDataOptionsWithMetadata { /** - * A positive integer in cents/pence representing how much of this transfer to reverse. Can only reverse up to the unreversed amount + * A positive integer in cents/pence representing how much of this transfer to reverse. Can only reverse up to the unreversed amount * remaining of the transfer. Partial transfer reversals are only allowed for transfers to Stripe Accounts. */ amount?: number; - + /** - * An arbitrary string which you can attach to a reversal object. It is displayed alongside the reversal in the dashboard. This will + * An arbitrary string which you can attach to a reversal object. It is displayed alongside the reversal in the dashboard. This will * be unset if you POST an empty value. */ description?: string; - + /** - * Boolean indicating whether the application fee should be refunded when reversing this transfer. If a full transfer reversal is - * given, the full application fee will be refunded. Otherwise, the application fee will be refunded with an amount proportional to + * Boolean indicating whether the application fee should be refunded when reversing this transfer. If a full transfer reversal is + * given, the full application fee will be refunded. Otherwise, the application fee will be refunded with an amount proportional to * the amount of the transfer reversed. */ refund_application_fee?: boolean; } - + interface IReversalUpdateOptions extends IDataOptionsWithMetadata { /** - * An arbitrary string which you can attach to a reversal object. It is displayed when in the web interface alongside the + * An arbitrary string which you can attach to a reversal object. It is displayed when in the web interface alongside the * reversal. This can be unset by updating the value to null and then saving. */ description?: string; } } - + namespace bankAccounts { interface IBankAccount extends IBankAccountHash { account: string; - + /** * This indicates whether or not this bank account is the default external account for its currency. */ default_for_currency: boolean; - + /** - * A set of key/value pairs that you can attach to a bank account object. It - * can be useful for storing additional information about the bank account in + * A set of key/value pairs that you can attach to a bank account object. It + * can be useful for storing additional information about the bank account in * a structured format. */ metadata: IMetadata; } - + interface IBankAccountHash extends IResourceObject { /** * value is "customer_bank_account" */ object: "customer_bank_account"; - + /** * The name of the person or business that owns the bank account. */ account_holder_name: string; - + /** - * The type of entity that holds the account. This can be either + * The type of entity that holds the account. This can be either * "individual"" or "company". */ account_holder_type: string; - + /** * Name of the bank associated with the routing number, e.g. WELLS FARGO. */ bank_name: string; - + /** * Two-letter ISO code representing the country the bank account is located in. */ @@ -3529,90 +3529,90 @@ declare namespace StripeNode { * Three-letter ISO currency code representing the currency paid out to the bank account. */ currency: string; - + /** - * Uniquely identifies this particular bank account. You can use this attribute + * Uniquely identifies this particular bank account. You can use this attribute * to check whether two bank accounts are the same. */ fingerprint: string; - + last4: string; - + /** * The routing transit number for the bank account. */ routing_number: string; - + /** - * Possible values are "new", "validated", "verified", "verification_failed", - * or "errored". A bank account that hasn’t had any activity or validation - * performed is "new". If Stripe can determine that the bank account exists, its - * status will be "validated". Note that there often isn’t enough information - * to know (e.g. for smaller credit unions), and the validation is not always - * run. If customer bank account verification has succeeded, the bank - * account status will be "verified". If the verification failed for any reason, - * such as microdeposit failure, the status will be "verification_failed". If a - * transfer sent to this bank account fails, we’ll set the status to "errored"" + * Possible values are "new", "validated", "verified", "verification_failed", + * or "errored". A bank account that hasn’t had any activity or validation + * performed is "new". If Stripe can determine that the bank account exists, its + * status will be "validated". Note that there often isn’t enough information + * to know (e.g. for smaller credit unions), and the validation is not always + * run. If customer bank account verification has succeeded, the bank + * account status will be "verified". If the verification failed for any reason, + * such as microdeposit failure, the status will be "verification_failed". If a + * transfer sent to this bank account fails, we’ll set the status to "errored"" * and will not continue to send transfers until the bank details are updated. */ status: "new" | "validated" | "verified" | "verification_failed" | "error" ; } - + interface ISourceCreationOptions { /** - * The account number for the bank account in string form. + * The account number for the bank account in string form. * Must be a checking account. */ account_number: string; - + /** * The country the bank account is in. */ country: string; - + /** - * The currency the bank account is in. This must be a + * The currency the bank account is in. This must be a * country/currency pairing that Stripe supports. */ currency: string; - + /** - * The routing number, sort code, or other country-appropriate - * institution number for the bank account. For US bank - * accounts, this is required and should be the ACH routing - * number, not the wire routing number. If you are providing an + * The routing number, sort code, or other country-appropriate + * institution number for the bank account. For US bank + * accounts, this is required and should be the ACH routing + * number, not the wire routing number. If you are providing an * IBAN for account_number, this field is not required. */ routing_number?: string; - + /** - * The name of the person or business that owns the bank - * account. This field is required when attaching the bank + * The name of the person or business that owns the bank + * account. This field is required when attaching the bank * account to a customer object. */ account_holder_name?: string; - + /** - * The type of entity that holds the account. This can be either - * "individual" or "company". This field is required when + * The type of entity that holds the account. This can be either + * "individual" or "company". This field is required when * attaching the bank account to a customer object. */ account_holder_type?: "individual" | "company" ; } - + interface IBankAccountUpdateOptions extends IDataOptionsWithMetadata { /** * The name of the person or business that owns the bank account. */ account_holder_name?: string; - + /** * The type of entity that holds the account. This can be either "individual" or "company". */ account_holder_type?: "individual" | "company"; } } - + namespace bitcoinReceivers { /** * A Bitcoin receiver wraps a Bitcoin address so that a customer can push a payment to you. This guide describes how to use @@ -3654,22 +3654,22 @@ declare namespace StripeNode { * This URI can be displayed to the customer as a clickable link (to activate their bitcoin client) or as a QR code (for mobile wallets). */ bitcoin_uri: number; - + created: number; /** * Three-letter ISO currency code representing the currency to which the bitcoin will be converted. */ currency: string; - + customer: string; description: string; - + /** * The customer's email address, set by the API call that creates the receiver. */ email: string; - + /** * This flag is initially false and updates to true when the customer sends the bitcoin_amount to this receiver. */ @@ -3679,20 +3679,20 @@ declare namespace StripeNode { * A bitcoin address that is specific to this receiver. The customer can send bitcoin to this address to fill the receiver. */ inbound_address: string; - + livemode: boolean; metadata: IMetadata; - + /** * The ID of the payment created from the receiver, if any. Hidden when viewing the receiver with a publishable key. */ payment: string; - + /** * The refund address for these bitcoin, if communicated by the customer. */ refund_address: string; - + /** * A list with one entry for each time that the customer sent bitcoin to the receiver. Hidden when viewing the * receiver with a publishable key. @@ -3703,7 +3703,7 @@ declare namespace StripeNode { * This receiver contains uncaptured funds that can be used for a payment or refunded. */ uncaptured_funds: boolean; - + used_for_payment: boolean; } @@ -3722,7 +3722,7 @@ declare namespace StripeNode { * The amount of bitcoin contained in the transaction. */ bitcoin_amount: number; - + created: number; /** @@ -3735,91 +3735,91 @@ declare namespace StripeNode { */ receiver: string; } - + interface IBitcoinReceiverCreationOptions extends IDataOptionsWithMetadata { /** * The amount of currency that you will be paid. */ amount: number; - + /** * The currency to which the bitcoin will be converted. You will be paid out in this currency. Only USD is currently supported. */ currency: string; - + /** * The email address of the customer. */ email: string; - + description?: string; - + /** * A flag that indicates whether you would like Stripe to automatically handle refunds for any mispayments to the receiver. */ refund_mispayments?: boolean; } - + interface IBitcoinReceiverListOptions extends IListOptions { /** * Filter for active receivers. */ active?: boolean; - + /** * Filter for filled receivers. */ filled?: boolean; - + /** * Filter for receivers with uncaptured funds. */ uncaptured_funds?: boolean; } } - - namespace cards { + + namespace cards { /** * You can store multiple cards on a customer in order to charge the customer later. You * can also store multiple debit cards on a recipient in order to transfer to those cards later. */ interface ICard extends ICardHash { /** - * The account this card belongs to. This attribute will not be in the + * The account this card belongs to. This attribute will not be in the * card object if the card belongs to a customer or recipient instead. * [Expandable] */ account?: string | accounts.IAccount; - + /** - * Only applicable on accounts (not customers or recipients). The - * card can be used as a transfer destination for funds in this + * Only applicable on accounts (not customers or recipients). The + * card can be used as a transfer destination for funds in this * currency. */ currency?: string; - + /** - * The customer that this card belongs to. This attribute will not be - * in the card object if the card belongs to an account or recipient + * The customer that this card belongs to. This attribute will not be + * in the card object if the card belongs to an account or recipient * instead. */ customer?: customers.ICustomer; - + /** - * Only applicable on accounts (not customers or recipients). This - * indicates whether or not this card is the default external account + * Only applicable on accounts (not customers or recipients). This + * indicates whether or not this card is the default external account * for its currency. */ default_for_currency?: boolean; - + /** - * The recipient that this card belongs to. This attribute will not be - * in the card object if the card belongs to a customer or account + * The recipient that this card belongs to. This attribute will not be + * in the card object if the card belongs to a customer or account * instead. [Expandable] */ recipient?: string | recipients.IRecipient; } - + /** * Hash describing the card used to make the charge */ @@ -3838,7 +3838,7 @@ declare namespace StripeNode { * The card number */ number: number; - + /** * Card brand. Can be Visa, American Express, MasterCard, Discover, JCB, Diners Club, or Unknown. */ @@ -3866,18 +3866,18 @@ declare namespace StripeNode { address_line2: string; address_state: string; address_zip: string; - + /** * If address_zip was provided, results of the check: pass, fail, unavailable, or unchecked. */ address_zip_check: "pass" | "fail" | "unavailable" | "unchecked" ; - + /** * Two-letter ISO code representing the country of the card. You could use this * attribute to get a sense of the international breakdown of cards you've collected. */ country: string; - + /** * If a CVC was provided, results of the check: pass, fail, unavailable, or unchecked */ @@ -3892,22 +3892,22 @@ declare namespace StripeNode { * Cardholder name */ name: string; - + /** * Uniquely identifies this particular card number. You can use this attribute to check * whether two customers who've signed up with you are using the same card number, for example. */ fingerprint: string; - + metadata?: IMetadata; - + /** - * If the card number is tokenized, this is the method that was + * If the card number is tokenized, this is the method that was * used. Can be "apple_pay" or "android_pay". */ tokenization_method: "apple_pay" | "android_pay"; } - + interface ICardUpdateOptions extends IDataOptionsWithMetadata { address_city?: string; address_country?: string; @@ -3915,85 +3915,85 @@ declare namespace StripeNode { address_line2?: string; address_state?: string; address_zip?: string; - + /** - * Only applicable on accounts (not customers or recipients). - * If set to true, this card will become the default external + * Only applicable on accounts (not customers or recipients). + * If set to true, this card will become the default external * account for its currency. - * + * * Managed accounts only */ default_for_currency?: boolean; - + exp_month?: number; exp_year?: number; - + /** * Cardholder name */ name?: string; } - + interface ISourceCreationOptions { /** * he type of payment source. Should be "card". */ object: "card"; - + /** * Two digit number representing the card's expiration month. */ exp_month: number; - + /** * Two or four digit number representing the card's expiration year. */ exp_year: number; - + /** * The card number, as a string without any separators. */ number: number; - + /** - * Card security code. Required unless your account is registered in - * Australia, Canada, or the United States. Highly recommended to always + * Card security code. Required unless your account is registered in + * Australia, Canada, or the United States. Highly recommended to always * include this value. */ cvc?: number; - + /** * Cardholder's full name. */ name?: string; - + address_city?: string; address_country?: string; address_line1?: string; address_line2?: string; address_state?: string; address_zip?: string; - + metadata?: IMetadata; } - + interface ISourceCreationOptionsExtended extends ISourceCreationOptions { /** - * Required when adding a card to an account (not applicable to a - * customers or recipients). The card (which must be a debit card) can be - * used as a transfer destination for funds in this currency. Currently, the + * Required when adding a card to an account (not applicable to a + * customers or recipients). The card (which must be a debit card) can be + * used as a transfer destination for funds in this currency. Currently, the * only supported currency for debit card transfers is usd. - * + * * Managed accounts only. */ currency?: string; - + /** - * Only applicable on accounts (not customers or recipients). If you set - * this to true (or if this is the first external account being added in this - * currency) this card will become the default external account for its + * Only applicable on accounts (not customers or recipients). If you set + * this to true (or if this is the first external account being added in this + * currency) this card will become the default external account for its * currency. - * + * * Managed accounts only. */ default_for_currency?: boolean; @@ -4010,70 +4010,70 @@ declare namespace StripeNode { * Value is "subscription" */ object: "subscription"; - + /** * A positive decimal that represents the fee percentage of the subscription invoice amount that will be transferred to * the application owner's Stripe account each billing period. */ application_fee_percent: number; - + /** * If the subscription has been canceled with the at_period_end flag set to true, cancel_at_period_end on the * subscription will be true. You can use this attribute to determine whether a subscription that has a status * of active is scheduled to be canceled at the end of the current period. */ cancel_at_period_end: boolean; - + /** * If the subscription has been canceled, the date of that cancellation. If the subscription was canceled with * cancel_at_period_end, canceled_at will still reflect the date of the initial cancellation request, not the end of the * subscription period when the subscription is automatically moved to a canceled state. */ canceled_at: number; - + created: number; - + /** * End of the current period that the subscription has been invoiced for. At the end of this period, a new invoice will be created. */ current_period_end: number; - + /** * Start of the current period that the subscription has been invoiced for */ current_period_start: number; - + customer: string; - + /** * Describes the current discount applied to this subscription, if there is one. When billing, a discount applied to a * subscription overrides a discount applied on a customer-wide basis. */ discount: coupons.IDiscount; - + /** * If the subscription has ended (either because it was canceled or because the customer was switched to a subscription * to a new plan), the date the subscription ended */ ended_at: number; - + metadata: IMetadata; - + /** * Hash describing the plan the customer is subscribed to */ plan: plans.IPlan; - + /** * The number of subscriptions for the associated plan */ quantity: number; - + /** * Date the subscription started */ start: number; - + /** * Possible values are "trialing", "active", "past_due", "canceled", or "unpaid". A subscription still in its trial period is trialing * and moves to active when the trial period is over. When payment to renew the subscription fails, the subscription becomes @@ -4084,145 +4084,145 @@ declare namespace StripeNode { * you may choose to reopen and pay their closed invoices. */ status: "trialing" | "active" | "past_due" | "canceled" | "unpaid"; - + /** * If provided, each invoice created by this subscription will apply the tax rate, increasing the amount billed to the customer. */ tax_percent: number; - + /** * If the subscription has a trial, the end of that trial. */ trial_end: number; - + /** * If the subscription has a trial, the beginning of that trial. */ trial_start: number; } - + interface ISubscriptionCustCreationOptions extends IDataOptionsWithMetadata { /** * The identifier of the plan to subscribe the customer to. */ plan: string; - + /** - * A positive decimal (with at most two decimal places) between 1 and 100. This represents the percentage of the subscription invoice - * subtotal that will be transferred to the application owner’s Stripe account. The request must be made with an OAuth key in order + * A positive decimal (with at most two decimal places) between 1 and 100. This represents the percentage of the subscription invoice + * subtotal that will be transferred to the application owner’s Stripe account. The request must be made with an OAuth key in order * to set an application fee percentage. For more information, see the application fees documentation. */ application_fee_percent?: number; - + /** - * The code of the coupon to apply to this subscription. A coupon applied to a subscription will only affect invoices created for that + * The code of the coupon to apply to this subscription. A coupon applied to a subscription will only affect invoices created for that * particular subscription. */ coupon?: string; - + source?: sources.ISourceCreationOptions; - + /** - * The quantity you'd like to apply to the subscription you're creating. For example, if your plan is £10/user/month, and your customer - * has 5 users, you could pass 5 as the quantity to have the customer charged £50 (5 x £10) monthly. If you update a subscription but - * don't change the plan ID (e.g. changing only the trial_end), the subscription will inherit the old subscription's quantity attribute - * unless you pass a new quantity parameter. If you update a subscription and change the plan ID, the new subscription will not inherit + * The quantity you'd like to apply to the subscription you're creating. For example, if your plan is £10/user/month, and your customer + * has 5 users, you could pass 5 as the quantity to have the customer charged £50 (5 x £10) monthly. If you update a subscription but + * don't change the plan ID (e.g. changing only the trial_end), the subscription will inherit the old subscription's quantity attribute + * unless you pass a new quantity parameter. If you update a subscription and change the plan ID, the new subscription will not inherit * the quantity attribute and will default to 1 unless you pass a quantity parameter. */ quantity?: number; - + /** - * A positive decimal (with at most two decimal places) between 1 and 100. This represents the percentage of the subscription invoice - * subtotal that will be calculated and added as tax to the final amount each billing period. For example, a plan which charges $10/month + * A positive decimal (with at most two decimal places) between 1 and 100. This represents the percentage of the subscription invoice + * subtotal that will be calculated and added as tax to the final amount each billing period. For example, a plan which charges $10/month * with a tax_percent of 20.0 will charge $12 per invoice. */ tax_percent?: number; - + /** - * Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. If set, trial_end - * will override the default trial period of the plan the customer is being subscribed to. The special value now can be provided to end the + * Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. If set, trial_end + * will override the default trial period of the plan the customer is being subscribed to. The special value now can be provided to end the * customer's trial immediately. */ trial_end?: number; } - + interface ISubscriptionCreationOptions extends ISubscriptionCustCreationOptions { /*** * The identifier of the customer to subscribe. */ customer: string; - } - + } + interface ISubscriptionUpdateOptions extends IDataOptionsWithMetadata { /** - * A positive decimal (with at most two decimal places) between 1 and 100. This represents the percentage of the subscription invoice - * subtotal that will be transferred to the application owner’s Stripe account. The request must be made with an OAuth key in order + * A positive decimal (with at most two decimal places) between 1 and 100. This represents the percentage of the subscription invoice + * subtotal that will be transferred to the application owner’s Stripe account. The request must be made with an OAuth key in order * to set an application fee percentage. For more information, see the application fees documentation. */ application_fee_percent?: number; - + /** - * The code of the coupon to apply to this subscription. A coupon applied to a subscription will only affect invoices created for that + * The code of the coupon to apply to this subscription. A coupon applied to a subscription will only affect invoices created for that * particular subscription. */ coupon?: string; - + /** * The identifier of the plan to update the subscription to. If omitted, the subscription will not change plans. */ plan?: string; - + /** * Flag telling us whether to prorate switching plans during a billing cycle. */ prorate?: boolean; - + /** - * If set, the proration will be calculated as though the subscription was updated at the given time. This can be used to apply exactly the - * same proration that was previewed with upcoming invoice endpoint. It can also be used to implement custom proration logic, such as + * If set, the proration will be calculated as though the subscription was updated at the given time. This can be used to apply exactly the + * same proration that was previewed with upcoming invoice endpoint. It can also be used to implement custom proration logic, such as * prorating by day instead of by second, by providing the time that you wish to use for proration calculations. */ proration_date?: number; - + /** - * The quantity you'd like to apply to the subscription you're creating. For example, if your plan is £10/user/month, and your customer - * has 5 users, you could pass 5 as the quantity to have the customer charged £50 (5 x £10) monthly. If you update a subscription but - * don't change the plan ID (e.g. changing only the trial_end), the subscription will inherit the old subscription's quantity attribute - * unless you pass a new quantity parameter. If you update a subscription and change the plan ID, the new subscription will not inherit + * The quantity you'd like to apply to the subscription you're creating. For example, if your plan is £10/user/month, and your customer + * has 5 users, you could pass 5 as the quantity to have the customer charged £50 (5 x £10) monthly. If you update a subscription but + * don't change the plan ID (e.g. changing only the trial_end), the subscription will inherit the old subscription's quantity attribute + * unless you pass a new quantity parameter. If you update a subscription and change the plan ID, the new subscription will not inherit * the quantity attribute and will default to 1 unless you pass a quantity parameter. */ quantity?: number; - + source?: sources.ISourceCreationOptions; - + /** - * A positive decimal (with at most two decimal places) between 1 and 100. This represents the percentage of the subscription invoice - * subtotal that will be calculated and added as tax to the final amount each billing period. For example, a plan which charges $10/month + * A positive decimal (with at most two decimal places) between 1 and 100. This represents the percentage of the subscription invoice + * subtotal that will be calculated and added as tax to the final amount each billing period. For example, a plan which charges $10/month * with a tax_percent of 20.0 will charge $12 per invoice. */ tax_percent?: number; - + /** - * Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. If set, trial_end - * will override the default trial period of the plan the customer is being subscribed to. The special value now can be provided to end the + * Unix timestamp representing the end of the trial period the customer will get before being charged for the first time. If set, trial_end + * will override the default trial period of the plan the customer is being subscribed to. The special value now can be provided to end the * customer's trial immediately. */ trial_end?: number; } - + interface ISubscriptionCancellationOptions extends IDataOptions { /** * A flag that if set to true will delay the cancellation of the subscription until the end of the current period. */ at_period_end?: boolean; } - + interface ISubscriptionListOptions extends IListOptionsCreated { /** * The ID of the customer whose subscriptions will be retrieved */ customer?: string; - + /** * The ID of the plan whose subscriptions will be retrieved */ @@ -4243,28 +4243,28 @@ declare namespace StripeNode { * Amount in cents/pence. */ amount: number; - + /** * Balance transaction that describes the impact of this reversal on your account balance. */ balance_transaction: string; - + /** * ID of the charge that was refunded. [Expandable] */ charge: string | charges.ICharge; - + created: number; /** * Three-letter ISO currency code representing the currency in which the charge was made. */ currency: string; - + description: string; - + /** - * A set of key/value pairs that you can attach to the object. It can be useful + * A set of key/value pairs that you can attach to the object. It can be useful * for storing additional information in a structured format. */ metadata: IMetadata; @@ -4279,63 +4279,63 @@ declare namespace StripeNode { */ receipt_number: string; } - + interface IRefundCreationOptions extends IDataOptions { /** - * A positive integer in cents/pence representing how much of this charge to - * refund. Can only refund up to the unrefunded amount remaining of the + * A positive integer in cents/pence representing how much of this charge to + * refund. Can only refund up to the unrefunded amount remaining of the * charge. - * + * * default is entire charge */ amount?: number; - + /** - * A set of key/value pairs that you can attach to a refund object. It can be - * useful for storing additional information about the refund in a structured - * format. You can unset an individual key by setting its value to null and + * A set of key/value pairs that you can attach to a refund object. It can be + * useful for storing additional information about the refund in a structured + * format. You can unset an individual key by setting its value to null and * then saving. To clear all keys, set metadata to null, then save. */ metadata?: IMetadata; - + /** - * String indicating the reason for the refund. If set, possible values are - * "duplicate", "fraudulent", and "requested_by_customer". Specifying - * "fraudulent" as the reason when you believe the charge to be fraudulent + * String indicating the reason for the refund. If set, possible values are + * "duplicate", "fraudulent", and "requested_by_customer". Specifying + * "fraudulent" as the reason when you believe the charge to be fraudulent * will help us improve our fraud detection algorithms. */ reason?: string; - + /** - * Boolean indicating whether the application fee should be refunded when - * refunding this charge. If a full charge refund is given, the full application - * fee will be refunded. Else, the application fee will be refunded with an + * Boolean indicating whether the application fee should be refunded when + * refunding this charge. If a full charge refund is given, the full application + * fee will be refunded. Else, the application fee will be refunded with an * amount proportional to the amount of the charge refunded. - * An application fee can only be refunded by the application that created the + * An application fee can only be refunded by the application that created the * charge. - * + * * Connect only, default is false. */ refund_application_fee?: boolean; - + /** - * Boolean indicating whether the transfer should be reversed when - * refunding this charge. The transfer will be reversed for the same amount + * Boolean indicating whether the transfer should be reversed when + * refunding this charge. The transfer will be reversed for the same amount * being refunded (either the entire or partial amount). * A transfer can only be reversed by the application that created the charge. - * + * * Connect only, default is false. */ reverse_transfer?: boolean; } - + interface IRefundCreationOptionsWithCharge extends IRefundCreationOptions { /** * The identifier of the charge to refund. */ charge: string; } - + interface IRefundListOptions extends IListOptions { /** * Only return refunds for the charge specified by this charge ID. @@ -4343,71 +4343,71 @@ declare namespace StripeNode { charge?: string; } } - + namespace sources { /** - * The source can either be a token, like the ones returned by our - * Stripe.js, or a object containing a user's credit card details (with - * the options shown below). You must provide a source if the - * customer does not already have a valid source attached, and you - * are subscribing the customer for a plan that is not free. Passing - * source will create a new source object, make it the customer - * default source, and delete the old customer default if one exists. - * If you want to add an additional source to use with subscriptions, - * instead use the card creation API to add the card and then the - * customer update API to set it as the default. Whenever you - * attach a card to a customer, Stripe will automatically validate the + * The source can either be a token, like the ones returned by our + * Stripe.js, or a object containing a user's credit card details (with + * the options shown below). You must provide a source if the + * customer does not already have a valid source attached, and you + * are subscribing the customer for a plan that is not free. Passing + * source will create a new source object, make it the customer + * default source, and delete the old customer default if one exists. + * If you want to add an additional source to use with subscriptions, + * instead use the card creation API to add the card and then the + * customer update API to set it as the default. Whenever you + * attach a card to a customer, Stripe will automatically validate the * card. */ type ISourceCreationOptions = string | cards.ISourceCreationOptions; - + /** - * The source can either be a token, like the ones returned by our - * Stripe.js, or a object containing a user's credit card details (with - * the options shown below). You must provide a source if the - * customer does not already have a valid source attached, and you - * are subscribing the customer for a plan that is not free. Passing - * source will create a new source object, make it the customer - * default source, and delete the old customer default if one exists. - * If you want to add an additional source to use with subscriptions, - * instead use the card creation API to add the card and then the - * customer update API to set it as the default. Whenever you - * attach a card to a customer, Stripe will automatically validate the + * The source can either be a token, like the ones returned by our + * Stripe.js, or a object containing a user's credit card details (with + * the options shown below). You must provide a source if the + * customer does not already have a valid source attached, and you + * are subscribing the customer for a plan that is not free. Passing + * source will create a new source object, make it the customer + * default source, and delete the old customer default if one exists. + * If you want to add an additional source to use with subscriptions, + * instead use the card creation API to add the card and then the + * customer update API to set it as the default. Whenever you + * attach a card to a customer, Stripe will automatically validate the * card. */ type ISourceCreationOptionsExtended = string | cards.ISourceCreationOptionsExtended; } - + namespace countrySpecs { interface ICountrySpec extends IResourceObject { /** * Value is "country_spec" */ object: "country_spec"; - + /** * The default currency for this country. This applies to both payment methods and bank accounts. */ default_currency: string; - + /** * Currencies that can be accepted in the specific country (for transfers). */ supported_bank_account_currencies: {}; - + /** * Currencies that can be accepted in the specified country (for payments). */ supported_payment_currencies: Array; - + /** - * Payment methods available in the specified country. You will need to enable bitcoin and ACH payments on your account for those methods to + * Payment methods available in the specified country. You will need to enable bitcoin and ACH payments on your account for those methods to * appear in this list. The stripe payment method refers to charging through your platform. */ supported_payment_methods: Array; - + /** - * Lists the types of verification data needed to keep an account open. Includes 'minimum' fields, which every account must eventually + * Lists the types of verification data needed to keep an account open. Includes 'minimum' fields, which every account must eventually * provide, as well as a 'additional' fields, which are only required for some merchants. */ verification_fields: { @@ -4422,11 +4422,11 @@ declare namespace StripeNode { } } } - + class StripeResource { constructor(stripe: Stripe, urlData: any); } - + namespace resources { class Accounts extends StripeResource { /** @@ -4434,7 +4434,7 @@ declare namespace StripeNode { */ create(data: accounts.IAccountCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: accounts.IAccountCreationOptions, response?: IResponseFn): Promise; - + /** * Retrieves the details of the account. */ @@ -4444,38 +4444,38 @@ declare namespace StripeNode { retrieve(id: string, response?: IResponseFn): Promise; retrieve(options: HeaderOptions, response?: IResponseFn): Promise; retrieve(response?: IResponseFn): Promise; - + /** * Updates an account by setting the values of the parameters passed. Any parameters not provided will be left unchanged. - * - * You may only update accounts that you manage. To update your own account, you can currently only do so via the dashboard. + * + * You may only update accounts that you manage. To update your own account, you can currently only do so via the dashboard. * For more information on updating managed accounts, see our guide. */ update(id: string, data: accounts.IAccountUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; update(id: string, data: accounts.IAccountUpdateOptions, response?: IResponseFn): Promise; - + /** * With Connect, you may delete Stripe accounts you manage. - * - * Managed accounts created using test-mode keys can be deleted at any time. Managed accounts created using live-mode keys may only be + * + * Managed accounts created using test-mode keys can be deleted at any time. Managed accounts created using live-mode keys may only be * deleted once all balances are zero. - * + * * If you are looking to close your own account, use the data tab in your account settings instead. */ del(id: string, options: HeaderOptions, response?: IResponseFn): Promise; del(id: string, response?: IResponseFn): Promise; del(options: HeaderOptions, response?: IResponseFn): Promise; del(response?: IResponseFn): Promise; - + /** * With Connect, you may flag managed accounts as suspicious. - * - * Managed accounts created using test-mode keys can be rejected at any time. Managed accounts created using live-mode keys may only be + * + * Managed accounts created using test-mode keys can be rejected at any time. Managed accounts created using live-mode keys may only be * rejected once all balances are zero. */ reject(id: string, data: accounts.IRejectReason, options: HeaderOptions, response?: IResponseFn): Promise; reject(id: string, data: accounts.IRejectReason, response?: IResponseFn): Promise; - + /** * Returns a list of accounts connected to your platform via Connect. If you’re not a platform, the list will be empty. */ @@ -4483,103 +4483,103 @@ declare namespace StripeNode { list(data: IListOptions, response?: IResponseFn>): Promise>; list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; - + /** * When you create a new bank account or credit card, you must specify a managed account to create it on. - * - * If the bank account's owner has no other external account in the bank account's currency, the new bank account will become the - * default for that currency. However, if the owner already has a bank account for that currency, the new account will only become + * + * If the bank account's owner has no other external account in the bank account's currency, the new bank account will become the + * default for that currency. However, if the owner already has a bank account for that currency, the new account will only become * the default if the default_for_currency parameter is set to true. - * - * If the account has no default destination card, then the new card will become the default. However, if the owner already has a - * default then it will not change. To change the default, you should set default_for_currency to true when creating a card for a + * + * If the account has no default destination card, then the new card will become the default. However, if the owner already has a + * default then it will not change. To change the default, you should set default_for_currency to true when creating a card for a * managed account. */ createExternalAccount(accId: string, data: accounts.IExternalAccountCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; createExternalAccount(accId: string, data: accounts.IExternalAccountCreationOptions, response?: IResponseFn): Promise; - + /** - * By default, you can see the 10 most recent bank accounts stored on a managed account directly on the object, but you can also + * By default, you can see the 10 most recent bank accounts stored on a managed account directly on the object, but you can also * retrieve details about a specific bank account stored on the Stripe account. */ retrieveExternalAccount(accId: string, bankAccId: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieveExternalAccount(accId: string, bankAccId: string, response?: IResponseFn): Promise; /** - * You can always see the 10 most recent cards directly on a managed account; this method lets you retrieve details about a specific + * You can always see the 10 most recent cards directly on a managed account; this method lets you retrieve details about a specific * card stored on the account. */ retrieveCard(accId: string, cardId: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieveCard(accId: string, cardId: string, response?: IResponseFn): Promise; - + /** - * Updates the metadata of a bank account belonging to a managed account, and optionally sets it as the default for its currency. + * Updates the metadata of a bank account belonging to a managed account, and optionally sets it as the default for its currency. * Other bank account details are not editable by design. */ updateExternalAccount(accId: string, bankAccId: string, data: accounts.IExternalAccountUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; updateExternalAccount(accId: string, bankAccId: string, data: accounts.IExternalAccountUpdateOptions, response?: IResponseFn): Promise; /** - * If you need to update only some card details, like the billing address or expiration date, you can do so without having to re-enter the - * full card details. Stripe also works directly with card networks so that your customers can continue using your service without + * If you need to update only some card details, like the billing address or expiration date, you can do so without having to re-enter the + * full card details. Stripe also works directly with card networks so that your customers can continue using your service without * interruption. - * + * * When you update a card, Stripe will automatically validate the card. */ updateExternalAccount(accId: string, cardId: string, data: cards.ICardUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; updateExternalAccount(accId: string, cardId: string, data: cards.ICardUpdateOptions, response?: IResponseFn): Promise; - + /** - * You can delete destination bank accounts and cards from a managed account. If a bank account is the default external account for its currency - * or card's default_for_currency property is true, it can only be deleted if it is the only external account for that currency, and the - * currency is not the Stripe account's default currency. Otherwise, you must set another external account to be the default for the currency + * You can delete destination bank accounts and cards from a managed account. If a bank account is the default external account for its currency + * or card's default_for_currency property is true, it can only be deleted if it is the only external account for that currency, and the + * currency is not the Stripe account's default currency. Otherwise, you must set another external account to be the default for the currency * before deleting it. */ deleteExternalAccount(accId: string, id: string, options: HeaderOptions, response?: IResponseFn): Promise; deleteExternalAccount(accId: string, id: string, response?: IResponseFn): Promise; - + /** - * You can see a list of the bank accounts belonging to a managed account. Note that the 10 most recent external accounts are always - * available by default on the corresponding Stripe object. If you need more than those 10, you can use this API method and the limit + * You can see a list of the bank accounts belonging to a managed account. Note that the 10 most recent external accounts are always + * available by default on the corresponding Stripe object. If you need more than those 10, you can use this API method and the limit * and starting_after parameters to page through additional bank accounts. */ listExternalAccounts(accId: string, data: accounts.IBankAccountListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; listExternalAccounts(accId: string, data: accounts.IBankAccountListOptions, response?: IResponseFn>): Promise>; - + /** - * You can see a list of the cards belonging to a managed account. Note that the 10 most recent external accounts are available on the - * account object. If you need more than those 10, you can use this API method and the limit and starting_after parameters to page + * You can see a list of the cards belonging to a managed account. Note that the 10 most recent external accounts are available on the + * account object. If you need more than those 10, you can use this API method and the limit and starting_after parameters to page * through additional cards. */ listExternalAccounts(accId: string, data: accounts.ICardListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; listExternalAccounts(accId: string, data: accounts.ICardListOptions, response?: IResponseFn>): Promise>; } - + class ApplicationFees extends StripeResource { /** - * Retrieves the details of an application fee that your account has collected. The same information is returned when refunding the + * Retrieves the details of an application fee that your account has collected. The same information is returned when refunding the * application fee. */ retrieve(id: string, data: IDataOptions, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(id: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(id: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(id: string, response?: IResponseFn): Promise; - + /** - * Returns a list of application fees you’ve previously collected. The application fees are returned in sorted order, with the most + * Returns a list of application fees you’ve previously collected. The application fees are returned in sorted order, with the most * recent fees appearing first. */ list(data: applicationFees.IApplicationFeeListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; list(data: applicationFees.IApplicationFeeListOptions, response?: IResponseFn>): Promise>; list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; - + /** - * Refunds an application fee that has previously been collected but not yet refunded. Funds will be refunded to the Stripe account that + * Refunds an application fee that has previously been collected but not yet refunded. Funds will be refunded to the Stripe account that * the fee was originally collected from. - * + * * You can optionally refund only part of an application fee. You can do so as many times as you wish until the entire fee has been refunded. - * - * Once entirely refunded, an application fee can't be refunded again. This method will throw an error when called on an already-refunded + * + * Once entirely refunded, an application fee can't be refunded again. This method will throw an error when called on an already-refunded * application fee, or when trying to refund more money than is left on an application fee. */ refund(feeId: string, data: applicationFees.IApplicationFeeRefundCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; @@ -4588,38 +4588,38 @@ declare namespace StripeNode { refund(feeId: string, response?: IResponseFn): Promise; /** - * Refunds an application fee that has previously been collected but not yet refunded. Funds will be refunded to the Stripe account that + * Refunds an application fee that has previously been collected but not yet refunded. Funds will be refunded to the Stripe account that * the fee was originally collected from. - * + * * You can optionally refund only part of an application fee. You can do so as many times as you wish until the entire fee has been refunded. - * - * Once entirely refunded, an application fee can't be refunded again. This method will throw an error when called on an already-refunded + * + * Once entirely refunded, an application fee can't be refunded again. This method will throw an error when called on an already-refunded * application fee, or when trying to refund more money than is left on an application fee. */ createRefund(feeId: string, data: applicationFees.IApplicationFeeRefundCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; createRefund(feeId: string, data: applicationFees.IApplicationFeeRefundCreationOptions, response?: IResponseFn): Promise; createRefund(feeId: string, response?: IResponseFn): Promise; createRefund(feeId: string, options: HeaderOptions, response?: IResponseFn): Promise; - + /** - * By default, you can see the 10 most recent refunds stored directly on the application fee object, but you can also retrieve details + * By default, you can see the 10 most recent refunds stored directly on the application fee object, but you can also retrieve details * about a specific refund stored on the application fee. */ retreiveRefund(feeId: string, refundId: string, options: HeaderOptions, response?: IResponseFn): Promise; retreiveRefund(feeId: string, refundId: string, response?: IResponseFn): Promise; - + /** - * Updates the specified application fee refund by setting the values of the parameters passed. Any parameters not provided will be left + * Updates the specified application fee refund by setting the values of the parameters passed. Any parameters not provided will be left * unchanged. - * + * * This request only accepts metadata as an argument. */ updateRefund(feeId: string, refundId: string, data: { metadata?: IMetadata }, options: HeaderOptions, response?: IResponseFn): Promise; updateRefund(feeId: string, refundId: string, data: { metadata?: IMetadata }, response?: IResponseFn): Promise; - + /** - * You can see a list of the refunds belonging to a specific application fee. Note that the 10 most recent refunds are always available - * by default on the application fee object. If you need more than those 10, you can use this API method and the limit and starting_after + * You can see a list of the refunds belonging to a specific application fee. Note that the 10 most recent refunds are always available + * by default on the application fee object. If you need more than those 10, you can use this API method and the limit and starting_after * parameters to page through additional refunds. */ listRefunds(feeId: string, data: IListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; @@ -4627,44 +4627,44 @@ declare namespace StripeNode { listRefunds(feeId: string, options: HeaderOptions, response?: IResponseFn>): Promise>; listRefunds(feeId: string, response?: IResponseFn>): Promise>; } - + class ApplicationFeeRefunds extends StripeResource { /** - * Refunds an application fee that has previously been collected but not yet refunded. Funds will be refunded to the Stripe account that + * Refunds an application fee that has previously been collected but not yet refunded. Funds will be refunded to the Stripe account that * the fee was originally collected from. - * + * * You can optionally refund only part of an application fee. You can do so as many times as you wish until the entire fee has been refunded. - * - * Once entirely refunded, an application fee can't be refunded again. This method will throw an error when called on an already-refunded + * + * Once entirely refunded, an application fee can't be refunded again. This method will throw an error when called on an already-refunded * application fee, or when trying to refund more money than is left on an application fee. */ create(data: applicationFees.IApplicationFeeRefundCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: applicationFees.IApplicationFeeRefundCreationOptions, response?: IResponseFn): Promise; create(options: HeaderOptions, response?: IResponseFn): Promise; create(response?: IResponseFn): Promise; - + /** - * By default, you can see the 10 most recent refunds stored directly on the application fee object, but you can also retrieve details + * By default, you can see the 10 most recent refunds stored directly on the application fee object, but you can also retrieve details * about a specific refund stored on the application fee. */ retrieve(refundId: string, data: IDataOptions, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(refundId: string, options: IDataOptions, response?: IResponseFn): Promise; retrieve(refundId: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(refundId: string, response?: IResponseFn): Promise; - - + + /** - * Updates the specified application fee refund by setting the values of the parameters passed. Any parameters not provided will be left + * Updates the specified application fee refund by setting the values of the parameters passed. Any parameters not provided will be left * unchanged. - * + * * This request only accepts metadata as an argument. */ update(refundId: string, data: { metadata?: IMetadata }, options: HeaderOptions, response?: IResponseFn): Promise; update(refundId: string, data: { metadata?: IMetadata }, response?: IResponseFn): Promise; - + /** - * You can see a list of the refunds belonging to a specific application fee. Note that the 10 most recent refunds are always available - * by default on the application fee object. If you need more than those 10, you can use this API method and the limit and starting_after + * You can see a list of the refunds belonging to a specific application fee. Note that the 10 most recent refunds are always available + * by default on the application fee object. If you need more than those 10, you can use this API method and the limit and starting_after * parameters to page through additional refunds. */ list(data: IListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; @@ -4672,28 +4672,28 @@ declare namespace StripeNode { list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; } - + class Balance extends StripeResource { retrieve(options: HeaderOptions, response?: IResponseFn): Promise; retrieve(response?: IResponseFn): Promise; - + retrieveTransaction(id: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieveTransaction(id: string, response?: IResponseFn): Promise; - + listTransactions(data: balance.IBalanceListOptions, options: HeaderOptions, response?: IResponseFn): Promise>; listTransactions(data: balance.IBalanceListOptions, response?: IResponseFn): Promise>; listTransactions(options: HeaderOptions, response?: IResponseFn): Promise>; listTransactions(response?: IResponseFn): Promise>; } - + class BitcoinReceivers extends StripeResource { /** - * Creates a Bitcoin receiver object that can be used to accept bitcoin payments from your customer. The receiver exposes a Bitcoin address + * Creates a Bitcoin receiver object that can be used to accept bitcoin payments from your customer. The receiver exposes a Bitcoin address * and is created with a bitcoin to USD exchange rate that is valid for 10 minutes. */ create(data: bitcoinReceivers.IBitcoinReceiverCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: bitcoinReceivers.IBitcoinReceiverCreationOptions, response?: IResponseFn): Promise; - + /** * Retrieves the Bitcoin receiver with the given ID. */ @@ -4701,16 +4701,16 @@ declare namespace StripeNode { retrieve(id: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(id: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(id: string, response?: IResponseFn): Promise; - - + + /** * Returns a list of your receivers. Receivers are returned sorted by creation date, with the most recently created receivers appearing first. */ list(data: bitcoinReceivers.IBitcoinReceiverListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; list(data: bitcoinReceivers.IBitcoinReceiverListOptions, response?: IResponseFn>): Promise>; - + //update(id: string): void; // This does seem to be a method in the library (https://github.com/stripe/stripe-node/blob/master/lib/resources/BitcoinReceivers.js#L12), but isn't in the API documentation. - + setMetadata(): void; //TODO: Implement placeholder method getMetadata(): void; //TODO: Implement placeholder method } @@ -4744,8 +4744,8 @@ declare namespace StripeNode { retrieve(id: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(id: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(id: string, response?: IResponseFn): Promise; - - + + /** * Updates the specified charge by setting the values of the parameters passed. Any parameters not provided will be left unchanged. * This request accepts only the description, metadata, receipt_emailand fraud_details as arguments. @@ -4779,7 +4779,7 @@ declare namespace StripeNode { list(data: charges.IChargeListOptions, response?: IResponseFn>): Promise>; list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; - + /** * When you create a new refund, you must specify a charge to create it on. * Creating a new refund will refund a charge that has previously been created but not yet refunded. Funds will be refunded to the credit or debit card that was originally charged. The fees you were originally charged are also refunded. @@ -4790,7 +4790,7 @@ declare namespace StripeNode { refund(chargeId: string, data: refunds.IRefundCreationOptions, response?: IResponseFn): Promise; refund(chargeId: string, options: HeaderOptions, response?: IResponseFn): Promise; refund(chargeId: string, response?: IResponseFn): Promise; - + /** * When you create a new refund, you must specify a charge to create it on. Creating a new refund will refund a charge that has previously * been created but not yet refunded. Funds will be refunded to the credit or debit card that was originally charged. The fees you were @@ -4804,7 +4804,7 @@ declare namespace StripeNode { * @param id The identifier of the charge to be refunded. * @param data Options for specifying reasons and refund amount * @param response The refund. - * + * * @deprecated According to source code (https://github.com/stripe/stripe-node/blob/master/lib/resources/Charges.js#L43) */ createRefund(id: string, data: refunds.IRefundCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; @@ -4849,7 +4849,7 @@ declare namespace StripeNode { listRefunds(chargeId: string, data: IListOptions, response?: IResponseFn>): Promise>; listRefunds(chargeId: string, options: HeaderOptions, response?: IResponseFn>): Promise>; listRefunds(chargeId: string, response?: IResponseFn>): Promise>; - + markAsSafe(chargeId: string, response?: IResponseFn): Promise; markAsFraudulent(chargeId: string, response?: IResponseFn): Promise; } @@ -4857,15 +4857,15 @@ declare namespace StripeNode { class ChargeRefunds extends StripeResource { /** * When you create a new refund, you must specify a charge to create it on. - * - * Creating a new refund will refund a charge that has previously been created but not yet refunded. - * Funds will be refunded to the credit or debit card that was originally charged. + * + * Creating a new refund will refund a charge that has previously been created but not yet refunded. + * Funds will be refunded to the credit or debit card that was originally charged. * The fees you were originally charged are also refunded. - * - * You can optionally refund only part of a charge. + * + * You can optionally refund only part of a charge. * You can do so as many times as you wish until the entire charge has been refunded. - * - * Once entirely refunded, a charge can't be refunded again. + * + * Once entirely refunded, a charge can't be refunded again. * This method will throw an error when called on an already-refunded charge, or when trying to refund more money than is left on a charge. */ create(data: refunds.IRefundCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; @@ -4885,15 +4885,15 @@ declare namespace StripeNode { /** * Updates the specified refund by setting the values of the parameters passed. * Any parameters not provided will be left unchanged. - * + * * This request only accepts metadata as an argument. */ update(id: string, data: IDataOptionsWithMetadata, options: HeaderOptions, response?: IResponseFn): Promise; update(id: string, data: IDataOptionsWithMetadata, response?: IResponseFn): Promise; /** - * Returns a list of all refunds you’ve previously created. The refunds are returned in sorted order, - * with the most recent refunds appearing first. + * Returns a list of all refunds you’ve previously created. The refunds are returned in sorted order, + * with the most recent refunds appearing first. * For convenience, the 10 most recent refunds are always available by default on the charge object. */ list(data: refunds.IRefundListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; @@ -4916,7 +4916,7 @@ declare namespace StripeNode { */ create(data: coupons.ICouponCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: coupons.ICouponCreationOptions, response?: IResponseFn): Promise; - + /** * Retrieves the coupon with the given ID. * @@ -4928,8 +4928,8 @@ declare namespace StripeNode { retrieve(id: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(id: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(id: string, response?: IResponseFn): Promise; - - + + /** * Updates the metadata of a coupon. Other coupon details (currency, duration, amount_off) are, by design, not editable. * @@ -4941,7 +4941,7 @@ declare namespace StripeNode { */ update(id: string, data: IDataOptionsWithMetadata, options: HeaderOptions, response?: IResponseFn): Promise; update(id: string, data: IDataOptionsWithMetadata, response?: IResponseFn): Promise; - + /** * You can delete coupons via the coupon management page of the Stripe dashboard. However, deleting a coupon does not affect any * customers who have already applied the coupon; it means that new customers can't redeem the coupon. You can also delete coupons @@ -4954,7 +4954,7 @@ declare namespace StripeNode { */ del(id: string, options: HeaderOptions, response?: IResponseFn): Promise; del(id: string, response?: IResponseFn): Promise; - + /** * Returns a list of your coupons. * @@ -4985,7 +4985,7 @@ declare namespace StripeNode { create(data: { card?: sources.ISourceCreationOptionsExtended; }, response?: IResponseFn): Promise; - + /** * You can see a list of the cards belonging to a customer or recipient. Note that the 10 most recent * cards are always available by default on the customer or recipient object. If you need more than @@ -5001,7 +5001,7 @@ declare namespace StripeNode { list(data: IListOptions, response?: IResponseFn>): Promise>; list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; - + /** * If you need to update only some card details, like the billing address or expiration date, you can do so without having to re-enter the * full card details. Stripe also works directly with card networks so that your customers can continue using your service without @@ -5013,7 +5013,7 @@ declare namespace StripeNode { */ update(cardId: string, data: cards.ICardUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; update(cardId: string, data: cards.ICardUpdateOptions, response?: IResponseFn): Promise; - + /** * By default, you can see the 10 most recent cards stored on a customer or recipient directly on the customer or recipient object, but * you can also retrieve details about a specific card stored on the customer or recipient. @@ -5024,7 +5024,7 @@ declare namespace StripeNode { */ retrieve(cardId: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(cardId: string, response?: IResponseFn): Promise; - + /** * You can delete cards from a customer or recipient. If you delete a card that is currently the * default source on a customer, then the most recently added source will become the new default. @@ -5042,7 +5042,7 @@ declare namespace StripeNode { del(cardId: string, options: HeaderOptions, response?: IResponseFn): Promise; del(cardId: string, response?: IResponseFn): Promise; } - + class Customers extends StripeResource { /** * Creates a new customer object. @@ -5057,7 +5057,7 @@ declare namespace StripeNode { */ create(data: customers.ICustomerCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: customers.ICustomerCreationOptions, response?: IResponseFn): Promise; - + /** * Returns a list of your customers. The customers are returned sorted by creation date, with the most recently created customers * appearing first. @@ -5073,7 +5073,7 @@ declare namespace StripeNode { list(data: IListOptionsCreated, response?: IResponseFn>): Promise>; list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; - + /** * Updates the specified customer by setting the values of the parameters passed. Any parameters not provided will be left unchanged. * For example, if you pass the card parameter, that becomes the customer's active card to be used for all charges in the future. @@ -5085,7 +5085,7 @@ declare namespace StripeNode { * * @returns Returns the customer object if the update succeeded. Throws an error if update parameters are invalid (e.g. specifying * an invalid coupon or an invalid card). - * + * * @param id The identifier of the customer to be retrieved. */ update(id: string, data: customers.ICustomerUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; @@ -5104,7 +5104,7 @@ declare namespace StripeNode { retrieve(id: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(id: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(id: string, response?: IResponseFn): Promise; - + /** * Permanently deletes a customer. It cannot be undone. Also immediately cancels any active subscriptions on the customer. * @@ -5116,9 +5116,9 @@ declare namespace StripeNode { */ del(id: string, options: HeaderOptions, response?: IResponseFn): Promise; del(id: string, response?: IResponseFn): Promise; - - - + + + /** * When you create a new credit card, you must specify a customer or recipient to create it on. If the card's owner has no default card, * then the new card will become the default. However, if the owner already has a default then it will not change. To change the default, @@ -5127,7 +5127,7 @@ declare namespace StripeNode { * @returns Returns the card object. * * @param customerId The customer ID to which to add the card. - * + * * @deprecated */ createCard(customerId: string, data: { @@ -5136,7 +5136,7 @@ declare namespace StripeNode { createCard(customerId: string, data: { card?: sources.ISourceCreationOptionsExtended; }, response?: IResponseFn): Promise; - + /** * By default, you can see the 10 most recent cards stored on a customer or recipient directly on the customer or recipient object, but * you can also retrieve details about a specific card stored on the customer or recipient. @@ -5148,7 +5148,7 @@ declare namespace StripeNode { */ retrieveCard(customerId: string, cardId: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieveCard(customerId: string, cardId: string, response?: IResponseFn): Promise; - + /** * If you need to update only some card details, like the billing address or expiration date, you can do so without having to re-enter the * full card details. Stripe also works directly with card networks so that your customers can continue using your service without @@ -5161,7 +5161,7 @@ declare namespace StripeNode { */ updateCard(customerId: string, cardId: string, data: cards.ICardUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; updateCard(customerId: string, cardId: string, data: cards.ICardUpdateOptions, response?: IResponseFn): Promise; - + /** * You can delete cards from a customer or recipient. If you delete a card that is currently the * default source on a customer, then the most recently added source will become the new default. @@ -5179,7 +5179,7 @@ declare namespace StripeNode { */ deleteCard(customerId: string, cardId: string, options: HeaderOptions, response?: IResponseFn): Promise; deleteCard(customerId: string, cardId: string, response?: IResponseFn): Promise; - + /** * You can see a list of the cards belonging to a customer or recipient. Note that the 10 most recent * cards are always available by default on the customer or recipient object. If you need more than @@ -5197,13 +5197,13 @@ declare namespace StripeNode { listCards(customerId: string, data: IListOptions, response?: IResponseFn>): Promise>; listCards(customerId: string, options: HeaderOptions, response?: IResponseFn>): Promise>; listCards(customerId: string, response?: IResponseFn>): Promise>; - - + + /** - * When adding a card to a customer, the parameter name is source. When - * adding to an account, the parameter name is external_account. The - * value can either be a token, like the ones returned by our Stripe.js, or a - * dictionary containing a user's credit card details. + * When adding a card to a customer, the parameter name is source. When + * adding to an account, the parameter name is external_account. The + * value can either be a token, like the ones returned by our Stripe.js, or a + * dictionary containing a user's credit card details. * Stripe will automatically validate the card. * * @returns Returns the card object. @@ -5213,10 +5213,10 @@ declare namespace StripeNode { createSource(customerId: string, data: customers.ICustomerCardSourceCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; createSource(customerId: string, data: customers.ICustomerCardSourceCreationOptions, response?: IResponseFn): Promise; /** - * When adding a card to a customer, the parameter name is source. When - * adding to an account, the parameter name is external_account. The - * value can either be a token, like the ones returned by our Stripe.js, or a - * dictionary containing a user’s credit card details. + * When adding a card to a customer, the parameter name is source. When + * adding to an account, the parameter name is external_account. The + * value can either be a token, like the ones returned by our Stripe.js, or a + * dictionary containing a user’s credit card details. * Stripe will automatically validate the card. * * @returns Returns the card or bank account object. @@ -5225,7 +5225,7 @@ declare namespace StripeNode { */ createSource(customerId: string, data: customers.ICustomerSourceCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; createSource(customerId: string, data: customers.ICustomerSourceCreationOptions, response?: IResponseFn): Promise; - + /** * You can see a list of the cards belonging to a customer or recipient. Note that the 10 most recent * cards are always available by default on the customer or recipient object. If you need more than @@ -5256,7 +5256,7 @@ declare namespace StripeNode { */ listSource(customerId: string, data: customers.IBankAccountSourceListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; listSource(customerId: string, data: customers.IBankAccountSourceListOptions, response?: IResponseFn>): Promise>; - + /** * By default, you can see the 10 most recent cards/bank accounts stored on a customer or recipient directly on the customer or recipient object, but * you can also retrieve details about a specific card/bank account stored on the customer or recipient. @@ -5268,7 +5268,7 @@ declare namespace StripeNode { */ retrieveSource(customerId: string, sourceId: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieveSource(customerId: string, sourceId: string, response?: IResponseFn): Promise; - + /** * If you need to update only some card details, like the billing address or expiration date, you can do so without having to re-enter the * full card details. Stripe also works directly with card networks so that your customers can continue using your service without @@ -5281,9 +5281,9 @@ declare namespace StripeNode { */ updateSource(customerId: string, sourceId: string, data: cards.ICardUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; updateSource(customerId: string, sourceId: string, data: cards.ICardUpdateOptions, response?: IResponseFn): Promise; - + /** - * Updates the metadata, account_holder_name, and account_holder_type of a bank account belonging to a Customer. Other bank account details + * Updates the metadata, account_holder_name, and account_holder_type of a bank account belonging to a Customer. Other bank account details * are not editable by design. * * @returns Returns the bank account object. @@ -5293,7 +5293,7 @@ declare namespace StripeNode { */ updateSource(customerId: string, sourceId: string, data: bankAccounts.IBankAccountUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; updateSource(customerId: string, sourceId: string, data: bankAccounts.IBankAccountUpdateOptions, response?: IResponseFn): Promise; - + /** * You can delete cards or bank accounts from a customer or recipient. If you delete a card or bank account that is currently the * default source on a customer, then the most recently added source will become the new default. @@ -5315,8 +5315,8 @@ declare namespace StripeNode { verifySource(customerId: string, sourceId: string, options: HeaderOptions): Promise<{}>; //TODO: This still needs properly implementing. verifySource(customerId: string, sourceId: string): Promise<{}>; //TODO: This still needs properly implementing. - - + + /** * Creates a new subscription on an existing customer. * @@ -5329,7 +5329,7 @@ declare namespace StripeNode { */ createSubscription(customerId: string, data: subscriptions.ISubscriptionCustCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; createSubscription(customerId: string, data: subscriptions.ISubscriptionCustCreationOptions, response?: IResponseFn): Promise; - + /** * By default, you can see the 10 most recent active subscriptions stored on a customer directly on the customer * object, but you can also retrieve details about a specific active subscription for a customer. @@ -5341,7 +5341,7 @@ declare namespace StripeNode { */ retrieveSubscription(customerId: string, subscriptionId: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieveSubscription(customerId: string, subscriptionId: string, response?: IResponseFn): Promise; - + /** * Updates an existing subscription on a customer to match the specified parameters. When changing plans or quantities, * we will optionally prorate the price we charge next month to make up for any price changes. @@ -5369,7 +5369,7 @@ declare namespace StripeNode { */ updateSubscription(customerId: string, subscriptionId: string, data: subscriptions.ISubscriptionUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; updateSubscription(customerId: string, subscriptionId: string, data: subscriptions.ISubscriptionUpdateOptions, response?: IResponseFn): Promise; - + /** * Cancels a customer's subscription. If you set the at_period_end parameter to true, the subscription will remain active until * the end of the period, at which point it will be canceled and not renewed. By default, the subscription is terminated @@ -5392,7 +5392,7 @@ declare namespace StripeNode { cancelSubscription(customerId: string, subscriptionId: string, data: subscriptions.ISubscriptionCancellationOptions, options: HeaderOptions, response?: IResponseFn): Promise; cancelSubscription(customerId: string, subscriptionId: string, data: subscriptions.ISubscriptionCancellationOptions, response?: IResponseFn): Promise; cancelSubscription(customerId: string, subscriptionId: string, response?: IResponseFn): Promise; - + /** * You can see a list of the customer's active subscriptions. Note that the 10 most recent active subscriptions are always available * by default on the customer object. If you need more than those 10, you can use the limit and starting_after parameters to page @@ -5408,8 +5408,8 @@ declare namespace StripeNode { listSubscriptions(customerId: string, data: IListOptions, response?: IResponseFn>): Promise>; listSubscriptions(customerId: string, options: HeaderOptions, response?: IResponseFn>): Promise>; listSubscriptions(customerId: string, response?: IResponseFn>): Promise>; - - + + /** * Removes the currently applied discount on a customer. * @@ -5420,7 +5420,7 @@ declare namespace StripeNode { */ deleteDiscount(customerId: string, options: HeaderOptions, response?: IResponseFn): Promise;; deleteDiscount(customerId: string, response?: IResponseFn): Promise;; - + /** * Removes the currently applied discount on a subscription. * @@ -5445,7 +5445,7 @@ declare namespace StripeNode { */ retrieve(subscriptionId: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(subscriptionId: string, response?: IResponseFn): Promise; - + /** * Updates an existing subscription on a customer to match the specified parameters. When changing plans or quantities, * we will optionally prorate the price we charge next month to make up for any price changes. @@ -5472,7 +5472,7 @@ declare namespace StripeNode { */ update(subscriptionId: string, data: subscriptions.ISubscriptionUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; update(subscriptionId: string, data: subscriptions.ISubscriptionUpdateOptions, response?: IResponseFn): Promise; - + /** * Cancels a customer's subscription. If you set the at_period_end parameter to true, the subscription will remain active until * the end of the period, at which point it will be canceled and not renewed. By default, the subscription is terminated @@ -5495,7 +5495,7 @@ declare namespace StripeNode { del(subscriptionId: string, data: subscriptions.ISubscriptionCancellationOptions, response?: IResponseFn): Promise; del(subscriptionId: string, options: HeaderOptions, response?: IResponseFn): Promise; del(subscriptionId: string, response?: IResponseFn): Promise; - + /** * You can see a list of the customer's active subscriptions. Note that the 10 most recent active subscriptions are always available * by default on the customer object. If you need more than those 10, you can use the limit and starting_after parameters to page @@ -5510,7 +5510,7 @@ declare namespace StripeNode { list(data: subscriptions.ISubscriptionListOptions, response?: IResponseFn>): Promise>; list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; - + /** * Removes the currently applied discount on a subscription. * @@ -5522,7 +5522,7 @@ declare namespace StripeNode { deleteDiscount(subscriptionId: string, options: HeaderOptions, response?: IResponseFn): Promise;; deleteDiscount(subscriptionId: string, response?: IResponseFn): Promise;; } - + class Subscriptions extends SubscriptionsBase { /** * Creates a new subscription on an existing customer. @@ -5549,7 +5549,7 @@ declare namespace StripeNode { create(data: subscriptions.ISubscriptionCustCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: subscriptions.ISubscriptionCustCreationOptions, response?: IResponseFn): Promise; } - + class Disputes extends StripeResource { /** * Retrieves the dispute with the given ID. @@ -5558,8 +5558,8 @@ declare namespace StripeNode { retrieve(disputeId: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(disputeId: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(disputeId: string, response?: IResponseFn): Promise; - - + + /** * When you get a dispute, contacting your customer is always the best first step. If that doesn't work, you can submit evidence in * order to help us resolve the dispute in your favor. You can do this in your dashboard, but if you prefer, you can use the API to @@ -5571,18 +5571,18 @@ declare namespace StripeNode { */ update(disputeId: string, data: disputes.IDisputeUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; update(disputeId: string, data: disputes.IDisputeUpdateOptions, response?: IResponseFn): Promise; - + /** - * Closing the dispute for a charge indicates that you do not have any evidence to submit and are + * Closing the dispute for a charge indicates that you do not have any evidence to submit and are * essentially ‘dismissing’ the dispute, acknowledging it as lost - * - * The status of the dispute will change from needs_response to lost. - * + * + * The status of the dispute will change from needs_response to lost. + * * *Closing a dispute is irreversible!* */ close(disputeId: string, options: HeaderOptions, response?: IResponseFn): Promise; close(disputeId: string, response?: IResponseFn): Promise; - + /** * Returns a list of your disputes. */ @@ -5590,22 +5590,22 @@ declare namespace StripeNode { list(data: IListOptionsCreated, response?: IResponseFn>): Promise>; list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; - + setMetadata(): void; //TODO: Implement placeholder method getMetadata(): void; //TODO: Implement placeholder method } - + class Events extends StripeResource { /** - * Retrieves the details of an event. Supply the unique identifier of the event, which you might have + * Retrieves the details of an event. Supply the unique identifier of the event, which you might have * received in a webhook. */ retrieve(id: string, data: IDataOptions, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(id: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(id: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(id: string, response?: IResponseFn): Promise; - - + + /** * List events, going back up to 30 days. */ @@ -5617,25 +5617,25 @@ declare namespace StripeNode { class FileUploads extends StripeResource { /** - * To upload a file to Stripe, you’ll need to send a request of type multipart/form-data. + * To upload a file to Stripe, you’ll need to send a request of type multipart/form-data. * The request should contain the file you would like to upload, as well as the parameters for creating a file. - * + * * All of Stripe’s officially supported API libraries should have support for sending multipart/form-data. */ create(data: fileUploads.IFileUploadCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: fileUploads.IFileUploadCreationOptions, response?: IResponseFn): Promise; - + /** - * Retrieves the details of an existing file object. + * Retrieves the details of an existing file object. * Supply the unique file upload ID from a file creation request, and Stripe will return the corresponding transfer information. */ retrieve(id: string, data: IDataOptions, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(id: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(id: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(id: string, response?: IResponseFn): Promise; - + /** - * Returns a list of the files that you have uploaded to Stripe. + * Returns a list of the files that you have uploaded to Stripe. * The file uploads are returned sorted by creation date, with the most recently created file uploads appearing first. */ list(data: fileUploads.IFileUploadListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; @@ -5658,7 +5658,7 @@ declare namespace StripeNode { */ create(data: invoices.IInvoiceCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: invoices.IInvoiceCreationOptions, response?: IResponseFn): Promise; - + /** * Retrieves the invoice with the given ID. The invoice object contains a * lines hash that contains information about the subscriptions and invoice items that have been applied to the @@ -5681,7 +5681,7 @@ declare namespace StripeNode { retrieve(id: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(id: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(id: string, response?: IResponseFn): Promise; - + /** * When retrieving an invoice, you'll get a lines property containing the total count of line items and the first * handful of those items. There is also a URL where you can retrieve the full (paginated) list of line items. @@ -5695,7 +5695,7 @@ declare namespace StripeNode { retrieveLines(id: string, data: invoices.IInvoiceLineItemRetrievalOptions, response?: IResponseFn>): Promise; retrieveLines(id: string, options: HeaderOptions, response?: IResponseFn>): Promise; retrieveLines(id: string, response?: IResponseFn>): Promise; - + /** * At any time, you can preview the upcoming invoice for a customer. This will show you all the charges that are pending, * including subscription renewal charges, invoice item charges, etc. It will also show you any discount that is applicable @@ -5712,7 +5712,7 @@ declare namespace StripeNode { retrieveUpcoming(id: string, data: invoices.IInvoiceUpcomingOptions, response?: IResponseFn): Promise; retrieveUpcoming(id: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieveUpcoming(id: string, response?: IResponseFn): Promise; - + /** * Until an invoice is paid, it is marked as open (closed=false). If you'd like to stop Stripe from automatically attempting * payment on an invoice or would simply like to close the invoice out as no longer owed by the customer, you can update the @@ -5725,7 +5725,7 @@ declare namespace StripeNode { */ update(id: string, data: invoices.IInvoiceUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; update(id: string, data: invoices.IInvoiceUpdateOptions, response?: IResponseFn): Promise; - + /** * Stripe automatically creates and then attempts to pay invoices for customers on subscriptions. We'll also retry unpaid * invoices according to your retry settings. However, if you'd like to attempt to collect payment on an invoice out of the @@ -5737,7 +5737,7 @@ declare namespace StripeNode { */ pay(id: string, options: HeaderOptions, response?: IResponseFn): Promise; pay(id: string, response?: IResponseFn): Promise; - + /** * You can list all invoices, or list the invoices for a specific customer. The invoices are returned * sorted by creation date, with the most recently created invoices appearing first. @@ -5751,44 +5751,44 @@ declare namespace StripeNode { list(data: invoices.IInvoiceListOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; } - + class InvoiceItems extends StripeResource { /** * Adds an arbitrary charge or credit to the customer’s upcoming invoice. */ create(data: invoiceItems.InvoiceItemCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: invoiceItems.InvoiceItemCreationOptions, response?: IResponseFn): Promise; - + /** * Retrieves the invoice item with the given ID. */ retrieve(invoiceItemId: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(invoiceItemId: string, response?: IResponseFn): Promise; - + /** - * Updates the amount or description of an invoice item on an upcoming invoice. Updating an invoice item is only possible before the + * Updates the amount or description of an invoice item on an upcoming invoice. Updating an invoice item is only possible before the * invoice it's attached to is closed. */ update(invoiceItemId: string, data: invoiceItems.InvoiceItemUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; update(invoiceItemId: string, data: invoiceItems.InvoiceItemUpdateOptions, response?: IResponseFn): Promise; - + /** - * Returns a list of your invoice items. Invoice items are returned sorted by creation date, with the most recently created invoice + * Returns a list of your invoice items. Invoice items are returned sorted by creation date, with the most recently created invoice * items appearing first. */ list(data: invoiceItems.InvoiceItemListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; list(data: invoiceItems.InvoiceItemListOptions, response?: IResponseFn>): Promise>; list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; - + /** - * Removes an invoice item from the upcoming invoice. Removing an invoice item is only possible before the invoice it's attached + * Removes an invoice item from the upcoming invoice. Removing an invoice item is only possible before the invoice it's attached * to is closed. */ del(invoiceItemId: string, options: HeaderOptions, response?: IResponseFn): Promise; del(invoiceItemId: string, response?: IResponseFn): Promise; } - + class Plans extends StripeResource { /** * You can create plans easily via the plan management page of the Stripe dashboard. Plan creation is also @@ -5800,7 +5800,7 @@ declare namespace StripeNode { */ create(data: plans.IPlanCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: plans.IPlanCreationOptions, response?: IResponseFn): Promise; - + /** * Retrieves the plan with the given ID. * @@ -5810,7 +5810,7 @@ declare namespace StripeNode { */ retrieve(planName: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(planName: string, response?: IResponseFn): Promise; - + /** * Updates the name of a plan. Other plan details (price, interval, etc.) are, by design, not editable. * @@ -5821,7 +5821,7 @@ declare namespace StripeNode { */ update(planName: string, data: plans.IPlanUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; update(planName: string, data: plans.IPlanUpdateOptions, response?: IResponseFn): Promise; - + /** * You can delete plans via the plan management page of the Stripe dashboard. However, deleting a plan does not affect * any current subscribers to the plan; it merely means that new subscribers can't be added to that plan. You can also @@ -5833,7 +5833,7 @@ declare namespace StripeNode { */ del(planName: string, options: HeaderOptions, response?: IResponseFn): Promise; del(planName: string, response?: IResponseFn): Promise; - + /** * Returns a list of your plans. * @@ -5847,7 +5847,7 @@ declare namespace StripeNode { list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; } - + /** * @deprecated */ @@ -5901,24 +5901,24 @@ declare namespace StripeNode { */ del(id: string): void; } - + class Refunds extends StripeResource { /** * When you create a new refund, you must specify a charge to create it on. - * - * Creating a new refund will refund a charge that has previously been created but not yet refunded. - * Funds will be refunded to the credit or debit card that was originally charged. + * + * Creating a new refund will refund a charge that has previously been created but not yet refunded. + * Funds will be refunded to the credit or debit card that was originally charged. * The fees you were originally charged are also refunded. - * - * You can optionally refund only part of a charge. + * + * You can optionally refund only part of a charge. * You can do so as many times as you wish until the entire charge has been refunded. - * - * Once entirely refunded, a charge can't be refunded again. + * + * Once entirely refunded, a charge can't be refunded again. * This method will throw an error when called on an already-refunded charge, or when trying to refund more money than is left on a charge. */ create(data: refunds.IRefundCreationOptionsWithCharge, options: HeaderOptions, response?: IResponseFn): Promise; create(data: refunds.IRefundCreationOptionsWithCharge, response?: IResponseFn): Promise; - + /** * Retrieves the details of an existing refund. */ @@ -5926,20 +5926,20 @@ declare namespace StripeNode { retrieve(id: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(id: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(id: string, response?: IResponseFn): Promise; - - + + /** * Updates the specified refund by setting the values of the parameters passed. * Any parameters not provided will be left unchanged. - * + * * This request only accepts metadata as an argument. */ update(id: string, data: IDataOptionsWithMetadata, options: HeaderOptions, response?: IResponseFn): Promise; update(id: string, data: IDataOptionsWithMetadata, response?: IResponseFn): Promise; - + /** - * Returns a list of all refunds you’ve previously created. The refunds are returned in sorted order, - * with the most recent refunds appearing first. + * Returns a list of all refunds you’ve previously created. The refunds are returned in sorted order, + * with the most recent refunds appearing first. * For convenience, the 10 most recent refunds are always available by default on the charge object. */ list(data: refunds.IRefundListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; @@ -5947,32 +5947,32 @@ declare namespace StripeNode { list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; } - + class Tokens extends StripeResource { /** - * Creates a single use token that wraps the details of a credit card. This token can be used - * in place of a credit card object with any API method. These tokens can only be used once: + * Creates a single use token that wraps the details of a credit card. This token can be used + * in place of a credit card object with any API method. These tokens can only be used once: * by creating a new charge object, or attaching them to a customer. */ create(data: tokens.ICardTokenCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: tokens.ICardTokenCreationOptions, response?: IResponseFn): Promise; - + /** - * Creates a single use token that wraps the details of a bank account. This token can be used - * in place of a bank account object with any API method. These tokens can only be used once: + * Creates a single use token that wraps the details of a bank account. This token can be used + * in place of a bank account object with any API method. These tokens can only be used once: * by attaching them to a recipient or managed account. */ create(data: tokens.IBankAccountTokenCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: tokens.IBankAccountTokenCreationOptions, response?: IResponseFn): Promise; - + /** - * Creates a single use token that wraps the details of personally identifiable information (PII). - * This token can be used in place of a personal_id_number in the Account Update API method. + * Creates a single use token that wraps the details of personally identifiable information (PII). + * This token can be used in place of a personal_id_number in the Account Update API method. * These tokens can only be used once. */ create(data: tokens.IPiiTokenCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: tokens.IPiiTokenCreationOptions, response?: IResponseFn): Promise; - + /** * Retrieves the token with the given ID. */ @@ -5980,155 +5980,155 @@ declare namespace StripeNode { retrieve(tokenId: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(tokenId: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(tokenId: string, response?: IResponseFn): Promise; - + } class Transfers extends StripeResource { /** - * To send funds from your Stripe account to a third-party recipient or to your own bank account, you create a new transfer + * To send funds from your Stripe account to a third-party recipient or to your own bank account, you create a new transfer * object. Your Stripe balance must be able to cover the transfer amount, or you'll receive an "Insufficient Funds" error. - * + * * If your API key is in test mode, money won't actually be sent, though everything else will occur as if in live mode. - * - * If you are creating a manual transfer or a special case transfer on a Stripe account that uses multiple payment source - * types, you'll need to specify the source type balance that the transfer should draw from. The balance object details + * + * If you are creating a manual transfer or a special case transfer on a Stripe account that uses multiple payment source + * types, you'll need to specify the source type balance that the transfer should draw from. The balance object details * available and pending amounts by source type. */ create(data: transfers.ITransferCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: transfers.ITransferCreationOptions, response?: IResponseFn): Promise; - + /** - * Retrieves the details of an existing transfer. Supply the unique transfer ID from either a transfer creation request or + * Retrieves the details of an existing transfer. Supply the unique transfer ID from either a transfer creation request or * the transfer list, and Stripe will return the corresponding transfer information. */ retrieve(id: string, data: IDataOptions, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(id: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(id: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(id: string, response?: IResponseFn): Promise; - - + + /** - * Updates the specified transfer by setting the values of the parameters passed. Any parameters not provided will be left + * Updates the specified transfer by setting the values of the parameters passed. Any parameters not provided will be left * unchanged. - * + * * This request accepts only the description and metadata as arguments. */ update(id: string, data: transfers.ITransferUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; update(id: string, data: transfers.ITransferUpdateOptions, response?: IResponseFn): Promise; - + /** - * Returns a list of existing transfers sent to third-party bank accounts or that Stripe has sent you. The transfers are + * Returns a list of existing transfers sent to third-party bank accounts or that Stripe has sent you. The transfers are * returned in sorted order, with the most recently created transfers appearing first. */ list(data: transfers.ITransferListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; list(data: transfers.ITransferListOptions, response?: IResponseFn>): Promise>; list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; - + cancel(id: string, options: HeaderOptions, response?: IResponseFn): Promise; cancel(id: string, response?: IResponseFn): Promise; - + listTransactions(options: HeaderOptions, response?: IResponseFn>): Promise>; //TODO: Not sure if this should be a list of balance transactions or charges. listTransactions(response?: IResponseFn>): Promise>; //TODO: Not sure if this should be a list of balance transactions or charges. - + /** * When you create a new reversal, you must specify a transfer to create it on. - * - * Creating a new reversal on a transfer that has previously been created but not paid out will return the funds to your available balance + * + * Creating a new reversal on a transfer that has previously been created but not paid out will return the funds to your available balance * and refund the fees you were originally charged on the transfer. You may not reverse automatic Stripe transfers. - * - * When reversing transfers to Stripe accounts, you can optionally reverse part of the transfer. You can do so as many times as you wish + * + * When reversing transfers to Stripe accounts, you can optionally reverse part of the transfer. You can do so as many times as you wish * until the entire transfer has been reversed. - * - * Once entirely reversed, a transfer can't be reversed again. This method will return an error when called on an already-reversed transfer, + * + * Once entirely reversed, a transfer can't be reversed again. This method will return an error when called on an already-reversed transfer, * or when trying to reverse more money than is left on a transfer. */ reverse(id: string, data: transferReversals.IReversalCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; reverse(id: string, options: HeaderOptions, response?: IResponseFn): Promise; reverse(id: string, response?: IResponseFn): Promise; - + /** * When you create a new reversal, you must specify a transfer to create it on. - * - * Creating a new reversal on a transfer that has previously been created but not paid out will return the funds to your available balance + * + * Creating a new reversal on a transfer that has previously been created but not paid out will return the funds to your available balance * and refund the fees you were originally charged on the transfer. You may not reverse automatic Stripe transfers. - * - * When reversing transfers to Stripe accounts, you can optionally reverse part of the transfer. You can do so as many times as you wish + * + * When reversing transfers to Stripe accounts, you can optionally reverse part of the transfer. You can do so as many times as you wish * until the entire transfer has been reversed. - * - * Once entirely reversed, a transfer can't be reversed again. This method will return an error when called on an already-reversed transfer, + * + * Once entirely reversed, a transfer can't be reversed again. This method will return an error when called on an already-reversed transfer, * or when trying to reverse more money than is left on a transfer. */ createReverse(transferId: string, data: transferReversals.IReversalCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; createReverse(transferId: string, options: HeaderOptions, response?: IResponseFn): Promise; createReverse(transferId: string, response?: IResponseFn): Promise; - + /** - * By default, you can see the 10 most recent reversals stored directly on the transfer object, but you can also retrieve details about a + * By default, you can see the 10 most recent reversals stored directly on the transfer object, but you can also retrieve details about a * specific reversal stored on the transfer. */ retrieveReversal(transferId: string, reversalId: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieveReversal(transferId: string, reversalId: string, response?: IResponseFn): Promise; - + /** * Updates the specified reversal by setting the values of the parameters passed. Any parameters not provided will be left unchanged. - * + * * This request only accepts metadata and description as arguments. */ updateReversal(transferId: string, reversalId: string, data: transferReversals.IReversalUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; updateReversal(transferId: string, reversalId: string, data: transferReversals.IReversalUpdateOptions, response?: IResponseFn): Promise; - + /** - * You can see a list of the reversals belonging to a specific transfer. Note that the 10 most recent reversals are always available by - * default on the transfer object. If you need more than those 10, you can use this API method and the limit and starting_after + * You can see a list of the reversals belonging to a specific transfer. Note that the 10 most recent reversals are always available by + * default on the transfer object. If you need more than those 10, you can use this API method and the limit and starting_after * parameters to page through additional reversals. */ listReversals(transferId: string, data: IListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; listReversals(transferId: string, data: IListOptions, response?: IResponseFn>): Promise>; listReversals(transferId: string, options: HeaderOptions, response?: IResponseFn>): Promise>; listReversals(transferId: string, response?: IResponseFn>): Promise>; - + setMetadata(): void; //TODO: Implement placeholder method getMetadata(): void; //TODO: Implement placeholder method } - + class TransferReversals extends StripeResource { /** * When you create a new reversal, you must specify a transfer to create it on. - * - * Creating a new reversal on a transfer that has previously been created but not paid out will return the funds to your available balance + * + * Creating a new reversal on a transfer that has previously been created but not paid out will return the funds to your available balance * and refund the fees you were originally charged on the transfer. You may not reverse automatic Stripe transfers. - * - * When reversing transfers to Stripe accounts, you can optionally reverse part of the transfer. You can do so as many times as you wish + * + * When reversing transfers to Stripe accounts, you can optionally reverse part of the transfer. You can do so as many times as you wish * until the entire transfer has been reversed. - * - * Once entirely reversed, a transfer can't be reversed again. This method will return an error when called on an already-reversed transfer, + * + * Once entirely reversed, a transfer can't be reversed again. This method will return an error when called on an already-reversed transfer, * or when trying to reverse more money than is left on a transfer. */ create(data: transferReversals.IReversalCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(options: HeaderOptions, response?: IResponseFn): Promise; create(response?: IResponseFn): Promise; - + /** - * By default, you can see the 10 most recent reversals stored directly on the transfer object, but you can also retrieve details about a + * By default, you can see the 10 most recent reversals stored directly on the transfer object, but you can also retrieve details about a * specific reversal stored on the transfer. */ retrieve(reversalId: string, data: IDataOptions, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(reversalId: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(reversalId: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(reversalId: string, response?: IResponseFn): Promise; - + /** * Updates the specified reversal by setting the values of the parameters passed. Any parameters not provided will be left unchanged. - * + * * This request only accepts metadata and description as arguments. */ update(reversalId: string, data: transferReversals.IReversalUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; update(reversalId: string, data: transferReversals.IReversalUpdateOptions, response?: IResponseFn): Promise; - + /** - * You can see a list of the reversals belonging to a specific transfer. Note that the 10 most recent reversals are always available by - * default on the transfer object. If you need more than those 10, you can use this API method and the limit and starting_after + * You can see a list of the reversals belonging to a specific transfer. Note that the 10 most recent reversals are always available by + * default on the transfer object. If you need more than those 10, you can use this API method and the limit and starting_after * parameters to page through additional reversals. */ list(data: IListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; @@ -6136,7 +6136,7 @@ declare namespace StripeNode { list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; } - + class CountrySpecs extends StripeResource { /** * Lists all Country Spec objects available in the API. @@ -6145,10 +6145,10 @@ declare namespace StripeNode { list(data: IListOptions, response?: IResponseFn>): Promise>; list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; - + /** * Returns a Country Spec for a given Country code. - * + * * @param retrieve An ISO country code. Available country codes can be listed with the List Country Specs endpoint. */ retrieve(id: string, data: IDataOptions, options: HeaderOptions, response?: IResponseFn): Promise; @@ -6156,36 +6156,36 @@ declare namespace StripeNode { retrieve(id: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(id: string, response?: IResponseFn): Promise; } - + class Orders { /** * Creates a new order object. */ create(data: orders.IOrderCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: orders.IOrderCreationOptions, response?: IResponseFn): Promise; - + /** - * Retrieves the details of an existing order. Supply the unique order ID from either an order creation request or the order list, + * Retrieves the details of an existing order. Supply the unique order ID from either an order creation request or the order list, * and Stripe will return the corresponding order information. */ retrieve(orderId: string, data: IDataOptions, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(orderId: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(orderId: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(orderId: string, response?: IResponseFn): Promise; - + /** - * Updates the specific order by setting the values of the parameters passed. Any parameters not provided will be left unchanged. + * Updates the specific order by setting the values of the parameters passed. Any parameters not provided will be left unchanged. * This request accepts only the metadata, and status as arguments. */ update(orderId: string, data: orders.IOrderUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; update(orderId: string, data: orders.IOrderUpdateOptions, response?: IResponseFn): Promise; - + /** * Pay an order by providing a source to create a payment. */ pay(orderId: string, data: orders.IOrderPayOptions, options: HeaderOptions, response?: IResponseFn): Promise; pay(orderId: string, data: orders.IOrderPayOptions, response?: IResponseFn): Promise; - + /** * Returns a list of your orders. The orders are returned sorted by creation date, with the most recently created orders appearing first. */ @@ -6194,32 +6194,32 @@ declare namespace StripeNode { list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; } - + class Products { /** * Creates a new product object. */ create(data: products.IProductCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: products.IProductCreationOptions, response?: IResponseFn): Promise; - + /** - * Retrieves the details of an existing product. Supply the unique product ID from either a product creation request or the product + * Retrieves the details of an existing product. Supply the unique product ID from either a product creation request or the product * list, and Stripe will return the corresponding product information. */ retrieve(productId: string, data: IDataOptions, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(productId: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(productId: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(productId: string, response?: IResponseFn): Promise; - + /** * Updates the specific product by setting the values of the parameters passed. Any parameters not provided will be left unchanged. - * - * Note that a product's attributes are not editable. Instead, you would need to deactivate the existing product and create a new one + * + * Note that a product's attributes are not editable. Instead, you would need to deactivate the existing product and create a new one * with the new attribute values. */ update(productId: string, data: products.IProductUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; update(productId: string, data: products.IProductUpdateOptions, response?: IResponseFn): Promise; - + /** * Returns a list of your products. The products are returned sorted by creation date, with the most recently created products appearing first. */ @@ -6227,39 +6227,39 @@ declare namespace StripeNode { list(data: products.IProductListOptions, response?: IResponseFn>): Promise>; list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; - + /** * Delete a product. Deleting a product is only possible if it has no SKUs associated with it. */ del(productId: string, options: HeaderOptions, response?: IResponseFn): Promise; del(productId: string, response?: IResponseFn): Promise; } - + class SKUs { /** * Creates a new SKU associated with a product. */ create(data: skus.ISkuCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; create(data: skus.ISkuCreationOptions, response?: IResponseFn): Promise; - + /** - * Retrieves the details of an existing SKU. Supply the unique SKU identifier from either a SKU creation request or from the + * Retrieves the details of an existing SKU. Supply the unique SKU identifier from either a SKU creation request or from the * product, and Stripe will return the corresponding SKU information. */ retrieve(skuId: string, data: IDataOptions, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(skuId: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(skuId: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(skuId: string, response?: IResponseFn): Promise; - + /** * Updates the specific SKU by setting the values of the parameters passed. Any parameters not provided will be left unchanged. - * - * Note that a SKU's attributes are not editable. Instead, you would need to deactivate the existing SKU and create a new one with + * + * Note that a SKU's attributes are not editable. Instead, you would need to deactivate the existing SKU and create a new one with * the new attribute values. */ update(skuId: string, data: skus.ISkuUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; update(skuId: string, data: skus.ISkuUpdateOptions, response?: IResponseFn): Promise; - + /** * Returns a list of your SKUs. The SKUs are returned sorted by creation date, with the most recently created SKUs appearing first. */ @@ -6267,7 +6267,7 @@ declare namespace StripeNode { list(data: skus.ISkuListOptions, response?: IResponseFn>): Promise>; list(options: HeaderOptions, response?: IResponseFn>): Promise>; list(response?: IResponseFn>): Promise>; - + /** * Delete a SKU. Deleting a SKU is only possible until it has been used in an order. */ @@ -6275,24 +6275,24 @@ declare namespace StripeNode { del(skuId: string, response?: IResponseFn): Promise; } } - + interface IObject { object: string; } - + interface IResourceObject extends IObject { id: string; } - + interface IResponseFn { (err: IStripeError, value: R): void; } - + interface IDeleteConfirmation { id: string; deleted: boolean; } - + /** - * A filter on the list based on this object field. The value can - * be a string with an integer Unix timestamp, or it can be a + * A filter on the list based on this object field. The value can + * be a string with an integer Unix timestamp, or it can be a * dictionary with the following options: */ type IDateFilter = string | { @@ -6387,12 +6387,12 @@ declare namespace StripeNode { * Value is 'list' */ object: string; - + /** * An array containing the actual response elements, paginated by any request parameters. */ data: Array; - + /** * Whether or not there are more elements available after this set. If false, this set comprises the end of the list. */ @@ -6437,22 +6437,22 @@ declare namespace StripeNode { */ created?: string | IDateFilter; } - + interface IDataOptions { expand?: Array; include?: Array; } - + interface IDataOptionsWithMetadata extends IDataOptions { /** - * A set of key/value pairs that you can attach to an object. It can be - * useful for storing additional information about the object in a structured - * format. You can unset an individual key by setting its value to null and + * A set of key/value pairs that you can attach to an object. It can be + * useful for storing additional information about the object in a structured + * format. You can unset an individual key by setting its value to null and * then saving. To clear all keys, set metadata to null, then save. */ metadata?: IMetadata; } - + interface IHeaderOptions { /** * To safely retry an API request without accidentally performing the same operation twice, @@ -6464,18 +6464,18 @@ declare namespace StripeNode { * with different request parameters. The keys expire after 24 hours. */ idempotency_key?: string; - + stripe_account?: string; - + api_key?: string; } - + /** - * Header options can either be a Connect Account Secret Key, + * Header options can either be a Connect Account Secret Key, * or a hash with one or more of these keys: idempotency_key, stripe_account, api_key */ type HeaderOptions = IHeaderOptions | string; - + /** * Stripe uses conventional HTTP response codes to indicate success or failure of an API request. * In general, codes in the 2xx range indicate success, codes in the 4xx range indicate an error that diff --git a/stripe/stripe.d.ts b/stripe/stripe.d.ts index 659c75bf3e..8a03ee3f33 100644 --- a/stripe/stripe.d.ts +++ b/stripe/stripe.d.ts @@ -17,8 +17,9 @@ interface StripeStatic { interface StripeTokenData { number: string; - exp_month: number; - exp_year: number; + exp_month?: number; + exp_year?: number; + exp?: string; cvc?: string; name?: string; address_line1?: string; diff --git a/stylus/stylus.d.ts b/stylus/stylus.d.ts index 52053af678..d143dc8b56 100644 --- a/stylus/stylus.d.ts +++ b/stylus/stylus.d.ts @@ -634,7 +634,7 @@ declare namespace Stylus { export class Compiler { } - export class Renderer implements NodeJS.EventEmitter { + export class Renderer extends NodeJS.EventEmitter { options: RenderOptions; str: string; events: any; diff --git a/sugar/sugar.d.ts b/sugar/sugar.d.ts index 217ffb110e..6270ed2330 100644 --- a/sugar/sugar.d.ts +++ b/sugar/sugar.d.ts @@ -907,7 +907,7 @@ interface String { } // Todo: fix when TypeScript supports adding static functions to native types. -interface NumberStatic { +interface NumberConstructor { /** * Returns a random integer between [n1] and [n2]. @@ -1963,8 +1963,8 @@ interface Number { upto(num: number, fn?: Function, step?: number): number[]; } -// Todo: Fix when TypeScript supports static members on native types. -interface ArrayStatic { +//Static members on native types. +interface ArrayConstructor { /** * Alternate array constructor. @@ -2918,7 +2918,7 @@ interface Array { //zip(...arrays: T[]): T[][]; } -interface ObjectStatic { +interface ObjectConstructor { /** * Creates a new object, equivalent to %new Object()% or %{}%, but with extended methods. @@ -4003,7 +4003,7 @@ interface Function { throttle(ms: number): Function; } -interface RegExpStatic { +interface RegExpConstructor { /** * Escapes all RegExp tokens in a string. @@ -4080,7 +4080,7 @@ interface Locale { timeParse: string[]; } -interface DateStatic { +interface DateConstructor { /** * Adds a locale to the locales understood by Sugar. @@ -4125,6 +4125,11 @@ interface DateStatic { **/ create(d: string, locale?: string): Date; + /** + * @see create + * @param timestamp + create(timestamp?: number): Date; + /** * @see create * @param year Year YYYY diff --git a/superagent/superagent-tests.ts b/superagent/superagent-tests.ts index 58b6840440..283244ac85 100644 --- a/superagent/superagent-tests.ts +++ b/superagent/superagent-tests.ts @@ -5,6 +5,7 @@ import * as request from 'superagent'; import * as fs from 'fs'; +import * as assert from 'assert'; // Examples taken from https://github.com/visionmedia/superagent/blob/gh-pages/docs/index.md // and https://github.com/visionmedia/superagent/blob/master/Readme.md @@ -193,6 +194,24 @@ request('/search') var charset: string = res.charset; }); +// Custom parsers +request + .post('/search') + .parse((res, callback) => { + res.setEncoding("binary"); + let data = ""; + res.on("data", (chunk: string) => { + data += chunk; + }); + + res.on("end", () => { + callback(null, new Buffer(data, "base64")); + }); + }) + .end((res: request.Response) => { + res.body.toString("hex"); + }); + var req = request.get('/hoge'); // Aborting requests req.abort(); @@ -279,3 +298,19 @@ request .attach('image', 'path/to/tobi.png') .on('error', (err: any) => {}) .end(callback); + +//Promise +request + .get('/search') + .then((response) => {}) + .catch((error) => {}); + +// Requesting binary data. +// adapted from: https://github.com/visionmedia/superagent/blob/v2.0.0/test/client/request.js#L110 +request + .get('/blob') + .responseType('blob') + .end(function (err, res) { + assert(res.xhr instanceof XMLHttpRequest) + assert(res.xhr.response instanceof Blob); + }); diff --git a/superagent/superagent.d.ts b/superagent/superagent.d.ts index fa0ac1827f..c41847775c 100644 --- a/superagent/superagent.d.ts +++ b/superagent/superagent.d.ts @@ -1,4 +1,4 @@ -// Type definitions for SuperAgent v1.4.0 +// Type definitions for SuperAgent v2.0.0 // Project: https://github.com/visionmedia/superagent // Definitions by: Alex Varju // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -13,6 +13,7 @@ declare module "superagent" { var request: request.SuperAgentStatic; namespace request { + interface SuperAgentRequest extends Request {} interface SuperAgentStatic extends SuperAgent { (url: string): SuperAgentRequest; (method: string, url: string): SuperAgentRequest; @@ -20,7 +21,7 @@ declare module "superagent" { agent(): SuperAgent; } - interface SuperAgent> extends stream.Stream { + interface SuperAgent extends stream.Stream { get(url: string, callback?: CallbackHandler): Req; post(url: string, callback?: CallbackHandler): Req; put(url: string, callback?: CallbackHandler): Req; @@ -49,7 +50,7 @@ declare module "superagent" { search(url: string, callback?: CallbackHandler): Req; connect(url: string, callback?: CallbackHandler): Req; - parse(fn: Function): Req; + parse(fn: (res: Response, callback: (err: Error, body: any) => void) => void): this; saveCookies(res: Response): void; attachCookies(req: Req): void; } @@ -76,41 +77,42 @@ declare module "superagent" { notAcceptable: boolean; notFound: boolean; forbidden: boolean; + xhr: XMLHttpRequest; get(header: string): string; } - interface Request> /* extends NodeJS.WritableStream */ { + interface Request extends Promise /* extends NodeJS.WritableStream */ { abort(): void; - accept(type: string): Req; - attach(field: string, file: string, filename?: string): Req; - auth(user: string, name: string): Req; - buffer(val: boolean): Req; - clearTimeout(): Req; - end(callback?: CallbackHandler): Req; - field(name: string, val: string): Req; + accept(type: string): this; + attach(field: string, file: string, filename?: string): this; + auth(user: string, name: string): this; + buffer(val?: boolean): this; + clearTimeout(): this; + end(callback?: CallbackHandler): this; + field(name: string, val: string): this; get(field: string): string; - on(name: string, handler: Function): Req; - on(name: 'error', handler: (err: any) => void): Req; - part(): Req; + on(name: string, handler: Function): this; + on(name: 'error', handler: (err: any) => void): this; + part(): this; pipe(stream: NodeJS.WritableStream, options?: Object): stream.Writable; - query(val: Object): Req; - redirects(n: number): Req; - send(data: string): Req; - send(data: Object): Req; - send(): Req; - set(field: string, val: string): Req; - set(field: Object): Req; - timeout(ms: number): Req; - type(val: string): Req; - use(fn: Function): Req; - withCredentials(): Req; - write(data: string, encoding?: string): Req; - write(data: Buffer, encoding?: string): Req; + query(val: Object): this; + redirects(n: number): this; + responseType(type: string): this; + send(data: string): this; + send(data: Object): this; + send(): this; + set(field: string, val: string): this; + set(field: Object): this; + timeout(ms: number): this; + type(val: string): this; + use(fn: Function): this; + withCredentials(): this; + write(data: string, encoding?: string): this; + write(data: Buffer, encoding?: string): this; + parse(fn: (res: Response, callback: (err: Error, body: any) => void) => void): this; } - interface SuperAgentRequest extends Request>>> {} } export = request; } - diff --git a/supertest-as-promised/supertest-as-promised.d.ts b/supertest-as-promised/supertest-as-promised.d.ts index a7256e5bbf..89bc3e5525 100644 --- a/supertest-as-promised/supertest-as-promised.d.ts +++ b/supertest-as-promised/supertest-as-promised.d.ts @@ -4,42 +4,33 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// +/// +/// declare module "supertest-as-promised" { - // Mostly copy-pasted from supertest.d.ts + import * as supertest from "supertest"; + import * as supersgent from "superagent"; + import { SuperTest, Response } from "supertest"; + import * as PromiseBlurbird from "bluebird"; - import * as superagent from 'superagent'; - import * as PromiseBluebird from 'bluebird'; + function supertestAsPromised(app: any): SuperTest; - function supertest(app: any): supertest.SuperTest; - - namespace supertest { - function agent(app?: any): supertest.SuperTest; - - interface SuperTest extends superagent.SuperAgent { + namespace supertestAsPromised { + interface Request extends supertest.Request { } - interface Promise extends PromiseBluebird { - toPromise(): PromiseBluebird; + interface Response extends supertest.Response { } - interface Test extends superagent.Request { - url: string; - serverAddress(app: any, path: string): string; - expect(status: number): Promise; - expect(status: number, body: string): Promise; - expect(body: string): Promise; - expect(body: RegExp): Promise; - expect(body: Object): Promise; - expect(field: string, val: string): Promise; - expect(field: string, val: RegExp): Promise; - expect(checker: (res: Response) => any): Promise; + interface Test extends supertest.Test, supersgent.Request { + toPromise(): PromiseBlurbird; } - interface Response extends superagent.Response { + function agent(app?: any): SuperTest; + + interface SuperTest extends supertest.SuperTest { } } + export = supertestAsPromised - export = supertest; } diff --git a/supertest/supertest.d.ts b/supertest/supertest.d.ts index 430c9f15c5..5793483300 100644 --- a/supertest/supertest.d.ts +++ b/supertest/supertest.d.ts @@ -6,35 +6,40 @@ /// declare module "supertest" { - import superagent = require('superagent'); + import * as superagent from "superagent" - type CallbackHandler = (err: any, res: supertest.Response) => void; - - function supertest(app: any): supertest.SuperTest; + function supertest(app: any): supertest.SuperTest; namespace supertest { - function agent(app?: any): supertest.SuperTest; - - interface SuperTest extends superagent.SuperAgent { - } - - interface Test extends superagent.Request { - url: string; - serverAddress(app: any, path: string): string; - expect(status: number, callback?: CallbackHandler): Test; - expect(status: number, body: string, callback?: CallbackHandler): Test; - expect(body: string, callback?: CallbackHandler): Test; - expect(body: RegExp, callback?: CallbackHandler): Test; - expect(body: Object, callback?: CallbackHandler): Test; - expect(field: string, val: string, callback?: CallbackHandler): Test; - expect(field: string, val: RegExp, callback?: CallbackHandler): Test; - expect(checker: (res: Response) => any): Test; - end(callback?: CallbackHandler): Test; - } - interface Response extends superagent.Response { } + + interface Request extends superagent.Request { + } + + type CallbackHandler = (err: any, res: Response) => void; + interface Test extends Request { + app?: any; + url: string; + serverAddress(app: any, path: string): string; + expect(status: number, callback?: CallbackHandler): this; + expect(status: number, body: string, callback?: CallbackHandler): this; + expect(body: string, callback?: CallbackHandler): this; + expect(body: RegExp, callback?: CallbackHandler): this; + expect(body: Object, callback?: CallbackHandler): this; + expect(field: string, val: string, callback?: CallbackHandler): this; + expect(fzield: string, val: RegExp, callback?: CallbackHandler): this; + expect(checker: (res: Response) => any): this; + end(callback?: CallbackHandler): this; + } + + function agent(app?: any): SuperTest; + + interface SuperTest extends superagent.SuperAgent { + } + } + export = supertest; } diff --git a/swiper/swiper.d.ts b/swiper/swiper.d.ts index f3c906710d..2be39474d2 100644 --- a/swiper/swiper.d.ts +++ b/swiper/swiper.d.ts @@ -53,6 +53,8 @@ interface SwiperOptions { // Navigation keyboardControl?: boolean; mousewheelControl?: boolean; + nextButton?: string | HTMLElement; + prevButton?: string | HTMLElement; // Pagination pagination?: any; @@ -120,8 +122,7 @@ declare class SwiperSlide { } declare class Swiper { - constructor(container: string, options?: SwiperOptions); - constructor(container: Element, options?: SwiperOptions); + constructor(container: string|Element, options?: SwiperOptions); // Properties width: number; @@ -192,4 +193,4 @@ declare class Swiper { getSlide(index: number): SwiperSlide; getLastSlide(): SwiperSlide; getFirstSlide(): SwiperSlide; -} \ No newline at end of file +} diff --git a/systemjs/systemjs.d.ts b/systemjs/systemjs.d.ts index 2fcc2b98dc..80fcfd7240 100644 --- a/systemjs/systemjs.d.ts +++ b/systemjs/systemjs.d.ts @@ -101,6 +101,12 @@ declare namespace SystemJSLoader { * Use this option to disable this iteration and copying of the exports. */ esmExports?: boolean; + + /** + * To ignore resources that shouldn't be traced as part of the build. + * Use with the SystemJS Builder. (https://github.com/systemjs/builder#ignore-resources) + */ + build?: boolean; } interface PackageConfig { diff --git a/tedious/tedious-tests.ts b/tedious/tedious-tests.ts index bbfdb7629c..d039ab6a2b 100644 --- a/tedious/tedious-tests.ts +++ b/tedious/tedious-tests.ts @@ -13,7 +13,7 @@ var config: tedious.ConnectionConfig = { database: "somedb", instanceName: "someinstance", } -} +}; var connection = new tedious.Connection(config); connection.on("connect", (): void => { @@ -23,7 +23,12 @@ connection.on("connect", (): void => { connection.beginTransaction((error: Error): void => {}, "some name"); connection.rollbackTransaction((error: Error): void => {}); connection.commitTransaction((error: Error): void => {}); - +connection.saveTransaction((error: Error): void => {}); +connection.transaction((error: Error, done: (error?: Error) => void): void => { + done(); + done(error); +}, "some name", tedious.ISOLATION_LEVEL.NO_CHANGE); +connection.transaction((error: Error, done: (error?: Error) => void): void => {}); var request = new tedious.Request("SELECT * FROM foo", (error: Error, rowCount: number): void => { }); diff --git a/tedious/tedious.d.ts b/tedious/tedious.d.ts index 0be051c91f..e790c24b51 100644 --- a/tedious/tedious.d.ts +++ b/tedious/tedious.d.ts @@ -443,7 +443,7 @@ declare module 'tedious' { * a connection, another request should not be initiated until this callback is called. * @param callback The callback is called when the request to start the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. * @param name A string representing a name to associate with the transaction. Optional, and defaults to an empty string. Required when isolationLevel is present. - * @param isolationLevel The isolation level that the transaction is to be run with. + * @param isolationLevel The isolation level that the transaction is to be run with. */ beginTransaction(callback: (error?: Error) => void, name?: string, isolationLevel?: ISOLATION_LEVEL): void; @@ -456,12 +456,32 @@ declare module 'tedious' { commitTransaction(callback: (error: Error) => void): void; /** - * Rollback a transaction. There should be an active transaction. That is, beginTransaction should have been previously called. - * @param callback The callback is called when the request to rollback the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. + * Rollback a transaction. There should be an active transaction. That is, beginTransaction should have been previously called. + * @param callback The callback is called when the request to rollback the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. */ rollbackTransaction(callback: (error: Error) => void): void; + /** + * Set a savepoint within a transaction. There should be an active transaction. That is, beginTransaction should have been previously called. + * @param callback The callback is called when the request to set a savepoint within the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. + * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. + */ + saveTransaction(callback: (error: Error) => void): void; + + /** + * Run the given callback after starting a transaction, and commit or rollback the transaction afterwards. + * This is a helper that employs beginTransaction, commitTransaction, rollbackTransaction and saveTransaction to greatly simplify the use of database transactions and automatically handle transaction nesting. + * @param callback The callback is called when the request to start a transaction (or create a savepoint, in the case of a nested transaction) has completed, either successfully or with an error. + * If an error occured, then err will describe the error. If no error occured, the callback should perform its work and eventually call done with an error or null + * (to trigger a transaction rollback or a transaction commit) and an additional completion callback that will be called when the request to rollback or commit the current transaction + * has completed, either successfully or with an error. Additional arguments given to done will be passed through to this callback. + * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. + * @param name A string representing a name to associate with the transaction. Optional, and defaults to an empty string. In case of a nested transaction, naming the transaction name has no effect. + * @param isolationLevel The isolation level that the transaction is to be run with. + */ + transaction(callback: (error: Error, done: (error?: Error) => void) => void, name?: string, isolationLevel?: ISOLATION_LEVEL): void; + /** * Prepare the SQL represented by the request. The request can then be used in subsequent calls to execute and unprepare * @param request A Request object representing the request. Parameters only require a name and type. Parameter values are ignored. diff --git a/drop/drop-tests.ts b/tether-drop/tether-drop-tests.ts similarity index 72% rename from drop/drop-tests.ts rename to tether-drop/tether-drop-tests.ts index cc19621fbd..8976f0344c 100644 --- a/drop/drop-tests.ts +++ b/tether-drop/tether-drop-tests.ts @@ -1,5 +1,7 @@ /// -/// +/// + +import 'tether-drop'; var yellowBox = document.querySelector(".yellow"); var greenBox = document.querySelector(".green"); @@ -22,7 +24,7 @@ d.remove(); d.toggle(); d.position(); d.destroy(); -d.element.appendChild(document.createElement("div")); +d.content.appendChild(document.createElement("div")); d.tether.position(); d.on("open", () => false); @@ -36,3 +38,11 @@ var e = new Drop({ content: () => greenBox }); +var Tooltip = Drop.createContext({ + classPrefix: 'tooltip' +}); + +var t = new Tooltip({ + target: yellowBox, + content: () => greenBox +}); diff --git a/drop/drop.d.ts b/tether-drop/tether-drop.d.ts similarity index 96% rename from drop/drop.d.ts rename to tether-drop/tether-drop.d.ts index 63f9c8621e..8ee8ca1c02 100644 --- a/drop/drop.d.ts +++ b/tether-drop/tether-drop.d.ts @@ -10,7 +10,6 @@ declare class Drop { constructor(options: Drop.IDropOptions); public content: HTMLElement; - public element: HTMLElement; public tether: Tether; public open(): void; public close(): void; @@ -27,7 +26,7 @@ declare class Drop { public once(event: string, handler: Function, context?: any): void; public off(event: string, handler?: Function): void; - public static createContext(options: Drop.IDropContextOptions): Drop; + public static createContext(options: Drop.IDropContextOptions): typeof Drop; } declare namespace Drop { @@ -56,7 +55,6 @@ declare namespace Drop { } } -declare module "drop" { +declare module "tether-drop" { export = Drop; } - diff --git a/threejs/tests/webgl/webgl_animation_cloth.ts b/threejs/tests/webgl/webgl_animation_cloth.ts index e58d460986..7bebdc3423 100644 --- a/threejs/tests/webgl/webgl_animation_cloth.ts +++ b/threejs/tests/webgl/webgl_animation_cloth.ts @@ -114,7 +114,7 @@ clothGeometry.dynamic = true; clothGeometry.computeFaceNormals(); - var uniforms = { texture: { type: "t", value: clothTexture } }; + var uniforms = { texture: { value: clothTexture } }; var vertexShader = document.getElementById('vertexShaderDepth').textContent; var fragmentShader = document.getElementById('fragmentShaderDepth').textContent; diff --git a/threejs/tests/webgl/webgl_animation_skinning_morph.ts b/threejs/tests/webgl/webgl_animation_skinning_morph.ts index 50976c4547..726a8f4b7f 100644 --- a/threejs/tests/webgl/webgl_animation_skinning_morph.ts +++ b/threejs/tests/webgl/webgl_animation_skinning_morph.ts @@ -182,7 +182,7 @@ scene.add( helper ); - var clipMorpher = THREE.AnimationClip.CreateFromMorphTargetSequence( 'facialExpressions', mesh.geometry.morphTargets, 3 ); + var clipMorpher = THREE.AnimationClip.CreateFromMorphTargetSequence( 'facialExpressions', mesh.geometry.morphTargets, 3, true ); var clipBones = geometry.animations[0]; mixer = new THREE.AnimationMixer( mesh ); diff --git a/threejs/tests/webgl/webgl_lights_hemisphere.ts b/threejs/tests/webgl/webgl_lights_hemisphere.ts index 892b3ed4cc..bed4d5e0b5 100644 --- a/threejs/tests/webgl/webgl_lights_hemisphere.ts +++ b/threejs/tests/webgl/webgl_lights_hemisphere.ts @@ -95,10 +95,10 @@ var vertexShader = document.getElementById( 'vertexShader' ).textContent; var fragmentShader = document.getElementById( 'fragmentShader' ).textContent; var uniforms = { - topColor: { type: "c", value: new THREE.Color( 0x0077ff ) }, - bottomColor: { type: "c", value: new THREE.Color( 0xffffff ) }, - offset: { type: "f", value: 33 }, - exponent: { type: "f", value: 0.6 } + topColor: { value: new THREE.Color( 0x0077ff ) }, + bottomColor: { value: new THREE.Color( 0xffffff ) }, + offset: { value: 33 }, + exponent: { value: 0.6 } }; uniforms.topColor.value.copy( hemiLight.color ); diff --git a/threejs/three-FirstPersonControls.d.ts b/threejs/three-FirstPersonControls.d.ts index fc13ca8ed9..9f6db3ec6c 100644 --- a/threejs/three-FirstPersonControls.d.ts +++ b/threejs/three-FirstPersonControls.d.ts @@ -10,7 +10,8 @@ declare namespace THREE { constructor(object: Camera, domElement?: HTMLElement); object: THREE.Object3D; target: THREE.Vector3; - domElement: HTMLCanvasElement; + domElement: HTMLCanvasElement | HTMLDocument; + enabled: boolean; movementSpeed: number; lookSpeed: number; noFly: boolean; @@ -18,8 +19,9 @@ declare namespace THREE { autoForward: boolean; activeLook: boolean; heightSpeed: boolean; - heightCoef: boolean; - heightMin: boolean; + heightCoef: number; + heightMin: number; + heightMax: number; constrainVertical: boolean; verticalMin: number; verticalMax: number; @@ -36,6 +38,7 @@ declare namespace THREE { moveRight: boolean; freeze: boolean; mouseDragOn: boolean; - update(delta?: number): void; + update(delta: number): void; + dispose(): void; } } diff --git a/threejs/three-canvasrenderer.d.ts b/threejs/three-canvasrenderer.d.ts index 2d2d9e4930..7dba387da9 100644 --- a/threejs/three-canvasrenderer.d.ts +++ b/threejs/three-canvasrenderer.d.ts @@ -17,7 +17,6 @@ declare namespace THREE { color: Color; program(context: any, color: Color): void; - clone(): SpriteCanvasMaterial; } export interface CanvasRendererParameters { diff --git a/threejs/three-orbitcontrols.d.ts b/threejs/three-orbitcontrols.d.ts index 910a658334..cb1ffd21d5 100644 --- a/threejs/three-orbitcontrols.d.ts +++ b/threejs/three-orbitcontrols.d.ts @@ -10,7 +10,7 @@ declare namespace THREE { constructor(object: Camera, domElement?: HTMLElement); object: Camera; - domElement: HTMLElement; + domElement: HTMLElement | HTMLDocument; // API enabled: boolean; @@ -49,6 +49,7 @@ declare namespace THREE { dollyOut(dollyScale: number): void; update(): void; reset(): void; + dispose(): void; getPolarAngle(): number; getAzimuthalAngle(): number; diff --git a/threejs/three-trackballcontrols.d.ts b/threejs/three-trackballcontrols.d.ts index 41b978fd3f..23ef373194 100644 --- a/threejs/three-trackballcontrols.d.ts +++ b/threejs/three-trackballcontrols.d.ts @@ -28,6 +28,7 @@ declare namespace THREE { maxDistance:number; keys:number[]; + target: THREE.Vector3; position0: THREE.Vector3; target0: THREE.Vector3; up0: THREE.Vector3; diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 389d247e53..830edbf864 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -1,4 +1,4 @@ -// Type definitions for three.js r75 +// Type definitions for three.js r80 // Project: http://mrdoob.github.com/three.js/ // Definitions by: Kon , Satoru Kimura , Florent Poujol , SereznoKot // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -149,6 +149,7 @@ declare namespace THREE { export const UnsignedShort4444Type: PixelType; export const UnsignedShort5551Type: PixelType; export const UnsignedShort565Type: PixelType; + export const UnsignedInt248Type: PixelType; // Pixel formats export enum PixelFormat { } @@ -158,6 +159,8 @@ declare namespace THREE { export const LuminanceFormat: PixelFormat; export const LuminanceAlphaFormat: PixelFormat; export const RGBEFormat: PixelFormat; + export const DepthFormat: PixelFormat; + export const DepthStencilFormat: PixelFormat; // Compressed texture formats // DDS / ST3C Compressed texture formats @@ -211,6 +214,11 @@ declare namespace THREE { export const RGBM16Encoding: TextureEncoding; export const RGBDEncoding: TextureEncoding; + // Depth packing strategies + export enum DepthPackingStrategies { } + export const BasicDepthPacking: DepthPackingStrategies; + export const RGBADepthPacking: DepthPackingStrategies; + // log handlers export function warn(message?: any, ...optionalParams: any[]): void; export function error(message?: any, ...optionalParams: any[]): void; @@ -218,40 +226,78 @@ declare namespace THREE { // Animation //////////////////////////////////////////////////////////////////////////////////////// + export class AnimationAction { + loop: boolean; + time: number; + timeScale: number; + weight: number; + repetitions: number; + paused: boolean; + enabled: boolean; + clampWhenFinished: boolean; + zeroSlopeAtStart: boolean; + zeroSlopeAtEnd: boolean; + + play(): AnimationAction; + stop(): AnimationAction; + reset(): AnimationAction; + isRunning(): boolean; + startAt(time: number): AnimationAction; + setLoop(mode: boolean, repetitions: number): AnimationAction; + setEffectiveWeight(weight: number): AnimationAction; + getEffectiveWeight(): number; + fadeIn(duration: number): AnimationAction; + fadeOut(duration: number): AnimationAction; + crossFadeFrom(fadeOutAction: AnimationAction, duration: number, warp: boolean): AnimationAction; + crossFadeTo(fadeInAction: AnimationAction, duration: number, warp: boolean): AnimationAction; + stopFading(): AnimationAction; + setEffectiveTimeScale(timeScale: number): AnimationAction; + getEffectiveTimeScale(): number; + setDuration(duration: number): AnimationAction; + syncWith(action: AnimationAction): AnimationAction; + halt(duration: number): AnimationAction; + warp(statTimeScale: number, endTimeScale: number, duration: number): AnimationAction; + stopWarping(): AnimationAction; + getMixer(): AnimationMixer; + getClip(): AnimationClip; + getRoot(): any; + } + export class AnimationClip { constructor( name?: string, duration?: number, tracks?: KeyframeTrack[] ); name: string; tracks: KeyframeTrack[]; duration: number; + uuid: string; results: any[]; resetDuration(): void; trim(): AnimationClip; optimize(): AnimationClip; - static CreateFromMorphTargetSequence( name: string, morphTargetSequence: MorphTarget[], fps: number ): AnimationClip; + static CreateFromMorphTargetSequence( name: string, morphTargetSequence: MorphTarget[], fps: number, noLoop: boolean ): AnimationClip; static findByName( clipArray: AnimationClip, name: string ): AnimationClip; - static CreateClipsFromMorphTargetSequences( morphTargets: MorphTarget[], fps: number ): AnimationClip[]; + static CreateClipsFromMorphTargetSequences( morphTargets: MorphTarget[], fps: number, noLoop: boolean ): AnimationClip[]; static parse( json: any ): AnimationClip; static parseAnimation( animation: any, bones: Bone[], nodeName: string ): AnimationClip; static toJSON(): any; } - export class AnimationMixer { + export class AnimationMixer extends EventDispatcher { constructor(root: any); time: number; timeScale: number; - clipAction(clip: AnimationClip, root?: any): any; // returns THREE.AnimationMixer._Action - existingAction(clip: AnimationClip, root?: any): any; /// returns THREE.AnimationMixer._Action + clipAction(clip: AnimationClip, root?: any): AnimationAction; + existingAction(clip: AnimationClip, root?: any): AnimationAction; stopAllAction(clip: AnimationClip, root?: any): AnimationMixer; update(deltaTime: number): AnimationMixer; getRoot(): any; uncacheClip(clip: AnimationClip): void; uncacheRoot(root: any): void; - uncazcheAction(clip: AnimationClip, root?: any): void; + uncacheAction(clip: AnimationClip, root?: any): void; } export class AnimationObjectGroup { @@ -367,6 +413,10 @@ declare namespace THREE { constructor(name: string, times: any[], values: any[]); } + export class ColorKeyframeTrack extends KeyframeTrack { + constructor(name: string, times: any[], values: any[], interpolation: InterpolationModes); + } + export class NumberKeyframeTrack extends KeyframeTrack { constructor(name: string, times: any[], values: any[], interpolation: InterpolationModes); } @@ -411,9 +461,6 @@ declare namespace THREE { * @param vector point to look at */ lookAt(vector: Vector3): void; - - clone(): Camera; - copy(camera?: Camera): Camera; } export class CubeCamera extends Object3D { @@ -445,6 +492,14 @@ declare namespace THREE { constructor(left: number, right: number, top: number, bottom: number, near?: number, far?: number); zoom: number; + view: { + fullWidth: number, + fullHeight: number, + offsetX: number, + offsetY: number, + width: number, + height: number + }; /** * Camera frustum left plane. @@ -480,8 +535,8 @@ declare namespace THREE { * Updates the camera projection matrix. Must be called after change of parameters. */ updateProjectionMatrix(): void; - clone(): OrthographicCamera; - copy(source: OrthographicCamera): OrthographicCamera; + setViewOffset(fullWidth: number, fullHeight: number, offsetX: number, offsetY: number, width: number, height: number): void; + clearViewOffset(): void; toJSON(meta?: any): any; } @@ -503,7 +558,6 @@ declare namespace THREE { */ constructor(fov?: number, aspect?: number, near?: number, far?: number); - focalLength: number; zoom: number; /** @@ -526,14 +580,23 @@ declare namespace THREE { */ far: number; - /** - * Uses focal length (in mm) to estimate and set FOV 35mm (fullframe) camera is used if frame size is not specified. - * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html - * @param focalLength focal length - * @param frameHeight frame size. Default value is 24. - */ - setLens(focalLength: number, frameHeight?: number): void; + focus: number; + view: { + fullWidth: number, + fullHeight: number, + offsetX: number, + offsetY: number, + width: number, + height: number + }; + filmGauge: number; + filmOffset: number; + setFocalLength(focalLength: number): void; + getFocalLength(): number; + getEffectiveFOV(): number; + getFilmWidth(): number; + getFilmHeight(): number; /** * Sets an offset in a larger frustum. This is useful for multi-window or multi-monitor/multi-machine setups. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and the monitors are in grid like this: @@ -572,14 +635,16 @@ declare namespace THREE { * @param height height of subcamera */ setViewOffset(fullWidth: number, fullHeight: number, x: number, y: number, width: number, height: number): void; + clearViewOffset(): void; /** * Updates the camera projection matrix. Must be called after change of parameters. */ updateProjectionMatrix(): void; - clone(): PerspectiveCamera; - copy(source: PerspectiveCamera): PerspectiveCamera; toJSON(meta?: any): any; + + // deprecated + setLens(focalLength: number, frameHeight?: number): void; } export class StereoCamera extends Camera { @@ -598,27 +663,28 @@ declare namespace THREE { * @see src/core/BufferAttribute.js */ export class BufferAttribute { - constructor(array: ArrayLike, itemSize: number); // array parameter should be TypedArray. + constructor(array: ArrayLike, itemSize: number, normalized?: boolean); // array parameter should be TypedArray. uuid: string; array: ArrayLike; itemSize: number; dynamic: boolean; - updateRange: {offset:number, count:number}; + updateRange: {offset: number, count: number}; version: number; + normalized: boolean; needsUpdate: boolean; count: number; setDynamic(dynamic: boolean): BufferAttribute; - clone(): BufferAttribute; - copy(source: BufferAttribute): BufferAttribute; + clone(): this; + copy(source: this): this; copyAt(index1: number, attribute: BufferAttribute, index2: number): BufferAttribute; copyArray(array: ArrayLike): BufferAttribute; - copyColorsArray(colors: {r:number, g:number, b:number}[]): BufferAttribute; - copyIndicesArray(indices: {a:number, b:number, c:number}[]): BufferAttribute; - copyVector2sArray(vectors: {x:number, y:number}[]): BufferAttribute; - copyVector3sArray(vectors: {x:number, y:number, z:number}[]): BufferAttribute; - copyVector4sArray(vectors: {x:number, y:number, z:number, w:number}[]): BufferAttribute; + copyColorsArray(colors: {r: number, g: number, b: number}[]): BufferAttribute; + copyIndicesArray(indices: {a: number, b: number, c: number}[]): BufferAttribute; + copyVector2sArray(vectors: {x: number, y: number}[]): BufferAttribute; + copyVector3sArray(vectors: {x: number, y: number, z: number}[]): BufferAttribute; + copyVector4sArray(vectors: {x: number, y: number, z: number, w: number}[]): BufferAttribute; set(value: ArrayLike, offset?: number): BufferAttribute; getX(index: number): number; setX(index: number, x: number): BufferAttribute; @@ -631,7 +697,6 @@ declare namespace THREE { setXY(index: number, x: number, y: number): BufferAttribute; setXYZ(index: number, x: number, y: number, z: number): BufferAttribute; setXYZW(index: number, x: number, y: number, z: number, w: number): BufferAttribute; - clone(): BufferAttribute; length: number; // deprecated, use count } @@ -682,7 +747,7 @@ declare namespace THREE { * * @see src/core/BufferGeometry.js */ - export class BufferGeometry { + export class BufferGeometry extends EventDispatcher { /** * This creates a new BufferGeometry. It also sets several properties to an default value. */ @@ -700,11 +765,9 @@ declare namespace THREE { index: BufferAttribute; attributes: BufferAttribute|InterleavedBufferAttribute[]; morphAttributes: any; - drawcalls: any; // deprecated, use groups - offsets: any; // deprecated, use groups groups: {start: number, count: number, materialIndex?: number}[]; boundingBox: Box3; - boundingSphere: BoundingSphere; + boundingSphere: Sphere; drawRange: { start: number, count: number }; getIndex(): BufferAttribute; @@ -734,8 +797,8 @@ declare namespace THREE { center(): Vector3; - setFromObject(object: Object3D) : void; - updateFromObject(object: Object3D) : void; + setFromObject(object: Object3D): void; + updateFromObject(object: Object3D): void; fromGeometry(geometry: Geometry, settings?: any): BufferGeometry; @@ -764,8 +827,8 @@ declare namespace THREE { toNonIndexed(): BufferGeometry; toJSON(): any; - clone(): BufferGeometry; - copy(source: BufferGeometry): BufferGeometry; + clone(): this; + copy(source: this): this; /** * Disposes the object from memory. @@ -773,17 +836,14 @@ declare namespace THREE { */ dispose(): void; - // EventDispatcher mixins - addEventListener(type: string, listener: (event: Event) => void ): void; - hasEventListener(type: string, listener: (event: Event) => void): void; - removeEventListener(type: string, listener: (event: Event) => void): void; - dispatchEvent(event: { type: string; [attachment: string]: any; }): void; + // deprecated + drawcalls: any; + offsets: any; - addIndex(index: any): void; // deprecated, use setIndex() - addAttribute(name: any, array: any, itemSize: any): any; // deprecated - addDrawCall(start: any, count: any, indexOffset?: any): void; // deprecated, use addGroup() - clearDrawCalls(): void; // deprecated, use clearGroups() - computeFaceNormals(): void; // deprecated + addIndex(index: any): void; + addDrawCall(start: any, count: any, indexOffset?: any): void; + clearDrawCalls(): void; + addAttribute(name: any, array: any, itemSize: any): any; } /** @@ -849,7 +909,7 @@ declare namespace THREE { /** * @see src/core/DirectGeometry.js */ - export class DirectGeometry { + export class DirectGeometry extends EventDispatcher { constructor(); id: number; @@ -867,7 +927,7 @@ declare namespace THREE { skinWeights: number[]; skinIndices: number[]; boundingBox: Box3; - boundingSphere: BoundingSphere; + boundingSphere: Sphere; verticesNeedUpdate: boolean; normalsNeedUpdate: boolean; colorsNeedUpdate: boolean; @@ -919,8 +979,6 @@ declare namespace THREE { */ constructor(); - apply(object: any): void; - /** * Adds a listener to an event type. * @param type The type of the listener that gets removed. @@ -947,6 +1005,9 @@ declare namespace THREE { * @param type The type of event that gets fired. */ dispatchEvent(event: { type: string; [attachment: string]: any; }): void; + + // deprecated + apply(target: any): void; } export interface Event { @@ -1018,8 +1079,8 @@ declare namespace THREE { */ materialIndex: number; - clone(): Face3; - copy(source: Face3): Face3; + clone(): this; + copy(source: this): this; } export class Face4 extends Face3 {} // deprecated, use Face3 @@ -1039,10 +1100,6 @@ declare namespace THREE { normals: Vector3[]; } - export interface BoundingSphere { - radius: number; - } - export let GeometryIdCount: number; /** @@ -1058,7 +1115,7 @@ declare namespace THREE { * * @see https://github.com/mrdoob/three.js/blob/master/src/core/Geometry.js */ - export class Geometry { + export class Geometry extends EventDispatcher { constructor(); /** @@ -1142,7 +1199,7 @@ declare namespace THREE { /** * Bounding sphere. */ - boundingSphere: BoundingSphere; + boundingSphere: Sphere; /** * Set to true if the vertices array has been updated. @@ -1244,9 +1301,9 @@ declare namespace THREE { /** * Creates a new clone of the Geometry. */ - clone(): Geometry; + clone(): this; - copy(source: Geometry): Geometry; + copy(source: this): this; /** * Removes The object from memory. @@ -1255,7 +1312,7 @@ declare namespace THREE { dispose(): void; - //These properties do not exist in a normal Geometry class, but if you use the instance that was passed by JSONLoader, it will be added. + // These properties do not exist in a normal Geometry class, but if you use the instance that was passed by JSONLoader, it will be added. bones: Bone[]; animation: AnimationClip; animations: AnimationClip[]; @@ -1268,7 +1325,7 @@ declare namespace THREE { } export namespace GeometryUtils { // deprecated - export function merge(goemetry1: any, goemetry2: any, materialIndexOffset?: any): any; // deprecated, use geometry.merge( geometry2, matrix, materialIndexOffset ) + export function merge(geometry1: any, geometry2: any, materialIndexOffset?: any): any; // deprecated, use geometry.merge( geometry2, matrix, materialIndexOffset ) export function center(geometry: any): any; // deprecated, use geometry.center() } @@ -1279,9 +1336,6 @@ declare namespace THREE { constructor(data: ArrayLike, itemSize: number, meshPerAttribute?: number); meshPerAttribute: number; - - clone(): InstancedBufferAttribute; - copy(source: InstancedBufferAttribute): InstancedBufferAttribute; } /** @@ -1290,12 +1344,10 @@ declare namespace THREE { export class InstancedBufferGeometry extends BufferGeometry { constructor(); - groups: {start:number, count:number, instances:number}[]; + groups: {start: number, count: number, instances: number}[]; maxInstancedCount: number; addGroup(start: number, count: number, instances: number): void; - clone(): InstancedBufferGeometry; - copy(source: InstancedBufferGeometry): InstancedBufferGeometry; } /** @@ -1314,11 +1366,11 @@ declare namespace THREE { needsUpdate: boolean; setDynamic(dynamic: boolean): InterleavedBuffer; - clone(): InterleavedBuffer; - copy(source: InterleavedBuffer): InterleavedBuffer; + clone(): this; + copy(source: this): this; copyAt(index1: number, attribute: InterleavedBufferAttribute, index2: number): InterleavedBuffer; set(value: ArrayLike, index: number): InterleavedBuffer; - clone(): InterleavedBuffer; + clone(): this; } /** @@ -1328,22 +1380,21 @@ declare namespace THREE { constructor(array: ArrayLike, stride: number, meshPerAttribute?: number); meshPerAttribute: number; - - clone(): InstancedInterleavedBuffer; - copy(source: InstancedInterleavedBuffer): InstancedInterleavedBuffer; } /** * @see src/core/InterleavedBufferAttribute.js */ export class InterleavedBufferAttribute { - constructor(interleavedBuffer: InterleavedBuffer, itemSize: number, offset: number); + constructor(interleavedBuffer: InterleavedBuffer, itemSize: number, offset: number, normalized: boolean); uuid: string; data: InterleavedBuffer; itemSize: number; offset: number; count: number; + normalized: boolean; + array: any[]; getX(index: number): number; setX(index: number, x: number): InterleavedBufferAttribute; @@ -1365,7 +1416,7 @@ declare namespace THREE { /** * Base class for scene graph objects */ - export class Object3D { + export class Object3D extends EventDispatcher { constructor(); /** @@ -1409,7 +1460,6 @@ declare namespace THREE { * Object's local rotation (Euler angles), in radians. */ rotation: Euler; - eulerOrder: string; // deprecated, use rotation.order /** * Global rotation. @@ -1425,11 +1475,6 @@ declare namespace THREE { normalMatrix: Matrix3; - /** - * When this is set, then the rotationMatrix gets calculated every frame. - */ - rotationAutoUpdate: boolean; - /** * Local transform. */ @@ -1539,7 +1584,6 @@ declare namespace THREE { * @param distance The distance to translate. */ translateOnAxis(axis: Vector3, distance: number): Object3D; - translate(distance: number, axis: Vector3): Object3D; // deprecated, use translateOnAxis(axis, distance) /** * Translates object along x axis by distance. @@ -1627,22 +1671,19 @@ declare namespace THREE { toJSON(meta?: { geometries: any, materials: any, textures: any, images: any }): any; - clone(recursive?: boolean): Object3D; + clone(recursive?: boolean): this; /** * * @param object * @param recursive */ - copy(source: Object3D, recursive?: boolean): Object3D; + copy(source: this, recursive?: boolean): this; - // EventDispatcher mixins - addEventListener(type: string, listener: (event: Event) => void ): void; - hasEventListener(type: string, listener: (event: Event) => void): void; - removeEventListener(type: string, listener: (event: Event) => void): void; - dispatchEvent(event: { type: string; [attachment: string]: any; }): void; - - getChildByName(name: string): Object3D; // deprecated, use getObjectByName() + // deprecated + eulerOrder: string; + getChildByName(name: string): Object3D; + translate(distance: number, axis: Vector3): Object3D; } export interface Intersection { @@ -1674,7 +1715,7 @@ declare namespace THREE { linePrecision: number; set(origin: Vector3, direction: Vector3): void; - setFromCamera(coords: { x: number; y: number;}, camera: Camera ): void; + setFromCamera(coords: { x: number; y: number; }, camera: Camera ): void; intersectObject(object: Object3D, recursive?: boolean): Intersection[]; intersectObjects(objects: Object3D[], recursive?: boolean): Intersection[]; } @@ -1692,9 +1733,9 @@ declare namespace THREE { } export class Font { - constructor(data: any); + constructor(jsondata: string); - data: any; + data: string; generateShapes(text: string, size: number, divisions: number): any[]; } @@ -1721,9 +1762,6 @@ declare namespace THREE { shadowBias: any; // deprecated, use shadow.bias shadowMapWidth: any; // deprecated, use shadow.mapSize.width shadowMapHeight: any; // deprecated, use shadow.mapSize.height - - copy(source: Light): Light; - clone(recursive?: boolean): Light; } export class LightShadow { @@ -1736,8 +1774,9 @@ declare namespace THREE { map: RenderTarget; matrix: Matrix4; - copy(source: LightShadow): LightShadow; - clone(recursive?: boolean): LightShadow; + copy(source: this): this; + clone(recursive?: boolean): this; + toJSON(): any; } /** @@ -1757,9 +1796,6 @@ declare namespace THREE { constructor(hex?: number|string, intensity?: number); castShadow: boolean; - - copy(source: AmbientLight): AmbientLight; - clone(recursive?: boolean): AmbientLight; } /** @@ -1788,19 +1824,15 @@ declare namespace THREE { intensity: number; shadow: LightShadow; - - copy(source: DirectionalLight): DirectionalLight; - clone(recursive?: boolean): HemisphereLight; } + export class DirectionalLightShadow extends LightShadow {} + export class HemisphereLight extends Light { constructor(skyColorHex?: number|string, groundColorHex?: number|string, intensity?: number); groundColor: Color; intensity: number; - - copy(source: HemisphereLight): HemisphereLight; - clone(recursive?: boolean): HemisphereLight; } /** @@ -1829,9 +1861,6 @@ declare namespace THREE { decay: number; shadow: LightShadow; power: number; - - copy(source: PointLight): PointLight; - clone(recursive?: boolean): PointLight; } /** @@ -1871,11 +1900,13 @@ declare namespace THREE { exponent: number; decay: number; - shadow: LightShadow; + shadow: SpotLightShadow; power: number; + penumbra: number; + } - clone(recursive?: boolean): SpotLight; - copy(source: PointLight): SpotLight; + export class SpotLightShadow extends LightShadow { + update(light: Light): void; } // Loaders ////////////////////////////////////////////////////////////////////////////////// @@ -1927,7 +1958,7 @@ declare namespace THREE { static Handlers: LoaderHandler; } - export interface LoaderHandler{ + export interface LoaderHandler { handlers: (RegExp | Loader)[]; add(regex: RegExp, loader: Loader): void; @@ -1943,9 +1974,9 @@ declare namespace THREE { withCredentials: boolean; load(url: string, onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): any; - setPath(path: string): void; - setResponseType(responseType: string): void; - setWithCredentials(withCredentials: boolean): void; + setPath(path: string): XHRLoader; + setResponseType(responseType: string): XHRLoader; + setWithCredentials(withCredentials: boolean): XHRLoader; } export class FontLoader { @@ -1954,6 +1985,7 @@ declare namespace THREE { manager: LoadingManager; load(url: string, onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + parse(json: string): Font; } /** @@ -1965,6 +1997,7 @@ declare namespace THREE { manager: LoadingManager; crossOrigin: string; + withCredentials: string; path: string; /** @@ -1972,8 +2005,9 @@ declare namespace THREE { * @param url */ load(url: string, onLoad?: (image: HTMLImageElement) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): HTMLImageElement; - setCrossOrigin(crossOrigin: string): void; - setPath(value: any): void; + setCrossOrigin(crossOrigin: string): ImageLoader; + setWithCredentials(value: string): ImageLoader; + setPath(value: string): ImageLoader; } /** @@ -1984,7 +2018,6 @@ declare namespace THREE { manager: LoadingManager; withCredentials: boolean; - statusDomElement: HTMLElement; // readonly and deprecated load(url: string, onLoad?: (geometry: Geometry, materials: Material[]) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; setTexturePath( value: string ): void; @@ -2073,6 +2106,7 @@ declare namespace THREE { manager: LoadingManager; crossOrigin: string; + withCredentials: string; path: string; /** @@ -2081,8 +2115,9 @@ declare namespace THREE { * @param url */ load(url: string, onLoad?: (texture: Texture) => void): Texture; - setCrossOrigin(crossOrigin: string): void; - setPath(path: string): void; + setCrossOrigin(crossOrigin: string): TextureLoader; + setWithCredentials(value: string): TextureLoader; + setPath(path: string): TextureLoader; } export class CubeTextureLoader { @@ -2093,8 +2128,8 @@ declare namespace THREE { path: string; load(urls: Array, onLoad?: (texture: CubeTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; - setCrossOrigin(crossOrigin: string): void; - setPath(path: string): void; + setCrossOrigin(crossOrigin: string): CubeTextureLoader; + setPath(path: string): CubeTextureLoader; } export class BinaryTextureLoader { @@ -2113,7 +2148,13 @@ declare namespace THREE { path: string; load(url: string, onLoad: (texture: CompressedTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; - setPath(path: string): void; + setPath(path: string): CompressedTextureLoader; + } + + export class AudioLoader { + constructor(manager?: LoadingManager); + + load(url: string, onLoad: Function, onPrgress: Function, onError: Function): void; } export namespace Cache { @@ -2153,12 +2194,16 @@ declare namespace THREE { premultipliedAlpha?: boolean; overdraw?: number; visible?: boolean; + fog?: boolean; + lights?: boolean; + shading?: Shading; + vertexColors?: Colors; } /** * Materials describe the appearance of objects. They are defined in a (mostly) renderer-independent way, so you don't have to rewrite materials if you decide to use a different renderer. */ - export class Material { + export class Material extends EventDispatcher { constructor(); /** @@ -2229,6 +2274,9 @@ declare namespace THREE { */ depthWrite: boolean; + clippingPlanes: any; + clipShadows: boolean; + colorWrite: boolean; precision: any; @@ -2271,20 +2319,20 @@ declare namespace THREE { */ needsUpdate: boolean; - warpRGB: Color; // deprecated, returns a new Color intance + fog: boolean; + lights: boolean; + shading: Shading; + vertexColors: Colors; setValues(parameters: MaterialParameters): void; toJSON(meta?: any): any; - clone(): Material; - copy(source: Material): Material; + clone(): this; + copy(source: this): this; update(): void; dispose(): void; - // EventDispatcher mixins - addEventListener(type: string, listener: (event: Event) => void ): void; - hasEventListener(type: string, listener: (event: Event) => void): void; - removeEventListener(type: string, listener: (event: Event) => void): void; - dispatchEvent(event: { type: string; [attachment: string]: any; }): void; + // deprecated + warpRGB: Color; } export interface LineBasicMaterialParameters extends MaterialParameters { @@ -2292,9 +2340,6 @@ declare namespace THREE { linewidth?: number; linecap?: string; linejoin?: string; - blending?: Blending; - vertexColors?: Colors; - fog?: boolean; } export class LineBasicMaterial extends Material { @@ -2304,13 +2349,8 @@ declare namespace THREE { linewidth: number; linecap: string; linejoin: string; - blending: Blending; - vertexColors: Colors; - fog: boolean; setValues(parameters: LineBasicMaterialParameters): void; - clone(): LineBasicMaterial; - copy(source: LineBasicMaterial): LineBasicMaterial; } export interface LineDashedMaterialParameters extends MaterialParameters { @@ -2319,9 +2359,6 @@ declare namespace THREE { scale?: number; dashSize?: number; gapSize?: number; - blending?: Blending; - vertexColors?: Colors; - fog?: boolean; } export class LineDashedMaterial extends Material { @@ -2332,13 +2369,8 @@ declare namespace THREE { scale: number; dashSize: number; gapSize: number; - blending: Blending; - vertexColors: Colors; - fog: boolean; setValues(parameters: LineDashedMaterialParameters): void; - clone(): LineDashedMaterial; - copy(source: LineDashedMaterial): LineDashedMaterial; } /** @@ -2357,15 +2389,12 @@ declare namespace THREE { reflectivity?: number; refractionRatio?: number; shading?: Shading; - blending?: Blending; wireframe?: boolean; wireframeLinewidth?: number; wireframeLinecap?: string; wireframeLinejoin?: string; - vertexColors?: Colors; skinning?: boolean; morphTargets?: boolean; - fog?: boolean; } export class MeshBasicMaterial extends Material { @@ -2381,20 +2410,15 @@ declare namespace THREE { combine: Combine; reflectivity: number; refractionRatio: number; - fog: boolean; shading: Shading; - blending: Blending; wireframe: boolean; wireframeLinewidth: number; wireframeLinecap: string; wireframeLinejoin: string; - vertexColors: Colors; skinning: boolean; morphTargets: boolean; setValues(parameters: MeshBasicMaterialParameters): void; - clone(): MeshBasicMaterial; - copy(source: MeshBasicMaterial): MeshBasicMaterial; } export interface MeshDepthMaterialParameters extends MaterialParameters { @@ -2409,8 +2433,6 @@ declare namespace THREE { wireframeLinewidth: number; setValues(parameters: MeshDepthMaterialParameters): void; - clone(): MeshDepthMaterial; - copy(source: MeshDepthMaterial): MeshDepthMaterial; } export interface MeshLambertMaterialParameters extends MaterialParameters { @@ -2429,13 +2451,10 @@ declare namespace THREE { combine?: Combine; reflectivity?: number; refractionRatio?: number; - fog?: boolean; - blending?: Blending; wireframe?: boolean; wireframeLinewidth?: number; wireframeLinecap?: string; wireframeLinejoin?: string; - vertexColors?: Colors; skinning?: boolean; morphTargets?: boolean; morphNormals?: boolean; @@ -2445,7 +2464,7 @@ declare namespace THREE { constructor(parameters?: MeshLambertMaterialParameters); color: Color; - emissive: Color; + emissive: number|string; emissiveIntensity: number; emissiveMap: Texture; map: Texture; @@ -2459,20 +2478,15 @@ declare namespace THREE { combine: Combine; reflectivity: number; refractionRatio: number; - fog: boolean; - blending: Blending; wireframe: boolean; wireframeLinewidth: number; wireframeLinecap: string; wireframeLinejoin: string; - vertexColors: Colors; skinning: boolean; morphTargets: boolean; morphNormals: boolean; setValues(parameters: MeshLambertMaterialParameters): void; - clone(): MeshLambertMaterial; - copy(source: MeshLambertMaterial): MeshLambertMaterial; } export interface MeshStandardMaterialParameters extends MaterialParameters { @@ -2500,20 +2514,17 @@ declare namespace THREE { envMap?: Texture; envMapIntensity?: number; refractionRatio?: number; - shading?: Shading; - blending?: Blending; wireframe?: boolean; wireframeLinewidth?: number; - vertexColors?: Colors; skinning?: boolean; morphTargets?: boolean; morphNormals?: boolean; - fog?: boolean; } export class MeshStandardMaterial extends Material { constructor(parameters?: MeshStandardMaterialParameters); + defines: any; color: Color; roughness: number; metalness: number; @@ -2538,38 +2549,13 @@ declare namespace THREE { envMap: Texture; envMapIntensity: number; refractionRatio: number; - shading: Shading; - blending: Blending; wireframe: boolean; wireframeLinewidth: number; - vertexColors: Colors; skinning: boolean; morphTargets: boolean; morphNormals: boolean; - fog: boolean; setValues(parameters: MeshStandardMaterialParameters): void; - clone(): MeshStandardMaterial; - copy(source: MeshStandardMaterial): MeshStandardMaterial; - } - - export interface MeshPhysicalMaterialParameters extends MeshStandardMaterialParameters { - reflectivity?: number; - clearCoat?: number; - clearCoatRoughness?: number; - } - - export class MeshPhysicalMaterial extends MeshStandardMaterial { - constructor(parameters?: MeshPhysicalMaterialParameters); - - defines: any; - reflectivity: number; - clearCoat: number; - clearCoatRoughness: number; - - setValues(parameters: MeshPhysicalMaterialParameters): void; - clone(): MeshPhysicalMaterial; - copy(source: MeshPhysicalMaterial): MeshPhysicalMaterial; } export interface MeshNormalMaterialParameters extends MaterialParameters { @@ -2588,8 +2574,6 @@ declare namespace THREE { morphTargets: boolean; setValues(parameters: MeshNormalMaterialParameters): void; - clone(): MeshNormalMaterial; - copy(source: MeshNormalMaterial): MeshNormalMaterial; } export interface MeshPhongMaterialParameters extends MaterialParameters { @@ -2619,17 +2603,13 @@ declare namespace THREE { combine?: Combine; reflectivity?: number; refractionRatio?: number; - shading?: Shading; - blending?: Blending; wireframe?: boolean; wireframeLinewidth?: number; wireframeLinecap?: string; wireframeLinejoin?: string; - vertexColors?: Colors; skinning?: boolean; morphTargets?: boolean; morphNormals?: boolean; - fog?: boolean; } export class MeshPhongMaterial extends Material { @@ -2659,22 +2639,31 @@ declare namespace THREE { combine: Combine; reflectivity: number; refractionRatio: number; - fog: boolean; - shading: Shading; - blending: Blending; wireframe: boolean; wireframeLinewidth: number; wireframeLinecap: string; wireframeLinejoin: string; - vertexColors: Colors; skinning: boolean; morphTargets: boolean; morphNormals: boolean; metal: boolean; // deprecated setValues(parameters: MeshPhongMaterialParameters): void; - clone(): MeshPhongMaterial; - copy(source: MeshPhongMaterial): MeshPhongMaterial; + } + + export interface MeshPhysicalMaterialParameters extends MeshStandardMaterialParameters { + reflectivity?: number; + clearCoat?: number; + clearCoatRoughness?: number; + } + + export class MeshPhysicalMaterial extends MeshStandardMaterial { + constructor(parameters: MeshPhysicalMaterialParameters); + + defines: any; + reflectivity: number; + clearCoat: number; + clearCoatRoughness: number; } // MultiMaterial does not inherit the Material class in the original code. However, it should treat as Material class. @@ -2685,7 +2674,6 @@ declare namespace THREE { materials: Material[]; toJSON(meta: any): any; - clone(): MultiMaterial; } export class MeshFaceMaterial extends MultiMaterial {} // deprecated, use MultiMaterial @@ -2695,9 +2683,6 @@ declare namespace THREE { map?: Texture; size?: number; sizeAttenuation?: boolean; - blending?: Blending; - vertexColors?: Colors; - fog?: boolean; } export class PointsMaterial extends Material { @@ -2707,31 +2692,24 @@ declare namespace THREE { map: Texture; size: number; sizeAttenuation: boolean; - blending: Blending; - vertexColors: boolean; - fog: boolean; setValues(parameters: PointsMaterialParameters): void; - clone(): PointsMaterial; - copy(source: PointsMaterial): PointsMaterial; } - export class PointCloudMaterial extends PointsMaterial {} // deprecated, use PointsMaterial - export class ParticleBasicMaterial extends PointsMaterial {} // deprecated, use PointsMaterial - export class ParticleSystemMaterial extends PointsMaterial {} // deprecated, use PointsMaterial + export class PointCloudMaterial extends PointsMaterial {} // deprecated + export class ParticleBasicMaterial extends PointsMaterial {} // deprecated + export class ParticleSystemMaterial extends PointsMaterial {} // deprecated export interface ShaderMaterialParameters extends MaterialParameters { defines?: any; uniforms?: any; vertexShader?: string; fragmentShader?: string; - shading?: Shading; lineWidth?: number; wireframe?: boolean; wireframeLinewidth?: number; - fog?: boolean; lights?: boolean; - vertexColors?: Colors; + clipping?: boolean; skinning?: boolean; morphTargets?: boolean; morphNormals?: boolean; @@ -2741,16 +2719,14 @@ declare namespace THREE { constructor(parameters?: ShaderMaterialParameters); defines: any; - uniforms: any; + uniforms: any; // type should be { [uniform: string]: { value: any }; }; but gives "Index signature is missing in type" error during compilation vertexShader: string; fragmentShader: string; - shading: Shading; linewidth: number; wireframe: boolean; wireframeLinewidth: number; - fog: boolean; lights: boolean; - vertexColors: Colors; + clipping: boolean; skinning: boolean; morphTargets: boolean; morphNormals: boolean; @@ -2760,8 +2736,6 @@ declare namespace THREE { index0AttributeName: string; setValues(parameters: ShaderMaterialParameters): void; - clone(): ShaderMaterial; - copy(source: ShaderMaterial): ShaderMaterial; toJSON(meta: any): any; } @@ -2773,7 +2747,6 @@ declare namespace THREE { color?: number|string; map?: Texture; rotation?: number; - fog?: boolean; } export class SpriteMaterial extends Material { @@ -2782,11 +2755,12 @@ declare namespace THREE { color: Color; map: Texture; rotation: number; - fog: boolean; setValues(parameters: SpriteMaterialParameters): void; - clone(): SpriteMaterial; - copy(source: SpriteMaterial): SpriteMaterial; + } + + export class ShadowMaterial extends ShaderMaterial { + constructor(parameters?: ShaderMaterialParameters); } // Math ////////////////////////////////////////////////////////////////////////////////// @@ -2800,10 +2774,9 @@ declare namespace THREE { set(min: Vector2, max: Vector2): Box2; setFromPoints(points: Vector2[]): Box2; setFromCenterAndSize(center: Vector2, size: Vector2): Box2; - clone(): Box2; - copy(box: Box2): Box2; + clone(): this; + copy(box: this): this; makeEmpty(): Box2; - empty(): any; // deprecated, use isEmpty() isEmpty(): boolean; center(optionalTarget?: Vector2): Vector2; size(optionalTarget?: Vector2): Vector2; @@ -2821,6 +2794,7 @@ declare namespace THREE { translate(offset: Vector2): Box2; equals(box: Box2): boolean; + empty(): any; // deprecated, use isEmpty() isIntersectionBox(b: any): any; // deprecated, use intersectsBox() } @@ -2831,12 +2805,12 @@ declare namespace THREE { min: Vector3; set(min: Vector3, max: Vector3): Box3; - setFromArray(array: number[]): Box3; + setFromArray(array: ArrayLike): Box3; setFromPoints(points: Vector3[]): Box3; setFromCenterAndSize(center: Vector3, size: Vector3): Box3; setFromObject(object: Object3D): Box3; - clone(): Box3; - copy(box: Box3): Box3; + clone(): this; + copy(box: this): this; makeEmpty(): Box3; isEmpty(): boolean; center(optionalTarget?: Vector3): Vector3; @@ -2932,13 +2906,13 @@ declare namespace THREE { /** * Clones this color. */ - clone(): Color; + clone(): this; /** * Copies given color. * @param color Color to copy. */ - copy(color: Color): Color; + copy(color: this): this; /** * Copies given color making conversion from gamma to linear space. @@ -2985,6 +2959,7 @@ declare namespace THREE { add(color: Color): Color; addColors(color1: Color, color2: Color): Color; addScalar(s: number): Color; + sub(color: Color): Color; multiply(color: Color): Color; multiplyScalar(s: number): Color; lerp(color: Color, alpha: number): Color; @@ -3153,10 +3128,10 @@ declare namespace THREE { onChangeCallback: Function; set(x: number, y: number, z: number, order?: string): Euler; - clone(): Euler; - copy(euler: Euler): Euler; + clone(): this; + copy(euler: this): this; setFromRotationMatrix(m: Matrix4, order?: string, update?: boolean): Euler; - setFromQuaternion(q:Quaternion, order?: string, update?: boolean): Euler; + setFromQuaternion(q: Quaternion, order?: string, update?: boolean): Euler; setFromVector3( v: Vector3, order?: string ): Euler; reorder(newOrder: string): Euler; equals(euler: Euler): boolean; @@ -3181,10 +3156,11 @@ declare namespace THREE { planes: Plane[]; set(p0?: number, p1?: number, p2?: number, p3?: number, p4?: number, p5?: number): Frustum; - clone(): Frustum; - copy(frustum: Frustum): Frustum; + clone(): this; + copy(frustum: this): this; setFromMatrix(m: Matrix4): Frustum; intersectsObject(object: Object3D): boolean; + intersectsObject(sprite: Sprite): boolean; intersectsSphere(sphere: Sphere): boolean; intersectsBox(box: Box3): boolean; containsPoint(point: Vector3): boolean; @@ -3197,8 +3173,8 @@ declare namespace THREE { end: Vector3; set(start?: Vector3, end?: Vector3): Line3; - clone(): Line3; - copy(line: Line3): Line3; + clone(): this; + copy(line: this): this; center(optionalTarget?: Vector3): Vector3; delta(optionalTarget?: Vector3): Vector3; distanceSq(): number; @@ -3215,6 +3191,9 @@ declare namespace THREE { * @see src/math/Math.js */ export namespace Math { + export const DEG2RAD: number; + export const RAD2DEG: number; + export function generateUUID(): string; /** @@ -3291,7 +3270,7 @@ declare namespace THREE { /** * copy(m:T):T; */ - copy(m: Matrix): Matrix; + copy(m: this): this; /** * multiplyScalar(s:number):T; @@ -3313,7 +3292,7 @@ declare namespace THREE { /** * clone():T; */ - clone(): Matrix; + clone(): this; } /** @@ -3332,30 +3311,19 @@ declare namespace THREE { set(n11: number, n12: number, n13: number, n21: number, n22: number, n23: number, n31: number, n32: number, n33: number): Matrix3; identity(): Matrix3; - clone(): Matrix3; - copy(m: Matrix3): Matrix3; - setFromMatix4(m: Matrix4): Matrix3; - - /** - * @deprecated Use applyToVector3Array() - */ - multiplyVector3Array(a: any): any; - applyToVector3Array(array: number[], offset?: number, length?: number): number[]; + clone(): this; + copy(m: this): this; + setFromMatrix4(m: Matrix4): Matrix3; + applyToVector3Array(array: ArrayLike, offset?: number, length?: number): ArrayLike; applyToBuffer(buffer: BufferAttribute, offset?: number, length?: number): BufferAttribute; multiplyScalar(s: number): Matrix3; determinant(): number; getInverse(matrix: Matrix3, throwOnDegenerate?: boolean): Matrix3; - /** - * @deprecated No longer takes a Matrix4 argument. - */ - getInverse(matrix: Matrix4, throwOnDegenerate?: boolean): Matrix3; - /** * Transposes this matrix in place. */ transpose(): Matrix3; - flattenToArrayOffset(array: number[], offset: number): number[]; getNormalMatrix(matrix4: Matrix4): Matrix3; /** @@ -3365,10 +3333,11 @@ declare namespace THREE { fromArray(array: number[]): Matrix3; toArray(): number[]; - /** - * @deprecated Use vector.applyMatrix3( matrix ) - */ + // deprecated multiplyVector3(vector: Vector3): any; + multiplyVector3Array(a: any): any; + getInverse(matrix: Matrix4, throwOnDegenerate?: boolean): Matrix3; + flattenToArrayOffset(array: number[], offset: number): number[]; } /** @@ -3406,9 +3375,8 @@ declare namespace THREE { * Resets this matrix to identity. */ identity(): Matrix4; - clone(): Matrix4; - copy(m: Matrix4): Matrix4; - extractPosition(m: Matrix4): Matrix4; // deprecated, use copyPosition() + clone(): this; + copy(m: this): this; copyPosition(m: Matrix4): Matrix4; extractBasis( xAxis: Vector3, yAxis: Vector3, zAxis: Vector3): Matrix4; makeBasis( xAxis: Vector3, yAxis: Vector3, zAxis: Vector3): Matrix4; @@ -3418,7 +3386,6 @@ declare namespace THREE { */ extractRotation(m: Matrix4): Matrix4; makeRotationFromEuler(euler: Euler): Matrix4; - setRotationFromQuaternion(q: Quaternion): Matrix4; // deprecated, use makeRotationFromQuaternion() makeRotationFromQuaternion(q: Quaternion): Matrix4; /** * Constructs a rotation matrix, looking from eye towards center with defined up vector. @@ -3430,6 +3397,8 @@ declare namespace THREE { */ multiply(m: Matrix4): Matrix4; + premultiply(m: Matrix4): Matrix4; + /** * Sets this matrix to a x b. */ @@ -3445,8 +3414,7 @@ declare namespace THREE { * Multiplies this matrix by s. */ multiplyScalar(s: number): Matrix4; - multiplyVector3Array(array: number[]): number[]; // deprecated, use applyToVector3Array() - applyToVector3Array(array: number[], offset?: number, length?: number): number[]; + applyToVector3Array(array: ArrayLike, offset?: number, length?: number): ArrayLike; applyToBuffer( buffer: BufferAttribute, offset?: number, length?: number): BufferAttribute; /** * Computes determinant of this matrix. @@ -3459,10 +3427,7 @@ declare namespace THREE { */ transpose(): Matrix4; - /** - * Flattens this matrix into supplied flat array starting from offset position in the array. - */ - flattenToArrayOffset(array: number[], offset: number): number[]; + /** * Sets the position component for this matrix from vector v. @@ -3551,26 +3516,15 @@ declare namespace THREE { fromArray(array: number[]): Matrix4; toArray(): number[]; - /** - * @deprecated Use Vector3.setFromMatrixPosition( matrix ) - */ - getPosition(): any; - /** - * @deprecated Use Vector3.applyMatrix4( matrix ) or Vector3.applyProjection( matrix ) - */ + // deprecated + extractPosition(m: Matrix4): Matrix4; + setRotationFromQuaternion(q: Quaternion): Matrix4; multiplyVector3(v: any): any; - /** - * @deprecated Use Vector3.applyMatrix4( matrix ) - */ multiplyVector4(v: any): any; - /** - * @deprecated Use Vector3.transformDirection( matrix ) - */ + multiplyVector3Array(array: number[]): number[]; rotateAxis(v: any): void; - /** - * @deprecated Use Vector3.applyMatrix( matrix ) - */ crossVector(v: any): void; + flattenToArrayOffset(array: number[], offset: number): number[]; } export class Plane { @@ -3583,8 +3537,8 @@ declare namespace THREE { setComponents(x: number, y: number, z: number, w: number): Plane; setFromNormalAndCoplanarPoint(normal: Vector3, point: Vector3): Plane; setFromCoplanarPoints(a: Vector3, b: Vector3, c: Vector3): Plane; - clone(): Plane; - copy(plane: Plane): Plane; + clone(): this; + copy(plane: this): this; normalize(): Plane; negate(): Plane; distanceToPoint(point: Vector3): number; @@ -3599,15 +3553,16 @@ declare namespace THREE { translate(offset: Vector3): Plane; equals(plane: Plane): boolean; - isIntersectionLine(l: any): any; // deprecated, use instersectsLine() + // deprecated + isIntersectionLine(l: any): any; } export class Spherical { constructor(radius?: number, phi?: number, theta?: number); - set(radius: number, phi: number, theta: number): void; - clone(): Spherical; - copy(other: Spherical): Spherical; + set(radius: number, phi: number, theta: number): Spherical; + clone(): this; + copy(other: this): this; makeSafe(): void; setFromVector3(vec3: Vector3): Spherical; } @@ -3643,12 +3598,12 @@ declare namespace THREE { /** * Clones this quaternion. */ - clone(): Quaternion; + clone(): this; /** * Copies values of q to this quaternion. */ - copy(q: Quaternion): Quaternion; + copy(q: this): this; /** * Sets this quaternion from rotation specified by Euler angles. @@ -3690,6 +3645,7 @@ declare namespace THREE { * Multiplies this quaternion by b. */ multiply(q: Quaternion): Quaternion; + premultiply(q: Quaternion): Quaternion; /** * Sets this quaternion to a x b @@ -3697,7 +3653,6 @@ declare namespace THREE { */ multiplyQuaternions(a: Quaternion, b: Quaternion): Quaternion; - multiplyVector3(v: any): any; // deprecated, use vector.applyQuaternion( quaternion ) slerp(qb: Quaternion, t: number): Quaternion; equals(v: Quaternion): boolean; @@ -3716,6 +3671,9 @@ declare namespace THREE { static slerp(qa: Quaternion, qb: Quaternion, qm: Quaternion, t: number): Quaternion; static slerpFlat(dst: number[], dstOffset: number, src0: number[], srcOffset: number, src1: number[], stcOffset1: number, t: number): Quaternion; + + // deprecated + multiplyVector3(v: any): any; } export class Ray { @@ -3725,8 +3683,8 @@ declare namespace THREE { direction: Vector3; set(origin: Vector3, direction: Vector3): Ray; - clone(): Ray; - copy(ray: Ray): Ray; + clone(): this; + copy(ray: this): this; at(t: number, optionalTarget?: Vector3): Vector3; lookAt(v: Vector3): Vector3; recast(t: number): Ray; @@ -3745,9 +3703,10 @@ declare namespace THREE { applyMatrix4(matrix4: Matrix4): Ray; equals(ray: Ray): boolean; - isIntersectionSphere(s: any): any; // deprecated, use intersectsSphere() - isIntersectionPlane(p: any): any; // deprecated, use intersectsPlane() - isIntersectionBox(b: any): any; // deprecated, use intersectsBox() + // deprecated + isIntersectionBox(b: any): any; + isIntersectionPlane(p: any): any; + isIntersectionSphere(s: any): any; } export class Sphere { @@ -3758,8 +3717,8 @@ declare namespace THREE { set(center: Vector3, radius: number): Sphere; setFromPoints(points: Vector3[], optionalCenter?: Vector3): Sphere; - clone(): Sphere; - copy(sphere: Sphere): Sphere; + clone(): this; + copy(sphere: this): this; empty(): boolean; containsPoint(point: Vector3): boolean; distanceToPoint(point: Vector3): number; @@ -3835,14 +3794,15 @@ declare namespace THREE { set(a: Vector3, b: Vector3, c: Vector3): Triangle; setFromPointsAndIndices(points: Vector3[], i0: number, i1: number, i2: number): Triangle; - clone(): Triangle; - copy(triangle: Triangle): Triangle; + clone(): this; + copy(triangle: this): this; area(): number; midpoint(optionalTarget?: Vector3): Vector3; normal(optionalTarget?: Vector3): Vector3; plane(optionalTarget?: Vector3): Plane; barycoordFromPoint(point: Vector3, optionalTarget?: Vector3): Vector3; containsPoint(point: Vector3): boolean; + closestPointToPoint(): Vector3; equals(triangle: Triangle): boolean; static normal(a: Vector3, b: Vector3, c: Vector3, optionalTarget?: Vector3): Vector3; @@ -3869,7 +3829,7 @@ declare namespace THREE { /** * copy(v:T):T; */ - copy(v: Vector): Vector; + copy(v: this): this; /** * add(v:T):T; @@ -3958,7 +3918,7 @@ declare namespace THREE { /** * clone():T; */ - clone(): Vector; + clone(): this; } /** @@ -4003,11 +3963,11 @@ declare namespace THREE { /** * Clones this vector. */ - clone(): Vector2; + clone(): this; /** * Copies value of v to this vector. */ - copy(v: Vector2): Vector2; + copy(v: this): this; /** * Adds v to this vector. @@ -4094,6 +4054,7 @@ declare namespace THREE { * Computes squared distance of this vector to v. */ distanceToSquared(v: Vector2): number; + distanceToManhattan(v: Vector2): number; /** * Normalizes this vector and multiplies it by l. @@ -4168,11 +4129,11 @@ declare namespace THREE { /** * Clones this vector. */ - clone(): Vector3; + clone(): this; /** * Copies value of v to this vector. */ - copy(v: Vector3): Vector3; + copy(v: this): this; /** * Adds v to this vector. @@ -4210,7 +4171,7 @@ declare namespace THREE { applyMatrix4(m: Matrix4): Vector3; applyProjection(m: Matrix4): Vector3; applyQuaternion(q: Quaternion): Vector3; - project(camera: Camera): Vector3; + project(camrea: Camera): Vector3; unproject(camera: Camera): Vector3; transformDirection(m: Matrix4): Vector3; divide(v: Vector3): Vector3; @@ -4292,15 +4253,12 @@ declare namespace THREE { * Computes squared distance of this vector to v. */ distanceToSquared(v: Vector3): number; + distanceToManhattan(v: Vector3): number; setFromSpherical(s: Spherical): Matrix3; - getPositionFromMatrix(m: Matrix4): Vector3; // deprecated, use setFromMatrixPosition() setFromMatrixPosition(m: Matrix4): Vector3; - getScaleFromMatrix(m: Matrix4): Vector3; // deprecated, use setFromMatrixScale() setFromMatrixScale(m: Matrix4): Vector3; - getColumnFromMatrixColumn(index: number, matrix: Matrix4): Vector3; // deprecated, use setFromMatrixColumn() setFromMatrixColumn(matrix: Matrix4, index: number): Vector3; - setFromMatrixColumn(index: number, matrix: Matrix4): Vector3; // deprecated, now expects ( matrix, index ) /** * Checks for strict equality of this vector and v. @@ -4308,13 +4266,16 @@ declare namespace THREE { equals(v: Vector3): boolean; fromArray(xyz: number[], offset?: number): Vector3; - toArray(xyz?: number[], offset?: number): number[]; - fromAttribute( attribute: BufferAttribute, index: number, offset?: number): Vector3; + + // deprecated + getPositionFromMatrix(m: Matrix4): Vector3; + getScaleFromMatrix(m: Matrix4): Vector3; + getColumnFromMatrix(index: number, matrix: Matrix4): Vector3; } - export class Vertex extends Vector3 {} // deprecated, use Vector3 + export class Vertex extends Vector3 {} // deprecated /** * 4D vector. @@ -4364,11 +4325,11 @@ declare namespace THREE { /** * Clones this vector. */ - clone(): Vector4; + clone(): this; /** * Copies value of v to this vector. */ - copy(v: Vector4): Vector4; + copy(v: this): this; /** * Adds v to this vector. @@ -4516,9 +4477,6 @@ declare namespace THREE { constructor(skin: SkinnedMesh); skin: SkinnedMesh; - - clone(): Bone; - copy(source: Bone): Bone; } export class Group extends Object3D { @@ -4529,16 +4487,15 @@ declare namespace THREE { constructor(); levels: any[]; - objects: any[]; // deprecated, use .levels addLevel(object: Object3D, distance?: number): void; getObjectForDistance(distance: number): Object3D; raycast(raycaster: Raycaster, intersects: any): void; update(camera: Camera): void; - - clone(): LOD; - copy(source: LOD): LOD; toJSON(meta: any): any; + + // deprecated + objects: any[]; } export interface LensFlareProperty { @@ -4565,8 +4522,6 @@ declare namespace THREE { add(object: Object3D): void; add(texture: Texture, size?: number, distance?: number, blending?: Blending, color?: Color): void; updateLensFlares(): void; - clone(): LensFlare; - copy(source: LensFlare): LensFlare; } export class Line extends Object3D { @@ -4580,24 +4535,20 @@ declare namespace THREE { material: Material; // LineDashedMaterial or LineBasicMaterial or ShaderMaterial raycast(raycaster: Raycaster, intersects: any): void; - clone(): Line; - copy(source: Line): Line; } + export const LineStrip: number; // deprecated + export const LinePieces: number; // deprecated + export class LineSegments extends Line { constructor( geometry?: Geometry | BufferGeometry, material?: LineDashedMaterial | LineBasicMaterial | ShaderMaterial, mode?: number ); - - clone(): LineSegments; - copy(source: LineSegments): LineSegments; } enum LineMode {} - var LineStrip: LineMode; // deprecated - var LinePieces: LineMode; // deprecated export class Mesh extends Object3D { constructor(geometry?: Geometry, material?: Material); @@ -4611,8 +4562,6 @@ declare namespace THREE { updateMorphTargets(): void; getMorphTargetIndexByName(name: string): number; raycast(raycaster: Raycaster, intersects: any): void; - clone(): Mesh; - copy(source: Mesh): Mesh; } /** @@ -4642,12 +4591,10 @@ declare namespace THREE { material: Material; raycast(raycaster: Raycaster, intersects: any): void; - clone(): Points; - copy(source: Points): Points; } - export class PointCloud extends Points {} // deprecated, use Points - export class ParticleSystem extends Points {} // deprecated, use Points + export class PointCloud extends Points {} // deprecated + export class ParticleSystem extends Points {} // deprecated export class Skeleton { constructor(bones: Bone[], boneInverses?: Matrix4[], useVertexTexture?: boolean); @@ -4664,7 +4611,7 @@ declare namespace THREE { calculateInverses(bone: Bone): void; pose(): void; update(): void; - clone(): Skeleton; + clone(): this; } export class SkinnedMesh extends Mesh { @@ -4685,8 +4632,6 @@ declare namespace THREE { pose(): void; normalizeSkinWeights(): void; updateMatrixWorld(force?: boolean): void; - clone(): SkinnedMesh; - copy(source: SkinnedMesh): SkinnedMesh; } export class Sprite extends Object3D { @@ -4696,19 +4641,18 @@ declare namespace THREE { material: SpriteMaterial; raycast(raycaster: Raycaster, intersects: any): void; - clone(): Sprite; - copy(source: Sprite): Sprite; } - export class Particle extends Sprite {} // deprecated, use Sprite + export class Particle extends Sprite {} // deprecated // Renderers ////////////////////////////////////////////////////////////////////////////////// export interface Renderer { - render(scene: Scene, camera: Camera): void; - setSize(width:number, height:number, updateStyle?:boolean): void; domElement: HTMLCanvasElement; + + render(scene: Scene, camera: Camera): void; + setSize(width: number, height: number, updateStyle?: boolean): void; } export interface WebGLRendererParameters { @@ -4814,9 +4758,10 @@ declare namespace THREE { */ sortObjects: boolean; - extensions: WebGLExtensions; + clippingPlanes: any[]; + localClippingEnabled: boolean; - gammaFactor: number; // deprecated + extensions: WebGLExtensions; /** * Default is false. @@ -4848,11 +4793,6 @@ declare namespace THREE { */ maxMorphNormals: number; - /** - * Default is true. - */ - autoScaleCubemaps: boolean; - /** * An object with a series of statistical information about the graphics board memory and the rendering process. Useful for debugging or just for the sake of curiosity. The object contains the following fields: */ @@ -4871,15 +4811,13 @@ declare namespace THREE { }; shadowMap: WebGLShadowMap; - shadowMapType: ShadowMapType; // deprecated, use shadowMap.type - shadowMapEnabled: boolean; // deprecated, use shadowMap.enabled - shadowMapCullFace: CullFace; // deprecated, use shadowMap.cullFace pixelRation: number; capabilities: WebGLCapabilities; properties: WebGLProperties; state: WebGLState; + allocTextureUnit: any; /** * Return the WebGL context. @@ -4943,7 +4881,7 @@ declare namespace THREE { clearColor(): void; clearDepth(): void; clearStencil(): void; - clearTarget(renderTarget:WebGLRenderTarget, color: boolean, depth: boolean, stencil: boolean): void; + clearTarget(renderTarget: WebGLRenderTarget, color: boolean, depth: boolean, stencil: boolean): void; resetGLState(): void; dispose(): void; @@ -4971,24 +4909,31 @@ declare namespace THREE { * @param frontFace "ccw" or "cw */ setFaceCulling(cullFace?: CullFace, frontFace?: FrontFaceDirection): void; - setTexture(texture: Texture, slot: number): void; + setTexture(texture: Texture, slot: number): void; // deprecated + setTexture2D(texture: Texture, slot: number): void; + setTextureCube(texture: Texture, slot: number): void; getCurrentRenderTarget(): RenderTarget; setRenderTarget(renderTarget: RenderTarget): void; readRenderTargetPixels( renderTarget: RenderTarget, x: number, y: number, width: number, height: number, buffer: any ): void; - supportsFloatTextures(): any; // deprecated - supportsHalfFloatTextures(): any; // deprecated - supportsStandardDerivatives(): any; // deprecated - supportsCompressedTextureS3TC(): any; // deprecated - supportsCompressedTexturePVRTC(): any; // deprecated - supportsBlendMinMax(): any; // deprecated - supportsVertexTextures(): any; // deprecated - supportsInstancedArrays(): any; // deprecated - enableScissorTest(boolean: any): any; // deprecated + // deprecated + gammaFactor: number; + shadowMapEnabled: boolean; + shadowMapType: ShadowMapType; + shadowMapCullFace: CullFace; + + supportsFloatTextures(): any; + supportsHalfFloatTextures(): any; + supportsStandardDerivatives(): any; + supportsCompressedTextureS3TC(): any; + supportsCompressedTexturePVRTC(): any; + supportsBlendMinMax(): any; + supportsVertexTextures(): any; + supportsInstancedArrays(): any; + enableScissorTest(boolean: any): any; } - export interface RenderTarget { - } + export interface RenderTarget {} // not defined in the code, used in LightShadow and WebGRenderer classes export interface WebGLRenderTargetOptions { wrapS?: Wrapping; @@ -5002,7 +4947,7 @@ declare namespace THREE { stencilBuffer?: boolean; // true; } - export class WebGLRenderTarget implements RenderTarget { + export class WebGLRenderTarget extends EventDispatcher { constructor(width: number, height: number, options?: WebGLRenderTargetOptions); uuid: string; @@ -5014,6 +4959,7 @@ declare namespace THREE { texture: Texture; depthBuffer: boolean; stencilBuffer: boolean; + depthTexture: Texture; wrapS: any; // deprecated, use texture.wrapS wrapT: any; // deprecated, use texture.wrapT magFilter: any; // deprecated, use texture.magFilter @@ -5026,15 +4972,9 @@ declare namespace THREE { generateMipmaps: any; // deprecated, use texture.generateMipmaps setSize(width: number, height: number): void; - clone(): WebGLRenderTarget; - copy(source: WebGLRenderTarget): WebGLRenderTarget; + clone(): this; + copy(source: this): this; dispose(): void; - - // EventDispatcher mixins - addEventListener(type: string, listener: (event: Event) => void ): void; - hasEventListener(type: string, listener: (event: Event) => void): void; - removeEventListener(type: string, listener: (event: Event) => void): void; - dispatchEvent(event: { type: string; [attachment: string]: any; }): void; } export class WebGLRenderTargetCube extends WebGLRenderTarget { @@ -5057,6 +4997,10 @@ declare namespace THREE { beginnormal_vertex: string; bsdfs: string; bumpmap_pars_fragment: string; + clipping_planes_fragment: string; + clipping_planes_pars_fragment: string; + clipping_planes_pars_vertex: string; + clipping_planes_vertex: string; color_fragment: string; color_pars_fragment: string; color_pars_vertex: string; @@ -5068,8 +5012,6 @@ declare namespace THREE { defaultnormal_vertex: string; depth_frag: string; depth_vert: string; - depthRGBA_frag: string; - depthRGBA_vert: string; distanceRGBA_frag: string; distanceRGBA_vert: string; displacementmap_vertex: string; @@ -5094,10 +5036,8 @@ declare namespace THREE { lights_pars: string; lights_phong_fragment: string; lights_phong_pars_fragment: string; - lights_phong_pars_vertex: string; - lights_phong_vertex: string; - lights_standard_fragment: string; - lights_standard_pars_fragment: string; + lights_physical_fragment: string; + lights_physical_pars_fragment: string; lights_template: string; logdepthbuf_fragment: string; logdepthbuf_pars_fragment: string; @@ -5113,19 +5053,24 @@ declare namespace THREE { meshlambert_vert: string; meshphong_frag: string; meshphong_vert: string; - meshstandard_frag: string; - meshstandard_vert: string; + meshphysical_frag: string; + meshphysical_vert: string; metalnessmap_fragment: string; metalnessmap_pars_fragment: string; morphnormal_vertex: string; morphtarget_pars_vertex: string; morphtarget_vertex: string; + normal_flip: string; normal_frag: string; normal_fragment: string; normal_vert: string; normalmap_pars_fragment: string; + packing: string; points_frag: string; points_vert: string; + shadow_frag: string; + shadow_vert: string; + premultiplied_alpha_fragment: string; project_vertex: string; roughnessmap_fragment: string; @@ -5149,10 +5094,10 @@ declare namespace THREE { uv_pars_vertex: string; uv_vertex: string; worldpos_vertex: string; - } + }; export interface Shader { - uniforms: any; + uniforms: IUniform; vertexShader: string; fragmentShader: string; } @@ -5171,10 +5116,10 @@ declare namespace THREE { equirect: Shader; depthRGBA: Shader; distanceRGBA: Shader; + physical: Shader; }; export interface IUniform { - type: string; value: any; } @@ -5224,61 +5169,57 @@ declare namespace THREE { lights: { ambientLightColor: IUniform directionalLights: { - type: string; value: any[]; properties: { - direction: { type: string }; - color: { type: string }; - shadow: { type: string }; - shadowBias: { type: string }; - shadowRadius: { type: string }; - shadowMapSize: { type: string }; + direction: {}; + color: {}; + shadow: {}; + shadowBias: {}; + shadowRadius: {}; + shadowMapSize: {}; }; }; directionalShadowMap: IUniform; directionalShadowMatrix: IUniform; spotLights: { - type: string; value: any[]; properties: { - color: { type: string }; - position: { type: string }; - direction: { type: string }; - distance: { type: string }; - coneCos: { type: string }; - penumbraCos: { type: string }; - decay: { type: string }; - shadow: { type: string }; - shadowBias: { type: string }; - shadowRadius: { type: string }; - shadowMapSize: { type: string }; + color: {}; + position: {}; + direction: {}; + distance: {}; + coneCos: {}; + penumbraCos: {}; + decay: {}; + shadow: {}; + shadowBias: {}; + shadowRadius: {}; + shadowMapSize: {}; }; }; spotShadowMap: IUniform; spotShadowMatrix: IUniform; pointLights: { - type: string; value: any[]; properties: { - color: { type: string }; - position: { type: string }; - decay: { type: string }; - distance: { type: string }; - shadow: { type: string }; - shadowBias: { type: string }; - shadowRadius: { type: string }; - shadowMapSize: { type: string }; + color: {}; + position: {}; + decay: {}; + distance: {}; + shadow: {}; + shadowBias: {}; + shadowRadius: {}; + shadowMapSize: {}; }; }; pointShadowMap: IUniform; pointShadowMatrix: IUniform; hemisphereLigtts: { - type: string; value: any[]; properties: { - direction: { type: string }; - skycolor: { type: string }; - groundColor: { type: string }; + direction: {}; + skycolor: {}; + groundColor: {}; }; }; }; @@ -5298,10 +5239,11 @@ declare namespace THREE { } export class Uniform { - constructor(type: string, value: string); + constructor(value: any); + constructor(type: string, value: any); // deprecated - type: string; - value: string; + type: string; // deprecated + value: any; dynamic: boolean; onUpdateCallback: Function; @@ -5313,10 +5255,20 @@ declare namespace THREE { constructor(_gl: WebGLRenderingContext, extensions: any, _infoRender: any); setMode(value: any): void; - render(start: any, count: any): void; + render(start: any, count: number): void; renderInstances(geometry: any): void; } + export class WebGLClipping { + uniform: { value: any, needsUpdate: boolean }; + numPlanes: number; + + init(planes: any[], enableLocalClipping: boolean, camera: Camera): boolean; + beginShadows(): void; + endShadows(): void; + setState(planes: any[], clipShadows: boolean, camera: Camera, cache: boolean, fromCache: boolean): void; + } + export interface WebGLCapabilitiesParameters { precision?: any; logarithmicDepthBuffer?: any; @@ -5339,7 +5291,8 @@ declare namespace THREE { floatFragmentTextures: any; floatVertexTextures: any; - getMaxPrecision(precision: any): any; + getMaxAnisotropy(): number; + getMaxPrecision(precision: string): string; } export class WebGLExtensions { @@ -5389,7 +5342,7 @@ declare namespace THREE { uniforms: any; // deprecated, use getUniforms() attributes: any; // deprecated, use getAttributes() - getUniforms(): any; + getUniforms(): WebGLUniforms; getAttributes(): any; destroy(): void; } @@ -5399,12 +5352,37 @@ declare namespace THREE { programs: any[]; - getParameters(material: ShaderMaterial, lights: any, fog: any, object: any): any[]; + getParameters(material: ShaderMaterial, lights: any, fog: any, nClipPlanes: number, object: any): any; getProgramCode(material: ShaderMaterial, parameters: any): string; acquireProgram(material: ShaderMaterial, parameters: any, code: string): WebGLProgram; releaseProgram(program: WebGLProgram): void; } + export class WebGLTextures { + constructor(gl: any, extensions: any, state: any, properties: any, capabilities: any, paramThreeToGL: Function, info: any); + + setTexture2D(texture: any, slot: number): void; + setTextureCube(texture: any, slot: number): void; + setTextureCubeDynamic(texture: any, slot: number): void; + setupRenderTarget(renderTarget: any): void; + updateRenderTargetMipmap(renderTarget: any): void; + } + + export class WebGLUniforms { + constructor(gl: any, program: WebGLProgram, renderer: WebGLRenderer); + + renderer: WebGLRenderer; + + setValue(gl: any, value: any, renderer?: any): void; + set(gl: any, object: any, name: string): void; + setOptional(gl: any, object: any, name: string): void; + + static upload(gl: any, seq: any, values: any[], renderer: any): void; + static seqWithValue(seq: any, values: any[]): any[]; + static splitDynamic(seq: any, values: any[]): any[]; + static evalDynamic(seq: any, values: any[], object: any, camera: any): any[]; + } + export class WebGLProperties { constructor(); @@ -5418,20 +5396,30 @@ declare namespace THREE { } export class WebGLShadowMap { - constructor(_renderer: Renderer, _lights: any[], _objects: any[]); + constructor(_renderer: Renderer, _lights: any[], _objects: any[], capabilities: any); enabled: boolean; autoUpdate: boolean; needsUpdate: boolean; type: ShadowMapType; - cullFace: CullFace; + renderReverseSided: boolean; + renderSingleSided: boolean; render(scene: Scene, camera: Camera): void; + + // deprecated + cullFace: any; } export class WebGLState { constructor(gl: any, extensions: any, paramThreeToGL: Function); + buffers: { + color: WebGLColorBuffer, + depth: WebGLDepthBuffer, + stencil: WebGLStencilBuffer, + }; + init(): void; initAttributes(): void; enableAttribute(attribute: string): void; @@ -5441,15 +5429,16 @@ declare namespace THREE { disable(id: string): void; getCompressedTextureFormats(): any[]; setBlending(blending: number, blendEquation: number, blendSrc: number, blendDst: number, blendEquationAlpha: number, blendSrcAlpha: number, blendDstAlpha: number): void; - setDepthFunc(func: Function): void; + setColorWrite(colorWrite: number): void; setDepthTest(depthTest: number): void; setDepthWrite(depthWrite: number): void; - setColorWrite(colorWrite: number): void; - setStencilFunc(stencilFunc: Function, stencilRef: any, stencilMask: any): void; - setStencilOp(stencilFail: any, stencilZFail: any, stencilZPass: any): void; + setDepthFunc(depthFunc: Function): void; setStencilTest(stencilTest: boolean): void; setStencilWrite(stencilWrite: any): void; + setStencilFunc(stencilFunc: Function, stencilRef: any, stencilMask: number): void; + setStencilOp(stencilFail: any, stencilZFail: any, stencilZPass: any): void; setFlipSided(flipSided: number): void; + setCullFace(cullFace: CullFace): void; setLineWidth(width: number): void; setPolygonOffset(polygonoffset: number, factor: number, units: number): void; setScissorTest(scissorTest: boolean): void; @@ -5466,6 +5455,38 @@ declare namespace THREE { reset(): void; } + export class WebGLColorBuffer { + constructor(gl: any, state: any); + + setMask(colorMask: number): void; + setLocked(lock: boolean): void; + setClear(r: number, g: number, b: number, a: number): void; + reset(): void; + } + + export class WebGLDepthBuffer { + constructor(gl: any, state: any); + + setTest(depthTest: boolean): void; + sertMask(depthMask: number): void; + setFunc(depthFunc: Function): void; + setLocked(lock: boolean): void; + setClear(depth: any): void; + reset(): void; + } + + export class WebGLStencilBuffer { + constructor(gl: any, state: any); + + setTest(stencilTest: boolean): void; + sertMask(stencilMask: number): void; + setFunc(stencilFunc: Function, stencilRef: any, stencilMask: number): void; + setOp(stencilFail: any, stencilZFail: any, stencilZPass: any): void; + setLocked(lock: boolean): void; + setClear(stencil: any): void; + reset(): void; + } + // Renderers / WebGL / Plugins ///////////////////////////////////////////////////////////////////// export class LensFlarePlugin { constructor(renderer: WebGLRenderer, flares: any[]); @@ -5497,14 +5518,16 @@ declare namespace THREE { */ overrideMaterial: Material; autoUpdate: boolean; + background: any; - copy(source: Scene, recursive?: boolean): Scene; + toJSON(meta?: any): any; } export interface IFog { - name:string; + name: string; color: Color; - clone():IFog; + clone(): this; + toJSON(): any; } /** @@ -5513,7 +5536,7 @@ declare namespace THREE { export class Fog implements IFog { constructor(hex: number, near?: number, far?: number); - name:string; + name: string; /** * Fog color. @@ -5531,7 +5554,8 @@ declare namespace THREE { */ far: number; - clone(): Fog; + clone(): this; + toJSON(): any; } /** @@ -5549,13 +5573,14 @@ declare namespace THREE { */ density: number; - clone(): FogExp2; + clone(): this; + toJSON(): any; } // Textures ///////////////////////////////////////////////////////////////////// export let TextureIdCount: number; - export class Texture { + export class Texture extends EventDispatcher { constructor( image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, mapping?: Mapping, @@ -5565,14 +5590,15 @@ declare namespace THREE { minFilter?: TextureFilter, format?: PixelFormat, type?: TextureDataType, - anisotropy?: number + anisotropy?: number, + encoding?: TextureEncoding ); id: number; uuid: string; name: string; sourceFile: string; - image: any; // HTMLImageElement or ImageData ; + image: any; // HTMLImageElement or ImageData or { width: number, height: number } in some children; mipmaps: ImageData[]; mapping: Mapping; wrapS: Wrapping; @@ -5595,17 +5621,27 @@ declare namespace THREE { static DEFAULT_IMAGE: any; static DEFAULT_MAPPING: any; - clone(): Texture; - copy(source: Texture): Texture; + clone(): this; + copy(source: this): this; toJSON(meta: any): any; dispose(): void; transformUv(uv: Vector): void; + } - // EventDispatcher mixins - addEventListener(type: string, listener: (event: Event) => void ): void; - hasEventListener(type: string, listener: (event: Event) => void): void; - removeEventListener(type: string, listener: (event: Event) => void): void; - dispatchEvent(event: { type: string; [attachment: string]: any; }): void; + export class DepthTexture extends Texture { + constructor( + width: number, + heighht: number, + type?: TextureDataType, + mapping?: Mapping, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + anisotropy?: number + ); + + image: { width: number, height: number }; } export class CanvasTexture extends Texture { @@ -5620,9 +5656,6 @@ declare namespace THREE { type?: TextureDataType, anisotropy?: number ); - - clone(): CanvasTexture; - copy(source: CanvasTexture): CanvasTexture; } export class CubeTexture extends Texture { @@ -5635,12 +5668,11 @@ declare namespace THREE { minFilter?: TextureFilter, format?: PixelFormat, type?: TextureDataType, - anisotropy?: number + anisotropy?: number, + encoding?: TextureEncoding ); images: any; // returns and sets the value of Texture.image in the codde ? - - copy(source: CubeTexture): CubeTexture; } export class CompressedTexture extends Texture { @@ -5655,13 +5687,11 @@ declare namespace THREE { wrapT?: Wrapping, magFilter?: TextureFilter, minFilter?: TextureFilter, - anisotropy?: number + anisotropy?: number, + encoding?: TextureEncoding ); image: { width: number; height: number; }; - - clone(): CompressedTexture; - copy(source: CompressedTexture): CompressedTexture; } export class DataTexture extends Texture { @@ -5676,13 +5706,11 @@ declare namespace THREE { wrapT: Wrapping, magFilter: TextureFilter, minFilter: TextureFilter, - anisotropy?: number + anisotropy?: number, + encoding?: TextureEncoding ); image: { data: ImageData; width: number; height: number; }; - - clone(): DataTexture; - copy(source: DataTexture): DataTexture; } export class VideoTexture extends Texture { @@ -5697,9 +5725,6 @@ declare namespace THREE { type?: TextureDataType, anisotropy?: number ); - - clone(): VideoTexture; - copy(source: VideoTexture): VideoTexture; } // Extras ///////////////////////////////////////////////////////////////////// @@ -5725,8 +5750,8 @@ declare namespace THREE { export namespace ShapeUtils { export function area(contour: number[]): number; - export function triangulate(contour: Vector2[], indices: boolean): Vector2[][] | number[][]; - export function triangulateShape(contour: Vector2[], holes: Vector2[][]): Vector2[][]; + export function triangulate(contour: number[], indices: boolean): number[]; + export function triangulateShape(contour: number[], holes: any[]): number[]; export function isClockWise(pts: number[]): boolean; export function b2(t: number, p0: number, p1: number, p2: number): number; export function b3(t: number, p0: number, p1: number, p2: number, p3: number): number; @@ -5747,26 +5772,28 @@ declare namespace THREE { hasPlaybackControl: boolean; isPlaying: boolean; sourceType: string; - filter: any; + filters: any[]; getOutput(): GainNode; - load(file: string): Audio; setNodeSource(audioNode: AudioBufferSourceNode): Audio; setBuffer(audioBuffer: AudioBuffer): Audio; - play(): void; - pause(): void; - stop(): void; - connect(): void; - disconnect(): void; - setFilter(value: any): void; + play(): Audio; + pause(): Audio; + stop(): Audio; + connect(): Audio; + disconnect(): Audio; + getFilters(): any[]; + setFilter(value: any[]): Audio; getFilter(): any; - setPlaybackRate(value: number): void; + setFilter(filter: any): Audio; + setPlaybackRate(value: number): Audio; getPlaybackRate(): number; onEnded(): void; - setLoop(value: boolean): void; getLoop(): boolean; - setVolume(value: number): void; + setLoop(value: boolean): void; getVolume(): number; + setVolume(value: number): Audio; + load(file: string): Audio; // deprecated, use the AudioLoader class } export class AudioAnalyser { @@ -5775,9 +5802,15 @@ declare namespace THREE { analyser: any; data: Uint8Array; - getData(): Uint8Array; + getFrequencyData(): Uint8Array; + getAverageFrequency(): number; + + // deprecated + getData(file: any): any; } + export const AudioContext: AudioContext; + export class AudioBuffer { constructor(context: any); @@ -5836,7 +5869,7 @@ declare namespace THREE { * Returns a vector for point at relative position in curve according to arc length * getPointAt(u: number): T; */ - getPointAt(u: number):T; + getPointAt(u: number): T; /** * Get sequence of points using getPoint( t ) @@ -5896,7 +5929,10 @@ declare namespace THREE { closePath(): void; getPoint(t: number): T; getLength(): number; + updateArcLengths(): void; getCurveLengths(): number[]; + getSpacedPoints(divisions?: number): T[]; + getPoints(divisions?: number): T[]; createPointsGeometry(divisions: number): Geometry; createSpacedPointsGeometry(divisions: number): Geometry; createGeometry(points: T[]): Geometry; @@ -5923,7 +5959,7 @@ declare namespace THREE { export class Path extends CurvePath { constructor(points?: Vector2[]); - actions: PathAction[]; + currentPoint: Vector2; fromPoints(vectors: Vector2[]): void; moveTo(x: number, y: number): void; @@ -5935,8 +5971,19 @@ declare namespace THREE { absarc(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; ellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number): void; absellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number): void; - getSpacedPoints(divisions?: number): Vector2[]; - getPoints(divisions?: number, closedPath?: boolean): Vector2[]; + } + + export class ShapePath { + constructor(); + + subPaths: any[]; + currentPath: any; + + moveTo(x: number, y: number): void; + lineTo(x: number, y: number): void; + quadraticCurveTo(aCPx: number, aCPy: number, aX: number, aY: number): void; + bezierCurveTo(aCP1x: number, aCP1y: number, aCP2x: number, aCP2y: number, aX: number, aY: number): void; + splineThru(pts: Vector2[]): void; toShapes(isCCW: boolean, noHoles: any): Shape[]; } @@ -6083,8 +6130,6 @@ declare namespace THREE { heightSegments: number; depthSegments: number; }; - - clone(): BoxGeometry; } export class CubeGeometry extends BoxGeometry {} // deprecated, use BoxGeometry @@ -6149,6 +6194,14 @@ declare namespace THREE { }; } + export class ConeBufferGeometry extends BufferGeometry { + constructor(radius?: number, height?: number, radialSegment?: number, heightSegment?: number, openEnded?: boolean, thetaStart?: number, thetaLength?: number); + } + + export class ConeGeometry extends CylinderGeometry { + constructor(radius?: number, height?: number, radialSegment?: number, heightSegment?: number, openEnded?: boolean, thetaStart?: number, thetaLength?: number); + } + export class DodecahedronGeometry extends Geometry { constructor(radius: number, detail: number); @@ -6160,8 +6213,6 @@ declare namespace THREE { export class EdgesGeometry extends BufferGeometry { constructor(geometry: BufferGeometry, thresholdAngle: number); - - clone(): EdgesGeometry; } export class ExtrudeGeometry extends Geometry { @@ -6352,7 +6403,7 @@ declare namespace THREE { bevelEnabled: boolean; bevelThickness: number; bevelSize: number; - } + }; } export class TorusBufferGeometry extends BufferGeometry { @@ -6458,7 +6509,7 @@ declare namespace THREE { } export class BoxHelper extends LineSegments { - constructor(object?: Object3D); + constructor(object?: Object3D, color?: Color); update(object?: Object3D): void; } @@ -6477,7 +6528,6 @@ declare namespace THREE { light: Light; lightPlane: Line; - targetLine: Line; dispose(): void; update(): void; @@ -6497,12 +6547,9 @@ declare namespace THREE { } export class GridHelper extends LineSegments { - constructor(size: number, step: number); + constructor(size: number, divisions: number, color1?: Color|number, color2?: Color|number); - color1: Color; - color2: Color; - - setColors(colorCenterLine: number, colorGrid: number): void; + setColors(color1?: Color|number, color2?: Color|number): void; // deprecated } export class HemisphereLightHelper extends Object3D { @@ -6536,10 +6583,9 @@ declare namespace THREE { } export class SpotLightHelper extends Object3D { - constructor(light: Light, sphereSize: number, arrowLength: number); + constructor(light: Light); light: Light; - cone: Mesh; dispose(): void; update(): void; @@ -6605,6 +6651,6 @@ declare namespace THREE { } } -declare module 'three' { +declare module "three" { export = THREE; } diff --git a/tinder/tinder-tests.ts b/tinder/tinder-tests.ts new file mode 100644 index 0000000000..12b8e6f071 --- /dev/null +++ b/tinder/tinder-tests.ts @@ -0,0 +1,37 @@ +/// + +import tinder = require('tinder'); +var client : tinder.TinderClient = new tinder.TinderClient(); + +client.authorize( + '', + '', + function () { + + client.getRecommendations(10, (error, data) => { + var results = data.results; + results.forEach((recommendation) => { + client.like(recommendation._id, (data) => { + if (data.matched) { + client.sendMessage(recommendation._id, "hey ;)", function (error, data) { + if (!error) { + console.log('Message sent to ' + recommendation.name + ' id: ' + recommendation._id) + } + }); + } + }) + }); + }); + + client.getHistory((error, history)=>{ + if (history.matches && history.matches.length) { + console.log(history.matches[0].messages); + } + }); + + client.getUpdates((error, updates)=>{ + if (updates.matches && updates.matches.length) { + console.log(updates.matches); + } + }); + }); \ No newline at end of file diff --git a/tinder/tinder.d.ts b/tinder/tinder.d.ts new file mode 100644 index 0000000000..9cbc19b360 --- /dev/null +++ b/tinder/tinder.d.ts @@ -0,0 +1,401 @@ +// Type definitions for tinder 1.19.0 +// Project: https://github.com/tinderjs/tinderjs +// Definitions by: Matej Drolc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'tinder' { + + import fs = require('fs'); + + class TinderClient { + constructor(); + /** + * Authorize this tinder client + * @param {String} fbToken the Facebook token. This will be obtained when authenticating the user + * @param {String} fbId the Facebook user id. + * @param {Function} callback the callback to invoke when the request completes + */ + authorize(fbToken: string, fbId: string, callback: Callback): void; + + /** + * Returns whether this client is authorized + * @return whether or not this client is authorized + */ + isAuthorized(): Boolean; + + /** + * Returns the xAuthToken + * @return xAuthToken + */ + getAuthToken(): string; + + /** + * Set auth token if you have it saved, no need to do fb login every time + */ + setAuthToken(xAuthToken: string): void; + + /** + * Returns client information and globals + * Globals are used for interacting with tinder api limits + */ + getDefaults(): any; + + /** + * The current account's user id + */ + userId: string; + + /** + * Gets a list of nearby users + * @param {Number} limit the maximum number of profiles to fetch + * @param {Function} callback the callback to invoke when the request completes + */ + getRecommendations(limit: number, callback: Callback): void; + + /** + * Sends a message to a user + * @param {String} matchId the id of the match + * @param {String} message the message to send + * @param {Function} callback the callback to invoke when the request completes + */ + sendMessage(matchId: string, message: string, callback: Callback): void; + + /** + * Likes (swipes right) on a user + * @param {String} userId the id of the user + * @param {Function} callback the callback to invoke when the request completes + */ + like(userId: string, callback: Callback): void; + + /** + * Superlikes a user + * @param {String} userId the id of the user + * @param {Function} callback the callback to invoke when the request completes + */ + superLike(userId: string, callback: Callback): void; + + /** + * Passes (swipes left) on a user + * @param {String} userId the id of the user + * @param {Function} callback the callback to invoke when the request completes + */ + pass(userId: string, callback: Callback): void; + + /** + * Unmatch with a user + * @param {String} matchID the id of the match + * @param {Function} callback the callback to invoke when the request completes + */ + unmatch(matchId: string, callback: Callback): void; + + /** + * Gets a list of new updates. This will be things like new messages, users who liked you, etc. + * @param {Function} callback the callback to invoke when the request completes + */ + getUpdates(callback: Callback): void; + + /** + * Gets the entire history for the current account (all matches, messages, blocks, etc.) + * + * NOTE: Old messages seem to not be returned after a certain threshold. Not yet + * sure what exactly that timeout is. The official client seems to get this update + * once when the app is installed then cache the results and only rely on the + * incremental updates + * @param {Function} callback the callback to invoke when the request completes + */ + getHistory(callback: Callback): void; + + /** + * Updates the geographical position for the current account + * @param {Number} lon the longitude + * @param {Number} lat the latitutde + * @param {Function} callback the callback to invoke when the request completes + */ + updatePosition(longitude: Number, latitude: Number, callback: Callback): void; + + /** + * Gets the current account info + * @param {Function} callback the callback to invoke when the request completes + */ + getAccount(callback: Callback): void; + + /** + * Updates the preferences for the current account + * @param {Boolean} discovery whether or not to show user's card + * @param {Number} ageMin the minimum age to show recommendations + * @param {Number} ageMax the maximum age to show recommendations + * @param {Number} gender the gender to show recommentations (0 = Male, 1 = Female, -1 = Both) + * @param {Number} distance the distance in miles to show recommendations + * @param {Function} callback the callback to invoke when the request completes + */ + updatePreferences(discovery: Boolean, ageMin: number, ageMax: number, gender: number, distance: number, callback: Callback): void; + + /** + * Upload a new picture to the current account + * @param {Buffer} file the picture that you want to upload + * @param {Function} callback the callback to invoke when the request completes + */ + uploadPicture(file: fs.ReadStream, callback: Callback): void; + + /** + * Post a new picture to the current account from Facebook + * @param {String} pictureId is the facebook id of the picture + * @param {Float} xdistance_percent is the zoom percentage in x 0 full Zoom 1 no Zoom + * @param {Float} ydistance_percent is the zoom percentage in x 0 full Zoom 1 no Zoom + * @param {Float} xoffset_percent is the offset from the left corner in percentage + * @param {Float} yoffset_percent is the offset from the top corner in percentage + * @param {Function} callback the callback to invoke when the request completes + */ + uploadFBPicture(pictureId: string, xdistance_percent: number, ydistance_percent: number, xoffset_percent: number, yoffset_percent: number, callback: Callback): void; + + /** + * Delete a picture from the current account + * @param {String} pictureId the id of the picture + * @param {Function} callback the callback to invoke when the request completes + */ + deletePicture(pictureId: string, callback: Callback): void; + + /** + * @deprecated + * Get authenticated user info + * @param {Function} callback the callback to invoke when the request completes + */ + getProfile(callback: Callback): void; + + /** + * Update your gender + * @param {Number} gender is your gender (0 = Male, 1 = Female) + * @param {Function} callback the callback to invoke when the request completes + */ + updateGender(gender: number, callback: Callback): void; + + /** + * Update your bio + * @param {String} bio is you bio (500 characters max.) + * @param {Function} callback the callback to invoke when the request completes + */ + updateBio(bio: string, callback: Callback): void; + + /** + * Update your job + * @param {String} id is the facebook id of the job + * @param {Function} callback the callback to invoke when the request completes + */ + updateJob(id: String, callback: Callback): void; + + /** + * Delete your current job + * @param {Function} callback the callback to invoke when the request completes + */ + deleteJob(callback: Callback): void; + + /** + * Update your school + * @param {String} id is the facebook id of the school + * @param {Function} callback the callback to invoke when the request completes + */ + updateSchool(id: String, callback: Callback): void; + + /** + * Delete your current school + * @param {Function} callback the callback to invoke when the request completes + */ + deleteSchool(callback: Callback): void; + + /** + * Delete the current account + * @param {Function} callback the callback to invoke when the request completes + */ + deleteAccount(callback: Callback): void; + + /** + * Gets a user by id + * @param {String} userId the id of the user + * @param {Function} callback the callback to invoke when the request completes + */ + getUser(userId: string, callback: Callback): void; + + /** + * Get a share URL for a user + * + * @param {String} userId the id of the user + * @param {Function} callback the callback to invoke when the request completes + */ + getShareLink(userId: string, callback: Callback): void; + + /** + * Report a user + * + * @param {String} userId the id of the user + * @param {Number} causeId one of 4 (inappropriate photos), 1 (spam), or 0 (other) + * @param {String} causeText optional reason for report when causeId is 0 (other) + * @param {Function} callback the callback to invoke when the request completes + */ + report(userId: string, causeId: Number, causeText: string, callback: Callback): void; + + /** + * Create a web username for the current account + * + * @param {String} userName the username to request be created + * @param {Function} callback the callback to invoke when the request completes + */ + createUsername(username: string, callback: Callback): void; + + /** + * Change a web username for the current account if it's already been set + * + * @param {String} userName the username to request be created + * @param {Function} callback the callback to invoke when the request completes + */ + changeUsername(username: string, callback: Callback): void; + + /** + * Deletes the existing web username for the current account + * + * @param {Function} callback the callback to invoke when the request completes + */ + deleteUsername(username: string, callback: Callback): void; + + /** + * Update the passport location + * @param {Number} lon the longitude + * @param {Number} lat the latitutde + * @param {Function} callback the callback to invoke when the request completes + */ + updatePassport(latitude: string, longitude: string, callback: Callback): void; + + /** + * Reset the passport location + * @param {Function} callback the callback to invoke when the request completes + */ + resetPassport(callback: Callback): void; + } + + interface Callback { + (error: any, data: T): any; + } + + interface TinderUpdates { + matches: any[]; + blocks: any[]; + matchmaker: any[]; + lists: any[]; + deleted_lists: any[]; + liked_messages: TinderMessage[]; + squads: any[]; + last_activity_date: string; + } + + /** + * When out of recommendations it is set to "out of recs", a possible value is also "recs timeout", + * otherwise does not seem to be used + */ + interface TinderRecommendationsResult { + message?: string; + status: Number; + results: TinderRecommendation[]; + } + + interface TinderRecommendation { + distance_mi: Number; + common_connections: any[]; // todo + common_likes: any[]; // todo + common_interests: any[]; // todo + uncommon_interests: any[]; // todo + common_friends: any[]; // todo + _id: string; + badges: any[]; // todo + bio: string; + birth_date: string; + gender: number; + name: string; + ping_time: string; + photos: TinderPhoto[]; + jobs: any[]; // todo + schools: any[]; // todo + teaser: { string: string; }; // todo + birth_date_info: string; + } + + interface TinderHistory { + matches: TinderMatch[]; + blocks: string[]; + lists: any[]; // todo + deleted_lists: any[]; // todo + liked_messages: TinderLikedMessage[]; + squads: any[]; // todo + last_activity_date: string; + } + + interface TinderLikedMessage { + message_id: string; + updated_at: string; + liker_id: string; + match_id: string; + is_liked: Boolean; + } + + interface TinderMatch { + _id: string; + closed: Boolean; + common_friend_count: number; + common_like_count: number; + created_date: string; + dead: Boolean; + last_activity_date: string; + message_count: number; + messages: TinderMessage[]; + muted: Boolean; + participants: string[]; + pending: Boolean; + is_super_like: Boolean; + following: Boolean; + following_moments: Boolean; + id: string; + person: TinderPerson; + } + + interface TinderPerson { + _id: string; + bio: string; + birth_date: string; + gender: number; + name: string; + ping_time: string; + user_number: number; + photos: TinderPhoto[]; + badges: any[]; // todo + } + + interface TinderPhoto { + url: string; + processedFiles: TinderPhotoProcessedFile[]; + extension: string; + fileName: string; + xoffset_percent: number; + ydistance_percent: number; + main: Boolean; + xdistance_percent: number; + id: string; + yoffset_percent: number; + } + + interface TinderPhotoProcessedFile { + url: string; + height: number; + width: number; + } + + interface TinderMessage { + _id: string; + match_id: string; + to: string; + from: string; + message: string; + sent_date: string; + created_date: string; + timestamp: number; + } +} diff --git a/tinycopy/tinycopy-tests.ts b/tinycopy/tinycopy-tests.ts new file mode 100644 index 0000000000..f695ebf19e --- /dev/null +++ b/tinycopy/tinycopy-tests.ts @@ -0,0 +1,17 @@ +/// + +import TinyCopy from 'tinycopy'; + +TinyCopy.exec('test', (err, data) => {}); + +var trigger_1 = document.getElementById('trigger_1'); +var target_1 = document.getElementById('target'); +new TinyCopy(trigger_1, target_1) + .on('success', function(data) {}) + .on('error', function(err) {}); + +var trigger_2 = document.getElementById('trigger_2'); +var target_2 = 'test'; +new TinyCopy(trigger_2, target_2) + .on('success', function(data) {}) + .on('error', function(err) {}); diff --git a/tinycopy/tinycopy.d.ts b/tinycopy/tinycopy.d.ts new file mode 100644 index 0000000000..33b7ae217c --- /dev/null +++ b/tinycopy/tinycopy.d.ts @@ -0,0 +1,14 @@ +// Type definitions for tinycopy 2.1.2 +// Project: https://github.com/vvatanabe/tinycopy +// Definitions by: Yuichi Watanabe +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "tinycopy" { + export default class TinyCopy { + constructor(trigger: Element, target: (string | Element | NodeListOf)); + on(type: "success", action: (data: string) => void): this; + on(type: "error", action: (err: Error) => void): this; + on(type: string, action: (e: (string | Error)) => void): this; + static exec(value: string, callback: (err?: Error, data?: string) => void): void; + } +} diff --git a/trayballoon/trayballoon-tests.ts b/trayballoon/trayballoon-tests.ts new file mode 100644 index 0000000000..dab23777e0 --- /dev/null +++ b/trayballoon/trayballoon-tests.ts @@ -0,0 +1,15 @@ +/// + +import trayballoon = require( "trayballoon" ); + +function testTrayballoon() { + trayballoon( { + text: "text", + title: "title", + icon: "icon", + timeout: 5000, + wait: true + }, () => { + + } ); +} diff --git a/trayballoon/trayballoon.d.ts b/trayballoon/trayballoon.d.ts new file mode 100644 index 0000000000..c60ffed40b --- /dev/null +++ b/trayballoon/trayballoon.d.ts @@ -0,0 +1,17 @@ +// Type definitions for trayballoon +// Project: https://github.com/sindresorhus/trayballoon +// Definitions by: André Eckardt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare interface TrayballoonOptions { + text:string + title?:string + icon?:string + timeout?:number + wait?:boolean +} + +declare function trayballoonFn( opts:TrayballoonOptions, fn:Function ): void; +declare module "trayballoon" { + export = trayballoonFn; +} \ No newline at end of file diff --git a/ts-activex/activex-data-objects-tests.ts b/ts-activex/activex-data-objects-tests.ts new file mode 100644 index 0000000000..27373ff8f0 --- /dev/null +++ b/ts-activex/activex-data-objects-tests.ts @@ -0,0 +1,21 @@ +/// + + +//open connection to an Excel file +var pathToExcelFile = 'C:\\path\\to\\excel\\file.xlsx'; +var conn = new ActiveXObject('ADODB.Connection'); +conn.Provider = 'Microsoft.ACE.OLEDB.12.0'; +conn.ConnectionString = + 'Data Source="' + pathToExcelFile + '";' + + 'Extended Properties="Excel 12.0;HDR=Yes"'; +conn.Open(); + +//create a Command to access the data +var cmd = new ActiveXObject('ADODB.Command'); +cmd.CommandText = 'SELECT DISTINCT LastName, CityName FROM [Sheet1$]'; +//get a Recordset +var rs = cmd.Execute(); +//build a string from the Recordset +var s = rs.GetString(ADODB.StringFormatEnum.adClipString, -1, '\t', '\n', '(NULL)'); +rs.Close(); +WScript.Echo(s); \ No newline at end of file diff --git a/ts-activex/activex-data-objects.d.ts b/ts-activex/activex-data-objects.d.ts new file mode 100644 index 0000000000..5b6844fef4 --- /dev/null +++ b/ts-activex/activex-data-objects.d.ts @@ -0,0 +1,836 @@ +// Type definitions for Microsoft ActiveX Data Objects +// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms675532(v=vs.85).aspx +// Definitions by: Zev Spitz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace ADODB { + + //Enums + const enum ADCPROP_ASYNCTHREADPRIORITY_ENUM { + adPriorityAboveNormal = 4, + adPriorityBelowNormal = 2, + adPriorityHighest = 5, + adPriorityLowest = 1, + adPriorityNormal = 3 + } + + const enum ADCPROP_AUTORECALC_ENUM { + adRecalcAlways = 1, + adRecalcUpFront = 0 + } + + const enum ADCPROP_UPDATECRITERIA_ENUM { + adCriteriaAllCols = 1, + adCriteriaKey = 0, + adCriteriaTimeStamp = 3, + adCriteriaUpdCols = 2 + } + + const enum ADCPROP_UPDATERESYNC_ENUM { + adResyncAll = 15, + adResyncAutoIncrement = 1, + adResyncConflicts = 2, + adResyncInserts = 8, + adResyncNone = 0, + adResyncUpdates = 4 + } + + const enum AffectEnum { + adAffectAll = 3, + adAffectAllChapters = 4, + adAffectCurrent = 1, + adAffectGroup = 2 + } + + const enum BookmarkEnum { + adBookmarkCurrent = 0, + adBookmarkFirst = 1, + adBookmarkLast = 2 + } + + const enum CommandTypeEnum { + adCmdFile = 256, + adCmdStoredProc = 4, + adCmdTable = 2, + adCmdTableDirect = 512, + adCmdText = 1, + adCmdUnknown = 8, + adCmdUnspecified = -1 + } + + const enum CompareEnum { + adCompareEqual = 1, + adCompareGreaterThan = 2, + adCompareLessThan = 0, + adCompareNotComparable = 4, + adCompareNotEqual = 3 + } + + const enum ConnectModeEnum { + adModeRead = 1, + adModeReadWrite = 3, + adModeRecursive = 4194304, + adModeShareDenyNone = 16, + adModeShareDenyRead = 4, + adModeShareDenyWrite = 8, + adModeShareExclusive = 12, + adModeUnknown = 0, + adModeWrite = 2 + } + + const enum ConnectOptionEnum { + adAsyncConnect = 16, + adConnectUnspecified = -1 + } + + const enum ConnectPromptEnum { + adPromptAlways = 1, + adPromptComplete = 2, + adPromptCompleteRequired = 3, + adPromptNever = 4 + } + + const enum CopyRecordOptionsEnum { + adCopyAllowEmulation = 4, + adCopyNonRecursive = 2, + adCopyOverWrite = 1, + adCopyUnspecified = -1 + } + + const enum CursorLocationEnum { + adUseClient = 3, + adUseClientBatch = 3, + adUseNone = 1, + adUseServer = 2 + } + + const enum CursorOptionEnum { + adAddNew = 16778240, + adApproxPosition = 16384, + adBookmark = 8192, + adDelete = 16779264, + adFind = 524288, + adHoldRecords = 256, + adIndex = 8388608, + adMovePrevious = 512, + adNotify = 262144, + adResync = 131072, + adSeek = 4194304, + adUpdate = 16809984, + adUpdateBatch = 65536 + } + + const enum CursorTypeEnum { + adOpenDynamic = 2, + adOpenForwardOnly = 0, + adOpenKeyset = 1, + adOpenStatic = 3, + adOpenUnspecified = -1 + } + + const enum DataTypeEnum { + adArray = 8192, + adBigInt = 20, + adBinary = 128, + adBoolean = 11, + adBSTR = 8, + adChapter = 136, + adChar = 129, + adCurrency = 6, + adDate = 7, + adDBDate = 133, + adDBTime = 134, + adDBTimeStamp = 135, + adDecimal = 14, + adDouble = 5, + adEmpty = 0, + adError = 10, + adFileTime = 64, + adGUID = 72, + adIDispatch = 9, + adInteger = 3, + adIUnknown = 13, + adLongVarBinary = 205, + adLongVarChar = 201, + adLongVarWChar = 203, + adNumeric = 131, + adPropVariant = 138, + adSingle = 4, + adSmallInt = 2, + adTinyInt = 16, + adUnsignedBigInt = 21, + adUnsignedInt = 19, + adUnsignedSmallInt = 18, + adUnsignedTinyInt = 17, + adUserDefined = 132, + adVarBinary = 204, + adVarChar = 200, + adVariant = 12, + adVarNumeric = 139, + adVarWChar = 202, + adWChar = 130 + } + + const enum EditModeEnum { + adEditAdd = 2, + adEditDelete = 4, + adEditInProgress = 1, + adEditNone = 0 + } + + const enum ErrorValueEnum { + adErrBoundToCommand = 3707, + adErrCannotComplete = 3732, + adErrCantChangeConnection = 3748, + adErrCantChangeProvider = 3220, + adErrCantConvertvalue = 3724, + adErrCantCreate = 3725, + adErrCatalogNotSet = 3747, + adErrColumnNotOnThisRow = 3726, + adErrConnectionStringTooLong = 3754, + adErrDataConversion = 3421, + adErrDataOverflow = 3721, + adErrDelResOutOfScope = 3738, + adErrDenyNotSupported = 3750, + adErrDenyTypeNotSupported = 3751, + adErrFeatureNotAvailable = 3251, + adErrFieldsUpdateFailed = 3749, + adErrIllegalOperation = 3219, + adErrIntegrityViolation = 3719, + adErrInTransaction = 3246, + adErrInvalidArgument = 3001, + adErrInvalidConnection = 3709, + adErrInvalidParamInfo = 3708, + adErrInvalidTransaction = 3714, + adErrInvalidURL = 3729, + adErrItemNotFound = 3265, + adErrNoCurrentRecord = 3021, + adErrNotExecuting = 3715, + adErrNotReentrant = 3710, + adErrObjectClosed = 3704, + adErrObjectInCollection = 3367, + adErrObjectNotSet = 3420, + adErrObjectOpen = 3705, + adErrOpeningFile = 3002, + adErrOperationCancelled = 3712, + adErrOutOfSpace = 3734, + adErrPermissionDenied = 3720, + adErrPropConflicting = 3742, + adErrPropInvalidColumn = 3739, + adErrPropInvalidOption = 3740, + adErrPropInvalidValue = 3741, + adErrPropNotAllSettable = 3743, + adErrPropNotSet = 3744, + adErrPropNotSettable = 3745, + adErrPropNotSupported = 3746, + adErrProviderFailed = 3000, + adErrProviderNotFound = 3706, + adErrProviderNotSpecified = 3753, + adErrReadFile = 3003, + adErrResourceExists = 3731, + adErrResourceLocked = 3730, + adErrResourceOutOfScope = 3735, + adErrSchemaViolation = 3722, + adErrSignMismatch = 3723, + adErrStillConnecting = 3713, + adErrStillExecuting = 3711, + adErrTreePermissionDenied = 3728, + adErrUnavailable = 3736, + adErrUnsafeOperation = 3716, + adErrURLDoesNotExist = 3727, + adErrURLNamedRowDoesNotExist = 3737, + adErrVolumeNotFound = 3733, + adErrWriteFile = 3004, + adwrnSecurityDialog = 3717, + adwrnSecurityDialogHeader = 3718 + } + + const enum EventReasonEnum { + adRsnAddNew = 1, + adRsnClose = 9, + adRsnDelete = 2, + adRsnFirstChange = 11, + adRsnMove = 10, + adRsnMoveFirst = 12, + adRsnMoveLast = 15, + adRsnMoveNext = 13, + adRsnMovePrevious = 14, + adRsnRequery = 7, + adRsnResynch = 8, + adRsnUndoAddNew = 5, + adRsnUndoDelete = 6, + adRsnUndoUpdate = 4, + adRsnUpdate = 3 + } + + const enum EventStatusEnum { + adStatusCancel = 4, + adStatusCantDeny = 3, + adStatusErrorsOccurred = 2, + adStatusOK = 1, + adStatusUnwantedEvent = 5 + } + + const enum ExecuteOptionEnum { + adAsyncExecute = 16, + adAsyncFetch = 32, + adAsyncFetchNonBlocking = 64, + adExecuteNoRecords = 128, + adExecuteRecord = 2048, + adExecuteStream = 1024, + adOptionUnspecified = -1 + } + + const enum FieldAttributeEnum { + adFldCacheDeferred = 4096, + adFldFixed = 16, + adFldIsChapter = 8192, + adFldIsCollection = 262144, + adFldIsDefaultStream = 131072, + adFldIsNullable = 32, + adFldIsRowURL = 65536, + adFldKeyColumn = 32768, + adFldLong = 128, + adFldMayBeNull = 64, + adFldMayDefer = 2, + adFldNegativeScale = 16384, + adFldRowID = 256, + adFldRowVersion = 512, + adFldUnknownUpdatable = 8, + adFldUnspecified = -1, + adFldUpdatable = 4 + } + + const enum FieldEnum { + adDefaultStream = -1, + adRecordURL = -2 + } + + const enum FieldStatusEnum { + adFieldAlreadyExists = 26, + adFieldBadStatus = 12, + adFieldCannotComplete = 20, + adFieldCannotDeleteSource = 23, + adFieldCantConvertValue = 2, + adFieldCantCreate = 7, + adFieldDataOverflow = 6, + adFieldDefault = 13, + adFieldDoesNotExist = 16, + adFieldIgnore = 15, + adFieldIntegrityViolation = 10, + adFieldInvalidURL = 17, + adFieldIsNull = 3, + adFieldOK = 0, + adFieldOutOfSpace = 22, + adFieldPendingChange = 262144, + adFieldPendingDelete = 131072, + adFieldPendingInsert = 65536, + adFieldPendingUnknown = 524288, + adFieldPendingUnknownDelete = 1048576, + adFieldPermissionDenied = 9, + adFieldReadOnly = 24, + adFieldResourceExists = 19, + adFieldResourceLocked = 18, + adFieldResourceOutOfScope = 25, + adFieldSchemaViolation = 11, + adFieldSignMismatch = 5, + adFieldTruncated = 4, + adFieldUnavailable = 8, + adFieldVolumeNotFound = 21 + } + + const enum FilterGroupEnum { + adFilterAffectedRecords = 2, + adFilterConflictingRecords = 5, + adFilterFetchedRecords = 3, + adFilterNone = 0, + adFilterPendingRecords = 1, + adFilterPredicate = 4 + } + + const enum GetRowsOptionEnum { + adGetRowsRest = -1 + } + + const enum IsolationLevelEnum { + adXactBrowse = 256, + adXactChaos = 16, + adXactCursorStability = 4096, + adXactIsolated = 1048576, + adXactReadCommitted = 4096, + adXactReadUncommitted = 256, + adXactRepeatableRead = 65536, + adXactSerializable = 1048576, + adXactUnspecified = -1 + } + + const enum LineSeparatorEnum { + adCR = 13, + adCRLF = -1, + adLF = 10 + } + + const enum LockTypeEnum { + adLockBatchOptimistic = 4, + adLockOptimistic = 3, + adLockPessimistic = 2, + adLockReadOnly = 1, + adLockUnspecified = -1 + } + + const enum MarshalOptionsEnum { + adMarshalAll = 0, + adMarshalModifiedOnly = 1 + } + + const enum MoveRecordOptionsEnum { + adMoveAllowEmulation = 4, + adMoveDontUpdateLinks = 2, + adMoveOverWrite = 1, + adMoveUnspecified = -1 + } + + const enum ObjectStateEnum { + adStateClosed = 0, + adStateConnecting = 2, + adStateExecuting = 4, + adStateFetching = 8, + adStateOpen = 1 + } + + const enum ParameterAttributesEnum { + adParamLong = 128, + adParamNullable = 64, + adParamSigned = 16 + } + + const enum ParameterDirectionEnum { + adParamInput = 1, + adParamInputOutput = 3, + adParamOutput = 2, + adParamReturnValue = 4, + adParamUnknown = 0 + } + + const enum PersistFormatEnum { + adPersistADTG = 0, + adPersistXML = 1 + } + + const enum PositionEnum { + adPosBOF = -2, + adPosEOF = -3, + adPosUnknown = -1 + } + + const enum PositionEnum_Param { + adPosBOF = -2, + adPosEOF = -3, + adPosUnknown = -1 + } + + const enum PropertyAttributesEnum { + adPropNotSupported = 0, + adPropOptional = 2, + adPropRead = 512, + adPropRequired = 1, + adPropWrite = 1024 + } + + const enum RecordCreateOptionsEnum { + adCreateCollection = 8192, + adCreateNonCollection = 0, + adCreateOverwrite = 67108864, + adCreateStructDoc = -2147483648, + adFailIfNotExists = -1, + adOpenIfExists = 33554432 + } + + const enum RecordOpenOptionsEnum { + adDelayFetchFields = 32768, + adDelayFetchStream = 16384, + adOpenAsync = 4096, + adOpenExecuteCommand = 65536, + adOpenOutput = 8388608, + adOpenRecordUnspecified = -1, + adOpenSource = 8388608 + } + + const enum RecordStatusEnum { + adRecCanceled = 256, + adRecCantRelease = 1024, + adRecConcurrencyViolation = 2048, + adRecDBDeleted = 262144, + adRecDeleted = 4, + adRecIntegrityViolation = 4096, + adRecInvalid = 16, + adRecMaxChangesExceeded = 8192, + adRecModified = 2, + adRecMultipleChanges = 64, + adRecNew = 1, + adRecObjectOpen = 16384, + adRecOK = 0, + adRecOutOfMemory = 32768, + adRecPendingChanges = 128, + adRecPermissionDenied = 65536, + adRecSchemaViolation = 131072, + adRecUnmodified = 8 + } + + const enum RecordTypeEnum { + adCollectionRecord = 1, + adSimpleRecord = 0, + adStructDoc = 2 + } + + const enum ResyncEnum { + adResyncAllValues = 2, + adResyncUnderlyingValues = 1 + } + + const enum SaveOptionsEnum { + adSaveCreateNotExist = 1, + adSaveCreateOverWrite = 2 + } + + const enum SchemaEnum { + adSchemaActions = 41, + adSchemaAsserts = 0, + adSchemaCatalogs = 1, + adSchemaCharacterSets = 2, + adSchemaCheckConstraints = 5, + adSchemaCollations = 3, + adSchemaColumnPrivileges = 13, + adSchemaColumns = 4, + adSchemaColumnsDomainUsage = 11, + adSchemaCommands = 42, + adSchemaConstraintColumnUsage = 6, + adSchemaConstraintTableUsage = 7, + adSchemaCubes = 32, + adSchemaDBInfoKeywords = 30, + adSchemaDBInfoLiterals = 31, + adSchemaDimensions = 33, + adSchemaForeignKeys = 27, + adSchemaFunctions = 40, + adSchemaHierarchies = 34, + adSchemaIndexes = 12, + adSchemaKeyColumnUsage = 8, + adSchemaLevels = 35, + adSchemaMeasures = 36, + adSchemaMembers = 38, + adSchemaPrimaryKeys = 28, + adSchemaProcedureColumns = 29, + adSchemaProcedureParameters = 26, + adSchemaProcedures = 16, + adSchemaProperties = 37, + adSchemaProviderSpecific = -1, + adSchemaProviderTypes = 22, + adSchemaReferentialConstraints = 9, + adSchemaReferentialContraints = 9, + adSchemaSchemata = 17, + adSchemaSets = 43, + adSchemaSQLLanguages = 18, + adSchemaStatistics = 19, + adSchemaTableConstraints = 10, + adSchemaTablePrivileges = 14, + adSchemaTables = 20, + adSchemaTranslations = 21, + adSchemaTrustees = 39, + adSchemaUsagePrivileges = 15, + adSchemaViewColumnUsage = 24, + adSchemaViews = 23, + adSchemaViewTableUsage = 25 + } + + const enum SearchDirection { + adSearchBackward = -1, + adSearchForward = 1 + } + + const enum SearchDirectionEnum { + adSearchBackward = -1, + adSearchForward = 1 + } + + const enum SeekEnum { + adSeekAfter = 8, + adSeekAfterEQ = 4, + adSeekBefore = 32, + adSeekBeforeEQ = 16, + adSeekFirstEQ = 1, + adSeekLastEQ = 2 + } + + const enum StreamOpenOptionsEnum { + adOpenStreamAsync = 1, + adOpenStreamFromRecord = 4, + adOpenStreamUnspecified = -1 + } + + const enum StreamReadEnum { + adReadAll = -1, + adReadLine = -2 + } + + const enum StreamTypeEnum { + adTypeBinary = 1, + adTypeText = 2 + } + + const enum StreamWriteEnum { + adWriteChar = 0, + adWriteLine = 1, + stWriteChar = 0, + stWriteLine = 1 + } + + const enum StringFormatEnum { + adClipString = 2 + } + + const enum XactAttributeEnum { + adXactAbortRetaining = 262144, + adXactAsyncPhaseOne = 524288, + adXactCommitRetaining = 131072, + adXactSyncPhaseOne = 1048576 + } + + //Interfaces + interface Command { + ActiveConnection: Connection; + Cancel: () => void; + CommandStream: any /*VT_UNKNOWN*/; + CommandText: string; + CommandTimeout: number; + CommandType: CommandTypeEnum; + CreateParameter: (Name?: string, Type?: DataTypeEnum, Direction?: ParameterDirectionEnum, Size?: number, Value?: any) => Parameter; + Dialect: string; + Execute: (RecordsAffected?: any, Parameters?: any, Options?: number) => Recordset; + Name: string; + NamedParameters: boolean; + Parameters: Parameters; + Prepared: boolean; + Properties: Properties; + State: number; + } + + interface Connection { + Attributes: number; + BeginTrans: () => number; + Cancel: () => void; + Close: () => void; + CommandTimeout: number; + CommitTrans: () => void; + ConnectionString: string; + ConnectionTimeout: number; + CursorLocation: CursorLocationEnum; + DefaultDatabase: string; + Errors: Errors; + Execute: (CommandText: string, RecordsAffected: any, Options?: number) => Recordset; + IsolationLevel: IsolationLevelEnum; + Mode: ConnectModeEnum; + Open: (ConnectionString?: string, UserID?: string, Password?: string, Options?: number) => void; + OpenSchema: (Schema: SchemaEnum, Restrictions?: any, SchemaID?: any) => Recordset; + Properties: Properties; + Provider: string; + RollbackTrans: () => void; + State: number; + Version: string; + } + + interface Error { + Description: string; + HelpContext: number; + HelpFile: string; + NativeError: number; + Number: number; + Source: string; + SQLState: string; + } + + interface Errors { + Clear: () => void; + Count: number; + Item: (Index: any) => Error; + Refresh: () => void; + } + + interface Field { + ActualSize: number; + AppendChunk: (Data: any) => void; + Attributes: number; + DataFormat: any /*VT_UNKNOWN*/; + DefinedSize: number; + GetChunk: (Length: number) => any; + Name: string; + NumericScale: number; + OriginalValue: any; + Precision: number; + Properties: Properties; + Status: number; + Type: DataTypeEnum; + UnderlyingValue: any; + Value: any; + } + + interface Fields { + _Append: (Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum) => void; + Append: (Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum, FieldValue?: any) => void; + CancelUpdate: () => void; + Count: number; + Delete: (Index: any) => void; + Item: (Index: any) => Field; + Refresh: () => void; + Resync: (ResyncValues?: ResyncEnum) => void; + Update: () => void; + } + + interface Parameter { + AppendChunk: (Val: any) => void; + Attributes: number; + Direction: ParameterDirectionEnum; + Name: string; + NumericScale: number; + Precision: number; + Properties: Properties; + Size: number; + Type: DataTypeEnum; + Value: any; + } + + interface Parameters { + Append: (Object: any /*VT_DISPATCH*/) => void; + Count: number; + Delete: (Index: any) => void; + Item: (Index: any) => Parameter; + Refresh: () => void; + } + + interface Properties { + Count: number; + Item: (Index: any) => Property; + Refresh: () => void; + } + + interface Property { + Attributes: number; + Name: string; + Type: DataTypeEnum; + Value: any; + } + + interface Record { + ActiveConnection: any; + Cancel: () => void; + Close: () => void; + CopyRecord: (Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: CopyRecordOptionsEnum, Async?: boolean) => string; + DeleteRecord: (Source?: string, Async?: boolean) => void; + Fields: Fields; + GetChildren: () => Recordset; + Mode: ConnectModeEnum; + MoveRecord: (Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: MoveRecordOptionsEnum, Async?: boolean) => string; + Open: (Source: any, ActiveConnection: any, Mode?: ConnectModeEnum, CreateOptions?: RecordCreateOptionsEnum, Options?: RecordOpenOptionsEnum, UserName?: string, Password?: string) => void; + ParentURL: string; + Properties: Properties; + RecordType: RecordTypeEnum; + Source: any; + State: ObjectStateEnum; + } + + interface Recordset { + _xClone: () => Recordset; + _xResync: (AffectRecords?: AffectEnum) => void; + _xSave: (FileName?: string, PersistFormat?: PersistFormatEnum) => void; + AbsolutePage: PositionEnum; + AbsolutePosition: PositionEnum; + ActiveCommand: any /*VT_DISPATCH*/; + ActiveConnection: any /*VT_DISPATCH*/; + AddNew: (FieldList?: any, Values?: any) => void; + BOF: boolean; + Bookmark: any; + CacheSize: number; + Cancel: () => void; + CancelBatch: (AffectRecords?: AffectEnum) => void; + CancelUpdate: () => void; + Clone: (LockType?: LockTypeEnum) => Recordset; + Close: () => void; + Collect: (Index: any) => any; //Also has setter with parameters + CompareBookmarks: (Bookmark1: any, Bookmark2: any) => CompareEnum; + CursorLocation: CursorLocationEnum; + CursorType: CursorTypeEnum; + DataMember: string; + DataSource: any /*VT_UNKNOWN*/; + Delete: (AffectRecords?: AffectEnum) => void; + EditMode: EditModeEnum; + EOF: boolean; + Fields: Fields; + Filter: any; + Find: (Criteria: string, SkipRecords?: number, SearchDirection?: SearchDirectionEnum, Start?: any) => void; + GetRows: (Rows?: number, Start?: any, Fields?: any) => any; + GetString: (StringFormat?: StringFormatEnum, NumRows?: number, ColumnDelimeter?: string, RowDelimeter?: string, NullExpr?: string) => string; + Index: string; + LockType: LockTypeEnum; + MarshalOptions: MarshalOptionsEnum; + MaxRecords: number; + Move: (NumRecords: number, Start?: any) => void; + MoveFirst: () => void; + MoveLast: () => void; + MoveNext: () => void; + MovePrevious: () => void; + NextRecordset: (RecordsAffected?: any) => Recordset; + Open: (Source: any, ActiveConnection: any, CursorType?: CursorTypeEnum, LockType?: LockTypeEnum, Options?: number) => void; + PageCount: number; + PageSize: number; + Properties: Properties; + RecordCount: number; + Requery: (Options?: number) => void; + Resync: (AffectRecords?: AffectEnum, ResyncValues?: ResyncEnum) => void; + Save: (Destination: any, PersistFormat?: PersistFormatEnum) => void; + Seek: (KeyValues: any, SeekOption?: SeekEnum) => void; + Sort: string; + Source: any /*VT_DISPATCH*/; + State: number; + Status: number; + StayInSync: boolean; + Supports: (CursorOptions: CursorOptionEnum) => boolean; + Update: (Fields?: any, Values?: any) => void; + UpdateBatch: (AffectRecords?: AffectEnum) => void; + } + + interface Stream { + Cancel: () => void; + Charset: string; + Close: () => void; + CopyTo: (DestStream: Stream, CharNumber?: number) => void; + EOS: boolean; + Flush: () => void; + LineSeparator: LineSeparatorEnum; + LoadFromFile: (FileName: string) => void; + Mode: ConnectModeEnum; + Open: (Source: any, Mode?: ConnectModeEnum, Options?: StreamOpenOptionsEnum, UserName?: string, Password?: string) => void; + Position: number; + Read: (NumBytes?: number) => any; + ReadText: (NumChars?: number) => string; + SaveToFile: (FileName: string, Options?: SaveOptionsEnum) => void; + SetEOS: () => void; + Size: number; + SkipLine: () => void; + State: ObjectStateEnum; + Type: StreamTypeEnum; + Write: (Buffer: any) => void; + WriteText: (Data: string, Options?: StreamWriteEnum) => void; + } + +} + +interface ActiveXObject { + new (progID: 'ADODB.Connection'): ADODB.Connection; + new (progID: 'ADODB.Record'): ADODB.Record; + new (progID: 'ADODB.Stream'): ADODB.Stream; + new (progID: 'ADODB.Command'): ADODB.Command; + new (progID: 'ADODB.Recordset'): ADODB.Recordset; + new (progID: 'ADODB.Parameter'): ADODB.Parameter; +} + diff --git a/ts-activex/microsoft-scripting-runtime-tests.ts b/ts-activex/microsoft-scripting-runtime-tests.ts index 623b48368a..d08dc5cf96 100644 --- a/ts-activex/microsoft-scripting-runtime-tests.ts +++ b/ts-activex/microsoft-scripting-runtime-tests.ts @@ -26,7 +26,7 @@ var showDriveType = (drive: Scripting.Drive) => { //Generates a string describing the attributes of a file or folder. var showFileAttributes = (file: Scripting.File) => { var attr = file.Attributes; - if (attr == 0) { + if (attr === 0) { return 'Normal'; } var attributeStrings: string[] = []; @@ -44,24 +44,24 @@ var showFileAttributes = (file: Scripting.File) => { //source --https://msdn.microsoft.com/en-us/library/ts2t8ybh(v=vs.84).aspx var showFreeSpace = (drvPath: string) => { - var fso = new ActiveXObject("Scripting.FileSystemObject"); + var fso = new ActiveXObject('Scripting.FileSystemObject'); var d = fso.GetDrive(fso.GetDriveName(drvPath)); - var s = "Drive " + drvPath + " - "; - s += d.VolumeName + "
      "; - s += "Free Space: " + d.FreeSpace / 1024 + " Kbytes"; + var s = 'Drive ' + drvPath + ' - '; + s += d.VolumeName + '
      '; + s += 'Free Space: ' + d.FreeSpace / 1024 + ' Kbytes'; return (s); }; //source -- https://msdn.microsoft.com/en-us/library/kaf6yaft(v=vs.84).aspx var getALine = (filespec: string) => { - var fso = new ActiveXObject("Scripting.FileSystemObject"); + var fso = new ActiveXObject('Scripting.FileSystemObject'); var file = fso.OpenTextFile(filespec, Scripting.IOMode.ForReading, false); - var s = ""; + var s = ''; while (!file.AtEndOfLine) { s += file.Read(1); } file.Close(); return (s); -} \ No newline at end of file +}; diff --git a/ts-activex/microsoft-scripting-runtime.d.ts b/ts-activex/microsoft-scripting-runtime.d.ts index 0f2f734818..fd50b7504f 100644 --- a/ts-activex/microsoft-scripting-runtime.d.ts +++ b/ts-activex/microsoft-scripting-runtime.d.ts @@ -1,5 +1,5 @@ // Type definitions for Microsoft Scripting Runtime -// Project: https://msdn.microsoft.com/en-us/library/bstcxhf7.aspx?f=255&MSPPError=-2147217396 +// Project: https://msdn.microsoft.com/en-us/library/bstcxhf7.aspx // Definitions by: Zev Spitz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -60,14 +60,14 @@ declare namespace Scripting { TristateUseDefault = -2 } - //Classes + //Interfaces interface Dictionary { Add: (Key: any, Item: any) => void; CompareMode: CompareMethod; Count: number; Exists: (Key: any) => boolean; HashVal: (Key: any) => any; - Item: (Key: any) => any //Also has setter with parameters; + Item: (Key: any) => any; //Also has setter with parameters Items: () => any; Key: (Key: any) => any; Keys: () => any; @@ -204,3 +204,4 @@ interface ActiveXObject { new (progID: 'Scripting.FileSystemObject'): Scripting.FileSystemObject; new (progID: 'Scripting.Encoder'): Scripting.Encoder; } + diff --git a/ts-activex/microsoft-windows-image-acquisition-tests.ts b/ts-activex/windows-image-acquisition-tests.ts similarity index 82% rename from ts-activex/microsoft-windows-image-acquisition-tests.ts rename to ts-activex/windows-image-acquisition-tests.ts index 66a9d75a7d..ae394a99f8 100644 --- a/ts-activex/microsoft-windows-image-acquisition-tests.ts +++ b/ts-activex/windows-image-acquisition-tests.ts @@ -1,4 +1,4 @@ -/// +/// //source -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms630826(v=vs.85).aspx @@ -6,17 +6,17 @@ //Convert a file var commonDialog = new ActiveXObject('WIA.CommonDialog'); var img = commonDialog.ShowAcquireImage(); -if (img.FormatID != WIA.FormatID.wiaFormatJPEG) { +if (img.FormatID !== WIA.FormatID.wiaFormatJPEG) { var ip = new ActiveXObject('WIA.ImageProcess'); ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID); - ip.Filters.Item(1).Properties.Item("FormatID").Value = WIA.FormatID.wiaFormatJPEG; + ip.Filters.Item(1).Properties.Item('FormatID').Value = WIA.FormatID.wiaFormatJPEG; img = ip.Apply(img); } //Take a picture var dev = commonDialog.ShowSelectDevice(); -if (dev.Type == WIA.WiaDeviceType.CameraDeviceType) { +if (dev.Type === WIA.WiaDeviceType.CameraDeviceType) { var itm = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture); } @@ -32,8 +32,8 @@ while (!e.atEnd()) { s += '[vector of data]'; } else { s += p.Value; - if (p.SubType != WIA.WiaSubType.UnspecifiedSubType) { - if (p.Value != p.SubTypeDefault) { + if (p.SubType !== WIA.WiaSubType.UnspecifiedSubType) { + if (p.Value !== p.SubTypeDefault) { s += ' (Default = ' + p.SubTypeDefault + ')'; } } @@ -45,7 +45,7 @@ while (!e.atEnd()) { switch (p.SubType) { case WIA.WiaSubType.FlagSubType: case WIA.WiaSubType.ListSubType: - if (p.SubType == WIA.WiaSubType.FlagSubType) { + if (p.SubType === WIA.WiaSubType.FlagSubType) { s += ' [valid flags include: '; } else { s += ' [valid values include: '; diff --git a/ts-activex/microsoft-windows-image-acquisition.d.ts b/ts-activex/windows-image-acquisition.d.ts similarity index 83% rename from ts-activex/microsoft-windows-image-acquisition.d.ts rename to ts-activex/windows-image-acquisition.d.ts index ccae387346..7be1884a4e 100644 --- a/ts-activex/microsoft-windows-image-acquisition.d.ts +++ b/ts-activex/windows-image-acquisition.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Microsoft Windows Image Acquisition +// Type definitions for Microsoft Windows Image Acquisition Library v2.0 // Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms630827(v=vs.85).aspx // Definitions by: Zev Spitz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,34 +8,34 @@ declare namespace WIA { //Enums - type CommandID = - "{04E725B0-ACAE-11D2-A093-00C04F72DC3C}" //wiaCommandChangeDocument - | "{E208C170-ACAD-11D2-A093-00C04F72DC3C}" //wiaCommandDeleteAllItems - | "{9B26B7B2-ACAD-11D2-A093-00C04F72DC3C}" //wiaCommandSynchronize - | "{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}" //wiaCommandTakePicture - | "{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}" //wiaCommandUnloadDocument + type CommandID = + "'{04E725B0-ACAE-11D2-A093-00C04F72DC3C}'" //wiaCommandChangeDocument + | "'{E208C170-ACAD-11D2-A093-00C04F72DC3C}'" //wiaCommandDeleteAllItems + | "'{9B26B7B2-ACAD-11D2-A093-00C04F72DC3C}'" //wiaCommandSynchronize + | "'{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}'" //wiaCommandTakePicture + | "'{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}'"; //wiaCommandUnloadDocument const CommandID: { wiaCommandChangeDocument: CommandID, wiaCommandDeleteAllItems: CommandID, wiaCommandSynchronize: CommandID, wiaCommandTakePicture: CommandID, wiaCommandUnloadDocument: CommandID - } + }; - type EventID = - "{A28BBADE-64B6-11D2-A231-00C04FA31809}" //wiaEventDeviceConnected - | "{143E4E83-6497-11D2-A231-00C04FA31809}" //wiaEventDeviceDisconnected - | "{4C8F4EF5-E14F-11D2-B326-00C04F68CE61}" //wiaEventItemCreated - | "{1D22A559-E14F-11D2-B326-00C04F68CE61}" //wiaEventItemDeleted - | "{C686DCEE-54F2-419E-9A27-2FC7F2E98F9E}" //wiaEventScanEmailImage - | "{C00EB793-8C6E-11D2-977A-0000F87A926F}" //wiaEventScanFaxImage - | "{9B2B662C-6185-438C-B68B-E39EE25E71CB}" //wiaEventScanFilmImage - | "{A6C5A715-8C6E-11D2-977A-0000F87A926F}" //wiaEventScanImage - | "{FC4767C1-C8B3-48A2-9CFA-2E90CB3D3590}" //wiaEventScanImage2 - | "{154E27BE-B617-4653-ACC5-0FD7BD4C65CE}" //wiaEventScanImage3 - | "{A65B704A-7F3C-4447-A75D-8A26DFCA1FDF}" //wiaEventScanImage4 - | "{9D095B89-37D6-4877-AFED-62A297DC6DBE}" //wiaEventScanOCRImage - | "{B441F425-8C6E-11D2-977A-0000F87A926F}" //wiaEventScanPrintImage + type EventID = + "'{A28BBADE-64B6-11D2-A231-00C04FA31809}'" //wiaEventDeviceConnected + | "'{143E4E83-6497-11D2-A231-00C04FA31809}'" //wiaEventDeviceDisconnected + | "'{4C8F4EF5-E14F-11D2-B326-00C04F68CE61}'" //wiaEventItemCreated + | "'{1D22A559-E14F-11D2-B326-00C04F68CE61}'" //wiaEventItemDeleted + | "'{C686DCEE-54F2-419E-9A27-2FC7F2E98F9E}'" //wiaEventScanEmailImage + | "'{C00EB793-8C6E-11D2-977A-0000F87A926F}'" //wiaEventScanFaxImage + | "'{9B2B662C-6185-438C-B68B-E39EE25E71CB}'" //wiaEventScanFilmImage + | "'{A6C5A715-8C6E-11D2-977A-0000F87A926F}'" //wiaEventScanImage + | "'{FC4767C1-C8B3-48A2-9CFA-2E90CB3D3590}'" //wiaEventScanImage2 + | "'{154E27BE-B617-4653-ACC5-0FD7BD4C65CE}'" //wiaEventScanImage3 + | "'{A65B704A-7F3C-4447-A75D-8A26DFCA1FDF}'" //wiaEventScanImage4 + | "'{9D095B89-37D6-4877-AFED-62A297DC6DBE}'" //wiaEventScanOCRImage + | "'{B441F425-8C6E-11D2-977A-0000F87A926F}'"; //wiaEventScanPrintImage const EventID: { wiaEventDeviceConnected: EventID, wiaEventDeviceDisconnected: EventID, @@ -50,29 +50,29 @@ declare namespace WIA { wiaEventScanImage4: EventID, wiaEventScanOCRImage: EventID, wiaEventScanPrintImage: EventID - } + }; - type FormatID = - "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}" //wiaFormatBMP - | "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}" //wiaFormatGIF - | "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}" //wiaFormatJPEG - | "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}" //wiaFormatPNG - | "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}" //wiaFormatTIFF + type FormatID = + "'{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatBMP + | "'{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatGIF + | "'{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatJPEG + | "'{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatPNG + | "'{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}'"; //wiaFormatTIFF const FormatID: { wiaFormatBMP: FormatID, wiaFormatGIF: FormatID, wiaFormatJPEG: FormatID, wiaFormatPNG: FormatID, wiaFormatTIFF: FormatID - } + }; - type Miscellaneous = - "*" //wiaAnyDeviceID - | "{00000000-0000-0000-0000-000000000000}" //wiaIDUnknown + type Miscellaneous = + "'*'" //wiaAnyDeviceID + | "'{00000000-0000-0000-0000-000000000000}'"; //wiaIDUnknown const Miscellaneous: { wiaAnyDeviceID: Miscellaneous, wiaIDUnknown: Miscellaneous - } + }; const enum WiaDeviceType { CameraDeviceType = 2, @@ -185,7 +185,7 @@ declare namespace WIA { UnspecifiedSubType = 0 } - //Classes + //Interfaces interface CommonDialog { ShowAcquireImage: (DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean, CancelError?: boolean) => ImageFile; ShowAcquisitionWizard: (Device: Device) => any; @@ -361,7 +361,7 @@ declare namespace WIA { Count: number; Date: VarDate; ImageFile: (Width?: number, Height?: number) => ImageFile; - Item: (Index: number) => any //Also has setter with parameters; + Item: (Index: number) => any; //Also has setter with parameters Picture: (Width?: number, Height?: number) => any; Remove: (Index: number) => any; SetFromString: (Value: string, Resizable?: boolean, Unicode?: boolean) => void; @@ -378,3 +378,4 @@ interface ActiveXObject { new (progID: 'WIA.CommonDialog'): WIA.CommonDialog; new (progID: 'WIA.DeviceManager'): WIA.DeviceManager; } + diff --git a/turf/turf-2.0-tests.ts b/turf/turf-2.0-tests.ts new file mode 100644 index 0000000000..45d9dbcc42 --- /dev/null +++ b/turf/turf-2.0-tests.ts @@ -0,0 +1,522 @@ +/// + +/////////////////////////////////////////// +// Tests data initialisation +/////////////////////////////////////////// + +var point1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-75.343, 39.984] + } +}; + +var point2: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-75.534, 39.123] + } +}; + +var line: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "LineString", + "coordinates": [ + [-77.031669, 38.878605], + [-77.029609, 38.881946], + [-77.020339, 38.884084], + [-77.025661, 38.885821], + [-77.021884, 38.889563], + [-77.019824, 38.892368] + ] + } +}; + +var polygons: GeoJSON.FeatureCollection = { + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [-67.031021, 10.458102], + [-67.031021, 10.53372], + [-66.929397, 10.53372], + [-66.929397, 10.458102], + [-67.031021, 10.458102] + ]] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [-66.919784, 10.397325], + [-66.919784, 10.513467], + [-66.805114, 10.513467], + [-66.805114, 10.397325], + [-66.919784, 10.397325] + ]] + } + } + ] +}; + +var polygon1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [105.818939,21.004714], + [105.818939,21.061754], + [105.890007,21.061754], + [105.890007,21.004714], + [105.818939,21.004714] + ]] + } +}; + +var polygon2: GeoJSON.Feature = { + "type": "Feature", + "properties": { + "fill": "#00f" + }, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [-122.520217, 45.535693], + [-122.64038, 45.553967], + [-122.720031, 45.526554], + [-122.669906, 45.507309], + [-122.723464, 45.446643], + [-122.532577, 45.408574], + [-122.487258, 45.477466], + [-122.520217, 45.535693] + ]] + } +} + +var features: GeoJSON.FeatureCollection = { + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.522259, 35.4691] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.502754, 35.463455] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.508269, 35.463245] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.516809, 35.465779] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.515372, 35.467072] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.509363, 35.463053] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.511123, 35.466601] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.518547, 35.469327] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.519706, 35.469659] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.517839, 35.466998] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.508678, 35.464942] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.514914, 35.463453] + } + } + ] +}; + +var triangle: GeoJSON.Feature = { + "type": "Feature", + "properties": { + "a": 11, + "b": 122, + "c": 44 + }, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [-75.1221, 39.57], + [-75.58, 39.18], + [-75.97, 39.86], + [-75.1221, 39.57] + ]] + } +}; + +var aggregations = [ + { + aggregation: 'sum', + inField: 'population', + outField: 'pop_sum' + }, + { + aggregation: 'average', + inField: 'population', + outField: 'pop_avg' + }, + { + aggregation: 'median', + inField: 'population', + outField: 'pop_median' + }, + { + aggregation: 'min', + inField: 'population', + outField: 'pop_min' + }, + { + aggregation: 'max', + inField: 'population', + outField: 'pop_max' + }, + { + aggregation: 'deviation', + inField: 'population', + outField: 'pop_deviation' + }, + { + aggregation: 'variance', + inField: 'population', + outField: 'pop_variance' + }, + { + aggregation: 'count', + inField: '', + outField: 'point_count' + } +]; + +/////////////////////////////////////////// +// Tests Aggregation +/////////////////////////////////////////// + +// -- Test aggregate -- +var aggregated = turf.aggregate(polygons, points, aggregations); + +// -- Test average -- +var averaged = turf.average(polygons, points, 'population', 'pop_avg'); + +// -- Test count -- +var counted = turf.count(polygons, points, 'pt_count'); + +// -- Test deviation -- +var deviated = turf.deviation(polygons, points, 'population', 'pop_deviation'); + +// -- Test max -- +var aggregated = turf.max(polygons, points, 'population', 'max'); + +// -- Test median -- +var medians = turf.median(polygons, points, 'population', 'median'); + +// -- Test min -- +var minimums = turf.min(polygons, points, 'population', 'min'); + +// -- Test sum -- +var summed = turf.sum(polygons, points, 'population', 'sum'); + +// -- Test variance -- +var varianced = turf.variance(polygons, points, 'population', 'variance'); + +/////////////////////////////////////////// +// Tests Measurement +/////////////////////////////////////////// + +// -- Test along -- +var along = turf.along(line, 1, 'miles'); + +// -- Test area -- +var area = turf.area(polygons); + +// -- Test bboxPolygon -- +var bbox = [0, 0, 10, 10]; +var poly = turf.bboxPolygon(bbox); + +// -- Test bearing -- +var bearing = turf.bearing(point1, point2); + +// -- Test center +var centerPt = turf.center(features); + +// -- Test centroid -- +var centroidPt = turf.centroid(polygon1); + +// -- Test destination -- +var distance = 50; +var bearing = 90; +var units = 'miles'; +var destination = turf.destination(point1, distance, bearing, units); + +// -- Test distance -- +var units = "miles"; +var distance = turf.distance(point1, point2, units); + +// -- Test envelope -- +var enveloped = turf.envelope(polygons); + +// -- Test extent -- +var bbox = turf.extent(polygons); + +// -- Test lineDistance +var length = turf.lineDistance(line, 'miles'); + +// -- Test midpoint -- +var midpointed = turf.midpoint(point1, point2); + +// -- Test pointOnSurface -- +var pointOnPolygon = turf.pointOnSurface(polygon1); + +// -- Test size -- +var resized = turf.size(bbox, 2); + +// -- Test square -- +var squared = turf.square(bbox); + +/////////////////////////////////////////// +// Tests Transformation +/////////////////////////////////////////// + +// -- Test bezier -- +var curved = turf.bezier(line); + +// -- Test buffer -- +var buffered = turf.buffer(point1, 500, units); + +// -- Test concave -- +var hull = turf.concave(features, 1, 'miles'); + +// -- Test convex -- +var hull = turf.convex(features); + +// -- Test difference -- +var differenced = turf.difference(polygon1, polygon2); + +// -- Test intersect -- +var intersection = turf.intersect(polygon1, polygon2); + +// -- Test merge -- +var merged = turf.merge(polygons); + +// -- Test simplify -- +var tolerance = 0.01; +var simplified = turf.simplify(polygon1, tolerance, false); + +// -- Test union -- +var union = turf.union(polygon1, polygon2); + +/////////////////////////////////////////// +// Tests Misc +/////////////////////////////////////////// + +// -- Test combine -- +var combined = turf.combine(features); + +// -- Test explode -- +var points = turf.explode(polygon1); + +// -- Test flip -- +var flipedPoint = turf.flip(point1); + +// -- Test kinks -- +var kinks = turf.kinks(polygon1); + +// -- Test lineSlice -- +var sliced = turf.lineSlice(point1, point2, line); + +// -- Test pointOnLine -- +var snapped = turf.pointOnLine(line, point1); + +/////////////////////////////////////////// +// Tests Helper +/////////////////////////////////////////// + +// -- Test featurecollection -- +var fc = turf.featurecollection([point1, point2]); + +// -- Test linestring -- +var linestring1 = turf.linestring([ + [-21.964416, 64.148203], + [-21.956176, 64.141316], + [-21.93901, 64.135924], + [-21.927337, 64.136673] +]); +var linestring2 = turf.linestring([ + [-21.929054, 64.127985], + [-21.912918, 64.134726], + [-21.916007, 64.141016], + [-21.930084, 64.14446] +], {name: 'line 1', distance: 145}); + +// -- Test point -- +var pt1 = turf.point([-75.343, 39.984]); +var pt2 = turf.point([-75.343, 39.984], {name: 'point 1', distance: 145}); + +// -- Test polygon -- +var polygon = turf.polygon([[ + [-2.275543, 53.464547], + [-2.275543, 53.489271], + [-2.215118, 53.489271], + [-2.215118, 53.464547], + [-2.275543, 53.464547] +]], { name: 'poly1', population: 400}); + +/////////////////////////////////////////// +// Tests Data +/////////////////////////////////////////// + +// -- Test filter -- +var key = "species"; +var value = "oak"; +var filtered = turf.filter(features, key, value); + +// -- Test random -- +var randomPoints = turf.random('points', 100, { + bbox: [-70, 40, -60, 60] +}); + +var randomPoints = turf.random('points', 100, { + bbox: [-70, 40, -60, 60], + num_vertices: 2, + max_radial_length: 10 +}); + +// -- Test remove -- +var filtered = turf.remove(points, 'marker-color', '#00f'); + +// -- Test sample -- +var randomPoints = turf.random('points', 1000); +var sample = turf.sample(points, 10); + +/////////////////////////////////////////// +// Tests Interpolation +/////////////////////////////////////////// + +// -- Test hexGrid -- +var cellWidth = 50; +var hexgrid = turf.hexGrid(bbox, cellWidth, units); + +// -- Test isolines -- +var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; +var isolined = turf.isolines(points, 'z', 15, breaks); + +// -- Test planepoint -- +var zValue = turf.planepoint(point1, triangle); + +// -- Test pointGrid -- +var extent = [-70.823364, -33.553984, -70.473175, -33.302986]; +var cellWidth = 3; +var grid = turf.pointGrid(extent, cellWidth, units); + +// -- Test squareGrid -- +var squareGrid = turf.squareGrid(extent, cellWidth, units); + +// -- Test tin -- +var tin = turf.tin(points, 'z'); + +// -- Test triangleGrid -- +var triangleGrid = turf.triangleGrid(extent, cellWidth, units); + +/////////////////////////////////////////// +// Tests Joins +/////////////////////////////////////////// + +// -- Test inside -- +var isInside1 = turf.inside(point1, polygon); + +// -- Test tag -- +var tagged = turf.tag(points, triangleGrid, 'fill', 'marker-color'); + +// -- Test within -- +var ptsWithin = turf.within(points, polygons); + +/////////////////////////////////////////// +// Tests Classification +/////////////////////////////////////////// + +// -- Test jenks -- +var breaks = turf.jenks(points, 'population', 3); + +// -- Test nearest -- +var nearest = turf.nearest(point1, points); + +// -- Test quantile -- +var breaks = turf.quantile(points, 'population', [25, 50, 75, 99]); + +// -- Test reclass -- +var translations = [ + [0, 200, "small"], + [200, 400, "medium"], + [400, 600, "large"] +]; +var reclassed = turf.reclass(points, 'population', 'size', translations); diff --git a/turf/turf-2.0.d.ts b/turf/turf-2.0.d.ts new file mode 100644 index 0000000000..647df93398 --- /dev/null +++ b/turf/turf-2.0.d.ts @@ -0,0 +1,580 @@ +// Type definitions for Turf 2.0 +// Project: http://turfjs.org/ +// Definitions by: Guillaume Croteau +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module turf { + ////////////////////////////////////////////////////// + // Aggregation + ////////////////////////////////////////////////////// + + /** + * Calculates a series of aggregations for a set of points within a set of polygons. + * Sum, average, count, min, max, and deviation are supported. + * @param polygons Polygons with values on which to aggregate + * @param points Points to be aggregated + * @param aggregations An array of aggregation objects + * @returns Polygons with properties listed based on outField values in aggregations + */ + function aggregate(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, aggregations: Array<{aggregation: string, inField: string, outField: string}>): GeoJSON.FeatureCollection; + + /** + * Calculates the average value of a field for a set of points within a set of polygons. + * @param polygons Polygons with values on which to average + * @param points Points from which to calculate the average + * @param field The field in the points features from which to pull values to average + * @param outField The field in polygons to put results of the averages + * @returns Polygons with the value of outField set to the calculated averages + */ + function average(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, field: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Takes a set of points and a set of polygons and calculates the number of points that fall within the set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param countField A field to append to the attributes of the Polygon features representing Point counts + * @returns Polygons with countField appended + */ + function count(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, countField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the standard deviation value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in points from which to aggregate + * @param outField The field to append to polygons representing deviation + * @returns Polygons with appended field representing deviation + */ + function deviation(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the maximum value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField values + */ + function max(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the median value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField values + */ + function median(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the minimum value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField values + */ + function min(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the sum of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField + */ + function sum(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the variance value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField + */ + function variance(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // Measurement + ////////////////////////////////////////////////////// + + /** + * Takes a line and returns a point at a specified distance along the line. + * @param line Input line + * @param distance Distance along the line + * @param [units=miles] 'miles', 'kilometers', 'radians' or 'degrees' + * @returns Point along the line + */ + function along(line: GeoJSON.Feature, distance: number, units?: string): GeoJSON.Feature; + + /** + * Takes one or more features and returns their area in square meters. + * @param input Input features + * @returns Area in square meters + */ + function area(input: GeoJSON.Feature | GeoJSON.FeatureCollection): number; + + /** + * Takes a bbox and returns an equivalent polygon. + * @param bbox An Array of bounding box coordinates in the form: [xLow, yLow, xHigh, yHigh] + * @returns A Polygon representation of the bounding box + */ + function bboxPolygon(bbox: Array): GeoJSON.Feature; + + /** + * Takes two points and finds the geographic bearing between them. + * @param start Starting Point + * @param end Ending point + * @returns Bearing in decimal degrees + */ + function bearing(start: GeoJSON.Feature, end: GeoJSON.Feature): number; + + /** + * Takes a FeatureCollection and returns the absolute center point of all features. + * @param features Input features + * @returns A Point feature at the absolute center point of all input features + */ + function center(features: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes one or more features and calculates the centroid using the arithmetic mean of all vertices. + * This lessens the effect of small islands and artifacts when calculating the centroid of a set of polygons. + * @param features Input features + * @returns The centroid of the input features + */ + function centroid(features: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a Point and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers; and bearing in degrees. + * This uses the Haversine formula to account for global curvature. + * @param start Starting point + * @param distance Distance from the starting point + * @param bearing Ranging from -180 and 180 + * @param units 'miles', 'kilometers', 'radians', or 'degrees' + * @returns Destination point + */ + function destination(start: GeoJSON.Feature, distance: number, bearing: number, units: string): GeoJSON.Feature; + + /** + * Calculates the distance between two points in degress, radians, miles, or kilometers. + * This uses the Haversine formula to account for global curvature. + * @param from Origin point + * @param to Destination point + * @param [units=kilometers] 'miles', 'kilometers', 'radians', or 'degrees' + * @returns Distance between the two points + */ + function distance(from: GeoJSON.Feature, to: GeoJSON.Feature, units?: string): number; + + /** + * Takes any number of features and returns a rectangular Polygon that encompasses all vertices. + * @param fc Input features + * @returns A rectangular Polygon feature that encompasses all vertices + */ + function envelope(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a set of features, calculates the extent of all input features, and returns a bounding box. + * @param input Input features + * @returns The bounding box of input given as an array in WSEN order (west, south, east, north) + */ + function extent(input: GeoJSON.Feature | GeoJSON.FeatureCollection): Array; + + /** + * Takes a line and measures its length in the specified units. + * @param line Line to measure + * @param units 'miles', 'kilometers', 'radians', or 'degrees' + * @returns Length of the input line + */ + function lineDistance(line: GeoJSON.Feature, units: string): number; + + /** + * Takes two points and returns a point midway between them. + * @param pt1 First point + * @param pt2 Second point + * @returns A point midway between pt1 and pt2 + */ + function midpoint(pt1: GeoJSON.Feature, pt2: GeoJSON.Feature): GeoJSON.Feature; + + /** + * Takes a feature and returns a Point guaranteed to be on the surface of the feature. Given a Polygon, the point will be in the area of the polygon. + * Given a LineString, the point will be along the string. Given a Point, the point will the same as the input. + * @param input Any feature or set of features + * @returns A point on the surface of input + */ + function pointOnSurface(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a bounding box and returns a new bounding box with a size expanded or contracted by a factor of X. + * @param bbox A bounding box + * @param factor The ratio of the new bbox to the input bbox + * @returns The resized bbox + */ + function size(bbox: Array, factor: number): Array; + + /** + * Takes a bounding box and calculates the minimum square bounding box that would contain the input. + * @param bbox A bounding box + * @returns A square surrounding bbox + */ + function square(bbox: Array): Array; + + ////////////////////////////////////////////////////// + // Transformation + ////////////////////////////////////////////////////// + + /** + * Takes a line and returns a curved version by applying a Bezier spline algorithm. + * The bezier spline implementation is by Leszek Rybicki. + * @param line Input LineString + * @param [resolution=10000] Time in milliseconds between points + * @param [sharpness=0.85] A measure of how curvy the path should be between splines + * @returns Curved line + */ + function bezier(line: GeoJSON.Feature, resolution?: number, sharpness?: number): GeoJSON.Feature; + + /** + * Calculates a buffer for input features for a given radius. Units supported are miles, kilometers, and degrees. + * @param feature Input to be buffered + * @param distance Distance to draw the buffer + * @param units 'miles', 'kilometers', 'radians', or 'degrees' + * @returns Buffered features + */ + function buffer(feature: GeoJSON.Feature | GeoJSON.FeatureCollection, distance: number, units: string): GeoJSON.FeatureCollection | GeoJSON.FeatureCollection | GeoJSON.Polygon | GeoJSON.MultiPolygon; + + /** + * Takes a set of points and returns a concave hull polygon. Internally, this implements a Monotone chain algorithm. + * @param points Input points + * @param maxEdge The size of an edge necessary for part of the hull to become concave (in miles) + * @param units Used for maxEdge distance (miles or kilometers) + * @returns A concave hull + */ + function concave(points: GeoJSON.FeatureCollection, maxEdge: number, units: string): GeoJSON.Feature; + + /** + * Takes a set of points and returns a convex hull polygon. Internally this uses the convex-hull module that implements a monotone chain hull. + * @param input Input points + * @returns A convex hull + */ + function convex(input: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Finds the difference between two polygons by clipping the second polygon from the first. + * @param poly1 Input Polygon feaure + * @param poly2 Polygon feature to difference from poly1 + * @returns A Polygon feature showing the area of poly1 excluding the area of poly2 + */ + function difference(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + + /** + * Takes two polygons and finds their intersection. + * If they share a border, returns the border; if they don't intersect, returns undefined. + * @param poly1 The first polygon + * @param poly2 The second polygon + * @returns If poly1 and poly2 overlap, returns a Polygon feature representing the area they overlap; + * if poly1 and poly2 do not overlap, returns undefined; + * if poly1 and poly2 share a border, a MultiLineString of the locations where their borders are shared + */ + function intersect(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature | typeof undefined; + + /** + * Takes a set of polygons and returns a single merged polygon feature. + * If the input polygon features are not contiguous, this function returns a MultiPolygon feature. + * @param fc Input polygons + * @returns Merged polygon or multipolygon + */ + function merge(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a LineString or Polygon and returns a simplified version. + * Internally uses simplify-js to perform simplification. + * @param feature Feature to be simplified + * @param tolerance Simplification tolerance + * @param highQuality Whether or not to spend more time to create a higher-quality simplification with a different algorithm + * @returns A simplified feature + */ + function simplify(feature: GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection, tolerance: number, highQuality: boolean): GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection; + + /** + * Takes two polygons and returns a combined polygon. + * If the input polygons are not contiguous, this function returns a MultiPolygon feature. + * @param poly1 Input polygon + * @param poly2 Another input polygon + * @returns A combined Polygon or MultiPolygon feature + */ + function union(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + + ////////////////////////////////////////////////////// + // Misc + ////////////////////////////////////////////////////// + + /** + * Combines a FeatureCollection of Point, LineString, or Polygon features into MultiPoint, MultiLineString, or MultiPolygon features. + * @param fc A FeatureCollection of any type + * @returns A FeatureCollection of corresponding type to input + */ + function combine(fc: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + + /** + * Takes a feature or set of features and returns all positions as points. + * @param input Input features + * @returns Points representing the exploded input features + */ + function explode(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + + /** + * Takes input features and flips all of their coordinates from [x, y] to [y, x]. + * @param input Input features + * @returns A feature or set of features of the same type as input with flipped coordinates + */ + function flip(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature | GeoJSON.FeatureCollection; + + /** + * Takes a polygon and returns points at all self-intersections. + * @param polygon Input polygon + * @returns Self-intersections + */ + function kinks(polygon: GeoJSON.Feature): GeoJSON.FeatureCollection; + + /** + * Takes a line, a start Point, and a stop point and returns the line in between those points. + * @param point1 Starting point + * @param point2 Stopping point + * @param line Line to slice + * @returns Sliced line + */ + function lineSlice(point1: GeoJSON.Feature, point2: GeoJSON.Feature, line: GeoJSON.Feature): GeoJSON.Feature; + + /** + * Takes a Point and a LineString and calculates the closest Point on the LineString. + * @param line Line to snap to + * @param point Point to snap from + * @returns Closest point on the line to point + */ + function pointOnLine(line: GeoJSON.Feature, point: GeoJSON.Feature): GeoJSON.Feature; + + ////////////////////////////////////////////////////// + // Helper + ////////////////////////////////////////////////////// + + /** + * Takes one or more Features and creates a FeatureCollection. + * @param features Input features + * @returns A FeatureCollection of input features + */ + function featurecollection(features: Array>): GeoJSON.FeatureCollection; + + /** + * Creates a LineString based on a coordinate array. Properties can be added optionally. + * @param coordinates An array of Positions + * @param [properties] An Object of key-value pairs to add as properties + * @returns A LineString feature + */ + function linestring(coordinates: Array>, properties?: any): GeoJSON.Feature; + + /** + * Takes coordinates and properties (optional) and returns a new Point feature. + * @param coordinates Longitude, latitude position (each in decimal degrees) + * @param [properties] An Object of key-value pairs to add as properties + * @returns A Point feature + */ + function point(coordinates: Array, properties?: any): GeoJSON.Feature; + + /** + * Takes an array of LinearRings and optionally an Object with properties and returns a Polygon feature. + * @param rings An array of LinearRings + * @param [properties] An Object of key-value pairs to add as properties + * @returns A Polygon feature + */ + function polygon(rings: Array>>, properties?: any): GeoJSON.Feature; + + ////////////////////////////////////////////////////// + // Data + ////////////////////////////////////////////////////// + + /** + * Takes a FeatureCollection and filters it by a given property and value. + * @param features Input features + * @param key The property on which to filter + * @param value The value of that property on which to filter + * @returns A filtered collection with only features that match input key and value + */ + function filter(features: GeoJSON.FeatureCollection, key: string, value: string): GeoJSON.FeatureCollection; + + /** + * Generates random GeoJSON data, including Points and Polygons, for testing and experimentation. + * @param [type='point'] Type of features desired: 'points' or 'polygons' + * @param [count=1] How many geometries should be generated. + * @param [options] Options relevant to the feature desired. Can include: + * - A bounding box inside of which geometries are placed. In the case of Point features, they are guaranteed to be within this bounds, while Polygon features have their centroid within the bounds. + * - The number of vertices added to polygon features. Default is 10; + * - The total number of decimal degrees longitude or latitude that a polygon can extent outwards to from its center. Default is 10. + * @returns Generated random features + */ + function random(type?: string, count?: number, options?: {bbox?: Array; num_vertices?: number; max_radial_length?: number;}): GeoJSON.FeatureCollection; + + /** + * Takes a FeatureCollection of any type, a property, and a value and returns a FeatureCollection with features matching that property-value pair removed. + * @param features Set of input features + * @param property The property to remove + * @param value The value to remove + * @returns The resulting FeatureCollection without features that match the property-value pair + */ + function remove(features: GeoJSON.FeatureCollection, property: string, value: string): GeoJSON.FeatureCollection; + + /** + * Takes a FeatureCollection and returns a FeatureCollection with given number of features at random. + * @param features Set of input features + * @param n Number of features to select + * @returns A FeatureCollection with n features + */ + function sample(features: GeoJSON.FeatureCollection, n: number): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // Interpolation + ////////////////////////////////////////////////////// + + /** + * Takes a bounding box and a cell size in degrees and returns a FeatureCollection of flat-topped hexagons (Polygon features) aligned in an "odd-q" vertical grid as described in Hexagonal Grids. + * @param bbox Bounding box in [minX, minY, maxX, maxY] order + * @param cellWidth Width of cell in specified units + * @param units Used in calculating cellWidth ('miles' or 'kilometers') + * @returns A hexagonal grid + */ + function hexGrid(bbox: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + + /** + * Takes points with z-values and an array of value breaks and generates isolines. + * @param points Input points + * @param z The property name in points from which z-values will be pulled + * @param resolution Resolution of the underlying grid + * @param breaks Where to draw contours + * @returns Isolines + */ + function isolines(points: GeoJSON.FeatureCollection, z: string, resolution: number, breaks: Array): GeoJSON.FeatureCollection; + + /** + * Takes a triangular plane as a Polygon and a Point within that triangle and returns the z-value at that point. + * The Polygon needs to have properties a, b, and c that define the values at its three corners. + * @param interpolatedPoint The Point for which a z-value will be calculated + * @param triangle A Polygon feature with three vertices + * @returns The z-value for interpolatedPoint + */ + function planepoint(interpolatedpoint: GeoJSON.Feature, triangle: GeoJSON.Feature): number; + + /** + * Takes a bounding box and a cell depth and returns a set of points in a grid. + * @param extent Extent in [minX, minY, maxX, maxY] order + * @param cellWidth The distance across each cell + * @param units Used in calculating cellWidth ('miles' or 'kilometers') + * @returns Grid of points + */ + function pointGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + + /** + * Takes a bounding box and a cell depth and returns a set of square polygons in a grid. + * @param extent Extent in [minX, minY, maxX, maxY] order + * @param cellWidth Width of each cell + * @param units Used in calculating cellWidth ('miles' or 'kilometers') + * @returns Grid of polygons + */ + function squareGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + + /** + * Takes a set of points and the name of a z-value property and creates a Triangulated Irregular Network, or a TIN for short, returned as a collection of Polygons. + * These are often used for developing elevation contour maps or stepped heat visualizations. + * This triangulates the points, as well as adds properties called a, b, and c representing the value of the given propertyName at each of the points that represent the corners of the triangle. + * @param points Input points + * @param [propertyName] Name of the property from which to pull z values This is optional: if not given, then there will be no extra data added to the derived triangles. + * @returns TIN output + */ + function tin(points: GeoJSON.FeatureCollection, propertyName?: string): GeoJSON.FeatureCollection; + + /** + * Takes a bounding box and a cell depth and returns a set of triangular polygons in a grid. + * @param extent Extent in [minX, minY, maxX, maxY] order + * @param cellWidth Width of each cell + * @param units Used in calculating cellWidth ('miles' or 'kilometers') + * @returns Grid of triangles + */ + function triangleGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // Joins + ////////////////////////////////////////////////////// + + /** + * Takes a Point and a Polygon or MultiPolygon and determines if the point resides inside the polygon. + * The polygon can be convex or concave. The function accounts for holes. + * @param point Input point + * @param polygon Input polygon or multipolygon + * @returns true if the Point is inside the Polygon; false if the Point is not inside the Polygon + */ + function inside(point: GeoJSON.Feature, polygon: GeoJSON.Feature): boolean; + + /** + * Takes a set of points and a set of polygons and performs a spatial join. + * @param points Input points + * @param polygons Input polygons + * @param polyId Property in polygons to add to joined Point features + * @param containingPolyId Property in points in which to store joined property from polygons + * @returns Points with containingPolyId property containing values from polyId + */ + function tag(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection, polyId: string, containingPolyId: string): GeoJSON.FeatureCollection; + + /** + * Takes a set of points and a set of polygons and returns the points that fall within the polygons. + * @param points Input points + * @param polygons Input polygons + * @returns Points that land within at least one polygon + */ + function within(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // Classification + ////////////////////////////////////////////////////// + + /** + * Takes a set of features and returns an array of the Jenks Natural breaks for a given property. + * @param input Input features + * @param field The property in input on which to calculate Jenks natural breaks + * @param numberOfBreaks Number of classes in which to group the data + * @returns The break number for each class plus the minimum and maximum values + */ + function jenks(input: GeoJSON.FeatureCollection, field: string, numberOfBreaks: number): Array; + + /** + * Takes a reference point and a set of points and returns the point from the set closest to the reference. + * @param point The reference point + * @param against Input point set + * @returns The closest point in the set to the reference point + */ + function nearest(point: GeoJSON.Feature, against: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a FeatureCollection, a property name, and a set of percentiles and returns a quantile array. + * @param input Set of features + * @param field The property in input from which to retrieve quantile values + * @param percentiles An Array of percentiles on which to calculate quantile values + * @returns An array of the break values + */ + function quantile(input: GeoJSON.FeatureCollection, field: string, percentiles: Array): Array; + + /** + * Takes a FeatureCollection, an input field, an output field, and an array of translations and outputs an identical FeatureCollection with the output field property populated. + * @param input Set of input features + * @param inField The field to translate + * @param outField The field in which to store translated results + * @param translations An array of translations + * @returns A FeatureCollection with identical geometries to input but with outField populated. + */ + function reclass(input: GeoJSON.FeatureCollection, inField: string, outField: string, translations: Array): GeoJSON.FeatureCollection; +} + +declare module 'turf' { + export= turf; +} diff --git a/turf/turf-tests.ts b/turf/turf-tests.ts index e671035892..31462adc51 100644 --- a/turf/turf-tests.ts +++ b/turf/turf-tests.ts @@ -1,28 +1,114 @@ /// +import * as turf from '@turf/turf' +// AGGREGATION +import * as collect from '@turf/collect' +// MEASUREMENT +import * as along from '@turf/along' +import * as area from '@turf/area' +import * as bboxPolygon from '@turf/bbox-polygon' +import * as bearing from '@turf/bearing' +import * as center from '@turf/center' +import * as centroid from '@turf/centroid' +import * as destination from '@turf/destination' +import * as envelope from '@turf/envelope' +import * as lineDistance from '@turf/line-distance' +import * as midpoint from '@turf/midpoint' +import * as pointOnSurce from '@turf/point-on-surface' +import * as square from '@turf/square' +// TRANSFORMATION +import * as bezier from '@turf/bezier' +import * as buffer from '@turf/buffer' +import * as concave from '@turf/concave' +import * as convex from '@turf/convex' +import * as difference from '@turf/difference' +import * as intersect from '@turf/intersect' +import * as simplify from '@turf/simplify' +import * as union from '@turf/union' +// MISC +import * as combine from '@turf/combine' +import * as explode from '@turf/explode' +import * as flip from '@turf/flip' +import * as kinks from '@turf/kinks' +import * as lineSlice from '@turf/line-slice' +import * as pointOnLine from '@turf/point-on-line' +// HELPER +import { + featureCollection, + feature, + lineString, + multiLineString, + point, + multiPoint, + polygon, + multiPolygon, + geometryCollection } from '@turf/helpers' +// DATA +import * as random from '@turf/random' +import * as sample from '@turf/sample' +// INTERPOLATION +import * as isolines from '@turf/isolines' +import * as planepoint from '@turf/planepoint' +import * as tin from '@turf/tin' +// JOINS +import * as inside from '@turf/inside' +import * as tag from '@turf/tag' +import * as within from '@turf/within' +// GRIDS +import * as hexGrid from '@turf/hex-grid' +import * as pointGrid from '@turf/point-grid' +import * as squareGrid from '@turf/square-grid' +import * as triangleGrid from '@turf/triangle-grid' +// CLASSIFICATION +import * as nearest from '@turf/nearest' +// // META +// import * as propEach from '@turf/propEach' +// import * as coordEach from '@turf/coordEach' +// import * as coordReduce from '@turf/coordReduce' +// import * as featureEach from '@turf/featureEach' +// import * as getCoord from '@turf/getCoord' +// // ASSERTIONS +// import * as featureOf from '@turf/featureOf' +// import * as collectionOf from '@turf/collectionOf' +import * as bboxAssertions from '@turf/bbox' +// import * as circle from '@turf/circle' +// import * as geojsonType from '@turf/geojsonType' +// import * as propReduce from '@turf/propReduce' +// import * as coordAll from '@turf/coordAll' +// import * as tesselate from '@turf/tesselate' /////////////////////////////////////////// // Tests data initialisation /////////////////////////////////////////// - -var point1: GeoJSON.Feature = { +const bbox = [0, 0, 10, 10] +const properties = {pop: 3000} +const point1: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [-75.343, 39.984] } -}; +} -var point2: GeoJSON.Feature = { +const point2: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-75.534, 39.123] - } -}; + "coordinates": [-75.401, 39.884] + } +} -var line: GeoJSON.Feature = { +const multiPoint1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "MultiPoint", + "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] + } +} + +const lineString1: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { @@ -36,9 +122,21 @@ var line: GeoJSON.Feature = { [-77.019824, 38.892368] ] } -}; +} -var polygons: GeoJSON.FeatureCollection = { +const multiLineString1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "MultiLineString", + "coordinates": [ + [ [100.0, 0.0], [101.0, 1.0] ], + [ [102.0, 2.0], [103.0, 3.0] ] + ] + } +} + +const polygons: GeoJSON.FeatureCollection = { "type": "FeatureCollection", "features": [ { @@ -69,9 +167,9 @@ var polygons: GeoJSON.FeatureCollection = { } } ] -}; +} -var polygon1: GeoJSON.Feature = { +const polygon1: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { @@ -84,13 +182,11 @@ var polygon1: GeoJSON.Feature = { [105.818939,21.004714] ]] } -}; +} -var polygon2: GeoJSON.Feature = { +const polygon2: GeoJSON.Feature = { "type": "Feature", - "properties": { - "fill": "#00f" - }, + "properties": {}, "geometry": { "type": "Polygon", "coordinates": [[ @@ -106,7 +202,20 @@ var polygon2: GeoJSON.Feature = { } } -var features: GeoJSON.FeatureCollection = { +const multiPolygon1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "MultiPolygon", + "coordinates": [ + [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], + [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], + [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] + ] + } +} + +const points: GeoJSON.FeatureCollection = { "type": "FeatureCollection", "features": [ { @@ -114,96 +223,50 @@ var features: GeoJSON.FeatureCollection = { "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.522259, 35.4691] + "coordinates": [-63.601226, 44.642643] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.502754, 35.463455] + "coordinates": [-63.591442, 44.651436] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.508269, 35.463245] + "coordinates": [-63.580799, 44.648749] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.516809, 35.465779] + "coordinates": [-63.573589, 44.641788] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.515372, 35.467072] + "coordinates": [-63.587665, 44.64533] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.509363, 35.463053] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.511123, 35.466601] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.518547, 35.469327] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.519706, 35.469659] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.517839, 35.466998] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.508678, 35.464942] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.514914, 35.463453] + "coordinates": [-63.595218, 44.64765] } } ] -}; +} -var triangle: GeoJSON.Feature = { +const triangle: GeoJSON.Feature = { "type": "Feature", - "properties": { - "a": 11, - "b": 122, - "c": 44 - }, + "properties": {}, "geometry": { "type": "Polygon", "coordinates": [[ @@ -213,310 +276,231 @@ var triangle: GeoJSON.Feature = { [-75.1221, 39.57] ]] } -}; - -var aggregations = [ - { - aggregation: 'sum', - inField: 'population', - outField: 'pop_sum' - }, - { - aggregation: 'average', - inField: 'population', - outField: 'pop_avg' - }, - { - aggregation: 'median', - inField: 'population', - outField: 'pop_median' - }, - { - aggregation: 'min', - inField: 'population', - outField: 'pop_min' - }, - { - aggregation: 'max', - inField: 'population', - outField: 'pop_max' - }, - { - aggregation: 'deviation', - inField: 'population', - outField: 'pop_deviation' - }, - { - aggregation: 'variance', - inField: 'population', - outField: 'pop_variance' - }, - { - aggregation: 'count', - inField: '', - outField: 'point_count' - } -]; - -/////////////////////////////////////////// -// Tests Aggregation -/////////////////////////////////////////// - -// -- Test aggregate -- -var aggregated = turf.aggregate(polygons, points, aggregations); - -// -- Test average -- -var averaged = turf.average(polygons, points, 'population', 'pop_avg'); - -// -- Test count -- -var counted = turf.count(polygons, points, 'pt_count'); - -// -- Test deviation -- -var deviated = turf.deviation(polygons, points, 'population', 'pop_deviation'); - -// -- Test max -- -var aggregated = turf.max(polygons, points, 'population', 'max'); - -// -- Test median -- -var medians = turf.median(polygons, points, 'population', 'median'); - -// -- Test min -- -var minimums = turf.min(polygons, points, 'population', 'min'); - -// -- Test sum -- -var summed = turf.sum(polygons, points, 'population', 'sum'); - -// -- Test variance -- -var varianced = turf.variance(polygons, points, 'population', 'variance'); +} /////////////////////////////////////////// // Tests Measurement /////////////////////////////////////////// // -- Test along -- -var along = turf.along(line, 1, 'miles'); +turf.along(lineString1, 50) +turf.along(lineString1, 50, 'miles') // -- Test area -- -var area = turf.area(polygons); +turf.area(polygons) // -- Test bboxPolygon -- -var bbox = [0, 0, 10, 10]; -var poly = turf.bboxPolygon(bbox); +turf.bboxPolygon(bbox) // -- Test bearing -- -var bearing = turf.bearing(point1, point2); +turf.bearing(point1, point2) // -- Test center -var centerPt = turf.center(features); +turf.center(points) // -- Test centroid -- -var centroidPt = turf.centroid(polygon1); +turf.centroid(polygon1) // -- Test destination -- -var distance = 50; -var bearing = 90; -var units = 'miles'; -var destination = turf.destination(point1, distance, bearing, units); +turf.destination(point1, 50, 90) +turf.destination(point1, 50, 90, 'miles') // -- Test distance -- -var units = "miles"; -var distance = turf.distance(point1, point2, units); +turf.distance(point1, point2) +turf.distance(point1, point2, 'miles') // -- Test envelope -- -var enveloped = turf.envelope(polygons); - -// -- Test extent -- -var bbox = turf.extent(polygons); +turf.envelope(polygons) // -- Test lineDistance -var length = turf.lineDistance(line, 'miles'); +turf.lineDistance(lineString1) +turf.lineDistance(lineString1, 'miles') // -- Test midpoint -- -var midpointed = turf.midpoint(point1, point2); +turf.midpoint(point1, point2) // -- Test pointOnSurface -- -var pointOnPolygon = turf.pointOnSurface(polygon1); - -// -- Test size -- -var resized = turf.size(bbox, 2); +turf.pointOnSurface(polygon1) // -- Test square -- -var squared = turf.square(bbox); +turf.square(bbox) /////////////////////////////////////////// // Tests Transformation /////////////////////////////////////////// // -- Test bezier -- -var curved = turf.bezier(line); +turf.bezier(lineString1) // -- Test buffer -- -var buffered = turf.buffer(point1, 500, units); +turf.buffer(point1, 50) +turf.buffer(point1, 50, 'miles') // -- Test concave -- -var hull = turf.concave(features, 1, 'miles'); +turf.concave(points, 1, 'miles') // -- Test convex -- -var hull = turf.convex(features); +turf.convex(points) // -- Test difference -- -var differenced = turf.difference(polygon1, polygon2); +turf.difference(polygon1, polygon2) // -- Test intersect -- -var intersection = turf.intersect(polygon1, polygon2); - -// -- Test merge -- -var merged = turf.merge(polygons); +turf.intersect(polygon1, polygon2) +turf.intersect(point1, polygon1) +turf.intersect(point1, point1) +turf.intersect(polygon1, point1) +turf.intersect(polygon1, lineString1) +turf.intersect(lineString1, point1) // -- Test simplify -- -var tolerance = 0.01; -var simplified = turf.simplify(polygon1, tolerance, false); + +turf.simplify(polygon1, 0.01, false) // -- Test union -- -var union = turf.union(polygon1, polygon2); +turf.union(polygon1, polygon2) /////////////////////////////////////////// // Tests Misc /////////////////////////////////////////// // -- Test combine -- -var combined = turf.combine(features); +turf.combine(points) // -- Test explode -- -var points = turf.explode(polygon1); +turf.explode(polygon1) // -- Test flip -- -var flipedPoint = turf.flip(point1); +turf.flip(point1) // -- Test kinks -- -var kinks = turf.kinks(polygon1); +turf.kinks(polygon1) // -- Test lineSlice -- -var sliced = turf.lineSlice(point1, point2, line); +turf.lineSlice(point1, point2, lineString1) // -- Test pointOnLine -- -var snapped = turf.pointOnLine(line, point1); +turf.pointOnLine(lineString1, point1) /////////////////////////////////////////// // Tests Helper /////////////////////////////////////////// // -- Test featurecollection -- -var fc = turf.featurecollection([point1, point2]); +turf.featureCollection([point1, point2]) +turf.featureCollection([point1, polygon1]) +turf.featureCollection([polygon1, polygon2]) +turf.featureCollection([lineString1, polygon1]) +turf.featureCollection([lineString1, point1]) -// -- Test linestring -- -var linestring1 = turf.linestring([ - [-21.964416, 64.148203], - [-21.956176, 64.141316], - [-21.93901, 64.135924], - [-21.927337, 64.136673] -]); -var linestring2 = turf.linestring([ - [-21.929054, 64.127985], - [-21.912918, 64.134726], - [-21.916007, 64.141016], - [-21.930084, 64.14446] -], {name: 'line 1', distance: 145}); +// -- Test feature -- +turf.feature(point1) +turf.feature(polygon1) +turf.feature(lineString1) + +// -- Test lineString -- +turf.lineString(lineString1.geometry.coordinates) +turf.lineString(lineString1.geometry.coordinates, properties) + +// -- Test multiLineString -- +turf.multiLineString(multiLineString1.geometry.coordinates) // -- Test point -- -var pt1 = turf.point([-75.343, 39.984]); -var pt2 = turf.point([-75.343, 39.984], {name: 'point 1', distance: 145}); +turf.point(point1.geometry.coordinates) +turf.point(point1.geometry.coordinates, properties) + +// -- Test multiPoint -- +turf.multiPoint(multiPoint1.geometry.coordinates) // -- Test polygon -- -var polygon = turf.polygon([[ - [-2.275543, 53.464547], - [-2.275543, 53.489271], - [-2.215118, 53.489271], - [-2.215118, 53.464547], - [-2.275543, 53.464547] -]], { name: 'poly1', population: 400}); +turf.polygon(polygon1.geometry.coordinates, properties) + +// -- Test multiPolygon -- +turf.multiPolygon(multiPolygon1.geometry.coordinates, properties) + +// -- Test geometryCollection -- +turf.geometryCollection([point1.geometry, lineString1.geometry]); /////////////////////////////////////////// // Tests Data /////////////////////////////////////////// -// -- Test filter -- -var key = "species"; -var value = "oak"; -var filtered = turf.filter(features, key, value); - // -- Test random -- -var randomPoints = turf.random('points', 100, { - bbox: [-70, 40, -60, 60] -}); - -var randomPoints = turf.random('points', 100, { - bbox: [-70, 40, -60, 60], - num_vertices: 2, +turf.random('points', 100) +turf.random('points', 100, { bbox }) +turf.random('polygons', 100, { + bbox, + num_vertices: 10, max_radial_length: 10 -}); - -// -- Test remove -- -var filtered = turf.remove(points, 'marker-color', '#00f'); +}) // -- Test sample -- -var randomPoints = turf.random('points', 1000); -var sample = turf.sample(points, 10); +turf.random('points', 100) +turf.sample(points, 10) /////////////////////////////////////////// // Tests Interpolation /////////////////////////////////////////// // -- Test hexGrid -- -var cellWidth = 50; -var hexgrid = turf.hexGrid(bbox, cellWidth, units); - -// -- Test isolines -- -var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; -var isolined = turf.isolines(points, 'z', 15, breaks); - -// -- Test planepoint -- -var zValue = turf.planepoint(point1, triangle); +turf.hexGrid(bbox, 50) +turf.hexGrid(bbox, 50, 'miles') // -- Test pointGrid -- -var extent = [-70.823364, -33.553984, -70.473175, -33.302986]; -var cellWidth = 3; -var grid = turf.pointGrid(extent, cellWidth, units); +turf.pointGrid(bbox, 50) +turf.pointGrid(bbox, 50, 'miles') // -- Test squareGrid -- -var squareGrid = turf.squareGrid(extent, cellWidth, units); - -// -- Test tin -- -var tin = turf.tin(points, 'z'); +turf.squareGrid(bbox, 50) +turf.squareGrid(bbox, 50, 'miles') // -- Test triangleGrid -- -var triangleGrid = turf.triangleGrid(extent, cellWidth, units); +turf.triangleGrid(bbox, 50) +turf.triangleGrid(bbox, 50, 'miles') + +/////////////////////////////////////////// +// Tests Interpolation +/////////////////////////////////////////// + +// -- Test isolines -- +turf.isolines(points, 'z', 15, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + +// -- Test planepoint -- +turf.planepoint(point1, triangle) + +// -- Test tin -- +turf.tin(points, 'z') /////////////////////////////////////////// // Tests Joins /////////////////////////////////////////// // -- Test inside -- -var isInside1 = turf.inside(point1, polygon); +turf.inside(point1, polygon1) // -- Test tag -- -var tagged = turf.tag(points, triangleGrid, 'fill', 'marker-color'); +turf.tag(points, polygons, 'pop', 'population') // -- Test within -- -var ptsWithin = turf.within(points, polygons); +turf.within(points, polygons) /////////////////////////////////////////// // Tests Classification /////////////////////////////////////////// -// -- Test jenks -- -var breaks = turf.jenks(points, 'population', 3); - // -- Test nearest -- -var nearest = turf.nearest(point1, points); +turf.nearest(point1, points) -// -- Test quantile -- -var breaks = turf.quantile(points, 'population', [25, 50, 75, 99]); +/////////////////////////////////////////// +// Tests Aggregation +/////////////////////////////////////////// +turf.collect(polygons, points, 'population', 'values') -// -- Test reclass -- -var translations = [ - [0, 200, "small"], - [200, 400, "medium"], - [400, 600, "large"] -]; -var reclassed = turf.reclass(points, 'population', 'size', translations); +/////////////////////////////////////////// +// Tests Assertions +/////////////////////////////////////////// +turf.bbox(polygon1) +turf.bbox(point1) +turf.bbox(lineString1) +turf.bbox(multiLineString1) +turf.bbox(multiPolygon1) \ No newline at end of file diff --git a/turf/turf.d.ts b/turf/turf.d.ts index 647df93398..e90cf69276 100644 --- a/turf/turf.d.ts +++ b/turf/turf.d.ts @@ -1,103 +1,130 @@ -// Type definitions for Turf 2.0 +// Type definitions for Turf 3.5.2 // Project: http://turfjs.org/ -// Definitions by: Guillaume Croteau +// Definitions by: Guillaume Croteau , Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/** +#### TODO: + +Update all methods with newest JSDocs & tests based on the latest TurfJS library. + +AGGREGATION +- [x] collect +MEASUREMENT +- [ ] along +- [ ] area +- [ ] bboxPolygon +- [ ] bearing +- [ ] center +- [ ] centroid +- [ ] destination +- [ ] distance +- [ ] envelope +- [ ] lineDistance +- [ ] midpoint +- [ ] pointOnSurface +- [ ] square +TRANSFORMATION +- [ ] bezier +- [ ] buffer +- [ ] concave +- [ ] convex +- [ ] difference +- [ ] intersect +- [ ] simplify +- [ ] union +MISC +- [ ] combine +- [ ] explode +- [ ] flip +- [ ] kinks +- [ ] lineSlice +- [ ] pointOnLine +HELPER +- [x] featureCollection +- [x] feature +- [x] lineString +- [x] multiLineString +- [x] point +- [x] multiPoint +- [x] polygon +- [x] multiPolygon +- [x] geometryCollection +DATA +- [x] random +- [x] sample +INTERPOLATION +- [ ] isolines +- [ ] planepoint +- [ ] tin +JOINS +- [x] inside +- [x] tag +- [ ] within +GRIDS +- [x] hexGrid +- [x] pointGrid +- [x] squareGrid +- [x] triangleGrid +CLASSIFICATION +- [ ] nearest +META +- [ ] propEach +- [ ] coordEach +- [ ] coordReduce +- [ ] featureEach +- [ ] getCoord +ASSERTIONS +- [ ] featureOf +- [ ] collectionOf +- [x] bbox +- [ ] circle +- [ ] geojsonType +- [ ] propReduce +- [ ] coordAll +- [ ] tesselate + */ + +declare const turf: turf.TurfStatic; +declare const TemplateUnits: 'miles' | 'nauticalmiles' | 'degrees' | 'radians' | 'inches' | 'yards' | 'meters' | 'metres' | 'kilometers' | 'kilometres' +declare const TemplateType: 'point'| 'points' | 'polygon' | 'polygons' declare module turf { + interface TurfStatic { ////////////////////////////////////////////////////// // Aggregation ////////////////////////////////////////////////////// /** - * Calculates a series of aggregations for a set of points within a set of polygons. - * Sum, average, count, min, max, and deviation are supported. - * @param polygons Polygons with values on which to aggregate - * @param points Points to be aggregated - * @param aggregations An array of aggregation objects - * @returns Polygons with properties listed based on outField values in aggregations - */ - function aggregate(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, aggregations: Array<{aggregation: string, inField: string, outField: string}>): GeoJSON.FeatureCollection; - - /** - * Calculates the average value of a field for a set of points within a set of polygons. - * @param polygons Polygons with values on which to average - * @param points Points from which to calculate the average - * @param field The field in the points features from which to pull values to average - * @param outField The field in polygons to put results of the averages - * @returns Polygons with the value of outField set to the calculated averages - */ - function average(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, field: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Takes a set of points and a set of polygons and calculates the number of points that fall within the set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param countField A field to append to the attributes of the Polygon features representing Point counts - * @returns Polygons with countField appended - */ - function count(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, countField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the standard deviation value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in points from which to aggregate - * @param outField The field to append to polygons representing deviation - * @returns Polygons with appended field representing deviation - */ - function deviation(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the maximum value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField values - */ - function max(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the median value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField values - */ - function median(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the minimum value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField values - */ - function min(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the sum of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField - */ - function sum(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the variance value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField - */ - function variance(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + * Merges a specified property from a FeatureCollection of points into a FeatureCollection of polygons. Given an `inProperty` on points and an `outProperty` for polygons, this finds every point that lies within each polygon, collects the `inProperty` values from those points, and adds them as an array to `outProperty` on the polygon. + * + * @name [collect](http://turfjs.org/docs/#collect) + * @param {FeatureCollection} polygons polygons with values on which to aggregate + * @param {FeatureCollection} points points to be aggregated + * @param {string} inProperty property to be nested from + * @param {string} outProperty property to be nested into + * @return {FeatureCollection} polygons with properties listed based on `outField` + * @example + * var poly1 = polygon([[[0,0],[10,0],[10,10],[0,10],[0,0]]]) + * var poly2 = polygon([[[10,0],[20,10],[20,20],[20,0],[10,0]]]) + * var polyFC = featurecollection([poly1, poly2]) + * var pt1 = point([5,5], {population: 200}) + * var pt2 = point([1,3], {population: 600}) + * var pt3 = point([14,2], {population: 100}) + * var pt4 = point([13,1], {population: 200}) + * var pt5 = point([19,7], {population: 300}) + * var ptFC = featurecollection([pt1, pt2, pt3, pt4, pt5]) + * var aggregated = aggregate(polyFC, ptFC, 'population', 'values') + * + * aggregated.features[0].properties.values // => [200, 600]) + */ + collect( + polygons: GeoJSON.FeatureCollection, + points: GeoJSON.FeatureCollection, + inProperty: string, + outProperty: string + ): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Measurement @@ -110,21 +137,49 @@ declare module turf { * @param [units=miles] 'miles', 'kilometers', 'radians' or 'degrees' * @returns Point along the line */ - function along(line: GeoJSON.Feature, distance: number, units?: string): GeoJSON.Feature; + along( + line: GeoJSON.Feature, + distance: number, + units?: typeof TemplateUnits + ): GeoJSON.Feature; /** * Takes one or more features and returns their area in square meters. * @param input Input features * @returns Area in square meters */ - function area(input: GeoJSON.Feature | GeoJSON.FeatureCollection): number; + area(input: GeoJSON.Feature | GeoJSON.FeatureCollection): number; + + /** + * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. + * + * @name bbox + * @param {(Feature|FeatureCollection)} geojson input features + * @return {Array} bbox extent in [minX, minY, maxX, maxY] order + * @example + * var pt1 = point([114.175329, 22.2524]) + * var pt2 = point([114.170007, 22.267969]) + * var pt3 = point([114.200649, 22.274641]) + * var pt4 = point([114.200649, 22.274641]) + * var pt5 = point([114.186744, 22.265745]) + * var features = featureCollection([pt1, pt2, pt3, pt4, pt5]) + * + * var bbox = turf.bbox(features); + * + * var bboxPolygon = turf.bboxPolygon(bbox); + * + * //=bbox + * + * //=bboxPolygon + */ + bbox(bbox: GeoJSON.Feature | GeoJSON.FeatureCollection): Array; /** * Takes a bbox and returns an equivalent polygon. * @param bbox An Array of bounding box coordinates in the form: [xLow, yLow, xHigh, yHigh] * @returns A Polygon representation of the bounding box */ - function bboxPolygon(bbox: Array): GeoJSON.Feature; + bboxPolygon(bbox: Array): GeoJSON.Feature; /** * Takes two points and finds the geographic bearing between them. @@ -132,14 +187,14 @@ declare module turf { * @param end Ending point * @returns Bearing in decimal degrees */ - function bearing(start: GeoJSON.Feature, end: GeoJSON.Feature): number; + bearing(start: GeoJSON.Feature, end: GeoJSON.Feature): number; /** * Takes a FeatureCollection and returns the absolute center point of all features. * @param features Input features * @returns A Point feature at the absolute center point of all input features */ - function center(features: GeoJSON.FeatureCollection): GeoJSON.Feature; + center(features: GeoJSON.FeatureCollection): GeoJSON.Feature; /** * Takes one or more features and calculates the centroid using the arithmetic mean of all vertices. @@ -147,10 +202,10 @@ declare module turf { * @param features Input features * @returns The centroid of the input features */ - function centroid(features: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; + centroid(features: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; /** - * Takes a Point and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers; and bearing in degrees. + * Takes a Point and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers and bearing in degrees. * This uses the Haversine formula to account for global curvature. * @param start Starting point * @param distance Distance from the starting point @@ -158,7 +213,12 @@ declare module turf { * @param units 'miles', 'kilometers', 'radians', or 'degrees' * @returns Destination point */ - function destination(start: GeoJSON.Feature, distance: number, bearing: number, units: string): GeoJSON.Feature; + destination( + start: GeoJSON.Feature, + distance: number, + bearing: number, + units?: typeof TemplateUnits + ): GeoJSON.Feature; /** * Calculates the distance between two points in degress, radians, miles, or kilometers. @@ -168,21 +228,18 @@ declare module turf { * @param [units=kilometers] 'miles', 'kilometers', 'radians', or 'degrees' * @returns Distance between the two points */ - function distance(from: GeoJSON.Feature, to: GeoJSON.Feature, units?: string): number; + distance( + from: GeoJSON.Feature, + to: GeoJSON.Feature, + units?: typeof TemplateUnits + ): number; /** * Takes any number of features and returns a rectangular Polygon that encompasses all vertices. * @param fc Input features * @returns A rectangular Polygon feature that encompasses all vertices */ - function envelope(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; - - /** - * Takes a set of features, calculates the extent of all input features, and returns a bounding box. - * @param input Input features - * @returns The bounding box of input given as an array in WSEN order (west, south, east, north) - */ - function extent(input: GeoJSON.Feature | GeoJSON.FeatureCollection): Array; + envelope(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; /** * Takes a line and measures its length in the specified units. @@ -190,7 +247,10 @@ declare module turf { * @param units 'miles', 'kilometers', 'radians', or 'degrees' * @returns Length of the input line */ - function lineDistance(line: GeoJSON.Feature, units: string): number; + lineDistance( + line: GeoJSON.Feature, + units?: typeof TemplateUnits + ): number; /** * Takes two points and returns a point midway between them. @@ -198,7 +258,7 @@ declare module turf { * @param pt2 Second point * @returns A point midway between pt1 and pt2 */ - function midpoint(pt1: GeoJSON.Feature, pt2: GeoJSON.Feature): GeoJSON.Feature; + midpoint(pt1: GeoJSON.Feature, pt2: GeoJSON.Feature): GeoJSON.Feature; /** * Takes a feature and returns a Point guaranteed to be on the surface of the feature. Given a Polygon, the point will be in the area of the polygon. @@ -206,22 +266,14 @@ declare module turf { * @param input Any feature or set of features * @returns A point on the surface of input */ - function pointOnSurface(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; - - /** - * Takes a bounding box and returns a new bounding box with a size expanded or contracted by a factor of X. - * @param bbox A bounding box - * @param factor The ratio of the new bbox to the input bbox - * @returns The resized bbox - */ - function size(bbox: Array, factor: number): Array; + pointOnSurface(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; /** * Takes a bounding box and calculates the minimum square bounding box that would contain the input. * @param bbox A bounding box * @returns A square surrounding bbox */ - function square(bbox: Array): Array; + square(bbox: Array): Array; ////////////////////////////////////////////////////// // Transformation @@ -235,7 +287,7 @@ declare module turf { * @param [sharpness=0.85] A measure of how curvy the path should be between splines * @returns Curved line */ - function bezier(line: GeoJSON.Feature, resolution?: number, sharpness?: number): GeoJSON.Feature; + bezier(line: GeoJSON.Feature, resolution?: number, sharpness?: number): GeoJSON.Feature; /** * Calculates a buffer for input features for a given radius. Units supported are miles, kilometers, and degrees. @@ -244,7 +296,14 @@ declare module turf { * @param units 'miles', 'kilometers', 'radians', or 'degrees' * @returns Buffered features */ - function buffer(feature: GeoJSON.Feature | GeoJSON.FeatureCollection, distance: number, units: string): GeoJSON.FeatureCollection | GeoJSON.FeatureCollection | GeoJSON.Polygon | GeoJSON.MultiPolygon; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; + buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; + buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; + buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; /** * Takes a set of points and returns a concave hull polygon. Internally, this implements a Monotone chain algorithm. @@ -253,14 +312,20 @@ declare module turf { * @param units Used for maxEdge distance (miles or kilometers) * @returns A concave hull */ - function concave(points: GeoJSON.FeatureCollection, maxEdge: number, units: string): GeoJSON.Feature; + concave( + points: GeoJSON.FeatureCollection, + maxEdge: number, + units?: typeof TemplateUnits + ): GeoJSON.Feature; /** * Takes a set of points and returns a convex hull polygon. Internally this uses the convex-hull module that implements a monotone chain hull. * @param input Input points * @returns A convex hull */ - function convex(input: GeoJSON.FeatureCollection): GeoJSON.Feature; + convex( + input: GeoJSON.FeatureCollection + ): GeoJSON.Feature; /** * Finds the difference between two polygons by clipping the second polygon from the first. @@ -268,26 +333,54 @@ declare module turf { * @param poly2 Polygon feature to difference from poly1 * @returns A Polygon feature showing the area of poly1 excluding the area of poly2 */ - function difference(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + difference( + poly1: GeoJSON.Feature, + poly2: GeoJSON.Feature + ): GeoJSON.Feature; /** - * Takes two polygons and finds their intersection. - * If they share a border, returns the border; if they don't intersect, returns undefined. - * @param poly1 The first polygon - * @param poly2 The second polygon - * @returns If poly1 and poly2 overlap, returns a Polygon feature representing the area they overlap; - * if poly1 and poly2 do not overlap, returns undefined; - * if poly1 and poly2 share a border, a MultiLineString of the locations where their borders are shared - */ - function intersect(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature | typeof undefined; - - /** - * Takes a set of polygons and returns a single merged polygon feature. - * If the input polygon features are not contiguous, this function returns a MultiPolygon feature. - * @param fc Input polygons - * @returns Merged polygon or multipolygon - */ - function merge(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; + * Takes two Features and finds their intersection. + * If they share a border, returns the border if they don't intersect, returns undefined. + * + * @name [intersect](http://turfjs.org/docs/#intersect) + * @param {Feature} poly1 + * @param {Feature} poly2 + * @returns {Feature|undefined} A feature representing the point(s) they share (in case of a {Point} or {MultiPoint}), the borders they share (in case of a {LineString} or a {MultiLineString}), the area they share (in case of {Polygon} or {MultiPolygon}). If they do not share any point, returns `undefined`. + * @example + * var poly1 = polygon([[ + * [-122.801742, 45.48565], + * [-122.801742, 45.60491], + * [-122.584762, 45.60491], + * [-122.584762, 45.48565], + * [-122.801742, 45.48565] + * ]]); + * + * var poly2 = polygon([[ + * [-122.520217, 45.535693], + * [-122.64038, 45.553967], + * [-122.720031, 45.526554], + * [-122.669906, 45.507309], + * [-122.723464, 45.446643], + * [-122.532577, 45.408574], + * [-122.487258, 45.477466], + * [-122.520217, 45.535693] + * ]]); + * var polygons = featureCollection([poly1, poly2]); + * + * var intersection = turf.intersect(poly1, poly2); + * + * //=polygons + * + * //=intersection + */ + intersect( + feature1: GeoJSON.Feature, + feature2: GeoJSON.Feature + ): GeoJSON.Feature; + intersect( + feature1: GeoJSON.Feature, + feature2: GeoJSON.Feature + ): GeoJSON.Feature; /** * Takes a LineString or Polygon and returns a simplified version. @@ -297,16 +390,16 @@ declare module turf { * @param highQuality Whether or not to spend more time to create a higher-quality simplification with a different algorithm * @returns A simplified feature */ - function simplify(feature: GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection, tolerance: number, highQuality: boolean): GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection; + simplify(feature: GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection, tolerance: number, highQuality: boolean): GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection; /** * Takes two polygons and returns a combined polygon. - * If the input polygons are not contiguous, this function returns a MultiPolygon feature. + * If the input polygons are not contiguous, this function returns a MultiPolygon feature.; * @param poly1 Input polygon * @param poly2 Another input polygon * @returns A combined Polygon or MultiPolygon feature */ - function union(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + union(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; ////////////////////////////////////////////////////// // Misc @@ -317,28 +410,28 @@ declare module turf { * @param fc A FeatureCollection of any type * @returns A FeatureCollection of corresponding type to input */ - function combine(fc: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + combine(fc: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; /** * Takes a feature or set of features and returns all positions as points. * @param input Input features * @returns Points representing the exploded input features */ - function explode(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + explode(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; /** * Takes input features and flips all of their coordinates from [x, y] to [y, x]. * @param input Input features * @returns A feature or set of features of the same type as input with flipped coordinates */ - function flip(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature | GeoJSON.FeatureCollection; + flip(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature | GeoJSON.FeatureCollection; /** * Takes a polygon and returns points at all self-intersections. * @param polygon Input polygon * @returns Self-intersections */ - function kinks(polygon: GeoJSON.Feature): GeoJSON.FeatureCollection; + kinks(polygon: GeoJSON.Feature): GeoJSON.FeatureCollection; /** * Takes a line, a start Point, and a stop point and returns the line in between those points. @@ -347,7 +440,7 @@ declare module turf { * @param line Line to slice * @returns Sliced line */ - function lineSlice(point1: GeoJSON.Feature, point2: GeoJSON.Feature, line: GeoJSON.Feature): GeoJSON.Feature; + lineSlice(point1: GeoJSON.Feature, point2: GeoJSON.Feature, line: GeoJSON.Feature): GeoJSON.Feature; /** * Takes a Point and a LineString and calculates the closest Point on the LineString. @@ -355,98 +448,348 @@ declare module turf { * @param point Point to snap from * @returns Closest point on the line to point */ - function pointOnLine(line: GeoJSON.Feature, point: GeoJSON.Feature): GeoJSON.Feature; + pointOnLine(line: GeoJSON.Feature, point: GeoJSON.Feature): GeoJSON.Feature; ////////////////////////////////////////////////////// // Helper ////////////////////////////////////////////////////// /** - * Takes one or more Features and creates a FeatureCollection. - * @param features Input features - * @returns A FeatureCollection of input features - */ - function featurecollection(features: Array>): GeoJSON.FeatureCollection; + * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}. + * + * @name [featureCollection](http://turfjs.org/docs/#featurecollection) + * @param {Feature[]} features input features + * @returns {FeatureCollection} a FeatureCollection of input features + * @example + * var features = [ + * turf.point([-75.343, 39.984], {name: 'Location A'}), + * turf.point([-75.833, 39.284], {name: 'Location B'}), + * turf.point([-75.534, 39.123], {name: 'Location C'}) + * ] + * + * var fc = turf.featureCollection(features) + * + * //=fc + */ + featureCollection(features: Array>): GeoJSON.FeatureCollection; /** - * Creates a LineString based on a coordinate array. Properties can be added optionally. - * @param coordinates An array of Positions - * @param [properties] An Object of key-value pairs to add as properties - * @returns A LineString feature - */ - function linestring(coordinates: Array>, properties?: any): GeoJSON.Feature; + * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}. + * + * @name [feature](http://turfjs.org/docs/#feature) + * @param {Geometry} geometry input geometry + * @param {Object} properties properties + * @returns {FeatureCollection} a FeatureCollection of input features + * @example + * var geometry = { + * "type": "Point", + * "coordinates": [ + * 67.5, + * 32.84267363195431 + * ] + * } + * + * var feature = turf.feature(geometry) + * + * //=feature + */ + feature(geometry:GeoJSON.Feature, properties?: any): GeoJSON.Feature; /** - * Takes coordinates and properties (optional) and returns a new Point feature. - * @param coordinates Longitude, latitude position (each in decimal degrees) - * @param [properties] An Object of key-value pairs to add as properties - * @returns A Point feature - */ - function point(coordinates: Array, properties?: any): GeoJSON.Feature; + * Creates a {@link LineString} based on a coordinate array. Properties can be added optionally. + * + * @name [lineString](http://turfjs.org/docs/#linestring) + * @param {Array>} coordinates an array of Positions + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a LineString feature + * @throws {Error} if no coordinates are passed + * @example + * var linestring1 = turf.lineString([ + * [-21.964416, 64.148203], + * [-21.956176, 64.141316], + * [-21.93901, 64.135924], + * [-21.927337, 64.136673] + * ]) + * var linestring2 = turf.lineString([ + * [-21.929054, 64.127985], + * [-21.912918, 64.134726], + * [-21.916007, 64.141016], + * [-21.930084, 64.14446] + * ], {name: 'line 1', distance: 145}) + * + * //=linestring1 + * + * //=linestring2 + */ + lineString(coordinates: Array>, properties?: any): GeoJSON.Feature; /** - * Takes an array of LinearRings and optionally an Object with properties and returns a Polygon feature. - * @param rings An array of LinearRings - * @param [properties] An Object of key-value pairs to add as properties - * @returns A Polygon feature - */ - function polygon(rings: Array>>, properties?: any): GeoJSON.Feature; + * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. + * + * @name [multiLineString](http://turfjs.org/docs/#multilinestring) + * @param {Array>>} coordinates an array of LineStrings + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a MultiLineString feature + * @throws {Error} if no coordinates are passed + * @example + * var multiLine = turf.multiLineString([[[0,0],[10,10]]]) + * + * //=multiLine + * + */ + multiLineString(coordinates: Array>>, properties?: any): GeoJSON.Feature; + + /** + * Takes coordinates and properties (optional) and returns a new {@link Point} feature. + * + * @name [point](http://turfjs.org/docs/#point) + * @param {Array} coordinates longitude, latitude position (each in decimal degrees) + * @param {Object=} properties an Object that is used as the {@link Feature}'s + * properties + * @returns {Feature} a Point feature + * @example + * var pt1 = turf.point([-75.343, 39.984]); + * + * //=pt1 + */ + point(coordinates: Array, properties?: any): GeoJSON.Feature; + + /** + * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. + * + * @name [multiPoint](http://turfjs.org/docs/#multipoint) + * @param {Array>} coordinates an array of Positions + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a MultiPoint feature + * @throws {Error} if no coordinates are passed + * @example + * var multiPt = turf.multiPoint([[0,0],[10,10]]) + * + * //=multiPt + * + */ + multiPoint(coordinates: Array>, properties?: any): GeoJSON.Feature; + + /** + * Takes an array of LinearRings and optionally an {@link Object} with properties and returns a {@link Polygon} feature. + * + * @name [polygon](http://turfjs.org/docs/#polygon) + * @param {Array>>} coordinates an array of LinearRings + * @param {Object=} properties a properties object + * @returns {Feature} a Polygon feature + * @throws {Error} throw an error if a LinearRing of the polygon has too few positions + * or if a LinearRing of the Polygon does not have matching Positions at the + * beginning & end. + * @example + * var polygon = turf.polygon([[ + * [-2.275543, 53.464547], + * [-2.275543, 53.489271], + * [-2.215118, 53.489271], + * [-2.215118, 53.464547], + * [-2.275543, 53.464547] + * ]], { name: 'poly1', population: 400}); + * + * //=polygon + */ + polygon(coordinates: Array>>, properties?: any): GeoJSON.Feature; + + /** + * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. + * + * @name [multiPolygon](http://turfjs.org/docs/#multipolygon) + * @param {Array>>>} coordinates an array of Polygons + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a multipolygon feature + * @throws {Error} if no coordinates are passed + * @example + * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]); + * + * //=multiPoly + * + */ + multiPolygon(coordinates: Array>>>, properties?: any): GeoJSON.Feature; + + /** + * Creates a {@link Feature} based on acoordinate array. Properties can be added optionally. + * + * @name [geometryCollection](http://turfjs.org/docs/#geometrycollection) + * @param {Array<{Geometry}>} geometries an array of GeoJSON Geometries + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a GeoJSON GeometryCollection Feature + * @example + * var point = { + * "type": "Point", + * "coordinates": [100, 0] + * }; + * var line = { + * "type": "LineString", + * "coordinates": [ [101, 0], [102, 1] ] + * }; + * var collection = turf.geometryCollection([point, line]); + * + * //=collection + */ + geometryCollection(geometries: Array, properties?: any): GeoJSON.GeometryCollection; ////////////////////////////////////////////////////// // Data ////////////////////////////////////////////////////// /** - * Takes a FeatureCollection and filters it by a given property and value. - * @param features Input features - * @param key The property on which to filter - * @param value The value of that property on which to filter - * @returns A filtered collection with only features that match input key and value - */ - function filter(features: GeoJSON.FeatureCollection, key: string, value: string): GeoJSON.FeatureCollection; + * Generates random {@link GeoJSON} data, including {@link Point|Points} and {@link Polygon|Polygons}, for testing and experimentation. + * + * @name [random](http://turfjs.org/docs/#random) + * @param {String} [type='point'] type of features desired: 'points' or 'polygons' + * @param {Number} [count=1] how many geometries should be generated. + * @param {Object} options options relevant to the feature desired. Can include: + * @param {Array} options.bbox a bounding box inside of which geometries + * are placed. In the case of {@link Point} features, they are guaranteed to be within this bounds, + * while {@link Polygon} features have their centroid within the bounds. + * @param {Number} [options.num_vertices=10] options.vertices the number of vertices added + * to polygon features. + * @param {Number} [options.max_radial_length=10] the total number of decimal + * degrees longitude or latitude that a polygon can extent outwards to + * from its center. + * @return {FeatureCollection} generated random features + * @example + * var points = turf.random('points', 100, { + * bbox: [-70, 40, -60, 60] + * }) + * + * //=points + * + * var polygons = turf.random('polygons', 4, { + * bbox: [-70, 40, -60, 60] + * }) + * + * //=polygons + */ + random(type?: typeof TemplateType, count?: number, options?: { + bbox?: Array + num_vertices?: number + max_radial_length?: number + }): GeoJSON.FeatureCollection; /** - * Generates random GeoJSON data, including Points and Polygons, for testing and experimentation. - * @param [type='point'] Type of features desired: 'points' or 'polygons' - * @param [count=1] How many geometries should be generated. - * @param [options] Options relevant to the feature desired. Can include: - * - A bounding box inside of which geometries are placed. In the case of Point features, they are guaranteed to be within this bounds, while Polygon features have their centroid within the bounds. - * - The number of vertices added to polygon features. Default is 10; - * - The total number of decimal degrees longitude or latitude that a polygon can extent outwards to from its center. Default is 10. - * @returns Generated random features - */ - function random(type?: string, count?: number, options?: {bbox?: Array; num_vertices?: number; max_radial_length?: number;}): GeoJSON.FeatureCollection; + * Takes a {@link FeatureCollection} and returns a FeatureCollection with given number of {@link Feature|features} at random. + * + * @name [sample](http://turfjs.org/docs/#sample) + * @param {FeatureCollection} featurecollection set of input features + * @param {number} num number of features to select + * @return {FeatureCollection} a FeatureCollection with `n` features + * @example + * var points = turf.random('points', 1000); + * + * //=points + * + * var sample = turf.sample(points, 10); + * + * //=sample + */ + sample(featurecollection: GeoJSON.FeatureCollection, num: number): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // GRIDS + ////////////////////////////////////////////////////// /** - * Takes a FeatureCollection of any type, a property, and a value and returns a FeatureCollection with features matching that property-value pair removed. - * @param features Set of input features - * @param property The property to remove - * @param value The value to remove - * @returns The resulting FeatureCollection without features that match the property-value pair - */ - function remove(features: GeoJSON.FeatureCollection, property: string, value: string): GeoJSON.FeatureCollection; + * Takes a bounding box and a cell size in degrees and returns a {@link FeatureCollection} of flat-topped hexagons ({@link Polygon} features) aligned in an "odd-q" vertical grid as described in [Hexagonal Grids](http://www.redblobgames.com/grids/hexagons/). + * + * @name [hexGrid](http://turfjs.org/docs/#hexgrid) + * @param {Array} bbox bounding box in [minX, minY, maxX, maxY] order + * @param {number} cellSize dimension of cell in specified units + * @param {string} units used in calculating cellSize ('miles' or 'kilometers') + * @param {boolean} triangles whether to return as triangles instead of hexagons + * @return {FeatureCollection} a hexagonal grid + * @example + * var bbox = [-96,31,-84,40]; + * var cellSize = 50; + * var units = 'miles'; + * + * var hexgrid = turf.hexGrid(bbox, cellSize, units); + * + * //=hexgrid + */ + hexGrid( + bbox: Array, + cellSize: number, + units?: typeof TemplateUnits, + triangles?: boolean + ): GeoJSON.FeatureCollection; /** - * Takes a FeatureCollection and returns a FeatureCollection with given number of features at random. - * @param features Set of input features - * @param n Number of features to select - * @returns A FeatureCollection with n features - */ - function sample(features: GeoJSON.FeatureCollection, n: number): GeoJSON.FeatureCollection; + * Takes a bounding box and a cell depth and returns a set of {@link Point|points} in a grid. + * + * @name [pointGrid](http://turfjs.org/docs/#pointgrid) + * @param {Array} bbox extent in [minX, minY, maxX, maxY] order + * @param {number} cellSize the distance across each cell + * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers + * @return {FeatureCollection} grid of points + * @example + * var extent = [-70.823364, -33.553984, -70.473175, -33.302986]; + * var cellSize = 3; + * var units = 'miles'; + * + * var grid = turf.pointGrid(extent, cellSize, units); + * + * //=grid + */ + pointGrid( + bbox: Array, + cellSize: number, + units?: typeof TemplateUnits + ): GeoJSON.FeatureCollection; + + /** + * Takes a bounding box and a cell depth and returns a set of square {@link Polygon|polygons} in a grid. + * + * @name [squareGrid](http://turfjs.org/docs/#squaregrid) + * @param {Array} bbox extent in [minX, minY, maxX, maxY] order + * @param {number} cellSize width of each cell + * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers + * @return {FeatureCollection} grid a grid of polygons + * @example + * var bbox = [-96,31,-84,40] + * var cellSize = 10 + * var units = 'miles' + * + * var squareGrid = turf.squareGrid(bbox, cellSize, units) + * + * //=squareGrid + */ + squareGrid( + bbox: Array, + cellSize: number, + units?: typeof TemplateUnits + ): GeoJSON.FeatureCollection; + + /** + * Takes a bounding box and a cell depth and returns a set of triangular {@link Polygon|polygons} in a grid. + * + * @name [triangleGrid](http://turfjs.org/docs/#trianglegrid)) + * @param {Array} bbox extent in [minX, minY, maxX, maxY] order + * @param {number} cellSize dimension of each cell + * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers + * @return {FeatureCollection} grid of polygons + * @example + * var bbox = [-96,31,-84,40] + * var cellSize = 10; + * var units = 'miles'; + * + * var triangleGrid = turf.triangleGrid(extent, cellSize, units); + * + * //=triangleGrid + */ + triangleGrid( + bbox: Array, + cellSize: number, + units?: typeof TemplateUnits + ): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Interpolation ////////////////////////////////////////////////////// - /** - * Takes a bounding box and a cell size in degrees and returns a FeatureCollection of flat-topped hexagons (Polygon features) aligned in an "odd-q" vertical grid as described in Hexagonal Grids. - * @param bbox Bounding box in [minX, minY, maxX, maxY] order - * @param cellWidth Width of cell in specified units - * @param units Used in calculating cellWidth ('miles' or 'kilometers') - * @returns A hexagonal grid - */ - function hexGrid(bbox: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; - /** * Takes points with z-values and an array of value breaks and generates isolines. * @param points Input points @@ -455,7 +798,7 @@ declare module turf { * @param breaks Where to draw contours * @returns Isolines */ - function isolines(points: GeoJSON.FeatureCollection, z: string, resolution: number, breaks: Array): GeoJSON.FeatureCollection; + isolines(points: GeoJSON.FeatureCollection, z: string, resolution: number, breaks: Array): GeoJSON.FeatureCollection; /** * Takes a triangular plane as a Polygon and a Point within that triangle and returns the z-value at that point. @@ -464,25 +807,7 @@ declare module turf { * @param triangle A Polygon feature with three vertices * @returns The z-value for interpolatedPoint */ - function planepoint(interpolatedpoint: GeoJSON.Feature, triangle: GeoJSON.Feature): number; - - /** - * Takes a bounding box and a cell depth and returns a set of points in a grid. - * @param extent Extent in [minX, minY, maxX, maxY] order - * @param cellWidth The distance across each cell - * @param units Used in calculating cellWidth ('miles' or 'kilometers') - * @returns Grid of points - */ - function pointGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; - - /** - * Takes a bounding box and a cell depth and returns a set of square polygons in a grid. - * @param extent Extent in [minX, minY, maxX, maxY] order - * @param cellWidth Width of each cell - * @param units Used in calculating cellWidth ('miles' or 'kilometers') - * @returns Grid of polygons - */ - function squareGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + planepoint(interpolatedpoint: GeoJSON.Feature, triangle: GeoJSON.Feature): number; /** * Takes a set of points and the name of a z-value property and creates a Triangulated Irregular Network, or a TIN for short, returned as a collection of Polygons. @@ -492,39 +817,59 @@ declare module turf { * @param [propertyName] Name of the property from which to pull z values This is optional: if not given, then there will be no extra data added to the derived triangles. * @returns TIN output */ - function tin(points: GeoJSON.FeatureCollection, propertyName?: string): GeoJSON.FeatureCollection; - - /** - * Takes a bounding box and a cell depth and returns a set of triangular polygons in a grid. - * @param extent Extent in [minX, minY, maxX, maxY] order - * @param cellWidth Width of each cell - * @param units Used in calculating cellWidth ('miles' or 'kilometers') - * @returns Grid of triangles - */ - function triangleGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + tin(points: GeoJSON.FeatureCollection, propertyName?: string): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Joins ////////////////////////////////////////////////////// /** - * Takes a Point and a Polygon or MultiPolygon and determines if the point resides inside the polygon. - * The polygon can be convex or concave. The function accounts for holes. - * @param point Input point - * @param polygon Input polygon or multipolygon - * @returns true if the Point is inside the Polygon; false if the Point is not inside the Polygon - */ - function inside(point: GeoJSON.Feature, polygon: GeoJSON.Feature): boolean; + * Takes a {} and a {} or {} and determines if the point resides inside the polygon. The polygon can be convex or concave. The function accounts for holes. + * + * @name [inside](http://turfjs.org/docs/#inside) + * @param {Feature} point input point + * @param {Feature<(Polygon|MultiPolygon)>} polygon input polygon or multipolygon + * @return {Boolean} `true` if the Point is inside the Polygon; `false` if the Point is not inside the Polygon + * @example + * var pt = point([-77, 44]) + * var poly = polygon([[[-81, 41], [-81, 47], [-72, 47], [-72, 41], [-81, 41]]]) + * + * var isInside = turf.inside(pt, poly) + * + * //=isInside + */ + inside( + point: GeoJSON.Feature, + polygon: GeoJSON.Feature + ): boolean; /** - * Takes a set of points and a set of polygons and performs a spatial join. - * @param points Input points - * @param polygons Input polygons - * @param polyId Property in polygons to add to joined Point features - * @param containingPolyId Property in points in which to store joined property from polygons - * @returns Points with containingPolyId property containing values from polyId - */ - function tag(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection, polyId: string, containingPolyId: string): GeoJSON.FeatureCollection; + * Takes a {FeatureCollection} and a {FeatureCollection} and performs a spatial join. + * + * @name [tag](http://turfjs.org/docs/#inside) + * @param {FeatureCollection} points input points + * @param {FeatureCollection} polygons input polygons + * @param {string} field property in `polygons` to add to joined {} features + * @param {string} outField property in `points` in which to store joined property from `polygons` + * @return {FeatureCollection} points with `containingPolyId` property containing values from `polyId` + * @example + * var pt1 = point([-77, 44]) + * var pt2 = point([-77, 38]) + * var poly1 = polygon([[[-81, 41], [-81, 47], [-72, 47], [-72, 41], [-81, 41]]], {pop: 1000}) + * var poly2 = polygon([[[-81, 35], [-81, 41], [-72, 41], [-72, 35], [-81, 35]]], {pop: 3000}) + * + * var points = featureCollection([pt1, pt2]) + * var polygons = featureCollection([poly1, poly2]) + * + * var tagged = turf.tag(points, polygons, 'pop', 'population') + * //=tagged + */ + tag( + points: GeoJSON.FeatureCollection, + polygons: GeoJSON.FeatureCollection, + field: string, + outField: string + ): GeoJSON.FeatureCollection; /** * Takes a set of points and a set of polygons and returns the points that fall within the polygons. @@ -532,49 +877,331 @@ declare module turf { * @param polygons Input polygons * @returns Points that land within at least one polygon */ - function within(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + within( + points: GeoJSON.FeatureCollection, + polygons: GeoJSON.FeatureCollection + ): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Classification ////////////////////////////////////////////////////// - /** - * Takes a set of features and returns an array of the Jenks Natural breaks for a given property. - * @param input Input features - * @param field The property in input on which to calculate Jenks natural breaks - * @param numberOfBreaks Number of classes in which to group the data - * @returns The break number for each class plus the minimum and maximum values - */ - function jenks(input: GeoJSON.FeatureCollection, field: string, numberOfBreaks: number): Array; - /** * Takes a reference point and a set of points and returns the point from the set closest to the reference. * @param point The reference point * @param against Input point set * @returns The closest point in the set to the reference point */ - function nearest(point: GeoJSON.Feature, against: GeoJSON.FeatureCollection): GeoJSON.Feature; - - /** - * Takes a FeatureCollection, a property name, and a set of percentiles and returns a quantile array. - * @param input Set of features - * @param field The property in input from which to retrieve quantile values - * @param percentiles An Array of percentiles on which to calculate quantile values - * @returns An array of the break values - */ - function quantile(input: GeoJSON.FeatureCollection, field: string, percentiles: Array): Array; - - /** - * Takes a FeatureCollection, an input field, an output field, and an array of translations and outputs an identical FeatureCollection with the output field property populated. - * @param input Set of input features - * @param inField The field to translate - * @param outField The field in which to store translated results - * @param translations An array of translations - * @returns A FeatureCollection with identical geometries to input but with outField populated. - */ - function reclass(input: GeoJSON.FeatureCollection, inField: string, outField: string, translations: Array): GeoJSON.FeatureCollection; + nearest( + point: GeoJSON.Feature, + against: GeoJSON.FeatureCollection + ): GeoJSON.Feature; + } } -declare module 'turf' { - export= turf; +// NPM Stable version of Turf +declare module "turf" { + export = turf } + +// Latest version of Turf +declare module "@turf/turf" { + export = turf +} + +// AGGREGATION +declare module "@turf/collect" { + const collect: typeof turf.collect; + export = collect; +} + +// MEASUREMENT +declare module "@turf/along" { + const along: typeof turf.along; + export = along; +} + +declare module "@turf/area" { + const area: typeof turf.area; + export = area; +} + +declare module "@turf/bbox-polygon" { + const bboxPolygon: typeof turf.bboxPolygon; + export = bboxPolygon; +} + +declare module "@turf/bearing" { + const bearing: typeof turf.bearing; + export = bearing; +} + +declare module "@turf/center" { + const center: typeof turf.center; + export = center; +} + +declare module "@turf/centroid" { + const centroid: typeof turf.centroid; + export = centroid; +} + +declare module "@turf/destination" { + const destination: typeof turf.destination; + export = destination; +} + +declare module "@turf/distance" { + const distance: typeof turf.distance; + export = distance; +} + +declare module "@turf/envelope" { + const envelope: typeof turf.envelope; + export = envelope; +} + +declare module "@turf/line-distance" { + const lineDistance: typeof turf.lineDistance; + export = lineDistance; +} + +declare module "@turf/midpoint" { + const midpoint: typeof turf.midpoint; + export = midpoint; +} + +declare module "@turf/point-on-surface" { + const pointOnSurface: typeof turf.pointOnSurface; + export = pointOnSurface; +} + +declare module "@turf/square" { + const square: typeof turf.square; + export = square; +} + +// TRANSFORMATION +declare module "@turf/bezier" { + const bezier: typeof turf.bezier; + export = bezier; +} + +declare module "@turf/buffer" { + const buffer: typeof turf.buffer; + export = buffer; +} + +declare module "@turf/concave" { + const concave: typeof turf.concave; + export = concave; +} + +declare module "@turf/convex" { + const convex: typeof turf.convex; + export = convex; +} + +declare module "@turf/difference" { + const difference: typeof turf.difference; + export = difference; +} + +declare module "@turf/intersect" { + const intersect: typeof turf.intersect; + export = intersect; +} + +declare module "@turf/simplify" { + const simplify: typeof turf.simplify; + export = simplify; +} + +declare module "@turf/union" { + const union: typeof turf.union; + export = union; +} + +// MISC +declare module "@turf/combine" { + const combine: typeof turf.combine; + export = combine; +} + +declare module "@turf/explode" { + const explode: typeof turf.explode; + export = explode; +} + +declare module "@turf/flip" { + const flip: typeof turf.flip; + export = flip; +} + +declare module "@turf/kinks" { + const kinks: typeof turf.kinks; + export = kinks; +} + +declare module "@turf/line-slice" { + const lineSlice: typeof turf.lineSlice; + export = lineSlice; +} + +declare module "@turf/point-on-line" { + const pointOnLine: typeof turf.pointOnLine; + export = pointOnLine; +} + +// HELPER +declare module "@turf/helpers" { + const helpers: { + featureCollection: typeof turf.featureCollection, + feature: typeof turf.feature, + lineString: typeof turf.lineString, + multiLineString: typeof turf.multiLineString, + point: typeof turf.point, + multiPoint: typeof turf.multiPoint, + polygon: typeof turf.polygon, + multiPolygon: typeof turf.multiPolygon, + geometryCollection: typeof turf.geometryCollection, + }; + export = helpers; +} + +// DATA +declare module "@turf/random" { + const random: typeof turf.random; + export = random; +} + +declare module "@turf/sample" { + const sample: typeof turf.sample; + export = sample; +} + +// INTERPOLATION +declare module "@turf/isolines" { + const isolines: typeof turf.isolines; + export = isolines; +} + +declare module "@turf/planepoint" { + const planepoint: typeof turf.planepoint; + export = planepoint; +} + +declare module "@turf/tin" { + const tin: typeof turf.tin; + export = tin; +} + +// JOINS +declare module "@turf/inside" { + const inside: typeof turf.inside; + export = inside; +} + +declare module "@turf/tag" { + const tag: typeof turf.tag; + export = tag; +} + +declare module "@turf/within" { + const within: typeof turf.within; + export = within; +} + +// GRIDS +declare module "@turf/hex-grid" { + const hexGrid: typeof turf.hexGrid; + export = hexGrid; +} + +declare module "@turf/point-grid" { + const pointGrid: typeof turf.pointGrid; + export = pointGrid; +} + +declare module "@turf/square-grid" { + const squareGrid: typeof turf.squareGrid; + export = squareGrid; +} + +declare module "@turf/triangle-grid" { + const triangleGrid: typeof turf.triangleGrid; + export = triangleGrid; +} + +// CLASSIFICATION +declare module "@turf/nearest" { + const nearest: typeof turf.nearest; + export = nearest; +} + +// // META +// declare module "@turf/propEach" { +// const propEach: typeof turf.propEach; +// export = propEach; +// } + +// declare module "@turf/coordEach" { +// const coordEach: typeof turf.coordEach; +// export = coordEach; +// } + +// declare module "@turf/coordReduce" { +// const coordReduce: typeof turf.coordReduce; +// export = coordReduce; +// } + +// declare module "@turf/featureEach" { +// const featureEach: typeof turf.featureEach; +// export = featureEach; +// } + +// declare module "@turf/getCoord" { +// const getCoord: typeof turf.getCoord; +// export = getCoord; +// } + +// // ASSERTIONS +// declare module "@turf/featureOf" { +// const featureOf: typeof turf.featureOf; +// export = featureOf; +// } + +// declare module "@turf/collectionOf" { +// const collectionOf: typeof turf.collectionOf; +// export = collectionOf; +// } + +declare module "@turf/bbox" { + const bbox: typeof turf.bbox; + export = bbox; +} + +// declare module "@turf/circle" { +// const circle: typeof turf.circle; +// export = circle; +// } + +// declare module "@turf/geojsonType" { +// const geojsonType: typeof turf.geojsonType; +// export = geojsonType; +// } + +// declare module "@turf/propReduce" { +// const propReduce: typeof turf.propReduce; +// export = propReduce; +// } + +// declare module "@turf/coordAll" { +// const coordAll: typeof turf.coordAll; +// export = coordAll; +// } + +// declare module "@turf/tesselate" { +// const tesselate: typeof turf.tesselate; +// export = tesselate; +// } diff --git a/twilio/twilio-tests.ts b/twilio/twilio-tests.ts new file mode 100644 index 0000000000..25c6915068 --- /dev/null +++ b/twilio/twilio-tests.ts @@ -0,0 +1,239 @@ +import * as twilio from './twilio'; +import * as Express from "express"; + +// Examples taken from https://twilio.github.io/twilio-node/ (v2.1.0) + +var str: string; + +// Create a client: +var client: twilio.RestClient = (require('twilio') as twilio)('ACCOUNT_SID', 'AUTH_TOKEN'); + +//Get a list of calls made by this account +// GET /2010-04-01/Accounts/ACCOUNT_SID/Calls +// alias for get is "list", if you prefer +client.calls.get(function(err: any, response: any) { + response.calls.forEach(function(call: any) { + console.log('Received call from: ' + call.from); + console.log('Call duration (in seconds): ' + call.duration); + }); +}); + +//Get a list of calls made by this account, from this phone number +// GET /2010-04-01/Accounts/ACCOUNT_SID/Calls?From=+16513334455 +client.calls.get({ + from:'+16513334455' +}, function(err: any, response: any) { + response.calls.forEach(function(call: any) { + console.log('Received call from: ' + call.from); + console.log('This call\'s unique ID is: ' + call.sid); + }); +}); + +//Get data for a specific call +// GET /2010-04-01/Accounts/ACCOUNT_SID/Calls/abc123... +client.calls('abc123...').get(function(err: any, call: any) { + console.log('This call\'s unique ID is: ' + call.sid); + console.log('This call was created at: ' + call.dateCreated); +}); + +//Get data for a specific call, for a specific account +// GET /2010-04-01/Accounts/AC.../Calls/abc123... +client.accounts('AC...').calls('abc123...').get(function(err: any, response: any) { + response.calls.forEach(function(call: any) { + console.log('Received call from: ' + call.from); + console.log('This call\'s unique ID is: ' + call.sid); + }); +}); + +// Create (send) an SMS message +// POST /2010-04-01/Accounts/ACCOUNT_SID/SMS/Messages +// "create" and "update" aliases are in place where appropriate on PUT and POST requests +client.sms.messages.post({ + to:'+16515559999', + from:'+14503334455', + body:'word to your mother.' +}, function(err: any, text: any) { + console.log('You sent: '+ text.body); + console.log('Current status of this text message is: '+ text.status); +}); + +// Delete a TwiML application +// DELETE /2010-04-01/Accounts/ACCOUNT_SID/Applications/APP... +client.applications('APP...').delete(function(err: any, response: any, nodeResponse: any) { + //DELETE requests do not return data - if there was no error, it worked. + err ? console.log('There was an error') : console.log('it worked!'); +}); + +var SOME_SUBACCOUNT_SID = 'AC...'; + +//Send a text message, associated with the given subaccount +client.accounts(SOME_SUBACCOUNT_SID).sms.messages.create({ + to:'+16512223333', + from:'+14505556677', + body:'word to your subaccount mother.' +}, function(err: any, text: any) { + console.log('You sent: '+ text.body); + console.log('Current status of this text message is: '+ text.status); +}); + +//This REST call using the master/default account for the client... +client.makeCall({ + to:'+16512223333', + from:'+14505556677', + url:'http://example.com/someTwiml.php' +}, function(err: any, call: any) { + console.log('This call\'s unique ID is: ' + call.sid); + console.log('This call was created at: ' + call.dateCreated); +}); + +//...is the same as... +client.accounts(str).calls.create({ + to:'+16512223333', + from:'+14505556677', + url:'http://example.com/someTwiml.php' +}, function(err: any, call: any) { + console.log('This call\'s unique ID is: ' + call.sid); + console.log('This call was created at: ' + call.dateCreated); +}); + +var restClient = new twilio.RestClient('ACCOUNT_SID', 'AUTH_TOKEN'); + +// A simple example of making a phone call using promises +var promise = restClient.makeCall({ + to:'+16515556667777', // a number to call + from:'+16518889999', // a Twilio number you own + url:'https://demo.twilio.com/welcome/voice' // A URL containing TwiML instructions for the call +}); + +// You can assign functions to be called, at any time, after the request to +// Twilio has been completed. The first function is called when the request +// succeeds, the second if there was an error. +promise.then(function(call: any) { + console.log('Call success! Call SID: '+call.sid); +}, function(error: any) { + console.error('Call failed! Reason: '+error.message); +}); + +// Let's look at an example where we're making multiple requests to Twilio, like +// buying a new phone number. This is where promises can become very useful: + +// First, search for available phone numbers +restClient.availablePhoneNumbers('US').local.get({ + areaCode:'651' +}).then(function(searchResults: any) { + + // handle the case where there are no numbers found + if (searchResults.availablePhoneNumbers.length < 1) { + throw { message:'No numbers found with that area code' }; + } + + // Okay, so there are some available numbers. Now, let's buy the first one + // in the list. Return the promise created by the next call to Twilio: + return restClient.incomingPhoneNumbers.create({ + phoneNumber:searchResults.availablePhoneNumbers[0].phoneNumber, + voiceUrl:'https://demo.twilio.com/welcome/voice', + smsUrl:'https://demo.twilio.com/welcome/sms/reply' + }); + +}).then(function(number: any) { + + // We bought the number! Everything worked! + console.log('Your new number: '+number.phoneNumber); + +}).fail(function(error: any) { + + // This callback will be invoked on any error returned in the + // process. + console.log('Number purchase failed! Reason: '+error.message); + +}).fin(function() { + + // You can use this optional callback like a "finally" block + // It will always execute last. Perform any cleanup necessary here. + +}); + +client.request({ + url:'/Accounts', + method:'GET' +}, function (error: any, responseData: any) { + //work with response data +}); + +/// TwiML +var resp = new twilio.TwimlResponse(); + +resp.say('Welcome to Twilio!'); +resp.say('Please let us know if we can help during your development.', { + voice:'woman', + language:'en-gb' +}); + +console.log(resp.toString()); + +resp.say('Welcome to Twilio!') + .pause({ length:3 }) + .say('Please let us know if we can help during your development.', { + voice:'woman', + language:'en-gb' + }) + .play('http://www.example.com/some_sound.mp3'); + +resp.say('Welcome to Acme Customer Service!') + .gather({ + action:'http://www.example.com/callFinished.php', + finishOnKey:'*' + }, function() { + this.say('Press 1 for customer service') + .say('Press 2 for British customer service', { language:'en-gb' }); + }); + +resp.say('Welcome to Acme Customer Service!') + .gather({ + action:'http://www.example.com/callFinished.php', + finishOnKey:'*' + }, function(node: twilio.Node) { //note the use of the "node" variable in the anonymous function + + //Now you can use this reference as well, if using "this" wrankles you + node.say('Press 1 for customer service') + .say('Press 2 for British customer service', { language:'en-gb' }); + + }); + +resp.say('Your conference call is starting.', + { + voice:'woman', + language:'en-gb' + }) + .dial({ + action:'http://example.com/something.php' + }, function(node: twilio.Node) { + node.conference('waitingRoom', { + beep:'false' + }); + }); + +resp.hangup(); + +/// Capabilities +var capability = new twilio.Capability(str, str); +capability.allowClientIncoming('jenny'); +var token = capability.generate(); + +capability.allowClientOutgoing('AP123'); +var token = capability.generate(); + +capability.allowClientOutgoing('AP123'); +var token = capability.generate(120); + +/// Utilities +twilio.validateRequest(token, str, 'http://example.herokuapp.com', { query: 'val' }); +twilio.validateExpressRequest(getMockExpressRequest(), 'YOUR_TWILIO_AUTH_TOKEN'); +twilio.validateExpressRequest(getMockExpressRequest(), 'YOUR_TWILIO_AUTH_TOKEN', {}); +twilio.webhook({ validate: false }); +twilio.webhook("MYAUTHTOKEN", { validate: false }); + + +function getMockExpressRequest(): Express.Request { + return JSON.parse("{}"); +} diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts new file mode 100644 index 0000000000..824b596330 --- /dev/null +++ b/twilio/twilio.d.ts @@ -0,0 +1,881 @@ +// Type definitions for twilio +// Project: https://github.com/twilio/twilio-node +// Definitions by: nickiannone +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// + +import * as Express from 'express'; +import * as Http from 'http'; + +import q = require('q'); + +declare interface twilio { + (sid?: string, tkn?: string, options?: twilio.ClientOptions): twilio.RestClient; +} + +declare namespace twilio { + + // Composite Classes: + //============================== + // RestClient + // PricingClient + // MonitorClient + // TaskRouterClient + // IpMessagingClient + // LookupsClient + // TrunkingClient + + // Classes: + //============================== + // AccessToken + // Capability + // TaskRouterCapability + // TaskRouterWorkerCapability + // TaskRouterWorkspaceCapability + // TaskRouterTaskQueueCapability + // TwimlResponse (TODO main export is generator function) + // webhook + + // Methods: + //=============================== + // validateRequest + // validateExpressRequest + + /// Random stuff + export interface GrantPayload {} + + export interface Grant { + toPayload(): GrantPayload; + } + + export interface RequestCallback { (err: any, data: any, response: Http.ClientResponse): void; } + export interface BaseRequestCallback { (err: any, data: any): void; } + + export interface RestMethod { (args: any | BaseRequestCallback, callback?: RequestCallback): Q.Promise; } + + /// Resource stock interfaces + export interface BaseMappedResource { + (resourceSid: string): T; + } + + export interface Resource { + get: RestMethod; + } + + export interface DeletableResource extends Resource { + delete: RestMethod; + } + + export interface ListableResource extends Resource { + list: RestMethod; + } + + export interface MappedResource extends Resource, BaseMappedResource {} + + export interface PostableResource extends Resource { + post: RestMethod; + } + + export interface InstanceResource extends PostableResource, DeletableResource { + update: RestMethod; + } + + export interface CreatableMappedResource extends MappedResource, PostableResource { + create: RestMethod; + } + + export interface ListMappedResource extends CreatableMappedResource, ListableResource {} + + /// AccessToken.js + export interface IpMessagingGrantOptions { + serviceSid: string; + endpointId: string; + deploymentRoleSid: string; + pushCredentialSid: string; + } + + export interface IpMessagingGrantPayload extends GrantPayload { + service_sid: string; + endpoint_id: string; + deployment_role_sid: string; + push_credential_sid: string; + } + + export class IpMessagingGrant implements Grant { + serviceSid: string; + endpointId: string; + deploymentRoleSid: string; + pushCredentialSid: string; + key: string; + + constructor(options?: IpMessagingGrantOptions); + + toPayload(): IpMessagingGrantPayload; + } + + export interface ConversationsGrantOptions { + configurationProfileSid: string; + } + + export interface ConversationsGrantPayload extends GrantPayload { + configuration_profile_sid: string; + } + + export class ConversationsGrant implements Grant { + configurationProfileSid: string; + + constructor(options?: ConversationsGrantOptions); + + toPayload(): ConversationsGrantPayload; + } + + export interface AccessTokenOptions { + ttl: number; + identity: string; + nbf: number; + } + + export class AccessToken { + accountSid: string; + keySid: string; + secret: string; + ttl: number; + identity: string; + nbf: number; + grants: Array; + + static IpMessagingGrant: IpMessagingGrant; + static ConversationGrant: ConversationsGrant; + static DEFAULT_ALGORITHM: string; + static ALGORITHMS: Array; + + constructor(accountSid: string, keySid: string, secret: string, opts?: AccessTokenOptions); + + addGrant(grant: Grant): void; + toJwt(algorithm: string): any; // TODO Find correct typedef + } + + /// Capability.js + export class Capability { + accountSid: string; + authToken: string; + capabilities: Array; + clientName: string; + outgoingScopeParams: any; + scopeParams: any; + + constructor(sid?: string, tkn?: string); + + allowClientIncoming(clientName: string): Capability; + allowClientOutgoing(appSid: string, params?: any): Capability; + allowEventStream(filters?: any): Capability; + generate(timeout?: number): string; + } + + /// Client.js + export interface ClientOptions { + host?: string; + apiVersion?: string; + timeout?: number; + } + + export interface ClientRequestOptions { + url: string; + method?: string; + form?: any; + } + + export class Client { + accountSid: string; + authToken: string; + host: string; + apiVersion: string; + timeout: number; + + constructor(sid?: string, tkn?: string, host?: string, api_version?: string, timeout?: number); + + getBaseUrl(): string; + request(options: ClientRequestOptions, callback?: RequestCallback): Q.Promise; + } + + /// IpMessagingClient.js + export class IpMessagingClient extends Client { + services: ServiceResource; + credentials: CredentialResource; + + constructor(sid?: string, tkn?: string, options?: ClientOptions); + } + + /// LookupsClient.js + export class LookupsClient extends Client { + phoneNumbers: PhoneNumberResource; + + constructor(sid?: string, tkn?: string, options?: ClientOptions); + } + + /// MonitorClient.js + export class MonitorClient extends Client { + events: EventResource; + alerts: AlertResource; + + constructor(sid?: string, tkn?: string, options?: ClientOptions); + } + + /// PricingClient.js + export class PricingClient extends Client { + voice: PricingVoiceResource; + phoneNumbers: PricingPhoneNumberResource; + messaging: PricingMessagingResource; + + constructor(sid?: string, tkn?: string, options?: ClientOptions); + } + + /// RestClient.js + export class RestClient extends Client { + constructor(sid?: string, tkn?: string, options?: ClientOptions); + + accounts: AccountResource; + + // Imported from AccountResource + availablePhoneNumbers: AvailablePhoneNumberResource; + outgoingCallerIds: OutgoingCallerIdResource; + incomingPhoneNumbers: IncomingPhoneNumberResource; + messages: MessageResource; + sms: SMSIntermediary; + applications: ApplicationResource; + connectApps: ConnectAppResource; + authorizedConnectApps: AuthorizedConnectAppResource; + calls: CallResource; + conferences: ConferenceResource; + queues: QueueResource; + recordings: RecordingResource; + tokens: TokenResource; + transcriptions: TranscriptionResource; + notifications: NotificationResource; + usage: UsageIntermediary; + sip: SIPIntermediary; + addresses: AddressResource; + keys: KeyResource; + + // Mixed-in Methods + put: RestMethod; + post: RestMethod; + get: RestMethod; + update: RestMethod; + list: RestMethod; + + // Messaging shorthand + sendSms: RestMethod; + sendMms: RestMethod; + sendMessage: RestMethod; + listSms: RestMethod; + listMessages: RestMethod; + getSms(messageSid: string, callback?: RequestCallback): Q.Promise; + getMessage(messageSid: string, callback?: RequestCallback): Q.Promise; + + // Calls shorthand + makeCall: RestMethod; + listCalls: RestMethod; + getCall(callSid: string, callback?: RequestCallback): Q.Promise; + + // Overrides Client.request(...) + request(options: ClientRequestOptions, callback?: RequestCallback): Q.Promise; + } + + /// TaskRouterCapability.js + + export interface Policy { + url: string; + method: string; + query_filter?: any; // Map, where FilterRequirement ::= Map + post_filter?: any; // Map, where FilterRequirement ::= Map + allow: boolean; + } + + export class TaskRouterCapability { + accountSid: string; + authToken: string; + policies: Array; + workspaceSid: string; + channelId: string; + + private _baseUrl: string; + private _resourceUrl: string; + + constructor(accountSid: string, authToken: string, workspaceSid: string, channelId: string); + + protected _setupResource(): void; + private _validateJWT(): void; + private _generate(ttl: number, extraAttributes: any): string; + + allowFetchSubresources(): void; + allowUpdates(): void; + allowUpdatesSubresources(): void; + allowDelete(): void; + allowDeleteSubresources(): void; + allowWorkerActivityUpdates(): void; + allowWorkerFetchAttributes(): void; + allowTaskReservationUpdates(): void; + + addPolicy(url: string, method: string, allowed?: boolean, queryFilter?: any, postFilter?: any): void; + allow(url: string, method: string, queryFilter?: any, postFilter?: any): void; + deny(url: string, method: string, queryFilter?: any, postFilter?: any): void; + generate(ttl: number): string; + } + + /// TaskRouterClient.js + export class TaskRouterClient extends Client { + workspaces: WorkspaceResource; + workspace: WorkspaceResource; + + constructor(sid?: string, tkn?: string, workspaceSid?: string, options?: ClientOptions); + } + + /// TaskRouterTaskQueueCapability.js + export class TaskRouterTaskQueueCapability extends TaskRouterCapability { + constructor(accountSid: string, authToken: string, workspaceSid: string, taskQueueSid: string); + + protected _setupResource(): void; + } + + /// TaskRouterWorkerCapability.js + export class TaskRouterWorkerCapability extends TaskRouterCapability { + reservationsUrl: string; + activityUrl: string; + workerReservationsUrl: string; + + constructor(accountSid: string, authToken: string, workspaceSid: string, workerSid: string); + + protected _setupResource(): void; + + allowActivityUpdates(): void; + allowReservationUpdates(): void; + } + + /// TaskRouterWorkspaceCapability.js + export class TaskRouterWorkspaceCapability extends TaskRouterCapability { + constructor(accountSid: string, authToken: string, workspaceSid: string); + + protected _setupResource(): void; + } + + /// TrunkingClient.js + export class TrunkingClient extends Client { + trunks: TrunkResource; + + constructor(sid?: string, tkn?: string, options?: ClientOptions); + } + + /// TwimlResponse.js + // ???? - Someone else should look at this thing to make sure it's correct + export interface NodeOptions { + name: string; + attributes?: any; + text?: string; + topLevel?: boolean; + legalNodes: Array; + } + + export interface TwimlMethod { + (): Node; + (arg1: TwimlCallback | string, arg2?: any): Node; + (arg1: any, arg2?: TwimlCallback | string): Node; + } + + export interface TwimlCallback { (node: Node): void; } + + export class Node implements NodeOptions { + name: string; + attributes: any; + text: any; + topLevel: boolean; + legalNodes: Array; + + constructor(config?: NodeOptions); + + // TwiML Verbs/Nouns: + gather: TwimlMethod; + say: TwimlMethod; + play: TwimlMethod; + pause: TwimlMethod; + + dial: TwimlMethod; + number: TwimlMethod; + client: TwimlMethod; + conference: TwimlMethod; + queue: TwimlMethod; + sip: TwimlMethod; + + message: TwimlMethod; + media: TwimlMethod; + body: TwimlMethod; + + enqueue: TwimlMethod; + task: TwimlMethod; + + record: TwimlMethod; + sms: TwimlMethod; + hangup: TwimlMethod; + redirect: TwimlMethod; + reject: TwimlMethod; + leave: TwimlMethod; + + toString(): string; + } + + export class TwimlResponse extends Node {} + + /// webhook.js + export interface WebhookOptions { + validate?: boolean; + includeHelpers?: boolean; + host?: string; + protocol?: string; + } + + export interface WebhookExpressOptions { + // The full URL (with query string) you used to configure the webhook with Twilio - overrides host/protocol options + url?: string; + + // manually specify the host name used by Twilio in a number's webhook config + host?: string; + + // manually specify the protocol used by Twilio in a number's webhook config + protocol?: string; + } + + // For interop with node middleware chains + export interface MiddlewareFunction { (request: Http.ServerRequest, response: Http.ServerResponse, next: Express.NextFunction): void; } + + export function webhook(authToken: string, options?: WebhookOptions): MiddlewareFunction; + export function webhook(options?: WebhookOptions): MiddlewareFunction; + + export function validateRequest(authToken: string, twilioHeader: string, url: string, params?: any): boolean; + export function validateExpressRequest(request: Express.Request, authToken: string, options?: WebhookExpressOptions): boolean; + + /// resources/Accounts.js + export interface OutgoingCallerIdInstance extends InstanceResource { + put: RestMethod; + } + export interface OutgoingCallerIdResource extends CreatableMappedResource {} + + export interface SMSMessageInstance extends Resource {} + export interface SMSMessageResource extends CreatableMappedResource {} + + export interface SMSShortCodeInstance extends PostableResource { + update: RestMethod; + } + export interface SMSShortCodeResource extends MappedResource {} + + export interface SMSIntermediary { + messages: SMSMessageResource; + shortCodes: SMSShortCodeResource; + } + + export interface ApplicationInstance extends InstanceResource {} + export interface ApplicationResource extends CreatableMappedResource {} + + export interface ConnectAppInstance extends PostableResource { + update: RestMethod; + } + export interface ConnectAppResource extends MappedResource {} + + export interface AuthorizedConnectAppInstance extends Resource {} + export interface AuthorizedConnectAppResource extends MappedResource {} + + export interface TokenInstance {} + export interface TokenResource extends BaseMappedResource { + post: RestMethod; + create: RestMethod; + } + + export interface TranscriptionInstance extends DeletableResource {} + export interface TranscriptionResource extends MappedResource {} + + export interface NotificationInstance extends DeletableResource {} + export interface NotificationResource extends MappedResource {} + + export interface UsageTriggerInstance extends InstanceResource {} + export interface UsageTriggerResource extends CreatableMappedResource {} + + export interface UsageIntermediary { + records: UsageRecordResource; + triggers: UsageTriggerResource; + } + + export interface SIPIntermediary { + domains: DomainResource; + ipAccessControlLists: IPAccessControlListResource; + credentialLists: CredentialListResource; + } + + export interface KeyInstance extends InstanceResource {} + export interface KeyResource extends CreatableMappedResource {} + + export interface AccountInstance extends PostableResource { + update: RestMethod; + put: RestMethod; + + // Mixed-in resources + availablePhoneNumbers: AvailablePhoneNumberResource; + outgoingCallerIds: OutgoingCallerIdResource; + incomingPhoneNumbers: IncomingPhoneNumberResource; + messages: MessageResource; + sms: SMSIntermediary; + applications: ApplicationResource; + connectApps: ConnectAppResource; + authorizedConnectApps: AuthorizedConnectAppResource; + calls: CallResource; + conferences: ConferenceResource; + queues: QueueResource; + recordings: RecordingResource; + tokens: TokenResource; + transcriptions: TranscriptionResource; + notifications: NotificationResource; + usage: UsageIntermediary; + sip: SIPIntermediary; + addresses: AddressResource; + keys: KeyResource; + } + + export interface AccountResource extends AccountInstance, ListMappedResource {} + + /// resources/Addresses.js + export interface DependentPhoneNumberResource extends ListableResource {} + + export interface AddressInstance extends PostableResource, DeletableResource { + // Mixins + dependentPhoneNumbers: DependentPhoneNumberResource; + } + export interface AddressResource extends ListMappedResource {} + + /// resources/AvailablePhoneNumbers.js + export interface AvailablePhoneNumberResourceGroup extends ListableResource { + search: RestMethod; + } + export interface AvailablePhoneNumberInstance { + local: AvailablePhoneNumberResourceGroup; + tollFree: AvailablePhoneNumberResourceGroup; + mobile: AvailablePhoneNumberResourceGroup; + } + export interface AvailablePhoneNumberResource extends BaseMappedResource {} + + /// resources/Calls.js + export interface CallRecordingResource extends ListableResource {} + export interface CallNotificationResource extends ListableResource {} + export interface CallFeedbackResource extends PostableResource, DeletableResource { + create: RestMethod; + } + + export interface CallInstance extends InstanceResource { + recordings: CallRecordingResource; + notifications: CallNotificationResource; + feedback: CallFeedbackResource; + } + + export interface CallFeedbackSummaryInstance extends DeletableResource {} + export interface CallFeedbackSummaryResource extends BaseMappedResource { + post: RestMethod; + create: RestMethod; + } + export interface CallResource extends CreatableMappedResource { + feedbackSummary: CallFeedbackSummaryResource; + } + + /// resources/Conferences.js + export interface ConferenceParticipantInstance extends InstanceResource { + kick: RestMethod; + } + export interface ConferenceParticipantResource extends MappedResource, ListableResource {} + export interface ConferenceInstance extends Resource { + participants: ConferenceParticipantResource; + } + export interface ConferenceResource extends MappedResource, ListableResource {} + + /// resources/IncomingPhoneNumbers.js + export interface IncomingPhoneNumberResourceGroup extends PostableResource { + create: RestMethod; + } + export interface IncomingPhoneNumberInstance extends InstanceResource { + put: RestMethod; + } + export interface IncomingPhoneNumberResource extends CreatableMappedResource { + local: IncomingPhoneNumberResourceGroup; + tollFree: IncomingPhoneNumberResourceGroup; + mobile: IncomingPhoneNumberResourceGroup; + } + + /// resources/Messages.js + export interface MessageMediaInstance extends DeletableResource {} + export interface MessageMediaResource extends MappedResource, ListableResource {} + export interface MessageInstance extends PostableResource, DeletableResource { + media: MessageMediaResource; + } + export interface MessageResource extends ListMappedResource {} + + /// resources/Queues.js + export interface QueueMemberInstance extends PostableResource { + update: RestMethod; + } + export interface QueueMemberResource extends MappedResource { + front: QueueMemberInstance; + } + + export interface QueueInstance extends InstanceResource { + members: QueueMemberResource; + } + export interface QueueResource extends CreatableMappedResource {} + + /// resources/Recordings.js + export interface RecordingTranscriptionResource extends ListableResource {} + export interface RecordingInstance extends ListableResource, DeletableResource { + transcriptions: RecordingTranscriptionResource; + } + export interface RecordingResource extends MappedResource, ListableResource {} + + /// resources/UsageRecords.js + export interface UsageRecordInstance extends Resource {} + export interface UsageRecordRange extends ListableResource {} + + export interface UsageRecordResource extends MappedResource { + daily: UsageRecordRange; + monthly: UsageRecordRange; + yearly: UsageRecordRange; + allTime: UsageRecordRange; + today: UsageRecordRange; + yesterday: UsageRecordRange; + thisMonth: UsageRecordRange; + lastMonth: UsageRecordRange; + } + + /// resources/ip_messaging/Credentials.js + export interface CredentialInstance extends InstanceResource {} + export interface CredentialResource extends ListMappedResource {} + + /// resources/ip_messaging/Services.js + export interface ServiceUserInstance extends InstanceResource {} + export interface ServiceUserResource extends ListMappedResource {} + export interface ServiceRoleInstance extends Resource {} + export interface ServiceRoleResource extends MappedResource, ListableResource {} + + export interface ServiceChannelMessageInstance extends InstanceResource {} + export interface ServiceChannelMessageResource extends ListMappedResource {} + + export interface ServiceChannelMemberInstance extends InstanceResource {} + export interface ServiceChannelMemberResource extends ListMappedResource {} + + export interface ServiceChannelInstance extends InstanceResource { + messages: ServiceChannelMessageResource; + members: ServiceChannelMemberResource; + } + export interface ServiceChannelResource extends ListMappedResource {} + + export interface ServiceInstance extends InstanceResource { + users: ServiceUserResource; + roles: ServiceRoleResource; + channels: ServiceChannelResource; + } + export interface ServiceResource extends ListMappedResource {} + + /// resources/lookups/PhoneNumbers.js + export interface PhoneNumberInstance extends Resource {} + export interface PhoneNumberResource extends BaseMappedResource {} + + /// resources/monitor/Alerts.js + export interface AlertInstance extends Resource {} + export interface AlertResource extends MappedResource, ListableResource {} + + /// resources/monitor/Events.js + export interface EventInstance extends Resource {} + export interface EventResource extends MappedResource, ListableResource {} + + /// resources/pricing/Messaging.js + export interface CountryInstance extends Resource {} + export interface CountryResource extends MappedResource, ListableResource {} + + export interface PricingMessagingResource { + countries: CountryResource; + } + + /// resources/pricing/PhoneNumbers.js + export interface PricingPhoneNumberResource { + countries: CountryResource; + } + + /// resources/pricing/Voice.js + export interface NumberInstance extends Resource {} + export interface NumberResource extends MappedResource, ListableResource {} + + export interface PricingVoiceResource { + countries: CountryResource; + numbers: NumberResource; + } + + /// resources/sip/CredentialLists.js + export interface CredentialListInstance extends InstanceResource { + credentials: CredentialResource; + } + export interface CredentialListResource extends ListMappedResource {} + + /// resources/sip/Domains.js + export interface IPAccessControlListMappingInstance extends DeletableResource {} + export interface IPAccessControlListMappingResource extends ListMappedResource {} + + export interface CredentialListMappingInstance extends DeletableResource {} + export interface CredentialListMappingResource extends ListMappedResource {} + + export interface DomainInstance extends InstanceResource { + ipAccessControlListMappings: IPAccessControlListMappingResource; + credentialListMappings: CredentialListMappingResource; + } + export interface DomainResource extends ListMappedResource {} + + /// resources/sip/IpAccessControlLists.js + export interface IPAddressInstance extends InstanceResource {} + export interface IPAddressResource extends ListMappedResource {} + + export interface IPAccessControlListInstance extends InstanceResource { + ipAddresses: IPAddressResource; + } + export interface IPAccessControlListResource extends ListMappedResource {} + + /// resources/task_router/WorkflowBuilder.js + export interface WorkflowRuleTargetOptions { + queue: string; + expression?: string; + priority?: number; + timeout?: number; + } + + export class WorkflowRuleTarget { + queue: string; + expression: string; + priority: number; + timeout: number; + + constructor(options?: WorkflowRuleTargetOptions); + } + + export interface WorkflowRuleOptions { + expression: string; + targets: Array; + // Don't ask me why, but all of these are supported options. + friendly_name?: string; + friendlyName?: string; + filter_friendly_name?: string; + } + + export class WorkflowRule { + friendly_name: string; + expression: string; + targets: Array; + friendlyName: string; // Defined property mapped to friendly_name. + + constructor(options?: WorkflowRuleOptions); + } + + export interface TaskRoutingConfigurationOptions { + filters: Array; + default_filter?: WorkflowRuleOptions; + defaultFilter?: WorkflowRuleOptions; + } + + export class TaskRoutingConfiguration { + filters: Array; + default_filter: WorkflowRuleOptions; + defaultFilter: WorkflowRuleOptions; // Defined property mapped to default_filter. + + constructor(options?: TaskRoutingConfigurationOptions); + } + + export interface WorkflowConfigurationOptions { + task_routing?: TaskRoutingConfigurationOptions; + taskRouting?: TaskRoutingConfigurationOptions; + } + + export class WorkflowConfiguration { + task_routing: TaskRoutingConfiguration; + taskRouting: TaskRoutingConfiguration; // Defined property mapped to task_routing. + + constructor(options?: WorkflowConfigurationOptions); + + static fromJSON(json: string): WorkflowConfiguration; + toJSON(): string; + } + + /// resources/task_router/Workspaces.js + export interface WorkspaceActivityInstance extends InstanceResource {} + export interface WorkspaceActivityResource extends ListMappedResource {} + + export interface WorkspaceEventInstance extends Resource {} + export interface WorkspaceEventResource extends MappedResource, ListableResource {} + + export interface WorkspaceTaskReservationInstance extends PostableResource { + update: RestMethod; + } + export interface WorkspaceTaskReservationResource extends MappedResource, ListableResource {} + + export interface WorkspaceTaskInstance extends InstanceResource { + reservations: WorkspaceTaskReservationResource; + } + export interface WorkspaceTaskResource extends ListMappedResource {} + + export interface WorkspaceInstanceStatisticResource extends Resource {} + export interface WorkspaceStatisticResource extends ListableResource {} + + export interface WorkspaceTaskQueueInstance extends InstanceResource { + statistics: WorkspaceInstanceStatisticResource; + } + export interface WorkspaceTaskQueueResource extends ListMappedResource { + statistics: WorkspaceStatisticResource; + } + + export interface WorkspaceWorkerReservationInstance extends PostableResource { + update: RestMethod; + } + export interface WorkspaceWorkerReservationResource extends MappedResource, ListableResource {} + + export interface WorkspaceWorkerInstance extends InstanceResource { + statistics: WorkspaceInstanceStatisticResource; + reservations: WorkspaceWorkerReservationResource; + } + export interface WorkspaceWorkerResource extends ListMappedResource { + statistics: WorkspaceStatisticResource; + } + + export interface WorkspaceWorkflowInstance extends InstanceResource { + statistics: WorkspaceInstanceStatisticResource; + } + export interface WorkspaceWorkflowResource extends ListMappedResource { + statistics: WorkspaceStatisticResource; + } + + export interface WorkspaceInstance extends InstanceResource { + activities: WorkspaceActivityResource; + events: WorkspaceEventResource; + tasks: WorkspaceTaskResource; + taskQueues: WorkspaceTaskQueueResource; + workers: WorkspaceWorkerResource; + workflows: WorkspaceWorkflowResource; + + statistics: WorkspaceInstanceStatisticResource; + } + export interface WorkspaceResource extends CreatableMappedResource {} + + /// resources/trunking/Trunks.js + export interface OriginationURLInstance extends InstanceResource {} + export interface OriginationURLResource extends ListMappedResource {} + + export interface TrunkInstance extends InstanceResource { + ipAccessControlLists: IPAccessControlListResource; + credentialLists: CredentialListResource; + phoneNumbers: PhoneNumberResource; + originationUrls: OriginationURLResource; + } + export interface TrunkResource extends ListMappedResource {} +} + +export = twilio; diff --git a/twit/twit-tests.ts b/twit/twit-tests.ts new file mode 100644 index 0000000000..b2d4dc83d9 --- /dev/null +++ b/twit/twit-tests.ts @@ -0,0 +1,9 @@ +/// + +import * as Twit from 'twit'; + +const t = new Twit( { + consumer_key: '', + consumer_secret: '', + app_only_auth: true, +} ); diff --git a/twit/twit.d.ts b/twit/twit.d.ts new file mode 100644 index 0000000000..612d4b3071 --- /dev/null +++ b/twit/twit.d.ts @@ -0,0 +1,306 @@ +// Type definitions for twit 2.2 +// Project: https://github.com/ttezel/twit +// Definitions by: Volox +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module 'twit' { + import { IncomingMessage } from 'http'; + + namespace Twit { + export type StreamEndpoint = 'statuses/filter' | 'statuses/sample' | 'statuses/firehose' | 'user' | 'site'; + + export namespace Twitter { + export type ResultType = 'mixed' | 'popular' | 'recent'; + + /** + * @see https://dev.twitter.com/overview/api/tweets#obj-contributors + */ + export interface Contributors { + id: number, + id_str: number, + screen_name: string, + } + + /** + * @see https://dev.twitter.com/overview/api/entities + */ + export interface HashtagEntity { + indices: number[], + text: string, + } + export interface Size { + h: number, + w: number, + resize: 'crop' | 'fit', + } + export interface Sizes { + thumb: Size, + large: Size, + medium: Size, + small: Size, + } + export interface MediaEntity { + id: number, + id_str: string, + indices: number[], + url: string, + display_url: string, + expanded_url: string, + media_url: string, + media_url_https: string, + sizes: Sizes, + source_status_id: number, + source_status_id_str: string, + type: string, + } + export interface UrlEntity { + url: string, + display_url: string, + expanded_url: string, + indices: number[], + } + export interface UserMentionEntity { + id: number, + id_str: string, + indices: number[], + name: string, + screen_name: string, + } + export interface Entities { + hashtags: HashtagEntity[], + media: MediaEntity[], + urls: UrlEntity[], + user_mentions: UserMentionEntity[], + } + + /** + * @see https://dev.twitter.com/overview/api/users + */ + export interface User { + contributors_enabled: boolean, + created_at: string, + default_profile: string, + default_profile_image: string, + description: string, + entities: Entities, + favourites_count: number, + follow_request_sent?: boolean, + following?: boolean, + followers_count: number, + friends_count: number, + geo_enabled?: boolean, + id: number, + id_str: string, + is_translator?: boolean, + lang: string, + listed_count: number, + location: string, + name: string, + notifications?: boolean, + profile_background_color: string, + profile_background_image_url: string, + profile_background_image_url_https: string, + profile_background_tile: boolean, + profile_banner_url: string, + profile_image_url: string, + profile_image_url_https: string, + profile_link_color: string, + profile_sidebar_border_color: string, + profile_sidebar_fill_color: string, + profile_text_color: string, + profile_use_background_image: boolean, + protected: boolean, + screen_name: string, + show_all_inline_media: boolean, + status?: Status, + statuses_count: number, + time_zone?: string, + url: string, + utc_offset?: number, + verified: boolean, + withheld_in_countries: string, + withheld_scope: string, + } + + /** + * @see https://dev.twitter.com/overview/api/places + */ + export interface PlaceAttribute { + street_address: string, + locality: string, + region: string, + iso3: string, + postal_code: string, + phone: string, + twitter: string, + url: string, + 'app:id': string, + } + export interface Place { + geometry: GeoJSON.Point, + attributes: PlaceAttribute, + bounding_box: GeoJSON.Polygon, + contained_within: Place[], + country: string, + country_code: string, + full_name: string, + id: string, + name: string, + place_type: string, + url: string, + } + + /** + * @see https://dev.twitter.com/overview/api/tweets + */ + export interface Status { + id: number, + id_str: string, + annotations?: Object, + contributors?: Contributors[], + coordinates?: GeoJSON.Point, + created_at: string, + current_user_retweet?: { + id: number, + id_str: number, + }, + entities: Entities, + favorite_count?: number, + favorited?: boolean, + filter_level: 'none' | 'low' | 'medium', + geo?: Object, + in_reply_to_screen_name?: string, + in_reply_to_status_id?: number, + in_reply_to_status_id_str?: string, + in_reply_to_user_id?: number, + in_reply_to_user_id_str?: string, + lang?: string, + place?: Place, + possibly_sensitive?: boolean, + quoted_status_id?: number, + quoted_status_id_str?: string, + quoted_status?: Status, + scopes?: Object, + retweet_count: number, + retweeted: boolean, + retweeted_status?: Status, + source?: string, + text: string, + truncated: boolean, + user: User, + withheld_copyright?: boolean, + withheld_in_countries?: string[], + withheld_scope?: string, + } + export interface Metadata { + max_id?: number, + since_id?: number, + refresh_url?: string, + next_results?: string, + count?: number, + completed_in?: number, + since_id_str?: string, + query?: string, + max_id_str?: string + } + } + + export interface Response { + statuses: Twitter.Status[], + search_metadata: Twitter.Metadata, + } + interface MediaParam { + file_path: string + } + interface Params { + // search/tweets + q?: string, + geocode?: string, + lang?: string, + locale?: string, + result_type?: Twitter.ResultType, + count?: number, + results_per_page?: number, + until?: string, + since_id?: string, + max_id?: string, + include_entities?: boolean, + + // Other params from various endpoints + media_id?: string, + media_ids?: string[], + alt_text?: { + text?: string + }, + media_data?: Buffer | string, + screen_name?: string, + id?: string, + slug?: string, + status?: string, + } + export interface PromiseResponse { + data: Response, + responde: IncomingMessage, + } + export interface Callback { + (err: Error, result: Response, response: IncomingMessage): void + } + export interface ConfigKeys { + consumer_key: string, + consumer_secret: string, + access_token?: string, + access_token_secret?: string, + } + export interface Options extends ConfigKeys { + app_only_auth?: boolean, + timeout_ms?: number, + trusted_cert_fingerprints?: string[], + } + } + + class Twit { + /** + * @see https://github.com/ttezel/twit#var-t--new-twitconfig + */ + constructor(config: Twit.Options); + + /** + * @see https://github.com/ttezel/twit#tgetpath-params-callback + */ + get(path: string, callback: Twit.Callback): void; + get(path: string, params: Twit.Params, callback: Twit.Callback): void; + get(path: string, params?: Twit.Params): Promise; + + /** + * @see https://github.com/ttezel/twit#tpostpath-params-callback + */ + post(path: string, callback: Twit.Callback): void; + post(path: string, params: Twit.Params, callback: Twit.Callback): void; + post(path: string, params?: Twit.Params): Promise; + + /** + * @see https://github.com/ttezel/twit#tpostmediachunkedparams-callback + */ + postMediaChunked(media: Twit.MediaParam, callback: Twit.Callback): void; + + /** + * @see https://github.com/ttezel/twit#tgetauth + */ + getAuth(): Twit.Options + + /** + * @see https://github.com/ttezel/twit#tsetauthtokens + */ + setAuth(tokens: Twit.ConfigKeys): void + + /** + * @see https://github.com/ttezel/twit#tstreampath-params + */ + stream(path: Twit.StreamEndpoint, params?: Twit.Params): NodeJS.ReadableStream; + } + + export = Twit; +} diff --git a/typescript-stl/typescript-stl-tests.ts b/typescript-stl/typescript-stl-tests.ts index cc684cde7e..d83a9ffc5a 100644 --- a/typescript-stl/typescript-stl-tests.ts +++ b/typescript-stl/typescript-stl-tests.ts @@ -1,4 +1,4 @@ /// import std = require("typescript-stl"); -std.example.test_all(); \ No newline at end of file +console.log(std); \ No newline at end of file diff --git a/typescript-stl/typescript-stl.d.ts b/typescript-stl/typescript-stl.d.ts index 9baa19ec30..36ad79e4a1 100644 --- a/typescript-stl/typescript-stl.d.ts +++ b/typescript-stl/typescript-stl.d.ts @@ -1,5 +1,5 @@ -// Type definitions for TypeScript-STL v1.0.0-rc.2 -// Project: https://github.com/samchon/stl +// Type definitions for TypeScript-STL v1.0.8 +// Project: https://github.com/samchon/typescript-stl // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -13,16 +13,102 @@ declare module "typescript-stl" *

      *

      * - *

      GitHub Repository: https://github.com/samchon/stl

      - * *

      STL (Standard Template Library) Containers and Algorithms for TypeScript.

      * *

      TypeScript-STL is a TypeScript's Standard Template Library who is migrated from C++ STL. Most of classes * and functions of STL have implemented. Just enjoy it.

      * + * @git https://github.com/samchon/typescript-stl * @author Jeongho Nam */ declare namespace std { + /** + * Type definition of {@link Vector} and it's the original name used in C++. + */ + export import vector = Vector; + /** + * Type definition of {@link List} and it's the original name used in C++. + */ + export import list = List; + /** + * Type definition of {@link Deque} and it's the original name used in C++. + */ + export import deque = Deque; + /** + * Type definition of {@link Stack} and it's the original name used in C++. + */ + type stack = Stack; + /** + * Type definition of {@link Queue} and it's the original name used in C++. + */ + type queue = Queue; + /** + * Type definition of {@link PriorityQueue} and it's the original name used in C++. + */ + type priority_queue = PriorityQueue; + var stack: typeof Stack; + var queue: typeof Queue; + var priority_queue: typeof PriorityQueue; + /** + * Type definition of {@link TreeSet} and it's the original name used in C++. + */ + export import set = TreeSet; + /** + * Type definition of {@link TreeMultiSet} and it's the original name used in C++. + */ + export import multiset = TreeMultiSet; + /** + * Type definition of {@link HashSet} and it's the original name used in C++. + */ + export import unordered_set = HashSet; + /** + * Type definition of {@link HashMultiSet} and it's the original name used in C++. + */ + export import unordered_multiset = HashMultiSet; + /** + * Type definition of {@link TreeMap} and it's the original name used in C++. + */ + export import map = TreeMap; + /** + * Type definition of {@link TreeMultiMap} and it's the original name used in C++. + */ + export import multimap = TreeMultiMap; + /** + * Type definition of {@link HashMap} and it's the original name used in C++. + */ + export import unordered_map = HashMap; + /** + * Type definition of {@link HashMultiMap} and it's the original name used in C++. + */ + export import unordered_multimap = HashMultiMap; + type exception = Exception; + type logic_error = LogicError; + type domain_error = DomainError; + type invalid_argument = InvalidArgument; + type length_error = LengthError; + type out_of_range = OutOfRange; + type runtime_error = RuntimeError; + type overflow_error = OverflowError; + type underflow_error = UnderflowError; + type range_error = RangeError; + type system_error = SystemError; + type error_category = ErrorCategory; + type error_condition = ErrorCondition; + type error_code = ErrorCode; + var exception: typeof Exception; + var logic_error: typeof LogicError; + var domain_error: typeof DomainError; + var invalid_argument: typeof InvalidArgument; + var length_error: typeof LengthError; + var out_of_range: typeof OutOfRange; + var runtime_error: typeof RuntimeError; + var overflow_error: typeof OverflowError; + var underflow_error: typeof UnderflowError; + var range_error: typeof RangeError; + var system_error: typeof SystemError; + var error_category: typeof ErrorCategory; + var error_condition: typeof ErrorCondition; + var error_code: typeof ErrorCode; } /** * Base classes composing STL in background. @@ -31,13 +117,6 @@ declare namespace std { */ declare namespace std.base { } -/** - * Examples for supporting developers who use STL library. - * - * @author Jeongho Nam - */ -declare namespace std.example { -} declare namespace std { /** *

      Apply function to range.

      @@ -2665,9 +2744,9 @@ declare namespace std.base { /** *

      An abstract container.

      * - *

      - * - *

      + *

      + * + *

      * *

      Container properties

      *
      @@ -2786,8 +2865,8 @@ declare namespace std { *

      There is not a single type of {@link Iterator bidirectional iterator}: {@link IContainer Each container} * may define its own specific iterator type able to iterate through it and access its elements.

      * - *

      - * + *

      + * *

      * * @reference http://www.cplusplus.com/reference/iterator/BidirectionalIterator @@ -2872,18 +2951,45 @@ declare namespace std { * first element in a range is reversed, the reversed iterator points to the element before the first element (this * would be the past-the-end element of the reversed range).

      * - *

      - * + *

      + * *

      * * @reference http://www.cplusplus.com/reference/iterator/reverse_iterator * @author Jeongho Nam */ abstract class ReverseIterator, This extends ReverseIterator> extends Iterator { + /** + * @hidden + */ protected base_: Base; + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: Base); + /** + *

      Return base iterator.

      + * + *

      Return a reference of the base iteraotr.

      + * + *

      The base iterator is an iterator of the same type as the one used to construct the {@link ReverseIterator}, + * but pointing to the element next to the one the {@link ReverseIterator} is currently pointing to + * (a {@link ReverseIterator} has always an offset of -1 with respect to its base iterator). + * + * @return A reference of the base iterator, which iterates in the opposite direction. + */ base(): Base; - protected abstract create_neighbor(): This; + /** + * @hidden + */ + protected abstract create_neighbor(base: Base): This; + /** + *

      Get value of the iterator is pointing.

      + * + * @return A value of the reverse iterator. + */ value: T; /** * @inheritdoc @@ -3074,6 +3180,10 @@ declare namespace std { */ function end(container: base.MapContainer): MapIterator; } +declare namespace std.Deque { + type iterator = std.DequeIterator; + type reverse_iterator = std.DequeReverseIterator; +} declare namespace std { /** *

      Double ended queue.

      @@ -3104,8 +3214,8 @@ declare namespace std { * the end, {@link Deque Deques} perform worse and have less consistent iterators and references than * {@link List Lists}.

      * - *

      - * + *

      + * *

      * *

      Container properties

      @@ -3127,70 +3237,27 @@ declare namespace std { */ class Deque extends base.Container implements base.IArrayContainer, base.IDequeContainer { /** - * Type definition of {@link Deque}'s {@link DequeIterator iterator}. - */ - static iterator: typeof DequeIterator; - /** - *

      Row size of the {@link matrix_ matrix} which contains elements.

      - * - *

      Note that the {@link ROW} affects on time complexity of accessing and inserting element. - * Accessing element is {@link ROW} times slower than ordinary {@link Vector} and inserting element - * in middle position is {@link ROW} times faster than ordinary {@link Vector}.

      - * - *

      When the {@link ROW} returns 8, time complexity of accessing element is O(8) and inserting - * element in middle position is O(N/8). ({@link Vector}'s time complexity of accessement is O(1) - * and inserting element is O(N)).

      + * @hidden */ private static ROW; /** - *

      Minimum {@link capacity}.

      - * - *

      Although a {@link Deque} has few elements, even no element is belonged to, the {@link Deque} - * keeps the minimum {@link capacity} at least.

      + * @hidden */ private static MIN_CAPACITY; /** - *

      A matrix containing elements.

      - * - *

      This {@link matrix_} is the biggest difference one between {@link Vector} and {@link Deque}. - * Its number of rows follows {@link ROW} and number of columns follows {@link get_col_size} which - * returns divide of {@link capacity} and {@link ROW}.

      - * - * By separating segment of elements (segment: row, elements in a segment: col), {@link Deque} takes - * advantage of time complexity on inserting element in middle position. {@link Deque} is {@link ROW} - * times faster than {@link Vector} when inserting elements in middle position.

      - * - *

      However, separating segment of elements from matrix, {@link Deque} also takes disadvantage of - * time complexity on accessing element. {@link Deque} is {@link ROW} times slower than {@link Vector} - * when accessing element.

      + * @hidden */ private matrix_; /** - * Number of elements in the {@link Deque}. + * @hidden */ private size_; /** - *

      Size of allocated storage capacity.

      - * - *

      The {@link capacity_ capacity} is size of the storage space currently allocated for the - * {@link Deque container}, expressed in terms of elements.

      - * - *

      This {@link capacity_ capacity} is not necessarily equal to the {@link Deque container} - * {@link size}. It can be equal or greater, with the extra space allowing to accommodate for growth - * without the need to reallocate on each insertion.

      - * - *

      Notice that this {@link capacity_ capacity} does not suppose a limit on the {@link size} of - * the {@link Deque container}. When this {@link capacity} is exhausted and more is needed, it is - * automatically expanded by the {@link Deque container} (reallocating it storage space). - * The theoretical limit on the {@link size} of a {@link Deque container} is given by member - * {@link max_size}.

      - * - *

      The {@link capacity_ capacity} of a {@link Deque container} can be explicitly altered by - * calling member {@link Deque.reserve}.

      + * @hidden */ private capacity_; /** - * Get column size; {@link capacity_ capacity} / {@link ROW row}. + * @hidden */ private get_col_size(); /** @@ -3225,7 +3292,7 @@ declare namespace std { * @param container Another container object of the same type (with the same class template * arguments T), whose contents are either copied or acquired. */ - constructor(container: base.IContainer); + constructor(container: Deque); /** *

      Range Constructor.

      * @@ -3272,6 +3339,10 @@ declare namespace std { * @inheritdoc */ size(): number; + /** + * @inheritdoc + */ + empty(): boolean; /** * @inheritdoc */ @@ -3293,11 +3364,9 @@ declare namespace std { */ back(): T; /** - *

      Fetch row and column's index.

      - * - *

      Fetches index of row and column of {@link matrix_} from sequence number.

      - * - * @param index Sequence number + // Fetch row and column's index. + /** + * @hidden */ private fetch_index(index); /** @@ -3351,11 +3420,11 @@ declare namespace std { /** * @hidden */ - protected insert_by_repeating_val(position: DequeIterator, n: number, val: T): DequeIterator; + protected _Insert_by_repeating_val(position: DequeIterator, n: number, val: T): DequeIterator; /** * @hidden */ - protected insert_by_range>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; + protected _Insert_by_range>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; /** * @hidden */ @@ -3379,23 +3448,37 @@ declare namespace std { /** * @hidden */ - protected erase_by_range(first: DequeIterator, last: DequeIterator): DequeIterator; + protected _Erase_by_range(first: DequeIterator, last: DequeIterator): DequeIterator; + /** + *

      Swap content.

      + * + *

      Exchanges the content of the container by the content of obj, which is another + * {@link Deque container} object with same type of elements. Sizes and container type may differ.

      + * + *

      After the call to this member function, the elements in this container are those which were in obj + * before the call, and the elements of obj are those which were in this. All iterators, references and + * pointers remain valid for the swapped objects.

      + * + *

      Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

      + * + * @param obj Another {@link Deque container} of the same type of elements (i.e., instantiated + * with the same template parameter, T) whose content is swapped with that of this + * {@link container Deque}. + */ + swap(obj: Deque): void; /** * @inheritdoc */ swap(obj: base.IContainer): void; - /** - * @hidden - */ - private swap_deque(obj); } } declare namespace std { /** *

      An iterator of {@link Deque}.

      * - *

      - * + *

      + * *

      * * @author Jeongho Nam @@ -3423,6 +3506,11 @@ declare namespace std { /** * @inheritdoc */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ value: T; /** * @inheritdoc @@ -3466,8 +3554,8 @@ declare namespace std { /** *

      A reverse-iterator of Deque.

      * - *

      - * + *

      + * *

      * * @param Type of the elements. @@ -3475,13 +3563,23 @@ declare namespace std { * @author Jeongho Nam */ class DequeReverseIterator extends ReverseIterator, DequeReverseIterator> implements base.IArrayIterator { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: DequeIterator); + /** + * @hidden + */ + protected create_neighbor(base: DequeIterator): DequeReverseIterator; /** * @inheritdoc */ - protected create_neighbor(): DequeReverseIterator; /** - * Set value. + * Set value of the iterator is pointing to. + * + * @param val Value to set. */ value: T; /** @@ -3543,8 +3641,8 @@ declare namespace std { *

      All objects thrown by components of the standard library are derived from this class. * Therefore, all standard exceptions can be caught by catching this type by reference.

      * - *

      - *

      + *

      + *

      * * @reference http://www.cplusplus.com/reference/exception/exception * @author Jeongho Nam @@ -3592,8 +3690,8 @@ declare namespace std { * *

      It is used as a base class for several logical error exceptions.

      * - *

      - *

      + *

      + *

      * * @reference http://www.cplusplus.com/reference/stdexcept/logic_error * @author Jeongho Nam @@ -3618,8 +3716,8 @@ declare namespace std { *

      No component of the standard library throws exceptions of this type. It is designed as a standard * exception to be thrown by programs.

      * - *

      < - * img src="http://samchon.github.io/stl/api/assets/images/design/exceptions.png" style="max-width: 100%" />

      + *

      + *

      * * @reference http://www.cplusplus.com/reference/stdexcept/domain_error * @author Jeongho Nam @@ -3640,8 +3738,8 @@ declare namespace std { *

      It is a standard exception that can be thrown by programs. Some components of the standard library * also throw exceptions of this type to signal invalid arguments.

      * - *

      - *

      + *

      + *

      * * @reference http://www.cplusplus.com/reference/stdexcept/invalid_argument * @author Jeongho Nam @@ -3662,8 +3760,8 @@ declare namespace std { *

      It is a standard exception that can be thrown by programs. Some components of the standard library, * such as vector and string also throw exceptions of this type to signal errors resizing.

      * - *

      - *

      + *

      + *

      * * @reference http://www.cplusplus.com/reference/stdexcept/length_error * @author Jeongho Nam @@ -3685,8 +3783,8 @@ declare namespace std { * such as vector, deque, string and bitset also throw exceptions of this type to signal arguments * out of range.

      * - *

      - *

      + *

      + *

      * * @reference http://www.cplusplus.com/reference/stdexcept/out_of_range * @author Jeongho Nam @@ -3707,8 +3805,8 @@ declare namespace std { * *

      It is used as a base class for several runtime error exceptions.

      * - *

      - *

      + *

      + *

      * * @reference http://www.cplusplus.com/reference/stdexcept/runtime_error * @author Jeongho Nam @@ -3729,10 +3827,10 @@ declare namespace std { *

      It is a standard exception that can be thrown by programs. Some components of the standard library * also throw exceptions of this type to signal range errors.

      * - *

      - *

      + *

      + *

      * - * @reference http://www.cplusplus.com/reference/stdexcept/outflow_error + * @reference http://www.cplusplus.com/reference/stdexcept/overflow_error * @author Jeongho Nam */ class OverflowError extends RuntimeError { @@ -3751,8 +3849,8 @@ declare namespace std { *

      No component of the standard library throws exceptions of this type. It is designed as a standard * exception to be thrown by programs.

      * - *

      - *

      + *

      + *

      * * @reference http://www.cplusplus.com/reference/stdexcept/underflow_error * @author Jeongho Nam @@ -3774,8 +3872,8 @@ declare namespace std { *

      It is a standard exception that can be thrown by programs. Some components of the standard library * also throw exceptions of this type to signal range errors.

      * - *

      - *

      + *

      + *

      * * @reference http://www.cplusplus.com/reference/stdexcept/range_error * @author Jeongho Nam @@ -4336,8 +4434,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

      * - *

      - *

      + *

      + *

      * *

      Container properties

      *
      @@ -4359,11 +4457,7 @@ declare namespace std.base { * * @author Jeongho Nam */ - abstract class MapContainer extends base.Container> { - /** - * Type definition of {@link MapContainer}'s {@link MapIterator iterator}. - */ - static iterator: typeof MapIterator; + abstract class MapContainer extends Container> { /** *

      {@link List} storing elements.

      * @@ -4372,45 +4466,11 @@ declare namespace std.base { * by storing {@link ListIterator iterators} ({@link MapIterator} references {@link ListIterator}) who are * created from {@link data_ here}.

      */ - protected data_: List>; + private data_; /** * Default Constructor. */ constructor(); - /** - * Construct from elements. - */ - constructor(items: Array>); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - */ - constructor(array: Array<[Key, T]>); - /** - * Copy Constructor. - */ - constructor(container: IContainer>); - /** - * Construct from range iterators. - */ - constructor(begin: Iterator>, end: Iterator>); - /** - * @hidden - */ - protected init(): void; - /** - * @hidden - */ - protected construct_from_array(items: Array | [Key, T]>): void; - /** - * @hidden - */ - protected construct_from_container(container: IContainer>): void; - /** - * @hidden - */ - protected construct_from_range>>(begin: InputIterator, end: InputIterator): void; /** * @inheritdoc */ @@ -4520,6 +4580,7 @@ declare namespace std.base { * Return the number of elements in the map. */ size(): number; + protected _Get_data(): List>; /** * @inheritdoc */ @@ -4595,7 +4656,7 @@ declare namespace std.base { /** * @hidden */ - protected abstract insert_by_pair(pair: Pair): any; + protected abstract _Insert_by_pair(pair: Pair): any; /** * @hidden */ @@ -4603,7 +4664,7 @@ declare namespace std.base { /** * @hidden */ - protected abstract insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + protected abstract _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ @@ -4611,7 +4672,7 @@ declare namespace std.base { /** * @hidden */ - protected abstract insert_by_range>>(first: InputIterator, last: InputIterator): void; + protected abstract _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** *

      Erase an elemet by key.

      * @@ -4710,7 +4771,7 @@ declare namespace std.base { * [first, last), which contains all the elements between first and last, * including the element pointed by first but not the element pointed by last. */ - protected abstract handle_insert(first: MapIterator, last: MapIterator): void; + protected abstract _Handle_insert(first: MapIterator, last: MapIterator): void; /** *

      Abstract method handling deletions for indexing.

      * @@ -4731,15 +4792,19 @@ declare namespace std.base { * [first, last), which contains all the elements between first and last, * including the element pointed by first but not the element pointed by last. */ - protected abstract handle_erase(first: MapIterator, last: MapIterator): void; + protected abstract _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + * @hidden + */ + protected _Swap(obj: MapContainer): void; } } declare namespace std { /** *

      An iterator of {@link MapContainer map container}.

      * - *

      - *

      + *

      + *

      * * @author Jeongho Nam */ @@ -4809,14 +4874,22 @@ declare namespace std { /** *

      A reverse-iterator of {@link MapContainer map container}.

      * - *

      - *

      + *

      + *

      * * @author Jeongho Nam */ class MapReverseIterator extends ReverseIterator, MapIterator, MapReverseIterator> { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: MapIterator); - protected create_neighbor(): MapReverseIterator; + /** + * @hidden + */ + protected create_neighbor(base: MapIterator): MapReverseIterator; /** * Get first, key element. */ @@ -4849,8 +4922,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

      * - *

      - *

      + *

      + *

      * *

      Container properties

      *
      @@ -4902,6 +4975,50 @@ declare namespace std.base { * @param val Value, the item. */ set(key: Key, val: T): void; + /** + *

      Extract an element.

      + * + *

      Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

      + * + * @param key Key value of the element whose mapped value is accessed. + * + * @return A {@link Pair} containing the value pointed to by key. + */ + extract(key: Key): Pair; + /** + *

      Extract an element.

      + * + *

      Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

      + * + * @param it An iterator pointing an element to extract. + * + * @return An iterator pointing to the element immediately following it prior to the element being + * erased. If no such element exists,returns {@link end end()}. + */ + extract(it: MapIterator): MapIterator; + /** + *

      Extract an element.

      + * + *

      Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

      + * + * @param it An iterator pointing an element to extract. + * + * @return An iterator pointing to the element immediately following it prior to the element being + * erased. If no such element exists,returns {@link end end()}. + */ + extract(it: MapReverseIterator): MapReverseIterator; + /** + * @hidden + */ + private extract_by_key(key); + /** + * @hidden + */ + private extract_by_iterator(it); + /** + * @hidden + */ + private extract_by_reverse_iterator(it); /** *

      Insert an element.

      * @@ -4965,23 +5082,74 @@ declare namespace std.base { */ insert>>(first: InputIterator, last: InputIterator): void; /** - *

      Swap content.

      + *

      Insert or assign an element.

      * - *

      Exchanges the content of the container by the content of obj, which is another - * {@link UniqueMap map} of the same type. Sizes abd container type may differ.

      + *

      Inserts an element or assigns to the current element if the key already exists.

      * - *

      After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

      + *

      Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of an element already in the container, and + * if so, the element is assigned, returning an iterator to this existing element (if the function returns a + * value).

      * - *

      Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

      + *

      For a similar container allowing for duplicate elements, see {@link MultiMap}.

      * - * @param obj Another {@link UniqueMap map container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link UniqueMap container}. + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly + * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The + * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or + * false if an equivalent key already existed so the value is assigned. */ - swap(obj: UniqueMap): void; + insert_or_assign(key: Key, value: T): Pair, boolean>; + /** + *

      Insert or assign an element.

      + * + *

      Inserts an element or assigns to the current element if the key already exists.

      + * + *

      Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of an element already in the container, and + * if so, the element is assigned, returning an iterator to this existing element (if the function returns a + * value).

      + * + *

      For a similar container allowing for duplicate elements, see {@link MultiMap}.

      + * + * @param hint Hint for the position where the element can be inserted. + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link UniqueMap}. + */ + insert_or_assign(hint: MapIterator, key: Key, value: T): MapIterator; + /** + *

      Insert or assign an element.

      + * + *

      Inserts an element or assigns to the current element if the key already exists.

      + * + *

      Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of an element already in the container, and + * if so, the element is assigned, returning an iterator to this existing element (if the function returns a + * value).

      + * + *

      For a similar container allowing for duplicate elements, see {@link MultiMap}.

      + * + * @param hint Hint for the position where the element can be inserted. + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link UniqueMap}. + */ + insert_or_assign(hint: MapReverseIterator, key: Key, value: T): MapReverseIterator; + /** + * @hidden + */ + private insert_or_assign_with_key_value(key, value); + /** + * @hidden + */ + private insert_or_assign_with_hint(hint, key, value); } } declare namespace std.base { @@ -5003,8 +5171,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

      * - *

      - *

      + *

      + *

      * *

      Container properties

      *
      @@ -5072,26 +5240,12 @@ declare namespace std.base { * @inheritdoc */ insert>>(first: InputIterator, last: InputIterator): void; - /** - *

      Swap content.

      - * - *

      Exchanges the content of the container by the content of obj, which is another - * {@link UniqueMap map} of the same type. Sizes abd container type may differ.

      - * - *

      After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

      - * - *

      Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

      - * - * @param obj Another {@link MultiMap map container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link MultiMap container}. - */ - swap(obj: MultiMap): void; } } +declare namespace std.HashMap { + type iterator = std.MapIterator; + type reverse_iterator = std.MapReverseIterator; +} declare namespace std { /** *

      Hashed, unordered map.

      @@ -5112,8 +5266,9 @@ declare namespace std { *

      {@link HashMap} containers are faster than {@link TreeMap} containers to access individual elements by their * key, although they are generally less efficient for range iteration through a subset of their elements.

      * - *

      - *

      + *

      + * + *

      * *

      Container properties

      *
      @@ -5142,15 +5297,32 @@ declare namespace std { * @author Jeongho Nam */ class HashMap extends base.UniqueMap implements base.IHashMap { + /** + * @hidden + */ private hash_buckets_; /** - * @hidden + * Default Constructor. */ - protected init(): void; + constructor(); /** - * @hidden + * Construct from elements. */ - protected construct_from_array(items: Array>): void; + constructor(items: Pair[]); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: [Key, T][]); + /** + * Copy Constructor. + */ + constructor(container: HashMap); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator>, end: Iterator>); /** * @inheritdoc */ @@ -5222,46 +5394,64 @@ declare namespace std { /** * @hidden */ - protected insert_by_pair(pair: Pair): any; + protected _Insert_by_pair(pair: Pair): any; /** * @hidden */ - protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ - protected insert_by_range>>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: MapIterator, last: MapIterator): void; + protected _Handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: MapIterator, last: MapIterator): void; + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + *

      Swap content.

      + * + *

      Exchanges the content of the container by the content of obj, which is another + * {@link HashMap map} of the same type. Sizes abd container type may differ.

      + * + *

      After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

      + * + *

      Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

      + * + * @param obj Another {@link HashMap map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashMap container}. + */ + swap(obj: HashMap): void; /** * @inheritdoc */ - swap(obj: base.UniqueMap): void; - /** - * @hidden - */ - private swap_hash_map(obj); + swap(obj: base.IContainer>): void; } } +declare namespace std.HashMultiMap { + type iterator = std.MapIterator; + type reverse_iterator = std.MapReverseIterator; +} declare namespace std { /** *

      Hashed, unordered Multimap.

      * - *

      {@link HashMap}s are associative containers that store elements formed by the combination of - * a key value and a mapped value, much like {@link HashMap} containers, but allowing + *

      {@link HashMultiMap}s are associative containers that store elements formed by the combination of + * a key value and a mapped value, much like {@link HashMultiMap} containers, but allowing * different elements to have equivalent keys.

      * - *

      In an {@link HashMap}, the key value is generally used to uniquely identify the + *

      In an {@link HashMultiMap}, the key value is generally used to uniquely identify the * element, while the mapped value is an object with the content associated to this key. * Types of key and mapped value may differ.

      * - *

      Internally, the elements in the {@link HashMap} are not sorted in any particular order with + *

      Internally, the elements in the {@link HashMultiMap} are not sorted in any particular order with * respect to either their key or mapped values, but organized into buckets depending on * their hash values to allow for fast access to individual elements directly by their key values * (with a constant average time complexity on average).

      @@ -5269,8 +5459,9 @@ declare namespace std { *

      Elements with equivalent keys are grouped together in the same bucket and in such a way that * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

      * - *

      - *

      + *

      + * + *

      * *

      Container properties

      *
      @@ -5291,26 +5482,40 @@ declare namespace std { *
      * * @param Type of the key values. - * Each element in an {@link HashMap} is identified by a key value. + * Each element in an {@link HashMultiMap} is identified by a key value. * @param Type of the mapped value. - * Each element in an {@link HashMap} is used to store some data as its mapped value. + * Each element in an {@link HashMultiMap} is used to store some data as its mapped value. * * @reference http://www.cplusplus.com/reference/unordered_map/unordered_multimap * @author Jeongho Nam */ class HashMultiMap extends base.MultiMap { /** - * + * @hidden */ private hash_buckets_; /** - * @hidden + * Default Constructor. */ - protected init(): void; + constructor(); /** - * @hidden + * Construct from elements. */ - protected construct_from_array(items: Array>): void; + constructor(items: Pair[]); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: [Key, T][]); + /** + * Copy Constructor. + */ + constructor(container: HashMultiMap); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator>, end: Iterator>); /** * @inheritdoc */ @@ -5386,31 +5591,45 @@ declare namespace std { /** * @hidden */ - protected insert_by_pair(pair: Pair): any; + protected _Insert_by_pair(pair: Pair): any; /** * @hidden */ - protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ - protected insert_by_range>>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: MapIterator, last: MapIterator): void; + protected _Handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: MapIterator, last: MapIterator): void; + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + *

      Swap content.

      + * + *

      Exchanges the content of the container by the content of obj, which is another + * {@link HashMultiMap map} of the same type. Sizes abd container type may differ.

      + * + *

      After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

      + * + *

      Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

      + * + * @param obj Another {@link HashMultiMap map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashMultiMap container}. + */ + swap(obj: HashMultiMap): void; /** * @inheritdoc */ - swap(obj: base.MultiMap): void; - /** - * @hidden - */ - private swap_hash_multimap(obj); + swap(obj: base.IContainer>): void; } } declare namespace std.base { @@ -5428,8 +5647,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

      * - *

      - *

      + *

      + *

      * *

      Container properties

      *
      @@ -5449,10 +5668,6 @@ declare namespace std.base { * @author Jeongho Nam */ abstract class SetContainer extends Container { - /** - * Type definition of {@link SetContainer}'s {@link SetIterator iterator}. - */ - static iterator: typeof SetIterator; /** *

      {@link List} storing elements.

      * @@ -5461,39 +5676,11 @@ declare namespace std.base { * by storing {@link ListIterator iterators} ({@link SetIterator} references {@link ListIterator}) who are * created from {@link data_ here}.

      */ - protected data_: List; + private data_; /** * Default Constructor. */ constructor(); - /** - * Construct from elements. - */ - constructor(items: Array); - /** - * Copy Constructor. - */ - constructor(container: IContainer); - /** - * Construct from range iterators. - */ - constructor(begin: Iterator, end: Iterator); - /** - * @hidden - */ - protected init(): void; - /** - * @hidden - */ - protected construct_from_array(items: Array): void; - /** - * @hidden - */ - protected construct_from_container(container: IContainer): void; - /** - * @hidden - */ - protected construct_from_range>(begin: InputIterator, end: InputIterator): void; /** * @inheritdoc */ @@ -5557,6 +5744,10 @@ declare namespace std.base { * @inheritdoc */ size(): number; + /** + * @hidden + */ + _Get_data(): List; /** * @inheritdoc */ @@ -5600,15 +5791,15 @@ declare namespace std.base { /** * @hidden */ - protected abstract insert_by_val(val: T): any; + protected abstract _Insert_by_val(val: T): any; /** * @hidden */ - protected abstract insert_by_hint(hint: SetIterator, val: T): SetIterator; + protected abstract _Insert_by_hint(hint: SetIterator, val: T): SetIterator; /** * @hidden */ - protected abstract insert_by_range>(begin: InputIterator, end: InputIterator): void; + protected abstract _Insert_by_range>(begin: InputIterator, end: InputIterator): void; /** *

      Erase an element.

      *

      Removes from the set container the elements whose value is key.

      @@ -5681,7 +5872,7 @@ declare namespace std.base { * [first, last), which contains all the elements between first and last, * including the element pointed by first but not the element pointed by last. */ - protected abstract handle_insert(first: SetIterator, last: SetIterator): void; + protected abstract _Handle_insert(first: SetIterator, last: SetIterator): void; /** *

      Abstract method handling deletions for indexing.

      * @@ -5702,15 +5893,19 @@ declare namespace std.base { * [first, last), which contains all the elements between first and last, * including the element pointed by first but not the element pointed by last. */ - protected abstract handle_erase(first: SetIterator, last: SetIterator): void; + protected abstract _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + * @hidden + */ + protected _Swap(obj: SetContainer): void; } } declare namespace std { /** *

      An iterator of a Set.

      * - *

      - *

      + *

      + *

      * * @author Jeongho Nam */ @@ -5768,100 +5963,24 @@ declare namespace std { /** *

      A reverse-iterator of Set.

      * - *

      - *

      + *

      + *

      * * @param Type of the elements. * * @author Jeongho Nam */ class SetReverseIterator extends ReverseIterator, SetReverseIterator> { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: SetIterator); /** - * @inheritdoc + * @hidden */ - protected create_neighbor(): SetReverseIterator; - } -} -declare namespace std.base { - /** - *

      An abstract set.

      - * - *

      {@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of - * individual elements based on their value.

      - * - *

      In an {@link SetContainer}, the value of an element is at the same time its key, used to uniquely - * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be modified - * once in the container - they can be inserted and removed, though.

      - * - *

      {@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

      - * - *

      - *

      - * - *

      Container properties

      - *
      - *
      Associative
      - *
      - * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
      - * - *
      Set
      - *
      The value of an element is also the key used to identify it.
      - * - *
      Unique keys
      - *
      No two elements in the container can have equivalent keys.
      - *
      - * - * @param Type of the elements. Each element in a {@link SetContainer} container is also identified - * by this value (each value is itself also the element's key). - * - * @author Jeongho Nam - */ - abstract class UniqueSet extends SetContainer { - /** - * @inheritdoc - */ - count(key: T): number; - /** - *

      Insert an element.

      - * - *

      Extends the container by inserting new elements, effectively increasing the container {@link size} by - * the number of element inserted (zero or one).

      - * - *

      Because elements in a {@link UniqueSet UniqueSets} are unique, the insertion operation checks whether - * each inserted element is equivalent to an element already in the container, and if so, the element is not - * inserted, returning an iterator to this existing element (if the function returns a value).

      - * - *

      For a similar container allowing for duplicate elements, see {@link MultiSet}.

      - * - * @param key Value to be inserted as an element. - * - * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly - * inserted element or to the equivalent element already in the {@link UniqueSet}. The - * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or - * false if an equivalent element already existed. - */ - insert(val: T): Pair, boolean>; - /** - * @inheritdoc - */ - insert(hint: SetIterator, val: T): SetIterator; - /** - * @inheritdoc - */ - insert(hint: SetReverseIterator, val: T): SetReverseIterator; - /** - * @inheritdoc - */ - insert>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - swap(obj: UniqueSet): void; + protected create_neighbor(base: SetIterator): SetReverseIterator; } } declare namespace std.base { @@ -5879,8 +5998,8 @@ declare namespace std.base { * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

      * - *
      + *

      + *

      * *

      Container properties

      *
      @@ -5926,171 +6045,18 @@ declare namespace std.base { * @inheritdoc */ insert>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - swap(obj: MultiSet): void; } } -declare namespace std { - /** - *

      Hashed, unordered set.

      - * - *

      {@link HashSet}s are containers that store unique elements in no particular order, and which - * allow for fast retrieval of individual elements based on their value.

      - * - *

      In an {@link HashSet}, the value of an element is at the same time its key, that - * identifies it uniquely. Keys are immutable, therefore, the elements in an {@link HashSet} cannot be - * modified once in the container - they can be inserted and removed, though.

      - * - *

      Internally, the elements in the {@link HashSet} are not sorted in any particular order, but - * organized into buckets depending on their hash values to allow for fast access to individual elements - * directly by their values (with a constant average time complexity on average).

      - * - *

      {@link HashSet} containers are faster than {@link TreeSet} containers to access individual - * elements by their key, although they are generally less efficient for range iteration through a - * subset of their elements.

      - * - *

      - *

      - * - *

      Container properties

      - *
      - *
      Associative
      - *
      Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
      - * - *
      Hashed
      - *
      Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their key.
      - * - *
      Set
      - *
      The value of an element is also the key used to identify it.
      - * - *
      Unique keys
      - *
      No two elements in the container can have equivalent keys.
      - *
      - * - * @param Type of the elements. - * Each element in an {@link HashSet} is also uniquely identified by this value. - * - * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set - * @author Jeongho Nam - */ - class HashSet extends base.UniqueSet { - private hash_buckets_; - /** - * @hidden - */ - protected init(): void; - /** - * @hidden - */ - protected construct_from_array(items: Array): void; - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: T): SetIterator; - /** - * @inheritdoc - */ - begin(): SetIterator; - /** - * @inheritdoc - */ - begin(index: number): SetIterator; - /** - * @inheritdoc - */ - end(): SetIterator; - /** - * @inheritdoc - */ - end(index: number): SetIterator; - /** - * @inheritdoc - */ - rbegin(): SetReverseIterator; - /** - * @inheritdoc - */ - rbegin(index: number): SetReverseIterator; - /** - * @inheritdoc - */ - rend(): SetReverseIterator; - /** - * @inheritdoc - */ - rend(index: number): SetReverseIterator; - /** - * @inheritdoc - */ - bucket_count(): number; - /** - * @inheritdoc - */ - bucket_size(n: number): number; - /** - * @inheritdoc - */ - max_load_factor(): number; - /** - * @inheritdoc - */ - max_load_factor(z: number): void; - /** - * @inheritdoc - */ - bucket(key: T): number; - /** - * @inheritdoc - */ - reserve(n: number): void; - /** - * @inheritdoc - */ - rehash(n: number): void; - /** - * @hidden - */ - protected insert_by_val(val: T): any; - /** - * @hidden - */ - protected insert_by_hint(hint: SetIterator, val: T): SetIterator; - /** - * @hidden - */ - protected insert_by_range>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected handle_insert(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - protected handle_erase(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - swap(obj: base.UniqueSet): void; - /** - * @hidden - */ - private swap_tree_set(obj); - } +declare namespace std.HashMultiSet { + type iterator = std.SetIterator; + type reverse_iterator = std.SetReverseIterator; } declare namespace std { /** *

      Hashed, unordered Multiset.

      * *

      {@link HashMultiSet HashMultiSets} are containers that store elements in no particular order, allowing fast - * retrieval of individual elements based on their value, much like {@link HashSet} containers, + * retrieval of individual elements based on their value, much like {@link HashMultiSet} containers, * but allowing different elements to have equivalent values.

      * *

      In an {@link HashMultiSet}, the value of an element is at the same time its key, used to @@ -6104,8 +6070,8 @@ declare namespace std { *

      Elements with equivalent values are grouped together in the same bucket and in such a way that an * iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

      * - *
      + *

      + *

      * *

      Container properties

      *
      @@ -6131,15 +6097,26 @@ declare namespace std { * @author Jeongho Nam */ class HashMultiSet extends base.MultiSet { + /** + * @hidden + */ private hash_buckets_; /** - * @hidden + * Default Constructor. */ - protected init(): void; + constructor(); /** - * @hidden + * Construct from elements. */ - protected construct_from_array(items: Array): void; + constructor(items: T[]); + /** + * Copy Constructor. + */ + constructor(container: HashMultiSet); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator, end: Iterator); /** * @inheritdoc */ @@ -6215,33 +6192,354 @@ declare namespace std { /** * @hidden */ - protected insert_by_val(val: T): any; + protected _Insert_by_val(val: T): any; /** * @hidden */ - protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; /** * @hidden */ - protected insert_by_range>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: SetIterator, last: SetIterator): void; + protected _Handle_insert(first: SetIterator, last: SetIterator): void; /** * @inheritdoc */ - protected handle_erase(first: SetIterator, last: SetIterator): void; + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + *

      Swap content.

      + * + *

      Exchanges the content of the container by the content of obj, which is another + * {@link HashMultiSet set} of the same type. Sizes abd container type may differ.

      + * + *

      After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

      + * + *

      Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

      + * + * @param obj Another {@link HashMultiSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashMultiSet container}. + */ + swap(obj: HashMultiSet): void; /** * @inheritdoc */ - swap(obj: base.MultiSet): void; - /** - * @hidden - */ - private swap_tree_set(obj); + swap(obj: base.IContainer): void; } } +declare namespace std.base { + /** + *

      An abstract set.

      + * + *

      {@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of + * individual elements based on their value.

      + * + *

      In an {@link SetContainer}, the value of an element is at the same time its key, used to uniquely + * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be modified + * once in the container - they can be inserted and removed, though.

      + * + *

      {@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

      + * + *

      + *

      + * + *

      Container properties

      + *
      + *
      Associative
      + *
      + * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
      + * + *
      Set
      + *
      The value of an element is also the key used to identify it.
      + * + *
      Unique keys
      + *
      No two elements in the container can have equivalent keys.
      + *
      + * + * @param Type of the elements. Each element in a {@link SetContainer} container is also identified + * by this value (each value is itself also the element's key). + * + * @author Jeongho Nam + */ + abstract class UniqueSet extends SetContainer { + /** + * @inheritdoc + */ + count(key: T): number; + /** + *

      Extract an element.

      + * + *

      Extracts the element pointed to by val and erases it from the {@link UniqueSet}.

      + * + * @param val Value to be extracted. + * + * @return A value. + */ + extract(val: T): T; + /** + *

      Extract an element.

      + * + *

      Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

      + * + * @param it An iterator pointing an element to extract. + * + * @return An iterator pointing to the element immediately following it prior to the element being + * erased. If no such element exists,returns {@link end end()}. + */ + extract(it: SetIterator): SetIterator; + /** + *

      Extract an element.

      + * + *

      Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

      + * + * @param it An iterator pointing an element to extract. + * + * @return An iterator pointing to the element immediately following it prior to the element being + * erased. If no such element exists,returns {@link end end()}. + */ + extract(it: SetReverseIterator): SetReverseIterator; + /** + * @hidden + */ + private extract_by_key(val); + /** + * @hidden + */ + private extract_by_iterator(it); + /** + * @hidden + */ + private extract_by_reverse_iterator(it); + /** + *

      Insert an element.

      + * + *

      Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of element inserted (zero or one).

      + * + *

      Because elements in a {@link UniqueSet UniqueSets} are unique, the insertion operation checks whether + * each inserted element is equivalent to an element already in the container, and if so, the element is not + * inserted, returning an iterator to this existing element (if the function returns a value).

      + * + *

      For a similar container allowing for duplicate elements, see {@link MultiSet}.

      + * + * @param key Value to be inserted as an element. + * + * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly + * inserted element or to the equivalent element already in the {@link UniqueSet}. The + * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or + * false if an equivalent element already existed. + */ + insert(val: T): Pair, boolean>; + /** + * @inheritdoc + */ + insert(hint: SetIterator, val: T): SetIterator; + /** + * @inheritdoc + */ + insert(hint: SetReverseIterator, val: T): SetReverseIterator; + /** + * @inheritdoc + */ + insert>(begin: InputIterator, end: InputIterator): void; + } +} +declare namespace std.HashSet { + type iterator = std.SetIterator; + type reverse_iterator = std.SetReverseIterator; +} +declare namespace std { + /** + *

      Hashed, unordered set.

      + * + *

      {@link HashSet}s are containers that store unique elements in no particular order, and which + * allow for fast retrieval of individual elements based on their value.

      + * + *

      In an {@link HashSet}, the value of an element is at the same time its key, that + * identifies it uniquely. Keys are immutable, therefore, the elements in an {@link HashSet} cannot be + * modified once in the container - they can be inserted and removed, though.

      + * + *

      Internally, the elements in the {@link HashSet} are not sorted in any particular order, but + * organized into buckets depending on their hash values to allow for fast access to individual elements + * directly by their values (with a constant average time complexity on average).

      + * + *

      {@link HashSet} containers are faster than {@link TreeSet} containers to access individual + * elements by their key, although they are generally less efficient for range iteration through a + * subset of their elements.

      + * + *

      + *

      + * + *

      Container properties

      + *
      + *
      Associative
      + *
      Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
      + * + *
      Hashed
      + *
      Hashed containers organize their elements using hash tables that allow for fast access to elements + * by their key.
      + * + *
      Set
      + *
      The value of an element is also the key used to identify it.
      + * + *
      Unique keys
      + *
      No two elements in the container can have equivalent keys.
      + *
      + * + * @param Type of the elements. + * Each element in an {@link HashSet} is also uniquely identified by this value. + * + * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set + * @author Jeongho Nam + */ + class HashSet extends base.UniqueSet implements base.IHashSet { + /** + * @hidden + */ + private hash_buckets_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + constructor(items: T[]); + /** + * Copy Constructor. + */ + constructor(container: HashSet); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator, end: Iterator); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: T): SetIterator; + /** + * @inheritdoc + */ + begin(): SetIterator; + /** + * @inheritdoc + */ + begin(index: number): SetIterator; + /** + * @inheritdoc + */ + end(): SetIterator; + /** + * @inheritdoc + */ + end(index: number): SetIterator; + /** + * @inheritdoc + */ + rbegin(): SetReverseIterator; + /** + * @inheritdoc + */ + rbegin(index: number): SetReverseIterator; + /** + * @inheritdoc + */ + rend(): SetReverseIterator; + /** + * @inheritdoc + */ + rend(index: number): SetReverseIterator; + /** + * @inheritdoc + */ + bucket_count(): number; + /** + * @inheritdoc + */ + bucket_size(n: number): number; + /** + * @inheritdoc + */ + max_load_factor(): number; + /** + * @inheritdoc + */ + max_load_factor(z: number): void; + /** + * @inheritdoc + */ + bucket(key: T): number; + /** + * @inheritdoc + */ + reserve(n: number): void; + /** + * @inheritdoc + */ + rehash(n: number): void; + /** + * @hidden + */ + protected _Insert_by_val(val: T): any; + /** + * @hidden + */ + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; + /** + * @inheritdoc + */ + protected _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @inheritdoc + */ + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + *

      Swap content.

      + * + *

      Exchanges the content of the container by the content of obj, which is another + * {@link HashSet set} of the same type. Sizes abd container type may differ.

      + * + *

      After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

      + * + *

      Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

      + * + * @param obj Another {@link HashSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashSet container}. + */ + swap(obj: HashSet): void; + /** + * @inheritdoc + */ + swap(obj: base.IContainer): void; + } +} +declare namespace std.List { + type iterator = std.ListIterator; + type reverse_iterator = std.ListReverseIterator; +} declare namespace std { /** *

      Doubly linked list.

      @@ -6266,8 +6564,8 @@ declare namespace std { * distance between these. They also consume some extra memory to keep the linking information associated to each * element (which may be an important factor for large lists of small-sized elements).

      * - *

      - * + *

      + * *

      * *

      Container properties

      @@ -6289,17 +6587,17 @@ declare namespace std { */ class List extends base.Container implements base.IDequeContainer { /** - * An iterator of beginning. + * @hidden */ - protected begin_: ListIterator; + private begin_; /** - * An iterator of end. + * @hidden */ - protected end_: ListIterator; + private end_; /** - * Number of elements in the {@link List}. + * @hidden */ - protected size_: number; + private size_; /** *

      Default Constructor.

      * @@ -6332,7 +6630,7 @@ declare namespace std { * @param container Another container object of the same type (with the same class template * arguments T), whose contents are either copied or acquired. */ - constructor(container: base.IContainer); + constructor(container: List); /** *

      Range Constructor.

      * @@ -6522,11 +6820,11 @@ declare namespace std { /** * @hidden */ - protected insert_by_repeating_val(position: ListIterator, size: number, val: T): ListIterator; + protected _Insert_by_repeating_val(position: ListIterator, size: number, val: T): ListIterator; /** * @hidden */ - protected insert_by_range>(position: ListIterator, begin: InputIterator, end: InputIterator): ListIterator; + protected _Insert_by_range>(position: ListIterator, begin: InputIterator, end: InputIterator): ListIterator; /** *

      Erase an element.

      * @@ -6596,7 +6894,7 @@ declare namespace std { /** * @hidden */ - protected erase_by_range(first: ListIterator, last: ListIterator): ListIterator; + protected _Erase_by_range(first: ListIterator, last: ListIterator): ListIterator; /** *

      Remove duplicate values.

      * @@ -6826,21 +7124,43 @@ declare namespace std { */ sort(compare: (left: T, right: T) => boolean): void; /** - * @inheritdoc + * @hidden */ - swap(obj: base.IContainer): void; + private qsort(first, last, compare); /** * @hidden */ - private swap_list(obj); + private partition(first, last, compare); + /** + *

      Swap content.

      + * + *

      Exchanges the content of the container by the content of obj, which is another + * {@link List container} object with same type of elements. Sizes and container type may differ.

      + * + *

      After the call to this member function, the elements in this container are those which were in obj + * before the call, and the elements of obj are those which were in this. All iterators, references and + * pointers remain valid for the swapped objects.

      + * + *

      Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

      + * + * @param obj Another {@link List container} of the same type of elements (i.e., instantiated + * with the same template parameter, T) whose content is swapped with that of this + * {@link container List}. + */ + swap(obj: List): void; + /** + * @inheritdoc + */ + swap(obj: base.IContainer): void; } } declare namespace std { /** *

      An iterator, node of a List.

      * - *

      - * + *

      + * *

      * * @author Jeongho Nam @@ -6862,14 +7182,6 @@ declare namespace std { * @param value Value to be stored in the node (iterator). */ constructor(source: List, prev: ListIterator, next: ListIterator, value: T); - /** - * @inheritdoc - */ - set_prev(it: ListIterator): void; - /** - * @inheritdoc - */ - set_next(next: ListIterator): void; private list(); /** * @inheritdoc @@ -6886,7 +7198,20 @@ declare namespace std { /** * @inheritdoc */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ value: T; + /** + * @hidden + */ + _Set_prev(it: ListIterator): void; + /** + * @hidden + */ + _Set_next(it: ListIterator): void; /** * @inheritdoc */ @@ -6901,8 +7226,8 @@ declare namespace std { /** *

      A reverse-iterator of List.

      * - *

      - * + *

      + * *

      * * @param Type of the elements. @@ -6910,17 +7235,213 @@ declare namespace std { * @author Jeongho Nam */ class ListReverseIterator extends ReverseIterator, ListReverseIterator> { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: ListIterator); /** - * @inheritdoc + * @hidden */ - protected create_neighbor(): ListReverseIterator; + protected create_neighbor(base: ListIterator): ListReverseIterator; /** * @inheritdoc */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ value: T; } } +declare namespace std { + /** + *

      Priority queue.

      + * + *

      {@link PriorityQueue Priority queues} are a type of container adaptors, specifically designed such that its + * first element is always the greatest of the elements it contains, according to some strict weak ordering + * criterion.

      + * + *

      This context is similar to a heap, where elements can be inserted at any moment, and only the + * max heap element can be retrieved (the one at the top in the {@link PriorityQueue priority queue}).

      + * + *

      {@link PriorityQueue Priority queues} are implemented as container adaptors, which are classes that + * use an encapsulated object of a specific container class as its {@link container_ underlying container}, + * providing a specific set of member functions to access its elements. Elements are popped from the "back" + * of the specific container, which is known as the top of the {@link PriorityQueue Priority queue}.

      + * + *

      The {@link container_ underlying container} may be any of the standard container class templates or some + * other specifically designed container class. The container shall be accessible through + * {@link IArrayIterator random access iterators} and support the following operations:

      + * + *
        + *
      • empty()
      • + *
      • size()
      • + *
      • front()
      • + *
      • push_back()
      • + *
      • pop_back()
      • + *
      + * + *

      The standard container classes {@link Vector} and {@link Deque} fulfill these requirements. By default, if + * no container class is specified for a particular {@link PriorityQueue} class instantiation, the standard + * container {@link Vector} is used.

      + * + *

      Support of {@link IArrayIterator random access iterators} is required to keep a heap structure internally + * at all times. This is done automatically by the container adaptor by automatically calling the algorithm + * functions make_heap, push_heap and pop_heap when needed.

      + * + * @param Type of the elements. + * + * @reference http://www.cplusplus.com/reference/queue/priority_queue/ + * @author Jeongho Nam + */ + class PriorityQueue { + /** + *

      The underlying container for implementing the priority queue.

      + * + *

      Following standard definition from the C++ committee, the underlying container should be one of + * {@link Vector} or {@link Deque}, however, I've adopted {@link TreeMultiSet} instead of them. Of course, + * there are proper reasons for adapting the {@link TreeMultiSet} even violating standard advice.

      + * + *

      Underlying container of {@link PriorityQueue} must keep a condition; the highest (or lowest) + * element must be placed on the terminal node for fast retrieval and deletion. To keep the condition with + * {@link Vector} or {@link Deque}, lots of times will only be spent for re-arranging elements. It calls + * rearrangement functions like make_heap, push_heap and pop_head for rearrangement.

      + * + *

      However, the {@link TreeMultiSet} container always keeps arrangment automatically without additional + * operations and it even meets full criteria of {@link PriorityQueue}. Those are the reason why I've adopted + * {@link TreeMultiSet} as the underlying container of {@link PriorityQueue}.

      + */ + private container_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. + */ + constructor(compare: (left: T, right: T) => boolean); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + */ + constructor(array: Array); + /** + * Contruct from elements with compare. + * + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array, compare: (left: T, right: T) => boolean); + /** + * Copy Constructor. + */ + constructor(container: base.IContainer); + /** + * Copy Constructor with compare. + * + * @param container A container to be copied. + * @param compare A binary predicate determines order of elements. + */ + constructor(container: base.IContainer, compare: (left: T, right: T) => boolean); + /** + * Range Constructor. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + */ + constructor(begin: Iterator, end: Iterator); + /** + * Range Constructor with compare. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * @param compare A binary predicate determines order of elements. + */ + constructor(begin: Iterator, end: Iterator, compare: (left: T, right: T) => boolean); + /** + *

      Return size.

      + * + *

      Returns the number of elements in the {@link PriorityQueue}.

      + * + *

      This member function effectively calls member {@link IArray.size size} of the + * {@link container_ underlying container} object.

      + * + * @return The number of elements in the underlying + */ + size(): number; + /** + *

      Test whether container is empty.

      + * + *

      Returns whether the {@link PriorityQueue} is empty: i.e. whether its {@link size} is zero.

      + * + *

      This member function effectively calls member {@link IARray.empty empty} of the + * {@link container_ underlying container} object.

      + */ + empty(): boolean; + /** + *

      Access top element.

      + * + *

      Returns a constant reference to the top element in the {@link PriorityQueue}.

      + * + *

      The top element is the element that compares higher in the {@link PriorityQueue}, and the next that is + * removed from the container when {@link PriorityQueue.pop} is called.

      + * + *

      This member function effectively calls member {@link IArray.front front} of the + * {@link container_ underlying container} object.

      + * + * @return A reference to the top element in the {@link PriorityQueue}. + */ + top(): T; + /** + *

      Insert element.

      + * + *

      Inserts a new element in the {@link PriorityQueue}. The content of this new element is initialized to + * val. + * + *

      This member function effectively calls the member function {@link IArray.push_back push_back} of the + * {@link container_ underlying container} object, and then reorders it to its location in the heap by calling + * the push_heap algorithm on the range that includes all the elements of the

      + * + * @param val Value to which the inserted element is initialized. + */ + push(val: T): void; + /** + *

      Remove top element.

      + * + *

      Removes the element on top of the {@link PriorityQueue}, effectively reducing its {@link size} by one. + * The element removed is the one with the highest (or lowest) value.

      + * + *

      The value of this element can be retrieved before being popped by calling member + * {@link PriorityQueue.top}.

      + * + *

      This member function effectively calls the pop_heap algorithm to keep the heap property of + * {@link PriorityQueue PriorityQueues} and then calls the member function {@link IArray.pop_back pop_back} of + * the {@link container_ underlying container} object to remove the element.

      + */ + pop(): void; + /** + *

      Swap contents.

      + * + *

      Exchanges the contents of the container adaptor by those of obj, swapping both the + * {@link container_ underlying container} value and their comparison function using the corresponding + * {@link std.swap swap} non-member functions (unqualified).

      + * + *

      This member function has a noexcept specifier that matches the combined noexcept of the + * {@link IArray.swap swap} operations on the {@link container_ underlying container} and the comparison + * functions.

      + * + * @param obj {@link PriorityQueue} container adaptor of the same type (i.e., instantiated with the same + * template parameters, T). Sizes may differ. + */ + swap(obj: PriorityQueue): void; + } +} declare namespace std { /** *

      FIFO queue.

      @@ -6951,8 +7472,8 @@ declare namespace std { * By default, if no container class is specified for a particular {@link Queue} class instantiation, the standard * container {@link List} is used.

      * - *

      - * + *

      + * *

      * * @param Type of elements. @@ -7057,204 +7578,6 @@ declare namespace std { swap(obj: Queue): void; } } -declare namespace std { - /** - *

      Priority queue.

      - * - *

      {@link PriorityQueue Priority queues} are a type of container adaptors, specifically designed such that its - * first element is always the greatest of the elements it contains, according to some strict weak ordering - * criterion.

      - * - *

      This context is similar to a heap, where elements can be inserted at any moment, and only the - * max heap element can be retrieved (the one at the top in the {@link PriorityQueue priority queue}).

      - * - *

      {@link PriorityQueue Priority queues} are implemented as container adaptors, which are classes that - * use an encapsulated object of a specific container class as its {@link container_ underlying container}, - * providing a specific set of member functions to access its elements. Elements are popped from the "back" - * of the specific container, which is known as the top of the {@link PriorityQueue Priority queue}.

      - * - *

      The {@link container_ underlying container} may be any of the standard container class templates or some - * other specifically designed container class. The container shall be accessible through - * {@link IArrayIterator random access iterators} and support the following operations:

      - * - *
        - *
      • empty()
      • - *
      • size()
      • - *
      • front()
      • - *
      • push_back()
      • - *
      • pop_back()
      • - *
      - * - *

      The standard container classes {@link Vector} and {@link Deque} fulfill these requirements. By default, if - * no container class is specified for a particular {@link PriorityQueue} class instantiation, the standard - * container {@link Vector} is used.

      - * - *

      Support of {@link IArrayIterator random access iterators} is required to keep a heap structure internally - * at all times. This is done automatically by the container adaptor by automatically calling the algorithm - * functions make_heap, push_heap and pop_heap when needed.

      - * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/queue/priority_queue/ - * @author Jeongho Nam - */ - class PriorityQueue { - /** - *

      The underlying container for implementing the priority queue.

      - * - *

      Following standard definition from the C++ committee, the underlying container should be one of - * {@link Vector} or {@link Deque}, however, I've adopted {@link TreeMultiSet} instead of them. Of course, - * there are proper reasons for adapting the {@link TreeMultiSet} even violating standard advice.

      - * - *

      Underlying container of {@link PriorityQueue} must keep a condition; the highest (or lowest) - * element must be placed on the terminal node for fast retrieval and deletion. To keep the condition with - * {@link Vector} or {@link Deque}, lots of times will only be spent for re-arranging elements. It calls - * rearrangement functions like make_heap, push_heap and pop_head for rearrangement.

      - * - *

      However, the {@link TreeMultiSet} container always keeps arrangment automatically without additional - * operations and it even meets full criteria of {@link PriorityQueue}. Those are the reason why I've adopted - * {@link TreeMultiSet} as the underlying container of {@link PriorityQueue}.

      - */ - private container_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from compare. - * - * @param compare A binary predicate determines order of elements. - */ - constructor(compare: (left: T, right: T) => boolean); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - */ - constructor(array: Array); - /** - * Contruct from elements with compare. - * - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array, compare: (left: T, right: T) => boolean); - /** - * Copy Constructor. - */ - constructor(container: base.Container); - /** - * Copy Constructor with compare. - * - * @param container A container to be copied. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: base.Container, compare: (left: T, right: T) => boolean); - /** - * Range Constructor. - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator, end: Iterator); - /** - * Range Constructor with compare. - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * @param compare A binary predicate determines order of elements. - */ - constructor(begin: Iterator, end: Iterator, compare: (left: T, right: T) => boolean); - /** - * @hidden - */ - protected construct_from_array(items: Array): void; - /** - * @hidden - */ - protected construct_from_container(container: base.IContainer): void; - /** - * @hidden - */ - protected construct_from_range(begin: Iterator, end: Iterator): void; - /** - *

      Return size.

      - * - *

      Returns the number of elements in the {@link PriorityQueue}.

      - * - *

      This member function effectively calls member {@link IArray.size size} of the - * {@link container_ underlying container} object.

      - * - * @return The number of elements in the underlying - */ - size(): number; - /** - *

      Test whether container is empty.

      - * - *

      Returns whether the {@link PriorityQueue} is empty: i.e. whether its {@link size} is zero.

      - * - *

      This member function effectively calls member {@link IARray.empty empty} of the - * {@link container_ underlying container} object.

      - */ - empty(): boolean; - /** - *

      Access top element.

      - * - *

      Returns a constant reference to the top element in the {@link PriorityQueue}.

      - * - *

      The top element is the element that compares higher in the {@link PriorityQueue}, and the next that is - * removed from the container when {@link PriorityQueue.pop} is called.

      - * - *

      This member function effectively calls member {@link IArray.front front} of the - * {@link container_ underlying container} object.

      - * - * @return A reference to the top element in the {@link PriorityQueue}. - */ - top(): T; - /** - *

      Insert element.

      - * - *

      Inserts a new element in the {@link PriorityQueue}. The content of this new element is initialized to - * val. - * - *

      This member function effectively calls the member function {@link IArray.push_back push_back} of the - * {@link container_ underlying container} object, and then reorders it to its location in the heap by calling - * the push_heap algorithm on the range that includes all the elements of the

      - * - * @param val Value to which the inserted element is initialized. - */ - push(val: T): void; - /** - *

      Remove top element.

      - * - *

      Removes the element on top of the {@link PriorityQueue}, effectively reducing its {@link size} by one. - * The element removed is the one with the highest (or lowest) value.

      - * - *

      The value of this element can be retrieved before being popped by calling member - * {@link PriorityQueue.top}.

      - * - *

      This member function effectively calls the pop_heap algorithm to keep the heap property of - * {@link PriorityQueue PriorityQueues} and then calls the member function {@link IArray.pop_back pop_back} of - * the {@link container_ underlying container} object to remove the element.

      - */ - pop(): void; - /** - *

      Swap contents.

      - * - *

      Exchanges the contents of the container adaptor by those of obj, swapping both the - * {@link container_ underlying container} value and their comparison function using the corresponding - * {@link std.swap swap} non-member functions (unqualified).

      - * - *

      This member function has a noexcept specifier that matches the combined noexcept of the - * {@link IArray.swap swap} operations on the {@link container_ underlying container} and the comparison - * functions.

      - * - * @param obj {@link PriorityQueue} container adaptor of the same type (i.e., instantiated with the same - * template parameters, T). Sizes may differ. - */ - swap(obj: PriorityQueue): void; - } -} declare namespace std { /** *

      LIFO stack.

      @@ -7283,8 +7606,8 @@ declare namespace std { * By default, if no container class is specified for a particular {@link Stack} class instantiation, the standard * container {@link List} is used.

      * - *

      - * + *

      + * *

      * * @param Type of elements. @@ -7394,18 +7717,18 @@ declare namespace std.base { * so that they can be interpreted when needed as more abstract (and portable) * {@link ErrorCondition error conditions}.

      * - *

      - *

      + *

      + *

      * * @author Jeongho Nam */ abstract class ErrorInstance { /** - * A reference to an {@link ErrorCategory} object. + * @hidden */ protected category_: ErrorCategory; /** - * A numerical value identifying an error instance. + * @hidden */ protected value_: number; /** @@ -7504,15 +7827,15 @@ declare namespace std { *

      The class inherits from {@link RuntimeError}, to which it adds an {@link ErrorCode} as * member code (and defines a specialized what member).

      * - *

      - *

      + *

      + *

      * * @reference http://www.cplusplus.com/reference/system_error/system_error * @author Jeongho Nam */ class SystemError extends RuntimeError { /** - * Error code. + * @hidden */ protected code_: ErrorCode; /** @@ -7570,8 +7893,8 @@ declare namespace std { * passed by reference. As such, only one object of each of these types shall exist, each uniquely identifying its own * category: all error codes and conditions of a same category shall return a reference to same object.

      * - *

      - *

      + *

      + *

      * * @reference http://www.cplusplus.com/reference/system_error/error_category * @author Jeongho Nam @@ -7698,8 +8021,8 @@ declare namespace std { *

      The {@link ErrorCategory categories} associated with the {@link ErrorCondition} and the * {@link ErrorCode} define the equivalences between them.

      * - *

      - *

      + *

      + *

      * * @reference http://www.cplusplus.com/reference/system_error/error_condition * @author Jeongho Nam @@ -7731,8 +8054,8 @@ declare namespace std { *

      Objects of this class associate such numerical codes to {@link ErrorCategory error categories}, so that they * can be interpreted when needed as more abstract (and portable) {@link ErrorCondition error conditions}.

      * - *

      - *

      + *

      + *

      * * @reference http://www.cplusplus.com/reference/system_error/error_code * @author Jeongho Nam @@ -7751,6 +8074,10 @@ declare namespace std { constructor(val: number, category: ErrorCategory); } } +declare namespace std.TreeMap { + type iterator = std.MapIterator; + type reverse_iterator = std.MapReverseIterator; +} declare namespace std { /** *

      Tree-structured map, std::map of STL.

      @@ -7773,8 +8100,8 @@ declare namespace std { * *

      {@link TreeMap}s are typically implemented as binary search trees.

      * - *

      - *

      + *

      + *

      * *

      Container properties

      *
      @@ -7802,7 +8129,7 @@ declare namespace std { */ class TreeMap extends base.UniqueMap implements base.ITreeMap { /** - * RB-Tree+ object for implemeting the {@link TreeMap}. + * @hidden */ private tree_; /** @@ -7846,14 +8173,14 @@ declare namespace std { * * @param container Another map to copy. */ - constructor(container: base.MapContainer); + constructor(container: TreeMap); /** * Copy Constructor. * * @param container Another map to copy. * @param compare A binary predicate determines order of elements. */ - constructor(container: base.MapContainer, compare: (x: Key, y: Key) => boolean); + constructor(container: TreeMap, compare: (x: Key, y: Key) => boolean); /** * Range Constructor. * @@ -7900,33 +8227,51 @@ declare namespace std { /** * @hidden */ - protected insert_by_pair(pair: Pair): any; + protected _Insert_by_pair(pair: Pair): any; /** * @hidden */ - protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ - protected insert_by_range>>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: MapIterator, last: MapIterator): void; + protected _Handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: MapIterator, last: MapIterator): void; + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + *

      Swap content.

      + * + *

      Exchanges the content of the container by the content of obj, which is another + * {@link TreeMap map} of the same type. Sizes abd container type may differ.

      + * + *

      After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

      + * + *

      Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

      + * + * @param obj Another {@link TreeMap map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeMap container}. + */ + swap(obj: TreeMap): void; /** * @inheritdoc */ - swap(obj: base.UniqueMap): void; - /** - * @hidden - */ - private swap_tree_map(obj); + swap(obj: base.IContainer>): void; } } +declare namespace std.TreeMultiMap { + type iterator = std.MapIterator; + type reverse_iterator = std.MapReverseIterator; +} declare namespace std { /** *

      Tree-structured multiple-key map.

      @@ -7951,8 +8296,8 @@ declare namespace std { * *

      {@link TreeMultiMap TreeMultiMaps} are typically implemented as binary search trees.

      * - *

      < - * img src="http://samchon.github.io/stl/api/assets/images/design/map_containers.png" style="max-width: 100%" />

      + *

      < + * img src="http://samchon.github.io/typescript-stl/images/design/class_diagram/map_containers.png" style="max-width: 100%" />

      * *

      Container properties

      *
      @@ -7985,6 +8330,9 @@ declare namespace std { * @author Jeongho Nam */ class TreeMultiMap extends base.MultiMap implements base.ITreeMap { + /** + * @hidden + */ private tree_; /** * Default Constructor. @@ -8027,14 +8375,14 @@ declare namespace std { * * @param container Another map to copy. */ - constructor(container: base.MapContainer); + constructor(container: TreeMultiMap); /** * Copy Constructor. * * @param container Another map to copy. * @param compare A binary predicate determines order of elements. */ - constructor(container: base.MapContainer, compare: (x: Key, y: Key) => boolean); + constructor(container: TreeMultiMap, compare: (x: Key, y: Key) => boolean); /** * Range Constructor. * @@ -8085,191 +8433,50 @@ declare namespace std { /** * @hidden */ - protected insert_by_pair(pair: Pair): any; + protected _Insert_by_pair(pair: Pair): any; /** * @hidden */ - protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ - protected insert_by_range>>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: MapIterator, last: MapIterator): void; + protected _Handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: MapIterator, last: MapIterator): void; + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + *

      Swap content.

      + * + *

      Exchanges the content of the container by the content of obj, which is another + * {@link TreeMapMulti map} of the same type. Sizes abd container type may differ.

      + * + *

      After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

      + * + *

      Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

      + * + * @param obj Another {@link TreeMapMulti map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeMapMulti container}. + */ + swap(obj: TreeMultiMap): void; /** * @inheritdoc */ - swap(obj: base.MultiMap): void; - /** - * @hidden - */ - private swap_tree_multimap(obj); + swap(obj: base.IContainer>): void; } } -declare namespace std { - /** - *

      Tree-structured set, std::set of STL.

      - * - *

      {@link TreeSet}s are containers that store unique elements following a specific order.

      - * - *

      In a {@link TreeSet}, the value of an element also identifies it (the value is itself the - * key, of type T), and each value must be unique. The value of the elements in a - * {@link TreeSet} cannot be modified once in the container (the elements are always const), but they - * can be inserted or removed from the

      - * - *

      Internally, the elements in a {@link TreeSet} are always sorted following a specific strict weak - * ordering criterion indicated by its internal comparison method (of {@link less}).

      - * - *

      {@link TreeSet} containers are generally slower than {@link HashSet} containers to access - * individual elements by their key, but they allow the direct iteration on subsets based on their - * order.

      - * - *

      {@link TreeSet}s are typically implemented as binary search trees.

      - * - *

      - *

      - * - *

      Container properties

      - *
      - *
      Associative
      - *
      - * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
      - * - *
      Ordered
      - *
      - * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
      - * - *
      Set
      - *
      The value of an element is also the key used to identify it.
      - * - *
      Unique keys
      - *
      No two elements in the container can have equivalent keys.
      - *
      - * - * @param Type of the elements. - * Each element in an {@link TreeSet} is also uniquely identified by this value. - * - * @reference http://www.cplusplus.com/reference/set/set - * @author Jeongho Nam - */ - class TreeSet extends base.UniqueSet implements base.ITreeSet { - /** - * RB-Tree+ object for implemeting the {@link TreeSet}. - */ - private tree_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from compare. - * - * @param compare A binary predicate determines order of elements. - */ - constructor(compare: (x: T, y: T) => boolean); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - */ - constructor(array: Array); - /** - * Contruct from elements with compare. - * - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array, compare: (x: T, y: T) => boolean); - /** - * Copy Constructor. - */ - constructor(container: base.IContainer); - /** - * Copy Constructor with compare. - * - * @param container A container to be copied. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: base.IContainer, compare: (x: T, y: T) => boolean); - /** - * Range Constructor. - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator, end: Iterator); - /** - * Range Constructor with compare. - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * @param compare A binary predicate determines order of elements. - */ - constructor(begin: Iterator, end: Iterator, compare: (x: T, y: T) => boolean); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(val: T): SetIterator; - /** - * @inheritdoc - */ - key_comp(): (x: T, y: T) => boolean; - /** - * @inheritdoc - */ - value_comp(): (x: T, y: T) => boolean; - /** - * @inheritdoc - */ - lower_bound(val: T): SetIterator; - /** - * @inheritdoc - */ - upper_bound(val: T): SetIterator; - /** - * @inheritdoc - */ - equal_range(val: T): Pair, SetIterator>; - /** - * @hidden - */ - protected insert_by_val(val: T): any; - protected insert_by_hint(hint: SetIterator, val: T): SetIterator; - /** - * @hidden - */ - protected insert_by_range>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected handle_insert(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - protected handle_erase(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - swap(obj: base.UniqueSet): void; - /** - * @hidden - */ - private swap_tree_set(obj); - } +declare namespace std.TreeMultiSet { + type iterator = std.SetIterator; + type reverse_iterator = std.SetReverseIterator; } declare namespace std { /** @@ -8292,8 +8499,8 @@ declare namespace std { * *

      {@link TreeMultiSet TreeMultiSets} are typically implemented as binary search trees.

      * - *
      + *

      + *

      * *

      Container properties

      *
      @@ -8324,7 +8531,7 @@ declare namespace std { */ class TreeMultiSet extends base.MultiSet implements base.ITreeSet { /** - * RB-Tree+ object for implemeting the {@link TreeMultiSet}. + * @hidden */ private tree_; /** @@ -8353,14 +8560,14 @@ declare namespace std { /** * Copy Constructor. */ - constructor(container: base.Container); + constructor(container: TreeMultiSet); /** * Copy Constructor with compare. * * @param container A container to be copied. * @param compare A binary predicate determines order of elements. */ - constructor(container: base.Container, compare: (x: T, y: T) => boolean); + constructor(container: TreeMultiSet, compare: (x: T, y: T) => boolean); /** * Range Constructor. * @@ -8411,31 +8618,226 @@ declare namespace std { /** * @hidden */ - protected insert_by_val(val: T): any; + _Get_tree(): base.AtomicTree; /** * @hidden */ - protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + protected _Insert_by_val(val: T): any; /** * @hidden */ - protected insert_by_range>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected handle_insert(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - protected handle_erase(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - swap(obj: base.MultiSet): void; + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; /** * @hidden */ - private swap_tree_set(obj); + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; + /** + * @inheritdoc + */ + protected _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @inheritdoc + */ + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + *

      Swap content.

      + * + *

      Exchanges the content of the container by the content of obj, which is another + * {@link TreeMultiSet set} of the same type. Sizes abd container type may differ.

      + * + *

      After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

      + * + *

      Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

      + * + * @param obj Another {@link TreeMultiSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeMultiSet container}. + */ + swap(obj: TreeMultiSet): void; + /** + * @inheritdoc + */ + swap(obj: base.IContainer): void; + } +} +declare namespace std.TreeSet { + type iterator = std.SetIterator; + type reverse_iterator = std.SetReverseIterator; +} +declare namespace std { + /** + *

      Tree-structured set, std::set of STL.

      + * + *

      {@link TreeSet}s are containers that store unique elements following a specific order.

      + * + *

      In a {@link TreeSet}, the value of an element also identifies it (the value is itself the + * key, of type T), and each value must be unique. The value of the elements in a + * {@link TreeSet} cannot be modified once in the container (the elements are always const), but they + * can be inserted or removed from the

      + * + *

      Internally, the elements in a {@link TreeSet} are always sorted following a specific strict weak + * ordering criterion indicated by its internal comparison method (of {@link less}).

      + * + *

      {@link TreeSet} containers are generally slower than {@link HashSet} containers to access + * individual elements by their key, but they allow the direct iteration on subsets based on their + * order.

      + * + *

      {@link TreeSet}s are typically implemented as binary search trees.

      + * + *

      + *

      + * + *

      Container properties

      + *
      + *
      Associative
      + *
      + * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
      + * + *
      Ordered
      + *
      + * The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order. + *
      + * + *
      Set
      + *
      The value of an element is also the key used to identify it.
      + * + *
      Unique keys
      + *
      No two elements in the container can have equivalent keys.
      + *
      + * + * @param Type of the elements. + * Each element in an {@link TreeSet} is also uniquely identified by this value. + * + * @reference http://www.cplusplus.com/reference/set/set + * @author Jeongho Nam + */ + class TreeSet extends base.UniqueSet implements base.ITreeSet { + /** + * @hidden + */ + private tree_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. + */ + constructor(compare: (x: T, y: T) => boolean); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + */ + constructor(array: Array); + /** + * Contruct from elements with compare. + * + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array, compare: (x: T, y: T) => boolean); + /** + * Copy Constructor. + */ + constructor(container: TreeMultiSet); + /** + * Copy Constructor with compare. + * + * @param container A container to be copied. + * @param compare A binary predicate determines order of elements. + */ + constructor(container: TreeMultiSet, compare: (x: T, y: T) => boolean); + /** + * Range Constructor. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + */ + constructor(begin: Iterator, end: Iterator); + /** + * Construct from range and compare. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * @param compare A binary predicate determines order of elements. + */ + constructor(begin: Iterator, end: Iterator, compare: (x: T, y: T) => boolean); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(val: T): SetIterator; + /** + * @inheritdoc + */ + key_comp(): (x: T, y: T) => boolean; + /** + * @inheritdoc + */ + value_comp(): (x: T, y: T) => boolean; + /** + * @inheritdoc + */ + lower_bound(val: T): SetIterator; + /** + * @inheritdoc + */ + upper_bound(val: T): SetIterator; + /** + * @inheritdoc + */ + equal_range(val: T): Pair, SetIterator>; + /** + * @hidden + */ + protected _Insert_by_val(val: T): any; + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; + /** + * @inheritdoc + */ + protected _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @inheritdoc + */ + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + *

      Swap content.

      + * + *

      Exchanges the content of the container by the content of obj, which is another + * {@link TreeSet set} of the same type. Sizes abd container type may differ.

      + * + *

      After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

      + * + *

      Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

      + * + * @param obj Another {@link TreeSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeSet container}. + */ + swap(obj: TreeSet): void; + /** + * @inheritdoc + */ + swap(obj: base.IContainer): void; } } declare namespace std { @@ -8454,8 +8856,8 @@ declare namespace std { * T2). The individual values can be accessed through its public members {@link first} and * {@link second}.

      * - * @param Type of member {@link first}. - * @param Type of member {@link second}. + * @param Type of member {@link first}. + * @param Type of member {@link second}. * * @reference http://www.cplusplus.com/reference/utility/pair * @author Jeongho Nam @@ -8509,6 +8911,10 @@ declare namespace std { */ function make_pair(x: T1, y: T2): Pair; } +declare namespace std.Vector { + type iterator = std.VectorIterator; + type reverse_iterator = std.VectorReverseIterator; +} declare namespace std { /** *

      Vector, the dynamic array.

      @@ -8541,9 +8947,9 @@ declare namespace std { * end, they perform worse than the others, and have less consistent iterators and references than {@link List}s. *

      * - *

      - * - *

      + *

      + * + *

      * *

      Container properties

      *
      @@ -8565,11 +8971,7 @@ declare namespace std { * @reference http://www.cplusplus.com/reference/vector/vector * @author Jeongho Nam */ - class Vector extends Array implements base.IArrayContainer { - /** - * Type definition of {@link Vector}'s {@link VectorIterator iterator}. - */ - static iterator: typeof VectorIterator; + class Vector extends Array implements base.IContainer, base.IArrayContainer { /** *

      Default Constructor.

      * @@ -8606,7 +9008,7 @@ declare namespace std { * @param container Another container object of the same type (with the same class template * arguments T), whose contents are either copied or acquired. */ - constructor(container: base.IContainer); + constructor(container: Vector); /** *

      Range Constructor.

      * @@ -8826,11 +9228,11 @@ declare namespace std { /** * @hidden */ - protected insert_by_repeating_val(position: VectorIterator, n: number, val: T): VectorIterator; + protected _Insert_by_repeating_val(position: VectorIterator, n: number, val: T): VectorIterator; /** * @hidden */ - protected insert_by_range>(position: VectorIterator, first: InputIterator, last: InputIterator): VectorIterator; + protected _Insert_by_range>(position: VectorIterator, first: InputIterator, last: InputIterator): VectorIterator; /** * @inheritdoc */ @@ -8914,9 +9316,27 @@ declare namespace std { */ erase(first: VectorReverseIterator, last: VectorReverseIterator): VectorReverseIterator; /** - * @hiddde + * @hidden */ - protected erase_by_range(first: VectorIterator, last: VectorIterator): VectorIterator; + protected _Erase_by_range(first: VectorIterator, last: VectorIterator): VectorIterator; + /** + *

      Swap content.

      + * + *

      Exchanges the content of the container by the content of obj, which is another + * {@link Vector container} object with same type of elements. Sizes and container type may differ.

      + * + *

      After the call to this member function, the elements in this container are those which were in obj + * before the call, and the elements of obj are those which were in this. All iterators, references and + * pointers remain valid for the swapped objects.

      + * + *

      Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

      + * + * @param obj Another {@link Vector container} of the same type of elements (i.e., instantiated + * with the same template parameter, T) whose content is swapped with that of this + * {@link container Vector}. + */ + obj(obj: Vector): void; /** * @inheritdoc */ @@ -8927,8 +9347,8 @@ declare namespace std { /** *

      An iterator of Vector.

      * - *

      - * + *

      + * *

      * * @param Type of the elements. @@ -8959,7 +9379,9 @@ declare namespace std { * @inheritdoc */ /** - * Set value. + * Set value of the iterator is pointing to. + * + * @param val Value to set. */ value: T; /** @@ -9004,8 +9426,8 @@ declare namespace std { /** *

      A reverse-iterator of Vector.

      * - *

      - * + *

      + * *

      * * @param Type of the elements. @@ -9013,13 +9435,23 @@ declare namespace std { * @author Jeongho Nam */ class VectorReverseIterator extends ReverseIterator, VectorReverseIterator> implements base.IArrayIterator { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ constructor(base: VectorIterator); + /** + * @hidden + */ + protected create_neighbor(base: VectorIterator): VectorReverseIterator; /** * @inheritdoc */ - protected create_neighbor(): VectorReverseIterator; /** - * Set value. + * Set value of the iterator is pointing to. + * + * @param val Value to set. */ value: T; /** @@ -9080,7 +9512,13 @@ declare namespace std.base { * @author Jeongho Nam */ class HashBuckets { + /** + * @hidden + */ private buckets_; + /** + * @hidden + */ private item_size_; /** * Default Constructor. @@ -9127,8 +9565,9 @@ declare namespace std.base { *

      Elements with equivalent keys are grouped together in the same bucket and in such a way that * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

      * - *

      - *

      + *

      + * + *

      * *

      Container properties

      *
      @@ -9422,8 +9861,9 @@ declare namespace std.base { /** *

      Hash buckets storing {@link MapIterator MapIterators}.

      * - *

      - *

      + *

      + * + *

      * * @author Jeongho Nam */ @@ -9452,8 +9892,9 @@ declare namespace std.base { * elements by their key, although they are generally less efficient for range iteration through a * subset of their elements.

      * - *

      - *

      + *

      + * + *

      * *

      Container properties

      *
      @@ -9675,8 +10116,9 @@ declare namespace std.base { /** *

      Hash buckets storing {@link SetIterator SetIterators}.

      * - *

      - *

      + *

      + * + *

      * * @author Jeongho Nam */ @@ -9716,9 +10158,9 @@ declare namespace std.base { * beginning or the end, {@link IArray} objects perform worse and have less consistent iterators and references * than {@link List Lists}

      . * - *

      - * - *

      + *

      + * + *

      * *

      Container properties

      *
      @@ -9830,9 +10272,9 @@ declare namespace std.base { *

      There is not a single type of {@link IArrayIterator random-access iterator}: Each container may define its * own specific iterator type able to iterate through it and access its elements.

      * - *

      - * - *

      + *

      + * + *

      * * @reference http://www.cplusplus.com/reference/iterator/RandomAccessIterator * @author Jeongho Nam @@ -9861,9 +10303,9 @@ declare namespace std.base { *

      {@link IContainer} is an interface designed for sequence containers. Sequence containers of STL * (Standard Template Library) are based on the {@link IContainer}.

      * - *

      - * - *

      + *

      + * + *

      * *

      Container properties

      *
      @@ -10053,9 +10495,9 @@ declare namespace std.base { /** *

      An interface for deque

      * - *

      - * - *

      + *

      + * + *

      * * @author Jeongho Nam */ @@ -10083,8 +10525,8 @@ declare namespace std.base { /** *

      An interface for linear containers.

      * - *

      - * + *

      + * *

      * * @author Jeonngho Nam @@ -10245,7 +10687,7 @@ declare namespace std.base { * * * - *

      * *

      These constraints enforce a critical property of red-black trees: the path from the root to the farthest @@ -10440,7 +10882,7 @@ declare namespace std.base { * the only loop, and any rotations occur after this loop, this proves that a constant number of rotations * occur.

      * - *

      * * @param N A node to be inserted or swapped. @@ -10474,7 +10916,7 @@ declare namespace std.base { * node are black) is still violated, but now we can resolve this by * continuing to case 5.

      * - *

      * * @param N A node to be inserted or swapped. @@ -10505,7 +10947,7 @@ declare namespace std.base { * through {@link XTreeNode.parent P}. In each case, this is the only * black node of the three.

      * - *

      * * @param N A node to be inserted or swapped. @@ -10659,7 +11101,7 @@ declare namespace std.base { /** *

      {@link XTreeNode.sibling S} is red.

      * - *

      * *

      In this case we reverse the colors of {@link XTreeNode.parent P} and @@ -10681,7 +11123,7 @@ declare namespace std.base { *

      {@link XTreeNode.parent P}, {@link XTreeNode.sibling S}, and {@link XTreeNode.sibling * S}'s children are black.

      * - *

      * *

      In this case, we simply repaint {@link XTreeNode.sibling S} red. The @@ -10705,7 +11147,7 @@ declare namespace std.base { *

      {@link XTreeNode.sibling S} and {@link XTreeNode.sibling S}'s children are * black, but {@link XTreeNode.parent P} is red.

      * - *

      * *

      In this case, we simply exchange the colors of {@link XTreeNode.sibling S} and @@ -10722,7 +11164,7 @@ declare namespace std.base { * left child is red, {@link XTreeNode.sibling S}'s right child is * black, and N is the left child of its parent.

      * - *

      * *

      In this case we rotate right at {@link XTreeNode.sibling S}, so that @@ -10761,7 +11203,7 @@ declare namespace std.base { *

      Thus, the paths passing through N pass through one additional * black node.

      * - *

      * *

      Meanwhile, if a path does not go through N, then there are two possibilities:

      @@ -10845,8 +11287,8 @@ declare namespace std.base { * *

      {@link ITreeMap TreeMultiMaps} are typically implemented as binary search trees.

      * - *

      - *

      + *

      + *

      * *

      Container properties

      *
      @@ -10980,18 +11422,25 @@ declare namespace std.base { /** *

      A red-black tree storing {@link MapIterator MapIterators}.

      * - *

      - *

      + *

      + *

      * * @author Jeongho Nam */ class PairTree extends XTree> { + /** + * @hidden + */ private map_; + /** + * @hidden + */ private compare_; /** * Default Constructor. */ constructor(map: TreeMap | TreeMultiMap, compare?: (x: Key, y: Key) => boolean); + _Set_compare(val: (x: Key, y: Key) => boolean): void; find(key: Key): XTreeNode>; find(it: MapIterator): XTreeNode>; /** @@ -11132,8 +11581,8 @@ declare namespace std.base { * *

      {@link ITreeSet TreeMultiSets} are typically implemented as binary search trees.

      * - *

      - *

      + *

      + *

      * *

      Container properties

      *
      @@ -11274,18 +11723,25 @@ declare namespace std.base { /** *

      A red-black Tree storing {@link SetIterator SetIterators}.

      * - *

      - *

      + *

      + *

      * * @author Jeongho Nam */ class AtomicTree extends XTree> { + /** + * @hidden + */ private set_; + /** + * @hidden + */ private compare_; /** * Default Constructor. */ constructor(set: TreeSet | TreeMultiSet, compare?: (x: T, y: T) => boolean); + _Set_compare(val: (x: T, y: T) => boolean): void; find(val: T): XTreeNode>; find(it: SetIterator): XTreeNode>; /** @@ -11461,27 +11917,3 @@ declare namespace std.base { uncle: XTreeNode; } } -declare namespace std.example { - function test_all(): void; -} -declare namespace std.example { - function test_bind(): void; -} -declare namespace std.example { - function test_deque(): void; -} -declare namespace std.example { - function test_for_each(): void; -} -declare namespace std.example { - function test_hash_map(): void; -} -declare namespace std.example { - function test_list(): void; -} -declare namespace std.example { - function sorting(): void; -} -declare namespace std.example { - function tree_set(): void; -} diff --git a/ui-grid/ui-grid-tests.ts b/ui-grid/ui-grid-tests.ts index 7d91d94748..5a088337cd 100644 --- a/ui-grid/ui-grid-tests.ts +++ b/ui-grid/ui-grid-tests.ts @@ -33,13 +33,14 @@ columnDef.filter = { condition: 2, term: 'yes', placeholder: 'testing', + ariaLabel: 'testing', noTerm: false, flags: { caseSensitive: true }, type: 1, selectOptions: [{value: 4, label: 'test'}], - disableCancelButton: false + disableCancelFilterButton: false }; columnDef.filter.condition = (searchTerm: string, cellValue: any, row: uiGrid.IGridRow, column: uiGrid.IGridColumn): boolean => { return true; diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts index a598bc9846..084a6ac17a 100644 --- a/ui-grid/ui-grid.d.ts +++ b/ui-grid/ui-grid.d.ts @@ -832,6 +832,11 @@ declare namespace uiGrid { * @default false */ useExternalFiltering?: boolean; + /** + * Disables client side sorting. When true, handle the sortChanged event and do the sorting there + * @default false + */ + useExternalSorting?: boolean; /** * Default time in milliseconds to throttle scroll events to, defaults to 70ms * @default 70 @@ -3558,7 +3563,7 @@ declare namespace uiGrid { * Algorithm to use for sorting this column. Takes 'a' and 'b' parameters * like any normal sorting function with additional 'rowA', 'rowB', and 'direction' * parameters that are the row objects and the current direction of the sort - * respectively. + * respectively. */ sortingAlgorithm?: (a: any, b: any, rowA: IGridRowOf, rowB: IGridRowOf, direction: string) => number; /** Column width */ @@ -3793,7 +3798,7 @@ declare namespace uiGrid { * Algorithm to use for sorting this column. Takes 'a' and 'b' parameters * like any normal sorting function with additional 'rowA', 'rowB', and 'direction' * parameters that are the row objects and the current direction of the sort - * respectively. + * respectively. */ sortingAlgorithm?: (a: any, b: any, rowA: IGridRowOf, rowB: IGridRowOf, direction: string) => number; /** @@ -3871,6 +3876,10 @@ declare namespace uiGrid { term?: string; /** String that will be set to the .placeholder attribute */ placeholder?: string; + /** + * String that will be set to the .ariaLabel attribute. This is what is read as a label to screen reader users. + */ + ariaLabel?: string; /** * set this to true if you have defined a custom function in condition, * and your custom function doesn't require a term @@ -3895,7 +3904,7 @@ declare namespace uiGrid { * If set to true then the 'x' button that cancels/clears the filter will not be shown. * @default false */ - disableCancelButton?: boolean; + disableCancelFilterButton?: boolean; } export interface ISelectOption { value: number | string; diff --git a/umzug/umzug.d.ts b/umzug/umzug.d.ts index c15b165b4a..c02beed19f 100644 --- a/umzug/umzug.d.ts +++ b/umzug/umzug.d.ts @@ -3,7 +3,7 @@ // Definitions by: Ivan Drinchev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// declare module "umzug" { diff --git a/underscore/underscore-tests.ts b/underscore/underscore-tests.ts index 26718207d8..432b47ea04 100644 --- a/underscore/underscore-tests.ts +++ b/underscore/underscore-tests.ts @@ -166,6 +166,8 @@ _.some({ a: 'a', b: 'B', c: 'C', d: 'd' }, l => l === l.toUpperCase()); _.contains([1, 2, 3], 3); +_.contains([1, 2, 3], 3, 1); + _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); var stooges = [{ name: 'moe', age: 40 }, { name: 'larry', age: 50 }, { name: 'curly', age: 60 }]; @@ -278,10 +280,12 @@ _.defer(function () { alert('deferred'); }); var updatePosition = (param:string) => alert('updating position... Param: ' + param); var throttled = _.throttle(updatePosition, 100); $(window).scroll(throttled); +throttled.cancel(); var calculateLayout = (param:string) => alert('calculating layout... Param: ' + param); var lazyLayout = _.debounce(calculateLayout, 300); $(window).resize(lazyLayout); +lazyLayout.cancel(); var createApplication = (param:string) => alert('creating application... Param: ' + param); var initialize = _.once(createApplication); @@ -406,6 +410,7 @@ function useBoolean(arg: Boolean) {}; function useDate(arg: Date) {}; function useRegExp(arg: RegExp) {}; function useArray(arg: T[]) {}; +function useSymbol(arg: symbol) {}; var guardedType: {}; if(_.isElement(guardedType)) useElement(guardedType); @@ -419,6 +424,7 @@ if(_.isNumber(guardedType)) useNumber(guardedType); if(_.isBoolean(guardedType)) useBoolean(guardedType); if(_.isDate(guardedType)) useDate(guardedType); if(_.isRegExp(guardedType)) useRegExp(guardedType); +if(_.isSymbol(guardedType)) useSymbol(guardedType); /////////////////////////////////////////////////////////////////////////////////////// @@ -505,6 +511,12 @@ function chain_tests() { var firstVal: number = _.chain([1, 2, 3]) .first() .value(); + + let numberObjects = [{property: 'odd', value: 1}, {property: 'even', value: 2}, {property: 'even', value: 0}]; + let evenAndOddGroupedNumbers = _.chain(numberObjects) + .groupBy('property') + .mapObject((objects: any) => _.pluck(objects, 'value')) + .value(); // { odd: [1], even: [0, 2] } } var obj: { [k: string] : number } = { diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index 761d9bca06..d8d08a3b75 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Underscore 1.7.0 +// Type definitions for Underscore 1.8.3 // Project: http://underscorejs.org/ // Definitions by: Boris Yankov , Josh Baldwin , Christopher Currens // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -74,6 +74,10 @@ declare module _ { interface MemoObjectIterator { (prev: TResult, curr: T, key: string, list: Dictionary): TResult; } + + interface Cancelable { + cancel() : void; + } } interface UnderscoreStatic { @@ -459,6 +463,10 @@ interface UnderscoreStatic { iterator?: _.ObjectIterator, context?: any): boolean; + any( + list: _.List, + value: T): boolean; + /** * Returns true if the value is present in the list. Uses indexOf internally, * if list is an Array. @@ -468,7 +476,8 @@ interface UnderscoreStatic { **/ contains( list: _.List, - value: T): boolean; + value: T, + fromIndex?: number): boolean; /** * @see _.contains @@ -482,7 +491,8 @@ interface UnderscoreStatic { **/ include( list: _.Collection, - value: T): boolean; + value: T, + fromIndex?: number): boolean; /** * @see _.contains @@ -491,6 +501,21 @@ interface UnderscoreStatic { object: _.Dictionary, value: T): boolean; + /** + * @see _.contains + **/ + includes( + list: _.Collection, + value: T, + fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + includes( + object: _.Dictionary, + value: T): boolean; + /** * Calls the method named by methodName on each value in the list. Any extra arguments passed to * invoke will be forwarded on to the method invocation. @@ -1051,6 +1076,14 @@ interface UnderscoreStatic { **/ range(stop: number): number[]; + /** + * Split an **array** into several arrays containing **count** or less elements + * of initial array. + * @param array The array to split + * @param count The maximum size of the inner arrays. + */ + chunk(array: _.Collection, count: number): (_.Collection)[] + /************* * Functions * *************/ @@ -3429,7 +3462,7 @@ interface UnderscoreStatic { throttle( func: T, wait: number, - options?: _.ThrottleSettings): T; + options?: _.ThrottleSettings): T & _.Cancelable; /** * Creates and returns a new debounced version of the passed function that will postpone its execution @@ -3448,7 +3481,7 @@ interface UnderscoreStatic { debounce( fn: T, wait: number, - immediate?: boolean): T; + immediate?: boolean): T & _.Cancelable; /** * Creates a version of the function that can only be called one time. Repeated calls to the modified @@ -3459,6 +3492,12 @@ interface UnderscoreStatic { **/ once(fn: T): T; + /** + * Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) + * This accumulates the arguments passed into an array, after a given index. + **/ + restArgs(func: Function, starIndex?: number) : Function; + /** * Creates a version of the function that will only be run after first being called count times. Useful * for grouping asynchronous responses, where you want to be sure that all the async calls have finished, @@ -3620,6 +3659,14 @@ interface UnderscoreStatic { destination: any, ...source: any[]): any; + /** + * Returns the first key on an object that passes a predicate test. + * @param obj the object to search in + * @param predicate Predicate function. + * @param context `this` object in `iterator`, optional. + */ + findKey(obj: _.Dictionary, predicate: _.ObjectIterator, context? : any): T + /** * Return a copy of the object, filtered to only have values for the whitelisted keys * (or array of valid keys). @@ -3673,6 +3720,16 @@ interface UnderscoreStatic { object: any, ...defaults: any[]): any; + + /** + * Creates an object that inherits from the given prototype object. + * If additional properties are provided then they will be added to the + * created object. + * @param prototype The prototype that the returned object will inherit from. + * @param props Additional props added to the returned object. + **/ + create(prototype: any, props?: Object): any; + /** * Create a shallow-copied clone of the object. * Any nested objects or arrays will be copied by reference, not duplicated. @@ -3706,6 +3763,14 @@ interface UnderscoreStatic { **/ matches(attrs: T): _.ListIterator; + /** + * Returns a predicate function that will tell you if a passed in object contains all of the key/value properties present in attrs. + * @see _.matches + * @param attrs Object with key values pair + * @return Predicate function + **/ + matcher(attrs: T): _.ListIterator; + /** * Returns a function that will itself return the key property of any passed-in object. * @param key Property of the object. @@ -3756,7 +3821,7 @@ interface UnderscoreStatic { * @param object Check if this object is an Array. * @return True if `object` is an Array, otherwise false. **/ - isArray(object: any): object is []; + isArray(object: any): object is any[]; /** * Returns true if object is an Array. @@ -3765,6 +3830,13 @@ interface UnderscoreStatic { **/ isArray(object: any): object is T[]; + /** + * Returns true if object is a Symbol. + * @param object Check if this object is a Symbol. + * @return True if `object` is a Symbol, otherwise false. + **/ + isSymbol(object: any): object is symbol; + /** * Returns true if value is an Object. Note that JavaScript arrays and functions are objects, * while (normal) strings and numbers are not. @@ -3931,11 +4003,10 @@ interface UnderscoreStatic { * a property matcher, or a propetery accessor. * @param string|Function|Object value The value to iterate over, usually the key. * @param any context - * @param number argCount * @return Callback that can be applied to each element in a collection. **/ iteratee(value: string): Function; - iteratee(value: Function, context?: any, argCount?: number): Function; + iteratee(value: Function, context?: any): Function; iteratee(value: Object): Function; /** @@ -4174,13 +4245,19 @@ interface Underscore { * Wrapped type `any[]`. * @see _.contains **/ - contains(value: T): boolean; + contains(value: T, fromIndex? : number): boolean; /** * Alias for 'contains'. * @see contains **/ - include(value: T): boolean; + include(value: T, fromIndex? : number): boolean; + + /** + * Alias for 'contains'. + * @see contains + **/ + includes(value: T, fromIndex? : number): boolean; /** * Wrapped type `any[]`. @@ -4509,6 +4586,12 @@ interface Underscore { **/ range(): number[]; + /** + * Wrapped type any[][]. + * @see _.chunk + **/ + chunk(): any[][]; + /* *********** * Functions * ************ */ @@ -4558,13 +4641,13 @@ interface Underscore { * Wrapped type `Function`. * @see _.throttle **/ - throttle(wait: number, options?: _.ThrottleSettings): Function; + throttle(wait: number, options?: _.ThrottleSettings): Function & _.Cancelable; /** * Wrapped type `Function`. * @see _.debounce **/ - debounce(wait: number, immediate?: boolean): Function; + debounce(wait: number, immediate?: boolean): Function & _.Cancelable; /** * Wrapped type `Function`. @@ -4572,6 +4655,12 @@ interface Underscore { **/ once(): Function; + /** + * Wrapped type `Function`. + * @see _.once + **/ + restArgs(starIndex?: number) : Function; + /** * Wrapped type `number`. * @see _.after @@ -4653,6 +4742,12 @@ interface Underscore { **/ extend(...sources: any[]): any; + /** + * Wrapped type `object`. + * @see _.extend + **/ + findKey(predicate: _.ObjectIterator, context? : any): any + /** * Wrapped type `object`. * @see _.pick @@ -4675,6 +4770,12 @@ interface Underscore { **/ defaults(...defaults: any[]): any; + /** + * Wrapped type `any`. + * @see _.create + **/ + create(props?: Object): any; + /** * Wrapped type `any[]`. * @see _.clone @@ -4699,6 +4800,12 @@ interface Underscore { **/ matches(): _.ListIterator; + /** + * Wrapped type `any[]`. + * @see _.matcher + **/ + matcher(): _.ListIterator; + /** * Wrapped type `string`. * @see _.property @@ -4741,6 +4848,12 @@ interface Underscore { **/ isArray(): boolean; + /** + * Wrapped type `object`. + * @see _.isSymbol + **/ + isSymbol(): boolean; + /** * Wrapped type `object`. * @see _.isObject @@ -4868,7 +4981,7 @@ interface Underscore { * Wrapped type `string|Function|Object`. * @see _.iteratee **/ - iteratee(context?: any, argCount?: number): Function; + iteratee(context?: any): Function; /** * Wrapped type `string`. @@ -5070,7 +5183,7 @@ interface _Chain { * Wrapped type `any[]`. * @see _.all **/ - all(iterator?: _.ListIterator, context?: any): _Chain; + all(iterator?: _.ListIterator, context?: any): _ChainSingle; /** * @see _.all @@ -5092,13 +5205,19 @@ interface _Chain { * Wrapped type `any[]`. * @see _.contains **/ - contains(value: T): _ChainSingle; + contains(value: T, fromIndex?: number): _ChainSingle; /** * Alias for 'contains'. * @see contains **/ - include(value: T): _ChainSingle; + include(value: T, fromIndex?: number): _ChainSingle; + + /** + * Alias for 'contains'. + * @see contains + **/ + includes(value: T, fromIndex?: number): _ChainSingle; /** * Wrapped type `any[]`. @@ -5386,18 +5505,18 @@ interface _Chain { * Wrapped type `any[]`. * @see _.indexOf **/ - indexOf(value: T, isSorted?: boolean): _ChainSingle; + indexOf(value: T, isSorted?: boolean): _ChainSingle; /** * @see _.indexOf **/ - indexOf(value: T, startFrom: number): _ChainSingle; + indexOf(value: T, startFrom: number): _ChainSingle; /** * Wrapped type `any[]`. * @see _.lastIndexOf **/ - lastIndexOf(value: T, from?: number): _ChainSingle; + lastIndexOf(value: T, from?: number): _ChainSingle; /** * @see _.findIndex @@ -5413,7 +5532,7 @@ interface _Chain { * Wrapped type `any[]`. * @see _.sortedIndex **/ - sortedIndex(value: T, iterator?: (x: T) => any, context?: any): _Chain; + sortedIndex(value: T, iterator?: (x: T) => any, context?: any): _ChainSingle; /** * Wrapped type `number`. @@ -5427,6 +5546,12 @@ interface _Chain { **/ range(): _Chain; + /** + * Wrapped type `any[][]`. + * @see _.chunk + **/ + chunk(): _Chain; + /* *********** * Functions * ************ */ @@ -5490,6 +5615,12 @@ interface _Chain { **/ once(): _Chain; + /** + * Wrapped type `Function`. + * @see _.once + **/ + restArgs(startIndex? : number): _Chain; + /** * Wrapped type `number`. * @see _.after @@ -5571,6 +5702,12 @@ interface _Chain { **/ extend(...sources: any[]): _Chain; + /** + * Wrapped type `object`. + * @see _.extend + **/ + findKey(predicate: _.ObjectIterator, context? : any): _Chain + /** * Wrapped type `object`. * @see _.pick @@ -5593,6 +5730,12 @@ interface _Chain { **/ defaults(...defaults: any[]): _Chain; + /** + * Wrapped type `any`. + * @see _.create + **/ + create(props?: Object): _Chain; + /** * Wrapped type `any[]`. * @see _.clone @@ -5617,6 +5760,12 @@ interface _Chain { **/ matches(): _Chain; + /** + * Wrapped type `any[]`. + * @see _.matcher + **/ + matcher(): _Chain; + /** * Wrapped type `string`. * @see _.property @@ -5659,6 +5808,12 @@ interface _Chain { **/ isArray(): _Chain; + /** + * Wrapped type `object`. + * @see _.isSymbol + **/ + isSymbol(): _Chain; + /** * Wrapped type `object`. * @see _.isObject @@ -5786,7 +5941,7 @@ interface _Chain { * Wrapped type `string|Function|Object`. * @see _.iteratee **/ - iteratee(context?: any, argCount?: number): _Chain; + iteratee(context?: any): _Chain; /** * Wrapped type `string`. @@ -5920,6 +6075,7 @@ interface _ChainSingle { } interface _ChainOfArrays extends _Chain { flatten(shallow?: boolean): _Chain; + mapObject(fn: _.ListIterator): _ChainOfArrays; } declare var _: UnderscoreStatic; diff --git a/universal-router/universal-router-tests.ts b/universal-router/universal-router-tests.ts new file mode 100644 index 0000000000..922ca137ad --- /dev/null +++ b/universal-router/universal-router-tests.ts @@ -0,0 +1,99 @@ +/// + +import {ActionContext, Params, resolve } from "universal-router"; + +// Test 1 +const routes1 = [ + { + path: "/one", + action: () => "Page One" + }, + { + path: "/two", + action: () => "Page Two" + } +]; + +resolve(routes1, { path: "/one" }) + .then(result => console.log(result)); + +// Test 2 +const routes2 = [ + { + path: "/hello/:username", + action: (context: ActionContext) => `Welcome, ${context.params["username"]}!` + } +]; + +resolve(routes2, { path: "/hello/john" }) + .then(result => console.log(result)); + + +// Test 3 +const routes3 = [ + { + path: "/hello/:username", + action: (ctx: ActionContext, { username }: Params) => `Welcome, ${username}!` + } +]; + +resolve(routes3, { path: "/hello/john" }) + .then(result => console.log(result)); + + +// Test 4 +const routes4 = [ + { + path: "/hello", + action: () => new Promise(resolve => { + setTimeout(() => resolve("Welcome!"), 1000); + }) + } +]; + +resolve(routes4, { path: "/hello" }) + .then(result => console.log(result)); + +// Test 5 +const routes5 = [ + { + path: "/hello/:username", + async action(ctx: ActionContext, { username }: Params) { + const waitable = async (name: string) => { + console.log(`Welcome ${name}`); + } + await waitable(username); + } + } +]; + +resolve(routes5, { path: "/hello/john" }) + .then(result => console.log(result)); + +// Test 6 +const routes6 = [ + { path: "/one", action: () => "

      Page One

      " }, + { path: "/two", action: () => "

      Page Two

      " } +]; + +resolve(routes6, { path: "/one" }).then(result => { + document.body.innerHTML = result || "

      Not Found

      "; +}); + +// Test 7 +interface Render { + render: typeof render; +} + +const routes7 = [ + { path: "/one", action: ({ render: func }: ActionContext & Render) => func("

      Page One

      ") }, + { path: "/two", action: ({ render: func }: ActionContext & Render) => func("

      Page Two

      ") } +]; + +function render(component: string) { + return new Promise(resolve => { + console.log(`Rendering... ${component}`); + }); +} + +resolve>(routes7, { path: "/one", render }); diff --git a/universal-router/universal-router.d.ts b/universal-router/universal-router.d.ts new file mode 100644 index 0000000000..6acba5c179 --- /dev/null +++ b/universal-router/universal-router.d.ts @@ -0,0 +1,70 @@ +// Type definitions for universal-router +// Project: https://github.com/kriasoft/universal-router +// Definitions by: Jack Moore +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "universal-router" { + /** + * Params is a key/value object that represents extracted URL paramters. Each + * URL parameter resolves to a string. + */ + export interface Params { + [key: string]: string; + } + + /** + * Context represents the context that is passed as the second argument + * passed to resolve. By default, it only is require to contain a path, but + * can be extended by the way of generics. + */ + export interface Context { + path: string; + } + + /** + * ActionContext is similar to Context, with the exception of an added params + * object. ActionContext is passed as the first argument to the action + * function. + */ + export interface ActionContext extends Context { + params: Params; + } + + /** + * A Route is a singular route in your application. It contains a path, an + * action function, and optional children which are an array of Route. + * + * @template C User context that is made union with ActionContext. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + */ + export interface Route { + path: string; + action: (ctx: ActionContext & C, params: Params) => R | Promise | void; + children?: Routes; + } + + /** + * Routes in an array of type Route. + * @template C User context that is made union with ActionContext. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + */ + export type Routes = Route[]; + + /** + * Resolve function that is given routes and a path or context object. + * Returns a Promise that resolves to result of the action function of the + * matched route. + * + * @template C User context that is made union with Context. + * @template R Result that every action function resolves to. If the action + * returns a Promise, R can be the type the Promise resolves to. + * + * @param {Routes | Route} routes - Single route or array of routes. + * @param {string | String | Context & C} pathOrContext - path to resolve or + * context object that contains the path along with other data. + * @return {Promise} - Result of matched action function wrapped in a Promsie. + */ + export function resolve(routes: Routes | Route, pathOrContext: string | String | Context & C): Promise +} \ No newline at end of file diff --git a/utf8/utf8-tests.ts b/utf8/utf8-tests.ts new file mode 100644 index 0000000000..852311ea6c --- /dev/null +++ b/utf8/utf8-tests.ts @@ -0,0 +1,19 @@ +/// + +import * as utf8 from "utf8"; + +function test_encode(): void { + utf8.encode("\x49"); + utf8.encode("\uD800\uDC01"); +} + +function test_decode(): void { + utf8.decode("\xC2\x49"); + utf8.decode("\xF0\x90\x80\x81"); +} + +function test_version(): void { + if (typeof utf8.version === "string") { + console.log(utf8.version); + } +} diff --git a/utf8/utf8.d.ts b/utf8/utf8.d.ts new file mode 100644 index 0000000000..e9ee9d16b1 --- /dev/null +++ b/utf8/utf8.d.ts @@ -0,0 +1,24 @@ +// Type definitions for utf8 v2.1.1 +// Project: https://github.com/mathiasbynens/utf8.js +// Definitions by: Nick Zelei +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "utf8" { + /** + * A string representing the semantic version number. + */ + let version: string; + /** + * Encodes any given JavaScript string (string) as UTF-8, and returns the UTF-8-encoded version of the string. + * It throws an error if the input string contains a non-scalar value, i.e. a lone surrogate. + * @param {string} inputString + */ + function encode(inputString: string): string; + + /** + * Decodes any given UTF-8-encoded string (byteString) as UTF-8, and returns the UTF-8-decoded version of the string. + * It throws an error when malformed UTF-8 is detected. + * @param {string} byteString + */ + function decode(byteString: string): string; +} diff --git a/uuid/UUID-tests.ts b/uuid/UUID-tests.ts index ce40ddee15..990354525c 100644 --- a/uuid/UUID-tests.ts +++ b/uuid/UUID-tests.ts @@ -1,9 +1,5 @@ /// - -import UUID = require("UUID"); - - const uuid1: string = UUID.generate() const uuid2: UUID.UUID = UUID.genV4() const uuid3: UUID.UUID = UUID.genV1() diff --git a/uuid/UUID.d.ts b/uuid/UUID.d.ts index 164cf503c8..4526506120 100644 --- a/uuid/UUID.d.ts +++ b/uuid/UUID.d.ts @@ -3,7 +3,7 @@ // Definitions by: Jason Jarrett // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "UUID" { +declare module UUID { interface UUID { intFields: UUIDArray; diff --git a/v8-profiler/v8-profiler-tests.ts b/v8-profiler/v8-profiler-tests.ts new file mode 100644 index 0000000000..aebaee7a15 --- /dev/null +++ b/v8-profiler/v8-profiler-tests.ts @@ -0,0 +1,60 @@ +/// + +import * as fs from "fs"; +import * as profiler from "v8-profiler"; + +{ + var snapshot1 = profiler.takeSnapshot('1'); + var snapshot2 = profiler.takeSnapshot(); + profiler.deleteAllSnapshots(); +} +{ + profiler.startProfiling('', true); + setTimeout(function () { + var profile = profiler.stopProfiling(''); + profiler.deleteAllProfiles(); + }, 1000); +} +{ + var snapshot1 = profiler.takeSnapshot(); + var snapshot2 = profiler.takeSnapshot(); + + console.log(snapshot1.getHeader(), snapshot2.getHeader()); + + console.log(snapshot1.compare(snapshot2)); + + // Export snapshot to file file + snapshot1.export(function (error, result) { + fs.writeFileSync('snapshot1.json', result); + snapshot1.delete(); + }); + + // Export snapshot to file stream + snapshot2.export() + .pipe(fs.createWriteStream('snapshot2.json')) + .on('finish', snapshot2.delete); +} +{ + profiler.startProfiling('1', true); + var profile1 = profiler.stopProfiling(); + profiler.startProfiling('2', true); + var profile2 = profiler.stopProfiling(); + + console.log(snapshot1.getHeader(), snapshot2.getHeader()); + + profile1.export(function (error, result) { + fs.writeFileSync('profile1.json', result); + profile1.delete(); + }); + + profile2.export() + .pipe(fs.createWriteStream('profile2.json')) + .on('finish', function () { + profile2.delete(); + }); +} +{ + var a: profiler.Profile; + var b: profiler.Profiler; + var c: profiler.Snapshot; +} diff --git a/v8-profiler/v8-profiler.d.ts b/v8-profiler/v8-profiler.d.ts new file mode 100644 index 0000000000..ca22a60af7 --- /dev/null +++ b/v8-profiler/v8-profiler.d.ts @@ -0,0 +1,100 @@ +// Type definitions for v8-profiler +// Project: https://github.com/node-inspector/v8-profiler +// Definitions by: York Yao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* =================== USAGE =================== + import * as profiler from "v8-profiler"; + profiler.startProfiling(); + =============================================== */ + +/// + +declare module "v8-profiler" { + import * as fs from "fs"; + + namespace V8Profiler { + type Profiler = { + /** + * returns new HEAP Snapshot instance. + * name is optional argument, by default snapshot name will be constructed from his uid. + */ + takeSnapshot: (name?: string) => Snapshot; + deleteAllSnapshots: () => void; + /** + * start CPU profiling. + * name is optional argument, by default profile name will be constructed from his uid. + * recsamples is true by default. + */ + startProfiling: (name?: string, recsamples?: boolean) => void; + /** + * returns new CPU Profile instance. + * There is no strictly described behavior for usage without name argument. + */ + stopProfiling: (name?: string) => Profile; + /** + * Changes default CPU profiler sampling interval to the specified number of microseconds. + * Default interval is 1000us. + * This method must be called when there are no profiles being recorded. + * If called without arguments it resets interval to default. + */ + setSamplingInterval: (ms?: number) => void; + deleteAllProfiles: () => void; + }; + type Snapshot = { + /** + * provides short information about snapshot. + */ + getHeader: () => any; + /** + * creates HEAP diff for two snapshots. + */ + compare: (snapshot: Snapshot) => void; + /** + * removes snapshot from memory. + */ + delete: () => any; + /** + * provides simple export API for snapshot. + * callback(error, data) receives serialized snapshot as second argument. (Serialization is not equal to JSON.stringify result). + * If callback will not be passed, export returns transform stream. + */ + export(callback: (error: Error, data: any) => void): void; + /** + * provides simple export API for snapshot. + * callback(error, data) receives serialized snapshot as second argument. (Serialization is not equal to JSON.stringify result). + * If callback will not be passed, export returns transform stream. + */ + export(): fs.ReadStream; + /** + * low level serialization method. + * Look Snapshot.export source for usage example. + */ + serialize: Function; + }; + + type Profile = { + /** + * provides short information about profile. + */ + getHeader: () => any; + /** + * removes profile from memory. + */ + delete: () => any; + /** + * provides simple export API for profile. + * callback(error, data) receives serialized profile as second argument. (Serialization is equal to JSON.stringify result). + */ + export(callback: (error: Error, data: any) => void): void; + /** + * provides simple export API for profile. + * callback(error, data) receives serialized profile as second argument. (Serialization is equal to JSON.stringify result). + */ + export(): fs.ReadStream; + } + } + + var V8Profiler: V8Profiler.Profiler; + export = V8Profiler; +} diff --git a/validate.js/validate.js-tests.ts b/validate.js/validate.js-tests.ts new file mode 100644 index 0000000000..c9294de25d --- /dev/null +++ b/validate.js/validate.js-tests.ts @@ -0,0 +1,184 @@ +/// +import Validator = ValidateJS.Validator; +import Field = ValidateJS.Field; +import Constraints = ValidateJS.Constraints; + +let validator: Validator; +validator = {}; +validator = {message: 'test'}; +validator = {message: (value: any, attribute: any, validatorOptions: any, attributes: any, globalOptions: any) => 'test'}; + +let date: Validator.Date; +date = {}; +date = { + earliest: 'a', + latest: 'b', + notValid: 'c', + tooEarly: 'd', + tooLate: 'e', + message: 'test', +}; + +let dateTime: Validator.DateTime; +dateTime = {}; +dateTime = { + dateOnly: true, + earliest: 'a', + latest: 'b', + notValid: 'c', + tooEarly: 'd', + tooLate: 'e', + message: 'test', +}; + +let email: Validator.Email; +email = {}; +email = {message: 'test'}; + +let equality: Validator.Equality; +equality = {}; +equality = { + attribute: 'a', + comparator: (v1: any, v2: any) => true, + message: 'test', +}; + +let exclusion: Validator.Exclusion; +exclusion = { + within: ['a', 'b'], + message: 'test', +}; +exclusion = { + within: {a: 'b', c: 'd'}, +}; + +let format: Validator.Format; +format = { + pattern: 'a', + message: 'test', +}; +format = { + pattern: /a/g, +}; +format = { + pattern: new RegExp('a'), +}; + +let inclusion: Validator.Inclusion; +inclusion = { + within: ['a', 'b'], + message: 'test', +}; +inclusion = { + within: {a: 'b', c: 'd'}, +}; + +let _length: Validator.Length; +_length = {}; +_length = { + is: 1, + notValid: 'a', + wrongLength: 'b', + message: 'test', + tokenizer: (value: any[]) => [1, 2], +}; +_length = { + minimum: 2, + maximum: 4, + tooShort: 'a', + tooLong: 'b', + tokenizer: (value: string) => 'test', +}; + +let numericality: Validator.Numericality; +numericality = {}; +numericality = { + onlyInteger: true, + strict: true, + equalTo: 8, + divisibleBy: 4, + even: true, + notValid: 'a', + notInteger: 'b', + notEqualTo: 'c', + notDivisibleBy: 'd', + notEven: 'e', + message: 'test', +}; +numericality = { + greaterThan: 4, + lessThan: 10, + odd: true, + notGreaterThan: 'a', + notLessThan: 'b', + notOdd: 'c', +}; +numericality = { + greaterThanOrEqualTo: 4, + lessThanOrEqualTo: 7, + notGreaterThanOrEqualTo: 'a', + notLessThanOrEqualTo: 'b', +}; + +let presence: Validator.Presence; +presence = {}; +presence = {message: 'test'}; + +let url: Validator.Url; +url = {}; +url = { + schemes: ['a', /b/g, new RegExp('c')], + allowLocal: true, + message: 'test', +}; + +let field: Field; +field = {}; +field = { + date: {earliest: 'a'}, + datetime: {dateOnly: true}, + email: {message: 'test'}, + equality: {attribute: 'b'}, + exclusion: {within: ['c']}, + format: {pattern: 'd'}, + inclusion: {within: ['e']}, + length: {is: 4}, + numericality: {onlyInteger: true}, + presence: {message: 'test2'}, + url: {schemes: ['f']}, +}; +field = { + date: true, + datetime: true, + email: true, + equality: 'a', + exclusion: ['b'], + format: 'c', + inclusion: ['d'], + numericality: true, + presence: true, + url: true, +}; +field = { + format: /a/g, +}; +field = { + date: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({earliest: 'a'}), + datetime: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({dateOnly: true}), + email: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({message: 'test'}), + equality: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({attribute: 'b'}), + exclusion: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({within: ['c']}), + format: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({pattern: 'd'}), + inclusion: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({within: ['e']}), + length: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({is: 4}), + numericality: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({onlyInteger: true}), + presence: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({message: 'test2'}), + url: (value: any, attributes: any, attributeName: any, options: any, constraints: any) => ({schemes: ['f']}), +}; + +let constraints: Constraints; +constraints = {}; +constraints = { + a: {date: true}, + b: (value: any, attribute: any, attributeName: any, options: any, constraints: any) => ({datetime: true}), +}; \ No newline at end of file diff --git a/validate.js/validate.js.d.ts b/validate.js/validate.js.d.ts new file mode 100644 index 0000000000..35754e844c --- /dev/null +++ b/validate.js/validate.js.d.ts @@ -0,0 +1,109 @@ +// Type definitions for Validate.js +// Project: https://github.com/ansman/validate.js +// Definitions by: Travis Hill +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace ValidateJS { + + export interface Validator { + message?: string | ((value: any, attribute: any, validatorOptions: any, attributes: any, globalOptions: any) => string); + } + + namespace Validator { + + export interface Date extends Validator { + earliest?: string; + latest?: string; + + notValid?: string; + tooEarly?: string; + tooLate?: string; + } + + export interface DateTime extends Date { + dateOnly?: boolean; + } + + export interface Email extends Validator {} + + export interface Equality extends Validator { + attribute?: string; + comparator?: (v1: any, v2: any) => boolean; + } + + export interface Exclusion extends Validator { + within: any[] | {[key: string]: any}; + } + + export interface Format extends Validator { + pattern: string | RegExp; + flags?: string; + } + + export interface Inclusion extends Validator { + within: any[] | {[key: string]: any}; + } + + export interface Length extends Validator { + is?: number; + minimum?: number; + maximum?: number; + + notValid?: string; + tooLong?: string; + tooShort?: string; + wrongLength?: string; + + tokenizer?: (value: string | any[]) => string | any[]; + } + + export interface Numericality extends Validator { + onlyInteger?: boolean; + strict?: boolean; + greaterThan?: number; + greaterThanOrEqualTo?: number; + equalTo?: number; + lessThanOrEqualTo?: number; + lessThan?: number; + divisibleBy?: number; + odd?: boolean; + even?: boolean; + + notValid?: string; + notInteger?: string; + notGreaterThan?: string; + notGreaterThanOrEqualTo?: string; + notEqualTo?: string; + notLessThanOrEqualTo?: string; + notLessThan?: string; + notDivisibleBy?: string; + notOdd?: string; + notEven?: string; + } + + export interface Presence extends Validator {} + + export interface Url extends Validator { + schemes?: [string | RegExp]; + allowLocal?: boolean; + } + } + + export interface Field { + date?: Validator.Date | boolean | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Date); + datetime?: Validator.DateTime | boolean | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.DateTime); + email?: Validator.Email | boolean | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Email); + equality?: Validator.Equality | string | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Equality); + exclusion?: Validator.Exclusion | any[] | {[key: string]: any} | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Exclusion); + format?: Validator.Format | string | RegExp | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Format); + inclusion?: Validator.Inclusion | any[] | {[key: string]: any} | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Inclusion); + length?: Validator.Length | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Length); + numericality?: Validator.Numericality | boolean | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Numericality); + presence?: Validator.Presence | boolean | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Presence); + url?: Validator.Url | boolean | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Validator.Url); + } + + export interface Constraints { + [attribute: string]: Field | ((value: any, attributes: any, attributeName: any, options: any, constraints: any) => Field); + } +} diff --git a/validator/validator-tests.ts b/validator/validator-tests.ts index 8afabc2099..96d5bc761a 100644 --- a/validator/validator-tests.ts +++ b/validator/validator-tests.ts @@ -4,9 +4,9 @@ import * as validator from 'validator'; let any: any; -/************** - * Validators * - **************/ +// ************** +// * Validators * +// ************** { let result: boolean; @@ -16,7 +16,7 @@ let any: any; result = validator.equals('sample', 'sample'); result = validator.isAfter('sample'); - result = validator.isAfter('sample', new Date()); + result = validator.isAfter('sample', new Date().toString()); result = validator.isAlpha('sample'); @@ -27,7 +27,7 @@ let any: any; result = validator.isBase64('sample'); result = validator.isBefore('sample'); - result = validator.isBefore('sample', new Date()); + result = validator.isBefore('sample', new Date().toString()); result = validator.isBoolean('sample'); @@ -42,6 +42,8 @@ let any: any; result = validator.isCurrency('sample'); result = validator.isCurrency('sample', isCurrencyOptions); + result = validator.isDataURI('sample'); + result = validator.isDate('sample'); result = validator.isDecimal('sample'); @@ -95,6 +97,8 @@ let any: any; result = validator.isMACAddress('sample'); + result = validator.isMD5('sample'); + result = validator.isMobilePhone('sample', 'en-US'); result = validator.isMongoId('sample'); @@ -113,6 +117,7 @@ let any: any; result = validator.isUUID('sample'); result = validator.isUUID('sample', 5); + result = validator.isUUID('sample', 'all'); result = validator.isUppercase('sample'); @@ -125,9 +130,9 @@ let any: any; result = validator.matches('foobar', 'foo', 'i'); } -/************** - * Sanitizers * - **************/ +// ************** +// * Sanitizers * +// ************** { let result: string; @@ -136,6 +141,8 @@ let any: any; result = validator.escape('sample'); + result = validator.unescape('sample'); + result = validator.ltrim('sample'); result = validator.ltrim('sample', ' '); @@ -175,16 +182,14 @@ let any: any; { let result: string; - result = validator.toString(any); - result = validator.trim('sample'); result = validator.trim('sample', ' '); result = validator.whitelist('sample', 'abc'); } -/************** - * Extensions * - **************/ +// ************** +// * Extensions * +// ************** validator.extend<(str: string, options: {}) => boolean>('isTest', (str: any, options: {}) => !str); diff --git a/validator/validator.d.ts b/validator/validator.d.ts index 0edb5e885b..1ec4711828 100644 --- a/validator/validator.d.ts +++ b/validator/validator.d.ts @@ -1,14 +1,14 @@ -// Type definitions for validator.js v4.5.1 +// Type definitions for validator.js v5.7.0 // Project: https://github.com/chriso/validator.js -// Definitions by: tgfjt , Ilya Mochalov +// Definitions by: tgfjt , Ilya Mochalov , Ayman Nedjmeddine , Louy Alakkad // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace ValidatorJS { interface ValidatorStatic { - /************** - * Validators * - **************/ + // ************** + // * Validators * + // ************** // check if the string contains the seed. contains(str: string, elem: any): boolean; @@ -17,7 +17,7 @@ declare namespace ValidatorJS { equals(str: string, comparison: any): boolean; // check if the string is a date that's after the specified date (defaults to now). - isAfter(str: string, date?: Date): boolean; + isAfter(str: string, date?: string): boolean; // check if the string contains only letters (a-zA-Z). isAlpha(str: string): boolean; @@ -32,7 +32,7 @@ declare namespace ValidatorJS { isBase64(str: string): boolean; // check if the string is a date that's before the specified date. - isBefore(str: string, date?: Date): boolean; + isBefore(str: string, date?: string): boolean; // check if a string is a boolean. isBoolean(str: string): boolean; @@ -47,6 +47,9 @@ declare namespace ValidatorJS { // check if the string is a valid currency amount. isCurrency(str: string, options?: IsCurrencyOptions): boolean; + // check if the string is a data uri format (https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs) + isDataURI(str: string): boolean; + // check if the string is a date. isDate(str: string): boolean; @@ -110,8 +113,14 @@ declare namespace ValidatorJS { // check if the string is a MAC address. isMACAddress(str: string): boolean; - // check if the string is a mobile phone number, (locale is one of ['zh-CN', 'zh-TW', 'en-ZA', 'en-AU', 'en-HK', - // 'pt-PT', 'fr-FR', 'el-GR', 'en-GB', 'en-US', 'en-ZM', 'ru-RU', 'nb-NO', 'nn-NO', 'vi-VN', 'en-NZ', 'en-IN']). + // check if the string is a MD5 hash. + isMD5(str: string): boolean; + + // check if the string is a mobile phone number, (locale is one of + // ['ar-DZ', 'ar-SA', 'ar-SY', 'cs-CZ', 'de-DE', 'da-DK', 'el-GR', 'en-AU', 'en-GB', 'en-HK', + // 'en-IN', 'en-NZ', 'en-US', 'en-CA', 'en-ZA', 'en-ZM', 'es-ES', 'fi-FI', 'fr-FR', 'hu-HU', + // 'it-IT', 'ja-JP', 'ms-MY', 'nb-NO', 'nn-NO', 'pl-PL', 'pt-PT', 'ru-RU', 'sr-RS', 'tr-TR', + // 'vi-VN', 'zh-CN', 'zh-TW']). isMobilePhone(str: string, locale: string): boolean; // check if the string is a valid hex-encoded representation of a MongoDB ObjectId @@ -133,8 +142,8 @@ declare namespace ValidatorJS { // check if the string is an URL. isURL(str: string, options?: IsURLOptions): boolean; - // check if the string is a UUID (version 3, 4 or 5). - isUUID(str: string, version?: number): boolean; + // check if the string is a UUID. Must be one of ['3', '4', '5', 'all'], default is all. + isUUID(str: string, version?: string|number): boolean; // check if the string is uppercase. isUppercase(str: string): boolean; @@ -146,11 +155,11 @@ declare namespace ValidatorJS { isWhitelisted(str: string, chars: string|string[]): boolean; // check if string matches the pattern. - matches(str: string, pattern: any, modifiers?: string): boolean; + matches(str: string, pattern: RegExp|string, modifiers?: string): boolean; - /************** - * Sanitizers * - **************/ + // ************** + // * Sanitizers * + // ************** // remove characters that appear in the blacklist. The characters are used in a RegExp and so you will need // to escape some chars, e.g. blacklist(input, '\\[\\]'). @@ -159,6 +168,9 @@ declare namespace ValidatorJS { // replace <, >, &, ', " and / with HTML entities. escape(input: string): string; + // replaces HTML encoded entities with <, >, &, ', " and /. + unescape(input: string): string; + // trim characters from the left-side of the input. ltrim(input: any, chars?: string): string; @@ -185,9 +197,6 @@ declare namespace ValidatorJS { // convert the input to an integer, or NaN if the input is not an integer. toInt(input: any, radix?: number): number; // number or NaN - // convert the input to a string. - toString(input: any): string; - // trim characters (whitespace by default) from both sides of the input. trim(input: any, chars?: string): string; @@ -195,9 +204,9 @@ declare namespace ValidatorJS { // need to escape some chars, e.g. whitelist(input, '\\[\\]'). whitelist(input: string, chars: string): string; - /************** - * Extensions * - **************/ + // ************** + // * Extensions * + // ************** // add your own validators. // Note: that the first argument will be automatically coerced to a string. @@ -263,10 +272,11 @@ declare namespace ValidatorJS { protocols?: string[]; require_tld?: boolean; require_protocol?: boolean; + require_host: boolean; require_valid_protocol?: boolean; allow_underscores?: boolean; - host_whitelist?: boolean; - host_blacklist?: boolean; + host_whitelist?: (string|RegExp)[]; + host_blacklist?: (string|RegExp)[]; allow_trailing_dot?: boolean; allow_protocol_relative_urls?: boolean; } @@ -280,8 +290,7 @@ declare namespace ValidatorJS { } declare module "validator" { - let validator: ValidatorJS.ValidatorStatic; - namespace validator {} + const validator: ValidatorJS.ValidatorStatic; export = validator; } diff --git a/victory/victory-tests.tsx b/victory/victory-tests.tsx new file mode 100644 index 0000000000..6be99c875a --- /dev/null +++ b/victory/victory-tests.tsx @@ -0,0 +1,607 @@ +/// +/// + +import * as React from "react"; +import { + VictoryAnimation, + VictoryLabel, + AnimationStyle, + VictoryArea, + VictoryAxis, + VictoryStack, + VictoryBar, + VictoryLine, + VictoryChart, + VictoryScatter, + VictoryPie +} from "victory"; + +// VictoryAnimation test +let test = {}} +> + {(style: AnimationStyle) => + Hello! + } + + +// VictoryLabel test +test = 50} + textAnchor="middle" + verticalAnchor="start" + events={{ + onClick: () => {} + }} + text="test" + transform="scale(1.2)" + dx={10} + dy={10} + lineHeight={1.5}> + {"data viz \n is \n fun!"} + + +// VictoryArea test +test = ( + (data.yield + data.error)} + /> +); + +test = ( + { + return { + mutation: (props) => { + return { style: { fill: "orange" } } + } + } + }, + onMouseEnter: () => { + return [ + { + target: "labels", + mutation: (props) => { + return { text: "hey" } + } + } + ] + } + } + } + ]} + /> +); + +test = ( + + + + + +); + +test = ( + +); + +test = ( + x.getFullYear()}/> +); + +test = ( + +); + +// VictoryBar test +test = ( + +); + +test = ( + (data.yield + data.error)} + /> +); + +test = ( + +); + +test = ( + data.y > 2 ? + "red" : "blue" + } + }} + data={[ + {x: 1, y: 1}, + {x: 2, y: 2}, + {x: 3, y: 3}, + {x: 4, y: 2}, + {x: 5, y: 1} + ]} + /> +); + +test = ( + { + evt.stopPropagation(); + return [ + { + mutation: () => { + return {style: {fill: "orange", width: 20}}; + } + }, + { + target: "labels", + eventKey: 3, + mutation: () => { + return {text: "now click me"}; + } + } + ]; + } + } + }, { + target: "parent", + eventHandlers: { + onClick: () => { + return [ + { + target: "data", + mutation: () => { + return {style: {fill: "tomato", width: 10}}; + } + } + ]; + } + } + } + ]} + /> +); + + +// VictoryChart test +test = ( + + 0.5 * data.x * data.x}/> + +); + +test = ( + + + Math.sin(2 * Math.PI * data.x) + } + /> + + Math.cos(2 * Math.PI * data.x) + } + /> + +); + +test = ( + + + + data.y > 3 ? + "gold" : "orange" + } + }} + data={[ + {x: 1, y: 1}, + {x: 2, y: 2.5}, + {x: 3, y: 4}, + {x: 4, y: 2.5}, + {x: 5, y: 1}, + ]}/> + +); + +test = ( + + x.getFullYear()}/> + + +); + +// VictoryLine test +test = ( + +); + +test = ( + (data.yield + data.error)} + /> +); + +test = ( + +); + +// VictoryScatter test +test = ( + (data.yield + data.error)} + /> +); + +test = ( + +); + +// VictoryPie test +test = ( + data.pet + data.wild} + /> +); + +test = ( + +); + +test = ( + { + return [ + { + mutation: (props) => { + return { + style: {fill: "orange"} + }; + } + }, { + target: "labels", + eventKey: [1, 2, 3], + mutation: () => { + return {text: "KITTEN"}; + } + } + ]; + } + } + }]} + /> +); + +test = ( + + ({y: 0, label: " "}), + after: (datum) => + ({y: datum.y, label: "NEW"}) + } + }} + /> +); \ No newline at end of file diff --git a/victory/victory.d.ts b/victory/victory.d.ts new file mode 100644 index 0000000000..852fde5f7d --- /dev/null +++ b/victory/victory.d.ts @@ -0,0 +1,1494 @@ +// Type definitions for Victory 0.9.0 +// Project: https://github.com/FormidableLabs/victory +// Definitions by: Alexey Svetliakov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +declare module "victory" { + import * as React from "react"; + /** + * Single animation object to interpolate + */ + export type AnimationStyle = { [key: string ]: string | number }; + /** + * Animation styles to interpolate + */ + export type AnimationData = AnimationStyle | AnimationStyle[]; + export type AnimationEasing = + "back" | "backIn" | "backOut" | "backInOut" | "bounce" | "bounceIn" | "bounceOut" | + "bounceInOut" | "circle" | "circleIn" | "circleOut" | "circleInOut" | "linear" | + "linearIn" | "linearOut" | "linearInOut" | "cubic" | "cubicIn" | "cubicOut" | + "cubicInOut" | "elastic" | "elasticIn" | "elasticOut" | "elasticInOut" | "exp" | + "expIn" | "expOut" | "expInOut" | "poly" | "polyIn" | "polyOut" | "polyInOut" | + "quad" | "quadIn" | "quadOut" | "quadInOut" | "sin" | "sinIn" | "sinOut" | "sinInOut"; + + // Many victory components accept string or number or callback which returns string or number + type StringOrNumberOrCallback = string | number | { (): string | number }; + + /** + * Style interface used in components/themeing + */ + export interface VictoryStyleInterface { + parent?: React.CSSProperties; + data?: React.CSSProperties; + labels?: React.CSSProperties; + } + + export interface VictoryAnimationProps { + /** + * The child of should be a function that takes an object of tweened values and returns a component to render. + * @param style + */ + children?: (style: AnimationStyle) => React.ReactElement; + /** + * The number of milliseconds the animation should take to complete. + * @default 1000 + */ + duration?: number; + /** + * The easing prop specifies an easing function name to use for tweening. + * @default "quadInOut" + */ + easing?: AnimationEasing; + /** + * The delay prop specifies a delay in milliseconds before the animation begins. + * If multiple values are in the animation queue, it is the delay between each animation. + * @default 0 + */ + delay?: number; + /** + * The onEnd prop specifies a function to run when the animation ends. If multiple animations are in the queue, it is called after the last animation. + */ + onEnd?: () => void; + /** + * The data prop specifies the latest set of values to tween to. + * When this prop changes, VictoryAnimation will begin animating from the current value to the new value. + * When given an array of values, VictoryAnimation will use it as an animation queue. + * @default {} + */ + data?: AnimationData; + } + + /** + * VictoryAnimation animates prop changes for any React component. + * Just use a child function inside VictoryAnimation that accepts an object of tweened values and returns a component to render. + */ + export class VictoryAnimation extends React.Component {} + + /** + * Text anchor type + */ + type TextAnchorType = "start" | "middle" | "end" | "inherit"; + /** + * Vertical anchor type + */ + type VerticalAnchorType = "start" | "middle" | "end"; + + export interface VictoryLabelProps { + /** + * Specifies the angle to rotate the text by. + */ + angle?: string | number; + /** + * The capHeight prop defines a text metric for the font being used: the expected height of capital letters. + * This is necessary because of SVG, which (a) positions the *bottom* of the text at `y`, and (b) has no notion of line height. + * The value should ideally use the same units as `lineHeight` and `dy`, preferably ems. If given a unitless number, it is assumed to be ems. + * @default "0.71em" + */ + capHeight?: StringOrNumberOrCallback; + /** + * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine child text + */ + datum?: {}; + /** + * Labels that apply to an entire data series will recieve the entire series as `data` instead of an individual datum prop. + */ + data?: any[]; + /** + * The events prop attaches arbitrary event handlers to the label component. + * Event handlers are currently only called with their corresponding events. + */ + events?: React.DOMAttributes; + /** + * All Victory components will pass a text prop to their label component. + * This defines the content of the label when child nodes are absent. It will be ignored if children are provided. + */ + text?: StringOrNumberOrCallback; + /** + * The children of this component define the content of the label. + * This makes using the component similar to normal HTML spans or labels. strings, numbers, and functions of data / value are supported. + */ + children?: StringOrNumberOrCallback; + /** + * The lineHeight prop defines how much space a single line of text should take up. + * Note that SVG has no notion of line-height, so the positioning may differ slightly from what you would expect with CSS, + * but the result is similar: a roughly equal amount of extra space is distributed above and below the line of text. + * The value should ideally use the same units as `capHeight` and `dy`, preferably ems. + * If given a unitless number, it is assumed to be ems. + * @default 1 + */ + lineHeight?: StringOrNumberOrCallback; + /** + * The style prop applies CSS properties to the rendered `` element. + */ + style?: React.CSSProperties; + /** + * The textAnchor prop defines how the text is horizontally positioned relative to the given `x` and `y` coordinates. + */ + textAnchor?: TextAnchorType | { (): TextAnchorType }; + /** + * The verticalAnchor prop defines how the text is vertically positioned relative to the given `x` and `y` coordinates. + */ + verticalAnchor?: VerticalAnchorType | { (): VerticalAnchorType }; + /** + * The transform prop applies a transform to the rendered `` element. + * In addition to being a string, it can be an object containing transform definitions for easier authoring. + */ + transform?: string | {} | { (): string | {} }; + /** + * The x prop defines the x coordinate to use as a basis for horizontal positioning. + */ + x?: number; + /** + * The y prop defines the y coordinate to use as a basis for vertical positioning. + */ + y?: number; + /** + * The dx prop defines a horizontal shift from the `x` coordinate. + */ + dx?: StringOrNumberOrCallback; + /** + * The dy prop defines a vertical shift from the `y` coordinate. + * Since this component already accounts for `capHeight`, `lineHeight`, and `verticalAnchor`, this will usually not be necessary. + */ + dy?: StringOrNumberOrCallback; + } + + /** + * VictoryLabel is a text component that provides several enhancements over SVG’s element. + */ + export class VictoryLabel extends React.Component {} + + export interface VictoryContainerProps { + /** + * The style prop specifies styles for your VictoryContainer. Any valid inline style properties + * will be applied. Height and width should be specified via the height + * and width props, as they are used to calculate the alignment of + * components within the container. Styles from the child component will + * also be passed, if any exist. + * @examples {border: 1px solid red} + */ + style?: React.CSSProperties; + /** + * The height props specifies the height the svg viewBox of the container. + * This value should be given as a number of pixels. If no height prop + * is given, the height prop from the child component passed will be used. + */ + height?: number; + /** + * The width props specifies the width of the svg viewBox of the container + * This value should be given as a number of pixels. If no width prop + * is given, the width prop from the child component passed will be used. + */ + width?: number; + /** + * The events prop attaches arbitrary event handlers to the container component. + * Event handlers passed from other Victory components are called with their + * corresponding events as well as scale, style, width, height, and data when + * applicable. Use the invert method to convert event coordinate information to + * data. `scale.x.invert(evt.offsetX)`. + * @examples {{ onClick: (evt) => alert(`x: ${evt.clientX}, y: ${evt.clientY}`)}} + */ + events?: React.DOMAttributes; + /** + * The title prop specifies the title to be applied to the SVG to assist + * accessibility for screen readers. The more descriptive this title is, the more + * useful it will be. If no title prop is passed, it will default to Victory Chart. + * @example "Popularity of Dog Breeds by Percentage" + * @default "Victory Chart" + */ + title?: string; + /** + * The desc prop specifies the description of the chart/SVG to assist with + * accessibility for screen readers. The more info about the chart provided in + * the description, the more usable it will be for people using screen readers. + * This prop defaults to an empty string. + * @example "Golden retreivers make up 30%, Labs make up 25%, and other dog breeds are + * not represented above 5% each." + * @default "" + */ + desc?: string; + } + export class VictoryContainer extends React.Component {} + + // Note: Many SVG attributes are missed in CSSProperties interface + export interface VictoryThemeDefinition { + area?: VictoryStyleInterface; + axis?: { + axis: React.CSSProperties; + axisLabel: React.CSSProperties; + grid: React.CSSProperties; + ticks: React.CSSProperties; + tickLabels: React.CSSProperties; + }; + bar?: VictoryStyleInterface; + candlestick?: VictoryStyleInterface & { + props: { + width: number; + height: number; + candleColors: { + positive: string; + negative: string; + }; + }; + }; + line?: VictoryStyleInterface; + pie?: { + props: { + width: number; + height: number; + colorScale: string[]; + }; + style: VictoryStyleInterface; + }; + scatter?: VictoryStyleInterface; + props?: { + width: number; + height: number; + colorScale: string[]; + }; + } + + interface VictoryThemeInterface { + /** + * Default theme + */ + material: VictoryThemeDefinition; + } + /** + * Available themes + */ + export const VictoryTheme: VictoryThemeInterface; + + /** + * Animate object used in components + */ + export interface AnimatePropTypeInterface { + /** + * Animation duration + */ + duration: number; + /** + * Animation end callback + */ + onEnd?: () => void; + /** + * Animation exit transition configuration + */ + onExit?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + }; + /** + * Animation enter transition configuration + */ + onEnter?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + after?: (datum: any) => AnimationStyle; + }; + } + + /** + * Return value for eventHandlers values + */ + interface EventCallbackInterface { + /** + * Use only in: + * - VictoryChart + * - VictoryStack + */ + childName?: string; + target?: TTarget; + eventKey?: TEventKey; + /** + * Will be called with the calculated props for the individual selected element and result will override + * props of selected element via object assignment + * @param props + */ + mutation: (props: any) => any; + } + + export interface EventPropTypeInterface { + /** + * Use only in: + * - VictoryChart + * - VictoryStack + */ + childName?: string; + /** + * Targets may be any valid style namespace for a given component + */ + target: TTarget; + /** + * + */ + eventKey?: TEventKey; + /** + * Event handlers map. Keys are standard event names (such as onClick) and values are event callbacks + */ + eventHandlers: { + [key: string]: { + (event: React.SyntheticEvent): EventCallbackInterface } | + { (event: React.SyntheticEvent): EventCallbackInterface[] + } + }; + } + + /** + * Data domain type + */ + type DomainPropType = [number, number] | { + x: [number, number]; + y: [number, number]; + }; + /** + * Domain padding + */ + type DomainPaddingPropType = number | { + x?: number; + y?: number; + }; + + /** + * D3 scale function shape. Don't want to introduce typing dependency to d3 + */ + interface D3Scale { + domain: () => any; + range: () => any; + copy: () => any; + } + /** + * Acceptable scale types + */ + type ScalePropType = "linear" | "time" | "log" | "sqrt"; + + /** + * Category prop type + */ + type CategoryPropType = string[] | { + x: string[] + y: string[] + }; + + /** + * Data getter property type + */ + type DataGetterPropType = number | string | string[] | { (data: any): number | string | string[] }; + + type InterpolationPropType = "basis" | "basisClosed" | "basisOpen" | "bundle" | + "cardinal" | "cardinalClosed" | "cardinalOpen" | + "catmullRom" | "catmullRomClosed" | "catmullRomOpen" | + "linear" | "linearClosed" | "monotoneX" | "monotoneY" | + "natural" | "radial" | "step" | "stepAfter" | "stepBefore"; + + type ColorScalePropType = "greyscale" | "qualitative" | "heatmap" | "warm" | "cool" | "red" | "green" | "blue" | string[]; + /** + * Common properties + */ + interface VictoryCommonProps { + /** + * The animate prop specifies props for VictoryAnimation to use. + * The animate prop should also be used to specify enter and exit + * transition configurations with the `onExit` and `onEnter` namespaces respectively. + * @example + * {duration: 500, onExit: () => {}, onEnter: {duration: 500, before: () => ({y: 0})})} + */ + animate?: AnimatePropTypeInterface; + /** + * The name prop is used to reference a component instance when defining shared events. + */ + name?: string; + /** + * The height props specifies the height the svg viewBox of the chart container. + * This value should be given as a number of pixels + */ + height?: number; + /** + * The padding props specifies the amount of padding in number of pixels between + * the edge of the chart and any rendered child components. This prop can be given + * as a number or as an object with padding specified for top, bottom, left + * and right. + * @default 50 + */ + padding?: number | { + top?: number; + bottom?: number; + left?: number; + right?: number; + }; + /** + * The scale prop determines which scales your chart should use. This prop can be + * given as a string specifying a supported scale ("linear", "time", "log", "sqrt"), + * as a d3 scale function, or as an object with scales specified for x and y + * @example d3Scale.time(), {x: "linear", y: "log"} + * @default "linear" + */ + scale?: ScalePropType | D3Scale | { + x?: ScalePropType | D3Scale; + y?: ScalePropType | D3Scale; + }; + /** + * The standalone prop determines whether the component will render a standalone svg + * or a tag that will be included in an external svg. Set standalone to false to + * compose VictoryAxis with other components within an enclosing tag. + * @default true + */ + standalone?: boolean; + /** + * The width props specifies the width of the svg viewBox of the chart container + * This value should be given as a number of pixels + */ + width?: number; + /** + * The containerComponent prop takes an entire component which will be used to + * create a container element for standalone charts. + * The new element created from the passed containerComponent wil be provided with + * these props from VictoryArea: height, width, children + * (the chart itself) and style. Props that are not provided by the + * child chart component include title and desc, both of which + * are intended to add accessibility to Victory components. The more descriptive these props + * are, the more accessible your data will be for people using screen readers. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a dataComponent is + * not provided, VictoryArea will use the default VictoryContainer component. + * @example + * @default + */ + containerComponent?: React.ReactElement; + /** + * The theme prop takes a style object with nested data, labels, and parent objects. + * You can create this object yourself, or you can use a theme provided by Victory. + * When using VictoryArea as a solo component, implement the theme directly on + * VictoryArea. If you are wrapping VictoryArea in VictoryChart, VictoryStack, or + * VictoryGroup, please call the theme on the outermost wrapper component instead. + * @example theme={VictoryTheme.material} + * http://www.github.com/FormidableLabs/victory-core/tree/master/src/victory-theme/material.js + */ + theme?: VictoryThemeDefinition; + /** + * The groupComponent prop takes an entire component which will be used to + * create group elements for use within container elements. This prop defaults + * to a tag on web, and a react-native-svg tag on mobile + * @default + */ + groupComponent?: React.ReactElement; + } + + /** + * Common properties for all data components + */ + interface VictoryDatableProps { + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these arrays of values specified for x and y. If this prop is not set, + * categorical data will be plotted in the order it was given in the data array + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The data prop specifies the data to be plotted. Data should be in the form of an array + * of data points, or an array of arrays of data points for multiple datasets. + * Each data point may be any format you wish (depending on the `x` and `y` accessor props), + * but by default, an object with x and y properties is expected. + * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], + * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] + */ + data?: any[]; + /** + * The dataComponent prop takes an entire component which will be used to create an area. + * The new element created from the passed dataComponent will be provided with the + * following properties calculated by VictoryArea: a scale, style, events, interpolation, + * and an array of modified data objects (including x, y, and calculated y0 and y1). + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a dataComponent is + * not provided, VictoryArea will use its default Area component. + * @default + */ + dataComponent?: React.ReactElement; + /** + * The domain prop describes the range of values your chart will cover. This prop can be + * given as a array of the minimum and maximum expected values for your bar chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The x prop specifies how to access the X value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) + * @default "x" + */ + x?: DataGetterPropType; + /** + * The y prop specifies how to access the Y value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) + * @default "y" + */ + y?: DataGetterPropType; + } + + // Common labable interface + interface VictoryLabableProps { + /** + * The labelComponent prop takes in an entire label component which will be used + * to create a label for the area. The new element created from the passed labelComponent + * will be supplied with the following properties: x, y, index, data, verticalAnchor, + * textAnchor, angle, style, text, and events. any of these props may be overridden + * by passing in props to the supplied component, or modified or ignored within + * the custom component itself. If labelComponent is omitted, a new VictoryLabel + * will be created with props described above. This labelComponent prop should be used to + * provide a series label for VictoryArea. If individual labels are required for each + * data point, they should be created by composing VictoryArea with VictoryScatter + * @default + */ + labelComponent?: React.ReactElement; + } + + interface VictoryMultiLabeableProps extends VictoryLabableProps { + /** + * The labels prop defines labels that will appear above each bar in your chart. + * This prop should be given as an array of values or as a function of data. + * If given as an array, the number of elements in the array should be equal to + * the length of the data array. Labels may also be added directly to the data object + * like data={[{x: 1, y: 1, label: "first"}]}. + * @example ["spring", "summer", "fall", "winter"], (datum) => datum.title + */ + labels?: string[] | { (data: any): string }; + } + + interface VictorySingleLabableProps extends VictoryLabableProps { + /** + * The label prop defines the label that will appear at the edge of the area. + * This prop should be given a string or as a function of data. If individual + * labels are required for each data point, they should be created by composing + * VictoryArea with VictoryScatter + * @example: "Series 1", (data) => `${data.length} points` + */ + label?: string | { (data: any): string }; + } + + export interface VictoryAreaProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryArea events. + * Since VictoryArea only renders a single element, the eventKey property is not used. + * The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. an area), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @example + * events={[ + * { + * target: "data", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + *}} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", "all">[]; + /** + * The interpolation prop determines how data points should be connected when plotting a line + * @default "linear" + */ + interpolation?: InterpolationPropType; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + * @default 50 + */ + samples?: number; + /** + * The style prop specifies styles for your VictoryArea. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. + * @example {data: {fill: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + } + /** + * Draw area charts with React. VictoryArea is a composable component, so it doesn't include axes. + * Add VictoryArea as a child of VictoryChart for a complete chart. + */ + export class VictoryArea extends React.Component {} + + export interface VictoryAxisProps extends VictoryCommonProps { + /** + * The axisComponent prop takes in an entire component which will be used + * to create the axis line. The new element created from the passed axisComponent + * will be supplied with the following properties: x1, y1, x2, y2, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If an axisComponent + * is not supplied, VictoryAxis will render its default AxisLine component. + * @default + */ + axisComponent?: React.ReactElement; + /** + * The axisLabelComponent prop takes in an entire component which will be used + * to create the axis label. The new element created from the passed axisLabelComponent + * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, + * angle, transform, style and events. Any of these props may be overridden by + * passing in props to the supplied component, or modified or ignored within + * the custom component itself. If an axisLabelComponent is not supplied, a new + * VictoryLabel will be created with props described above + * @default + */ + axisLabelComponent?: React.ReactElement; + /** + * This prop specifies whether a given axis is intended to cross another axis. + */ + crossAxis?: boolean; + /** + * The dependentAxis prop specifies whether the axis corresponds to the + * dependent variable (usually y). This prop is useful when composing axis + * with other components to form a chart. + */ + dependentAxis?: boolean; + /** + * The domain prop describes the range of values your axis will include. This prop should be + * given as a array of the minimum and maximum expected values for your axis. + * If this value is not given it will be calculated based on the scale or tickValues. + * @examples [-1, 1] + */ + domain?: DomainPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "axis", "axisLabel", "ticks", "tickLabels", and "grid" are + * all valid targets for VictoryAxis events. The eventKey may optionally be used to select a + * single element by index rather than an entire set. The eventHandlers object + * should be given as an object whose keys are standard event names (i.e. onClick) + * and whose values are event callbacks. The return value of an event handler + * be used to modify other elemnts. The return value should be given as an object or + * an array of objects with optional target and eventKey keys, and a mutation + * key whose value is a function. The target and eventKey keys will default to those + * corresponding to the element the event handler was attached to. The mutation + * function will be called with the calculated props for the individual selected + * element (i.e. a single tick), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "grid", + * eventKey: 2, + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {stroke: "orange"})}; + * } + * }, { + * target: "tickLabels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + *}} + */ + events?: EventPropTypeInterface<"axis" | "axisLabel" | "grid" | "ticks" | "tickLabels" | "parent", number | string>[]; + /** + * The gridComponent prop takes in an entire component which will be used + * to create grid lines. The new element created from the passed gridComponent + * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a gridComponent + * is not supplied, VictoryAxis will render its default GridLine component. + * @default + */ + gridComponent?: React.ReactElement; + /** + * The label prop defines the label that will appear along the axis. This + * prop should be given as a value or an entire, HTML-complete label + * component. If a label component is given, it will be cloned. The new + * element's properties x, y, textAnchor, verticalAnchor, and transform + * will have defaults provided by the axis; styles filled out with + * defaults provided by the axis, and overrides from the label component. + * If a value is given, a new VictoryLabel will be created with props and + * styles from the axis. + */ + label?: any; + /** + * This value describes how far from the "edge" of its permitted area each axis + * will be set back in the x-direction. If this prop is not given, + * the offset is calculated based on font size, axis orientation, and label padding. + */ + offsetX?: number; + /** + * This value describes how far from the "edge" of its permitted area each axis + * will be set back in the y-direction. If this prop is not given, + * the offset is calculated based on font size, axis orientation, and label padding. + */ + offsetY?: number; + /** + * The orientation prop specifies the position and orientation of your axis. + */ + orientation?: "top" | "bottom" | "left" | "right"; + /** + * The style prop specifies styles for your VictoryAxis. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. + * @example {axis: {stroke: "#756f6a"}, grid: {stroke: "grey"}, ticks: {stroke: "grey"}, + * tickLabels: {fontSize: 10, padding: 5}, axisLabel: {fontSize: 16, padding: 20}} + */ + style?: { + parent?: React.CSSProperties; + axis?: React.CSSProperties; + axisLabel?: React.CSSProperties; + grid?: React.CSSProperties; + ticks?: React.CSSProperties; + tickLabels?: React.CSSProperties; + }; + /** + * The tickComponent prop takes in an entire component which will be used + * to create tick lines. The new element created from the passed tickComponent + * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a tickComponent + * is not supplied, VictoryAxis will render its default Tick component. + * @default + */ + tickComponent?: React.ReactElement; + /** + * The tickCount prop specifies approximately how many ticks should be drawn on the axis if + * tickValues are not explicitly provided. This value is calculated by d3 scale and + * prioritizes returning "nice" values and evenly spaced ticks over an exact number of ticks. + * If you need an exact number of ticks, please specify them via the tickValues prop. + * This prop must have a value greater than zero. + * @default 5 + */ + tickCount?: number; + /** + * The tickLabelComponent prop takes in an entire component which will be used + * to create the tick labels. The new element created from the passed tickLabelComponent + * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, + * angle, tick, style and events. Any of these props may be overridden by + * passing in props to the supplied component, or modified or ignored within + * the custom component itself. If an tickLabelComponent is not supplied, a new + * VictoryLabel will be created with props described above + * @default + */ + tickLabelComponent?: React.ReactElement; + /** + * The tickFormat prop specifies how tick values should be expressed visually. + * tickFormat can be given as a function to be applied to every tickValue, or as + * an array of display values for each tickValue. + * @example d3.time.format("%Y"), (x) => x.toPrecision(2), ["first", "second", "third"] + */ + tickFormat?: any[] | { (data: any): string | number }; + /** + * The tickValues prop explicitly specifies which tick values to draw on the axis. + * @example ["apples", "bananas", "oranges"], [2, 4, 6, 8] + */ + tickValues?: any[] + } + + /** + * VictoryAxis draws an SVG chart axis with React. + * Styles and data can be customized by passing in your own values as properties to the component. + * Data changes are animated with VictoryAnimation. + */ + export class VictoryAxis extends React.Component {} + + export interface VictoryBarProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryBar events. + * The eventKey may optionally be used to select a single element by index rather than an entire + * set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @example + * events={[ + * { + * target: "data", + * eventKey: "thisOne", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: "theOtherOne", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: "theOtherOne", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + *}} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The style prop specifies styles for your VictoryBar. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. In addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + } + /** + * Draw SVG bar charts with React. VictoryBar is a composable component, so it doesn't include axes + * Check out VictoryChart for complete bar charts and more. + */ + export class VictoryBar extends React.Component {} + + export interface VictoryChartProps extends VictoryCommonProps { + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryChart, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + *}} + */ + events?: EventPropTypeInterface[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The style prop specifies styles for your chart. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. + * @example {border: "1px solid #ccc", margin: "2%", maxWidth: "40%"} + */ + style?: React.CSSProperties; + } + /** + * A flexible charting component for React. + * VictoryChart composes other Victory components into reusable charts. + * Acting as a coordinator rather than a stand-alone component, VictoryChart reconciles props such as domain and scale for child components, + * and provides a set of sensible defaults. This component works with: + * - VictoryAxis + * - VictoryLine + * - VictoryScatter + * - VictoryBar + */ + export class VictoryChart extends React.Component {} + + export interface VictoryGroupProps extends VictoryCommonProps, VictoryMultiLabeableProps { + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these values for x and y. When categories are not given as an object + * When this prop is set on a wrapper component, it will dictate the categories of + * its the children. If this prop is not set, any categories on child component + * or categorical data, will be merged to create a shared set of categories. + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The colorScale prop is an optional prop that defines the color scale the chart's bars + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryBar will automatically assign + * values from this color scale to the bars unless colors are explicitly provided in the + * `dataAttributes` prop. + */ + colorScale?: ColorScalePropType; + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @examples: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryGroup, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + *}} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The style prop specifies styles for your grouped chart. These styles will be + * applied to all grouped children + */ + style?: VictoryStyleInterface; + } + export class VictoryGroup extends React.Component {} + + export interface VictoryLineProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryLine events. + * Since VictoryLine only renders a single element, the eventKey property is not used. + * The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a line), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {stroke: "orange"})}; + * } + * }, { + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + *}} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; + /** + * The interpolation prop determines how data points should be connected + * when plotting a line + */ + interpolation?: InterpolationPropType; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + */ + samples?: number; + /** + * The style prop specifies styles for your VictoryLine. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. in addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @examples{data: {stroke: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + } + /** + * VictoryLine creates a line based on data. VictoryLine is a composable component, so it does not include an axis. + * Check out VictoryChart for easy to use line charts and more. + */ + export class VictoryLine extends React.Component {} + + type ScatterSymbolType = "circle" | "diamond" | "plus" | "square" | "star" | "triangleDown" | "triangleUp"; + export interface VictoryScatterProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { + /** + * The bubbleProperty prop indicates which property of the data object should be used + * to scale data points in a bubble chart + */ + bubbleProperty?: string; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryScatter + * events. The eventKey may optionally be used to select a single element by index rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * eventKey: "thisOne", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: "theOtherOne", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: "theOtherOne", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + *}} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The maxBubbleSize prop sets an upper limit for scaling data points in a bubble chart + */ + maxBubbleSize?: number; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + */ + samples?: number; + /** + * The size prop determines how to scale each data point + */ + size?: number | { (data: any): number }; + /** + * The style prop specifies styles for your VictoryScatter. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. In addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @example {data: {fill: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + /** + * The symbol prop determines which symbol should be drawn to represent data points. + */ + symbol?: ScatterSymbolType | { (data: any): ScatterSymbolType }; + } + /** + * VictoryScatter creates a scatter of points from data. VictoryScatter is a composable component, so it does not include an axis. + * Check out VictoryChart for easy to use scatter plots and more. + */ + export class VictoryScatter extends React.Component {} + + export interface VictoryStackProps extends VictoryCommonProps, VictoryMultiLabeableProps { + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these values for x and y. When categories are not given as an object + * When this prop is set on a wrapper component, it will dictate the categories of + * its the children. If this prop is not set, any categories on child component + * or catigorical data, will be merged to create a shared set of categories. + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The colorScale prop is an optional prop that defines the color scale the chart's bars + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryBar will automatically assign + * values from this color scale to the bars unless colors are explicitly provided in the + * `dataAttributes` prop. + */ + colorScale?: ColorScalePropType; + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryStack, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + *}} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The style prop specifies styles for your grouped chart. These styles will be + * applied to all grouped children + */ + style?: VictoryStyleInterface; + /** + * The xOffset prop is used for grouping stacks of bars. This prop will be set + * by the VictoryGroup component wrapper, or can be set manually. + */ + xOffset?: number; + } + export class VictoryStack extends React.Component {} + + export interface VictoryPieProps extends VictoryCommonProps, VictoryMultiLabeableProps { + /** + * The colorScale prop is an optional prop that defines the color scale the pie + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryPie will automatically assign + * values from this color scale to the pie slices unless colors are explicitly provided in the + * data object + */ + colorScale?: ColorScalePropType; + /** + * The data prop specifies the data to be plotted, + * where data X-value is the slice label (string or number), + * and Y-value is the corresponding number value represented by the slice + * Data should be in the form of an array of data points. + * Each data point may be any format you wish (depending on the `x` and `y` accessor props), + * but by default, an object with x and y properties is expected. + * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], + * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] + */ + data?: any[]; + /** + * The dataComponent prop takes an entire, HTML-complete data component which will be used to + * create slices for each datum in the pie chart. The new element created from the passed + * dataComponent will have the property datum set by the pie chart for the point it renders; + * properties style and pathFunction calculated by VictoryPie; an index property set + * corresponding to the location of the datum in the data provided to the pie; events bound to + * the VictoryPie; and the d3 compatible slice object. + * If a dataComponent is not provided, VictoryPie's Slice component will be used. + */ + dataComponent?: React.ReactElement; + /** + * The overall end angle of the pie in degrees. This prop is used in conjunction with + * startAngle to create a pie that spans only a segment of a circle. + */ + endAngle?: number; + /** + * The event prop takes an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryPie + * events. The eventKey may optionally be used to select a single element by index rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * eventKey: 1, + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: 2, + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: 2, + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + *}} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * When creating a donut chart, this prop determines the number of pixels between + * the center of the chart and the inner edge of a donut. When this prop is set to zero + * a regular pie chart is rendered. + */ + innerRadius?: number; + /** + * Set the cornerRadius for every dataComponent (Slice by default) within VictoryPie + */ + cornerRadius?: number; + /** + * The padAngle prop determines the amount of separation between adjacent data slices + * in number of degrees + */ + padAngle?: number; + /** + * The overall start angle of the pie in degrees. This prop is used in conjunction with + * endAngle to create a pie that spans only a segment of a circle. + */ + startAngle?: number; + /** + * The style prop specifies styles for your pie. VictoryPie relies on Radium, + * so valid Radium style objects should work for this prop. Height, width, and + * padding should be specified via the height, width, and padding props. + * @example {data: {stroke: "black"}, label: {fontSize: 10}} + */ + style?: VictoryStyleInterface; + /** + * The x prop specifies how to access the X value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) + */ + x?: DataGetterPropType; + /** + * The y prop specifies how to access the Y value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) + */ + y?: DataGetterPropType; + } + /** + * victory-pie draws an SVG pie or donut chart with React. + * Styles and data can be customized by passing in your own values as properties to the component. + * Data changes are animated with VictoryAnimation. + */ + export class VictoryPie extends React.Component {} +} diff --git a/videojs/videojs.d.ts b/videojs/videojs.d.ts index d0da6b10db..3ac6007daf 100644 --- a/videojs/videojs.d.ts +++ b/videojs/videojs.d.ts @@ -44,10 +44,15 @@ interface VideoJSPlayer { size(width: number, height: number): VideoJSPlayer; requestFullScreen(): VideoJSPlayer; cancelFullScreen(): VideoJSPlayer; - ready(callback: () => void ): void; - on(eventName: string, callback: () => void ): void; + ready(callback: () => void ): VideoJSPlayer; + on(eventName: string, callback: (eventObject: Event) => void ): void; off(eventName: string, callback: () => void ): void; + off(eventName: string): void; + off(): void; dispose(): void; + addRemoteTextTrack(options : {}) : HTMLTrackElement; + removeRemoteTextTrack(track : HTMLTrackElement) : void; + poster(val?: string) : string|VideoJSPlayer; } interface VideoJSStatic { diff --git a/vso-node-api/vso-node-api.d.ts b/vso-node-api/vso-node-api.d.ts index 55fd857703..846cbf270a 100644 --- a/vso-node-api/vso-node-api.d.ts +++ b/vso-node-api/vso-node-api.d.ts @@ -12714,7 +12714,8 @@ declare module 'vso-node-api/WorkItemTrackingApi' { getWorkItem(id: number, fields: string[], asOf: Date, expand: WorkItemTrackingInterfaces.WorkItemExpand, onResult: (err: any, statusCode: number, workItem: WorkItemTrackingInterfaces.WorkItem) => void): void; getWorkItems(ids: number[], fields: string[], asOf: Date, expand: WorkItemTrackingInterfaces.WorkItemExpand, onResult: (err: any, statusCode: number, workItems: WorkItemTrackingInterfaces.WorkItem[]) => void): void; updateWorkItem(customHeaders: any, document: VSSInterfaces.JsonPatchDocument, id: number, validateOnly: boolean, bypassRules: boolean, onResult: (err: any, statusCode: number, workItem: WorkItemTrackingInterfaces.WorkItem) => void): void; - getWorkItemTemplate(project: string, type: string, fields: string, asOf: Date, expand: WorkItemTrackingInterfaces.WorkItemExpand, onResult: (err: any, statusCode: number, workItem: WorkItemTrackingInterfaces.WorkItem) => void): void; + createWorkItem(customHeaders: any, document: VSSInterfaces.JsonPatchDocument, project: string, type: string, validateOnly: boolean, bypassRules: boolean, onResult: (err: any, statusCode: number, workItem: WorkItemTrackingInterfaces.WorkItem) => void): void; + getWorkItemTemplate(project: string, type: string, fields: string, asOf: Date, expand: WorkItemTrackingInterfaces.WorkItemExpand, onResult: (err: any, statusCode: number, workItem: WorkItemTrackingInterfaces.WorkItem) => void): void; updateWorkItemTemplate(customHeaders: any, document: VSSInterfaces.JsonPatchDocument, project: string, type: string, validateOnly: boolean, bypassRules: boolean, onResult: (err: any, statusCode: number, workItem: WorkItemTrackingInterfaces.WorkItem) => void): void; getWorkItemTypeCategories(project: string, onResult: (err: any, statusCode: number, workItemTypeCategories: WorkItemTrackingInterfaces.WorkItemTypeCategory[]) => void): void; getWorkItemTypeCategory(project: string, category: string, onResult: (err: any, statusCode: number, workItemTypeCategorie: WorkItemTrackingInterfaces.WorkItemTypeCategory) => void): void; @@ -12752,7 +12753,8 @@ declare module 'vso-node-api/WorkItemTrackingApi' { getWorkItem(id: number, fields?: string[], asOf?: Date, expand?: WorkItemTrackingInterfaces.WorkItemExpand): Q.Promise; getWorkItems(ids: number[], fields?: string[], asOf?: Date, expand?: WorkItemTrackingInterfaces.WorkItemExpand): Q.Promise; updateWorkItem(customHeaders: any, document: VSSInterfaces.JsonPatchDocument, id: number, validateOnly?: boolean, bypassRules?: boolean): Q.Promise; - getWorkItemTemplate(project: string, type: string, fields?: string, asOf?: Date, expand?: WorkItemTrackingInterfaces.WorkItemExpand): Q.Promise; + createWorkItem(customHeaders: any, document: VSSInterfaces.JsonPatchDocument, project: string, type: string, validateOnly?: boolean, bypassRules?: boolean): Q.Promise; + getWorkItemTemplate(project: string, type: string, fields?: string, asOf?: Date, expand?: WorkItemTrackingInterfaces.WorkItemExpand): Q.Promise; updateWorkItemTemplate(customHeaders: any, document: VSSInterfaces.JsonPatchDocument, project: string, type: string, validateOnly?: boolean, bypassRules?: boolean): Q.Promise; getWorkItemTypeCategories(project: string): Q.Promise; getWorkItemTypeCategory(project: string, category: string): Q.Promise; @@ -13027,7 +13029,16 @@ declare module 'vso-node-api/WorkItemTrackingApi' { * @param {WorkItemTrackingInterfaces.WorkItemExpand} expand * @param onResult callback function with the resulting WorkItemTrackingInterfaces.WorkItem */ - getWorkItemTemplate(project: string, type: string, fields: string, asOf: Date, expand: WorkItemTrackingInterfaces.WorkItemExpand, onResult: (err: any, statusCode: number, workItem: WorkItemTrackingInterfaces.WorkItem) => void): void; + getWorkItemTemplate(project: string, type: string, fields: string, asOf: Date, expand: WorkItemTrackingInterfaces.WorkItemExpand, onResult: (err: any, statusCode: number, workItem: WorkItemTrackingInterfaces.WorkItem) => void): void; + /** + * @param {VSSInterfaces.JsonPatchDocument} document + * @param {string} project - Project ID or project name + * @param {string} type + * @param {boolean} validateOnly + * @param {boolean} bypassRules + * @param onResult callback function with the resulting WorkItemTrackingInterfaces.WorkItem + */ + createWorkItem(customHeaders: any, document: VSSInterfaces.JsonPatchDocument, project: string, type: string, validateOnly: boolean, bypassRules: boolean, onResult: (err: any, statusCode: number, workItem: WorkItemTrackingInterfaces.WorkItem) => void): void; /** * @param {VSSInterfaces.JsonPatchDocument} document * @param {string} project - Project ID or project name @@ -13282,7 +13293,15 @@ declare module 'vso-node-api/WorkItemTrackingApi' { * @param {boolean} bypassRules */ updateWorkItem(customHeaders: any, document: VSSInterfaces.JsonPatchDocument, id: number, validateOnly?: boolean, bypassRules?: boolean): Q.Promise; - /** + /** + * @param {VSSInterfaces.JsonPatchDocument} document + * @param {string} project - Project ID or project name + * @param {string} type + * @param {boolean} validateOnly + * @param {boolean} bypassRules + */ + createWorkItem(customHeaders: any, document: VSSInterfaces.JsonPatchDocument, project: string, type: string, validateOnly?: boolean, bypassRules?: boolean): Q.Promise; + /** * Returns a single work item from a template * * @param {string} project - Project ID or project name @@ -13433,4 +13452,4 @@ declare module 'vso-node-api/WebApi' { getQWorkItemTrackingApi(serverUrl?: string, handlers?: VsoBaseInterfaces.IRequestHandler[]): workitemtrackingm.IQWorkItemTrackingApi; } -} +} \ No newline at end of file diff --git a/vue-resource/vue-resource-tests.ts b/vue-resource/vue-resource-tests.ts index 28ae5abe09..8c6167da60 100644 --- a/vue-resource/vue-resource-tests.ts +++ b/vue-resource/vue-resource-tests.ts @@ -29,6 +29,9 @@ class App extends Vue { response.headers('expires'); this.$set('someData', response.data); + this.$set('someJsonData', response.json()); + this.$set('someTextData', response.text()); + this.$set('someBlobData', response.blob()); }); var resource = this.$resource('someItem/{id}'); diff --git a/vue-resource/vue-resource.d.ts b/vue-resource/vue-resource.d.ts index 2276634e68..4226112aa9 100644 --- a/vue-resource/vue-resource.d.ts +++ b/vue-resource/vue-resource.d.ts @@ -1,4 +1,4 @@ -// Type definitions for vue-resoure 0.7.0 +// Type definitions for vue-resoure 0.9.3 // Project: https://github.com/vuejs/vue-resource // Definitions by: kaorun343 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -15,7 +15,7 @@ declare namespace vuejs { common?: { [key: string]: string }; custom?: { [key: string]: string }; [key: string]: any; - } + } interface HttpResponse { data: Object; @@ -23,21 +23,22 @@ declare namespace vuejs { status: number; statusText: string; headers: Function; + text():string; + json():any; + blob():Blob; } interface HttpOptions { url?: string; method?: string; - data?: any; + body?: any; params?: any; headers?: any; - beforeSend?(request: any): any; + before?(request: any): any; + progress?(event: any): any; + credentials?:boolean; emulateHTTP?: boolean; emulateJSON?: boolean; - xhr?: any; - upload?: any; - jsonp?: string; - timeout?: string; } interface $http { diff --git a/vue/vue-tests.ts b/vue/vue-tests.ts index c8612ca870..48d8d91683 100644 --- a/vue/vue-tests.ts +++ b/vue/vue-tests.ts @@ -30,9 +30,20 @@ namespace TestGlobalAPI { twoWay: true, acceptStatement: true, priority: 1, + terminal: true, count: 30 }); - Vue.directive("my-directive", () => {}); + Vue.directive("my-directive", function() { + const d = this as vuejs.Directive; + d.el; + d.vm; + d.expression; + d.arg; + d.name; + d.modifiers; + d.descriptor; + d.params; + }); var myDirective = Vue.directive("my-directive"); var elementDirective = Vue.elementDirective("element-directive"); Vue.elementDirective("element-directive", elementDirective); diff --git a/vue/vue.d.ts b/vue/vue.d.ts index faee50af8f..a335ee63d1 100644 --- a/vue/vue.d.ts +++ b/vue/vue.d.ts @@ -38,10 +38,22 @@ declare namespace vuejs { deep?: boolean; twoWay?: boolean; acceptStatement?: boolean; + terminal?: boolean; priority?: number; [key: string]: any; } + interface Directive { + el: HTMLElement; + vm: Vue; + expression: string; + arg?: string; + name: string; + modifiers: { [key: string]: boolean }; + descriptor: any; + params?: { [key: string]: any }; + } + interface FilterOption { read?: Function; write?: Function; diff --git a/wallabyjs/wallabyjs-tests.ts b/wallabyjs/wallabyjs-tests.ts new file mode 100644 index 0000000000..132984d039 --- /dev/null +++ b/wallabyjs/wallabyjs-tests.ts @@ -0,0 +1,40 @@ +/// + +import * as wallabyjs from 'wallabyjs'; + +export class WallabyConfig implements wallabyjs.IWallabyConfig { + + public files: string[] = [ + 'src/**/*.ts', + '!src/**/*.spec.ts' + ]; + + public tests: string[] = [ + 'src/**/*.spec.ts' + ]; + + public compilers: wallabyjs.IWallabyCompilers = { + 'src/**/*.js': this.wallaby.compilers.babel({}), + 'src/**/*.ts': this.wallaby.compilers.typeScript({}) + }; + + public preprocessors: wallabyjs.IWallabyProcessor = { + '**/*.js': file => file.content + '\n// this is JavaScript', + '**/*.ts': file => file.content + '\n// this is TypeScript' + }; + + public postprocessors: wallabyjs.IWallabyProcessor = { + '**/*.js': file => file.content + '\n// this is JavaScript', + '**/*.ts': file => file.content + '\n// this is TypeScript' + }; + + public env: wallabyjs.IWallabyEnvironment = { + type: 'node', + params: { + env: 'KEY1=value1;KEY2=value2', + runner: '--arg1;--arg2;' + } + }; + + constructor(private wallaby: wallabyjs.IWallaby) { } +} diff --git a/wallabyjs/wallabyjs.d.ts b/wallabyjs/wallabyjs.d.ts new file mode 100644 index 0000000000..7b791e44ff --- /dev/null +++ b/wallabyjs/wallabyjs.d.ts @@ -0,0 +1,207 @@ +// Type definitions for WallabyJS +// Project: http://wallabyjs.com +// Definitions by: Andrew Connell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'wallabyjs' { + /** + * Wallaby configuration settings. + * + * @interface + * + * @property {IWallabyCompiler=} compilers - File patterns as keys and compiler functions as values. + * @property {boolean=} debug - Flag if debug messages written to Wallaby console (default=false). + * @prooperty {IWallabyEnvironment=} env - Specify a different test runner or change the runner settings. + * @property {string[] | IWallabyFilePattern[]} files - Specifies an array of source files or file name patterns to copy + * to the local cache. + * @property {Function=} postprocessor - Function that runs for every batch of file changes after all compilers and preprocessors. + * @property {Function=} preprocessor - Function that runs for every batch of file changes after all compilers. + * @property {string=} testFramework - Specifies the name and version of the testing framework you are using for your tests. + * @property {string[] | IWallabyFilePattern[]} tests - Specifies an array of test files or test file name patterns to copy + * to the local cache. + * @property {IWallabyWorkers=} workers - Degree of parallelism used to run your tests and controls the way wallaby re-uses workers. + * + * @see {@link https://wallabyjs.com/docs/config/overview.html} for details. + */ + export interface IWallabyConfig { + comilers?: IWallabyCompilers; + debug?: boolean; + env?: IWallabyEnvironment; + files: string[] | IWallabyFilePattern[]; + postprocessor?: IWallabyProcessor; + preprocessor?: IWallabyProcessor; + testFramework?: string; + tests: string[] | IWallabyFilePattern[]; + workers?: IWallabyWorkers; + } + + /** + * Wallaby compilers. + * + * @export + * @interface IWallabyCompiler + * + * @see {@link https://wallabyjs.com/docs/config/compilers.html} for details. + */ + export interface IWallabyCompilers { + [pattern: string]: any + } + + /** + * Wallaby built in compiler options. These are name-value pairs passed into each compiler. + * + * @export + * @interface IWallabyCompilerOptions + * + * @see {@link https://wallabyjs.com/docs/config/compilers.html} for details. + */ + export interface IWallabyBuiltInCompilerOptions { + [option: string]: string; + } + + /** + * Wallaby build in compilers. + * + * @export + * @interface IWallabyBuiltInCompilers + * + * @see {@link https://wallabyjs.com/docs/config/compilers.html} for details. + */ + export interface IWallabyBuiltInCompilers { + babel(compilerOptions?: IWallabyBuiltInCompilerOptions): IWallabyCompilerResult; + coffeeScript(compilerOptions?: IWallabyBuiltInCompilerOptions): IWallabyCompilerResult; + typeScript(compilerOptions?: IWallabyBuiltInCompilerOptions): IWallabyCompilerResult; + } + + /** + * Wallaby compiler result entity. + * + * @export + * @interface IWallabyCompilerResult + * + * @property {string} map - Source map. + * @property {string} code - Code transformed to JavaScript. + * @property {any} ranges - All converable ranges of the original file. + * + * @see {@link https://wallabyjs.com/docs/config/compilers.html} for details. + */ + export interface IWallabyCompilerResult { + map: string; + code: string; + ranges: any; + } + + /** + * Wallaby processor used in pre & post processors. + * + * @interface IWallabyProcessor + * + * @see {@link https://wallabyjs.com/docs/config/preprocessors.html} for details. + */ + export interface IWallabyProcessor { + [pattern: string]: (file: IWallabyFile) => void; + } + + /** + * Wallaby file object passed to pre & post processors. + * + * @interface IWallabyFile + * + * @property {string=} content - The current content of the file. + * @property {string=} path - The current path to the file. + * @function rename - Allows you to rename/move the file to newPath. + * @function changeExt - Shortcut for the rename function allowing you to change the file extension. + * + * @see {@link https://wallabyjs.com/docs/config/preprocessors.html} for details. + */ + export interface IWallabyFile { + content?: string; + path?: string; + rename(newPath: string): void; + changeExt(newExt: string): void; + } + + /** + * Wallaby file pattern. + * + * @interface IWallabyFilePattern + * + * @property {string} pattern - File name or file pattern. + * @property {boolean=} ignore - Used to completely exclude the file from Wallaby (default=false). + * @property {boolean=} instrument - Determines if file is instrumented (default=true). + * @property {boolean=} load - Determines if the file is loaded to sandbox HTML via script tag .(default=true). + * + * @see {@link https://wallabyjs.com/docs/config/files.html} for details. + */ + export interface IWallabyFilePattern { + pattern: string; + ignore?: boolean; + instrument?: boolean; + load?: boolean; + } + + /** + * Wallaby environment configuration. + * + * @interface IWallabyEnvironment + * + * @property {IWallabyEnvironmentParameters=} params - set parameters on environment. + * @property {string=} runner - Path of local Node / PhantomJs / Electron. + * @property {string=} type - Specify a different test runner or change the runner settings. + * + * @see {@link https://wallabyjs.com/docs/config/runner.html} for details. + */ + export interface IWallabyEnvironment { + params?: IWallabyEnvironmentParameters; + runner?: string; + type?: string; + } + + /** + * Wallaby environment parameters. + * + * @interface IWallabyEnvironmentParameters + * + * @property {string=} env - Semicolon-separated spawed runner process env variables. + * @property {string=} runner - Space-separated spawed runner process flags. + * + * @see {@link https://wallabyjs.com/docs/config/runner.html} for details. + */ + export interface IWallabyEnvironmentParameters { + env?: string; + runner?: string; + } + + /** + * Wallaby worker configuration. + * + * @interface IWallabyWorkers + * + * @property {boolean=} recycle - Specifies the degree of parallelism used to run your tests and + * controls the way wallaby re-uses workers. + * + * @see {@link https://wallabyjs.com/docs/config/workers.html} for details. + */ + export interface IWallabyWorkers { + recycle?: boolean; + } + + /** + * Wallaby object passed into config. + * + * @interface IWallaby + * + * @property {string=} localProjectDir - String property which returns the project local folder. + * @property {string=} projectCacheDir - String property which returns the project cache folder. + * @property {IWallabyBuiltInCompilers=} compilers - Property which allows you to access the built-in TypeScript, CoffeeScript and Babel compilers. + * @property {object=} defaults - Property which allows you to set the default values for file object properties. + * + * @see {@link https://wallabyjs.com/docs/config/overview.html} for details. + */ + export interface IWallaby { + localProjectDir?: string; + projectCacheDir?: string; + compilers?: IWallabyBuiltInCompilers; + defaults?: any; + } +} diff --git a/webcomponents.js/webcomponents.js-tests.ts b/webcomponents.js/webcomponents.js-tests.ts index b5e67abb93..cb1ea0f2c4 100644 --- a/webcomponents.js/webcomponents.js-tests.ts +++ b/webcomponents.js/webcomponents.js-tests.ts @@ -36,6 +36,15 @@ window.HTMLImports.whenReady(() => { document.querySelectorAll(`link[type=${window.HTMLImports.IMPORT_LINK_TYPE}`); +/* + * Shadow DOM + */ + +var shadow = xFoo.createShadowRoot(); +xFoo.shadowRoot; +shadow.innerHTML; +shadow.host; + /* * Web Components */ diff --git a/webcomponents.js/webcomponents.js.d.ts b/webcomponents.js/webcomponents.js.d.ts index 7390cc5bc8..2f4ea424e4 100644 --- a/webcomponents.js/webcomponents.js.d.ts +++ b/webcomponents.js/webcomponents.js.d.ts @@ -31,6 +31,11 @@ declare namespace webcomponents { whenReady(callback: () => void): void; } + export interface ShadowRootPolyfill extends DocumentFragment { + innerHTML: string; + host: Element; + } + export interface Polyfill { flags: any; } @@ -41,6 +46,11 @@ declare module "webcomponents.js" { export = webcomponents; } +interface Element { + createShadowRoot(): webcomponents.ShadowRootPolyfill; + shadowRoot?: webcomponents.ShadowRootPolyfill; +} + interface Document { registerElement(name: string, prototype: webcomponents.CustomElementInit): webcomponents.CustomElementConstructor; } diff --git a/webdriverio/webdriverio.d.ts b/webdriverio/webdriverio.d.ts index b0aa6fb5be..8b1ffd5ac1 100644 --- a/webdriverio/webdriverio.d.ts +++ b/webdriverio/webdriverio.d.ts @@ -1,4 +1,4 @@ -// Type definitions for webdriverio 3.3.0 +// Type definitions for webdriverio 4.0.4 // Project: http://www.webdriver.io/ // Definitions by: Nick Malaguti // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -92,6 +92,14 @@ declare namespace WebdriverIO { callback: (err: any) => P ): Client

      ; + selectByAttribute(selector: string, attribute: string, value: string): Client; + selectByAttribute

      ( + selector: string, + attribute: string, + value: string, + callback: (err: any) => P + ): Client

      ; + selectByIndex(selectElem: string, index: number): Client; selectByIndex

      ( selectElem: string, @@ -204,6 +212,28 @@ declare namespace WebdriverIO { ): Client

      ; } + export interface Client { + session(action?: string, sessionId?: string): Client>; + session

      ( + callback: (err: any, result: RawResult) => P + ): Client

      ; + + getGridNodeDetails(): Client; + getGridNodeDetails

      ( + callback: (err: any, details: Object) => P + ): Client

      ; + + gridProxyDetails(): Client; + gridProxyDetails

      ( + callback: (err: any, result: Object) => P + ): Client

      ; + + gridTestSession(): Client; + gridProxyDetails

      ( + callback: (err: any, result: Object) => P + ): Client

      ; + } + // Mobile export interface Client { // flick @@ -946,22 +976,15 @@ declare namespace WebdriverIO { waitUntil( condition: () => boolean | Q.IPromise, timeout?: number, + timeoutMsg?: string, interval?: number ): Client; waitUntil

      ( condition: () => boolean | Q.IPromise, - callback: (err: any, enabled: boolean) => P - ): Client

      ; - waitUntil

      ( - condition: () => boolean | Q.IPromise, - timeout: number, - callback: (err: any, enabled: boolean) => P - ): Client

      ; - waitUntil

      ( - condition: () => boolean | Q.IPromise, - timeout: number, - interval: number, - callback: (err: any, enabled: boolean) => P + timeout?: number, + timeoutMsg?: string, + interval?: number, + callback?: (err: any, enabled: boolean) => P ): Client

      ; } diff --git a/webix/webix.d.ts b/webix/webix.d.ts index 9c516654a1..7931ef83d9 100644 --- a/webix/webix.d.ts +++ b/webix/webix.d.ts @@ -9,6 +9,7 @@ type WebixTemplate = (...args: any[])=>string; type WebixCallback = (...args: any[])=>any; interface PromisedData { then(handler:(data:any)=>any):PromisedData; + fail(handler:(error:any)=>any):PromisedData; } function ajax():webix._ajax; @@ -8620,4 +8621,4 @@ interface window extends webix.ui.baseview{ }} -declare function $$(id: string | Event | HTMLElement): webix.ui.baseview; \ No newline at end of file +declare function $$(id: string | Event | HTMLElement): webix.ui.baseview; diff --git a/webpack-dev-server/webpack-dev-server-tests.ts b/webpack-dev-server/webpack-dev-server-tests.ts new file mode 100644 index 0000000000..df805219f9 --- /dev/null +++ b/webpack-dev-server/webpack-dev-server-tests.ts @@ -0,0 +1,67 @@ +/// +/// + +import * as webpack from 'webpack'; +import * as WebpackDevServer from 'webpack-dev-server'; +var compiler = webpack({}); + +// basic example +var server = new WebpackDevServer(compiler, { + publicPath: "/assets/" +}); +server.listen(8080); + +// API example +server = new WebpackDevServer(compiler, { + // webpack-dev-server options + contentBase: "/path/to/directory", + // or: contentBase: "http://localhost/", + + hot: true, + // Enable special support for Hot Module Replacement + // Page is no longer updated, but a "webpackHotUpdate" message is send to the content + // Use "webpack/hot/dev-server" as additional module in your entry point + // Note: this does _not_ add the `HotModuleReplacementPlugin` like the CLI option does. + + // Set this as true if you want to access dev server from arbitrary url. + // This is handy if you are using a html5 router. + historyApiFallback: false, + + // Set this if you want to enable gzip compression for assets + compress: true, + + // Set this if you want webpack-dev-server to delegate a single path to an arbitrary server. + // Use "**" to proxy all paths to the specified server. + // This is useful if you want to get rid of 'http://localhost:8080/' in script[src], + // and has many other use cases (see https://github.com/webpack/webpack-dev-server/pull/127 ). + proxy: { + "**": "http://localhost:9090" + }, + + setup: function (app) { + // Here you can access the Express app object and add your own custom middleware to it. + // For example, to define custom handlers for some paths: + // app.get('/some/path', function(req, res) { + // res.json({ custom: 'response' }); + // }); + }, + + // pass [static options](http://expressjs.com/en/4x/api.html#express.static) to inner express server + staticOptions: { + }, + + // webpack-dev-middleware options + quiet: false, + noInfo: false, + lazy: true, + filename: "bundle.js", + watchOptions: { + aggregateTimeout: 300, + poll: 1000 + }, + // It's a required option. + publicPath: "/assets/", + headers: { "X-Custom-Header": "yes" }, + stats: { colors: true } +}); +server.listen(8080, "localhost", function () { }); \ No newline at end of file diff --git a/webpack-dev-server/webpack-dev-server.d.ts b/webpack-dev-server/webpack-dev-server.d.ts new file mode 100644 index 0000000000..41abe0f871 --- /dev/null +++ b/webpack-dev-server/webpack-dev-server.d.ts @@ -0,0 +1,55 @@ +// Type definitions for webpack-dev-server 1.12.1 +// Project: https://github.com/webpack/webpack-dev-server +// Definitions by: maestroh +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// + +declare module "webpack-dev-server" { + import * as webpack from 'webpack'; + import * as core from 'express-serve-static-core'; + import * as serveStatic from 'serve-static'; + import * as http from 'http'; + + namespace WebpackDevServer { + export interface Configuration { + contentBase?: string; + hot?: boolean; + historyApiFallback?: boolean; + compress?: boolean; + proxy?: any; + staticOptions?: any; + quiet?: boolean; + noInfo?: boolean; + lazy?: boolean; + filename?: string; + watchOptions?: webpack.WatchOptions; + publicPath: string; + headers?: any; + stats?: webpack.compiler.StatsToJsonOptions | webpack.compiler.StatsToStringOptions; + + setup?(app: core.Express): void; + } + + export interface WebpackDevServer { + new ( + webpack: webpack.compiler.Compiler, + config: Configuration + ):WebpackDevServer; + + listen(port: number, + hostname: string, + callback?: Function + ): http.Server; + + listen(port: number, + callback?: Function + ): http.Server; + } + } + var wds: WebpackDevServer.WebpackDevServer; + + export = wds; +} \ No newline at end of file diff --git a/webpack-fail-plugin/webpack-fail-plugin-tests.ts b/webpack-fail-plugin/webpack-fail-plugin-tests.ts new file mode 100644 index 0000000000..4b7ab67b22 --- /dev/null +++ b/webpack-fail-plugin/webpack-fail-plugin-tests.ts @@ -0,0 +1,9 @@ +/// +import * as Webpack from "webpack"; +import FailPlugin = require("webpack-fail-plugin"); + +const config: Webpack.Configuration = { + plugins: [ + FailPlugin + ] +} diff --git a/webpack-fail-plugin/webpack-fail-plugin.d.ts b/webpack-fail-plugin/webpack-fail-plugin.d.ts new file mode 100644 index 0000000000..abfaea11d6 --- /dev/null +++ b/webpack-fail-plugin/webpack-fail-plugin.d.ts @@ -0,0 +1,17 @@ +// Type definitions for webpack-fail-plugin v1.0.5 +// Project: https://github.com/TiddoLangerak/webpack-fail-plugin +// Definitions by: Simon Hartcher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "webpack-fail-plugin" { + import {Plugin} from "webpack"; + + /** + * Webpack plugin that will make the process return status code 1 when it finishes with errors in single-run mode. + */ + function WebpackFailPlugin(): Plugin; + + export = WebpackFailPlugin; +} diff --git a/webpack-merge/webpack-merge-tests.ts b/webpack-merge/webpack-merge-tests.ts new file mode 100644 index 0000000000..1d39e0e7ab --- /dev/null +++ b/webpack-merge/webpack-merge-tests.ts @@ -0,0 +1,14 @@ +/// + +import merge = require("webpack-merge"); +import {Configuration} from "webpack"; + +const a: Configuration = { + entry: "test.js" +} +const b: Configuration = { + devtool: "source-map" +} + +const c = merge(a, b); +const d = merge.smart(a, b); diff --git a/webpack-merge/webpack-merge.d.ts b/webpack-merge/webpack-merge.d.ts new file mode 100644 index 0000000000..3d2683fa85 --- /dev/null +++ b/webpack-merge/webpack-merge.d.ts @@ -0,0 +1,25 @@ +// Type definitions for webpack-merge +// Project: https://github.com/survivejs/webpack-merge +// Definitions by: Simon Hartcher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "webpack-merge" { + import {Configuration} from "webpack"; + + interface WebpackMerge { + /** + * Merge multiple webpack configurations into one. + */ + (...configs: Configuration[]): Configuration; + + /** + * Merge multiple webpack configurations into one, with smart merging of loaders. + */ + smart(...configs: Configuration[]): Configuration; + } + + const merge: WebpackMerge; + export = merge; +} diff --git a/webpack-stream/webpack-stream-tests.ts b/webpack-stream/webpack-stream-tests.ts new file mode 100644 index 0000000000..bd57e1c735 --- /dev/null +++ b/webpack-stream/webpack-stream-tests.ts @@ -0,0 +1,12 @@ +/// +/// + +import webpackStream = require("webpack-stream"); +import webpack = require("webpack"); + +let output: NodeJS.ReadWriteStream; + +output = webpackStream(); +output = webpackStream({ entry: '' }); +output = webpackStream({ entry: '' }, webpack); +output = webpackStream({ entry: '' }, webpack, (error: Error, stats: webpack.compiler.Stats) => { }); diff --git a/webpack-stream/webpack-stream.d.ts b/webpack-stream/webpack-stream.d.ts new file mode 100644 index 0000000000..c98c0372dd --- /dev/null +++ b/webpack-stream/webpack-stream.d.ts @@ -0,0 +1,48 @@ +// Type definitions for webpack-stream v3.2.0 +// Project: https://github.com/shama/webpack-stream +// Definitions by: Ian Clanton-Thuon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module "webpack-stream" { + import webpack = require("webpack"); + + interface WebpackStreamStatic { + /** + * Run webpack with the default configuration. + */ + (): NodeJS.ReadWriteStream; + + /** + * Run webpack with the specified configuration. + * + * @param {config} Webpack configuration + */ + (config: webpack.Configuration): NodeJS.ReadWriteStream; + + /** + * Run webpack with the specified configuration and webpack instance + * + * @param {config} Webpack configuration + * @param {webpack} A webpack object + */ + (config: webpack.Configuration, webpack: webpack.Webpack): NodeJS.ReadWriteStream; + + /** + * Run webpack with the specified configuration and webpack instance + * + * @param {config} Webpack configuration + * @param {webpack} A webpack object + * @param {callback} A callback with the webpack stats and error objects. + */ + (config: webpack.Configuration, + webpack: webpack.Webpack, + callback?: (err: Error, stats: webpack.compiler.Stats) => void): NodeJS.ReadWriteStream; + } + + var webpackStream: WebpackStreamStatic; + + export = webpackStream; +} diff --git a/webpack-validator/webpack-validator-tests.ts b/webpack-validator/webpack-validator-tests.ts new file mode 100644 index 0000000000..f64b478b2e --- /dev/null +++ b/webpack-validator/webpack-validator-tests.ts @@ -0,0 +1,17 @@ +/// + +import {Configuration} from "webpack"; +import validate = require("webpack-validator"); + +const a: Configuration = { + entry: "test" +} + +const b = validate(a); +const c = validate(b, { + "no-root-files-node-modules-nameclash": true +}); +const d = validate(b, { + "loader-enforce-include-or-exclude": false, + "loader-prefer-include": true +}); diff --git a/webpack-validator/webpack-validator.d.ts b/webpack-validator/webpack-validator.d.ts new file mode 100644 index 0000000000..3c03627bb3 --- /dev/null +++ b/webpack-validator/webpack-validator.d.ts @@ -0,0 +1,27 @@ +// Type definitions for webpack-validator v2.2.6 +// Project: https://github.com/js-dxtools/webpack-validator +// Definitions by: Simon Hartcher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "webpack-validator" { + import {Configuration} from "webpack"; + + interface ValidationOptions { + "no-root-files-node-modules-nameclash"?: boolean; + "loader-enforce-include-or-exclude"?: boolean; + "loader-prefer-include"?: boolean; + } + + /** + * Validate your webpack configs with joi + */ + function Validate(config: Configuration): Configuration; + /** + * Validate your webpack configs with joi + */ + function Validate(config: Configuration, options: ValidationOptions): Configuration; + + export = Validate; +} diff --git a/webpack/webpack.d.ts b/webpack/webpack.d.ts index e2ed2d1658..96a7c710df 100644 --- a/webpack/webpack.d.ts +++ b/webpack/webpack.d.ts @@ -102,7 +102,7 @@ declare module "webpack" { /** Include comments with information about the modules. */ pathinfo?: boolean; /** If set, export the bundle as library. output.library is the name. */ - library?: boolean; + library?: string; /** * Which format to export the library: *

        diff --git a/webrtc/RTCPeerConnection-tests.ts b/webrtc/RTCPeerConnection-tests.ts index 9cd8087947..4a9e558ac7 100644 --- a/webrtc/RTCPeerConnection-tests.ts +++ b/webrtc/RTCPeerConnection-tests.ts @@ -41,7 +41,7 @@ navigator.getUserMedia({ audio: true, video: true }, }); peerConnection.onaddstream = ev => console.log(ev.type); -peerConnection.ondatachannel = ev => console.log(ev.type); +peerConnection.ondatachannel = ev => console.log(ev.channel); peerConnection.oniceconnectionstatechange = ev => console.log(ev.type); peerConnection.onnegotiationneeded = ev => console.log(ev.type); peerConnection.onopen = ev => console.log(ev.type); diff --git a/webrtc/RTCPeerConnection.d.ts b/webrtc/RTCPeerConnection.d.ts index 66b92c2416..c985cf2855 100644 --- a/webrtc/RTCPeerConnection.d.ts +++ b/webrtc/RTCPeerConnection.d.ts @@ -191,6 +191,7 @@ declare var RTCDataChannel: { new (): RTCDataChannel; }; +// https://www.w3.org/TR/webrtc/#rtcdatachannelevent interface RTCDataChannelEvent extends Event { channel: RTCDataChannel; } @@ -309,7 +310,7 @@ interface RTCPeerConnection { getRemoteStreams(): MediaStream[]; createDataChannel(label?: string, dataChannelDict?: RTCDataChannelInit): RTCDataChannel; - ondatachannel: (event: Event) => void; + ondatachannel: (event: RTCDataChannelEvent) => void; addStream(stream: MediaStream, constraints?: RTCMediaConstraints): void; removeStream(stream: MediaStream): void; close(): void; diff --git a/websocket/websocket.d.ts b/websocket/websocket.d.ts index bbcd7e04d8..f862ec8410 100644 --- a/websocket/websocket.d.ts +++ b/websocket/websocket.d.ts @@ -1,5 +1,5 @@ // Type definitions for websocket -// Project: https://github.com/Worlize/WebSocket-Node +// Project: https://github.com/theturtle32/WebSocket-Node // Definitions by: Paul Loyd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -236,8 +236,9 @@ declare module "websocket" { * You may optionally pass in an HTTP Status code (such as 404) and a textual * description that will be sent to the client in the form of an * `X-WebSocket-Reject-Reason` header. + * Optional extra http headers can be added via Object key/values on extraHeaders. */ - reject(httpStatus?: number, reason?: string): void; + reject(httpStatus?: number, reason?: string, extraHeaders?: Object): void; // Events on(event: string, listener: () => void): this; diff --git a/whatwg-fetch/whatwg-fetch-tests.ts b/whatwg-fetch/whatwg-fetch-tests.ts index 8dbbd2964b..3f23abe914 100644 --- a/whatwg-fetch/whatwg-fetch-tests.ts +++ b/whatwg-fetch/whatwg-fetch-tests.ts @@ -1,5 +1,18 @@ /// +function test_HeadersCopiedFromHeaders() { + var source = new Headers(); + source.append('Content-Type', 'application/json'); + return new Headers(source); +} + +function test_HeadersCopiedFromHash() { + var source: DOMStringMap = { + 'Content-Type': 'application/json' + }; + return new Headers(source); +} + function test_fetchUrlWithOptions() { var headers = new Headers(); headers.append("Content-Type", "application/json"); diff --git a/whatwg-fetch/whatwg-fetch.d.ts b/whatwg-fetch/whatwg-fetch.d.ts index 8997ab6917..793244976e 100644 --- a/whatwg-fetch/whatwg-fetch.d.ts +++ b/whatwg-fetch/whatwg-fetch.d.ts @@ -1,92 +1,111 @@ -// Type definitions for fetch API +// Type definitions for Fetch API // Project: https://github.com/github/fetch -// Definitions by: Ryan Graham +// Definitions by: Ryan Graham , Kagami Sascha Rosylight // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare class Request extends Body { - constructor(input: string|Request, init?:RequestInit); - method: string; - url: string; - headers: Headers; - context: RequestContext; - referrer: string; - mode: RequestMode; - redirect: RequestRedirect; - credentials: RequestCredentials; - cache: RequestCache; -} - -interface RequestInit { - method?: string; - headers?: HeaderInit|{ [index: string]: string }; - body?: BodyInit; - mode?: RequestMode; - redirect?: RequestRedirect; - credentials?: RequestCredentials; - cache?: RequestCache; -} - -type RequestContext = - "audio" | "beacon" | "cspreport" | "download" | "embed" | - "eventsource" | "favicon" | "fetch" | "font" | "form" | "frame" | - "hyperlink" | "iframe" | "image" | "imageset" | "import" | - "internal" | "location" | "manifest" | "object" | "ping" | "plugin" | - "prefetch" | "script" | "serviceworker" | "sharedworker" | - "subresource" | "style" | "track" | "video" | "worker" | - "xmlhttprequest" | "xslt"; -type RequestMode = "same-origin" | "no-cors" | "cors"; -type RequestRedirect = "follow" | "error" | "manual"; -type RequestCredentials = "omit" | "same-origin" | "include"; -type RequestCache = - "default" | "no-store" | "reload" | "no-cache" | - "force-cache" | "only-if-cached"; - -declare class Headers { - append(name: string, value: string): void; - delete(name: string):void; - get(name: string): string; - getAll(name: string): Array; - has(name: string): boolean; - set(name: string, value: string): void; - forEach(callback: (value: string, name: string) => void): void; -} - -declare class Body { - bodyUsed: boolean; - arrayBuffer(): Promise; - blob(): Promise; - formData(): Promise; - json(): Promise; - json(): Promise; - text(): Promise; -} -declare class Response extends Body { - constructor(body?: BodyInit, init?: ResponseInit); - static error(): Response; - static redirect(url: string, status: number): Response; - type: ResponseType; - url: string; - status: number; - ok: boolean; - statusText: string; - headers: Headers; - clone(): Response; -} - -type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; - -interface ResponseInit { - status: number; - statusText?: string; - headers?: HeaderInit; -} - -declare type HeaderInit = Headers|Array; -declare type BodyInit = ArrayBuffer|ArrayBufferView|Blob|FormData|string; -declare type RequestInfo = Request|string; +/// interface Window { - fetch(url: string|Request, init?: RequestInit): Promise; + fetch(url: RequestInfo, init?: RequestInit): Promise; +} +declare var fetch: typeof window.fetch; + +declare type HeadersInit = Headers | string[][] | { [key: string]: string }; +declare class Headers { + constructor(init?: HeadersInit); + + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string; // | null; (TS 2.0 strict null check) + has(name: string): boolean; + set(name: string, value: string): void; + + // WebIDL pair iterator: iterable + entries(): IterableIterator<[string, string]>; + forEach(callback: (value: string, index: number, headers: Headers) => void, thisArg?: any): void; + keys(): IterableIterator; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; } -declare var fetch: typeof window.fetch; +declare type BodyInit = Blob | ArrayBufferView | ArrayBuffer | FormData /* | URLSearchParams */ | string; +interface Body { + bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; +} + +declare type RequestInfo = Request | string; +interface Request extends Body { + method: string; + url: string; + headers: Headers; + + type: RequestType + destination: RequestDestination; + referrer: string; + referrerPolicy: ReferrerPolicy; + mode: RequestMode; + credentials: RequestCredentials; + cache: RequestCache; + redirect: RequestRedirect; + integrity: string; + + clone(): Request; +} +interface RequestInit { + method?: string; + headers?: HeadersInit; + body?: BodyInit; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + mode?: RequestMode; + credentials?: RequestCredentials; + cache?: RequestCache; + redirect?: RequestRedirect; + integrity?: string; + window?: any; +} +interface RequestConstructor { + new (input: RequestInfo, init?: RequestInit): Request; +} +declare var Request: RequestConstructor; + +type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video"; +type RequestDestination = "" | "document" | "embed" | "font" | "image" | "manifest" | "media" | "object" | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "worker" | "xslt"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached"; +type RequestRedirect = "follow" | "error" | "manual"; +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url"; + +interface Response extends Body { + type: ResponseType; + url: string; + redirected: boolean; + status: number; + ok: boolean; + statusText: string; + headers: Headers; + body: ReadableStream; // | null; + trailer: Promise; + + clone(): Response; +} +interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; +} +interface ResponseConstructor { + new (body?: BodyInit, init?: ResponseInit): Response; + + error(): Response; + redirect(url: string, status?: number): Response; +} +declare var Response: ResponseConstructor; + +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; diff --git a/whatwg-streams/whatwg-streams-tests.ts b/whatwg-streams/whatwg-streams-tests.ts new file mode 100644 index 0000000000..d1e23eda98 --- /dev/null +++ b/whatwg-streams/whatwg-streams-tests.ts @@ -0,0 +1,189 @@ +/// + +function makeReadableWebSocketStream(url: string, protocols: string[]) { + const ws = new WebSocket(url, protocols); + ws.binaryType = "arraybuffer"; + + return new ReadableStream({ + start(controller) { + ws.onmessage = event => controller.enqueue(event.data); + ws.onclose = () => controller.close(); + ws.onerror = () => controller.error(new Error("The WebSocket errored!")); + }, + + cancel() { + ws.close(); + } + }); +} + +function makeReadableBackpressureSocketStream(host: string, port: number) { + const socket = createBackpressureSocket(host, port); + + return new ReadableStream({ + start(controller) { + socket.ondata = (event: any) => { + controller.enqueue(event.data); + + if (controller.desiredSize <= 0) { + // The internal queue is full, so propagate + // the backpressure signal to the underlying source. + socket.readStop(); + } + }; + + socket.onend = () => controller.close(); + socket.onerror = () => controller.error(new Error("The socket errored!")); + }, + + pull() { + // This is called if the internal queue has been emptied, but the + // stream’s consumer still wants more data. In that case, restart + // the flow of data if we have previously paused it. + socket.readStart(); + }, + + cancel() { + socket.close(); + } + }); + + function createBackpressureSocket(host: string, port: number): any { }; +} + +const DEFAULT_CHUNK_SIZE = 65536; + +function makeUDPSocketStream(host: string, port: number) { + const socket = createUDPSocket(host, port); + + return new ReadableStream({ + type: "bytes", + + start(controller) { + readRepeatedly().catch(e => controller.error(e)); + + function readRepeatedly(): Promise { + return socket.select2().then(() => { + // Since the socket can become readable even when there’s + // no pending BYOB requests, we need to handle both cases. + let bytesRead: number; + if (controller.byobRequest) { + const v = controller.byobRequest.view; + bytesRead = socket.readInto(v.buffer, v.byteOffset, v.byteLength); + controller.byobRequest.respond(bytesRead); + } else { + const buffer = new ArrayBuffer(DEFAULT_CHUNK_SIZE); + bytesRead = socket.readInto(buffer, 0, DEFAULT_CHUNK_SIZE); + controller.enqueue(new Uint8Array(buffer, 0, bytesRead)); + } + + if (bytesRead === 0) { + controller.close(); + return; + } + + return readRepeatedly(); + }); + } + }, + + cancel() { + socket.close(); + } + }); + + function createUDPSocket(host: string, port: number): any { }; +} + +function makeWritableWebSocketStream(url: string, protocols: string[]) { + const ws = new WebSocket(url, protocols); + + return new WritableStream({ + start(controller) { + ws.onerror = () => controller.error(new Error("The WebSocket errored!")); + return new Promise(resolve => ws.onopen = () => resolve()); + }, + + write(chunk) { + ws.send(chunk); + // Return immediately, since the web socket gives us no easy way to tell + // when the write completes. + }, + + close() { + return new Promise((resolve, reject) => { + ws.onclose = () => resolve(); + ws.close(); + }); + } + }); +} + +function streamifyWebSocket(url: string, protocol: string) { + const ws = new WebSocket(url, protocol); + ws.binaryType = "arraybuffer"; + + return { + readable: new ReadableStream(new WebSocketSource(ws)), + writable: new WritableStream(new WebSocketSink(ws)) + }; +} + +class WebSocketSource implements ReadableStreamSource { + private _ws: WebSocket + + constructor(ws: WebSocket) { + this._ws = ws; + } + + start(controller: ReadableStreamDefaultController) { + this._ws.onmessage = event => controller.enqueue(event.data); + this._ws.onclose = () => controller.close(); + + this._ws.addEventListener("error", () => { + controller.error(new Error("The WebSocket errored!")); + }); + } + + cancel() { + this._ws.close(); + } +} + +class WebSocketSink implements WritableStreamSink { + private _ws: WebSocket + + constructor(ws: WebSocket) { + this._ws = ws; + } + + start(controller: WritableStreamDefaultController) { + this._ws.addEventListener("error", () => { + controller.error(new Error("The WebSocket errored!")); + }); + + return new Promise(resolve => this._ws.onopen = () => resolve()); + } + + write(chunk: any) { + this._ws.send(chunk); + } + + close() { + return new Promise((resolve, reject) => { + this._ws.onclose = () => resolve(); + this._ws.close(); + }); + } +} + +const streamyWS = streamifyWebSocket("wss://example.com:443/", "protocol"); +const writer = streamyWS.writable.getWriter(); +const reader = streamyWS.readable.getReader(); + +writer.write("Hello"); +writer.write("web socket!"); + +reader.read().then(({ value, done }) => { + console.log("The web socket says: ", value); +}); \ No newline at end of file diff --git a/whatwg-streams/whatwg-streams.d.ts b/whatwg-streams/whatwg-streams.d.ts new file mode 100644 index 0000000000..862b312a77 --- /dev/null +++ b/whatwg-streams/whatwg-streams.d.ts @@ -0,0 +1,134 @@ +// Type definitions for Streams API +// Project: https://github.com/whatwg/streams +// Definitions by: Kagami Sascha Rosylight +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface ReadableStreamSource { + start?(controller: ReadableStreamDefaultController): void | Promise; + pull?(controller: ReadableStreamDefaultController): void | Promise; + cancel?(reason: string): void | Promise; +} + +interface ReadableByteStreamSource { + start?(controller: ReadableByteStreamController): void | Promise; + pull?(controller: ReadableByteStreamController): void | Promise; + cancel?(reason: string): void | Promise; + + type: "bytes"; +} + +interface QueuingStrategy { + highWaterMark?: number; + size?(chunk: ArrayBufferView): number; +} + +declare class ReadableStream { + constructor(underlyingSource?: ReadableStreamSource, strategy?: QueuingStrategy); + constructor(underlyingSource?: ReadableByteStreamSource, strategy?: QueuingStrategy); + + locked: boolean; + + cancel(reason: string): Promise; + getReader(): ReadableStreamDefaultReader; + getReader({ mode }: { mode: "byob" }): ReadableStreamBYOBReader; + pipeThrough({ writable, readable }: { writable: WritableStream, readable: T }): T; + pipeTo(dest: WritableStream, { preventClose, preventAbort, preventCancel }: { preventClose?: boolean, preventAbort?: boolean, preventCancel?: boolean }): Promise; + tee(): [ReadableStream, ReadableStream]; +} + +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + + closed: Promise; + + cancel(reason: string): Promise; + read(): Promise>; + releaseLock(): void; +} + +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + + closed: Promise; + + cancel(reason: string): Promise; + read(view: ArrayBufferView): Promise>; + releaseLock(): void; +} + +declare class ReadableStreamDefaultController { + constructor(stream: ReadableStream, underlyingSource: ReadableStreamSource, size: number, highWaterMark: number); + + desiredSize: number; + + close(): void; + enqueue(chunk: ArrayBufferView): number; + error(e: any): void; +} + +declare class ReadableByteStreamController { + constructor(stream: ReadableStream, underlyingSource: ReadableStreamSource, highWaterMark: number); + + byobRequest: ReadableStreamBYOBRequest; + desiredSize: number; + + close(): void; + enqueue(chunk: ArrayBufferView): number; + error(e: any): void; +} + +declare class ReadableStreamBYOBRequest { + constructor(controller: ReadableByteStreamController, view: ArrayBufferView); + + view: ArrayBufferView; + + respond(bytesWritten: number): void; + respondWithNewView(view: ArrayBufferView): void; +} + +interface WritableStreamSink { + start?(controller: WritableStreamDefaultController): void | Promise; + write?(chunk: any): void | Promise; + close?(): void | Promise; + abort?(reason: string): void | Promise; +} + +declare class WritableStream { + constructor(underlyingSink?: WritableStreamSink, strategy?: QueuingStrategy); + + locked: boolean; + + abort(reason: string): Promise; + getWriter(): WritableStreamDefaultWriter; +} + +declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + + closed: Promise; + desiredSize: number; + ready: Promise; + + abort(reason: string): Promise; + close(): Promise; + releaseLock(): void; + write(chunk: any): Promise; +} + +declare class WritableStreamDefaultController { + constructor(stream: WritableStream, underlyingSink: WritableStreamSink, size: number, highWaterMark: number); + + error(e: any): void; +} + +declare class ByteLengthQueuingStrategy { + constructor({ highWaterMark }: { highWaterMark: number }); + + size(chunk: ArrayBufferView): number; +} + +declare class CountQueuingStrategy { + constructor({ highWaterMark }: { highWaterMark: number }); + + size(): number; // 1; +} \ No newline at end of file diff --git a/window-size/window-size.d.ts b/window-size/window-size.d.ts new file mode 100644 index 0000000000..c97e4c81b6 --- /dev/null +++ b/window-size/window-size.d.ts @@ -0,0 +1,12 @@ +// Type definitions for window-size 0.2.0 +// Project: https://github.com/jonschlinkert/window-size +// Definitions by: Pouya Kary +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "window-size" { + /** Height of the terminal window.*/ + export const height: number; + + /** Width of the terminal window.*/ + export const width: number; +} \ No newline at end of file diff --git a/winston-dynamodb/winston-dynamodb-tests.ts b/winston-dynamodb/winston-dynamodb-tests.ts new file mode 100644 index 0000000000..00f5cdfa59 --- /dev/null +++ b/winston-dynamodb/winston-dynamodb-tests.ts @@ -0,0 +1,284 @@ +/// +/// + +import winston = require('winston'); +require('winston-dynamodb').DynamoDB; + +var str: string; +var bool: boolean; +var num: number; +var metadata: any; +var obj: any = {}; + +winston.level = 'debug'; + +var queryOptions: winston.QueryOptions; +var transportOptions: winston.TransportOptions; +var loggerOptions: winston.LoggerOptions = { + transports: [new (winston.Transport)()], + rewriters: [new (winston.Transport)()], + exceptionHandlers: [new (winston.Transport)()], + handleExceptions: false +}; + +var options: any; +var value: any; +var transport: winston.TransportInstance; +var logger: winston.LoggerInstance; +var profiler: winston.ProfileHandler; + +var writeableStream: NodeJS.WritableStream; +var readableStream: NodeJS.ReadableStream; + + +var transportStatic: winston.TransportStatic = winston.Transport; + + +var transportInstance: winston.TransportInstance = new (winston.Transport)(transportOptions); +transportInstance = new (winston.Transport)(); + +var containerInstance: winston.ContainerInstance = new (winston.Container)(loggerOptions); +winston.loggers.options.transports = [ + new (winston.Transport)() +]; +winston.loggers.add('category1', { + console: { + level: 'silly', + colorize: 'true', + label: 'category one' + }, + file: { + filename: '/path/to/some/file' + }, + transports: [ + new (winston.Transport)() + ] +}); +logger = winston.loggers.get('category1'); + +bool = containerInstance.has(str); +logger = containerInstance.get(str, loggerOptions); +containerInstance.close(str); + +transport = winston.transports.Console; +transport = winston.transports.DailyRotateFile; +transport = winston.transports.File; +transport = winston.transports.Http; +transport = winston.transports.Loggly; +transport = winston.transports.Memory +transport = winston.transports.Webhook; + +value = transport.formatQuery({}); +queryOptions = transport.normalizeQuery(queryOptions); +value = transport.formatResults([], {}); +transport.logException(str, metadata, () => { }); + +winston.exitOnError = bool; + + +winston.log(str, str); +winston.log(str, str, metadata); +winston.log(str, str, metadata, metadata, metadata); +winston.debug(str); +winston.debug(str, metadata); +winston.debug(str, metadata, metadata, metadata); +winston.info(str); +winston.info(str, metadata); +winston.info(str, metadata, metadata, metadata); +winston.warn(str); +winston.warn(str, metadata); +winston.warn(str, metadata, metadata, metadata); +winston.error(str); +winston.error(str, metadata); +winston.error(str, metadata, metadata, metadata); + +winston.query(queryOptions, (err: Error, results: any): void => { + +}); +winston.query((err: Error, results: any): void => { + +}); + +logger = winston.add(transport, transportOptions); +logger = winston.remove(transport); +logger = winston.add(transport, {filename: 'path/to/file.log'}); + +winston.clear(); +logger = winston.profile(str, str, metadata, (err: Error, level: string, msg: string, meta: any):void => { + +}); +logger = winston.profile(str); +profiler = winston.startTimer(); +winston.setLevels({}); +logger = winston.cli(); + +winston.handleExceptions(transport); +winston.unhandleExceptions(transport); + +readableStream = winston.stream(options); + +readableStream.on('log', function (log:any):void { + console.log(log); +}); + + + +logger = logger.extend(obj); +logger.log(str, str); +logger.log(str, str, metadata); +logger.log(str, str, metadata, metadata, metadata); +logger.debug(str); +logger.debug(str, metadata); +logger.debug(str, metadata, metadata, metadata); +logger.info(str); +logger.info(str, metadata); +logger.info(str, metadata, metadata, metadata); +logger.warn(str); +logger.warn(str, metadata); +logger.warn(str, metadata, metadata, metadata); +logger.error(str); +logger.error(str, metadata); +logger.error(str, metadata, metadata, metadata); + +logger.query(queryOptions, (err: Error, results: any): void => { + +}); +logger.query((err: Error, results: any): void => { + +}); + +readableStream = winston.stream(options); +logger.close(); +logger.handleExceptions(transport); +logger.unhandleExceptions(transport); +logger = logger.add(transport, transportOptions, bool); +logger = logger.add(transport); +logger = logger.add(transport, {filename: 'path/to/file.log'}); + +logger.clear(); +logger = logger.remove(transport); +profiler = logger.startTimer(); +logger = logger.profile(str, str, metadata, (err: Error, level: string, msg: string, meta: any):void => { + +}); +value = logger.setLevels(value); +logger = logger.cli(); + + +logger = profiler.done(str); +logger = profiler.logger; +profiler.start = new Date(); + +let testRewriter : winston.MetadataRewriter; +testRewriter = function(level: string, msg: string, meta: any) { + return meta; +}; + +logger.rewriters.push(testRewriter); + +/** + * DynamoDB-specific stuff + */ +let dynamoDBOptions = { + useEnvironment: bool, + level: str, + tableName: str, + accessKeyId: str, + secretAccessKey: str, + region: str, + dynamoDoc: bool, +}; + +winston.add(winston.transports.DynamoDB, dynamoDBOptions); + +/** + * New Logger instances with transports tests: + */ + +var logger: winston.LoggerInstance = new (winston.Logger)({ + transports: [ + new (winston.transports.Console)({ + level: str, + silent: bool, + json: bool, + colorize: bool, + timestamp: bool, + showLevel: bool, + label: str, + logstash: bool, + debugStdout: bool, + depth: num, + }), + new (winston.transports.DailyRotateFile)({ + level: str, + silent: bool, + json: bool, + colorize: bool, + maxsize: num, + maxFiles: num, + maxRetries: num, + prettyPrint: bool, + timestamp: bool, + filename: str, + dirname: str, + datePattern: str, + eol: str, + stream: writeableStream, + }), + new (winston.transports.File)({ + level: str, + silent: bool, + json: bool, + colorize: bool, + prettyPrint: bool, + timestamp: bool, + showLevel: bool, + logstash: bool, + rotationFormat: bool, + depth: num, + zippedArchive: bool, + eol: str, + tailable: bool, + maxRetries: num, + filename: str, + maxsize: num, + maxFiles: num, + stream: writeableStream, + }), + new (winston.transports.Http)({ + level: str, + host: str, + port: num, + path: str, + auth: { username: str, password: str }, + ssl: bool, + }), + new (winston.transports.Loggly)({ + level: str, + subdomain: str, + auth: {}, + inputName: str, + json: bool, + }), + new (winston.transports.Memory)({ + level: str, + json: bool, + colorize: bool, + showLevel: bool, + depth: num, + timestamp: bool, + label: str, + }), + new (winston.transports.Webhook)({ + level: str, + name: str, + host: str, + port: num, + method: str, + path: str, + auth: { username: str, password: str }, + ssl: {ca: {}}, + }), + new (winston.transports.DynamoDB)(dynamoDBOptions), + ] +}); diff --git a/winston-dynamodb/winston-dynamodb.d.ts b/winston-dynamodb/winston-dynamodb.d.ts new file mode 100644 index 0000000000..7d4c2e9544 --- /dev/null +++ b/winston-dynamodb/winston-dynamodb.d.ts @@ -0,0 +1,38 @@ +// Type definitions for winston-dynamodb +// Project: https://github.com/inspiredjw/winston-dynamodb +// Definitions by: nickiannone +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as winston from 'winston'; +import { TransportInstance } from 'winston'; +export interface DynamoDBTransportOptions { + useEnvironment?: boolean; + accessKeyId?: string; + secretAccessKey?: string; + region?: string; + tableName: string; + level: string; + dynamoDoc?: boolean; +} +export interface DynamoDBTransportInstance extends TransportInstance { + new (options?: DynamoDBTransportOptions): DynamoDBTransportInstance; +} +export declare class DynamoDB extends winston.Transport implements DynamoDBTransportInstance { + regions: string[]; + name: string; + level: string; + db: any; + AWS: any; + region: string; + tableName: string; + dynamoDoc: boolean; + constructor(options?: DynamoDBTransportOptions); + log(level: any, msg: any, meta: any, callback: any): any; +} +declare module "winston" { + interface Transports { + DynamoDB: DynamoDB; + } +} diff --git a/wolfy87-eventemitter/wolfy87-eventemitter.d.ts b/wolfy87-eventemitter/wolfy87-eventemitter.d.ts index 8291c50c11..d9af289d1a 100644 --- a/wolfy87-eventemitter/wolfy87-eventemitter.d.ts +++ b/wolfy87-eventemitter/wolfy87-eventemitter.d.ts @@ -405,14 +405,14 @@ declare namespace Wolfy87EventEmitter { * * Added to mirror the node API. */ - removeAllListeners(event: string): EventEmitter; + removeAllListeners(event?: string): EventEmitter; /** * Alias of removeEvent. * * Added to mirror the node API. */ - removeAllListeners(event: RegExp): EventEmitter; + removeAllListeners(event?: RegExp): EventEmitter; /** * Emits an event of your choice. diff --git a/ws/ws-tests.ts b/ws/ws-tests.ts index ec2bc431e0..3c85d678cb 100644 --- a/ws/ws-tests.ts +++ b/ws/ws-tests.ts @@ -1,6 +1,9 @@ /// -import WebSocket = require('ws'); +import * as WebSocket from 'ws'; +import * as http from'http'; +import * as https from'https'; + var WebSocketServer = WebSocket.Server; { @@ -29,7 +32,7 @@ var WebSocketServer = WebSocket.Server; { var wss = new WebSocketServer({port: 8080}); - function broadcast(data: any) { + const broadcast = function(data: any) { for(var i in wss.clients) wss.clients[i].send(data); }; @@ -51,3 +54,30 @@ var WebSocketServer = WebSocket.Server; }, 500); }); } + +{ + new WebSocket.Server({ server: https.createServer({}) }); + new WebSocket.Server({ server: http.createServer() }); +} + + +{ + const verifyClient = function( + info: { + origin: string + secure: boolean + req: http.ServerRequest + } + , callback: (res: boolean) => void + ): void { + callback(true) + } + + var wsv = new WebSocketServer({ + verifyClient + }) + + wsv.on('connection', function connection(ws) { + console.log(ws.protocol) + }) +} diff --git a/ws/ws.d.ts b/ws/ws.d.ts index d9a1338d21..b7ce3bd829 100644 --- a/ws/ws.d.ts +++ b/ws/ws.d.ts @@ -8,6 +8,7 @@ declare module "ws" { import * as events from 'events'; import * as http from 'http'; + import * as https from 'https'; import * as net from 'net'; class WebSocket extends events.EventEmitter { @@ -22,6 +23,7 @@ declare module "ws" { url: string; supports: any; upgradeReq: http.ServerRequest; + protocol: string; CONNECTING: number; OPEN: number; @@ -33,21 +35,8 @@ declare module "ws" { onclose: (event: {wasClean: boolean; code: number; reason: string; target: WebSocket}) => void; onmessage: (event: {data: any; type: string; target: WebSocket}) => void; - constructor(address: string, options?: { - protocol?: string; - agent?: http.Agent; - headers?: {[key: string]: string}; - protocolVersion?: any; - host?: string; - origin?: string; - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any[]; - ciphers?: string; - rejectUnauthorized?: boolean; - }); + constructor(address: string, options?: WebSocket.IClientOptions); + constructor(address: string, protocols?: string | string[], options?: WebSocket.IClientOptions); close(code?: number, data?: any): void; pause(): void; @@ -87,15 +76,32 @@ declare module "ws" { } namespace WebSocket { + + type VerifyClientCallbackSync = (info: {origin: string; secure: boolean; req: http.ServerRequest}) => boolean; + type VerifyClientCallbackAsync = (info: {origin: string; secure: boolean; req: http.ServerRequest} + , callback: (res: boolean) => void) => void; + + export interface IClientOptions { + protocol?: string; + agent?: http.Agent; + headers?: {[key: string]: string}; + protocolVersion?: any; + host?: string; + origin?: string; + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any[]; + ciphers?: string; + rejectUnauthorized?: boolean; + } + export interface IServerOptions { host?: string; port?: number; - server?: http.Server; - verifyClient?: { - (info: {origin: string; secure: boolean; req: http.ServerRequest}): boolean; - (info: {origin: string; secure: boolean; req: http.ServerRequest}, - callback: (res: boolean) => void): void; - }; + server?: http.Server | https.Server; + verifyClient?: VerifyClientCallbackAsync | VerifyClientCallbackSync; handleProtocols?: any; path?: string; noServer?: boolean; diff --git a/xlsx/xlsx.d.ts b/xlsx/xlsx.d.ts index b761387681..68f89b545a 100644 --- a/xlsx/xlsx.d.ts +++ b/xlsx/xlsx.d.ts @@ -7,6 +7,7 @@ declare module 'xlsx' { export function readFile(filename:string, opts?:IParsingOptions):IWorkBook; export function read(data:any, opts?:IParsingOptions):IWorkBook; + export function write(data:any, opts?:IParsingOptions): any; export var utils:IUtils; export interface IProperties { @@ -41,6 +42,7 @@ declare module 'xlsx' { bookSheets?:boolean; bookVBA?:boolean; password?:string; + bookType?:string; /** * Possible options: 'binary', 'base64', 'buffer', 'file' @@ -127,10 +129,21 @@ declare module 'xlsx' { s?: string; } + export interface ICell { + c: number; + r: number; + } + export interface IUtils { - sheet_to_json(worksheet:IWorkSheet):T[]; - sheet_to_csv(worksheet:IWorkSheet):any; - sheet_to_formulae(worksheet:IWorkSheet):any; + sheet_to_json(worksheet:IWorkSheet, opts?: { + raw?: boolean; + range?: any; + header?: "A"|number|string[]; + }):T[]; + sheet_to_csv(worksheet: IWorkSheet):any; + sheet_to_formulae(worksheet: IWorkSheet):any; + encode_cell(cell: ICell): any; + encode_range(s: ICell, e: ICell): any; } } diff --git a/xmlpoke/xmlpoke-tests.ts b/xmlpoke/xmlpoke-tests.ts new file mode 100644 index 0000000000..b77463f164 --- /dev/null +++ b/xmlpoke/xmlpoke-tests.ts @@ -0,0 +1,83 @@ +/// +/// + +// tsc xmlpoke-tests.ts && node xmlpoke-tests.js + +import * as xmlpoke from 'xmlpoke'; +import * as assert from 'assert'; + +let result: string; + +// add with xpath, value +result = xmlpoke('', xml => xml.add('/a/b', 'c')); +assert.equal(result, 'c'); + +// add with xpath, Transform +const addfn: XmlPoke.Transform = (node, value) => 'c'; +result = xmlpoke('', xml => xml.add('/a/b', addfn)); +assert.equal(result, 'c'); + +// add with xpath, CDataValue +const cdataval: XmlPoke.CDataValue = new xmlpoke.CDataValue('c'); +result = xmlpoke('', xml => xml.add('/a/b', cdataval)); +assert.equal(result, ''); + +// add with xpath, XMLVal +const xmlval = new xmlpoke.XmlString(''); +result = xmlpoke('', xml => xml.add('/a/b', xmlval)); +assert.equal(result, ''); + +// add with map +result = xmlpoke('', xml => xml.add({ + '/a/b': 'c' +})); +assert.equal(result, 'c'); + +// set with xpath, value +result = xmlpoke('b', xml => xml.set('/a', 'c')); +assert.equal(result, 'c'); + +// set with map +result = xmlpoke('b', xml => xml.set({ + '/a': 'c' +})); +assert.equal(result, 'c'); + +// set with xpath that doesn't exist (no-op) +result = xmlpoke('bval', xml => xml.set('/a/c', 'cval')); +assert.equal(result, 'bval'); + +// setOrAdd with xpath, value +result = xmlpoke('', xml => xml.setOrAdd('/a/b', 'c')); +assert.equal(result, 'c'); + +// setOrAdd with map +result = xmlpoke('', xml => xml.setOrAdd({ + '/a/b': 'c' +})); +assert.equal(result, 'c'); + +// setOrAdd with xpath that doesn't exist: add +result = xmlpoke('bval', xml => xml.setOrAdd('/a/c', 'cval')); +assert.equal(result, 'bvalcval'); + +// remove +result = xmlpoke('', xml => xml.remove('//b')); +assert.equal(result, ''); + +// clear +result = xmlpoke('', xml => xml.clear('/a')); +assert.equal(result, ''); + +// withBasePath, addNamespace, errorOnNoMatches +result = xmlpoke('', xml => + xml.withBasePath('/test') + .addNamespace('x', 'http://example.com/x') + .errorOnNoMatches() + .set('/x', (node, value) => { + assert.equal(typeof node, 'object'); + assert.equal((node.constructor as any).name, 'Element'); + assert.equal(value, 'hello'); + return 'y'; + })); +assert.equal(result, 'y'); diff --git a/xmlpoke/xmlpoke.d.ts b/xmlpoke/xmlpoke.d.ts new file mode 100644 index 0000000000..4b8868be98 --- /dev/null +++ b/xmlpoke/xmlpoke.d.ts @@ -0,0 +1,45 @@ +// Type definitions for xmlpoke 0.1.12 +// Project: https://github.com/mikeobrien/node-xmlpoke +// Definitions by: Garth Kidd +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module XmlPoke { // ghost module + interface Transform { + (node: Node, value: string): Value; + } + type Value = string | boolean | number | XmlValue | CDataValue | PathToValueMap | Transform; + type PathToValueMap = { + [xpath: string]: Value; + } + interface API { + add(xpath: string, value: Value): API; + add(map: PathToValueMap): API; + set(xpath: string, value: Value): API; + set(map: PathToValueMap): API; + setOrAdd(xpath: string, value: Value): API; + setOrAdd(map: PathToValueMap): API; + remove(xpath: string): API; + clear(xpath: string): API; + withBasePath(xpath: string): API; + addNamespace(prefix: string, uri: string): API; + errorOnNoMatches(): API; + } + interface CDataValue { + value: string; + } + interface XmlValue { + value: string; + } +} + +declare module 'xmlpoke' { + const xmlpoke: { + (xml: string, modify: (api: XmlPoke.API) => void): string; + CDataValue: new (value: string) => XmlPoke.CDataValue; + XmlString: new (value: string) => XmlPoke.XmlValue; + }; + namespace xmlpoke {} + export = xmlpoke; +} diff --git a/xrm/xrm.d.ts b/xrm/xrm.d.ts index cf2b4c77c3..824c91ba0c 100644 --- a/xrm/xrm.d.ts +++ b/xrm/xrm.d.ts @@ -786,7 +786,7 @@ declare namespace Xrm * * @return The event source. */ - getEventSource(): Attribute | Entity; + getEventSource(): Attribute | Control | Entity; /** * Gets the shared variable with the specified key. @@ -1726,7 +1726,7 @@ declare namespace Xrm * * @param {Function} handler The handler. */ - addPreSearch( handler: () => void ): void; + addPreSearch( handler: ContextSensitiveHandler ): void; /** * Adds an additional custom filter to the lookup, with the "AND" filter operator. diff --git a/yargs/yargs-tests.ts b/yargs/yargs-tests.ts index 14509d2072..c964e1b724 100644 --- a/yargs/yargs-tests.ts +++ b/yargs/yargs-tests.ts @@ -236,9 +236,10 @@ function completion_async() { } function Argv$help() { - var yargs1 = yargs - .usage("$0 -operand1 number -operand2 number -operation [add|subtract]"); - var s: string = yargs1.help(); + var argv = yargs + .usage("$0 -operand1 number -operand2 number -operation [add|subtract]") + .help() + .argv; } function Argv$showHelpOnFail() { @@ -321,3 +322,24 @@ function Argv$reset() { ya.showHelp(); } } + +// http://yargs.js.org/docs/#methods-commanddirdirectory-opts +function Argv$commandDir() { + var ya = yargs + .commandDir('.') + .argv +} + + +// http://yargs.js.org/docs/#methods-commanddirdirectory-opts +function Argv$commandDirWithOptions() { + var ya = yargs + .commandDir('.', { + recurse: false, + extensions: ['js'], + visit: (commandObject: any, pathToFile: string, filename: string) => { }, + include: /.*\.js$/, + exclude: /.*\.spec.js$/, + }) + .argv +} diff --git a/yargs/yargs.d.ts b/yargs/yargs.d.ts index 7dc1ef2319..e2f329e3c0 100644 --- a/yargs/yargs.d.ts +++ b/yargs/yargs.d.ts @@ -70,6 +70,8 @@ declare module "yargs" { command(command: string, description: string, builder: { [optionName: string]: Options }, handler: (args: Argv) => void): Argv; command(command: string, description: string, builder: (args: Argv) => Options, handler: (args: Argv) => void): Argv; + commandDir(dir: string, opts?: RequireDirectoryOptions): Argv; + completion(cmd: string, fn?: SyncCompletionFunction): Argv; completion(cmd: string, description?: string, fn?: SyncCompletionFunction): Argv; completion(cmd: string, fn?: AsyncCompletionFunction): Argv; @@ -95,7 +97,7 @@ declare module "yargs" { strict(): Argv; - help(): string; + help(): Argv; help(option: string, description?: string): Argv; env(prefix?: string): Argv; @@ -136,6 +138,14 @@ declare module "yargs" { fail(func: (msg: string) => any): void; } + interface RequireDirectoryOptions { + recurse?: boolean; + extensions?: string[]; + visit?: (commandObject: any, pathToFile?: string, filename?: string) => any; + include?: RegExp | ((pathToFile: string)=>boolean); + exclude?: RegExp | ((pathToFile: string)=>boolean); + } + interface Options { type?: string; group?: string; diff --git a/yeoman-generator/yeoman-generator.d.ts b/yeoman-generator/yeoman-generator.d.ts index ff3428ef61..e635126d15 100644 --- a/yeoman-generator/yeoman-generator.d.ts +++ b/yeoman-generator/yeoman-generator.d.ts @@ -31,7 +31,7 @@ declare namespace yo { fs: IMemFsEditor; } - export class YeomanGeneratorBase implements IYeomanGenerator, NodeJS.EventEmitter { + export class YeomanGeneratorBase extends NodeJS.EventEmitter implements IYeomanGenerator { argument(name: string, config: IArgumentConfig): void; composeWith(namespace: string, options: any, settings?: IComposeSetting): IYeomanGenerator; defaultFor(name: string): void;

      - *

      - *

      - *