Merge branch 'master' into ember-fix-isEvery

This commit is contained in:
Chris Krycho
2018-02-26 20:20:11 -07:00
committed by GitHub
371 changed files with 19949 additions and 9729 deletions
+1 -1
View File
@@ -1214,7 +1214,7 @@
/types/gm/ @ChaosinaCan @maartenvanvliet
/types/go/ @NorthwoodsSoftware
/types/google-adwords-scripts/ @jafaircl
/types/google-apps-script/ @motemen
/types/google-apps-script/ @motemen @grant
/types/google-apps-script-oauth2/ @dhayab
/types/google-cloud__datastore/ @beaulac
/types/google-cloud__pubsub/ @pheromonez
+492 -66
View File
@@ -1,79 +1,505 @@
// Note -- running these tests under cscript requires some ES5 polyfills
const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
const results: T[] = [];
const enumerator = new Enumerator<T>(col);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
results.push(enumerator.item());
enumerator.moveNext();
}
return results;
};
// source -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms630826(v=vs.85).aspx
{
const cd = new ActiveXObject('WIA.CommonDialog');
const dm = new ActiveXObject('WIA.DeviceManager');
// Convert a file
let commonDialog = new ActiveXObject('WIA.CommonDialog');
let img = commonDialog.ShowAcquireImage();
// Download new items as they are created
{
dm.RegisterEvent(WIA.EventID.wiaEventItemCreated, WIA.Miscellaneous.wiaAnyDeviceID);
ActiveXObject.on(dm, 'OnEvent', ['EventID', 'DeviceID', 'ItemID'], x => {
const dev = dm.DeviceInfos(x.DeviceID).Connect();
const itm = dev.GetItem(x.ItemID);
const img = cd.ShowTransfer(itm);
const v = img.FileData;
// Picture type not available in Javascript
});
}
// when DefinitelyTyped supports Typescript 2.4 -- end of July 2017, replace these:
let jpegFormatID = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}';
if (img.FormatID !== jpegFormatID) {
const ip = new ActiveXObject('WIA.ImageProcess');
ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID);
ip.Filters.Item(1).Properties.Item('FormatID').Value = jpegFormatID;
img = ip.Apply(img);
}
// with this:
/*if (img.FormatID !== WIA.FormatID.wiaFormatJPEG) {
let ip = new ActiveXObject('WIA.ImageProcess');
ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID);
ip.Filters.Item(1).Properties.Item('FormatID').Value = WIA.FormatID.wiaFormatJPEG;
img = ip.Apply(img);
}*/
// Take a picture
let dev = commonDialog.ShowSelectDevice();
if (dev.Type === WIA.WiaDeviceType.CameraDeviceType) {
// when DefinitelyTyped supports Typescript 2.4 -- end of July 2017, replace these:
const commandID = '{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}';
const itm = dev.ExecuteCommand(commandID);
// with this:
// let itm = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture);
}
// Display detailed property information
dev = commonDialog.ShowSelectDevice();
let e = new Enumerator<WIA.Property>(dev.Properties); // no foreach over ActiveX collections
e.moveFirst();
while (!e.atEnd()) {
const p = e.item();
let s = `${p.Name} (${p.PropertyID}) = `;
if (p.IsVector) {
s += '[vector of data]';
} else {
s += p.Value;
if (p.SubType !== WIA.WiaSubType.UnspecifiedSubType) {
if (p.Value !== p.SubTypeDefault) {
s += ` (Default = ${p.SubTypeDefault})`;
}
// Convert a file
{
let img = cd.ShowAcquireImage();
if (img && img.FormatID !== WIA.FormatID.wiaFormatJPEG) {
const ip = new ActiveXObject('WIA.ImageProcess');
ip.Filters.Add(ip.FilterInfos('Convert').FilterID);
ip.Filters(1).Properties('FormatID').Value = WIA.FormatID.wiaFormatJPEG;
img = ip.Apply(img);
}
}
if (p.IsReadOnly) {
s += ' [READ ONLY]';
} else {
switch (p.SubType) {
case WIA.WiaSubType.FlagSubType:
case WIA.WiaSubType.ListSubType:
if (p.SubType === WIA.WiaSubType.FlagSubType) {
s += ' [valid flags include: ';
// Take a picture
{
const dev = cd.ShowSelectDevice();
if (dev && dev.Type === WIA.WiaDeviceType.CameraDeviceType) {
const item = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture);
}
}
// Display detailed property information
{
const dev = cd.ShowSelectDevice();
if (dev) {
collectionToArray(dev.Properties).forEach(p => {
let s = `${p.Name} (${p.PropertyID}) = `;
if (p.IsVector) {
s += '[vector of data]';
} else {
s += ' [valid values include: ';
}
const count = p.SubTypeValues.Count;
for (let i = 1; i <= count; i++) {
s += p.SubTypeValues.Item(i);
if (i < count) {
s += ', ';
s += p.Value;
if (p.SubType !== WIA.WiaSubType.UnspecifiedSubType
&& p.Value !== p.SubTypeDefault) {
s += ` (Default = ${p.SubTypeDefault})`;
}
}
s += ']';
break;
case WIA.WiaSubType.RangeSubType:
s += ` [valid values in the range from ${p.SubTypeMin} to ${p.SubTypeMax} in increments of ${p.SubTypeStep}]`;
break;
if (p.IsReadOnly) {
s += ' [READ ONLY]';
} else {
switch (p.SubType) {
case WIA.WiaSubType.FlagSubType:
case WIA.WiaSubType.ListSubType:
const count = p.SubTypeValues.Count;
const items: string[] = [];
for (let i = 1; i <= count; i++) {
items.push(p.SubTypeValues(i));
}
const descr = p.SubType === WIA.WiaSubType.FlagSubType ? 'flags' : 'values';
s += ` [valid ${descr} include: ${items.join(',')}]`;
break;
case WIA.WiaSubType.RangeSubType:
s += ` [valid values in the range from ${p.SubTypeMin} to ${p.SubTypeMax} in increments of ${p.SubTypeStep}]`;
break;
}
}
WScript.Echo(s);
});
}
}
WScript.Echo(s);
// Determine whether the selected device is a camera
{
const dev = cd.ShowSelectDevice();
if (dev && dev.Type === WIA.WiaDeviceType.CameraDeviceType) {
WScript.Echo('Selectd device is a camera');
}
}
// Count root - level images for transfer
{
const dev = cd.ShowSelectDevice();
if (dev) {
const count = collectionToArray(dev.Items).filter(f => {
const imageFlag = WIA.WiaItemFlag.ImageItemFlag;
return (f.Properties('Item Flags').Value & imageFlag) === imageFlag;
}).length;
WScript.Echo(`Selected device has ${count} top-level images`);
}
}
// Display all imagefile properties
{
const img = cd.ShowAcquireImage();
if (img) {
collectionToArray(img.Properties).forEach(p => {
let contents = '';
if (p.IsVector) {
contents = '[vector data not emitted]';
} else if (p.Type === WIA.WiaImagePropertyType.RationalImagePropertyType) {
contents = `${p.Value.Nunerator}/${p.Value.Denominator}`;
} else if (p.Type === WIA.WiaImagePropertyType.StringImagePropertyType) {
contents = `"${p.Value}"`;
} else {
contents = p.Value;
}
WScript.Echo(`${p.Name} (${p.PropertyID}) = ${contents}`);
});
}
}
// Determine the event type
{
const dev = cd.ShowSelectDevice();
if (dev) {
const actionEvent = WIA.WiaEventFlag.ActionEvent;
collectionToArray(dev.Events).forEach(e => {
const msg = (e.Type & actionEvent) === actionEvent ?
`${e.Name} is an Action event` :
`${e.Name} is not an Action event`;
WScript.Echo(msg);
});
}
}
// Set rational numerator and denominator
{
const r = new ActiveXObject('WIA.Rational');
r.Numerator = 1;
r.Denominator = 3;
WScript.Echo(`1/3 = ${r.Value}`);
r.Numerator = 2;
r.Denominator = 6;
WScript.Echo(`2/6 = ${r.Value}`);
}
// Create and initialize a vector object
{
const v: WIA.Vector<number> = new ActiveXObject('WIA.Vector');
v.SetFromString('This is a test', true, false);
// when iterated using Enumerator / collectionToArray, each item comes back as an Automation Byte
// https://stackoverflow.com/questions/48757982/wia-vector-returns-something-which-is-not-a-number
// so the following falls, because fromCharCode is expecting a number
// collectionToArray(v).forEach(item => WScript.Echo(String.fromCharCode(item)));
// Instead, use the Vector's Item method, or the Vector's default property:
for (let i = 1; i <= v.Count; i++) {
WScript.Echo(String.fromCharCode(v(i)));
}
}
// Display detailed image information
{
const img = new ActiveXObject('WIA.ImageFile');
img.LoadFile('c:\\windows\\web\\Screen\\img102.jpg');
let s = `
Width = ${img.Width}
Height = ${img.Height}
Depth = ${img.PixelDepth}
Horizontal resolution = ${img.HorizontalResolution}
Vertical resolution = ${img.VerticalResolution}
Frame count = ${img.FrameCount}}
`.trim();
let arr: string[] = [];
if (img.IsIndexedPixelFormat) { arr.push('Pixel data contains palette indexes'); }
if (img.IsAlphaPixelFormat) { arr.push('Pixel data has alpha information'); }
if (img.IsExtendedPixelFormat) { arr.push('Pixel data has extended color information (16 bit/channel)'); }
if (img.IsAnimated) { arr.push('Image is animated'); }
const propertyTests = [40091, 40092, 40093, 40094, 40095]
.filter(n => img.Properties.Exists(n))
.map(n => {
const prp = img.Properties(n);
return `${prp.Name} = ${prp.Value.String}`;
});
arr = arr.concat(propertyTests);
if (arr.length) {
s += '\n' + arr.join('\n');
}
WScript.Echo(s);
}
// Create an imageprocess object and enumerate filters
{
const ip = new ActiveXObject('WIA.ImageProcess');
collectionToArray(ip.FilterInfos).forEach(fi => {
const s = [
fi.Name,
new Array(51).join('='),
fi.Description
].join('\n');
WScript.Echo(s);
});
}
// Create an imageprocess object and create one of each available filter
{
const ip = new ActiveXObject('WIA.ImageProcess');
const stringValue = (v: any) => {
if (typeof v === 'string') { return `"${v}"`; }
return v;
};
const listValues = (v: any) => collectionToArray(v).join(', ');
const listProperties = (filter: WIA.Filter) => {
let s = [
`${filter.Name} (${filter.FilterID})`,
new Array(51).join('='),
filter.Description,
new Array(51).join('=')
].map(line => line + '\n').join('');
s += collectionToArray(filter.Properties).map(p => {
let contents: string;
switch (typeof p.Value) {
// these case clauses replace the IsObject function in VB6/VBScript
case 'boolean':
case 'string':
case 'number':
contents = stringValue(p.Value);
default:
switch (p.SubType) {
case WIA.WiaSubType.FlagSubType:
contents = ` // [valid values formed by using the OR operator with the following bit flags: ${listValues(p.SubTypeValues)}]`;
break;
case WIA.WiaSubType.ListSubType:
contents = ` // [valid values from the following list: ${listValues(p.SubTypeValues)}]`;
break;
case WIA.WiaSubType.RangeSubType:
contents = ` // [valid values between ${p.SubTypeMin} and ${p.SubTypeMax}, with a step of ${p.SubTypeStep}]`;
break;
default:
contents = '';
break;
}
}
return `ip.Filters(1).Properties("${p.Name}") = ${contents}`;
}).join('\n');
WScript.Echo(s);
};
collectionToArray(ip.FilterInfos).forEach(fi => {
ip.Filters.Add(fi.FilterID);
listProperties(ip.Filters(1));
ip.Filters.Remove(1);
});
}
// List the supported transfer formats
{
const stringFormat = (fld: string) => {
switch (fld) {
case WIA.FormatID.wiaFormatBMP: return 'BMP';
case WIA.FormatID.wiaFormatPNG: return 'PNG';
case WIA.FormatID.wiaFormatGIF: return 'GIF';
case WIA.FormatID.wiaFormatJPEG: return 'JPEG';
case WIA.FormatID.wiaFormatTIFF: return 'TIFF';
default: return 'Unknown';
}
};
const dev = cd.ShowSelectDevice();
const items = dev && cd.ShowSelectItems(dev, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true);
if (items) {
WScript.Echo(collectionToArray(items(1).Formats).map(stringFormat).join(', '));
}
}
// Enumerate supported commands in commands collection
{
const dev = cd.ShowSelectDevice();
if (dev && collectionToArray(dev.Commands).some(dc => dc.CommandID === WIA.CommandID.wiaCommandTakePicture)) {
WScript.Echo('Selected device supports the TakePicture command');
}
}
// Enumerate root - level items and display their names
{
const dev = cd.ShowSelectDevice();
if (dev) {
collectionToArray(dev.Items).forEach(item => {
let s: string = item.Properties("Item Name").Value;
if (item.Properties.Exists("Item Time Stamp")) {
const v: WIA.Vector = item.Properties("Item Time Stamp").Value;
if (v.Count === 8) { s += ` (${v.Date})`; }
}
WScript.Echo(s);
});
}
}
// Determine the number of items returned by ShowSelectItems
{
const dev = cd.ShowSelectDevice();
const items = dev && cd.ShowSelectItems(dev, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true);
if (items) {
WScript.Echo(`You selected ${items.Count} items`);
}
}
// Enumerate all the supported events for the selected device
{
const dev = cd.ShowSelectDevice();
if (dev) {
const msg = collectionToArray(dev.Events)
.map(e => `\n${e.Name} (${e.EventID}): ${e.Description}`)
.join('');
WScript.Echo('The selected device supports the following events: ' + msg);
}
}
// List all available devices by name and deviceid
collectionToArray(dm.DeviceInfos).forEach(di => {
const name: string = di.Properties("Name").Value;
WScript.Echo(`${name} (${di.DeviceID})`);
});
// Display all the properties for the selected device
{
const dev = cd.ShowSelectDevice();
if (dev) {
collectionToArray(dev.Properties).forEach(p => {
const name = `${p.Name} (${p.PropertyID})`;
let contents: string;
if (p.IsVector) {
contents = '[vector of data]';
} else if (p.Type === WIA.WiaPropertyType.StringPropertyType) {
contents = `"${p.Value}"`;
} else {
contents = p.Value;
}
WScript.Echo(`${name} = ${contents}`);
});
}
}
// Enumerate the supported commands
{
const dev = cd.ShowSelectDevice();
const items = dev && cd.ShowSelectItems(dev, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true);
if (items) {
const msg = collectionToArray(items(1).Commands)
.map(c => `${c.Name}: ${c.Description}\n`)
.join('');
WScript.Echo(`The selected item supports the following commands:\n${msg}`);
}
}
// Create an imagefile object that contains a blank page
{
// This fails with the error: `The Vector's Type is not compatible with this operation`
/*const c = 0xFF0000FF;
const v: WIA.Vector<number> = new ActiveXObject('WIA.Vector');
for (let i = 0; i < 4; i++) {
v.Add(c);
}
const img = v.ImageFile(2, 2);
img.SaveFile('C:\\test.' + img.FileExtension);*/
}
interface WshArgumentsBase<TKey = number | string> {
Item(index: TKey): string;
(index: TKey): string;
length: number;
Count(): number;
}
interface WshArguments extends WshArgumentsBase { // not sure if WshArguments takes a string as well, or only a number
Named: WshArgumentsBase<string>;
Unnamed: WshArgumentsBase<number>;
ShowUsage(): void;
}
// Implement a windows script host script that runs automatically
{
const args = collectionToArray(WScript.Arguments as WshArguments)
.map(arg => arg.toLowerCase());
switch (args.length) {
case 1:
case 2:
const command = `${WScript.FullName} "${WScript.ScriptFullName}" connect`;
const name = 'QuickTransfer';
const title = 'Quick Scripting Transfer';
const icon = `${WScript.FullName}, 0`;
const eventID = WIA.EventID.wiaEventDeviceConnected;
const deviceID = args.length === 2 ? args[1] : WIA.Miscellaneous.wiaAnyDeviceID;
if (args[0] === 'register') {
WScript.Echo('Registering event handler');
dm.RegisterPersistentEvent(command, name, title, icon, eventID, deviceID);
WScript.Quit();
} else if (args[0] === 'unregister') {
WScript.Echo('Unregistering event handler');
dm.UnregisterPersistentEvent(command, name, title, icon, eventID, deviceID);
WScript.Quit();
}
break;
case 3:
if (args[0] === 'connect') {
const deviceID = args[1].substr(12);
const device = dm.DeviceInfos(deviceID).Connect();
collectionToArray(device.Items).forEach(item => {
const img = item.Transfer();
img.SaveFile(`C:\\${item.Properties('Item Name').Value}.${img.FileExtension}`);
// Uncomment the following lines to remove the picture from the camera after transfer
for (let i = 1; i < device.Items.Count; i++) {
const item2 = device.Items(i);
if (item2.ItemID !== item.ItemID) { continue; }
try {
// some cameras don't support deleting a picture
device.Items.Remove(i);
} catch (error) {
WScript.Echo(error);
}
}
});
WScript.Quit();
}
break;
}
const usage = `
Usage:
To register, type:
${WScript.ScriptName} register [<device id>]
To unregister, type:
${WScript.ScriptName} unregister [<device id>]
Available device ids:
${collectionToArray(dm.DeviceInfos)
.map(device => `${device.DeviceID} '${device.Properties("Name").Value}'`)
.join('\n')}
`.trim();
WScript.Echo(usage);
}
// Count the number of child items available for transfer
{
const device = cd.ShowSelectDevice();
const items = device && cd.ShowSelectItems(device, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true);
const item = items && items(1);
if (item) {
const count = collectionToArray(item.Items).filter(childItem => {
const flags = childItem.Properties('Item Flags').Value as number;
return (flags & WIA.WiaItemFlag.TransferItemFlag) === WIA.WiaItemFlag.TransferItemFlag;
}).length;
WScript.Echo(`Selected device has ${count} child items that can be transferred.`);
}
}
// Use a vector object
{
const v: WIA.Vector<number | string> = new ActiveXObject('WIA.Vector');
v.Add(1);
v.Add(42);
v.Add(3);
v.Remove(1);
v.Remove(2);
WScript.Echo(`v(1) = ${v(1)}`);
v.Clear();
v.Add('This');
v.Add('is');
v.Add('Cool');
v.Remove(1);
v.Remove(2);
WScript.Echo(`v(1) = ${v(1)}`);
}
}
+196 -148
View File
@@ -2,22 +2,20 @@
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms630368(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Typescript Version: 2.4
// TypeScript Version: 2.6
declare namespace WIA {
/** String versions of globally unique identifiers (GUIDs) that identify common Device and Item commands. */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum CommandID {
const enum CommandID {
wiaCommandChangeDocument = '{04E725B0-ACAE-11D2-A093-00C04F72DC3C}',
wiaCommandDeleteAllItems = '{E208C170-ACAD-11D2-A093-00C04F72DC3C}',
wiaCommandSynchronize = '{9B26B7B2-ACAD-11D2-A093-00C04F72DC3C}',
wiaCommandTakePicture = '{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}',
wiaCommandUnloadDocument = '{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}'
}*/
wiaCommandUnloadDocument = '{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}',
}
/** String versions of globally unique identifiers (GUIDs) that identify DeviceManager events. */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum EventID {
const enum EventID {
wiaEventDeviceConnected = '{A28BBADE-64B6-11D2-A231-00C04FA31809}',
wiaEventDeviceDisconnected = '{143E4E83-6497-11D2-A231-00C04FA31809}',
wiaEventItemCreated = '{4C8F4EF5-E14F-11D2-B326-00C04F68CE61}',
@@ -30,50 +28,48 @@ declare namespace WIA {
wiaEventScanImage3 = '{154E27BE-B617-4653-ACC5-0FD7BD4C65CE}',
wiaEventScanImage4 = '{A65B704A-7F3C-4447-A75D-8A26DFCA1FDF}',
wiaEventScanOCRImage = '{9D095B89-37D6-4877-AFED-62A297DC6DBE}',
wiaEventScanPrintImage = '{B441F425-8C6E-11D2-977A-0000F87A926F}'
}*/
wiaEventScanPrintImage = '{B441F425-8C6E-11D2-977A-0000F87A926F}',
}
/** String versions of globally unique identifiers (GUIDs) that indicate the file format of an image. */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum FormatID {
const enum FormatID {
wiaFormatBMP = '{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}',
wiaFormatGIF = '{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}',
wiaFormatJPEG = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}',
wiaFormatPNG = '{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}',
wiaFormatTIFF = '{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}'
}*/
wiaFormatTIFF = '{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}',
}
/** Miscellaneous string constants */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum Miscellaneous {
const enum Miscellaneous {
wiaAnyDeviceID = '*',
wiaIDUnknown = '{00000000-0000-0000-0000-000000000000}'
}*/
wiaIDUnknown = '{00000000-0000-0000-0000-000000000000}',
}
/**
* The WiaDeviceType enumeration specifies the type of device attached to a user's computer. Use the Type property on the DeviceInfo object or the Device
* object to obtain these values from the device.
* object to obtain these values from the device.
*/
const enum WiaDeviceType {
CameraDeviceType = 2,
ScannerDeviceType = 1,
UnspecifiedDeviceType = 0,
VideoDeviceType = 3
VideoDeviceType = 3,
}
/**
* A DeviceEvent's type is composed of bits from the WiaEventFlags enumeration. You can test a DeviceEvent's type by using the AND operation with DeviceEv
* ent.Type and a member from the WiaEventFlags enumeration.
* A DeviceEvent's type is composed of bits from the WiaEventFlags enumeration. You can test a DeviceEvent's type by using the AND operation with
* DeviceEvent.Type and a member from the WiaEventFlags enumeration.
*/
const enum WiaEventFlag {
ActionEvent = 2,
NotificationEvent = 1
NotificationEvent = 1,
}
/** The WiaImageBias enumeration helps specify what type of data the image is intended to represent. */
const enum WiaImageBias {
MaximizeQuality = 131072,
MinimizeSize = 65536
MinimizeSize = 65536,
}
/** The WiaImageIntent enumeration helps specify what type of data the image is intended to represent. */
@@ -81,12 +77,12 @@ declare namespace WIA {
ColorIntent = 1,
GrayscaleIntent = 2,
TextIntent = 4,
UnspecifiedIntent = 0
UnspecifiedIntent = 0,
}
/**
* The WiaImagePropertyType enumeration specifies the type of the value of an image property. Image properties can be found in the Properties collection o
* f an ImageFile object.
* The WiaImagePropertyType enumeration specifies the type of the value of an image property. Image properties can be found in the Properties collection
* of an ImageFile object.
*/
const enum WiaImagePropertyType {
ByteImagePropertyType = 1001,
@@ -103,12 +99,12 @@ declare namespace WIA {
VectorOfUndefinedImagePropertyType = 1100,
VectorOfUnsignedIntegersImagePropertyType = 1102,
VectorOfUnsignedLongsImagePropertyType = 1104,
VectorOfUnsignedRationalsImagePropertyType = 1106
VectorOfUnsignedRationalsImagePropertyType = 1106,
}
/**
* An Item's type is composed of bits from the WiaItemFlags enumeration. You can test an Item's type by using the AND operation with Item.Properties("Item
* Flags") and a member from the WiaItemFlags enumeration.
* An Item's type is composed of bits from the WiaItemFlags enumeration. You can test an Item's type by using the AND operation with
* Item.Properties("Item Flags") and a member from the WiaItemFlags enumeration.
*/
const enum WiaItemFlag {
AnalyzeItemFlag = 16,
@@ -129,12 +125,12 @@ declare namespace WIA {
StorageItemFlag = 4096,
TransferItemFlag = 8192,
VideoItemFlag = 65536,
VPanoramaItemFlag = 1024
VPanoramaItemFlag = 1024,
}
/**
* The WiaPropertyType enumeration specifies the type of the value of an item property. Item properties can be found in the Properties collection of a Dev
* ice or Item object.
* The WiaPropertyType enumeration specifies the type of the value of an item property. Item properties can be found in the Properties collection of a
* Device or Item object.
*/
const enum WiaPropertyType {
BooleanPropertyType = 1,
@@ -173,28 +169,31 @@ declare namespace WIA {
VectorOfUnsignedIntegersPropertyType = 104,
VectorOfUnsignedLargeIntegersPropertyType = 109,
VectorOfUnsignedLongsPropertyType = 106,
VectorOfVariantsPropertyType = 119
VectorOfVariantsPropertyType = 119,
}
/**
* The WiaSubType enumeration specifies more detail about the property value. Use the SubType property on the Property object to obtain these values for t
* he property.
* The WiaSubType enumeration specifies more detail about the property value. Use the SubType property on the Property object to obtain these values for
* the property.
*/
const enum WiaSubType {
FlagSubType = 3,
ListSubType = 2,
RangeSubType = 1,
UnspecifiedSubType = 0
UnspecifiedSubType = 0,
}
/**
* The CommonDialog control is an invisible-at-runtime control that contains all the methods that display a User Interface. A CommonDialog control can be
* created using "WIA.CommonDialog" in a call to CreateObject or by dropping a CommonDialog on a form.
* created using "WIA.CommonDialog" in a call to CreateObject or by dropping a CommonDialog on a form.
*/
interface CommonDialog {
class CommonDialog {
private constructor();
private 'WIA.CommonDialog_typekey': CommonDialog;
/**
* Displays one or more dialog boxes that enable the user to acquire an image from a hardware device for image acquisition and returns an ImageFile object
* on success, otherwise Nothing
* Displays one or more dialog boxes that enable the user to acquire an image from a hardware device for image acquisition and returns an ImageFile
* object on success, otherwise Nothing
* @param WIA.WiaDeviceType [DeviceType=0]
* @param WIA.WiaImageIntent [Intent=0]
* @param WIA.WiaImageBias [Bias=131072]
@@ -203,11 +202,11 @@ declare namespace WIA {
* @param boolean [UseCommonUI=true]
* @param boolean [CancelError=false]
*/
ShowAcquireImage(
DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean, CancelError?: boolean): ImageFile;
ShowAcquireImage(DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean,
CancelError?: boolean): ImageFile | null;
/** Launches the Windows Scanner and Camera Wizard and returns Nothing. Future versions may return a collection of ImageFile objects. */
ShowAcquisitionWizard(Device: Device): any;
ShowAcquisitionWizard(Device: Device): null;
/**
* Displays the properties dialog box for the specified Device
@@ -222,38 +221,41 @@ declare namespace WIA {
ShowItemProperties(Item: Item, CancelError?: boolean): void;
/** Launches the Photo Printing Wizard with the absolute path of a specific file or Vector of absolute paths to files */
ShowPhotoPrintingWizard(Files: any): void;
ShowPhotoPrintingWizard(Files: string | Vector<string>): void;
/**
* Displays a dialog box that enables the user to select a hardware device for image acquisition. Returns the selected Device object on success, otherwise
* Nothing
* Displays a dialog box that enables the user to select a hardware device for image acquisition. Returns the selected Device object on success,
* otherwise Nothing
* @param WIA.WiaDeviceType [DeviceType=0]
* @param boolean [AlwaysSelectDevice=false]
* @param boolean [CancelError=false]
*/
ShowSelectDevice(DeviceType?: WiaDeviceType, AlwaysSelectDevice?: boolean, CancelError?: boolean): Device;
ShowSelectDevice(DeviceType?: WiaDeviceType, AlwaysSelectDevice?: boolean, CancelError?: boolean): Device | null;
/**
* Displays a dialog box that enables the user to select an item for transfer from a hardware device for image acquisition. Returns the selection as an It
* ems collection on success, otherwise Nothing
* Displays a dialog box that enables the user to select an item for transfer from a hardware device for image acquisition. Returns the selection as an
* Items collection on success, otherwise Nothing
* @param WIA.WiaImageIntent [Intent=0]
* @param WIA.WiaImageBias [Bias=131072]
* @param boolean [SingleSelect=true]
* @param boolean [UseCommonUI=true]
* @param boolean [CancelError=false]
*/
ShowSelectItems(Device: Device, Intent?: WiaImageIntent, Bias?: WiaImageBias, SingleSelect?: boolean, UseCommonUI?: boolean, CancelError?: boolean): Items;
ShowSelectItems(Device: Device, Intent?: WiaImageIntent, Bias?: WiaImageBias, SingleSelect?: boolean, UseCommonUI?: boolean, CancelError?: boolean): Items | null;
/**
* Displays a progress dialog box while transferring the specified Item to the local machine. See Item.Transfer for additional information.
* @param string [FormatID='{00000000-0000-0000-0000-000000000000}']
* @param boolean [CancelError=false]
*/
ShowTransfer(Item: Item, FormatID?: string, CancelError?: boolean): any;
ShowTransfer(Item: Item, FormatID?: string, CancelError?: boolean): ImageFile;
}
/** The Device object represents an active connection to an imaging device. */
interface Device {
class Device {
private constructor();
private 'WIA.Device_typekey': Device;
/** A collection of all commands for this imaging device */
readonly Commands: DeviceCommands;
@@ -264,8 +266,8 @@ declare namespace WIA {
readonly Events: DeviceEvents;
/**
* Issues the command specified by CommandID to the imaging device. CommandIDs are device dependent. Valid CommandIDs for this Device are contained in the
* Commands collection.
* Issues the command specified by CommandID to the imaging device. CommandIDs are device dependent. Valid CommandIDs for this Device are contained in
* the Commands collection.
*/
ExecuteCommand(CommandID: string): Item;
@@ -280,13 +282,13 @@ declare namespace WIA {
/** Returns the Type of Device */
readonly Type: WiaDeviceType;
/** Returns the underlying IWiaItem interface for this Device object */
readonly WiaItem: any;
}
/** The DeviceCommand object describes a CommandID that can be used when calling ExecuteCommand on a Device or Item object. */
interface DeviceCommand {
class DeviceCommand {
private constructor();
private 'WIA.DeviceCommand_typekey': DeviceCommand;
/** Returns the commandID for this Command */
readonly CommandID: string;
@@ -298,8 +300,8 @@ declare namespace WIA {
}
/**
* The DeviceCommands object is a collection of all the supported DeviceCommands for an imaging device. See the Commands property of a Device or Item obje
* ct for more details on determining the collection of supported device commands.
* The DeviceCommands object is a collection of all the supported DeviceCommands for an imaging device. See the Commands property of a Device or Item
* object for more details on determining the collection of supported device commands.
*/
interface DeviceCommands {
/** Returns the number of members in the collection */
@@ -307,10 +309,16 @@ declare namespace WIA {
/** Returns the specified item in the collection by position */
Item(Index: number): DeviceCommand;
/** Returns the specified item in the collection by position */
(Index: number): DeviceCommand;
}
/** The DeviceEvent object describes an EventID that can be used when calling RegisterEvent or RegisterPersistentEvent on a DeviceManager object. */
interface DeviceEvent {
class DeviceEvent {
private constructor();
private 'WIA.DeviceEvent_typekey': DeviceEvent;
/** Returns the event Description */
readonly Description: string;
@@ -325,8 +333,8 @@ declare namespace WIA {
}
/**
* The DeviceEvents object is a collection of all the supported DeviceEvent for an imaging device. See the Events property of a Device object for more det
* ails on determining the collection of supported device events.
* The DeviceEvents object is a collection of all the supported DeviceEvent for an imaging device. See the Events property of a Device object for more
* details on determining the collection of supported device events.
*/
interface DeviceEvents {
/** Returns the number of members in the collection */
@@ -334,13 +342,19 @@ declare namespace WIA {
/** Returns the specified item in the collection by position */
Item(Index: number): DeviceEvent;
/** Returns the specified item in the collection by position */
(Index: number): DeviceEvent;
}
/**
* The DeviceInfo object is a container that describes the unchanging (static) properties of an imaging device that is currently connected to the computer
* .
* The DeviceInfo object is a container that describes the unchanging (static) properties of an imaging device that is currently connected to the
* computer.
*/
interface DeviceInfo {
class DeviceInfo {
private constructor();
private 'WIA.DeviceInfo_typekey': DeviceInfo;
/** Establish a connection with this device and return a Device object */
Connect(): Device;
@@ -355,59 +369,68 @@ declare namespace WIA {
}
/**
* The DeviceInfos object is a collection of all the imaging devices currently connected to the computer. See the DeviceInfos property on the DeviceManage
* r object for detail on accessing the DeviceInfos object.
* The DeviceInfos object is a collection of all the imaging devices currently connected to the computer. See the DeviceInfos property on the
* DeviceManager object for detail on accessing the DeviceInfos object.
*/
interface DeviceInfos {
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection either by position or Device ID */
Item(Index: any): DeviceInfo;
Item(Index: number | string): DeviceInfo;
/** Returns the specified item in the collection either by position or Device ID */
(Index: number | string): DeviceInfo;
}
/**
* The DeviceManager control is an invisible-at-runtime control that manages the imaging devices connected to the computer. A DeviceManager control can be
* created using "WIA.DeviceManager" in a call to CreateObject or by dropping a DeviceManager on a form.
* The DeviceManager control is an invisible-at-runtime control that manages the imaging devices connected to the computer. A DeviceManager control can
* be created using "WIA.DeviceManager" in a call to CreateObject or by dropping a DeviceManager on a form.
*/
interface DeviceManager {
class DeviceManager {
private constructor();
private 'WIA.DeviceManager_typekey': DeviceManager;
/** A collection of all imaging devices connected to this computer */
readonly DeviceInfos: DeviceInfos;
/**
* Registers the specified EventID for the specified DeviceID. If DeviceID is "*" then OnEvent will be called whenever the event specified occurs for any
* device. Otherwise, OnEvent will only be called if the event specified occurs on the device specified.
* device. Otherwise, OnEvent will only be called if the event specified occurs on the device specified.
* @param string [DeviceID='*']
*/
RegisterEvent(EventID: string, DeviceID?: string): void;
/**
* Registers the specified Command to launch when the specified EventID for the specified DeviceID occurs. Command can be either a ClassID or the full pat
* h name and the appropriate command-line arguments needed to invoke the application.
* Registers the specified Command to launch when the specified EventID for the specified DeviceID occurs. Command can be either a ClassID or the full
* path name and the appropriate command-line arguments needed to invoke the application.
* @param string [DeviceID='*']
*/
RegisterPersistentEvent(Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string): void;
/**
* Unregisters the specified EventID for the specified DeviceID. UnregisterEvent should only be called for EventID and DeviceID for which you called Regis
* terEvent.
* Unregisters the specified EventID for the specified DeviceID. UnregisterEvent should only be called for EventID and DeviceID for which you called
* RegisterEvent.
* @param string [DeviceID='*']
*/
UnregisterEvent(EventID: string, DeviceID?: string): void;
/**
* Unregisters the specified Command for the specified EventID for the specified DeviceID. UnregisterPersistentEvent should only be called for the Command
* , Name, Description, Icon, EventID and DeviceID for which you called RegisterPersistentEvent.
* Unregisters the specified Command for the specified EventID for the specified DeviceID. UnregisterPersistentEvent should only be called for the
* Command, Name, Description, Icon, EventID and DeviceID for which you called RegisterPersistentEvent.
* @param string [DeviceID='*']
*/
UnregisterPersistentEvent(Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string): void;
}
/**
* The Filter object represents a unit of modification on an ImageFile. To use a Filter, add it to the Filters collection, then set the filter's propertie
* s and finally use the Apply method of the ImageProcess object to filter an ImageFile.
* The Filter object represents a unit of modification on an ImageFile. To use a Filter, add it to the Filters collection, then set the filter's
* properties and finally use the Apply method of the ImageProcess object to filter an ImageFile.
*/
interface Filter {
class Filter {
private constructor();
private 'WIA.Filter_typekey': Filter;
/** Returns a Description of what the filter does */
readonly Description: string;
@@ -422,10 +445,13 @@ declare namespace WIA {
}
/**
* The FilterInfo object is a container that describes a Filter object without requiring a Filter to be Added to the process chain. See the FilterInfos pr
* operty on the ImageProcess object for details on accessing FilterInfo objects.
* The FilterInfo object is a container that describes a Filter object without requiring a Filter to be Added to the process chain. See the FilterInfos
* property on the ImageProcess object for details on accessing FilterInfo objects.
*/
interface FilterInfo {
class FilterInfo {
private constructor();
private 'WIA.FilterInfo_typekey': FilterInfo;
/** Returns a technical Description of what the filter does and how to use it in a filter chain */
readonly Description: string;
@@ -437,15 +463,18 @@ declare namespace WIA {
}
/**
* The FilterInfos object is a collection of all the available FilterInfo objects. See the FilterInfos property on the ImageProcess object for detail on a
* ccessing the FilterInfos object.
* The FilterInfos object is a collection of all the available FilterInfo objects. See the FilterInfos property on the ImageProcess object for detail on
* accessing the FilterInfos object.
*/
interface FilterInfos {
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection either by position or name */
Item(Index: any): FilterInfo;
Item(Index: number | string): FilterInfo;
/** Returns the specified item in the collection either by position or name */
(Index: number | string): FilterInfo;
}
/** The Filters object is a collection of the Filters that will be applied to an ImageFile when you call the Apply method on the ImageProcess object. */
@@ -464,11 +493,14 @@ declare namespace WIA {
/** Removes the designated filter */
Remove(Index: number): void;
/** Returns the specified item in the collection by position or FilterID */
(Index: number): Filter;
}
/**
* The Formats object is a collection of supported FormatIDs that you can use when calling Transfer on an Item object or ShowTransfer on a CommonDialog ob
* ject for this Item.
* The Formats object is a collection of supported FormatIDs that you can use when calling Transfer on an Item object or ShowTransfer on a CommonDialog
* object for this Item.
*/
interface Formats {
/** Returns the number of members in the collection */
@@ -476,13 +508,19 @@ declare namespace WIA {
/** Returns the specified item in the collection by position */
Item(Index: number): string;
/** Returns the specified item in the collection by position */
(Index: number): string;
}
/**
* The ImageFile object is a container for images transferred to your computer when you call Transfer or ShowTransfer. It also supports image files throug
* h LoadFile. An ImageFile object can be created using "WIA.ImageFile" in a call to CreateObject.
* The ImageFile object is a container for images transferred to your computer when you call Transfer or ShowTransfer. It also supports image files
* through LoadFile. An ImageFile object can be created using "WIA.ImageFile" in a call to CreateObject.
*/
interface ImageFile {
class ImageFile {
private constructor();
private 'WIA.ImageFile_typekey': ImageFile;
/** Returns/Sets the current frame in the image */
ActiveFrame: number;
@@ -539,7 +577,10 @@ declare namespace WIA {
}
/** The ImageProcess object manages the filter chain. An ImageProcess object can be created using "WIA.ImageProcess" in a call to CreateObject. */
interface ImageProcess {
class ImageProcess {
private constructor();
private 'WIA.ImageProcess_typekey': ImageProcess;
/** Takes the specified ImageFile and returns the new ImageFile with all the filters applied on success */
Apply(Source: ImageFile): ImageFile;
@@ -551,10 +592,13 @@ declare namespace WIA {
}
/**
* The Item object is a container for an item on an imaging device object. See the Items property on the Device or Item object for details on accessing It
* em objects.
* The Item object is a container for an item on an imaging device object. See the Items property on the Device or Item object for details on accessing
* Item objects.
*/
interface Item {
class Item {
private constructor();
private 'WIA.Item_typekey': Item;
/** A collection of all commands for this item */
readonly Commands: DeviceCommands;
@@ -574,17 +618,15 @@ declare namespace WIA {
readonly Properties: Properties;
/**
* Returns an ImageFile object, in this version, in the format specified in FormatID if supported, otherwise using the preferred format for this imaging d
* evice. Future versions may return a collection of ImageFile objects.
* Returns an ImageFile object, in this version, in the format specified in FormatID if supported, otherwise using the preferred format for this imaging
* device. Future versions may return a collection of ImageFile objects.
* @param string [FormatID='{00000000-0000-0000-0000-000000000000}']
*/
Transfer(FormatID?: string): any;
/** Returns the underlying IWiaItem interface for this Item object */
readonly WiaItem: any;
Transfer(FormatID?: string): ImageFile;
}
/** The Items object contains a collection of Item objects. See the Items property on the Device or Item object for details on accessing the Items object. */
// tslint:disable-next-line interface-name
interface Items {
/** Adds a new Item with the specified Name and Flags. The Flags value is created by using the OR operation with members of the WiaItemFlags enumeration. */
Add(Name: string, Flags: number): void;
@@ -597,28 +639,37 @@ declare namespace WIA {
/** Removes the designated Item */
Remove(Index: number): void;
/** Returns the specified item in the collection by position */
(Index: number): Item;
}
/**
* The Properties object is a collection of all the Property objects associated with a given Device, DeviceInfo, Filter, ImageFile or Item object. See the
* Properties property on any of these objects for detail on accessing the Properties object.
* The Properties object is a collection of all the Property objects associated with a given Device, DeviceInfo, Filter, ImageFile or Item object. See
* the Properties property on any of these objects for detail on accessing the Properties object.
*/
interface Properties {
/** Returns the number of members in the collection */
readonly Count: number;
/** Indicates whether the specified Property exists in the collection */
Exists(Index: any): boolean;
Exists(Index: number | string): boolean;
/** Returns the specified item in the collection either by position or name. */
Item(Index: any): Property;
Item(Index: number | string): Property;
/** Returns the specified item in the collection either by position or name. */
(Index: number | string): Property;
}
/**
* The Property object is a container for a property associated with a Device, DeviceInfo, Filter, ImageFile or Item object. See the Properties property o
* n any of these objects for details on accessing Property objects.
* The Property object is a container for a property associated with a Device, DeviceInfo, Filter, ImageFile or Item object. See the Properties property
* on any of these objects for details on accessing Property objects.
*/
interface Property {
class Property {
private constructor();
private 'WIA.Property_typekey': Property;
/** Indicates whether the Property Value is read only */
readonly IsReadOnly: boolean;
@@ -657,10 +708,13 @@ declare namespace WIA {
}
/**
* The Rational object is a container for the rational values found in Exif tags. It is a supported element type of the Vector object and may be created u
* sing "WIA.Rational" in a call to CreateObject.
* The Rational object is a container for the rational values found in Exif tags. It is a supported element type of the Vector object and may be created
* using "WIA.Rational" in a call to CreateObject.
*/
interface Rational {
class Rational {
private constructor();
private 'WIA.Rational_typekey': Rational;
/** Returns/Sets the Rational Value Denominator */
Denominator: number;
@@ -672,19 +726,19 @@ declare namespace WIA {
}
/**
* The Vector object is a collection of values of the same type. It is used throughout the library in many different ways. The Vector object may be create
* d using "WIA.Vector" in a call to CreateObject.
* The Vector object is a collection of values of the same type. It is used throughout the library in many different ways. The Vector object may be
* created using "WIA.Vector" in a call to CreateObject.
*/
interface Vector {
interface Vector<TItem = any> {
/**
* If Index is not zero, Inserts a new element into the Vector collection before the specified Index. If Index is zero, Appends a new element to the Vecto
* r collection.
* If Index is not zero, Inserts a new element into the Vector collection before the specified Index. If Index is zero, Appends a new element to the
* Vector collection.
* @param number [Index=0]
*/
Add(Value: any, Index?: number): void;
Add(Value: TItem, Index?: number): void;
/** Returns/Sets the Vector of Bytes as an array of bytes */
BinaryData: any;
BinaryData: SafeArray;
/** Removes all elements. */
Clear(): void;
@@ -696,30 +750,30 @@ declare namespace WIA {
Date: VarDate;
/**
* Used to get the Thumbnail property of an ImageFile which is an image file, The thumbnail property of an Item which is RGB data, or creating an ImageFil
* e from raw ARGB data. Returns an ImageFile object on success. See the Picture method for more details.
* Used to get the Thumbnail property of an ImageFile which is an image file, The thumbnail property of an Item which is RGB data, or creating an
* ImageFile from raw ARGB data. Returns an ImageFile object on success. See the Picture method for more details.
* @param number [Width=0]
* @param number [Height=0]
*/
ImageFile(Width?: number, Height?: number): ImageFile;
/** Returns/Sets the specified item in the vector by position */
Item(Index: number): any;
/** Returns the specified item in the vector by position */
Item(Index: number): TItem;
/**
* If the Vector of Bytes contains an image file, then Width and Height are ignored. Otherwise a Vector of Bytes must be RGB data and a Vector of Longs mu
* st be ARGB data. Returns a Picture object on success. See the ImageFile method for more details.
* If the Vector of Bytes contains an image file, then Width and Height are ignored. Otherwise a Vector of Bytes must be RGB data and a Vector of Longs
* must be ARGB data. Returns a Picture object on success. See the ImageFile method for more details.
* @param number [Width=0]
* @param number [Height=0]
*/
Picture(Width?: number, Height?: number): any;
/** Removes the designated element and returns it if successful */
Remove(Index: number): any;
Remove(Index: number): TItem | null;
/**
* Stores the string Value into the Vector of Bytes including the NULL terminator. Value may be truncated unless Resizable is True. The string will be sto
* red as an ANSI string unless Unicode is True, in which case it will be stored as a Unicode string.
* Stores the string Value into the Vector of Bytes including the NULL terminator. Value may be truncated unless Resizable is True. The string will be
* stored as an ANSI string unless Unicode is True, in which case it will be stored as a Unicode string.
* @param boolean [Resizable=true]
* @param boolean [Unicode=true]
*/
@@ -730,30 +784,24 @@ declare namespace WIA {
* @param boolean [Unicode=true]
*/
String(Unicode?: boolean): string;
/** Returns the specified item in the vector by position */
(Index: number): TItem;
}
}
interface ActiveXObject {
new<K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
on(obj: WIA.DeviceManager, event: 'OnEvent', argNames: ['EventID', 'DeviceID', 'ItemID'], handler: (
this: WIA.DeviceManager, parameter: {
EventID: string, DeviceID: string, ItemID: string}) => void): void;
set(obj: WIA.Vector, propertyName: 'Item', parameterTypes: [number], newValue: any): void;
new(progid: 'WIA.CommonDialog'): WIA.CommonDialog;
new(progid: 'WIA.DeviceManager'): WIA.DeviceManager;
new(progid: 'WIA.ImageFile'): WIA.ImageFile;
new(progid: 'WIA.ImageProcess'): WIA.ImageProcess;
new(progid: 'WIA.Rational'): WIA.Rational;
new(progid: 'WIA.Vector'): WIA.Vector;
this: WIA.DeviceManager, parameter: { readonly EventID: string, readonly DeviceID: string, readonly ItemID: string }) => void): void;
set<TItem>(obj: WIA.Vector<TItem>, propertyName: 'Item', parameterTypes: [number], newValue: TItem): void;
}
interface EnumeratorConstructor {
new(col: WIA.DeviceCommands): WIA.DeviceCommand;
new(col: WIA.DeviceEvents): WIA.DeviceEvent;
new(col: WIA.DeviceInfos): WIA.DeviceInfo;
new(col: WIA.FilterInfos): WIA.FilterInfo;
new(col: WIA.Filters): WIA.Filter;
new(col: WIA.Formats): string;
new(col: WIA.Items): WIA.Item;
new(col: WIA.Properties): WIA.Property;
new(col: WIA.Vector): any;
interface ActiveXObjectNameMap {
'WIA.CommonDialog': WIA.CommonDialog;
'WIA.DeviceManager': WIA.DeviceManager;
'WIA.ImageFile': WIA.ImageFile;
'WIA.ImageProcess': WIA.ImageProcess;
'WIA.Rational': WIA.Rational;
'WIA.Vector': WIA.Vector;
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"rules":{
"no-const-enum": false
}
}
@@ -0,0 +1,28 @@
import * as ampHtmlValidator from "amphtml-validator";
(async () => {
const validator = await ampHtmlValidator.getInstance();
const result = validator.validateString("<html></html>");
const { status, errors } = result;
if (status === "FAIL" || status === "UNKNOWN") {
const errs = errors.map(err => {
const {
severity,
line,
col,
message,
specUrl,
category,
code,
params
} = err;
return err;
});
}
})();
(() => {
const validator = ampHtmlValidator.newInstance("");
const result = validator.validateString("<html></html>");
const { status, errors } = result;
})();
+156
View File
@@ -0,0 +1,156 @@
// Type definitions for amphtml-validator 1.0
// Project: https://github.com/ampproject/amphtml/tree/master/validator/nodejs
// Definitions by: Kevin Tjiam <https://github.com/kevincharm>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="node" />
import { Context, Script } from "vm";
export interface ValidationError {
severity: ValidationErrorSeverity;
line: number;
col: number;
message: string;
specUrl: string | null;
category: ErrorCategoryCode;
code: ValidationErrorCode;
params: string[];
}
export interface ValidationResult {
status: ValidationResultStatus;
errors: ValidationError[];
}
export class Validator extends Script {
sandbox: Context;
validateString(stringToValidate: string): ValidationResult;
}
export function getInstance(
validatorJs?: string,
userAgent?: string
): Promise<Validator>;
export function newInstance(validatorJsContents: string): Validator;
/**
* Enums from protobufs
* https://github.com/ampproject/amphtml/blob/master/validator/validator.proto
*/
export type ValidationResultStatus = "UNKNOWN" | "PASS" | "FAIL";
export type ValidationErrorSeverity = "UNKNOWN_SEVERITY" | "ERROR" | "WARNING";
export type ErrorCategoryCode =
| "UNKNOWN"
| "GENERIC"
| "DISALLOWED_HTML_WITH_AMP_EQUIVALENT"
| "DISALLOWED_HTML"
| "AUTHOR_STYLESHEET_PROBLEM"
| "MANDATORY_AMP_TAG_MISSING_OR_INCORRECT"
| "AMP_TAG_PROBLEM"
| "CUSTOM_JAVASCRIPT_DISALLOWED"
| "AMP_LAYOUT_PROBLEM"
| "AMP_HTML_TEMPLATE_PROBLEM"
| "DEPRECATION";
export type ValidationErrorCode =
| "UNKNOWN_CODE"
| "MANDATORY_TAG_MISSING"
| "TAG_REQUIRED_BY_MISSING"
| "WARNING_TAG_REQUIRED_BY_MISSING"
| "WARNING_EXTENSION_UNUSED"
| "EXTENSION_UNUSED"
| "WARNING_EXTENSION_DEPRECATED_VERSION"
| "ATTR_REQUIRED_BUT_MISSING"
| "DISALLOWED_TAG"
| "GENERAL_DISALLOWED_TAG"
| "DISALLOWED_SCRIPT_TAG"
| "DISALLOWED_ATTR"
| "DISALLOWED_STYLE_ATTR"
| "INVALID_ATTR_VALUE"
| "DUPLICATE_ATTRIBUTE"
| "ATTR_VALUE_REQUIRED_BY_LAYOUT"
| "IMPLIED_LAYOUT_INVALID"
| "SPECIFIED_LAYOUT_INVALID"
| "MANDATORY_ATTR_MISSING"
| "MANDATORY_ONEOF_ATTR_MISSING"
| "DUPLICATE_DIMENSION"
| "DUPLICATE_UNIQUE_TAG"
| "DUPLICATE_UNIQUE_TAG_WARNING"
| "WRONG_PARENT_TAG"
| "STYLESHEET_TOO_LONG"
| "MANDATORY_CDATA_MISSING_OR_INCORRECT"
| "CDATA_VIOLATES_BLACKLIST"
| "NON_WHITESPACE_CDATA_ENCOUNTERED"
| "DEPRECATED_ATTR"
| "DEPRECATED_TAG"
| "MANDATORY_PROPERTY_MISSING_FROM_ATTR_VALUE"
| "INVALID_PROPERTY_VALUE_IN_ATTR_VALUE"
| "MISSING_URL"
| "INVALID_URL"
| "INVALID_URL_PROTOCOL"
| "DISALLOWED_DOMAIN"
| "DISALLOWED_RELATIVE_URL"
| "DISALLOWED_PROPERTY_IN_ATTR_VALUE"
| "MUTUALLY_EXCLUSIVE_ATTRS"
| "UNESCAPED_TEMPLATE_IN_ATTR_VALUE"
| "TEMPLATE_PARTIAL_IN_ATTR_VALUE"
| "TEMPLATE_IN_ATTR_NAME"
| "INCONSISTENT_UNITS_FOR_WIDTH_AND_HEIGHT"
| "DISALLOWED_TAG_ANCESTOR"
| "MANDATORY_LAST_CHILD_TAG"
| "MANDATORY_TAG_ANCESTOR"
| "MANDATORY_TAG_ANCESTOR_WITH_HINT"
| "ATTR_DISALLOWED_BY_IMPLIED_LAYOUT"
| "ATTR_DISALLOWED_BY_SPECIFIED_LAYOUT"
| "INCORRECT_NUM_CHILD_TAGS"
| "INCORRECT_MIN_NUM_CHILD_TAGS"
| "DISALLOWED_CHILD_TAG_NAME"
| "DISALLOWED_FIRST_CHILD_TAG_NAME"
| "DISALLOWED_MANUFACTURED_BODY"
| "CHILD_TAG_DOES_NOT_SATISFY_REFERENCE_POINT"
| "MANDATORY_REFERENCE_POINT_MISSING"
| "DUPLICATE_REFERENCE_POINT"
| "TAG_NOT_ALLOWED_TO_HAVE_SIBLINGS"
| "TAG_REFERENCE_POINT_CONFLICT"
| "CHILD_TAG_DOES_NOT_SATISFY_REFERENCE_POINT_SINGULAR"
| "BASE_TAG_MUST_PRECEED_ALL_URLS"
| "MISSING_REQUIRED_EXTENSION"
| "ATTR_MISSING_REQUIRED_EXTENSION"
| "DOCUMENT_TOO_COMPLEX"
| "INVALID_UTF8"
| "CSS_SYNTAX"
| "CSS_SYNTAX_INVALID_AT_RULE"
| "CSS_SYNTAX_STRAY_TRAILING_BACKSLASH"
| "CSS_SYNTAX_UNTERMINATED_COMMENT"
| "CSS_SYNTAX_UNTERMINATED_STRING"
| "CSS_SYNTAX_BAD_URL"
| "CSS_SYNTAX_EOF_IN_PRELUDE_OF_QUALIFIED_RULE"
| "CSS_SYNTAX_INVALID_DECLARATION"
| "CSS_SYNTAX_INCOMPLETE_DECLARATION"
| "CSS_SYNTAX_ERROR_IN_PSEUDO_SELECTOR"
| "CSS_SYNTAX_MISSING_SELECTOR"
| "CSS_SYNTAX_NOT_A_SELECTOR_START"
| "CSS_SYNTAX_UNPARSED_INPUT_REMAINS_IN_SELECTOR"
| "CSS_SYNTAX_MISSING_URL"
| "CSS_SYNTAX_INVALID_URL"
| "CSS_SYNTAX_INVALID_URL_PROTOCOL"
| "CSS_SYNTAX_DISALLOWED_DOMAIN"
| "CSS_SYNTAX_DISALLOWED_RELATIVE_URL"
| "CSS_SYNTAX_INVALID_ATTR_SELECTOR"
| "CSS_SYNTAX_INVALID_PROPERTY"
| "CSS_SYNTAX_INVALID_PROPERTY_NOLIST"
| "CSS_SYNTAX_QUALIFIED_RULE_HAS_NO_DECLARATIONS"
| "CSS_SYNTAX_DISALLOWED_QUALIFIED_RULE_MUST_BE_INSIDE_KEYFRAME"
| "CSS_SYNTAX_DISALLOWED_KEYFRAME_INSIDE_KEYFRAME"
| "CSS_SYNTAX_MALFORMED_MEDIA_QUERY"
| "CSS_SYNTAX_DISALLOWED_MEDIA_TYPE"
| "CSS_SYNTAX_DISALLOWED_MEDIA_FEATURE"
| "CSS_SYNTAX_DISALLOWED_PROPERTY_VALUE"
| "CSS_SYNTAX_DISALLOWED_PROPERTY_VALUE_WITH_HINT"
| "CSS_SYNTAX_PROPERTY_DISALLOWED_WITHIN_AT_RULE"
| "CSS_SYNTAX_PROPERTY_DISALLOWED_TOGETHER_WITH"
| "CSS_SYNTAX_PROPERTY_REQUIRES_QUALIFICATION";
+16
View File
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": ["index.d.ts", "amphtml-validator-tests.ts"]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1
View File
@@ -96,6 +96,7 @@ export interface ConnectionOptions {
authMechanism?: string;
vhost?: string;
noDelay?: boolean;
heartbeat?: number;
ssl?: {
enabled: boolean;
keyFile?: string;
+4 -4
View File
@@ -1,4 +1,3 @@
import * as AsyncLock from "async-lock";
const lock = new AsyncLock();
@@ -6,9 +5,9 @@ lock.acquire("key", (done) => {
done();
}, (err, ret) => { /* ... */ });
lock.acquire("key", (done) => {
done();
}).then(() => { /* ... */ });
lock.acquire("key", (done) => { done(); })
.then(() => { /* ... */ })
.catch(() => { /* ... */ });
lock.acquire("key", () => "stringValue")
// Check returned value's type is inherited properly
@@ -23,6 +22,7 @@ lock.acquire([ "key1", "key2" ], (done) => {
}, (err, ret) => { /* ... */ });
lock.isBusy();
lock.isBusy('key');
const lock2 = new AsyncLock({ timeout : 5000 });
const lock3 = new AsyncLock({ maxPending : 5000 });
+7 -8
View File
@@ -1,13 +1,12 @@
// Type definitions for async-lock
// Type definitions for async-lock 1.1
// Project: https://github.com/rain1017/async-lock
// Definitions by: Elisée MAURER <https://github.com/elisee>, Alejandro <https://github.com/afharo>
// Definitions by: Elisée MAURER <https://github.com/elisee>
// Alejandro <https://github.com/afharo>
// Anatoly <https://github.com/rhymmor>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
interface AsyncLockDoneCallback<T> {
(err?: Error, ret?: T): void;
}
type AsyncLockDoneCallback<T> = (err?: Error, ret?: T) => void;
interface AsyncLockOptions {
timeout?: number;
@@ -21,13 +20,13 @@ declare class AsyncLock {
acquire<T>(key: string | string[],
fn: (() => T | PromiseLike<T>) | ((done: AsyncLockDoneCallback<T>) => any),
opts?: AsyncLockOptions): PromiseLike<T>;
opts?: AsyncLockOptions): Promise<T>;
acquire<T>(key: string | string[],
fn: (done: AsyncLockDoneCallback<T>) => any,
cb: AsyncLockDoneCallback<T>,
opts?: AsyncLockOptions): void;
isBusy(): boolean;
isBusy(key?: string): boolean;
}
declare namespace AsyncLock { }
+1 -75
View File
@@ -1,77 +1,3 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
"extends": "dtslint/dt.json"
}
@@ -0,0 +1,38 @@
import Button, { ButtonGroup, themeNamespace } from "@atlaskit/button";
import * as React from "react";
import { render } from "react-dom";
declare const container: Element;
render(
<ButtonGroup appearance="primary">
<Button
appearance="danger"
ariaControls="some-aria-controls"
ariaExpanded={true}
ariaHaspopup={true}
className="some-class-name"
component={Button}
form="some-form"
href="some-href"
iconAfter={<div />}
iconBefore={<div />}
id="some-id"
innerRef={() => {}}
isDisabled={true}
isSelected={true}
key="some-key"
onClick={event => event.currentTarget.formMethod}
ref="some-ref"
shouldFitContainer={true}
spacing="compact"
tabIndex={88}
target="some-target"
type="button"
>
{themeNamespace}
</Button>
</ButtonGroup>,
container
);
+93
View File
@@ -0,0 +1,93 @@
// Type definitions for @atlaskit/button 6.4
// Project: https://bitbucket.org/atlassian/atlaskit-mk-2/
// Definitions by: Jimmy Luong <https://github.com/dijimsta>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
import {
Component,
ReactNode,
ReactElement,
ComponentClass,
MouseEventHandler
} from "react";
export type ButtonAppearances =
| "default"
| "danger"
| "link"
| "primary"
| "subtle"
| "subtle-link"
| "warning"
| "help";
export interface ButtonProps {
/** The base styling to apply to the button. */
readonly appearance?: ButtonAppearances;
/** Pass aria-controls to underlying html button. */
readonly ariaControls?: string;
/** Pass aria-expanded to underlying html button. */
readonly ariaExpanded?: boolean;
/** Pass aria-haspopup to underlying html button. */
readonly ariaHaspopup?: boolean;
/** This button's child nodes. */
readonly children?: ReactNode;
/** Add a classname to the button. */
readonly className?: string;
/** A custom component to use instead of the default button. */
readonly component?: ComponentClass<any>;
/** Name property of a linked form that the button submits when clicked. */
readonly form?: string;
/** Provides a url for buttons being used as a link. */
readonly href?: string;
/** Places an icon within the button, after the button's text. */
readonly iconAfter?: ReactElement<any>;
/** Places an icon within the button, before the button's text. */
readonly iconBefore?: ReactElement<any>;
/** Pass a reference on to the styled component */
readonly innerRef?: (instance: any) => void;
/** Provide a unique id to the button. */
readonly id?: string;
/** Set if the button is disabled. */
readonly isDisabled?: boolean;
/** Change the style to indicate the button is selected. */
readonly isSelected?: boolean;
/** Handler to be called on click. */
readonly onClick?: MouseEventHandler<HTMLButtonElement>;
/** Set the amount of padding in the button. */
readonly spacing?: ButtonSpacing;
/** Assign specific tabIndex order to the underlying html button. */
readonly tabIndex?: number;
/** Pass target down to a link within the button component, if a href is provided. */
readonly target?: string;
/** Set whether it is a button or a form submission. */
readonly type?: ButtonType;
/** Option to fit button width to its parent width */
readonly shouldFitContainer?: boolean;
}
export type ButtonType = "button" | "submit";
export type ButtonSpacing = "compact" | "default" | "none";
export interface ButtonState {
readonly isActive: boolean;
readonly isFocus: boolean;
readonly isHover: boolean;
}
declare class Button extends Component<ButtonProps, ButtonState> {}
export interface ButtonGroupProps {
/** The appearance to apply to all buttons. */
readonly appearance?: ButtonAppearances;
/** The buttons to render. */
readonly children: ReactNode;
}
export class ButtonGroup extends Component<ButtonGroupProps> {}
export const themeNamespace: string;
export default Button;
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6", "dom"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"jsx": "react",
"paths": {
"@atlaskit/button": ["atlaskit__button"]
}
},
"files": ["index.d.ts", "atlaskit__button-tests.tsx"]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+9 -1
View File
@@ -631,7 +631,15 @@ let apiGtwProxyHandler: AWSLambda.APIGatewayProxyHandler = (event: AWSLambda.API
let proxyHandler: AWSLambda.ProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.ProxyCallback) => { };
apiGtwProxyHandler = proxyHandler;
let cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLambda.CloudFrontRequestEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontRequestCallback) => { };
let cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLambda.CloudFrontRequestEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontRequestCallback) => {
cb();
cb(null);
cb(new Error(''));
cb(null, { clientIp: str, method: str, uri: str, querystring: str, headers: { } });
cb(null, { status: str });
// $ExpectError
cb(null, { });
};
let cloudFrontResponseHandler: AWSLambda.CloudFrontResponseHandler = (event: AWSLambda.CloudFrontResponseEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontResponseCallback) => { };
+2 -1
View File
@@ -15,6 +15,7 @@
// Palmi Valgeirsson <https://github.com/palmithor>
// Danilo Raisi <https://github.com/daniloraisi>
// Simon Buchan <https://github.com/simonbuchan>
// David Hayden <https://github.com/Haydabase>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -516,7 +517,7 @@ export interface CloudFrontResponseEvent {
}>;
}
export type CloudFrontRequestResult = undefined | null | CloudFrontResultResponse;
export type CloudFrontRequestResult = undefined | null | CloudFrontResultResponse | CloudFrontRequest;
export interface CloudFrontRequestEvent {
Records: Array<{
+1 -1
View File
@@ -422,7 +422,7 @@ export interface ExportNamedDeclaration extends Node {
type: "ExportNamedDeclaration";
declaration: Declaration;
specifiers: ExportSpecifier[];
source: StringLiteral;
source: StringLiteral | null;
}
export interface ExportSpecifier extends Node {
+8
View File
@@ -0,0 +1,8 @@
import * as base64topdf from 'base64topdf';
base64topdf.base64Encode('index.ts'); // $ExpectType void
base64topdf.base64Decode('decodethis', 'test.b64'); // $ExpectType void
base64topdf.rtfToText('rtf'); // $ExpectType string
base64topdf.textToRtf('text'); // $ExpectType string
base64topdf.strToBase64('str'); // $ExpectType string
base64topdf.base64ToStr('base64'); // $ExpectType string
+13
View File
@@ -0,0 +1,13 @@
// Type definitions for base64topdf 1.1
// Project: https://github.com/rpsankar001
// Definitions by: Lucas Riondel <https://github.com/lucasriondel>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export as namespace base64topdf;
export function base64Encode(file: string): void;
export function base64Decode(base64str: string, file: string): void;
export function rtfToText(rtfStr: string): string;
export function textToRtf(textStr: string): string;
export function strToBase64(str: string): string;
export function base64ToStr(base64Str: string): string;
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"base64topdf-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1
View File
@@ -295,6 +295,7 @@ export const Big: BigConstructor;
export type Big_ = Big;
export type BigConstructor_ = BigConstructor;
export type BigSource_ = BigSource;
export default Big;
declare global {
namespace BigJs {
@@ -0,0 +1,12 @@
/*
This file contains tests for the named export definitions of big.js.
Import the default Big constructor from 'big.js'
*/
import Big from 'big.js';
function constructorTests() {
const x = new Big(9); // '9'
}
+2 -1
View File
@@ -19,6 +19,7 @@
"files": [
"index.d.ts",
"test/big.js-module-tests.ts",
"test/big.js-global-tests.ts"
"test/big.js-global-tests.ts",
"test/big.js-import-default-tests.ts"
]
}
+1
View File
@@ -58,6 +58,7 @@ interface DatepickerOptions {
daysOfWeekHighlighted?:string|number[];
defaultViewDate?:Date|string|DatepickerViewDate;
updateViewDate?:boolean;
enableOnReadonly?: boolean;
}
interface DatepickerViewDate {
-5
View File
@@ -456,11 +456,6 @@ declare namespace Bull {
*/
getFailed(start?: number, end?: number): Promise<Job[]>;
/**
* Returns a promise that will return an array with the waiting jobs between start and end.
*/
getWaiting(start?: number, end?: number): Promise<Job[]>;
/**
* Returns JobInformation of repeatable jobs (ordered descending). Provide a start and/or an end
* index to limit the number of results. Start defaults to 0, end to -1 and asc to false.
@@ -0,0 +1,45 @@
import confetti = require("canvas-confetti");
confetti.Promise = null;
confetti();
confetti({
particleCount: 150
});
confetti({
spread: 180
});
confetti({
particleCount: 100,
startVelocity: 30,
spread: 360,
origin: {
x: Math.random(),
// since they fall down, start a bit higher than random
y: Math.random() - 0.2
}
});
confetti({
particleCount: 100,
spread: 70,
origin: {
y: 0.6
}
});
function r(min: number, max: number) {
return Math.random() * (max - min) + min;
}
confetti({
angle: r(55, 125),
spread: r(50, 70),
particleCount: r(50, 100),
origin: {
y: 0.6
}
});
+86
View File
@@ -0,0 +1,86 @@
// Type definitions for canvas-confetti 0.0
// Project: https://github.com/catdad/canvas-confetti#readme
// Definitions by: Martin Tracey <https://github.com/matracey>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* `confetti` takes a single optional object. When `window.Promise` is available, it will return a Promise to let you know when it is done. When promises are not available (like in IE), it will return
* `null`. You can polyfill promises using any of the popular polyfills. You can also provide a custom promise implementation to `confetti` through:
*
* `const MyPromise = require('some-promise-lib');
* const confetti = require('canvas-confetti');
* confetti.Promise = MyPromise;`
*
* If you call `confetti` multiple times before it is done, it
* will return the same promise every time. Internally, the same canvas element will be reused, continuing the existing animation with the new confetti added. The promise returned by each call to
* `confetti` will resolve once all animations are done.
*
*/
declare function confetti(options?: confetti.Options): Promise<null> | null;
declare namespace confetti {
/**
* You can polyfill promises using any of the popular polyfills. You can also provide a promise implementation to `confetti` through this property.
*/
let Promise: any;
interface Options {
/**
* The number of confetti to launch. More is always fun... but be cool, there's a lot of math involved.
* @default 50
*/
particleCount?: number;
/**
* The angle in which to launch the confetti, in degrees. 90 is straight up.
* @default 90
*/
angle?: number;
/**
* How far off center the confetti can go, in degrees. 45 means the confetti will launch at the defined angle plus or minus 22.5 degrees.
* @default 45
*/
spread?: number;
/**
* How fast the confetti will start going, in pixels.
* @default 45
*/
startVelocity?: number;
/**
* How quickly the confetti will lose speed. Keep this number between 0 and 1, otherwise the confetti will gain speed. Better yet, just never change it.
* @default 0.9
*/
decay?: number;
/**
* How many times the confetti will move. This is abstract... but play with it if the confetti disappear too quickly for you.
* @default 200
*/
ticks?: number;
/**
* Where to start firing confetti from. Feel free to launch off-screen if you'd like.
*/
origin?: Origin;
/**
* An array of color strings, in the HEX format... you know, like #bada55.
*/
colors?: string[];
/**
* The confetti should be on top, after all. But if you have a crazy high page, you can set it even higher.
* @default 100
*/
zIndex?: number;
}
interface Origin {
/**
* The x position on the page, with 0 being the left edge and 1 being the right edge.
* @default 0.5
*/
x?: number;
/**
* The y position on the page, with 0 being the left edge and 1 being the right edge.
* @default 0.5
*/
y?: number;
}
}
export = confetti;
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"canvas-confetti-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+12 -12
View File
@@ -1,26 +1,26 @@
import Catbox = require("catbox");
import { CacheItem, Client, Policy, EnginePrototypeOrObject } from "catbox";
const Memory: Catbox.EnginePrototypeOrObject = {
start(callback: Catbox.CallBackNoResult) {},
stop() {},
get() {},
set() {},
drop() {},
const Memory: EnginePrototypeOrObject = {
async start(): Promise<void> {},
stop(): void {},
async get(): Promise<null | CacheItem> {},
async set(): Promise<void> {},
async drop(): Promise<void> {},
isReady(): boolean { return true; },
validateSegmentName(segment: string): null { return null; },
};
const client = new Catbox.Client(Memory, { partition: 'cache' });
const client = new Client(Memory, { partition: 'cache' });
const cache = new Catbox.Policy({
const cache = new Policy({
expiresIn: 5000,
}, client, 'cache');
cache.set('foo', 'bar', 5000, () => {});
cache.set('foo', 'bar', 5000).then(() => {});
cache.get('foo', () => {});
cache.get('foo').then(() => {});
cache.drop('foo', () => {});
cache.drop('foo').then(() => {});
cache.isReady();
+44 -58
View File
@@ -1,14 +1,11 @@
// Type definitions for catbox 7.1
// Type definitions for catbox 10.0
// Project: https://github.com/hapijs/catbox
// Definitions by: Jason Swearingen <https://github.com/jasonswearingen>, AJP <https://github.com/AJamesPhillips>
// Definitions by: Jason Swearingen <https://github.com/jasonswearingen>
// AJP <https://github.com/AJamesPhillips>
// Rodrigo Saboya <https://github.com/saboya>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import * as Boom from 'boom';
export type CallBackNoResult = (err?: Boom.BoomError) => void;
export type CallBackWithResult<T> = (err: Boom.BoomError | null | undefined, result: T) => void;
/**
* Client
* The Client object provides a low-level cache abstraction. The object is constructed using new Client(engine, options) where:
@@ -23,34 +20,31 @@ export type CallBackWithResult<T> = (err: Boom.BoomError | null | undefined, res
export class Client implements ClientApi {
constructor(engine: EnginePrototypeOrObject, options: ClientOptions);
/** start(callback) - creates a connection to the cache server. Must be called before any other method is available. The callback signature is function(err). */
start(callback: CallBackNoResult): void;
/** start() - creates a connection to the cache server. Must be called before any other method is available. */
start(): Promise<void>;
/** stop() - terminates the connection to the cache server. */
stop(): void;
/**
* get(key, callback) - retrieve an item from the cache engine if found where:
* * key - a cache key object (see [ICacheKey]).
* * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned
*/
get(key: CacheKey, callback: CallBackWithResult<null | CachedObject>): CacheItem;
get(key: CacheKey): Promise<null | CachedObject>;
/**
* set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where:
* * key - a cache key object (see [ICacheKey]).
* * value - the string or object value to be stored.
* * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid).
* * callback - a function with the signature function(err).
*/
set(key: CacheKey, value: CacheItem, ttl: number, callback: CallBackNoResult): void;
set(key: CacheKey, value: CacheItem, ttl: number): Promise<void>;
/**
* drop(key, callback) - remove an item from cache where:
* * key - a cache key object (see [ICacheKey]).
* * callback - a function with the signature function(err).
*/
drop(key: CacheKey, callback: CallBackNoResult): void;
drop(key: CacheKey): Promise<void>;
/** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */
isReady(): boolean;
/** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */
validateSegmentName(segment: string): null | Boom.BoomError;
validateSegmentName(segment: string): null | Error;
}
export type EnginePrototypeOrObject = EnginePrototype | ClientApi;
@@ -68,34 +62,31 @@ export interface EnginePrototype {
* @see {@link https://github.com/hapijs/catbox#api}
*/
export interface ClientApi {
/** start(callback) - creates a connection to the cache server. Must be called before any other method is available. The callback signature is function(err). */
start(callback: CallBackNoResult): void;
/** start() - creates a connection to the cache server. Must be called before any other method is available. */
start(): Promise<void>;
/** stop() - terminates the connection to the cache server. */
stop(): void;
/**
* get(key, callback) - retrieve an item from the cache engine if found where:
* * key - a cache key object (see [ICacheKey]).
* * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned
*/
get(key: CacheKey, callback: CallBackWithResult<null | CachedObject>): CacheItem;
get(key: CacheKey): Promise<null | CachedObject>;
/**
* set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where:
* set(key, value, ttl) - store an item in the cache for a specified length of time, where:
* * key - a cache key object (see [ICacheKey]).
* * value - the string or object value to be stored.
* * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid).
* * callback - a function with the signature function(err).
*/
set(key: CacheKey, value: CacheItem, ttl: number, callback: CallBackNoResult): void;
set(key: CacheKey, value: CacheItem, ttl: number): Promise<void>;
/**
* drop(key, callback) - remove an item from cache where:
* drop(key) - remove an item from cache where:
* * key - a cache key object (see [ICacheKey]).
* * callback - a function with the signature function(err).
*/
drop(key: CacheKey, callback: CallBackNoResult): void;
drop(key: CacheKey): Promise<void>;
/** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */
isReady(): boolean;
/** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */
validateSegmentName(segment: string): null | Boom.BoomError;
validateSegmentName(segment: string): null | Error;
}
/**
@@ -135,27 +126,24 @@ export interface ClientOptions {
export class Policy implements PolicyAPI {
constructor(options: PolicyOptions, cache: Client, segment: string);
/**
* get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided,
* get(id) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided,
* a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are:
* * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key.
* * callback - the return function.
*/
get(id: string | {id: string}, callback: PolicyGetCallback): CacheItem;
get(id: string | { id: string }): Promise<PolicyGetPromiseResult | null>;
/**
* set(id, value, ttl, callback) - store an item in the cache where:
* set(id, value, ttl) - store an item in the cache where:
* * id - the unique item identifier (within the policy segment).
* * value - the string or object value to be stored.
* * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid).
* This should be set to 0 in order to use the caching rules configured when creating the Policy object.
* * callback - a function with the signature function(err).
*/
set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void;
set(id: string | { id: string }, value: CacheItem, ttl: number | null): Promise<void>;
/**
* drop(id, callback) - remove the item from cache where:
* drop(id) - remove the item from cache where:
* * id - the unique item identifier (within the policy segment).
* * callback - a function with the signature function(err).
*/
drop(id: string | {id: string}, callback: CallBackNoResult): void;
drop(id: string | { id: string }): Promise<void>;
/** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */
ttl(created: number): number;
/** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */
@@ -173,27 +161,24 @@ export class Policy implements PolicyAPI {
*/
export interface PolicyAPI {
/**
* get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided,
* get(id) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided,
* a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are:
* * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key.
* * callback - the return function.
*/
get(id: string | {id: string}, callback: PolicyGetCallback): CacheItem;
get(id: string | { id: string }): Promise<PolicyGetPromiseResult | null>;
/**
* set(id, value, ttl, callback) - store an item in the cache where:
* set(id, value, ttl) - store an item in the cache where:
* * id - the unique item identifier (within the policy segment).
* * value - the string or object value to be stored.
* * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid).
* This should be set to 0 in order to use the caching rules configured when creating the Policy object.
* * callback - a function with the signature function(err).
*/
set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void;
set(id: string | { id: string }, value: CacheItem, ttl: number | null): Promise<void>;
/**
* drop(id, callback) - remove the item from cache where:
* drop(id) - remove the item from cache where:
* * id - the unique item identifier (within the policy segment).
* * callback - a function with the signature function(err).
*/
drop(id: string | {id: string}, callback: CallBackNoResult): void;
drop(id: string | { id: string }): Promise<void>;
/** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */
ttl(created: number): number;
/** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */
@@ -204,16 +189,13 @@ export interface PolicyAPI {
stats(): CacheStatisticsObject;
}
/**
* The return function. The function signature is function(err, value, cached, report) where:
* @param err - any errors encountered.
* @param value - the fetched or generated value.
* @param cached - null if a valid item was not found in the cache, or IPolicyGetCallbackCachedOptions
* @param report - an object with logging information about the generation operation
*/
export type PolicyGetCallback = (err: null | Boom.BoomError, value: CacheItem, cached: PolicyGetCallbackCachedOptions, report: PolicyGetCallbackReportLog) => void;
export interface PolicyGetPromiseResult {
value: CacheItem;
cached: PolicyGetCachedOptions;
report: PolicyGetReportLog;
}
export interface PolicyGetCallbackCachedOptions {
export interface PolicyGetCachedOptions {
/** item - the cached value. */
item: CacheItem;
/** stored - the timestamp when the item was stored in the cache. */
@@ -262,10 +244,14 @@ export interface PolicyOptions {
pendingGenerateTimeout?: number;
}
export interface GenerateFuncFlags {
ttl: number;
}
/**
* generateFunc
* Is used in PolicyOptions
* A function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next)
* A function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id)
* @param id - the id string or object provided to the get() method.
* @param next - the method called when the new item is returned with the signature function(err, value, ttl) where:
* * err - an error condition.
@@ -273,12 +259,12 @@ export interface PolicyOptions {
* * ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy.
* @see {@link https://github.com/hapijs/catbox#policy}
*/
export type GenerateFunc = (id: string, next: ((err: null | Boom.BoomError, value: CacheItem, ttl?: number) => void)) => void;
export type GenerateFunc = (id: string, flags: GenerateFuncFlags) => Promise<CacheItem>;
/**
* An object with logging information about the generation operation containing the following keys (as relevant):
*/
export interface PolicyGetCallbackReportLog {
export interface PolicyGetReportLog {
/** msec - the cache lookup time in milliseconds. */
msec: number;
/** stored - the timestamp when the item was stored in the cache. */
@@ -288,7 +274,7 @@ export interface PolicyGetCallbackReportLog {
/** ttl - the cache ttl value for the record. */
ttl: number;
/** error - lookup error. */
error?: Boom.BoomError;
error?: Error;
}
/**
-5
View File
@@ -13,11 +13,6 @@
"../"
],
"types": [],
"paths": {
"boom": [
"boom/v4"
]
},
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
+27
View File
@@ -0,0 +1,27 @@
import Catbox = require("catbox");
const Memory: Catbox.EnginePrototypeOrObject = {
start(callback: Catbox.CallBackNoResult) {},
stop() {},
get() {},
set() {},
drop() {},
isReady(): boolean { return true; },
validateSegmentName(segment: string): null { return null; },
};
const client = new Catbox.Client(Memory, { partition: 'cache' });
const cache = new Catbox.Policy({
expiresIn: 5000,
}, client, 'cache');
cache.set('foo', 'bar', 5000, () => {});
cache.get('foo', () => {});
cache.drop('foo', () => {});
cache.isReady();
cache.stats();
+310
View File
@@ -0,0 +1,310 @@
// Type definitions for catbox 7.1
// Project: https://github.com/hapijs/catbox
// Definitions by: Jason Swearingen <https://github.com/jasonswearingen>, AJP <https://github.com/AJamesPhillips>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import * as Boom from 'boom';
export type CallBackNoResult = (err?: Boom.BoomError) => void;
export type CallBackWithResult<T> = (err: Boom.BoomError | null | undefined, result: T) => void;
/**
* Client
* The Client object provides a low-level cache abstraction. The object is constructed using new Client(engine, options) where:
* engine - is an object or a prototype function implementing the cache strategy:
* * function - a prototype function with the signature function(options). catbox will call new func(options).
* * object - a pre instantiated client implementation object. Does not support passing options.
* options - the strategy configuration object. Each strategy defines its own configuration options with the following common options:
* * partition - the partition name used to isolate the cached results across multiple clients. The partition name is used as the MongoDB database name,
* the Riak bucket, or as a key prefix in Redis and Memcached. To share the cache across multiple clients, use the same partition name.
* @see {@link https://github.com/hapijs/catbox#client}
*/
export class Client implements ClientApi {
constructor(engine: EnginePrototypeOrObject, options: ClientOptions);
/** start(callback) - creates a connection to the cache server. Must be called before any other method is available. The callback signature is function(err). */
start(callback: CallBackNoResult): void;
/** stop() - terminates the connection to the cache server. */
stop(): void;
/**
* get(key, callback) - retrieve an item from the cache engine if found where:
* * key - a cache key object (see [ICacheKey]).
* * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned
*/
get(key: CacheKey, callback: CallBackWithResult<null | CachedObject>): CacheItem;
/**
* set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where:
* * key - a cache key object (see [ICacheKey]).
* * value - the string or object value to be stored.
* * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid).
* * callback - a function with the signature function(err).
*/
set(key: CacheKey, value: CacheItem, ttl: number, callback: CallBackNoResult): void;
/**
* drop(key, callback) - remove an item from cache where:
* * key - a cache key object (see [ICacheKey]).
* * callback - a function with the signature function(err).
*/
drop(key: CacheKey, callback: CallBackNoResult): void;
/** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */
isReady(): boolean;
/** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */
validateSegmentName(segment: string): null | Boom.BoomError;
}
export type EnginePrototypeOrObject = EnginePrototype | ClientApi;
/**
* A prototype CatBox engine function
*/
export interface EnginePrototype {
new(settings: ClientOptions): ClientApi;
}
/**
* Client API
* The Client object provides the following methods:
* @see {@link https://github.com/hapijs/catbox#api}
*/
export interface ClientApi {
/** start(callback) - creates a connection to the cache server. Must be called before any other method is available. The callback signature is function(err). */
start(callback: CallBackNoResult): void;
/** stop() - terminates the connection to the cache server. */
stop(): void;
/**
* get(key, callback) - retrieve an item from the cache engine if found where:
* * key - a cache key object (see [ICacheKey]).
* * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned
*/
get(key: CacheKey, callback: CallBackWithResult<null | CachedObject>): CacheItem;
/**
* set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where:
* * key - a cache key object (see [ICacheKey]).
* * value - the string or object value to be stored.
* * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid).
* * callback - a function with the signature function(err).
*/
set(key: CacheKey, value: CacheItem, ttl: number, callback: CallBackNoResult): void;
/**
* drop(key, callback) - remove an item from cache where:
* * key - a cache key object (see [ICacheKey]).
* * callback - a function with the signature function(err).
*/
drop(key: CacheKey, callback: CallBackNoResult): void;
/** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */
isReady(): boolean;
/** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */
validateSegmentName(segment: string): null | Boom.BoomError;
}
/**
* Any method with a key argument takes an object with the following required properties:
*/
export interface CacheKey {
/** segment - a caching segment name string. Enables using a single cache server for storing different sets of items with overlapping ids. */
segment: string;
/** id - a unique item identifier string (per segment). Can be an empty string. */
id: string;
}
/** Cached object contains the following: */
export interface CachedObject {
/** item - the value stored in the cache using set(). */
item: any;
/** stored - the timestamp when the item was stored in the cache (in milliseconds). */
stored: number;
/** ttl - the remaining time-to-live (not the original value used when storing the object). */
ttl: number;
}
export type CacheItem = any;
export interface ClientOptions {
partition: string;
}
/**
* The Policy object provides a convenient cache interface by setting a global policy which is automatically applied to every storage action.
* The object is constructed using new Policy(options, [cache, segment]) where:
* * options - an object with the IPolicyOptions structure
* * cache - a Client instance (which has already been started).
* * segment - required when cache is provided. The segment name used to isolate cached items within the cache partition.
* @see {@link https://github.com/hapijs/catbox#policy}
*/
export class Policy implements PolicyAPI {
constructor(options: PolicyOptions, cache: Client, segment: string);
/**
* get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided,
* a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are:
* * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key.
* * callback - the return function.
*/
get(id: string | {id: string}, callback: PolicyGetCallback): CacheItem;
/**
* set(id, value, ttl, callback) - store an item in the cache where:
* * id - the unique item identifier (within the policy segment).
* * value - the string or object value to be stored.
* * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid).
* This should be set to 0 in order to use the caching rules configured when creating the Policy object.
* * callback - a function with the signature function(err).
*/
set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void;
/**
* drop(id, callback) - remove the item from cache where:
* * id - the unique item identifier (within the policy segment).
* * callback - a function with the signature function(err).
*/
drop(id: string | {id: string}, callback: CallBackNoResult): void;
/** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */
ttl(created: number): number;
/** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */
rules(options: PolicyOptions): void;
/** isReady() - returns true if cache engine determines itself as ready, false if it is not ready or if there is no cache engine set. */
isReady(): boolean;
/** stats - an object with cache statistics */
stats(): CacheStatisticsObject;
}
/**
* Policy API
* The Policy object provides the following methods:
* @see {@link https://github.com/hapijs/catbox#api-1}
*/
export interface PolicyAPI {
/**
* get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided,
* a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are:
* * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key.
* * callback - the return function.
*/
get(id: string | {id: string}, callback: PolicyGetCallback): CacheItem;
/**
* set(id, value, ttl, callback) - store an item in the cache where:
* * id - the unique item identifier (within the policy segment).
* * value - the string or object value to be stored.
* * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid).
* This should be set to 0 in order to use the caching rules configured when creating the Policy object.
* * callback - a function with the signature function(err).
*/
set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void;
/**
* drop(id, callback) - remove the item from cache where:
* * id - the unique item identifier (within the policy segment).
* * callback - a function with the signature function(err).
*/
drop(id: string | {id: string}, callback: CallBackNoResult): void;
/** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */
ttl(created: number): number;
/** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */
rules(options: PolicyOptions): void;
/** isReady() - returns true if cache engine determines itself as ready, false if it is not ready or if there is no cache engine set. */
isReady(): boolean;
/** stats - an object with cache statistics */
stats(): CacheStatisticsObject;
}
/**
* The return function. The function signature is function(err, value, cached, report) where:
* @param err - any errors encountered.
* @param value - the fetched or generated value.
* @param cached - null if a valid item was not found in the cache, or IPolicyGetCallbackCachedOptions
* @param report - an object with logging information about the generation operation
*/
export type PolicyGetCallback = (err: null | Boom.BoomError, value: CacheItem, cached: PolicyGetCallbackCachedOptions, report: PolicyGetCallbackReportLog) => void;
export interface PolicyGetCallbackCachedOptions {
/** item - the cached value. */
item: CacheItem;
/** stored - the timestamp when the item was stored in the cache. */
stored: number;
/** ttl - the cache ttl value for the record. */
ttl: number;
/** isStale - true if the item is stale. */
isStale: boolean;
}
/**
* @see {@link https://github.com/hapijs/catbox#policy}
*/
export interface PolicyOptions {
/** expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */
expiresIn?: number;
/** expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Uses local time. Cannot be used together with expiresIn. */
expiresAt?: string;
/** generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: */
generateFunc?: GenerateFunc;
/**
* staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided.
* Must be less than expiresIn. Alternatively function that returns staleIn value in milliseconds. The function signature is function(stored, ttl) where:
* * stored - the timestamp when the item was stored in the cache (in milliseconds).
* * ttl - the remaining time-to-live (not the original value used when storing the object).
*/
staleIn?: number | ((stored: number, ttl: number) => number);
/** staleTimeout - number of milliseconds to wait before returning a stale value while generateFunc is generating a fresh value. */
staleTimeout?: number;
/**
* generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value.
* When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present.
* Set to false to disable timeouts which may cause all get() requests to get stuck forever.
*/
generateTimeout?: number | false;
/** dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. */
dropOnError?: boolean;
/** generateOnReadError - if false, an upstream cache read error will stop the get() method from calling the generate function and will instead pass back the cache error. Defaults to true. */
generateOnReadError?: boolean;
/** generateIgnoreWriteError - if false, an upstream cache write error will be passed back with the generated value when calling the get() method. Defaults to true. */
generateIgnoreWriteError?: boolean;
/**
* pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed.
* Defaults to 0, no blocking of concurrent generateFunc calls beyond staleTimeout.
*/
pendingGenerateTimeout?: number;
}
/**
* generateFunc
* Is used in PolicyOptions
* A function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next)
* @param id - the id string or object provided to the get() method.
* @param next - the method called when the new item is returned with the signature function(err, value, ttl) where:
* * err - an error condition.
* * value - the new value generated.
* * ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy.
* @see {@link https://github.com/hapijs/catbox#policy}
*/
export type GenerateFunc = (id: string, next: ((err: null | Boom.BoomError, value: CacheItem, ttl?: number) => void)) => void;
/**
* An object with logging information about the generation operation containing the following keys (as relevant):
*/
export interface PolicyGetCallbackReportLog {
/** msec - the cache lookup time in milliseconds. */
msec: number;
/** stored - the timestamp when the item was stored in the cache. */
stored: number;
/** isStale - true if the item is stale. */
isStale: boolean;
/** ttl - the cache ttl value for the record. */
ttl: number;
/** error - lookup error. */
error?: Boom.BoomError;
}
/**
* an object with cache statistics where:
*/
export interface CacheStatisticsObject {
/** sets - number of cache writes. */
sets: number;
/** gets - number of cache get() requests. */
gets: number;
/** hits - number of cache get() requests in which the requested id was found in the cache (can be stale). */
hits: number;
/** stales - number of cache reads with stale requests (only counts the first request in a queued get() operation). */
stales: number;
/** generates - number of calls to the generate function. */
generates: number;
/** errors - cache operations errors. TODO check this */
errors: number;
}
+31
View File
@@ -0,0 +1,31 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"types": [],
"paths": {
"boom": [
"boom/v4"
],
"catbox": [
"catbox/v7"
]
},
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"catbox-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1 -1
View File
@@ -149,7 +149,7 @@ export interface WatchOptions {
/**
* can be set to an object in order to adjust timing params:
*/
awaitWriteFinish?: AwaitWriteFinishOptions;
awaitWriteFinish?: AwaitWriteFinishOptions | boolean;
}
export interface AwaitWriteFinishOptions {
+2 -2
View File
@@ -427,7 +427,7 @@ declare namespace cytoscape {
/**
* Get elements in the graph matching the specified selector or filter function.
*/
filter(selector: Selector | ((i: number, ele: Singular) => boolean)): CollectionElements;
filter(selector: Selector | ((ele: Singular, i: number, eles: CollectionElements) => boolean)): CollectionElements;
/**
* Allow for manipulation of elements without triggering multiple style calculations or multiple redraws.
@@ -2231,7 +2231,7 @@ declare namespace cytoscape {
* ele - The element being considered.
* http://js.cytoscape.org/#eles.filter
*/
filter(selector: Selector | ((i: number, ele: CollectionElements) => boolean)): CollectionElements;
filter(selector: Selector | ((ele: Singular, i: number, eles: CollectionElements) => boolean)): CollectionElements;
/**
* Get the nodes that match the specified selector.
*
+14 -7
View File
@@ -38,6 +38,7 @@ let booleanFlag: boolean;
// test keys(...) signatures ------------------------------------------------------
stringArray = d3Collection.keys(keyValueObj);
stringArray = d3Collection.keys([0, 1, 2]);
stringArray = d3Collection.keys(document); // purely for the fun of it
@@ -48,17 +49,21 @@ anyArray = d3Collection.values(keyValueObj);
stringArray = d3Collection.values(keyValueObj2);
stringArray = d3Collection.values<string>(keyValueObj2);
// stringArray = d3Collection.values<string>(keyValueObj); // test fails, as values in keyValueObj do not meet generic constraint
stringArray = d3Collection.values(['1', '2']);
anyArray = d3Collection.values(document); // purely for the fun of it
// test entries(...) signatures ------------------------------------------------------
anyKVArray = d3Collection.entries(keyValueObj);
// stringKVArray = d3Collection.entres(keyValueObj); // test fails, as values in keyValueObj are not all strings
// stringKVArray = d3Collection.entries(keyValueObj); // test fails, as values in keyValueObj are not all strings
stringKVArray = d3Collection.entries(keyValueObj2);
stringKVArray = d3Collection.entries<string>(keyValueObj2);
// stringKVArray = d3Collection.entries<string>(keyValueObj); // test fails, as values in keyValueObj do not meet generic constraint
stringKVArray = d3Collection.entries(['1', '2']);
anyKVArray = d3Collection.entries(document); // purely for the fun of it
// ---------------------------------------------------------------------
@@ -70,13 +75,15 @@ interface TestObject {
val: number;
}
let testObject: TestObject;
let testObjectMaybe: TestObject | undefined;
let testObjArray: TestObject[];
let testObjKVArray: Array<{ key: string, value: TestObject }>;
// Create Map ========================================================
let basicMap: d3Collection.Map<string>;
let anyMap: d3Collection.Map<any>;
anyMap = d3Collection.map(); // empty map
basicMap = d3Collection.map<string>(); // empty map
// from array with accessor without accessor
@@ -107,7 +114,7 @@ booleanFlag = basicMap.has('foo');
// get(...) ------------------------------------------------------------
testObject = testObjMap.get('foo');
testObjectMaybe = testObjMap.get('foo');
// set(...) ------------------------------------------------------------
@@ -304,11 +311,11 @@ let testL1NestedMapRollup: TestL1NestedMapRollup;
testL2NestedMap = nestL2.map(raw);
num = testL2NestedMap.get('1931').get('Manchuria')[0].yield; // access chain to leaf property
num = testL2NestedMap.get('1931')!.get('Manchuria')![0].yield; // use existence assertion with care for access chain to leaf property
testL1NestedMapRollup = nestL1Rollup.map(raw);
num = testL1NestedMapRollup.get('1931'); // get rollup value
num = testL1NestedMapRollup.get('1931')!; // get rollup value (use existence assertion with care)
// object(...) --------------------------------------------------------
@@ -345,7 +352,7 @@ type TestL2NestedArray = Array<{
type TestL1NestedArrayRollup = Array<{
key: string;
value: number;
value?: number; // conservatively allow for value to be undefined
}>;
let testL2NestedArray: TestL2NestedArray;
@@ -357,4 +364,4 @@ num = testL2NestedArray[0].values[0].values[0].yield; // access chain to leaf pr
testL1NestedArrayRollup = nestL1Rollup.entries(raw);
num = testL1NestedArrayRollup[0].value; // get rollup value
num = testL1NestedArrayRollup[0].value!; // get rollup value use existence assertion with care
+402 -40
View File
@@ -2,8 +2,9 @@
// Project: https://github.com/d3/d3-collection/
// Definitions by: Tom Wanzek <https://github.com/tomwanzek>, Alex Ford <https://github.com/gustavderdrache>, Boris Yankov <https://github.com/borisyankov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// Last module patch version validated against: 1.0.1
// Last module patch version validated against: 1.0.4
/**
* Reference type things that can be coerced to string implicitely
@@ -16,106 +17,467 @@ export interface Stringifiable {
// Objects
// ---------------------------------------------------------------------
export function keys(object: { [key: string]: any }): string[];
// TODO: When upgrading definitions to use TS 2.2+, use "object" data type in next line
export function keys(object: any): string[];
/**
* Returns an array containing the property names of the specified object (an associative array).
* The order of the returned array is undefined.
*
* @param obj An object.
*/
export function keys(obj: object): string[];
export function values<T>(object: { [key: string]: T }): T[];
// TODO: When upgrading definitions to use TS 2.2+, use "object" data type in next line
export function values(object: any): any[];
/**
* Returns an array containing the property values of the specified object (an associative array).
* The order of the returned array is undefined.
*
* The generic refers to the data type of the values.
*
* @param obj An object.
*/
export function values<T>(obj: { [key: string]: T } | ArrayLike<T>): T[];
/**
* Returns an array containing the property values of the specified object (an associative array).
* The order of the returned array is undefined.
*
* @param obj An object.
*/
export function values(obj: object): any[];
export function entries<T>(object: { [key: string]: T }): Array<{ key: string, value: T }>;
// TODO: When upgrading definitions to use TS 2.2+, use "object" data type in next line
export function entries(object: any): Array<{ key: string, value: any }>;
/**
* Returns an array containing the property keys and values of the specified object (an associative array).
* Each entry is an object with a key and value attribute.The order of the returned array is undefined.
*
* The generic refers to the data type of the values.
*
* @param obj An object.
*/
export function entries<T>(obj: { [key: string]: T } | ArrayLike<T>): Array<{ key: string, value: T }>;
/**
* Returns an array containing the property keys and values of the specified object (an associative array).
* Each entry is an object with a key and value attribute.The order of the returned array is undefined.
*
* @param obj An object.
*/
export function entries(obj: object): Array<{ key: string, value: any }>;
// ---------------------------------------------------------------------
// map / Map
// ---------------------------------------------------------------------
/**
* A datastructure similar to ES6 Maps, but with a few differences:
* - Keys are coerced to strings.
* - map.each, not map.forEach. (Also, no thisArg.)
* - map.remove, not map.delete.
* - map.entries returns an array of {key, value} objects, not an iterator of [key, value].
* - map.size is a method, not a property; also, theres map.empty.
*
* The generic refers to the data type of the map entry values.
*/
export interface Map<T> {
/**
* Returns true if and only if this map has an entry for the specified key string.
* Note: the value may be null or undefined.
*
* @param key Key of map entry to access.
*/
has(key: string): boolean;
/**
* Returns the value for the specified key string.
* If the map does not have an entry for the specified key, returns undefined.
*
* @param key Key of map entry to access.
*/
get(key: string): T | undefined;
/**
* Sets the value for the specified key string and returns the updated map.
* If the map previously had an entry for the same key string, the old entry is replaced with the new value.
*
* @param key Key of map entry to access.
* @param value Value to set for entry at key.
*/
set(key: string, value: T): this;
/**
* If the map has an entry for the specified key string, removes the entry and returns true.
* Otherwise, this method does nothing and returns false.
*
* @param key Map key for which to remove the entry.
*/
remove(key: string): boolean;
/**
* Removes all entries from this map.
*/
clear(): void;
/**
* Returns an array of string keys for every entry in this map.
* The order of the returned keys is arbitrary.
*/
keys(): string[];
/**
* Returns an array of values for every entry in this map.
* The order of the returned values is arbitrary.
*/
values(): T[];
/**
* Returns an array of key-value objects for each entry in this map. The order of the returned entries is arbitrary.
* Each entrys key is a string, but the value can have arbitrary type.
*/
entries(): Array<{ key: string, value: T }>;
/**
* Calls the specified function for each entry in this map and returns undefined.
* The iteration order is arbitrary.
*
* @param func Function to call for each entry. The function is passed the entrys value and key as arguments,
* followed by the map itself.
*/
each(func: (value: T, key: string, map: Map<T>) => void): void;
/**
* Returns true if and only if this map has zero entries.
*/
empty(): boolean;
/**
* Returns the number of entries in this map.
*/
size(): number;
}
export function map<T>(): Map<T>;
/**
* Constructs a new empty map.
*
* The generic refers to the data type of the map entry values.
*/
export function map<T = any>(): Map<T>;
/**
* Constructs a new map by copying another map.
*
* The generic refers to the data type of the map entry values.
*
* @param d3Map A D3 Map.
*/
export function map<T>(d3Map: Map<T>): Map<T>;
export function map<T>(object: { [key: string]: T }): Map<T>;
export function map<T>(object: { [key: number]: T }): Map<T>;
/**
* Constructs a new map by copying all enumerable properties from the specified object into this map.
*
* The generic refers to the data type of the map entry values.
*
* @param obj Object to construct the map from.
*/
export function map<T>(obj: { [key: string]: T }): Map<T>;
/**
* Constructs a new map by copying all enumerable properties from the specified object into this map.
*
* The generic refers to the data type of the map entry values.
*
* @param obj Object to construct the map from.
*/
export function map<T>(obj: { [key: number]: T }): Map<T>;
/**
* Constructs a new map from the elements of an array.
* An optional key function may be specified to compute the key for each value in the array.
*
* The generic refers to the data type of the map entry values.
*
* @param array Array to convert into a map
* @param key An optional key function. The functions is invoked for each element in the array being passed
* the element's value , it's zero-based index in the array, and the array itself. The function must return a unique string
* to be used as the map entry's key.
*/
export function map<T>(array: T[], key?: (value: T, i?: number, array?: T[]) => string): Map<T>;
export function map(object: any): Map<any>; // TODO: When upgrading definitions to use TS 2.2+, use "object" data type for argument
/**
* Constructs a new map by copying all enumerable properties from the specified object into this map.
*
* @param obj Object to construct the map from.
*/
export function map(obj: object): Map<any>;
// ---------------------------------------------------------------------
// set / Set
// ---------------------------------------------------------------------
/**
* A datastructure similar to ES6 Sets, but with a few differences:
*
* - Values are coerced to strings.
* - set.each, not set.forEach. (Also, no thisArg.)
* - set.remove, not set.delete.
* - set.size is a method, not a property; also, theres set.empty.
*/
export interface Set {
/**
* Returns true if and only if this set has an entry for the specified value string.
*
* @param value Value whose membership in the class to test.
*/
has(value: string | Stringifiable): boolean;
/**
* Adds the specified value string to this set and returns the set.
*
* @param value Value to add to set.
*/
add(value: string | Stringifiable): this;
/**
* If the set contains the specified value string, removes it and returns true.
* Otherwise, this method does nothing and returns false.
*
* @param value Value to remove from set.
*/
remove(value: string | Stringifiable): boolean;
/**
* Removes all values from this set.
*/
clear(): void;
/**
* Returns an array of the string values in this set. The order of the returned values is arbitrary.
* Can be used as a convenient way of computing the unique values for a set of strings.
*/
values(): string[];
/**
* The first and second parameter of the function are both passed
* the 'value' of the set entry for consistency with map.each(...)
* signature
* Calls the specified function for each value in this set, passing the value as the first two arguments (for symmetry with map.each),
* followed by the set itself. Returns undefined.
* The iteration order is arbitrary.
*
* @param func Function to call for each set element. The first and second argument of the function are both passed
* the 'value' of the set entry for consistency with the map.each(...) signature, as a third argument the entire set is passed in.
*/
each(func: (value: string, valueRepeat: string, set: Set) => void): void;
/**
* Returns true if and only if this set has zero values.
*/
empty(): boolean;
/**
* Returns the number of values in this set.
*/
size(): number;
}
/**
* Constructs a new empty set.
*/
export function set(): Set;
/**
* Constructs a new set by copying an existing set.
*
* @param set A D3 set.
*/
export function set(d3Set: Set): Set;
/**
* Constructs a new set by adding the given array of string values to the returned set.
*
* @param array An array of strings of values which can be implicitly converted to strings.
*/
export function set(array: Array<string | Stringifiable>): Set;
export function set<T>(array: T[], key: (value: T, index?: number, array?: T[]) => string): Set;
/**
* Constructs a new set from an array, adds an array of mapped string values to the returned set.
* The specified accessor function is invoked equivalent to calling array.map(accessor) before constructing the set.
*
* The generic refers to the data type of the array elements.
*
* @param array An Array of values to map and add as set elements.
* @param key An accessor function used to map the original array elements to string elements to be added to the set.
* The function is invoked for each array element, being passed the element's value, it's zero-based index in the array, and the array itself.
*/
export function set<T>(array: T[], key: (value: T, index: number, array: T[]) => string): Set;
// ---------------------------------------------------------------------
// nest / Nest
// ---------------------------------------------------------------------
// NB: the following three interfaces NestedArray, NestedMap and NestedObject provide a more formal definitions
// of the return values provided by Nest.entries(...), Nest.map(...) and Nest.object(...), respectively. However,
// the union types cannot be ex ante simplified without knowledge of the nesting level (number of key(...) operations)
// and whether the data were rolled-up. The latter question also determins whether NestedArray has the 'values' property
// with an array of type Datum at leaf level, or has a rolled-up 'value' property.
// The interfaces are not used as return types, as they are cumbersome to work with on the consuming side (Determining the
// applicable type from the respective union, i. p. for array elements).
// It is preferable to carefully define appropriate use-case-specific interfaces for the variables that
// are assigned the return values of the Nest.entries(...), Nest.map(...) and Nest.object(...) operations. The downside
// is an overly permissive return type.
// Also note, that the below return types for Nest.entries(...), Nest.map(...) and Nest.object(...) strictly only work,
// if AT LEAST ONE KEY was set. This seems a reasonable constraint in practice, given the intent of the nest operator.
// Otherwise, an additional '| Datum[] | RollupType` would have to be added to the union type. This would cover
// cases (a) without key or rollup (b) without key but with rollup. However, again, the union types make it cumbersome
// without much gain.
/**
* A more formal defintion of the nested array returned by Nest.entries(...). This data structure is intended as a reference only.
*
* As the union types cannot be ex ante simplified without knowledge
* of the nesting level (number of key(...) operations) and whether the data were rolled-up, this data structure becomes cumbersome
* to use in practice. This is particularly true for discrimiation of array element types.
* The use of the rollup function, or lack thereof, also determines whether NestedArray has the 'values' property
* with an array of type Datum at leaf level, or has a rolled-up 'value' property.
*/
// tslint:disable-next-line:no-empty-interface
export interface NestedArray<Datum, RollupType> extends Array<{ key: string, values: NestedArray<Datum, RollupType> | Datum[] | undefined, value: RollupType | undefined }> { }
/**
* A more formal defintion of the nested array returned by Nest.map(...). This data structure is intended as a reference only.
*
* As the union types cannot be ex ante simplified without knowledge
* of the nesting level (number of key(...) operations) and whether the data were rolled-up, this data structure becomes cumbersome
* to use in practice.
*/
// tslint:disable-next-line:no-empty-interface
export interface NestedMap<Datum, RollupType> extends Map<NestedMap<Datum, RollupType> | Datum[] | RollupType> { }
/**
* A more formal defintion of the nested array returned by Nest.object(...). This data structure is intended as a reference only.
*
* As the union types cannot be ex ante simplified without knowledge
* of the nesting level (number of key(...) operations) and whether the data were rolled-up, this data structure becomes cumbersome
* to use in practice.
*/
export interface NestedObject<Datum, RollupType> {
[key: string]: NestedObject<Datum, RollupType> | Datum[] | RollupType;
}
/**
* A nest operator for generating nested data structures from arrays.
*
* Nesting allows elements in an array to be grouped into a hierarchical tree structure;
* think of it like the GROUP BY operator in SQL, except you can have multiple levels of grouping, and the resulting output is a tree rather than a flat table.
* The levels in the tree are specified by key functions. The leaf nodes of the tree can be sorted by value, while the internal nodes can be sorted by key.
* An optional rollup function will collapse the elements in each leaf node using a summary function.
* The nest operator is reusable, and does not retain any references to the data that is nested.
*
* The first generic refers to the data type of the array elements on which the nest operator will
* be invoked.
*
* The second generic refers to the data type returned by the roll-up function to be used with the
* nest operator.
*/
export interface Nest<Datum, RollupType> {
/**
* Registers a new key function and returns this nest operator.
* The key function will be invoked for each element in the input array and must return a string identifier to assign the element to its group.
* Most often, the function is a simple accessor. (Keys functions are not passed the input array index.)
*
* Each time a key is registered, it is pushed onto the end of the internal array of keys,
* and the nest operator applies an additional level of nesting.
*
* @param func A key accessor function being invoked for each element.
*/
key(func: (datum: Datum) => string): this;
/**
* Sorts key values for the current key using the specified comparator function, such as d3.ascending or d3.descending.
*
* If no comparator is specified for the current key, the order in which keys will be returned is undefined.
*
* Note that this only affects the result of nest.entries;
* the order of keys returned by nest.map and nest.object is always undefined, regardless of comparator.
*
* @param comparator A comparator function which returns a negative value if, according to the sorting criterion,
* a is less than b, or a positive value if a is greater than b, or 0 if the two values are the same under the sorting criterion.
*/
sortKeys(comparator: (a: string, b: string) => number): this;
/**
* Sorts leaf elements using the specified comparator function, such as d3.ascending or d3.descending.
* This is roughly equivalent to sorting the input array before applying the nest operator;
* however it is typically more efficient as the size of each group is smaller.
*
* If no value comparator is specified, elements will be returned in the order they appeared in the input array.
* This applies to nest.map, nest.entries and nest.object.
*
* @param comparator A comparator function which returns a negative value if, according to the sorting criterion,
* a is less than b, or a positive value if a is greater than b, or 0 if the two values are the same under the sorting criterion.
*/
sortValues(comparator: (a: Datum, b: Datum) => number): this;
/**
* Specifies a rollup function to be applied on each group of leaf elements and returns this nest operator.
* The return value of the rollup function will replace the array of leaf values in either the associative array returned by nest.map or nest.object;
* for nest.entries, it replaces the leaf entry.values with entry.value.
*
* If a leaf comparator is specified, the leaf elements are sorted prior to invoking the rollup function.
*
* @param func A function computing the rollup value for a group of leaf elements.
*/
rollup(func: (values: Datum[]) => RollupType): this;
map(array: Datum[]): Map<any>; // more specifically it returns NestedMap<Datum, RollupType>
object(array: Datum[]): { [key: string]: any }; // more specifically it returns NestedObject<Datum, RollupType>
entries(array: Datum[]): Array<{ key: string; values: any; value: RollupType | undefined }>; // more specifically it returns NestedArray<Datum, RollupType>
/**
* Applies the nest operator to the specified array, returning a nested map.
*
* Each entry in the returned map corresponds to a distinct key value returned by the first key function.
* The entry value depends on the number of registered key functions: if there is an additional key, the value is another map;
* otherwise, the value is the array of elements filtered from the input array that have the given key value.
*
* NOTE:
*
* Strictly speaking the return type of this method is:
*
* (1) NestedMap<Datum, RollupType>, if at least one key function was defined,
*
* (2) Datum[], if neither a key nor a rollup function were defined, and
*
* (3) RollupType, if no keys, but a rollup function were defined.
*
* Since (2) and (3) are edge cases with little to no practical relevance, they have been omitted in favour of ease-of-use.
*
* Should you determine that this simplification creates an issue in practice, please file an issue on
* https://github.com/DefinitelyTyped/DefinitelyTyped.
*
* The formal, generalized return type under (1) is cumbersome to work with in practice. The recommended approach
* is to define the type of the variable being assigned the return value using knowledge specific to the use-case at hand.
* I.e. making use of knowing how many keys are applied, and the nature of any roll-up function will make working with
* the variable more meaningful, despite the compromise in type-safety.
*
* @param array An array to create a nested data structure from.
*/
map(array: Datum[]): Map<any>;
/**
* Applies the nest operator to the specified array, returning a nested object.
* Each entry in the returned associative array corresponds to a distinct key value returned by the first key function.
* The entry value depends on the number of registered key functions: if there is an additional key, the value is another associative array;
* otherwise, the value is the array of elements filtered from the input array that have the given key value.
*
* WARNING: this method is unsafe if any of the keys conflict with built-in JavaScript properties, such as __proto__.
* If you cannot guarantee that the keys will be safe, you should use nest.map instead.
*
* NOTE:
*
* Strictly speaking the return type of this method is:
*
* (1) NestedObject<Datum, RollupType>, if at least one key function was defined,
*
* (2) Datum[], if neither a key nor a rollup function were defined, and
*
* (3) RollupType, if no keys, but a rollup function were defined.
*
* Since (2) and (3) are edge cases with little to no practical relevance, they have been omitted in favour of ease-of-use.
*
* Should you determine that this simplification creates an issue in practice, please file an issue on
* https://github.com/DefinitelyTyped/DefinitelyTyped.
*
* The formal, generalized return type under (1) is cumbersome to work with in practice. The recommended approach
* is to define the type of the variable being assigned the return value using knowledge specific to the use-case at hand.
* I.e. making use of knowing how many keys are applied, and the nature of any roll-up function will make working with
* the variable more meaningful, despite the compromise in type-safety.
*
* @param array An array to create a nested data structure from.
*/
object(array: Datum[]): { [key: string]: any };
/**
* Applies the nest operator to the specified array, returning an array of key-values entries.
* Conceptually, this is similar to applying map.entries to the associative array returned by nest.map,
* but it applies to every level of the hierarchy rather than just the first (outermost) level.
* Each entry in the returned array corresponds to a distinct key value returned by the first key function.
* The entry value depends on the number of registered key functions: if there is an additional key, the value is another nested array of entries;
* otherwise, the value is the array of elements filtered from the input array that have the given key value.
*
* NOTE:
*
* Strictly speaking the return type of this method is:
*
* (1) NestedArray<Datum, RollupType>, if at least one key function was defined,
*
* (2) Datum[], if neither a key nor a rollup function were defined, and
*
* (3) RollupType, if no keys, but a rollup function were defined.
*
* Since (2) and (3) are edge cases with little to no practical relevance, they have been omitted in favour of ease-of-use.
*
* Should you determine that this simplification creates an issue in practice, please file an issue on
* https://github.com/DefinitelyTyped/DefinitelyTyped.
*
* The formal, generalized return type under (1) is cumbersome to work with in practice. The recommended approach
* is to define the type of the variable being assigned the return value using knowledge specific to the use-case at hand.
* I.e. making use of knowing how many keys are applied, and the nature of any roll-up function will make working with
* the variable more meaningful, despite the compromise in type-safety.
*
* @param array An array to create a nested data structure from.
*/
entries(array: Datum[]): Array<{ key: string; values: any; value: RollupType | undefined }>;
}
export function nest<Datum>(): Nest<Datum, undefined>;
export function nest<Datum, RollupType>(): Nest<Datum, RollupType>;
/**
* Creates a new nest operator.
*
* The first generic refers to the data type of the array elements on which the nest operator will
* be invoked.
*
* The second generic refers to the data type returned by the roll-up function to be used with the
* nest operator. If not explicitly set, this generic parameter defaults to undefined, implying that
* no rollup function will be applied.
*/
export function nest<Datum, RollupType = undefined>(): Nest<Datum, RollupType>;
+2 -2
View File
@@ -7,7 +7,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
@@ -21,4 +21,4 @@
"index.d.ts",
"d3-collection-tests.ts"
]
}
}
@@ -0,0 +1,6 @@
import decompressResponse = require("decompress-response");
import http = require("http");
http.get("localhost", response => {
response = decompressResponse(response);
});
+11
View File
@@ -0,0 +1,11 @@
// Type definitions for decompress-response 3.3
// Project: https://github.com/sindresorhus/decompress-response#readme
// Definitions by: Daniel Rosenwasser <https://github.com/DanielRosenwasser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import http = require("http");
export = decompress_response;
declare function decompress_response(response: http.IncomingMessage): http.IncomingMessage;
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"decompress-response-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+26 -6
View File
@@ -1,20 +1,20 @@
import ElectronStore = require('electron-store');
new ElectronStore({
defaults: {}
defaults: {}
});
new ElectronStore({
name: 'myConfiguration',
cwd: 'unicorn'
name: 'myConfiguration',
cwd: 'unicorn'
});
const electronStore = new ElectronStore();
electronStore.set('foo', 'bar');
electronStore.set({
foo: 'bar',
foo2: 'bar2'
foo: 'bar',
foo2: 'bar2'
});
electronStore.delete('foo');
electronStore.get('foo');
@@ -28,7 +28,27 @@ electronStore.size;
electronStore.store;
electronStore.store = {
foo: 'bar'
foo: 'bar'
};
electronStore.path;
interface SampleStore {
enabled: boolean;
interval: number;
}
const typedElectronStore = new ElectronStore<SampleStore>({
defaults: {
enabled: true,
interval: 30000,
},
});
const interval: number = typedElectronStore.get('interval');
const enabled = false;
typedElectronStore.set('enabled', enabled);
typedElectronStore.set({
enabled: true,
interval: 10000,
});
+90 -57
View File
@@ -1,79 +1,112 @@
// Type definitions for electron-store 1.2
// Type definitions for electron-store 1.3
// Project: https://github.com/sindresorhus/electron-store
// Definitions by: Daniel Perez Alvarez <https://github.com/unindented>
// Jakub Synowiec <https://github.com/jsynowiec>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface ElectronStoreOptions {
/**
* Default config.
*/
defaults?: {};
// TypeScript Version: 2.3
/**
* Name of the config file (without extension).
*/
name?: string;
/// <reference types="node" />
/**
* Storage file location. *Don't specify this unless absolutely necessary!*
*/
cwd?: string;
type JSONValue = string | number | boolean | JSONObject | JSONArray;
interface JSONObject {
[x: string]: JSONValue;
}
declare class ElectronStore implements Iterable<[string, string | number | boolean | symbol | {}]> {
constructor(options?: ElectronStoreOptions);
interface JSONArray extends Array<JSONValue> {}
/**
* Sets an item.
*/
set(key: string, value: any): void;
interface ElectronStoreOptions<T> {
/**
* Default data.
*/
defaults?: T;
/**
* Sets multiple items at once.
*/
set(object: {}): void;
/**
* Name of the storage file (without extension).
*/
name?: string;
/**
* Retrieves an item.
*/
get(key: string, defaultValue?: any): any;
/**
* Storage file location. Don't specify this unless absolutely necessary!
*/
cwd?: string;
/**
* Checks if an item exists.
*/
has(key: string): boolean;
/**
* When specified, the store will be encrypted using the aes-256-cbc encryption algorithm.
*/
encryptionKey?: string | Buffer;
}
/**
* Deletes an item.
*/
delete(key: string): void;
declare class ElectronStore<T = {}> implements Iterable<[string, JSONValue]> {
constructor(options?: ElectronStoreOptions<T>);
/**
* Deletes all items.
*/
clear(): void;
/**
* Set an item.
*/
set<K extends keyof T>(key: K, value: T[K]): void;
set(key: string, value: any): void;
/**
* Open the storage file in the user's editor.
*/
openInEditor(): void;
/**
* Set multiple items at once.
*/
set(object: Pick<T, keyof T> | T | JSONObject): void;
/**
* Gets the item count.
*/
size: number;
/**
* Get an item or defaultValue if the item does not exist.
*/
get<K extends keyof T>(key: K, defaultValue?: JSONValue): T[K];
get(key: string, defaultValue?: any): any;
/**
* Gets all the config as an object or replace the current config with an object.
*/
store: {};
/**
* Check if an item exists.
*/
has(key: keyof T | string): boolean;
/**
* Gets the path to the config file.
*/
path: string;
/**
* Delete an item.
*/
delete(key: keyof T | string): void;
[Symbol.iterator](): Iterator<[string, string | number | boolean | symbol | {}]>;
/**
* Delete all items.
*/
clear(): void;
/**
* Watches the given key, calling callback on any changes. When a key is first set oldValue
* will be undefined, and when a key is deleted newValue will be undefined.
*/
onDidChange<K extends keyof T>(
key: K,
callback: (newValue: T[K], oldValue: T[K]) => void
): void;
onDidChange(
key: string,
callback: (newValue: JSONValue, oldValue: JSONValue) => void
): void;
/**
* Get the item count.
*/
size: number;
/**
* Get all the data as an object or replace the current data with an object.
*/
store: T;
/**
* Get the path to the storage file.
*/
path: string;
/**
* Open the storage file in the user's editor.
*/
openInEditor(): void;
[Symbol.iterator](): Iterator<[string, JSONValue]>;
}
export = ElectronStore;
+40 -30
View File
@@ -13,6 +13,32 @@ declare module 'ember-data' {
export interface ModelRegistry {}
export interface AdapterRegistry {}
export interface SerializerRegistry {}
export interface TransformRegistry {
'string': string;
'boolean': boolean;
'number': number;
'date': Date;
}
type AttributesFor<Model> = keyof Model; // TODO: filter to attr properties only (TS 2.8)
type RelationshipsFor<Model> = keyof Model; // TODO: filter to hasMany/belongsTo properties only (TS 2.8)
interface AttributeMeta<Model extends DS.Model> {
type: keyof TransformRegistry;
options: object;
name: AttributesFor<Model>;
parentType: Model;
isAttribute: true;
}
interface RelationshipMeta<Model extends DS.Model> {
key: RelationshipsFor<Model>;
kind: 'belongsTo' | 'hasMany';
type: keyof ModelRegistry;
options: object;
name: string;
parentType: Model;
isRelationship: true;
}
namespace DS {
/**
@@ -82,27 +108,11 @@ declare module 'ember-data' {
* `boolean` and `date`. You can define your own transforms by subclassing
* [DS.Transform](/api/data/classes/DS.Transform.html).
*/
function attr(
type: 'string',
options?: AttrOptions<string>
): Ember.ComputedProperty<string>;
function attr(
type: 'boolean',
options?: AttrOptions<boolean>
): Ember.ComputedProperty<boolean>;
function attr(
type: 'number',
options?: AttrOptions<number>
): Ember.ComputedProperty<number>;
function attr(
type: 'date',
options?: AttrOptions<Date>
): Ember.ComputedProperty<Date>;
function attr<T>(
type: string,
options?: AttrOptions<T>
): Ember.ComputedProperty<T>;
function attr<T>(options?: AttrOptions<T>): Ember.ComputedProperty<T>;
function attr<K extends keyof TransformRegistry>(
type: K,
options?: AttrOptions<TransformRegistry[K]>
): Ember.ComputedProperty<TransformRegistry[K]>;
function attr(options?: AttrOptions): Ember.ComputedProperty<any>;
/**
* WARNING: This interface is likely to change in order to accomodate https://github.com/emberjs/rfcs/pull/4
* ## Using BuildURLMixin
@@ -481,7 +491,7 @@ declare module 'ember-data' {
/**
* Same as `deleteRecord`, but saves the record immediately.
*/
destroyRecord(options: {}): RSVP.Promise<any>;
destroyRecord(options?: {}): RSVP.Promise<any>;
/**
* Unloads the record from the store. This will cause the record to be destroyed and freed up for garbage collection.
*/
@@ -860,7 +870,7 @@ declare module 'ember-data' {
*/
interface PromiseArray<T>
extends Ember.ArrayProxy<T>,
Ember.PromiseProxyMixin<PromiseArray<T>> {}
Ember.PromiseProxyMixin<Ember.ArrayProxy<T>> {}
class PromiseArray<T> {}
/**
* A `PromiseObject` is an object that acts like both an `Ember.Object`
@@ -871,7 +881,7 @@ declare module 'ember-data' {
*/
interface PromiseObject<T>
extends Ember.ObjectProxy,
Ember.PromiseProxyMixin<T & PromiseObject<T>> {}
Ember.PromiseProxyMixin<T & Ember.ObjectProxy> {}
class PromiseObject<T> {}
/**
* A PromiseManyArray is a PromiseArray that also proxies certain method calls
@@ -942,7 +952,7 @@ declare module 'ember-data' {
/**
* Returns the value of an attribute.
*/
attr<L extends keyof ModelRegistry[K]>(keyName: L): ModelRegistry[K][L];
attr<L extends AttributesFor<ModelRegistry[K]>>(keyName: L): ModelRegistry[K][L];
/**
* Returns all attributes and their corresponding values.
*/
@@ -954,18 +964,18 @@ declare module 'ember-data' {
/**
* Returns the current value of a belongsTo relationship.
*/
belongsTo<L extends keyof ModelRegistry[K]>(
belongsTo<L extends RelationshipsFor<ModelRegistry[K]>>(
keyName: L,
options?: {}
): Snapshot<K>['record'][L] | string | null | undefined;
/**
* Returns the current value of a hasMany relationship.
*/
hasMany<L extends keyof ModelRegistry[K]>(
hasMany<L extends RelationshipsFor<ModelRegistry[K]>>(
keyName: L,
options?: { ids: false }
): Array<Snapshot<K>['record'][L]> | undefined;
hasMany<L extends keyof ModelRegistry[K]>(
hasMany<L extends RelationshipsFor<ModelRegistry[K]>>(
keyName: L,
options: { ids: true }
): string[] | undefined;
@@ -973,12 +983,12 @@ declare module 'ember-data' {
* Iterates through all the attributes of the model, calling the passed
* function on each attribute.
*/
eachAttribute(callback: Function, binding: {}): any;
eachAttribute<M extends ModelRegistry[K]>(callback: (key: keyof M, meta: AttributeMeta<M>) => void, binding?: {}): any;
/**
* Iterates through all the relationships of the model, calling the passed
* function on each relationship.
*/
eachRelationship(callback: Function, binding: {}): any;
eachRelationship<M extends ModelRegistry[K]>(callback: (key: keyof M, meta: RelationshipMeta<M>) => void, binding?: {}): any;
/**
* Serializes the snapshot using the serializer for the model.
*/
+56
View File
@@ -37,3 +37,59 @@ const EmbeddedRecordMixin = DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin, {
}
}
});
class Message extends DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
author: DS.belongsTo('user'),
comments: DS.belongsTo('comment')
}) {}
declare module 'ember-data' {
interface ModelRegistry {
'message-for-serializer': Message;
}
}
interface CustomSerializerOptions {
includeId: boolean;
}
const SerializerUsingSnapshots = DS.RESTSerializer.extend({
serialize(snapshot: DS.Snapshot<'message-for-serializer'>, options: CustomSerializerOptions) {
let json: any = {
POST_TTL: snapshot.attr('title'),
POST_BDY: snapshot.attr('body'),
POST_CMS: snapshot.hasMany('comments', { ids: true })
};
if (options.includeId) {
json.POST_ID_ = snapshot.id;
}
return json;
}
});
DS.Serializer.extend({
serialize(snapshot: DS.Snapshot<'message-for-serializer'>, options: {}) {
let json: any = {
id: snapshot.id
};
snapshot.eachAttribute((key, attribute) => {
json[key] = snapshot.attr(key);
});
snapshot.eachRelationship((key, relationship) => {
if (relationship.kind === 'belongsTo') {
json[key] = snapshot.belongsTo(key, { id: true });
} else if (relationship.kind === 'hasMany') {
json[key] = snapshot.hasMany(key, { ids: true });
}
});
return json;
},
});
+33 -2
View File
@@ -4,13 +4,16 @@ import { assertType } from './lib/assert';
declare const store: DS.Store;
class PostComment extends DS.Model {}
class Post extends DS.Model {
title = DS.attr('string');
comments = DS.hasMany('comment');
}
declare module 'ember-data' {
interface ModelRegistry {
post: Post;
'post': Post;
'post-comment': PostComment;
}
}
@@ -48,7 +51,7 @@ store.queryRecord('user', {}).then(function(user) {
console.log(`Currently logged in as ${username}`);
});
store.findAll('post'); // => GET /blog-posts
store.findAll('post'); // => GET /posts
store.findAll('author', { reload: true }).then(function(authors) {
authors.getEach('id'); // ['first', 'second']
});
@@ -107,6 +110,34 @@ const SomeComponent = Ember.Component.extend({
}
});
const MyRouteAsync = Ember.Route.extend({
async beforeModel(): Promise<Ember.Array<DS.Model>> {
const store = Ember.get(this, 'store');
return await store.findAll('post-comment');
},
async model(): Promise<DS.Model> {
const store = this.get('store');
return await store.findRecord('post-comment', 1);
},
async afterModel(): Promise<Ember.Array<PostComment>> {
const post = await this.get('store').findRecord('post', 1);
return await post.get('comments');
}
});
class MyRouteAsyncES6 extends Ember.Route {
async beforeModel(): Promise<Ember.Array<DS.Model>> {
return await this.store.findAll('post-comment');
}
async model(): Promise<DS.Model> {
return await this.store.findRecord('post-comment', 1);
}
async afterModel(): Promise<Ember.Array<PostComment>> {
const post = await this.store.findRecord('post', 1);
return await post.get('comments');
}
}
// GET to /users?filter[email]=tomster@example.com
const tom = store
.query('user', {
+2 -1
View File
@@ -15,7 +15,8 @@
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"files": [
"index.d.ts",
+2 -1
View File
@@ -14,6 +14,7 @@
"prefer-const": false,
"no-unnecessary-generics": false,
"no-declare-current-package": false,
"no-self-import": false
"no-self-import": false,
"no-return-await": false // used in tests
}
}
+2 -2
View File
@@ -1182,7 +1182,7 @@ declare module 'ember' {
* argument for all items in the enumerable. This method is often simpler/faster
* than using a callback.
*/
isEvery(key: string, value?: boolean): boolean;
isEvery(key: string, value?: any): boolean;
/**
* Returns `true` if the passed function returns true for any item in the
* enumeration.
@@ -1193,7 +1193,7 @@ declare module 'ember' {
* argument for any item in the enumerable. This method is often simpler/faster
* than using a callback.
*/
isAny(key: string, value?: boolean): boolean;
isAny(key: string, value?: any): boolean;
/**
* This will combine the values of the enumerator into a single value. It
* is a useful way to collect a summary value from an enumeration. This
+1 -1
View File
@@ -15,7 +15,7 @@ const people = Ember.A([
assertType<number>(people.get('length'));
assertType<Person>(people.get('lastObject'));
assertType<boolean>(people.isAny('isHappy'));
assertType<boolean>(people.isAny('isHappy', false));
assertType<boolean>(people.isAny('isHappy', 'false'));
assertType<Ember.Enumerable<Person>>(people.filterBy('isHappy'));
assertType<Ember.Enumerable<Person>>(people.rejectBy('isHappy'));
assertType<Ember.Enumerable<Person>>(people.filter((person) => person.get('name') === 'Yehuda'));
+1 -1
View File
@@ -132,7 +132,7 @@ people2.every(isHappy);
people2.any(isHappy);
people2.isEvery('isHappy');
people2.isEvery('isHappy', true);
people2.isAny('isHappy', true);
people2.isAny('isHappy', 'true');
people2.isAny('isHappy');
// Examples taken from http://emberjs.com/api/classes/Em.RSVP.Promise.html
+2 -8
View File
@@ -1,6 +1,6 @@
/// <reference types="node" />
import promisify = require('es6-promisify');
import { promisify } from 'es6-promisify';
function callbackFunction(a: string, b: string, callback: (error: any, combined: string) => void): void {
callback(undefined, a + b);
@@ -10,14 +10,8 @@ function multiArgFunction(a: string, b: string, c: string, callback: (error: any
callback(undefined, a + c, b + c);
}
const noKeys: promisify.Settings = {};
const multiArgFunctionSettings: promisify.Settings = {
thisArg: multiArgFunction,
multiArgs: true
};
const callbackPromiseFactory: (...args: any[]) => Promise<string> = promisify(callbackFunction);
const multiArgPromiseFactory: (...args: any[]) => Promise<string[]> = promisify(multiArgFunction, multiArgFunctionSettings);
const multiArgPromiseFactory: (...args: any[]) => Promise<any> = promisify(multiArgFunction);
const callbackPromise: Promise<string> = callbackPromiseFactory('stringA', 'stringB');
const multiArgPromise: Promise<string[]> = multiArgPromiseFactory('stringA', 'stringB', 'stringC');
+33 -14
View File
@@ -1,24 +1,43 @@
// Type definitions for es6-promisify 5.0
// Type definitions for es6-promisify 6.0
// Project: https://github.com/digitaldesignlabs/es6-promisify#readme
// Definitions by: Harry Shipton <https://github.com/harryshipton>
// Brian Schlenker <https://github.com/bschlenk>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function es6_promisify(original: (...args: any[]) => any, settings?: es6_promisify.Settings): ((...args: any[]) => Promise<any>);
// If the issue at https://github.com/Microsoft/TypeScript/issues/1360 is fixed,
// then an update should be submitted replacing the above declaration with the
// following declarations.
// then an update should be submitted replacing the promisify declaration with
// the following declarations.
/*
declare function es6_promisify<T>(original: (...args: any[], callback: (error: any, arg: T) => any) => any, settings?: Settings): ((...args: any[]) => Promise<T>);
function promisify<T>(original: (...args: any[], callback: (error: any, arg: T) => any) => any): ((...args: any[]) => Promise<T>);
declare function es6_promisify(original: (...args: any[], callback: (error: any, ...args: any[]) => any) => any, settings?: Settings): ((...args: any[]) => Promise<any[]>);
function promisify(original: (...args: any[], callback: (error: any, ...args: any[]) => any) => any): ((...args: any[]) => Promise<any>);
*/
declare namespace es6_promisify {
interface Settings {
thisArg?: any;
multiArgs?: boolean;
}
}
export type Callback<T> = (err: any, arg?: T) => any;
export type CallbackFunction = (...args: any[]) => any;
export type PromiseFunction = (...args: any[]) => Promise<any>;
export = es6_promisify;
export function promisify<T>(original: (cb: Callback<T>) => any):
() => Promise<T>;
export function promisify<T, U>(original: (param1: U, cb: Callback<T>) => any):
(param1: U) => Promise<T>;
export function promisify<T, U, V>(original: (param1: U, param2: V, cb: Callback<T>) => any):
(param1: U, param2: V) => Promise<T>;
export function promisify<T, U, V, W>(original: (param1: U, param2: V, param3: W, cb: Callback<T>) => any):
(param1: U, param2: V, param3: W) => Promise<T>;
export function promisify(original: CallbackFunction): PromiseFunction;
export namespace promisify {
/**
* This symbol can be placed on the function to be promisified to
* provide names as an array of strings for the values in a success
* callback.
*/
const argumentNames: symbol;
/**
* The user can supply their own Promise implementation by setting it
* here. Otherwise, the global Promise object will be used.
*/
let Promise: PromiseConstructor;
}
+6
View File
@@ -53,6 +53,12 @@ setTimeout(() => {
emitter.removeAllListeners('send');
}, 3000);
setTimeout(() => {
console.log('\n');
emitter.emit('send', 'params1');
emitter.removeAllListeners();
}, 3000);
setTimeout(() => {
console.log('\n');
emitter.emit(1);
+2 -2
View File
@@ -1,4 +1,4 @@
// Type definitions for events 1.1
// Type definitions for events 1.2
// Project: https://github.com/Gozala/events
// Definitions by: Yasunori Ohoka <https://github.com/yasupeke>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -15,7 +15,7 @@ export class EventEmitter {
on(type: string | number, listener: Listener): this;
once(type: string | number, listener: Listener): this;
removeListener(type: string | number, listener: Listener): this;
removeAllListeners(type: string | number): this;
removeAllListeners(type?: string | number): this;
listeners(type: string | number): Listener[];
listenerCount(type: string | number): number;
}
+115
View File
@@ -88,6 +88,17 @@ describe('A spy', () => {
expect(spy).toHaveBeenCalledWith(1, 2, 3);
});
it('knows the arguments it was last called with', () => {
spy(0, 1, 2);
spy(1, 2, 3);
expect(spy).toHaveBeenLastCalledWith(1, 2, 3);
});
it('accepts to have been called with any object', () => {
spy({});
expect(spy).toHaveBeenCalledWith(expect.any(Object));
});
describe('that calls some other function', () => {
let otherContext: any;
let otherArguments: any;
@@ -462,6 +473,66 @@ describe('toBeFalsy', () => {
});
});
describe('toBeDefined', () => {
it('does not throw on defined actual values', () => {
expect(() => {
expect(1).toBeDefined();
expect(0).toBeDefined();
expect(null).toBeDefined();
}).toNotThrow();
});
it('throws on undefined actual values', () => {
expect(() => {
expect(undefined).toBeDefined();
}).toThrow();
});
});
describe('toBeUndefined', () => {
it('throws on defined values', () => {
expect(() => {
expect(42).toBeUndefined();
}).toThrow();
expect(() => {
expect(0).toBeUndefined();
}).toThrow();
expect(() => {
expect(null).toBeUndefined();
}).toThrow();
});
it('does not throw with undefined actual values', () => {
expect(() => {
expect(undefined).toBeUndefined();
}).toNotThrow();
});
});
describe('toBeNull', () => {
it('throws on non-null values', () => {
expect(() => {
expect(42).toBeNull();
}).toThrow();
expect(() => {
expect(0).toBeNull();
}).toThrow();
expect(() => {
expect(undefined).toBeNull();
}).toThrow();
});
it('does not throw with null actual values', () => {
expect(() => {
expect(null).toBeNull();
}).toNotThrow();
});
});
describe('toEqual', () => {
it('works', () => {
expect(() => {
@@ -953,6 +1024,36 @@ describe('expect(array).toNotMatch', () => {
});
});
describe('expect(object).toMatchObject', () => {
it('does not throw when the actual value matches', () => {
expect(() => {
expect({
statusCode: 200,
headers: {
server: 'express web server'
}
}).toMatchObject({
statusCode: 200,
headers: {}
});
}).toNotThrow();
});
it('throws when the actual value does not match', () => {
expect(() => {
expect({
statusCode: 200,
headers: {
server: 'nginx web server'
}
}).toMatchObject({
statusCode: 201,
headers: {}
});
}).toThrow(/to match/);
});
});
describe('toNotEqual', () => {
it('works', () => {
expect('actual').toNotEqual('expected');
@@ -1100,3 +1201,17 @@ describe('withContext', () => {
}).toThrow(/must be a function/);
});
});
describe('not', () => {
it('does not throw on different values', () => {
expect(() => {
expect(1).not.toEqual(2);
}).toNotThrow();
});
it('throws on equal values', () => {
expect(() => {
expect(1).not.toEqual(1);
}).toThrow();
});
});
+8
View File
@@ -14,6 +14,9 @@ declare namespace expect {
toBeTruthy(message?: string): Expectation<T>;
toNotExist(message?: string): Expectation<T>;
toBeFalsy(message?: string): Expectation<T>;
toBeNull(message?: string): Expectation<T>;
toBeDefined(message?: string): Expectation<T>;
toBeUndefined(message?: string): Expectation<T>;
toBe(value: T, message?: string): Expectation<T>;
toNotBe(value: any, message?: string): Expectation<T>;
@@ -28,6 +31,7 @@ declare namespace expect {
toNotBeAn(value: string | {}, message?: string): Expectation<T>;
toMatch(value: string | RegExp | {}, message?: string): Expectation<T>;
toNotMatch(value: string | RegExp | {}, message?: string): Expectation<T>;
toMatchObject(value: {}, message?: string): Expectation<T>;
toBeLessThan(value: number, message?: string): Expectation<T>;
toBeLessThanOrEqualTo(value: number, messasge?: string): Expectation<T>;
@@ -55,6 +59,9 @@ declare namespace expect {
toHaveBeenCalled(message?: string): Expectation<T>;
toNotHaveBeenCalled(message?: string): Expectation<T>;
toHaveBeenCalledWith(...args: any[]): Expectation<T>;
toHaveBeenLastCalledWith(...args: any[]): Expectation<T>;
not: Expectation<T>;
// deprecated
withContext(context: any): Expectation<T>;
@@ -90,6 +97,7 @@ declare namespace expect {
function restoreSpies(): void;
function assert(condition: boolean, messageFormat: string, ...extraArgs: any[]): void;
function extend(extension: Extension): void;
function any<T>(ctor: { new (): T }): T;
}
declare function expect<T>(actual: T): expect.Expectation<T>;
+133 -5
View File
@@ -27,7 +27,10 @@ import {
LinearGradient,
Permissions,
registerRootComponent,
ScreenOrientation
ScreenOrientation,
SQLite,
Calendar,
MailComposer
} from 'expo';
Accelerometer.addListener((obj) => {
@@ -207,7 +210,7 @@ const barcodeReadCallback = () => {};
<BarCodeScanner
type="front"
torchMode="off"
barCodeTypes={['s']}
barCodeTypes={[BarCodeScanner.Constants.BarCodeType.aztec]}
onBarCodeRead={barcodeReadCallback} />
);
@@ -515,9 +518,13 @@ KeepAwake.deactivate();
() => (
<LinearGradient
colors={['#fff']}
start={[1, 1]}
end={[3, 3]}
locations={[1, 2]} />
start={[1, 1]} />
);
() => (
<LinearGradient
colors={['#fff']}
style={{ flex: 1 }} />
);
Permissions.CAMERA === 'camera';
@@ -548,3 +555,124 @@ class __TestEntry__ extends React.Component {
}
}
registerRootComponent(__TestEntry__);
Calendar.EntityTypes.EVENT === 'event';
Calendar.EntityTypes.REMINDER === 'reminder';
Calendar.CalendarType.LOCAL === 'local';
Calendar.CalendarType.CALDAV === 'caldav';
Calendar.CalendarType.EXCHANGE === 'exchange';
Calendar.CalendarType.SUBSCRIBED === 'subscribed';
Calendar.CalendarType.BIRTHDAYS === 'birthdays';
async () => {
const result = await Calendar.getCalendarsAsync(Calendar.EntityTypes.EVENT);
result.length;
const calendar = result[0];
calendar.id === '';
calendar.title === '';
calendar.sourceId === '';
calendar.type === Calendar.CalendarType.BIRTHDAYS;
calendar.color === '';
calendar.entityType === Calendar.EntityTypes.EVENT;
calendar.allowsModifications === true;
calendar.allowedAvailabilities === [''];
calendar.isPrimary === true;
calendar.name === '';
calendar.ownerAccount === '';
calendar.timeZone === '';
calendar.allowedReminders === [''];
calendar.allowedAttendeeTypes === [''];
calendar.isVisible === false;
calendar.isSynced === false;
calendar.accessLevel === Calendar.CalendarAccessLevel.CONTRIBUTOR;
if (calendar.source) {
calendar.source.id === '';
calendar.source.type === '';
calendar.source.name === '';
calendar.source.isLocalAccount === false;
}
const id1 = await Calendar.createCalendarAsync({
accessLevel: Calendar.CalendarAccessLevel.EDITOR
});
id1 === '';
const id2 = await Calendar.updateCalendarAsync('1234', {
isVisible: false
});
id2 === '';
const id3 = await Calendar.updateCalendarAsync('1234', null);
await Calendar.deleteCalendarAsync('1234');
const events = await Calendar.getEventsAsync(
['123', '124'],
new Date(),
new Date()
);
const event1 = events[0];
event1.accessLevel === Calendar.EventAccessLevel.CONFIDENTIAL;
event1.alarms === [];
event1.allDay === true;
event1.availability === Calendar.Availability.FREE;
event1.calendarId === '';
event1.creationDate === '';
event1.endDate === '';
event1.endTimeZone === '';
event1.guestsCanInviteOthers === true;
event1.guestsCanModify === true;
event1.guestsCanSeeGuests === false;
event1.id === '';
event1.instanceId === '';
event1.isDetached === false;
const event2 = await Calendar.getEventAsync('123', {
futureEvents: true
});
const eventId1 = await Calendar.createEventAsync('123');
const eventId2 = await Calendar.updateEventAsync('1234');
await Calendar.deleteEventAsync('1234');
const attendees = await Calendar.getAttendeesForEventAsync('123');
const aId1 = await Calendar.createAttendeeAsync('123');
const aId2 = await Calendar.updateAttendeeAsync('123');
await Calendar.deleteAttendeeAsync('123');
const reminders = await Calendar.getRemindersAsync(['123']);
const reminder = await Calendar.getReminderAsync('123');
const remId1 = await Calendar.createReminderAsync('123');
const remId2 = await Calendar.updateReminderAsync('123');
await Calendar.deleteReminderAsync('123');
const sources = await Calendar.getSourcesAsync();
const source = await Calendar.getSourceAsync('123');
Calendar.openEventInCalendar('123');
};
async () => {
const result = await MailComposer.composeAsync({
subject: 'sss'
});
result.status === 'saved';
};
+652 -46
View File
@@ -1,9 +1,10 @@
// Type definitions for expo 24.0
// Type definitions for expo 25.0
// Project: https://github.com/expo/expo-sdk
// Definitions by: Konstantin Kai <https://github.com/KonstantinKai>
// Martynas Kadiša <https://github.com/martynaskadisa>
// Jan Aagaard <https://github.com/janaagaard75>
// Sergio Sánchez <https://github.com/ssanchezmarc>
// Fernando Helwanger <https://github.com/fhelwanger>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
@@ -632,7 +633,14 @@ export interface BarCodeScannerProps extends ViewProperties {
onBarCodeRead?: BarCodeReadCallback;
}
export class BarCodeScanner extends Component<BarCodeScannerProps> { }
export class BarCodeScanner extends Component<BarCodeScannerProps> {
static Constants: {
TorchMode: {
on: string;
off: string
}
} & CameraConstants;
}
// #endregion
// #region BlurView
@@ -686,17 +694,21 @@ export class CameraObject {
}
export interface CameraProps extends ViewProperties {
flashMode?: string | number;
type?: string | number;
ratio?: string;
autoFocus?: string | number | boolean;
focusDepth?: FloatFromZeroToOne;
zoom?: FloatFromZeroToOne;
whiteBalance?: string | number;
barCodeTypes?: string[];
ratio?: string;
focusDepth?: FloatFromZeroToOne;
type?: string | number;
onCameraReady?: () => void;
onMountError?: () => void;
onBarCodeRead?: BarCodeReadCallback;
faceDetectionMode?: number;
flashMode?: string | number;
barCodeTypes?: Array<string | number>;
whiteBalance?: string | number;
faceDetectionLandmarks?: number;
autoFocus?: string | number | boolean;
faceDetectionClassifications?: number;
onMountError?: () => void;
onFacesDetected?: (options: { faces: TrackedFaceFeature[] }) => void;
ref?: Ref<CameraObject>;
}
@@ -706,7 +718,28 @@ export interface CameraConstants {
readonly AutoFocus: string;
readonly WhiteBalance: string;
readonly VideoQuality: string;
readonly BarCodeType: string;
readonly BarCodeType: {
aztec: string;
codabar: string;
code39: string;
code93: string;
code128: string;
code138: string;
code39mod43: string;
datamatrix: string;
ean13: string;
ean8: string;
interleaved2of5: string;
itf14: string;
maxicode: string;
pdf417: string;
rss14: string;
rssexpanded: string;
upc_a: string;
upc_e: string;
upc_ean: string;
qr: string;
};
}
export class Camera extends Component<CameraProps> {
@@ -726,10 +759,14 @@ export namespace Constants {
const isDevice: boolean;
interface Platform {
ios: {
ios?: {
platform: string;
model: string;
userInterfaceIdiom: string;
buildNumber: string;
};
android?: {
versionCode: string;
};
}
const platform: Platform;
@@ -1088,36 +1125,42 @@ export namespace FacebookAds {
/**
* FaceDetector
*/
export interface Point {
x: Axis;
y: Axis;
}
export interface FaceFeature {
bounds: {
size: {
width: number;
height: number;
},
origin: Point;
};
smilingProbability?: number;
leftEarPosition?: Point;
rightEarPosition?: Point;
leftEyePosition?: Point;
leftEyeOpenProbability?: number;
rightEyePosition?: Point;
rightEyeOpenProbability?: number;
leftCheekPosition?: Point;
rightCheekPosition?: Point;
leftMouthPosition?: Point;
mouthPosition?: Point;
rightMouthPosition?: Point;
bottomMouthPosition?: Point;
noseBasePosition?: Point;
yawAngle?: number;
rollAngle?: number;
}
export interface TrackedFaceFeature extends FaceFeature {
faceID?: number;
}
export namespace FaceDetector {
interface Point {
x: Axis;
y: Axis;
}
interface FaceFeature {
bounds: {
size: {
width: number;
height: number;
},
origin: Point;
};
smilingProbability?: number;
leftEarPosition?: Point;
rightEarPosition?: Point;
leftEyePosition?: Point;
leftEyeOpenProbability?: number;
rightEyePosition?: Point;
rightEyeOpenProbability?: number;
leftCheekPosition?: Point;
rightCheekPosition?: Point;
leftMouthPosition?: Point;
mouthPosition?: Point;
rightMouthPosition?: Point;
bottomMouthPosition?: Point;
noseBasePosition?: Point;
yawAngle?: number;
rollAngle?: number;
}
interface DetectFaceResult {
faces: FaceFeature[];
image: {
@@ -1153,7 +1196,6 @@ export namespace FaceDetector {
function detectFaces(uri: string, options?: DetectionOptions): Promise<DetectFaceResult>;
}
/**
* FileSystem
*/
@@ -1509,11 +1551,11 @@ export class KeepAwake extends Component {
/**
* LinearGradient
*/
export interface LinearGradientProps {
export interface LinearGradientProps extends ViewProperties {
colors: string[];
start: [number, number];
end: [number, number];
locations: number[];
start?: [number, number];
end?: [number, number];
locations?: number[];
}
export class LinearGradient extends Component<LinearGradientProps> { }
@@ -1764,6 +1806,12 @@ export namespace Speech {
function speak(text: string, options?: SpeechOptions): void;
function stop(): void;
function isSpeakingAsync(): Promise<boolean>;
/** Available on iOS only */
function pause(): void;
/** Available on iOS only */
function resume(): void;
}
/**
@@ -2070,3 +2118,561 @@ export namespace WebBrowser {
function openAuthSessionAsync(url: string, redirectUrl?: string): Promise<{ type: 'cancelled' | 'dismissed' }>;
function dismissBrowser(): Promise<{ type: 'dismissed' }>;
}
// #region Calendar
/**
* Calendar
*
* Provides an API for interacting with the devices system calendars, events, reminders, and associated records.
*/
export namespace Calendar {
interface Calendar {
/** Internal ID that represents this calendar on the device */
id?: string;
/** Visible name of the calendar */
title?: string;
sourceId?: string; // iOS
/** Object representing the source to be used for the calendar */
source?: Source;
/** Type of calendar this object represents */
type?: CalendarType; // iOS
/** Color used to display this calendars events */
color?: string;
/** Whether the calendar is used in the Calendar or Reminders OS app */
entityType?: EntityTypes; // iOS
/** Boolean value that determines whether this calendar can be modified */
allowsModifications?: boolean;
/** Availability types that this calendar supports */
allowedAvailabilities?: Availability[];
/** Boolean value indicating whether this is the devices primary calendar */
isPrimary?: boolean; // Android
/** Internal system name of the calendar */
name?: string; // Android
/** Name for the account that owns this calendar */
ownerAccount?: string; // Android
/** Time zone for the calendar */
timeZone?: string; // Android
/** Alarm methods that this calendar supports */
allowedReminders?: AlarmMethod[]; // Android
/** Attendee types that this calendar supports */
allowedAttendeeTypes?: AttendeeType[]; // Android
/** Indicates whether the OS displays events on this calendar */
isVisible?: boolean; // Android
/** Indicates whether this calendar is synced and its events stored on the device */
isSynced?: boolean; // Android
/** Level of access that the user has for the calendar */
accessLevel?: CalendarAccessLevel; // Android
}
interface Source {
/** Internal ID that represents this source on the device */
id?: string; // iOS only ??
/** Type of account that owns this calendar */
type?: string;
/** Name for the account that owns this calendar */
name?: string;
/** Whether this source is the local phone account */
isLocalAccount?: boolean; // Android
}
interface Event {
/** Internal ID that represents this event on the device */
id?: string;
/** ID of the calendar that contains this event */
calendarId?: string;
/** Visible name of the event */
title?: string;
/** Location field of the event */
location?: string;
/** Date when the event record was created */
creationDate?: string; // iOS
/** Date when the event record was last modified */
lastModifiedDate?: string; // iOS
/** Time zone the event is scheduled in */
timeZone?: string;
/** Time zone for the event end time */
endTimeZone?: string; // Android
/** URL for the event */
url?: string; // iOS
/** Description or notes saved with the event */
notes?: string;
/** Array of Alarm objects which control automated reminders to the user */
alarms?: Alarm[];
/** Object representing rules for recurring or repeating events. Null for one-time events. */
recurrenceRule?: RecurrenceRule;
/** Date object or string representing the time when the event starts */
startDate?: string;
/** Date object or string representing the time when the event ends */
endDate?: string;
/** For recurring events, the start date for the first (original) instance of the event */
originalStartDate?: string; // iOS
/** Boolean value indicating whether or not the event is a detached (modified) instance of a recurring event */
isDetached?: boolean; // iOS
/** Whether the event is displayed as an all-day event on the calendar */
allDay?: boolean;
/** The availability setting for the event */
availability?: Availability; // Availability
/** Status of the event */
status?: EventStatus; // Status
/** Organizer of the event, as an Attendee object */
organizer?: string; // Organizer - iOS
/** Email address of the organizer of the event */
organizerEmail?: string; // Android
/** Users access level for the event */
accessLevel?: EventAccessLevel; // Android,
/** Whether invited guests can modify the details of the event */
guestsCanModify?: boolean; // Android,
/** Whether invited guests can invite other guests */
guestsCanInviteOthers?: boolean; // Android
/** Whether invited guests can see other guests */
guestsCanSeeGuests?: boolean; // Android
/** For detached (modified) instances of recurring events, the ID of the original recurring event */
originalId?: string; // Android
/** For instances of recurring events, volatile ID representing this instance; not guaranteed to always refer to the same instance */
instanceId?: string; // Android
}
interface Attendee {
/** Internal ID that represents this attendee on the device */
id?: string; // Android
/** Indicates whether or not this attendee is the current OS user */
isCurrentUser?: boolean; // iOS
/** Displayed name of the attendee */
name?: string;
/** Role of the attendee at the event */
role?: AttendeeRole;
/** Status of the attendee in relation to the event */
status?: AttendeeStatus;
/** Type of the attendee */
type?: AttendeeType;
/** URL for the attendee */
url?: string; // iOS
/** Email address of the attendee */
email?: string; // Android
}
interface Reminder {
/** Internal ID that represents this reminder on the device */
id?: string;
/** ID of the calendar that contains this reminder */
calendarId?: string;
/** Visible name of the reminder */
title?: string;
/** Location field of the reminder */
location?: string;
/** Date when the reminder record was created */
creationDate?: string;
/** Date when the reminder record was last modified */
lastModifiedDate?: string;
/** Time zone the reminder is scheduled in */
timeZone?: string;
/** URL for the reminder */
url?: string;
/** Description or notes saved with the reminder */
notes?: string;
/** Array of Alarm objects which control automated alarms to the user about the task */
alarms?: Alarm[];
/** Object representing rules for recurring or repeated reminders. Null for one-time tasks. */
recurrenceRule?: RecurrenceRule;
/** Date object or string representing the start date of the reminder task */
startDate?: string;
/** Date object or string representing the time when the reminder task is due */
dueDate?: string;
/** Indicates whether or not the task has been completed */
completed?: boolean;
/** Date object or string representing the date of completion, if completed is true */
completionDate?: string;
}
interface Alarm {
/** Date object or string representing an absolute time the alarm should occur; overrides relativeOffset and structuredLocation if specified alongside either */
absoluteDate?: string; // iOS
/** Number of minutes from the startDate of the calendar item that the alarm should occur; use negative values to have the alarm occur before the startDate */
relativeOffset?: string;
structuredLocation?: {
// iOS
title?: string;
proximity?: string; // Proximity
radius?: number;
coords?: {
latitude?: number;
longitude?: number;
};
};
/** Method of alerting the user that this alarm should use; on iOS this is always a notification */
method?: AlarmMethod; // Method, Android
}
interface RecurrenceRule {
/** How often the calendar item should recur */
frequency: Frequency; // Frequency
/** Interval at which the calendar item should recur. For example, an interval: 2 with frequency: DAILY would yield an event that recurs every other day. Defaults to 1 . */
interval?: number;
/** Date on which the calendar item should stop recurring; overrides occurrence if both are specified */
endDate?: string;
/** Number of times the calendar item should recur before stopping */
occurrence?: number;
}
enum EntityTypes {
EVENT = 'event',
REMINDER = 'reminder',
}
enum CalendarType {
LOCAL = 'local',
CALDAV = 'caldav',
EXCHANGE = 'exchange',
SUBSCRIBED = 'subscribed',
BIRTHDAYS = 'birthdays'
}
enum Availability {
NOT_SUPPORTED = 'notSupported', // iOS
BUSY = 'busy',
FREE = 'free',
TENTATIVE = 'tentative',
UNAVAILABLE = 'unavailable' // iOS
}
enum AlarmMethod {
ALARM = 'alarm',
ALERT = 'alert',
EMAIL = 'email',
SMS = 'sms',
DEFAULT = 'default',
}
enum AttendeeType {
UNKNOWN = 'unknown', // iOS
PERSON = 'person', // iOS
ROOM = 'room', // iOS
GROUP = 'group', // iOS
RESOURCE = 'resource',
OPTIONAL = 'optional', // Android
REQUIRED = 'required', // Android
NONE = 'none' // Android
}
enum CalendarAccessLevel {
CONTRIBUTOR = 'contributor',
EDITOR = 'editor',
FREEBUSY = 'freebusy',
OVERRIDE = 'override',
OWNER = 'owner',
READ = 'read',
RESPOND = 'respond',
ROOT = 'root',
NONE = 'none'
}
enum EventAccessLevel {
CONFIDENTIAL = 'confidential',
PRIVATE = 'private',
PUBLIC = 'public',
DEFAULT = 'default'
}
enum EventStatus {
NONE = 'none',
CONFIRMED = 'confirmed',
TENTATIVE = 'tentative',
CANCELED = 'canceled'
}
enum AttendeeRole {
UNKNOWN = 'unknown', // iOS
REQUIRED = 'required', // iOS
OPTIONAL = 'optional', // iOS
CHAIR = 'chair', // iOS
NON_PARTICIPANT = 'nonParticipant', // iOS
ATTENDEE = 'attendee', // Android
ORGANIZER = 'organizer', // Android
PERFORMER = 'performer', // Android
SPEAKER = 'speaker', // Android
NONE = 'none' // Android
}
enum AttendeeStatus {
UNKNOWN = 'unknown', // iOS
PENDING = 'pending', // iOS
ACCEPTED = 'accepted',
DECLINED = 'declined',
TENTATIVE = 'tentative',
DELEGATED = 'delegated', // iOS
COMPLETED = 'completed', // iOS
IN_PROCESS = 'inProcess', // iOS
INVITED = 'invited', // Android
NONE = 'none' // Android
}
enum Frequency {
DAILY = 'daily',
WEEKLY = 'weekly',
MONTHLY = 'monthly',
YEARLY = 'yearly'
}
enum ReminderStatus {
COMPLETED = 'completed',
INCOMPLETE = 'incomplete'
}
interface RecurringEventOptions {
futureEvents?: boolean;
instanceStartDate?: string;
}
/** Gets an array of calendar objects with details about the different calendars stored on the device. */
function getCalendarsAsync(
/** (iOS only) Not required, but if defined, filters the returned calendars to a specific entity type. */
entityType?: EntityTypes
): Promise<Calendar[]>;
/** Creates a new calendar on the device, allowing events to be added later and displayed. */
function createCalendarAsync(details: Calendar): Promise<string>;
/** Updates the provided details of an existing calendar stored on the device. To remove a property, explicitly set it to null in details */
function updateCalendarAsync(id: string, details?: Calendar | null): Promise<string>;
/** Deletes an existing calendar and all associated events/reminders/attendees from the device. Use with caution. */
function deleteCalendarAsync(id: string): Promise<void>;
/** Returns all events in a given set of calendars over a specified time period. */
function getEventsAsync(
/** Array of IDs of calendars to search for events in. Required. */
calendarIds: string[],
/** Beginning of time period to search for events in. Required. */
startDate: Date,
/** End of time period to search for events in. Required. */
endDate: Date
): Promise<Event[]>;
/** Returns a specific event selected by ID. If a specific instance of a recurring event is desired, the start date of this instance must also be provided, as instances of recurring events do not have their own unique and stable IDs on either iOS or Android. */
function getEventAsync(
/** ID of the event to return. Required. */
id: string,
/** A map of options for recurring events */
recurringEventOptions?: RecurringEventOptions
): Promise<Event>;
/** Creates a new event on the specified calendar. */
function createEventAsync(
/** ID of the calendar to create this event in. Required. */
calendarId: string,
details?: Event
): Promise<string>;
/** Updates the provided details of an existing calendar stored on the device. To remove a property, explicitly set it to null in details */
function updateEventAsync(
/** ID of the event to be updated. Required. */
id: string,
/** A map of properties to be updated */
details?: Event | null,
/** A map of options for recurring events */
recurrentEventOptions?: RecurringEventOptions
): Promise<string>;
/** Deletes an existing event from the device. Use with caution. */
function deleteEventAsync(
/** ID of the event to be deleted. Required. */
id: string,
/** A map of options for recurring events */
recurringEventOptions?: RecurringEventOptions
): Promise<void>;
/** Gets all attendees for a given event (or instance of a recurring event). */
function getAttendeesForEventAsync(
/** ID of the event to return attendees for. Required. */
eventId: string,
/** A map of options for recurring events */
recurrentEventOptions?: RecurringEventOptions
): Promise<Attendee[]>;
/** Available on Android only. Creates a new attendee record and adds it to the specified event. Note that if eventId specifies a recurring event, this will add the attendee to every instance of the event. */
function createAttendeeAsync(
/** ID of the event to add this attendee to. Required. */
eventId: string,
/** A map of details for the attendee to be created */
details?: Attendee
): Promise<string>;
/** Available on Android only. Updates an existing attendee record. To remove a property, explicitly set it to null in details. */
function updateAttendeeAsync(
/** ID of the attendee record to be updated. Required. */
id: string,
/** A map of properties to be updated */
details?: Attendee | null
): Promise<string>;
/** Available on Android only. Deletes an existing attendee record from the device. Use with caution. */
function deleteAttendeeAsync(id: string): Promise<void>;
/** Available on iOS only. Returns a list of reminders matching the provided criteria. */
function getRemindersAsync(
/** Array of IDs of calendars to search for reminders in. Required. */
calendarIds: string[],
status?: ReminderStatus,
/** Beginning of time period to search for reminders in. Required if status is defined. */
startDate?: Date,
/** End of time period to search for reminders in. Required if status is defined. */
endDate?: Date
): Promise<Reminder[]>;
/** Available on iOS only. Returns a specific reminder selected by ID. */
function getReminderAsync(id: string): Promise<Reminder>;
/** Available on iOS only. Creates a new reminder on the specified calendar. */
function createReminderAsync(
/** ID of the calendar to create this reminder in. Required. */
calendarId: string,
/** A map of details for the reminder to be created */
details?: Reminder
): Promise<string>;
/** Available on iOS only. Updates the provided details of an existing reminder stored on the device. To remove a property, explicitly set it to null in details. */
function updateReminderAsync(
/** ID of the reminder to be updated. Required. */
id: string,
/** A map of properties to be updated */
details?: Reminder | null
): Promise<string>;
/** Available on iOS only. Deletes an existing reminder from the device. Use with caution. */
function deleteReminderAsync(id: string): Promise<void>;
/** Available on iOS only. */
function getSourcesAsync(): Promise<Source[]>;
/** Available on iOS only. Returns a specific source selected by ID. */
function getSourceAsync(id: string): Promise<Source>;
/** Available on Android only. Sends an intent to open the specified event in the OS Calendar app. */
function openEventInCalendar(
/** ID of the event to open. Required. */
id: string
): void;
}
// #endregion
// #region Calendar
/**
* An API to compose mails using OS specific UI.
*/
export namespace MailComposer {
interface ComposeOptions {
/** An array of e-mail addressess of the recipients. */
recipients?: string[];
/** An array of e-mail addressess of the CC recipients. */
ccRecipients?: string[];
/** An array of e-mail addressess of the BCC recipients. */
bccRecipients?: string[];
/** Subject of the mail. */
subject?: string;
/** Body of the mail. */
body?: string;
/** Whether the body contains HTML tags so it could be formatted properly. Not working perfectly on Android. */
isHtml?: boolean;
/** An array of apps internal file uris to attach. */
attachments?: string[];
}
/** Resolves to a promise with object containing status field that could be either sent, saved or cancelled. Android does not provide such info so it always resolves to sent. */
function composeAsync(
/** A map defining the data to fill the mail */
options: ComposeOptions
): Promise<{ status: 'sent' | 'saved' | 'cancelled' }>;
}
// #endregion
+554
View File
@@ -0,0 +1,554 @@
import * as React from 'react';
import { Text } from 'react-native';
import {
Accelerometer,
Amplitude,
Asset,
AuthSession,
Audio,
AppLoading,
BarCodeScanner,
BlurViewProps,
BlurView,
Brightness,
Camera,
CameraObject,
DocumentPicker,
Facebook,
FacebookAds,
FileSystem,
ImagePicker,
ImageManipulator,
FaceDetector,
Svg,
IntentLauncherAndroid,
KeepAwake,
LinearGradient,
Permissions,
registerRootComponent,
ScreenOrientation
} from 'expo';
Accelerometer.addListener((obj) => {
obj.x;
obj.y;
obj.z;
});
Accelerometer.removeAllListeners();
Accelerometer.setUpdateInterval(1000);
Amplitude.initialize('key');
Amplitude.setUserId('userId');
Amplitude.setUserProperties({key: 1});
Amplitude.clearUserProperties();
Amplitude.logEvent('name');
Amplitude.logEventWithProperties('event', {key: 'value'});
Amplitude.setGroup('type', ['value']);
const asset = Asset.fromModule(1);
asset.downloadAsync();
Asset.loadAsync(1);
Asset.loadAsync([1, 2, 3]);
const asset1 = new Asset({
uri: 'uri',
type: 'type',
name: 'name',
hash: 'hash',
width: 122,
height: 122
});
const url = AuthSession.getRedirectUrl();
AuthSession.dismiss();
AuthSession.startAsync({
authUrl: 'url1',
returnUrl: 'url2'
}).then(result => {
switch (result.type) {
case 'success':
result.event;
result.params;
break;
case 'error':
result.errorCode;
result.params;
result.event;
break;
case 'dismissed':
case 'cancel':
result.type;
break;
}
});
AuthSession.startAsync({
authUrl: 'url1',
returnUrl: undefined
});
Audio.setAudioModeAsync({
shouldDuckAndroid: false,
playsInSilentModeIOS: true,
interruptionModeIOS: 2,
interruptionModeAndroid: 1,
allowsRecordingIOS: true
});
Audio.setIsEnabledAsync(true);
Audio.INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS === 0;
Audio.INTERRUPTION_MODE_IOS_DO_NOT_MIX === 1;
Audio.INTERRUPTION_MODE_IOS_DUCK_OTHERS === 2;
Audio.INTERRUPTION_MODE_ANDROID_DO_NOT_MIX === 1;
Audio.INTERRUPTION_MODE_ANDROID_DUCK_OTHERS === 2;
Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_DEFAULT === 0;
Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_THREE_GPP === 1;
Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG_4 === 2;
Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_NB === 3;
Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_WB === 4;
Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADIF === 5;
Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADTS === 6;
Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_RTP_AVP === 7;
Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG2TS === 8;
Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_WEBM === 9;
Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_DEFAULT === 0;
Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_NB === 1;
Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_WB === 2;
Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC === 3;
Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_HE_AAC === 4;
Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC_ELD === 5;
Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_VORBIS === 6;
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_LINEARPCM === 'lpcm';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AC3 === 'ac-3';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_60958AC3 === 'cac3';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLEIMA4 === 'ima4';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC === 'aac ';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4CELP === 'celp';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4HVXC === 'hvxc';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4TWINVQ === 'twvq';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE3 === 'MAC3';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE6 === 'MAC6';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ULAW === 'ulaw';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ALAW === 'alaw';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN === 'QDMC';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN2 === 'QDM2';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QUALCOMM === 'Qclp';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER1 === '.mp1';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER2 === '.mp2';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER3 === '.mp3';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLELOSSLESS === 'alac';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE === 'aach';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_LD === 'aacl';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD === 'aace';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_SBR === 'aacf';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_V2 === 'aacg';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE_V2 === 'aacp';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_SPATIAL === 'aacs';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR === 'samr';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR_WB === 'sawb';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AUDIBLE === 'AUDB';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ILBC === 'ilbc';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_DVIINTELIMA === 0x6d730011;
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MICROSOFTGSM === 0x6d730031;
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AES3 === 'aes3';
Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ENHANCEDAC3 === 'ec-3';
Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MIN === 0;
Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_LOW === 0x20;
Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MEDIUM === 0x40;
Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH === 0x60;
Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MAX === 0x7f;
Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_CONSTANT === 0;
Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_LONG_TERM_AVERAGE === 1;
Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE_CONSTRAINED === 2;
Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE === 3;
Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY;
Audio.RECORDING_OPTIONS_PRESET_LOW_QUALITY;
async () => {
const result = await Audio.Sound.create({uri: 'uri'}, {
volume: 0.5,
rate: 0.6
}, null, true);
const sound = result.sound;
const status = result.status;
if (!status.isLoaded) {
status.error;
} else {
status.didJustFinish;
// etc.
}
const _status = await sound.getStatusAsync();
await sound.loadAsync({uri: 'uri'});
};
() => (
<AppLoading
startAsync={() => Promise.resolve()}
onFinish={() => {}}
onError={(error) => console.log(error)} />
);
() => (
<AppLoading
startAsync={null}
onFinish={null}
onError={null} />
);
const barcodeReadCallback = () => {};
() => (
<BarCodeScanner
type="front"
torchMode="off"
barCodeTypes={[BarCodeScanner.Constants.BarCodeType.aztec]}
onBarCodeRead={barcodeReadCallback} />
);
() => (
<BlurView
tint="dark"
intensity={2} />
);
async () => {
await Brightness.setBrightnessAsync(.6);
await Brightness.setSystemBrightnessAsync(.7);
const br1 = await Brightness.getBrightnessAsync();
const br2 = await Brightness.getSystemBrightnessAsync();
};
Camera.Constants.AutoFocus;
Camera.Constants.Type;
Camera.Constants.FlashMode;
Camera.Constants.WhiteBalance;
Camera.Constants.VideoQuality;
Camera.Constants.BarCodeType;
() => {
return(<Camera ref={(component: any) => {
if (component) {
component.recordAsync();
}
}} />);
};
async () => {
const result = await DocumentPicker.getDocumentAsync();
if (result.type === 'success') {
result.name;
result.uri;
result.size;
}
};
async () => {
const { type, expires, token } = await Facebook.logInWithReadPermissionsAsync("appId");
};
() => (
<FacebookAds.BannerView
type="large"
placementId="str"
onPress={() => {}}
onError={() => {}} />
);
async () => {
const info = await FileSystem.getInfoAsync('file');
info.exists;
info.isDirectory;
if (info.exists) {
info.md5;
info.uri;
info.size;
info.modificationTime;
}
const string: string = await FileSystem.readAsStringAsync('file');
await FileSystem.writeAsStringAsync('file', 'content');
await FileSystem.deleteAsync('file');
await FileSystem.moveAsync({ from: 'from', to: 'to'});
await FileSystem.copyAsync({ from: 'from', to: 'to' });
await FileSystem.makeDirectoryAsync('dir');
const dirs: string[] = await FileSystem.readDirectoryAsync('dir');
const result = await FileSystem.downloadAsync('from', 'to');
result.headers;
result.status;
result.uri;
result.md5;
};
async () => {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Videos
});
if (!result.cancelled) {
result.uri;
result.width;
result.height;
}
};
async () => {
const result = await ImageManipulator.manipulate('url', {
rotate: 90
}, {
compress: 0.5
});
result.height;
result.uri;
result.width;
};
FaceDetector.Constants.Mode.fast;
FaceDetector.Constants.Mode.accurate;
FaceDetector.Constants.Landmarks.all;
FaceDetector.Constants.Landmarks.none;
FaceDetector.Constants.Classifications.all;
FaceDetector.Constants.Classifications.none;
async () => {
const result = await FaceDetector.detectFaces('url', {
mode: FaceDetector.Constants.Mode.fast,
detectLandmarks: FaceDetector.Constants.Landmarks.all,
runClassifications: FaceDetector.Constants.Classifications.none
});
result.faces[0];
};
() => (
<Svg width={100} height={50}>
<Svg.Rect
x={25}
y={5}
width={150}
height={50}
fill='rgb(0,0,255)'
strokeWidth={3}
stroke='rgb(0,0,0)'
/>
<Svg.Circle
cx={50}
cy={50}
r={50}
fill="pink"
/>
<Svg.Ellipse
cx={55}
cy={55}
rx={50}
ry={30}
stroke="purple"
strokeWidth={2}
fill="yellow"
/>
<Svg.Line
x1={0}
y1={0}
x2={100}
y2={100}
stroke="red"
strokeWidth={2}
/>
<Svg.Polygon
points="40,5 70,80 25,95"
fill="lime"
stroke="purple"
strokeWidth={1}
/>
<Svg.Polyline
points="10,10 20,12 30,20 40,60 60,70 95,90"
fill="none"
stroke="black"
strokeWidth={3}
/>
<Svg.Text
fill="none"
stroke="purple"
fontSize={20}
fontWeight="bold"
x={100}
y={20}
textAnchor="middle"
>
STROKED TEXT
</Svg.Text>
<Svg.Defs>
<Svg.Path
id="path"
d=""
/>
</Svg.Defs>
<Svg.G y={20}>
<Svg.Text fill="blue" >
<Svg.TextPath href="#path" startOffset="-10%">
We go up and down,
<Svg.TSpan fill="red" dy="5,5,5">then up again</Svg.TSpan>
</Svg.TextPath>
</Svg.Text>
<Svg.Path
d=""
fill="none"
stroke="red"
strokeWidth={1}
/>
</Svg.G>
<Svg.Use href="#shape" x="20" y="0" />
<Svg.Symbol id="symbol" viewBox="0 0 150 110" width="100" height="50">
<Svg.Circle cx="50" cy="50" r="40" strokeWidth="8" stroke="red" fill="red"/>
<Svg.Circle cx="90" cy="60" r="40" strokeWidth="8" stroke="green" fill="white"/>
</Svg.Symbol>
<Svg.Defs>
<Svg.ClipPath id="clip">
<Svg.Circle cx="50%" cy="50%" r="40%"/>
</Svg.ClipPath>
<Svg.RadialGradient id="grad" cx="50%" cy="50%" rx="50%" ry="50%" fx="50%" fy="50%" gradientUnits="userSpaceOnUse">
<Svg.Stop
offset="0%"
stopColor="#ff0"
stopOpacity="1"
/>
</Svg.RadialGradient>
<Svg.LinearGradient id="grad" x1="0" y1="0" x2="170" y2="0">
<Svg.Stop offset="1" stopColor="red" stopOpacity="1" />
</Svg.LinearGradient>
</Svg.Defs>
</Svg>
);
IntentLauncherAndroid.ACTION_ACCESSIBILITY_SETTINGS === 'android.settings.ACCESSIBILITY_SETTINGS';
IntentLauncherAndroid.ACTION_APP_NOTIFICATION_REDACTION === 'android.settings.ACTION_APP_NOTIFICATION_REDACTION';
IntentLauncherAndroid.ACTION_CONDITION_PROVIDER_SETTINGS === 'android.settings.ACTION_CONDITION_PROVIDER_SETTINGS';
IntentLauncherAndroid.ACTION_NOTIFICATION_LISTENER_SETTINGS === 'android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS';
IntentLauncherAndroid.ACTION_PRINT_SETTINGS === 'android.settings.ACTION_PRINT_SETTINGS';
IntentLauncherAndroid.ACTION_ADD_ACCOUNT_SETTINGS === 'android.settings.ADD_ACCOUNT_SETTINGS';
IntentLauncherAndroid.ACTION_AIRPLANE_MODE_SETTINGS === 'android.settings.AIRPLANE_MODE_SETTINGS';
IntentLauncherAndroid.ACTION_APN_SETTINGS === 'android.settings.APN_SETTINGS';
IntentLauncherAndroid.ACTION_APPLICATION_DETAILS_SETTINGS === 'android.settings.APPLICATION_DETAILS_SETTINGS';
IntentLauncherAndroid.ACTION_APPLICATION_DEVELOPMENT_SETTINGS === 'android.settings.APPLICATION_DEVELOPMENT_SETTINGS';
IntentLauncherAndroid.ACTION_APPLICATION_SETTINGS === 'android.settings.APPLICATION_SETTINGS';
IntentLauncherAndroid.ACTION_APP_NOTIFICATION_SETTINGS === 'android.settings.APP_NOTIFICATION_SETTINGS';
IntentLauncherAndroid.ACTION_APP_OPS_SETTINGS === 'android.settings.APP_OPS_SETTINGS';
IntentLauncherAndroid.ACTION_BATTERY_SAVER_SETTINGS === 'android.settings.BATTERY_SAVER_SETTINGS';
IntentLauncherAndroid.ACTION_BLUETOOTH_SETTINGS === 'android.settings.BLUETOOTH_SETTINGS';
IntentLauncherAndroid.ACTION_CAPTIONING_SETTINGS === 'android.settings.CAPTIONING_SETTINGS';
IntentLauncherAndroid.ACTION_CAST_SETTINGS === 'android.settings.CAST_SETTINGS';
IntentLauncherAndroid.ACTION_DATA_ROAMING_SETTINGS === 'android.settings.DATA_ROAMING_SETTINGS';
IntentLauncherAndroid.ACTION_DATE_SETTINGS === 'android.settings.DATE_SETTINGS';
IntentLauncherAndroid.ACTION_DEVICE_INFO_SETTINGS === 'android.settings.DEVICE_INFO_SETTINGS';
IntentLauncherAndroid.ACTION_DEVICE_NAME === 'android.settings.DEVICE_NAME';
IntentLauncherAndroid.ACTION_DISPLAY_SETTINGS === 'android.settings.DISPLAY_SETTINGS';
IntentLauncherAndroid.ACTION_DREAM_SETTINGS === 'android.settings.DREAM_SETTINGS';
IntentLauncherAndroid.ACTION_HARD_KEYBOARD_SETTINGS === 'android.settings.HARD_KEYBOARD_SETTINGS';
IntentLauncherAndroid.ACTION_HOME_SETTINGS === 'android.settings.HOME_SETTINGS';
IntentLauncherAndroid.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS === 'android.settings.IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS';
IntentLauncherAndroid.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS === 'android.settings.IGNORE_BATTERY_OPTIMIZATION_SETTINGS';
IntentLauncherAndroid.ACTION_INPUT_METHOD_SETTINGS === 'android.settings.INPUT_METHOD_SETTINGS';
IntentLauncherAndroid.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS === 'android.settings.INPUT_METHOD_SUBTYPE_SETTINGS';
IntentLauncherAndroid.ACTION_INTERNAL_STORAGE_SETTINGS === 'android.settings.INTERNAL_STORAGE_SETTINGS';
IntentLauncherAndroid.ACTION_LOCALE_SETTINGS === 'android.settings.LOCALE_SETTINGS';
IntentLauncherAndroid.ACTION_LOCATION_SOURCE_SETTINGS === 'android.settings.LOCATION_SOURCE_SETTINGS';
IntentLauncherAndroid.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS === 'android.settings.MANAGE_ALL_APPLICATIONS_SETTINGS';
IntentLauncherAndroid.ACTION_MANAGE_APPLICATIONS_SETTINGS === 'android.settings.MANAGE_APPLICATIONS_SETTINGS';
IntentLauncherAndroid.ACTION_MANAGE_DEFAULT_APPS_SETTINGS === 'android.settings.MANAGE_DEFAULT_APPS_SETTINGS';
IntentLauncherAndroid.ACTION_MEMORY_CARD_SETTINGS === 'android.settings.MEMORY_CARD_SETTINGS';
IntentLauncherAndroid.ACTION_MONITORING_CERT_INFO === 'android.settings.MONITORING_CERT_INFO';
IntentLauncherAndroid.ACTION_NETWORK_OPERATOR_SETTINGS === 'android.settings.NETWORK_OPERATOR_SETTINGS';
IntentLauncherAndroid.ACTION_NFCSHARING_SETTINGS === 'android.settings.NFCSHARING_SETTINGS';
IntentLauncherAndroid.ACTION_NFC_PAYMENT_SETTINGS === 'android.settings.NFC_PAYMENT_SETTINGS';
IntentLauncherAndroid.ACTION_NFC_SETTINGS === 'android.settings.NFC_SETTINGS';
IntentLauncherAndroid.ACTION_NIGHT_DISPLAY_SETTINGS === 'android.settings.NIGHT_DISPLAY_SETTINGS';
IntentLauncherAndroid.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS === 'android.settings.NOTIFICATION_POLICY_ACCESS_SETTINGS';
IntentLauncherAndroid.ACTION_NOTIFICATION_SETTINGS === 'android.settings.NOTIFICATION_SETTINGS';
IntentLauncherAndroid.ACTION_PAIRING_SETTINGS === 'android.settings.PAIRING_SETTINGS';
IntentLauncherAndroid.ACTION_PRIVACY_SETTINGS === 'android.settings.PRIVACY_SETTINGS';
IntentLauncherAndroid.ACTION_QUICK_LAUNCH_SETTINGS === 'android.settings.QUICK_LAUNCH_SETTINGS';
IntentLauncherAndroid.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS === 'android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS';
IntentLauncherAndroid.ACTION_SECURITY_SETTINGS === 'android.settings.SECURITY_SETTINGS';
IntentLauncherAndroid.ACTION_SETTINGS === 'android.settings.SETTINGS';
IntentLauncherAndroid.ACTION_SHOW_ADMIN_SUPPORT_DETAILS === 'android.settings.SHOW_ADMIN_SUPPORT_DETAILS';
IntentLauncherAndroid.ACTION_SHOW_INPUT_METHOD_PICKER === 'android.settings.SHOW_INPUT_METHOD_PICKER';
IntentLauncherAndroid.ACTION_SHOW_REGULATORY_INFO === 'android.settings.SHOW_REGULATORY_INFO';
IntentLauncherAndroid.ACTION_SHOW_REMOTE_BUGREPORT_DIALOG === 'android.settings.SHOW_REMOTE_BUGREPORT_DIALOG';
IntentLauncherAndroid.ACTION_SOUND_SETTINGS === 'android.settings.SOUND_SETTINGS';
IntentLauncherAndroid.ACTION_STORAGE_MANAGER_SETTINGS === 'android.settings.STORAGE_MANAGER_SETTINGS';
IntentLauncherAndroid.ACTION_SYNC_SETTINGS === 'android.settings.SYNC_SETTINGS';
IntentLauncherAndroid.ACTION_SYSTEM_UPDATE_SETTINGS === 'android.settings.SYSTEM_UPDATE_SETTINGS';
IntentLauncherAndroid.ACTION_TETHER_PROVISIONING_UI === 'android.settings.TETHER_PROVISIONING_UI';
IntentLauncherAndroid.ACTION_TRUSTED_CREDENTIALS_USER === 'android.settings.TRUSTED_CREDENTIALS_USER';
IntentLauncherAndroid.ACTION_USAGE_ACCESS_SETTINGS === 'android.settings.USAGE_ACCESS_SETTINGS';
IntentLauncherAndroid.ACTION_USER_DICTIONARY_INSERT === 'android.settings.USER_DICTIONARY_INSERT';
IntentLauncherAndroid.ACTION_USER_DICTIONARY_SETTINGS === 'android.settings.USER_DICTIONARY_SETTINGS';
IntentLauncherAndroid.ACTION_USER_SETTINGS === 'android.settings.USER_SETTINGS';
IntentLauncherAndroid.ACTION_VOICE_CONTROL_AIRPLANE_MODE === 'android.settings.VOICE_CONTROL_AIRPLANE_MODE';
IntentLauncherAndroid.ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE === 'android.settings.VOICE_CONTROL_BATTERY_SAVER_MODE';
IntentLauncherAndroid.ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE === 'android.settings.VOICE_CONTROL_DO_NOT_DISTURB_MODE';
IntentLauncherAndroid.ACTION_VOICE_INPUT_SETTINGS === 'android.settings.VOICE_INPUT_SETTINGS';
IntentLauncherAndroid.ACTION_VPN_SETTINGS === 'android.settings.VPN_SETTINGS';
IntentLauncherAndroid.ACTION_VR_LISTENER_SETTINGS === 'android.settings.VR_LISTENER_SETTINGS';
IntentLauncherAndroid.ACTION_WEBVIEW_SETTINGS === 'android.settings.WEBVIEW_SETTINGS';
IntentLauncherAndroid.ACTION_WIFI_IP_SETTINGS === 'android.settings.WIFI_IP_SETTINGS';
IntentLauncherAndroid.ACTION_WIFI_SETTINGS === 'android.settings.WIFI_SETTINGS';
IntentLauncherAndroid.ACTION_WIRELESS_SETTINGS === 'android.settings.WIRELESS_SETTINGS';
IntentLauncherAndroid.ACTION_ZEN_MODE_AUTOMATION_SETTINGS === 'android.settings.ZEN_MODE_AUTOMATION_SETTINGS';
IntentLauncherAndroid.ACTION_ZEN_MODE_EVENT_RULE_SETTINGS === 'android.settings.ZEN_MODE_EVENT_RULE_SETTINGS';
IntentLauncherAndroid.ACTION_ZEN_MODE_EXTERNAL_RULE_SETTINGS === 'android.settings.ZEN_MODE_EXTERNAL_RULE_SETTINGS';
IntentLauncherAndroid.ACTION_ZEN_MODE_PRIORITY_SETTINGS === 'android.settings.ZEN_MODE_PRIORITY_SETTINGS';
IntentLauncherAndroid.ACTION_ZEN_MODE_SCHEDULE_RULE_SETTINGS === 'android.settings.ZEN_MODE_SCHEDULE_RULE_SETTINGS';
IntentLauncherAndroid.ACTION_ZEN_MODE_SETTINGS === 'android.settings.ZEN_MODE_SETTINGS';
KeepAwake.activate();
KeepAwake.deactivate();
() => (
<LinearGradient
colors={['#fff']}
start={[1, 1]} />
);
() => (
<LinearGradient
colors={['#fff']}
style={{ flex: 1 }} />
);
Permissions.CAMERA === 'camera';
Permissions.CAMERA_ROLL === 'cameraRoll';
Permissions.AUDIO_RECORDING === 'audioRecording';
Permissions.CONTACTS === 'contacts';
Permissions.NOTIFICATIONS === 'remoteNotifications';
Permissions.REMOTE_NOTIFICATIONS === 'remoteNotifications';
Permissions.SYSTEM_BRIGHTNESS === 'systemBrightness';
async () => {
const result = await Permissions.askAsync(Permissions.CAMERA);
result.status === 'granted';
result.status === 'denied';
result.status === 'undetermined';
result.expires === 'never';
};
ScreenOrientation.Orientation.ALL;
ScreenOrientation.allow(ScreenOrientation.Orientation.ALL);
class __TestEntry__ extends React.Component {
render() {
return(
<Text>test</Text>
);
}
}
registerRootComponent(__TestEntry__);
+2101
View File
File diff suppressed because it is too large Load Diff
+32
View File
@@ -0,0 +1,32 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"jsx": "react",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"paths": {
"expo": [
"expo/v24"
],
"expo/*": [
"expo/v24/*"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"expo-tests.tsx"
]
}
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "dtslint/dt.json",
"rules": {
"void-return": false,
"max-line-length": false
}
}
+4428
View File
File diff suppressed because it is too large Load Diff
+1 -4426
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
import { fabric } from "fabric";
new fabric.Canvas("C");
+2 -1
View File
@@ -19,6 +19,7 @@
},
"files": [
"index.d.ts",
"fabric-tests.ts"
"test/index.ts",
"test/import.ts"
]
}
+8 -7
View File
@@ -3,7 +3,7 @@
// Definitions by: Jan Lohage <https://github.com/j2L4e>, Abraao Alves <https://github.com/AbraaoAlves>
// Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript
// TypeScript Version: 2.2
// TypeScript Version: 2.3
/// <reference types="node" />
@@ -30,7 +30,7 @@ export type ServerSideParams = Params;
export interface Params {
query?: Query;
paginate: false | Pick<PaginationOptions, 'max'>;
paginate?: false | Pick<PaginationOptions, 'max'>;
[key: string]: any; // (JL) not sure if we want this
}
@@ -42,10 +42,11 @@ export interface Paginated<T> {
data: T[];
}
export type Hook = <T>(hook: HookContext<T>) => (Promise<HookContext<T>> | undefined);
// tslint:disable-next-line void-return
export type Hook = <T>(hook: HookContext<T>) => (Promise<HookContext<T>> | void);
export interface HookContext<T> {
app?: Application<any>;
app?: Application;
data?: T;
error?: any;
id?: string | number;
@@ -89,7 +90,7 @@ export interface ServiceMethods<T> {
}
export interface SetupMethod {
setup(app: Application<any>, path: string): void;
setup(app: Application, path: string): void;
}
export interface ServiceOverloads<T> {
@@ -106,7 +107,7 @@ export interface ServiceAddons<T> extends EventEmitter {
export type Service<T> = ServiceOverloads<T> & ServiceAddons<T> & ServiceMethods<T>;
export interface Application<ServiceTypes> extends EventEmitter {
export interface Application<ServiceTypes = any> extends EventEmitter {
get(name: string): any;
set(name: string, value: any): this;
@@ -129,7 +130,7 @@ export interface Application<ServiceTypes> extends EventEmitter {
service(location: string): Service<any>;
use(path: string, service: Partial<ServiceMethods<any> & SetupMethod> | Application<any>, options?: any): this;
use(path: string, service: Partial<ServiceMethods<any> & SetupMethod> | Application, options?: any): this;
version: string;
}
+4 -2
View File
@@ -28,8 +28,10 @@ declare module '@feathersjs/feathers' {
interface Application<ServiceTypes> {
channel(...names: string[]): Channel;
publish<T>(callback: (data: T, hook: HookContext<T>) => Channel | Channel[]): Application<ServiceTypes>;
// tslint:disable-next-line void-return
publish<T>(callback: (data: T, hook: HookContext<T>) => Channel | Channel[] | void): Application<ServiceTypes>;
publish<T>(event: string, callback: (data: T, hook: HookContext<T>) => Channel | Channel[]): Application<ServiceTypes>;
// tslint:disable-next-line void-return
publish<T>(event: string, callback: (data: T, hook: HookContext<T>) => Channel | Channel[] | void): Application<ServiceTypes>;
}
}
+1 -1
View File
@@ -7,6 +7,6 @@
/// <reference types="socket.io" />
/// <reference types="feathersjs__socket-commons"/>
export default function feathersSocketIO(callback: (io: SocketIO.Server) => void): () => void;
export default function feathersSocketIO(callback?: (io: SocketIO.Server) => void): () => void;
export default function feathersSocketIO(options: number | SocketIO.ServerOptions, callback?: (io: SocketIO.Server) => void): () => void;
export default function feathersSocketIO(port: number, options?: SocketIO.ServerOptions, callback?: (io: SocketIO.Server) => void): () => void;
+3
View File
@@ -41,3 +41,6 @@ interface Fingerprint2Options {
excludePixelRatio?: boolean;
excludeHardwareConcurrency?: boolean;
}
export = Fingerprint2;
export as namespace Fingerprint2;
@@ -0,0 +1,37 @@
import ForeverAgent = require("forever-agent");
const agent = new ForeverAgent();
const agentSsl = new ForeverAgent.SSL();
const agentWithBaseOptions = new ForeverAgent({
keepAlive: true,
keepAliveMsecs: 100,
maxFreeSockets: 500,
maxSockets: 100,
});
const agentSslWithBaseOptions = new ForeverAgent({
keepAlive: true,
keepAliveMsecs: 100,
maxFreeSockets: 500,
maxSockets: 100,
});
const agentWithAllOptions = new ForeverAgent({
keepAlive: true,
keepAliveMsecs: 100,
maxFreeSockets: 500,
maxSockets: 100,
minSockets: 500,
});
const agentSslWithAllOptions = new ForeverAgent({
keepAlive: true,
keepAliveMsecs: 100,
maxFreeSockets: 500,
maxSockets: 100,
minSockets: 500,
});
const agentDefaultMinSockets = ForeverAgent.defaultMinSockets;
const agentSslDefaultMinSockets = ForeverAgent.SSL.defaultMinSockets;
+28
View File
@@ -0,0 +1,28 @@
// Type definitions for forever-agent 0.6
// Project: https://github.com/mikeal/forever-agent
// Definitions by: Dmitry Guketlev <https://github.com/yavanosta>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { Agent as HttpAgent, AgentOptions as HttpAgentOptions } from "http";
export = ForeverAgentModule;
interface ForeverAgentOptions extends HttpAgentOptions {
minSockets?: number;
}
declare class ForeverAgent extends HttpAgent {
constructor(options?: ForeverAgentOptions);
static defaultMinSockets: number;
}
declare class ForeverAgentSSL extends ForeverAgent {
constructor(options?: ForeverAgentOptions);
}
declare const ForeverAgentModule: typeof ForeverAgent & {
SSL: typeof ForeverAgentSSL,
};
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"forever-agent-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1
View File
@@ -290,6 +290,7 @@ export interface WriteOptions extends WriteFileOptions {
fs?: object;
replacer?: any;
spaces?: number | string;
EOL?: string;
}
export interface ReadResult {
+1
View File
@@ -290,6 +290,7 @@ export interface WriteOptions extends WriteFileOptions {
fs?: object;
replacer?: any;
spaces?: number | string;
EOL?: string;
}
export interface ReadResult {
+22
View File
@@ -0,0 +1,22 @@
import get = require("get-value");
const obj = { a: { b: { c: { d: "foo" } } } };
get(obj);
get(obj, "a");
get(obj, "a.b");
get(obj, "a.b.c");
get(obj, "a.b.c.d");
{
const isEnumerable = Object.prototype.propertyIsEnumerable;
const options: get.Options = {
isValid: (key, obj) => isEnumerable.call(obj, key) || typeof obj[key] === "string",
};
const obj = {};
Object.defineProperty(obj, 'foo', { value: 'bar', enumerable: false });
get(obj, 'foo', options);
get({}, 'hasOwnProperty', options);
get({}, 'constructor', options);
}
+53
View File
@@ -0,0 +1,53 @@
// Type definitions for get-value 3.0
// Project: https://github.com/jonschlinkert/get-value
// Definitions by: Daniel Rosenwasser <https://github.com/DanielRosenwasser>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
export = get;
declare function get<T>(obj: T): T;
declare function get(obj: object, key: string, options?: get.Options): any;
declare namespace get {
interface Options {
/**
* The default value to return when get-value cannot result a value from the given object.
*
* default: `undefined`
*/
default?: any;
/**
* If defined, this function is called on each resolved value.
* Useful if you want to do `.hasOwnProperty` or `Object.prototype.propertyIsEnumerable`.
*/
isValid?: <K extends string>(key: K, object: Record<K, any>) => boolean;
/**
* Custom function to use for splitting the string into object path segments.
*
* default: `String.split`
*/
split?: (s: string) => string[];
/**
* The separator to use for spliting the string.
* (this is probably not needed when `options.split` is used).
*
* default: `"."`
*/
separator?: string | RegExp;
/**
* Customize how the object path is created when iterating over path segments.
*
* default: `Array.join`
*/
join?: (segs: string[]) => string;
/**
* The character to use when re-joining the string to check for keys
* with dots in them (this is probably not needed when `options.join` is used).
* This can be a different value than the separator, since the separator can be a string or regex.
*
* default: `"."`
*/
joinChar?: string;
}
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"get-value-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
File diff suppressed because it is too large Load Diff
+1
View File
@@ -26,6 +26,7 @@
/// <reference path="google-apps-script.properties.d.ts"/>
/// <reference path="google-apps-script.script.d.ts"/>
/// <reference path="google-apps-script.sites.d.ts"/>
/// <reference path="google-apps-script.slides.d.ts"/>
/// <reference path="google-apps-script.spreadsheet.d.ts"/>
/// <reference path="google-apps-script.types.d.ts"/>
/// <reference path="google-apps-script.ui.d.ts"/>
@@ -33,6 +33,13 @@ describe('UniversalAnalytics', () => {
ga('send', 'timing', {timingCategory: 'category', timingVar: 'lookup', timingValue: 123, timingLabel: 'label'});
ga('trackerName.send', 'event', 'load');
ga('require', 'somePlugin');
ga('require', 'somePlugin', 'option');
ga('require', 'somePlugin', { some: 'options' });
ga('provide', 'somePlugin', () => {});
ga('provide', 'somePlugin', tracker => {});
ga('provide', 'somePlugin', (tracker, options) => {});
ga.create('UA-65432-1', 'auto');
ga.create('UA-65432-1', {some: 'config'});
ga.create('UA-65432-1', 'auto', {some: 'config'});
+2
View File
@@ -601,6 +601,8 @@ declare namespace UniversalAnalytics {
}): void;
(command: 'send', fieldsObject: FieldsObject): void;
(command: string, hitType: HitType, ...fields: any[]): void;
(command: 'require', pluginName: string, pluginOptions?: any): void;
(command: 'provide', pluginName: string, pluginConstructor: (tracker: Tracker, pluginOptions?: Object) => void): void;
(command: 'create', trackingId: string, cookieDomain?: string, name?: string, fieldsObject?: FieldsObject): void;
(command: 'remove'): void;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"private": true,
"dependencies": {
"styled-components": ">=2.0 || >=3.0"
"styled-components": "2.x - 3.x"
}
}
+7 -1
View File
@@ -17,8 +17,14 @@
"boom": [
"boom/v4"
],
"catbox": [
"catbox/v7"
],
"hapi": [
"hapi/v16"
],
"inert": [
"inert/v4"
]
},
"noEmit": true,
@@ -28,4 +34,4 @@
"index.d.ts",
"h2o2-tests.ts"
]
}
}
@@ -39,5 +39,5 @@ server.register(Basic).then(() => {
server.auth.strategy('simple', 'basic', { validate });
server.auth.default('simple');
server.route({ method: 'GET', path: '/', config: { auth: 'simple' } });
server.route({ method: 'GET', path: '/', options: { auth: 'simple' } });
});
-5
View File
@@ -13,11 +13,6 @@
"../"
],
"types": [],
"paths": {
"boom": [
"boom/v4"
]
},
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
+7 -1
View File
@@ -17,8 +17,14 @@
"boom": [
"boom/v4"
],
"catbox": [
"catbox/v7"
],
"hapi": [
"hapi/v16"
],
"inert": [
"inert/v4"
]
},
"noEmit": true,
@@ -28,4 +34,4 @@
"index.d.ts",
"hapi-auth-jwt2-tests.ts"
]
}
}
+7 -1
View File
@@ -19,8 +19,14 @@
"boom": [
"boom/v4"
],
"catbox": [
"catbox/v7"
],
"hapi": [
"hapi/v16"
],
"inert": [
"inert/v4"
]
},
"noEmit": true,
@@ -30,4 +36,4 @@
"index.d.ts",
"hapi-decorators-tests.ts"
]
}
}
-32
View File
@@ -1,32 +0,0 @@
/**
* [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations)
*/
export interface PluginsListRegistered {
}
/**
* An object of the currently registered plugins where each key is a registered plugin name and the value is an
* object containing:
* * version - the plugin version.
* * name - the plugin name.
* * options - (optional) options passed to the plugin during registration.
* [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations)
*/
export interface PluginRegistered {
/**
* the plugin version.
*/
version: string;
/**
* the plugin name.
*/
name: string;
/**
* options used to register the plugin.
*/
options: object;
}

Some files were not shown because too many files have changed in this diff Show More