Merge branch 'master' into office-js-in-preview

This commit is contained in:
Elizabeth Samuel
2018-08-17 12:00:01 -07:00
128 changed files with 6369 additions and 634 deletions
+6
View File
@@ -1536,6 +1536,12 @@
"sourceRepoURL": "https://github.com/samchon/tstl",
"asOfVersion": "1.5.7"
},
{
"libraryName": "typed.js",
"typingsPackageName": "typed.js",
"sourceRepoURL": "https://github.com/mattboldt/typed.js",
"asOfVersion": "2.0.9"
},
{
"libraryName": "TypeScript",
"typingsPackageName": "typescript",
+1
View File
@@ -90,6 +90,7 @@ const themeOptions : Auth0LockConstructorOptions = {
icon: 'http://baz.com/icon.png'
}
},
hideMainScreenTitle: false,
labeledSubmitButton: false,
logo: "https://example.com/assets/logo.png",
primaryColor: "green"
+2
View File
@@ -3,6 +3,7 @@
// Definitions by: Brian Caruso <https://github.com/carusology>
// Dan Caddigan <https://github.com/goldcaddy77>
// Larry Faudree <https://github.com/lfaudreejr>
// Will Caulfield <https://github.com/willcaul>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="auth0-js" />
@@ -75,6 +76,7 @@ interface Auth0LockThemeButtonOptions {
interface Auth0LockThemeOptions {
authButtons?: Auth0LockThemeButtonOptions;
hideMainScreenTitle?: boolean;
labeledSubmitButton?: boolean;
logo?: string;
primaryColor?: string;
+131
View File
@@ -0,0 +1,131 @@
import Queue = require('better-queue');
interface TestTask {
taskId: string;
taskPayload: any;
}
interface TestResult {
some: string;
}
new Queue((task) => {
const test = task.anything;
console.log(task);
});
new Queue((task: TestTask[]) => {
const test = task[0].taskId;
console.log(task);
});
new Queue<TestTask>((task: TestTask, cb) => {
const id = task.taskId;
cb(null, 'result');
cb();
}, {});
new Queue<TestTask, TestResult>({
process(task: TestTask, cb) {
const id = task.taskId;
cb(null, { some: 'prop' });
},
filter(task, cb) {
const id = task.taskId;
cb(null, task);
},
merge(oldTask, newTask, cb) {
const oldId = oldTask.taskId;
const newId = newTask.taskId;
cb(null, newTask);
},
priority(task, cb) {
const id = task.taskId;
cb(null, 10);
},
precondition(cb) {
cb(null, true);
},
afterProcessDelay: 1000,
autoResume: true,
batchDelay: 123,
batchDelayTimeout: 123,
batchSize: 123,
cancelIfRunning: true,
concurrent: 123,
failTaskOnProcessException: true,
filo: true,
id: 'taskId',
maxRetries: 1,
maxTimeout: 1,
retryDelay: 1,
storeMaxRetries: 1,
storeRetryTimeout: 1,
preconditionRetryTimeout: 1,
store: 'test'
});
new Queue<TestTask, TestResult>({
process(task: TestTask[], cb) {
const firstId = task[0].taskId;
cb(null, { some: 'prop' });
}
});
new Queue<TestTask, TestResult>(() => { }, {
id(task, cb) {
const id = task.taskId;
cb(null, 'taskId');
}
});
new Queue<TestTask, TestResult>(() => { }, {
store: {
type: 'test'
}
});
const q = new Queue<TestTask, TestResult>(() => {});
const testTask = {taskId: '', taskPayload: ''};
q.push(testTask);
q.push(testTask, (error, result) => {});
q.cancel('id', () => {});
class TestStore implements Queue.Store<TestTask> {
connect(cb: (error: any, length: number) => void) {
cb(null, 1);
}
getTask(taskId: any, cb: (error: any, task: TestTask) => void) {
cb(null, { taskId: '', taskPayload: '' });
}
deleteTask(taskId: any, cb: () => void) {
cb();
}
putTask(taskId: any, task: TestTask, priority: number, cb: (error: any) => void) {
cb(null);
}
takeFirstN(n: number, cb: (error: any, lockId: string) => void) {
cb(null, '');
}
takeLastN(n: number, cb: (error: any, lockId: string) => void) {
cb(null, '');
}
getLock(lockId: string, cb: (error: any, tasks: { [taskId: string]: TestTask }) => void) {
cb(null, {
id: { taskId: 'id', taskPayload: 'payload' }
});
}
releaseLock(lockId: string, cb: (error: any) => void) {
cb(null);
}
}
+136
View File
@@ -0,0 +1,136 @@
// Type definitions for better-queue 3.8
// Project: https://github.com/diamondio/better-queue
// Definitions by: Ostap Nagovitsyn <https://github.com/maozedong>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/* =================== USAGE ===================
import * as Queue from "better-queue";
var queue = new Queue(...);
=============================================== */
/// <reference types="node" />
declare class BetterQueue<T = any, K = any> extends NodeJS.EventEmitter {
constructor(options: BetterQueue.QueueOptions<T, K>);
constructor(process: BetterQueue.ProcessFunction<T, K>, options?: Partial<BetterQueue.QueueOptions<T, K>>);
push(task: T, cb?: (err: any, result: K) => void): BetterQueue.Ticket;
cancel(taskId: any, cb?: () => void): void;
pause(): void;
resume(): void;
destroy(cb: () => void): void;
use(store: BetterQueue.Store<T>): void;
getStats(): BetterQueue.QueueStats;
resetStats(): void;
on(event: 'task_finish', listener: (taskId: any, result: K) => void): this;
on(event: 'task_failed', listener: (taskId: any, errorMessage: string) => void): this;
on(event: 'task_progress', listener: (taskId: any, completed: number, total: number) => void): this;
on(event: BetterQueue.QueueEvent, listener: (...args: any[]) => void): this;
}
declare namespace BetterQueue {
interface QueueOptions<T, K> {
process: ProcessFunction<T, K>;
filter?(task: T, cb: (error: any, task: T) => void): void;
merge?(oldTask: T, newTask: T, cb: (error: any, mergedTask: T) => void): void;
priority?(task: T, cb: (error: any, priority: number) => void): void;
precondition?(cb: (error: any, passOrFail: boolean) => void): void;
id?: keyof T | ((task: T, cb: (error: any, id: keyof T) => void) => void);
cancelIfRunning?: boolean;
autoResume?: boolean;
failTaskOnProcessException?: boolean;
filo?: boolean;
batchSize?: number;
batchDelay?: number;
batchDelayTimeout?: number;
concurrent?: number;
maxTimeout?: number;
afterProcessDelay?: number;
maxRetries?: number;
retryDelay?: number;
storeMaxRetries?: number;
storeRetryTimeout?: number;
preconditionRetryTimeout?: number;
store?: string | StoreOptions | Store<T>;
}
// TODO reflect task types somehow (task: T | T[])
type ProcessFunction<T, K> = (task: any, cb: ProcessFunctionCb<K>) => void;
type ProcessFunctionCb<K> = (error?: any, result?: K) => void;
type QueueEvent =
'task_queued'
| 'task_accepted'
| 'task_started'
| 'task_finish'
| 'task_failed'
| 'task_progress'
| 'batch_finish'
| 'batch_failed'
| 'batch_progress'
| 'error';
type TicketEvent =
'accept'
| 'queued'
| 'started'
| 'progress'
| 'finish'
| 'failed'
| 'error';
interface Store<T> {
connect(cb: (error: any, length: number) => void): void;
getTask(taskId: any, cb: (error: any, task: T) => void): void;
deleteTask(taskId: any, cb: () => void): void;
putTask(taskId: any, task: T, priority: number, cb: (error: any) => void): void;
takeFirstN(n: number, cb: (error: any, lockId: string) => void): void;
takeLastN(n: number, cb: (error: any, lockId: string) => void): void;
getLock(lockId: string, cb: (error: any, tasks: { [taskId: string]: T }) => void): void;
releaseLock(lockId: string, cb: (error: any) => void): void;
}
interface StoreOptions {
type: string;
// store-specific options
[key: string]: any;
}
class Ticket extends NodeJS.EventEmitter {
on(event: TicketEvent, listener: (...args: any[]) => void): this;
}
interface TickerProgress {
eta: string;
pct: number;
complete: number;
total: number;
message: string;
}
interface QueueStats {
total: number;
average: number;
successRate: number;
peak: number;
}
}
export = BetterQueue;
+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",
"better-queue-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+2 -1
View File
@@ -14,6 +14,7 @@
// Slavik Nychkalo <https://github.com/gebeto>
// Francesco Benedetto <https://github.com/frabnt>
// Alexandros Dorodoulis <https://github.com/alexdor>
// Manuel Heidrich <https://github.com/mahnuh>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -31,7 +32,7 @@ declare class Chart {
stop: () => {};
resize: () => {};
clear: () => {};
toBase64: () => string;
toBase64Image: () => string;
generateLegend: () => {};
getElementAtEvent: (e: any) => {};
getElementsAtEvent: (e: any) => Array<{}>;
@@ -0,0 +1,277 @@
import * as ChartMogul from 'chartmogul-node';
const config = new ChartMogul.Config("token", "secret", "baseURL");
config.retries = 10;
config.getAccountToken(); // $ExpectType string
config.getSecretKey(); // $ExpectType string
config.VERSION; // $ExpectType string
ChartMogul.Ping.ping(config); // $ExpectType Promise<string>
// $ExpectType Promise<DataSource>
ChartMogul.DataSource.create(config, {
name: ""
});
// $ExpectType Promise<DataSource>
ChartMogul.DataSource.retrieve(config, "");
// $ExpectType Promise<{}>
ChartMogul.DataSource.destroy(config, "");
// $ExpectType Promise<DataSources>
ChartMogul.DataSource.all(config, {
name: ""
});
ChartMogul.DataSource.all(config).then(data => {
data.data_sources[0]; // $ExpectType DataSource
data.data_sources[0].name; // $ExpectType string
});
// $ExpectType Promise<Customer>
ChartMogul.Customer.create(config, {
data_source_uuid: "",
name: "",
external_id: "",
attributes: {
tags: ["important", "Prio1"],
custom: [
{type: "String", key: "channel", value: "Facebook", source: "integration"},
{type: "Integer", key: "age", value: 18}
]
}
});
// $ExpectType Promise<Customer>
ChartMogul.Customer.retrieve(config, "");
// $ExpectType Promise<Customer>
ChartMogul.Customer.modify(config, "", {});
// $ExpectType Promise<{}>
ChartMogul.Customer.destroy(config, "");
// $ExpectType Promise<Entries<Customer>>
ChartMogul.Customer.all(config, {
data_source_uuid: ""
});
ChartMogul.Customer.all(config).then(data => {
data.entries[0]; // $ExpectType Customer
data.entries[0].attributes!.stripe!['something']; // $ExpectType any
data.page!; // $ExpectType number
});
// $ExpectType Promise<Entries<Customer>>
ChartMogul.Customer.search(config, {
email: ""
});
// $ExpectType Promise<{}>
ChartMogul.Customer.merge(config, {
from: {customer_uuid: ""},
into: {customer_uuid: ""}
});
// $ExpectType Promise<Attributes>
ChartMogul.Customer.attributes(config, "");
// $ExpectType Promise<Plan>
ChartMogul.Plan.create(config, {
data_source_uuid: "",
name: "",
interval_count: 1,
interval_unit: "",
external_id: ""
});
// $ExpectType Promise<Plan>
ChartMogul.Plan.retrieve(config, "");
// $ExpectType Promise<Plan>
ChartMogul.Plan.modify(config, "", {
name: ""
});
// $ExpectType Promise<{}>
ChartMogul.Plan.destroy(config, "");
ChartMogul.Plan.all(config, {
page: 1
}).then(data => {
data.plans[0]; // $ExpectType Plan
data.plans[0].name!; // $ExpectType string
data.page!; // $ExpectType number
});
// $ExpectType Promise<Invoice>
ChartMogul.Invoice.retrieve(config, "");
// $ExpectType Promise<Invoice>
ChartMogul.Invoice.create(config, "", {
invoices: [
{
external_id: ""
}
]
});
// $ExpectType Promise<{}>
ChartMogul.Invoice.destroy(config, "");
ChartMogul.Invoice.all(config, {
external_id: ""
}).then(data => {
data.invoices[0]; // $ExpectType Invoice
data.invoices[0].uuid!; // $ExpectType string
data.page!; // $ExpectType number
});
ChartMogul.Invoice.all(config, "", {
page: 1
}).then(data => {
data.customer_uuid!; // $ExpectType string
data.invoices[0]; // $ExpectType Invoice
data.invoices[0].uuid!; // $ExpectType string
data.page!; // $ExpectType number
});
// $ExpectType Promise<Transaction>
ChartMogul.Transaction.create(config, "", {
type: "",
date: "",
result: ""
});
ChartMogul.Subscription.all(config, "", {
page: 1
}).then(data => {
data.customer_uuid!; // $ExpectType string
data.subscriptions[0]; // $ExpectType Subscription
data.subscriptions[0].uuid; // $ExpectType string
data.current_page!; // $ExpectType number
});
ChartMogul.Subscription.cancel(config, "", {
cancelled_at: ""
}).then(data => {
data.customer_uuid; // $ExpectType string
});
// $ExpectType Promise<Entries<Customer>>
ChartMogul.Tag.add(config, "", {
email: "",
tags: [""]
});
// $ExpectType Promise<Tags>
ChartMogul.Tag.add(config, "", {
tags: [""]
});
// $ExpectType Promise<Tags>
ChartMogul.Tag.remove(config, "", {
tags: [""]
});
// $ExpectType Promise<CustomAttributes>
ChartMogul.CustomAttribute.add(config, "", {
custom: [
{type: "", key: "", value: 0}
]
});
// $ExpectType Promise<Entries<Customer>>
ChartMogul.CustomAttribute.add(config, "", {
email: "",
custom: [
{type: "", key: "", value: 0}
]
});
// $ExpectType Promise<CustomAttributes>
ChartMogul.CustomAttribute.update(config, "", {
custom: {
pro: true,
channel: ""
}
});
ChartMogul.CustomAttribute.remove(config, "", {
custom: [""]
}).then(data => {
data.custom["key"]; // $ExpectType any
});
// $ExpectType Promise<All>
ChartMogul.Metrics.all(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-24',
interval: '',
geo: '',
plans: ''
});
// $ExpectType Promise<EntriesSummary<MRR>>
ChartMogul.Metrics.mrr(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-01'
});
// $ExpectType Promise<EntriesSummary<ARR>>
ChartMogul.Metrics.arr(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-01'
});
// $ExpectType Promise<EntriesSummary<ARPA>>
ChartMogul.Metrics.arpa(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-01'
});
// $ExpectType Promise<EntriesSummary<ASP>>
ChartMogul.Metrics.asp(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-01'
});
// $ExpectType Promise<EntriesSummary<CustomerCount>>
ChartMogul.Metrics.customerCount(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-01'
});
// $ExpectType Promise<EntriesSummary<CustomerChurnRate>>
ChartMogul.Metrics.customerChurnRate(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-01',
geo: '',
plans: ''
});
// $ExpectType Promise<EntriesSummary<MRRChurnRate>>
ChartMogul.Metrics.mrrChurnRate(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-01'
});
ChartMogul.Metrics.ltv(config, {
'start-date': '2015-01-01',
'end-date': '2015-11-01'
}).then(data => {
data.entries[0].ltv; // $ExpectType number
data.summary; // $ExpectType Summary
data.summary.current; // $ExpectType number
});
// $ExpectType Promise<Entries<MetricsSubscription>>
ChartMogul.Metrics.Customer.subscriptions(config, "", {
page: 1
});
ChartMogul.Metrics.Customer.activities(config, "", {
page: 1
}).then(data => {
data.entries; // $ExpectType MetricsActivity[]
data.entries[0]; // $ExpectType MetricsActivity
data.entries[0]['activity-mrr']; // $ExpectType number
data.page!; // $ExpectType number
});
+28
View File
@@ -0,0 +1,28 @@
export interface Map {
[key: string]: any
}
export interface CursorParams {
page?: number;
per_page?: number;
}
export type Strings = string[];
export interface Cursor {
page?: number;
per_page?: number;
has_more?: boolean;
current_page?: number;
total_pages?: number;
}
export interface Entries<T> extends Cursor {
entries: T[]
}
interface Summary {
current: number;
previous: number;
['percentage-change']: number;
}
export interface EntriesSummary<T> {
entries: T[];
summary: Summary;
}
+410
View File
@@ -0,0 +1,410 @@
// Type definitions for chartmogul-node 1.0
// Project: https://github.com/chartmogul/chartmogul-node
// Definitions by: ChartMogul <https://github.com/chartmogul>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import { Map, Cursor, CursorParams, Strings, Entries, EntriesSummary } from './common';
export class Config {
VERSION: string;
API_BASE: string;
retries: number;
constructor(token: string, secret: string, base?: string);
getAccountToken(): string;
getSecretKey(): string;
}
export namespace Ping {
function ping(config: Config): Promise<string>;
}
export namespace DataSource {
interface DataSource {
uuid?: string;
name: string;
created_at?: string;
status?: string;
system?: string;
}
interface DataSources {
data_sources: DataSource[];
}
interface ListDataSourcesParams {
name?: string;
system?: string;
}
function create(config: Config, data: DataSource): Promise<DataSource>;
function retrieve(config: Config, uuid: string): Promise<DataSource>;
function destroy(config: Config, uuid: string): Promise<{}>;
function all(config: Config, params?: ListDataSourcesParams): Promise<DataSources>;
}
export namespace Customer {
interface Customer {
id?: number;
data_source_uuid?: string;
data_source_uuids?: Strings;
uuid?: string;
external_id?: string;
external_ids?: Strings;
name?: string;
email?: string;
status?: string;
['customer-since']?: string;
attributes?: Attributes;
address?: {
address_zip?: string;
city?: string;
state?: string;
country?: string;
};
mrr?: number;
arr?: number;
['billing-system-url']?: string;
['chartmogul-url']?: string;
['billing-system-type']?: string;
currency?: string;
['currency-sign']?: string;
company?: string;
country?: string;
state?: string;
city?: string;
zip?: string;
lead_created_at?: string;
free_trial_started_at?: string;
}
interface NewCustomer {
data_source_uuid: string;
external_id: string;
name: string;
email?: string;
company?: string;
country?: string;
state?: string;
city?: string;
zip?: string;
lead_created_at?: string;
free_trial_started_at?: string;
attributes?: NewAttributes;
}
interface UpdateCustomer {
name?: string;
email?: string;
company?: string;
country?: string;
state?: string;
city?: string;
zip?: string;
lead_created_at?: string;
free_trial_started_at?: string;
attributes?: NewAttributes;
}
interface NewAttributes {
tags?: Strings;
custom?: NewCustomAttributes[];
}
interface NewCustomAttributes {
type?: string;
key: string;
value: any;
source?: string;
}
interface Attributes {
tags?: Strings;
stripe?: Map;
clearbit?: Map;
custom?: Map;
}
interface ListCustomersParams extends CursorParams {
data_source_uuid?: string;
status?: string;
system?: string;
external_id?: string;
}
interface SearchCustomersParams extends CursorParams {
email: string;
}
interface MergeID {
customer_uuid?: string;
external_id?: string;
}
interface MergeCustomersParams {
from: MergeID;
into: MergeID;
}
function create(config: Config, data: NewCustomer): Promise<Customer>;
function retrieve(config: Config, uuid: string): Promise<Customer>;
function modify(config: Config, uuid: string, data: UpdateCustomer): Promise<Customer>;
function destroy(config: Config, uuid: string): Promise<{}>;
function all(config: Config, params?: ListCustomersParams): Promise<Entries<Customer>>;
function search(config: Config, params?: SearchCustomersParams): Promise<Entries<Customer>>;
function merge(config: Config, params?: MergeCustomersParams): Promise<{}>;
function attributes(config: Config, uuid: string): Promise<Attributes>;
}
export namespace Plan {
interface Plan {
uuid?: string;
data_source_uuid?: string;
external_id?: string;
name?: string;
interval_count?: number;
interval_unit?: string;
}
interface ListPlansParams extends CursorParams {
data_source_uuid?: string;
system?: string;
external_id?: string;
}
interface Plans extends Cursor {
plans: Plan[];
}
function create(config: Config, data: Plan): Promise<Plan>;
function retrieve(config: Config, uuid: string): Promise<Plan>;
function modify(config: Config, uuid: string, data: Plan): Promise<Plan>;
function destroy(config: Config, uuid: string): Promise<{}>;
function all(config: Config, params?: ListPlansParams): Promise<Plans>;
}
export namespace Invoice {
interface Invoice {
uuid?: string;
customer_uuid?: string;
currency?: string;
data_source_uuid?: string;
date?: string;
due_date?: string;
external_id?: string;
line_items?: LineItem[];
transactions?: Transaction[];
}
interface LineItem {
uuid?: string;
account_code?: string;
amount_in_cents?: number;
cancelled_at?: string;
description?: string;
discount_amount_in_cents?: number;
discount_code?: string;
external_id?: string;
plan_uuid?: string;
prorated?: boolean;
quantity?: number;
service_period_end?: string;
service_period_start?: string;
subscription_external_id?: string;
subscription_uuid?: string;
tax_amount_in_cents?: number;
transaction_fees_in_cents?: number;
type?: string;
}
interface Transaction {
uuid?: string;
date?: string;
external_id?: string;
result?: string;
type?: string;
}
interface ListInvoicesParams extends CursorParams {
data_source_uuid?: string;
customer_uuid?: string;
external_id?: string;
}
interface Invoices extends Cursor {
customer_uuid?: string;
invoices: Invoice[];
}
function create(config: Config, uuid: string, data: {
invoices: Invoice[]
}): Promise<Invoice>;
function retrieve(config: Config, uuid: string): Promise<Invoice>;
function destroy(config: Config, uuid: string): Promise<{}>;
function all(config: Config, uuid: string, params?: ListInvoicesParams): Promise<Invoices>;
function all(config: Config, params?: ListInvoicesParams): Promise<Invoices>;
}
export namespace Transaction {
interface Transaction {
uuid?: string;
date: string;
external_id?: string;
result: string;
type: string;
}
function create(config: Config, uuid: string, data: Transaction): Promise<Transaction>;
}
export namespace Subscription {
interface Subscription {
uuid: string;
external_id: string;
customer_uuid: string;
plan_uuid: string;
cancellation_dates: Strings;
data_source_uuid: string;
}
interface CancelSubscriptionParams {
cancelled_at?: string;
cancellation_dates?: Strings;
}
interface Subscriptions extends Cursor {
customer_uuid?: string;
subscriptions: Subscription[];
}
function all(config: Config, uuid: string, data: CursorParams): Promise<Subscriptions>;
function cancel(config: Config, uuid: string, data: CancelSubscriptionParams): Promise<Subscription>;
}
export namespace Tag {
interface Tags {
tags: Strings;
}
interface TagsWithEmail {
email: string;
tags: Strings;
}
function add(config: Config, uuid: string, data: TagsWithEmail): Promise<Entries<Customer.Customer>>;
function add(config: Config, uuid: string, data: Tags): Promise<Tags>;
function remove(config: Config, uuid: string, data: Tags): Promise<Tags>;
}
export namespace CustomAttribute {
import NewCustomAttributes = Customer.NewCustomAttributes;
interface CustomAttributes {
custom: Map;
}
function add(config: Config, uuid: string, data: {
email: string;
custom: NewCustomAttributes[];
}): Promise<Entries<Customer.Customer>>;
function add(config: Config, uuid: string, data: {
custom: NewCustomAttributes[];
}): Promise<CustomAttributes>;
function update(config: Config, uuid: string, data: CustomAttributes): Promise<CustomAttributes>;
function remove(config: Config, uuid: string, data: {
custom: Strings;
}): Promise<CustomAttributes>;
}
export namespace Metrics {
interface Params extends ParamsNoInterval {
interval?: string;
}
interface ParamsNoInterval {
['start-date']: string;
['end-date']: string;
geo?: string;
plans?: string;
}
interface All {
entries: {
date: string;
['customer-churn-rate']: number;
['mrr-churn-rate']: number;
ltv: number;
customers: number;
asp: number;
arpa: number;
arr: number;
mrr: number;
};
}
interface MRR {
date: string;
mrr: number;
['mrr-new-business']: number;
['mrr-expansion']: number;
['mrr-contraction']: number;
['mrr-churn']: number;
['mrr-reactivation']: number;
}
interface ARR {
date: string;
arr: number;
}
interface ARPA {
date: string;
arpa: number;
}
interface ASP {
date: string;
asp: number;
}
interface CustomerCount {
date: string;
customers: number;
}
interface CustomerChurnRate {
date: string;
['customer-churn-rate']: number;
}
interface MRRChurnRate {
date: string;
['mrr-churn-rate']: number;
}
interface LTV {
date: string;
ltv: number;
}
function all(config: Config, params: Params): Promise<All>;
function mrr(config: Config, params: Params): Promise<EntriesSummary<MRR>>;
function arr(config: Config, params: Params): Promise<EntriesSummary<ARR>>;
function asp(config: Config, params: Params): Promise<EntriesSummary<ASP>>;
function arpa(config: Config, params: Params): Promise<EntriesSummary<ARPA>>;
function customerCount(config: Config, params: Params): Promise<EntriesSummary<CustomerCount>>;
function customerChurnRate(config: Config, params: ParamsNoInterval): Promise<EntriesSummary<CustomerChurnRate>>;
function mrrChurnRate(config: Config, params: ParamsNoInterval): Promise<EntriesSummary<MRRChurnRate>>;
function ltv(config: Config, params: ParamsNoInterval): Promise<EntriesSummary<LTV>>;
namespace Customer {
interface MetricsSubscription {
id: number;
external_id: string;
plan: string;
quantity: number;
mrr: number;
arr: number;
status: string;
['billing-cycle']: string;
['billing-cycle-count']: number;
['start-date']: string;
['end-date']: string;
currency: string;
['currency-sign']: string;
}
interface MetricsActivity {
id: number;
date: string;
['activity-arr']: number;
['activity-mrr']: number;
['activity-mrr-movement']: number;
currency: string;
['currency-sign']: string;
description: string;
type: string;
}
function subscriptions(config: Config, uuid: string, params?: CursorParams): Promise<Entries<MetricsSubscription>>;
function activities(config: Config, uuid: string, params?: CursorParams): Promise<Entries<MetricsActivity>>;
}
}
export class ChartMogulError extends Error {
response: any;
httpStatus: number;
}
export class ConfigurationError extends ChartMogulError {}
export class ForbiddenError extends ChartMogulError {}
export class NotFoundError extends ChartMogulError {}
export class ResourceInvalidError extends ChartMogulError {}
export class SchemaInvalidError extends ChartMogulError {}
+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",
"chartmogul-node-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+250
View File
@@ -0,0 +1,250 @@
import * as dav from "dav";
(() => {
const xhr = new dav.transport.Basic(
new dav.Credentials({
username: 'xxx',
password: 'xxx'
})
);
dav.createAccount({ server: 'http://dav.example.com', xhr })
.then((account) => {
account.calendars.forEach(() => {
});
});
const client = new dav.Client(xhr);
client.createAccount({
server: 'http://dav.example.com',
accountType: 'carddav'
}).then((account) => {
account.addressBooks.forEach(() => {
});
});
})();
(() => {
const client = new dav.Client(
new dav.transport.Basic(
new dav.Credentials({
username: 'xxx',
password: 'xxx'
})
),
{
baseUrl: 'https://mail.mozilla.com'
}
);
const req = dav.request.basic({
method: 'PUT',
data: 'BEGIN:VCALENDAR\nEND:VCALENDAR',
etag: '12345'
});
client.send(req, '/calendars/123.ics')
.then(() => { });
})();
(() => {
const xhr = new dav.transport.Basic(
new dav.Credentials({
username: 'xxx',
password: 'xxx'
})
);
const req = dav.request.basic({
method: 'PUT',
data: 'BEGIN:VCALENDAR\nEND:VCALENDAR',
etag: '12345'
});
xhr.send(req, 'https://mail.mozilla.com/calendars/123.ics')
.then(() => {
});
})();
dav.debug.enabled = true;
(() => {
const xhr = new dav.transport.Basic(
new dav.Credentials({
username: 'Killer BOB',
password: 'blacklodge'
})
);
const client = new dav.Client(xhr, { baseUrl: 'https://mail.mozilla.com' });
const url = 'https://mail.mozilla.com/';
const req = dav.request.basic({
method: 'PUT',
data: 'BEGIN:VCALENDAR\nEND:VCALENDAR',
etag: 'abc123'
});
const sandbox = dav.createSandbox();
client.send(req, url, { sandbox });
xhr.send(req, url, { sandbox });
client.createAccount({ sandbox: {}, server: 'http://dav.example.com' });
dav.createAccount({
sandbox: {},
server: 'http://dav.example.com',
xhr
});
let calendar = new dav.Calendar();
client.createCalendarObject(calendar, {
data: 'BEGIN:VCALENDAR\nEND:VCALENDAR',
filename: 'test.ics'
});
dav.createCalendarObject(
calendar,
{
data: 'BEGIN:VCALENDAR\nEND:VCALENDAR',
filename: 'test.ics',
xhr
});
let object = new dav.CalendarObject();
client.updateCalendarObject(object);
dav.updateCalendarObject(
object,
{
xhr
}
);
object = new dav.CalendarObject();
client.deleteCalendarObject(object);
dav.deleteCalendarObject(
object,
{
xhr
}
);
calendar = new dav.Calendar();
client.syncCalendar(calendar, { syncMethod: 'webdav' });
dav.syncCalendar(
calendar,
{
syncMethod: 'webdav',
xhr
}
);
let account = new dav.Account();
client.syncCaldavAccount(account, { syncMethod: 'webdav' });
dav.syncCaldavAccount(
account,
{
syncMethod: 'webdav',
xhr
}
);
let addressBook = new dav.AddressBook();
client.createCard(addressBook, {
data: 'BEGIN:VCARD\nEND:VCARD',
filename: 'test.vcf'
});
dav.createCard(addressBook,
{
data: 'BEGIN:VCARD\nEND:VCARD',
filename: 'test.vcf',
xhr
});
let vcard = new dav.VCard();
client.updateCard(vcard);
dav.updateCard(
vcard,
{
xhr
}
);
vcard = new dav.VCard();
client.deleteCard(vcard);
dav.deleteCard(
vcard,
{
xhr
});
addressBook = new dav.AddressBook();
client.syncAddressBook(addressBook, {
syncMethod: 'basic'
});
dav.syncAddressBook(
addressBook,
{
syncMethod: 'basic',
xhr
});
account = new dav.Account();
client.syncCarddavAccount(account, { syncMethod: 'basic' });
dav.syncCarddavAccount(
account,
{
syncMethod: 'basic',
xhr
});
})();
(() => {
const xhr = new dav.transport.Basic(
new dav.Credentials({ username: 'admin', password: 'admin' })
);
const req: dav.Request = {
method: 'GET',
transformRequest: (xhr: any) => xhr
};
const sandbox = dav.createSandbox();
xhr.send(req, 'http://127.0.0.1:1337', { sandbox });
sandbox.requestList;
xhr.send(req, 'http://127.0.0.1:1337');
})();
(() => {
const credentials = new dav.Credentials({
clientId: '605300196874-1ki833poa7uqabmh3hq' +
'6u1onlqlsi54h.apps.googleusercontent.com',
clientSecret: 'jQTKlOhF-RclGaGJot3HIcVf',
redirectUrl: 'https://oauth.gaiamobile.org/authenticated',
tokenUrl: 'https://accounts.google.com/o/oauth2/token',
authorizationCode: 'gareth'
});
const xhr = new dav.transport.OAuth2(credentials);
const req = { method: 'GET' };
credentials.accessToken = 'EXPIRED';
credentials.refreshToken = '1/oPHTPFgECWFPrs7KgHdis24u6Xl4E4EnRrkkiwLfzdk';
credentials.expiration = Date.now() - 1;
xhr.send(req, 'http://127.0.0.1:1337', {
retry: false
});
credentials.accessToken = 'Little Bear';
credentials.refreshToken = 'spicy tamales';
const expiration = credentials.expiration = Date.now() + 60 * 60 * 1000;
credentials.accessToken = 'EXPIRED';
credentials.refreshToken = 'raspberry pie';
credentials.expiration = Date.now() + 60 * 60 * 1000;
credentials.accessToken = 'EXPIRED';
credentials.refreshToken = 'soda';
})();
+804
View File
@@ -0,0 +1,804 @@
// Type definitions for dav 1.7
// Project: https://github.com/lambdabaa/dav/
// Definitions by: ToastHawaii <https://github.com/ToastHawaii>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
export let version: string;
/**
* Perform an initial download of a caldav or carddav account's data.
* @param options
* @returns a Promise which will be fulfilled with a dav.Account object.
*/
export function createAccount(options: CreateAccountOptions): Promise<Account>;
export interface CreateAccountOptions {
/**
* one of 'caldav' or 'carddav'. Defaults to 'caldav'.
*/
accountType?: "caldav" | "carddav";
/**
* list of caldav filters to send with request.
*/
filters?: object[];
/**
* whether or not to load dav collections.
*/
loadCollections?: boolean;
/**
* whether or not to load dav objects.
*/
loadObjects?: boolean;
/**
* request sandox.
*/
sandbox?: Sandbox | {};
/**
* some url for server (needn't be base url).
*/
server: string;
/**
* VTIMEZONE calendar object.
*/
timezone?: string;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Create a calendar object on the parameter calendar.
* @param calendar the calendar to put the object on.
* @param options
* @returns a Promise which will be fulfilled when the calendar has been created.
*/
export function createCalendarObject(calendar: Calendar, options: CreateCalendarObjectOptions): Promise<CalendarObject>;
export interface CreateCalendarObjectOptions {
/**
* rfc 5545 VCALENDAR object.
*/
data: string;
/**
* name for the calendar ics file.
*/
filename: string;
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Persist updates to the parameter calendar object to the server.
* @param calendarObject updated calendar object.
* @param options
* @returns a Promise which will be fulfilled when the calendar has been updated.
*/
export function updateCalendarObject(calendarObject: CalendarObject, options: UpdateCalendarObjectOptions): Promise<CalendarObject>;
export interface UpdateCalendarObjectOptions {
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Delete the parameter calendar object on the server.
* @param calendarObject target calendar object.
* @param options
* @returns a Promise which will be fulfilled when the calendar has been deleted.
*/
export function deleteCalendarObject(calendarObject: CalendarObject, options: DeleteCalendarObjectOptions): Promise<CalendarObject>;
export interface DeleteCalendarObjectOptions {
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Fetch changes from the remote server to the parameter calendar.
* @param calendar the calendar to fetch changes for.
* @param options
* @returns a Promise which will be fulfilled with an updated dav.Calendar object once sync is complete.
*/
export function syncCalendar(calendar: Calendar, options: SyncCalendarOptions): Promise<Calendar>;
export interface SyncCalendarOptions {
/**
* list of caldav filters to send with request.
*/
filters?: object[];
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* either 'basic' or 'webdav'. If unspecified, will try to do webdav sync
* and failover to basic sync if rfc 6578 is not supported by the server.
*/
syncMethod?: "basic" | "webdav";
/**
* VTIMEZONE calendar object.
*/
timezone?: string;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Fetch changes from the remote server to the account's calendars.
* @param account the calendar account to sync.
* @param options
* @returns a Promise which will be fulfilled with an updated dav.Account object once sync is complete.
*/
export function syncCaldavAccount(account: Account, options: SyncCaldavAccountOptions): Promise<Account>;
export interface SyncCaldavAccountOptions {
/**
* list of caldav filters to send with request.
*/
filters?: object[];
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* either 'basic' or 'webdav'. If unspecified, will try to do webdav sync
* and failover to basic sync if rfc 6578 is not supported by the server.
*/
syncMethod?: "basic" | "webdav";
/**
* VTIMEZONE calendar object.
*/
timezone?: string;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Create a vcard object on the parameter address book.
* @param addressBook the address book to put the object on.
* @param options
* @returns a Promise which will be fulfilled when the vcard has been created.
*/
export function createCard(addressBook: AddressBook, options: CreateCardOptions): Promise<AddressBook>;
export interface CreateCardOptions {
/**
* VCARD object.
*/
data: string;
/**
* name for the vcard vcf file.
*/
filename: string;
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Persist updates to the parameter vcard object to the server.
* @param card updated vcard object.
* @param options
* @returns a Promise which will be fulfilled when the vcard has been updated.
*/
export function updateCard(card: VCard, options: UpdateCardOptions): Promise<VCard>;
export interface UpdateCardOptions {
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Delete the parameter vcard object on the server.
* @param card target vcard object.
* @param options
* @returns a Promise which will be fulfilled when the vcard has been deleted.
*/
export function deleteCard(card: VCard, options: DeleteCardOptions): Promise<VCard>;
export interface DeleteCardOptions {
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Fetch changes from the remote server to the parameter address books.
* @param addressBook the address book to fetch changes for.
* @param options
* @returns a Promise which will be fulfilled with an updated AddressBook object once sync is complete.
*/
export function syncAddressBook(addressBook: AddressBook, options: SyncAddressBookOptions): Promise<AddressBook>;
export interface SyncAddressBookOptions {
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* either 'basic' or 'webdav'.If unspecified, will try to do webdav sync
* and failover to basic sync if rfc 6578 is not supported by the server.
*/
syncMethod?: "basic" | "webdav";
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Fetch changes from the remote server to the account's address books.
* @param account the address book account to sync.
* @param options
* @returns a Promise which will be fulfilled with an updated Account object once sync is complete.
*/
export function syncCarddavAccount(account: Account, options: SyncCarddavAccountOptions): Promise<Account>;
export interface SyncCarddavAccountOptions {
/**
* list of caldav filters to send with request.
*/
filters?: object[];
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* either 'basic' or 'webdav'. If unspecified, will try to do webdav sync
* and failover to basic sync if rfc 6578 is not supported by the server.
*/
syncMethod?: "basic" | "webdav";
/**
* VTIMEZONE calendar object.
*/
timezone?: string;
/**
* request sender.
*/
xhr?: transport.Transport;
}
/**
* Create a request sandbox.
*/
export class Sandbox {
constructor();
requestList: any[];
add(request: any): void;
/**
* abort sandboxed requests as a group.
*/
abort(): void;
}
/**
* @deprecated
*/
export function createSandbox(): Sandbox;
export namespace transport {
class Transport {
/**
* @param credentials user authorization.
*/
constructor(credentials: Credentials);
send(request: Request, url: string, options?: TransportOptions): Promise<any>;
}
interface TransportOptions {
/**
* request sandbox.
*/
sandbox?: Sandbox;
retry?: boolean;
}
class Basic extends Transport {
/**
* Create a new Basic object. This sends dav requests using http basic authentication.
* @param credentials user authorization.
*/
constructor(credentials: Credentials);
/**
*
* @param request object with request info.
* @param url
* @param options
* @return a promise that will be resolved with an xhr request after
* its readyState is 4 or the result of applying an optional request
* `transformResponse` function to the xhr object after its readyState
* is 4.
*/
send(request: Request, url: string, options?: TransportOptions): Promise<any>;
}
/**
* Create a new OAuth2 object.This sends dav requests authorized via rfc 6749 oauth2.
* @param credentials user authorization.
*/
class OAuth2 extends Transport {
constructor(credentials: Credentials);
/**
*
* @param request object with request info.
* @param url
* @param options
* @return a promise that will be resolved with an xhr request after
* its readyState is 4 or the result of applying an optional request
* `transformResponse` function to the xhr object after its readyState
* is 4.
*/
send(request: Request, url: string, options?: TransportOptions): Promise<any>;
}
}
export namespace request {
/**
*
* @param options
* @returns
*/
function addressBookQuery(options: AddressBookQueryOptions): string;
interface AddressBookQueryOptions {
/**
* value for Depth header.
*/
depth?: string;
/**
* list of props to request.
*/
props: object[];
}
/**
*
* @param options
* @returns
*/
function basic(options: BasicOptions): Request;
interface BasicOptions {
/**
* put request body.
*/
data: string;
/**
* http method.
*/
method: string;
/**
* cached calendar object etag.
*/
etag: string;
}
/**
*
* @param options
* @returns
*/
function calendarQuery(options: CalendarQueryOptions): string;
interface CalendarQueryOptions {
/**
* value for Depth header.
*/
depth?: string;
/**
* list of filters to send with request.
*/
filters: object[];
/**
* list of props to request.
*/
props: object[];
/**
* VTIMEZONE calendar object.
*/
timezone: string;
}
/**
*
* @param options
* @returns
*/
function propfind(options: PropfindOptions): string;
interface PropfindOptions {
/**
* value for Depth header.
*/
depth?: string;
/**
* list of props to request.
*/
props: object[];
}
/**
*
* @param options
* @returns
*/
function syncCollection(options: SyncCollectionOptions): string;
interface SyncCollectionOptions {
/**
* option value for Depth header.
*/
depth?: string;
/**
* list of props to request.
*/
props: object[];
/**
* indicates scope of the sync report request.
*/
syncLevel: number;
/**
* synchronization token provided by the server.
*/
syncToken: string;
}
}
export class Client {
/**
* Create a new Client object. The client interface allows consumers to set
* their credentials and transport once and then make authorized requests
* without passing them to each request. Each of the other, public API
* methods should be available on Client objects.
* @param xhr request sender.
* @param options
*/
constructor(xhr: transport.Transport, options?: ClientOptions);
/**
* Send a request using this client's transport (and perhaps baseUrl).
* @param req dav request.
* @param options
* @return a promise that will be resolved with an xhr request after
* its readyState is 4 or the result of applying an optional request
* `transformResponse` function to the xhr object after its readyState
* is 4.
*/
send(req: Request, uri: string, options?: ClientSendOptions): Promise<any>;
/**
* Perform an initial download of a caldav or carddav account's data.
* @param options
* @returns a Promise which will be fulfilled with a dav.Account object.
*/
createAccount(options?: CreateAccountOptions): Promise<Account>;
/**
* Create a calendar object on the parameter calendar.
* @param calendar the calendar to put the object on.
* @param options
* @returns a Promise which will be fulfilled when the calendar has been created.
*/
createCalendarObject(calendar: Calendar, options?: CreateCalendarObjectOptions): Promise<CalendarObject>;
/**
* Persist updates to the parameter calendar object to the server.
* @param calendarObject updated calendar object.
* @param options
* @returns a Promise which will be fulfilled when the calendar has been updated.
*/
updateCalendarObject(calendarObject: CalendarObject, options?: UpdateCalendarObjectOptions): Promise<CalendarObject>;
/**
* Delete the parameter calendar object on the server.
* @param calendarObject target calendar object.
* @param options
* @returns a Promise which will be fulfilled when the calendar has been deleted.
*/
deleteCalendarObject(calendarObject: CalendarObject, options?: DeleteCalendarObjectOptions): Promise<CalendarObject>;
/**
* Fetch changes from the remote server to the parameter calendar.
* @param calendar the calendar to fetch changes for.
* @param options
* @returns a Promise which will be fulfilled with an updated dav.Calendar object once sync is complete.
*/
syncCalendar(calendar: Calendar, options?: SyncCalendarOptions): Promise<Calendar>;
/**
* Fetch changes from the remote server to the account's calendars.
* @param account the calendar account to sync.
* @param options
* @returns a Promise which will be fulfilled with an updated dav.Account object once sync is complete.
*/
syncCaldavAccount(account: Account, options?: SyncCaldavAccountOptions): Promise<Account>;
/**
* Create a vcard object on the parameter address book.
* @param addressBook the address book to put the object on.
* @param options
* @returns a Promise which will be fulfilled when the vcard has been created.
*/
createCard(addressBook: AddressBook, options?: CreateCardOptions): Promise<AddressBook>;
/**
* Persist updates to the parameter vcard object to the server.
* @param card updated vcard object.
* @param options
* @returns a Promise which will be fulfilled when the vcard has been updated.
*/
updateCard(card: VCard, options?: UpdateCardOptions): Promise<VCard>;
/**
*
* Delete the parameter vcard object on the server.
* @param card target vcard object.
* @param options
* @returns a Promise which will be fulfilled when the vcard has been deleted.
*/
deleteCard(card: VCard, options?: DeleteCardOptions): Promise<VCard>;
/**
* Fetch changes from the remote server to the parameter address books.
* @param addressBook the address book to fetch changes for.
* @param options
* @returns a Promise which will be fulfilled with an updated AddressBook object once sync is complete.
*/
syncAddressBook(addressBook: AddressBook, options?: SyncAddressBookOptions): Promise<AddressBook>;
/**
* Fetch changes from the remote server to the account's address books.
* @param account the address book account to sync.
* @param options
* @returns a Promise which will be fulfilled with an updated Account object once sync is complete.
*/
syncCarddavAccount(account: Account, options?: SyncCarddavAccountOptions): Promise<Account>;
}
export interface ClientOptions {
/**
* root url to resolve relative request urls with.
*/
baseUrl: string;
}
export interface ClientSendOptions {
/**
* request sandbox.
*/
sandbox?: Sandbox;
/**
* relative url for request.
*/
url?: string;
}
export type Partial<T> = {
[P in keyof T]?: T[P];
};
export class Account {
constructor(options?: AccountOptions);
server: string;
credentials: Credentials;
rootUrl: string;
principalUrl: string;
homeUrl: string;
calendars: Calendar[];
addressBooks: AddressBook[];
}
export type AccountOptions = Partial<Account>;
export class Credentials {
constructor(options?: CredentialsOptions);
/**
* username (perhaps email) for calendar user.
*/
username: string;
/**
* plaintext password for calendar user.
*/
password: string;
/**
* oauth client id.
*/
clientId: string;
/**
* oauth client secret.
*/
clientSecret: string;
/**
* oauth code.
*/
authorizationCode: string;
/**
* oauth redirect url.
*/
redirectUrl: string;
/**
* oauth token url.
*/
tokenUrl: string;
/**
* oauth access token.
*/
accessToken: string;
/**
* oauth refresh token.
*/
refreshToken: string;
/**
* unix time for access token expiration.
*/
expiration: number;
}
export type CredentialsOptions = Partial<Credentials>;
export class DAVCollection<T> {
constructor(options: DAVCollectionOptions<T>);
data: string;
objects: T[];
account: Account;
ctag: string;
description: string;
displayName: string;
reports: string[];
resourcetype: string;
syncToken: string;
url: string;
}
export type DAVCollectionOptions<T> = Partial<DAVCollection<T>>;
export class AddressBook extends DAVCollection<VCard> {
constructor(options?: AddressBookOptions);
}
export type AddressBookOptions = Partial<AddressBook>;
export class Calendar extends DAVCollection<CalendarObject> {
constructor(options?: CalendarOptions);
components: string[];
timezone: string;
}
export type CalendarOptions = Partial<Calendar>;
export class DAVObject {
constructor(options: DAVObjectOptions);
data: string;
etag: string;
url: string;
}
export type DAVObjectOptions = Partial<DAVObject>;
export class CalendarObject extends DAVObject {
constructor(options?: CalendarObjectOptions);
calendar: Calendar;
calendarData: string;
}
export type CalendarObjectOptions = Partial<CalendarObject>;
export class VCard extends DAVObject {
constructor(options?: VCardOptions);
addressBook: AddressBook;
addressData: string;
}
export type VCardOptions = Partial<VCard>;
export class Request {
constructor(options?: RequestOptions);
method: string;
requestData?: string;
transformRequest?: (xhr: any) => any;
transformResponse?: (xhr: any) => any;
onerror?: (error: Error) => any;
}
export type RequestOptions = Partial<Request>;
export namespace debug {
let enabled: boolean;
}
export namespace ns {
const CALENDAR_SERVER = 'http://calendarserver.org/ns/';
const CALDAV_APPLE = 'http://apple.com/ns/ical/';
const CALDAV = 'urn:ietf:params:xml:ns:caldav';
const CARDDAV = 'urn:ietf:params:xml:ns:carddav';
const DAV = 'DAV:';
}
+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",
"dav-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+10
View File
@@ -0,0 +1,10 @@
import * as dialogflow from "dialogflow";
const agentsClient = new dialogflow.AgentsClient();
const contextsClient = new dialogflow.ContextsClient();
const entityTypesClient = new dialogflow.EntityTypesClient();
const intentsClient = new dialogflow.IntentsClient();
const sessionEntityTypesClient = new dialogflow.SessionEntityTypesClient();
const sessionsClient = new dialogflow.SessionsClient();
// TODO: Add real significant tests
+927
View File
@@ -0,0 +1,927 @@
// Type definitions for dialogflow 0.6
// Project: https://github.com/dialogflow/dialogflow-nodejs-client-v2#readme
// Definitions by: Daniel Dyla <https://github.com/dyladan>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
export namespace v2 {
class AgentsClient {
constructor(options?: ClientOptions);
servicePath: string;
port: number;
scopes: string[];
getProjectId(): Promise<string>;
getProjectId(callback?: (error: Error, id: string) => string): void;
getAgent(
request: GetAgentRequest,
options?: gax.CallOptions,
cb?: (err: Error, agent: Agent) => void
): Promise<[Agent]>;
searchAgents(
request: SearchAgentRequest,
options?: gax.CallOptions,
cb?: (
err: Error,
agents: Agent[],
arg3: any,
response: any
) => void
): Promise<Agent[]>;
searchAgentsStream(
request: SearchAgentRequest,
options?: gax.CallOptions
): any;
trainAgent(
request: TrainAgentRequest,
options?: gax.CallOptions,
cb?: (err: Error, operation: gax.Operation) => void
): Promise<[gax.Operation]>;
exportAgent(
request: ExportAgentRequest,
options?: gax.CallOptions,
cb?: (err: Error, operation: gax.Operation) => void
): Promise<[gax.Operation]>;
importAgent(
request: ImportAgentRequest,
options?: gax.CallOptions,
cb?: (err: Error, operation: gax.Operation) => void
): Promise<[gax.Operation]>;
restoreAgent(
request: RestoreAgentRequest,
options?: gax.CallOptions,
cb?: (err: Error, operation: gax.Operation) => void
): Promise<[gax.Operation]>;
}
class ContextsClient {
constructor(options?: ClientOptions);
servicePath: string;
port: number;
scopes: string[];
getProjectId(): Promise<string>;
getProjectId(callback?: (error: Error, id: string) => string): void;
listContexts(
request: ListContextsRequest,
options?: gax.CallOptions
): Promise<[Context[]]>;
listContextsStream(
request: ListContextsRequest,
options?: gax.CallOptions
): any;
getContext(
request: GetContextRequest,
options?: gax.CallOptions
): Promise<[Context]>;
createContext(
request: CreateContextReqeust,
options?: gax.CallOptions
): Promise<[Context]>;
updateContext(
request: UpdateContextRequest,
options?: gax.CallOptions
): Promise<[Context]>;
deleteContext(
request: DeleteContextRequest,
options?: gax.CallOptions
): Promise<void>;
deleteAllContexts(
request: DeleteAllContextsRequest,
options?: gax.CallOptions
): Promise<void>;
sessionPath(project: string, session: string): string;
contextPath(project: string, session: string, context: string): string;
matchProjectFromContextName(name: string): string;
matchSessionFromContextName(name: string): string;
matchContextFromContextName(name: string): string;
matchProjectFromSessionName(name: string): string;
matchSessionFromSessionName(name: string): string;
}
class EntityTypesClient {
constructor(options?: ClientOptions);
servicePath: string;
port: number;
scopes: string[];
getProjectId(): Promise<string>;
getProjectId(callback?: (error: Error, id: string) => string): void;
listEntityTypes(
request: ListEntityTypesRequest,
options?: gax.CallOptions
): Promise<[EntityType[]]>;
listEntityTypesStream(
request: ListEntityTypesRequest,
options?: gax.CallOptions
): any;
getEntityType(
request: GetEntityTypeRequest,
options?: gax.CallOptions
): Promise<[EntityType]>;
createEntityType(
request: CreateEntityTypeRequest,
options?: gax.CallOptions
): Promise<[EntityType]>;
updateEntityType(
request: UpdateEntityTypeRequest,
options?: gax.CallOptions
): Promise<[EntityType]>;
deleteEntityType(
request: DeleteEntityTypeRequest,
options?: gax.CallOptions
): Promise<void>;
// TODO: add batch style calls
// batchUpdateEntityTypes
// batchDeleteEntityTypes
// batchCreateEntities
// batchUpdateEntities
// batchDeleteEntities
projectAgentPath(project: string): string;
entityTypePath(project: string, entityType: string): string;
matchProjectFromProjectAgentName(entityTypeName: string): string;
matchProjectFromEntityTypeName(entityTypeName: string): string;
matchEntityTypeFromEntityTypeName(entityTypeName: string): string;
}
class IntentsClient {
constructor(options?: ClientOptions);
servicePath: string;
port: number;
scopes: string[];
getProjectId(): Promise<string>;
getProjectId(callback?: (error: Error, id: string) => string): void;
listIntents(
request: ListIntentsRequest,
options?: gax.CallOptions
): Promise<[Intent[]]>;
getIntent(
request: GetIntentRequest,
options?: gax.CallOptions
): Promise<[Intent]>;
createIntent(
request: CreateIntentRequest,
options?: gax.CallOptions
): Promise<[Intent]>;
updateIntent(
request: UpdateIntentRequest,
options?: gax.CallOptions
): Promise<[Intent]>;
deleteIntent(
request: DeleteIntentRequest,
options?: gax.CallOptions
): Promise<void>;
// TODO: add batch style calls
// batchUpdateIntents(request: BatchUpdateIntentsRequest): void;
// batchDeleteIntents(request: BatchDeleteIntentsRequest): void;
projectAgentPath(project: string): string;
intentPath(project: string, intent: string): string;
agentPath(project: string, agent: string): string;
matchProjectFromProjectAgentName(projectAgentName: string): string;
matchProjectFromIntentName(intentName: string): string;
matchIntentFromIntentName(intentName: string): string;
matchProjectFromAgentName(agentName: string): string;
matchAgentFromAgentName(agentName: string): string;
}
class SessionEntityTypesClient {
constructor(options?: ClientOptions);
servicePath: string;
port: number;
scopes: string[];
getProjectId(): Promise<string>;
getProjectId(callback?: (error: Error, id: string) => string): void;
// TODO: add Session Entity Types service methods
}
class SessionsClient {
constructor(options?: ClientOptions);
servicePath: string;
port: number;
scopes: string[];
getProjectId(): Promise<string>;
getProjectId(callback?: (error: Error, id: string) => string): void;
detectIntent(
request: DetectIntentRequest,
options?: gax.CallOptions
): Promise<DetectIntentResponse[]>;
streamingDetectIntent(options?: gax.CallOptions): Promise<any>;
sessionPath(projectId: string, sessionId: string): string;
}
}
export namespace v2beta1 {
class AgentsClient extends v2.AgentsClient {}
class ContextsClient extends v2.ContextsClient {
environmentSessionPath(
project: string,
environment: string,
user: string,
session: string
): string;
environmentContextPath(
project: string,
environment: string,
user: string,
session: string,
context: string
): string;
matchProjectFromEnvironmentSessionName(
environmentSessionName: string
): string;
matchEnvironmentFromEnvironmentSessionName(
environmentSessionName: string
): string;
matchUserFromEnvironmentSessionName(
environmentSessionName: string
): string;
matchSessionFromEnvironmentSessionName(
environmentSessionName: string
): string;
matchProjectFromEnvironmentContextName(
environmentContextName: string
): string;
matchEnvironmentFromEnvironmentContextName(
environmentContextName: string
): string;
matchUserFromEnvironmentContextName(
environmentContextName: string
): string;
matchSessionFromEnvironmentContextName(
environmentContextName: string
): string;
matchContextFromEnvironmentContextName(
environmentContextName: string
): string;
}
class EntityTypesClient extends v2.EntityTypesClient {}
class IntentsClient extends v2.IntentsClient {}
class SessionEntityTypesClient extends v2.SessionEntityTypesClient {}
class SessionsClient extends v2.SessionsClient {
environmentSessionPath(
project: string,
environment: string,
user: string,
session: string
): string;
matchProjectFromEnvironmentSessionName(
environmentSessionName: string
): string;
matchEnvironmentFromEnvironmentSessionName(
environmentSessionName: string
): string;
matchUserFromEnvironmentSessionName(
environmentSessionName: string
): string;
matchSessionFromEnvironmentSessionName(
environmentSessionName: string
): string;
}
}
export class AgentsClient extends v2.AgentsClient {}
export class ContextsClient extends v2.ContextsClient {}
export class EntityTypesClient extends v2.EntityTypesClient {}
export class IntentsClient extends v2.IntentsClient {}
export class SessionEntityTypesClient extends v2.SessionEntityTypesClient {}
export class SessionsClient extends v2.SessionsClient {}
export namespace entities {
namespace DateTimeVariants {
interface DateTime {
date_time: string;
}
interface DateTimePeriod {
startDateTime: DateTime;
endDateTime: DateTime;
}
interface DatePeriod {
startDate: Date;
endDate: Date;
}
interface TimePeriod {
startTime: string;
endTime: string;
}
}
type DateTime =
| string
| DateTimeVariants.DatePeriod
| DateTimeVariants.TimePeriod
| DateTimeVariants.DateTime
| DateTimeVariants.DateTimePeriod;
interface Duration {
unit: string;
amount: number;
}
type Date = string;
type Time = string;
}
export namespace gax {
interface BackoffSettings {
initialRetryDelayMillis: number;
retryDelayMultiplier: number;
maxRetryDelayMillis: number;
initialRpcTimeoutMillis: number;
maxRpcTimeoutMillis: number;
totalTimeoutMillis: number;
}
interface RetryOptions {
retryCodes: string[];
backoffSettings: BackoffSettings;
}
interface CallOptions {
timeout?: number;
retry?: RetryOptions;
autoPaginate?: boolean;
pageToken?: any;
isBundling?: boolean;
longrunning?: BackoffSettings;
promise?: PromiseConstructor;
}
interface Operation {
grpcOp: longrunning.Operation;
longrunningDescriptor: any;
backoffSettings: BackoffSettings;
callOptions?: CallOptions;
}
}
export namespace longrunning {
type Operation =
| UnfinishedOperation
| FailedOperation
| SuccessfulOperation;
interface BaseOperation {
name: string;
metadata: any;
done: boolean;
}
interface UnfinishedOperation extends BaseOperation {
done: false;
}
interface FailedOperation extends BaseOperation {
done: true;
error: Status;
}
interface SuccessfulOperation extends BaseOperation {
done: true;
response: any;
}
interface Status {
code: number;
message: string;
details: any[];
}
}
export interface GetAgentRequest {
parent: string;
}
export interface SearchAgentRequest {
parent: string;
pageSize?: number;
}
export interface TrainAgentRequest {
parent: string;
}
export interface ExportAgentRequest {
parent: string;
agentUri?: string;
}
export interface ImportAgentRequest {
parent: string;
agentUri?: string;
agentContent?: string;
}
export interface RestoreAgentRequest {
parent: string;
agentUri?: string;
agentContent?: string;
}
export interface ListContextsRequest {
parent: string;
pageSize?: number;
}
export interface GetContextRequest {
name: string;
}
export interface CreateContextReqeust {
parent: string;
context: Context;
}
export interface UpdateContextRequest {
context: Context;
updatemask?: any;
}
export interface DeleteContextRequest {
name: string;
}
export interface DeleteAllContextsRequest {
parent: string;
}
export interface ListEntityTypesRequest {
parent: string;
languageCode?: string;
pageSize?: number;
}
export interface GetEntityTypeRequest {
name: string;
languageCode?: string;
}
export interface CreateEntityTypeRequest {
parent: string;
entityType: EntityType;
}
export interface UpdateEntityTypeRequest {
entityType: EntityType;
languageCode?: string;
/** @link https://github.com/google/protobuf/blob/master/src/google/protobuf/field_mask.proto */
updateMask?: any;
}
export interface DeleteEntityTypeRequest {
name: string;
}
export interface ListIntentsRequest {
parent: string;
languageCode?: string;
intentView?: IntentView;
pageSize?: number;
}
export interface GetIntentRequest {
name: string;
languageCode?: string;
intentView?: IntentView;
}
export interface CreateIntentRequest {
parent: string;
intent: Intent;
languageCode?: string;
intentView?: IntentView;
}
export interface UpdateIntentRequest {
intent: Intent;
languageCode?: string;
updateMask?: any;
intentView?: IntentView;
}
export interface DeleteIntentRequest {
name: string;
}
export interface DetectIntentRequest {
session: string;
queryInput: QueryInput;
queryParams?: QueryParams;
inputAudio?: any;
}
export interface DetectIntentResponse {
responseId: string;
queryResult: QueryResult;
webhookStatus: Status;
}
export interface QueryResult {
queryText: string;
laugnageCode: string;
speechRecognitionConfidence: number;
action: string;
parameters: any;
allRequiredParamsSent: boolean;
fulfillmentText: string;
fulfillmentMessages: Message[];
webhookSource: string;
webhookPayload: any;
outputContexts: Context[];
intent: Intent;
intentDetectionConfidence: number;
diagnosticInfo: any;
}
export interface Status {
code: StatusCode;
message: string;
details: any[];
}
export enum StatusCode {
// Not an error; returned on success
//
// HTTP Mapping: 200 OK
OK = 0,
// The operation was cancelled, typically by the caller.
//
// HTTP Mapping: 499 Client Closed Request
CANCELLED = 1,
// Unknown error. For example, this error may be returned when
// a `Status` value received from another address space belongs to
// an error space that is not known in this address space. Also
// errors raised by APIs that do not return enough error information
// may be converted to this error.
//
// HTTP Mapping: 500 Internal Server Error
UNKNOWN = 2,
// The client specified an invalid argument. Note that this differs
// from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` indicates arguments
// that are problematic regardless of the state of the system
// (e.g., a malformed file name).
//
// HTTP Mapping: 400 Bad Request
INVALID_ARGUMENT = 3,
// The deadline expired before the operation could complete. For operations
// that change the state of the system, this error may be returned
// even if the operation has completed successfully. For example, a
// successful response from a server could have been delayed long
// enough for the deadline to expire.
//
// HTTP Mapping: 504 Gateway Timeout
DEADLINE_EXCEEDED = 4,
// Some requested entity (e.g., file or directory) was not found.
//
// Note to server developers: if a request is denied for an entire class
// of users, such as gradual feature rollout or undocumented whitelist,
// `NOT_FOUND` may be used. If a request is denied for some users within
// a class of users, such as user-based access control, `PERMISSION_DENIED`
// must be used.
//
// HTTP Mapping: 404 Not Found
NOT_FOUND = 5,
// The entity that a client attempted to create (e.g., file or directory)
// already exists.
//
// HTTP Mapping: 409 Conflict
ALREADY_EXISTS = 6,
// The caller does not have permission to execute the specified
// operation. `PERMISSION_DENIED` must not be used for rejections
// caused by exhausting some resource (use `RESOURCE_EXHAUSTED`
// instead for those errors). `PERMISSION_DENIED` must not be
// used if the caller can not be identified (use `UNAUTHENTICATED`
// instead for those errors). This error code does not imply the
// request is valid or the requested entity exists or satisfies
// other pre-conditions.
//
// HTTP Mapping: 403 Forbidden
PERMISSION_DENIED = 7,
// The request does not have valid authentication credentials for the
// operation.
//
// HTTP Mapping: 401 Unauthorized
UNAUTHENTICATED = 16,
// Some resource has been exhausted, perhaps a per-user quota, or
// perhaps the entire file system is out of space.
//
// HTTP Mapping: 429 Too Many Requests
RESOURCE_EXHAUSTED = 8,
// The operation was rejected because the system is not in a state
// required for the operation's execution. For example, the directory
// to be deleted is non-empty, an rmdir operation is applied to
// a non-directory, etc.
//
// Service implementors can use the following guidelines to decide
// between `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`:
// (a) Use `UNAVAILABLE` if the client can retry just the failing call.
// (b) Use `ABORTED` if the client should retry at a higher level
// (e.g., when a client-specified test-and-set fails, indicating the
// client should restart a read-modify-write sequence).
// (c) Use `FAILED_PRECONDITION` if the client should not retry until
// the system state has been explicitly fixed. E.g., if an "rmdir"
// fails because the directory is non-empty, `FAILED_PRECONDITION`
// should be returned since the client should not retry unless
// the files are deleted from the directory.
//
// HTTP Mapping: 400 Bad Request
FAILED_PRECONDITION = 9,
// The operation was aborted, typically due to a concurrency issue such as
// a sequencer check failure or transaction abort.
//
// See the guidelines above for deciding between `FAILED_PRECONDITION`,
// `ABORTED`, and `UNAVAILABLE`.
//
// HTTP Mapping: 409 Conflict
ABORTED = 10,
// The operation was attempted past the valid range. E.g., seeking or
// reading past end-of-file.
//
// Unlike `INVALID_ARGUMENT`, this error indicates a problem that may
// be fixed if the system state changes. For example, a 32-bit file
// system will generate `INVALID_ARGUMENT` if asked to read at an
// offset that is not in the range [0,2^32-1], but it will generate
// `OUT_OF_RANGE` if asked to read from an offset past the current
// file size.
//
// There is a fair bit of overlap between `FAILED_PRECONDITION` and
// `OUT_OF_RANGE`. We recommend using `OUT_OF_RANGE` (the more specific
// error) when it applies so that callers who are iterating through
// a space can easily look for an `OUT_OF_RANGE` error to detect when
// they are done.
//
// HTTP Mapping: 400 Bad Request
OUT_OF_RANGE = 11,
// The operation is not implemented or is not supported/enabled in this
// service.
//
// HTTP Mapping: 501 Not Implemented
UNIMPLEMENTED = 12,
// Internal errors. This means that some invariants expected by the
// underlying system have been broken. This error code is reserved
// for serious errors.
//
// HTTP Mapping: 500 Internal Server Error
INTERNAL = 13,
// The service is currently unavailable. This is most likely a
// transient condition, which can be corrected by retrying with
// a backoff.
//
// See the guidelines above for deciding between `FAILED_PRECONDITION`,
// `ABORTED`, and `UNAVAILABLE`.
//
// HTTP Mapping: 503 Service Unavailable
UNAVAILABLE = 14,
// Unrecoverable data loss or corruption.
//
// HTTP Mapping: 500 Internal Server Error
DATA_LOSS = 15
}
export interface Agent {
parent: string;
displayName: string;
defaultLanguageCode: string;
supportedLanguageCodes?: string[];
timeZone: string;
description?: string;
avatarUri?: string;
enableLogging?: boolean;
matchMode?: MatchMode;
classificationThreshold?: number;
}
export interface Context {
name: string;
lifespanCount?: number;
parameters?: any;
}
export interface EntityType {
name: string;
entities: EntitySynonyms[];
displayName: string;
kind: EntityKind;
autoExpansionMode: EntityAutoExpansionMode;
}
export enum MatchMode {
MATCH_MODE_UNSPECIFIED = "MATCH_MODE_UNSPECIFIED",
MATCH_MODE_HYBRID = "MATCH_MODE_HYBRID",
MATCH_MODE_ML_ONLY = "MATCH_MODE_ML_ONLY"
}
export interface Credentials {
clientEmail?: string;
privateKey?: string;
}
export interface ClientOptions {
credentials?: Credentials;
email?: string;
keyFilename?: string;
port?: number;
projectId?: string;
promise?: PromiseConstructor;
servicePath?: string;
}
export interface EntitySynonyms {
synonyms: string[];
value: string;
}
export enum EntityKind {
KIND_MAP = "KIND_MAP",
KIND_LIST = "KIND_LIST"
}
export enum EntityAutoExpansionMode {
AUTO_EXPANSION_MODE_DEFAULT = "AUTO_EXPANSION_MODE_DEFAULT",
AUTO_EXPANSION_MODE_UNSPECIFIED = "AUTO_EXPANSION_MODE_UNSPECIFIED"
}
export enum IntentView {
INTENT_VIEW_UNSPECIFIED = "INTENT_VIEW_UNSPECIFIED",
INTENT_VIEW_FULL = "INTENT_VIEW_FULL"
}
export interface Intent {
name: string;
displayName: string;
webhookState: string;
priority?: number;
isFallback?: boolean;
mlEnabled?: boolean;
inputContextNames?: string[];
events?: string[];
trainingPhrases?: TrainingPhrase[];
action?: string;
outputContexts?: Context[];
resetContexts?: boolean;
parameters?: Parameter[];
messages?: Message[];
defaultResponsePlatforms?: string[];
rootFollowupIntentName: string;
parentFollowupIntentName: string;
followupIntentInfo?: FollowupIntentInfo[];
}
export interface TrainingPhrase {
name: string;
type: string;
parts: Part[];
timesAddedCount?: number;
}
export interface Part {
text: string;
entityType?: string;
alias?: string;
userDefined?: boolean;
}
export interface Parameter {
name: string;
displayName: string;
value?: string;
defaultValue?: string;
entityTypeDisplayName?: string;
mandatory?: boolean;
prompts?: string[];
isList?: boolean;
}
export interface FollowupIntentInfo {
followupIntentName: string;
parentFollowupIntentName: string;
}
export interface Message {
platform?: string;
text?: Text;
card?: Card;
payload?: any;
}
export interface Text {
text: string[];
}
export interface Card {
title?: string;
subtitle?: string;
imageUri?: string;
buttons?: Button[];
}
export interface Button {
text?: string;
postback?: string;
}
export interface EventInput {
name: string;
languageCode: string;
parameters?: any;
}
export interface TextInput {
text: string;
languageCode: string;
}
export interface QueryInput {
text?: TextInput;
event?: EventInput;
}
export interface QueryParams {
timeZone?: string;
geoLocation?: LatLong;
contexts?: Context[];
resetContexts?: boolean;
sessionEntityTypes?: SessionEntityType[];
payload?: any;
}
export interface LatLong {
latitude: number;
longitude: number;
}
export interface SessionEntityType {
name: string;
entityOverrideMode: string;
entities: Entity[];
}
export interface Entity {
value: string;
synonyms: string[];
}
export interface WebhookRequest {
session: string;
responseId: string;
queryResult: QueryResult;
originalDetectIntentRequest?: any;
}
export interface WebhookResponse {
fulfillmentText?: string;
fulfillmentMessages?: Message[];
source?: string;
payload?: any;
outputContexts?: Context[];
followupEventInput?: EventInput;
}
+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",
"dialogflow-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
@@ -0,0 +1,16 @@
const clipboard = navigator.clipboard;
let text: string;
clipboard.writeText('foo');
clipboard.readText().then((val) => {
text = val;
});
const transfer = new DataTransfer();
transfer.setData('text/plain', 'foo');
clipboard.write(transfer);
clipboard.read().then((tf) => {
text = tf.getData('text/plain');
});
+15
View File
@@ -0,0 +1,15 @@
// Type definitions for w3c Clipboard API 1.0
// Project: https://w3c.github.io/clipboard-apis/
// Definitions by: James Garbutt <https://github.com/43081j>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface Clipboard extends EventTarget {
read(): Promise<DataTransfer>;
readText(): Promise<string>;
write(data: DataTransfer): Promise<void>;
writeText(data: string): Promise<void>;
}
interface Navigator {
readonly clipboard: Clipboard;
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"dom-clipboard-api-tests.ts"
]
}
+5
View File
@@ -0,0 +1,5 @@
{
"extends": "dtslint/dt.json",
"rules": {
}
}
+1
View File
@@ -44,6 +44,7 @@ declare module 'leaflet' {
| 'GrayLabels'
| 'DarkGrayLabels'
| 'ImageryLabels'
| 'ImageryClarity'
| 'ImageryTransportation'
| 'ShadedReliefLabels'
| 'TerrainLabels';
+106
View File
@@ -0,0 +1,106 @@
import ffi = require('ffi-napi');
import ref = require('ref-napi');
import Struct = require('ref-struct-di');
import Union = require('ref-union-di');
import TArray = require('ref-array-di');
{
const sqlite3 = ref.types.void;
const sqlite3Ptr = ref.refType(sqlite3);
const sqlite3PtrPtr = ref.refType(sqlite3Ptr);
const stringPtr = ref.refType(ref.types.CString);
const libsqlite3 = ffi.Library('libsqlite3', {
sqlite3_open: [ 'int', [ 'string', sqlite3PtrPtr ] ],
sqlite3_close: [ 'int', [ sqlite3PtrPtr ] ],
sqlite3_exec: [ 'int', [ sqlite3PtrPtr, 'string', 'pointer', 'pointer', stringPtr ] ],
sqlite3_changes: [ 'int', [ sqlite3PtrPtr ]]
});
const dbPtrPtr = ref.alloc(sqlite3PtrPtr);
libsqlite3.sqlite3_open("test.sqlite3", dbPtrPtr);
}
{
const func = ffi.ForeignFunction(new Buffer(10), 'int', [ 'int' ]);
func(-5);
func.async(-5, (err: any, res: any) => {});
}
{
const funcPtr = ffi.Callback('int', [ 'int' ], Math.abs);
const func = ffi.ForeignFunction(funcPtr, 'int', [ 'int' ]);
}
{
const printfPointer = ffi.DynamicLibrary().get('printf');
const printfGen = ffi.VariadicForeignFunction(printfPointer, 'void', [ 'string' ]);
printfGen()('Hello World!\n');
printfGen('int')('This is an int: %d\n', 10);
printfGen('string')('This is a string: %s\n', 'hello');
}
{
ref.address(new Buffer(1));
const intBuf = ref.alloc(ref.types.int);
const intWith4 = ref.alloc(ref.types.int, 4);
const buf0 = ref.allocCString('hello world');
const type = ref.coerceType('int **');
const val = ref.deref(intBuf);
}
{
ref.isNull(new Buffer(1));
}
{
const str = ref.readCString(new Buffer('hello\0world\0'), 0);
const buf = ref.alloc('int64');
ref.writeInt64BE(buf, 0, '9223372036854775807');
const val = ref.readInt64BE(buf, 0);
}
{
const voidPtrType = ref.refType(ref.types.void);
const buf = ref.alloc('int64');
ref.writeInt64LE(buf, 0, '9223372036854775807');
}
{
const S1 = Struct({ a: ref.types.int });
const S2 = new Struct({ a: 'int' });
}
{
const P = new Struct();
P.defineProperty('a', ref.types.int);
P.defineProperty('d', 'long');
}
{
const SimpleStruct = Struct({
first : ref.types.byte,
last : ref.types.byte
});
const ss = new SimpleStruct({ first: 50, last: 100 });
ss.first += 200;
}
{
const ST = Struct();
const test: ref.Type = ST.fields['t'].type;
}
{
const CharArray = TArray('char');
const b = new Buffer('hello', 'ascii');
const a = new CharArray(b);
}
{
const Int32Array = TArray(ref.types.int32);
const input = [1, 4, 91, 123123, 5123512, 0, -1];
const a = new Int32Array(input);
}
{
const int = ref.types.int;
const IntArray = TArray(int);
const buf = new Buffer(int.size * 3);
int.set(buf, int.size * 0, 5);
int.set(buf, int.size * 1, 8);
int.set(buf, int.size * 2, 0);
const array = IntArray.untilZeros(buf);
}
{
const refCharArr = TArray('char')([1, 3, 5], 2).ref();
}
+186
View File
@@ -0,0 +1,186 @@
// Type definitions for node-ffi-napi 2.4
// Project: https://github.com/node-ffi/node-ffi
// Definitions by: Keerthi Niranjan <https://github.com/keerthi16>, Kiran Niranjan <https://github.com/KiranNiranjan>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/// <reference types="node" />
import ref = require('ref-napi');
import StructType = require('ref-struct-di');
/** Provides a friendly API on-top of `DynamicLibrary` and `ForeignFunction`. */
export interface Library {
/** The extension to use on libraries. */
EXT: string;
/**
* @param libFile name of library
* @param funcs hash of [retType, [...argType], opts?: {abi?, async?, varargs?}]
* @param lib hash that will be extended
*/
new (libFile: string, funcs?: {[key: string]: any[]}, lib?: object): any;
/**
* @param libFile name of library
* @param funcs hash of [retType, [...argType], opts?: {abi?, async?, varargs?}]
* @param lib hash that will be extended
*/
(libFile: string, funcs?: {[key: string]: any[]}, lib?: object): any;
}
export const Library: Library;
/** Get value of errno. */
export function errno(): number;
export interface Function extends ref.Type {
/** The type of return value. */
retType: ref.Type;
/** The type of arguments. */
argTypes: ref.Type[];
/** Is set for node-ffi functions. */
ffi_type: Buffer;
abi: number;
/** Get a `Callback` pointer of this function type. */
toPointer(fn: (...args: any[]) => any): Buffer;
/** Get a `ForeignFunction` of this function type. */
toFunction(buf: Buffer): ForeignFunction;
}
/** Creates and returns a type for a C function pointer. */
export const Function: {
new (retType: ref.Type | string, argTypes: any[], abi?: number): Function;
(retType: ref.Type | string, argTypes: any[], abi?: number): Function;
};
export interface ForeignFunction {
(...args: any[]): any;
async(...args: any[]): void;
}
/**
* Represents a foreign function in another library. Manages all of the aspects
* of function execution, including marshalling the data parameters for the
* function into native types and also unmarshalling the return from function
* execution.
*/
export const ForeignFunction: {
new (ptr: Buffer, retType: ref.Type | string, argTypes: any[], abi?: number): ForeignFunction;
(ptr: Buffer, retType: ref.Type | string, argTypes: any[], abi?: number): ForeignFunction;
};
export interface VariadicForeignFunction {
/**
* What gets returned is another function that needs to be invoked with the rest
* of the variadic types that are being invoked from the function.
*/
(...args: any[]): ForeignFunction;
/**
* Return type as a property of the function generator to
* allow for monkey patching the return value in the very rare case where the
* return type is variadic as well
*/
returnType: any;
}
/**
* For when you want to call to a C function with variable amount of arguments.
* i.e. `printf`.
*
* This function takes care of caching and reusing `ForeignFunction` instances that
* contain the same ffi_type argument signature.
*/
export const VariadicForeignFunction: {
new (ptr: Buffer, ret: ref.Type | string, fixedArgs: any[], abi?: number): VariadicForeignFunction;
(ptr: Buffer, ret: ref.Type | string, fixedArgs: any[], abi?: number): VariadicForeignFunction;
};
export interface DynamicLibrary {
/** Close library, returns the result of the `dlclose` system function. */
close(): number;
/** Get a symbol from this library. */
get(symbol: string): Buffer;
/** Get the result of the `dlerror` system function. */
error(): string;
}
/**
* This class loads and fetches function pointers for dynamic libraries
* (.so, .dylib, etc). After the libray's function pointer is acquired, then you
* call `get(symbol)` to retreive a pointer to an exported symbol. You need to
* call `get___` on the pointer to dereference it into its actual value, or
* turn the pointer into a callable function with `ForeignFunction`.
*/
export const DynamicLibrary: {
FLAGS: {
RTLD_LAZY: number;
RTLD_NOW: number;
RTLD_LOCAL: number;
RTLD_GLOBAL: number;
RTLD_NOLOAD: number;
RTLD_NODELETE: number;
RTLD_NEXT: Buffer;
RTLD_DEFAUL: Buffer;
}
new (path?: string, mode?: number): DynamicLibrary;
(path?: string, mode?: number): DynamicLibrary;
};
/**
* Turns a JavaScript function into a C function pointer.
* The function pointer may be used in other C functions that
* accept C callback functions.
*/
export interface Callback {
new (retType: any, argTypes: any[], abi: number, fn: any): Buffer;
new (retType: any, argTypes: any[], fn: any): Buffer;
(retType: any, argTypes: any[], abi: number, fn: any): Buffer;
(retType: any, argTypes: any[], fn: any): Buffer;
}
export const Callback: Callback;
export const ffiType: {
/** Get a `ffi_type *` Buffer appropriate for the given type. */
(type: ref.Type | string): Buffer
FFI_TYPE: StructType;
};
export function CIF(retType: any, types: any[], abi?: any): Buffer;
export function CIF_var(retType: any, types: any[], numFixedArgs: number, abi?: any): Buffer;
export const HAS_OBJC: boolean;
export const FFI_TYPES: {[key: string]: Buffer};
export const FFI_OK: number;
export const FFI_BAD_TYPEDEF: number;
export const FFI_BAD_ABI: number;
export const FFI_DEFAULT_ABI: number;
export const FFI_FIRST_ABI: number;
export const FFI_LAST_ABI: number;
export const FFI_SYSV: number;
export const FFI_UNIX64: number;
export const RTLD_LAZY: number;
export const RTLD_NOW: number;
export const RTLD_LOCAL: number;
export const RTLD_GLOBAL: number;
export const RTLD_NOLOAD: number;
export const RTLD_NODELETE: number;
export const RTLD_NEXT: Buffer;
export const RTLD_DEFAULT: Buffer;
export const LIB_EXT: string;
export const FFI_TYPE: StructType;
/** Default types. */
export const types: {
void: ref.Type; int64: ref.Type; ushort: ref.Type;
int: ref.Type; uint64: ref.Type; float: ref.Type;
uint: ref.Type; long: ref.Type; double: ref.Type;
int8: ref.Type; ulong: ref.Type; Object: ref.Type;
uint8: ref.Type; longlong: ref.Type; CString: ref.Type;
int16: ref.Type; ulonglong: ref.Type; bool: ref.Type;
uint16: ref.Type; char: ref.Type; byte: ref.Type;
int32: ref.Type; uchar: ref.Type; size_t: ref.Type;
uint32: ref.Type; short: ref.Type;
};
+50
View File
@@ -0,0 +1,50 @@
// DefinitelyTyped: partial
interface Buffer {
/** Shorthand for `ref.address`. */
address(): number;
/** Shorthand for `ref.deref`. */
deref(): any;
/** Shorthand for `ref.isNull`. */
isNull(): boolean;
/** Shorthand for `ref.readCString`. */
readCString(offset?: number): string;
/** Shorthand for `ref.readInt64BE`. */
readInt64BE(offset?: number): string;
/** Shorthand for `ref.readInt64LE`. */
readInt64LE(offset?: number): string;
/** Shorthand for `ref.readObject`. */
readObject(offset?: number): string;
/** Shorthand for `ref.readPointer`. */
readPointer(offset?: number): string;
/** Shorthand for `ref.readUInt64BE`. */
readUInt64BE(offset?: number): string;
/** Shorthand for `ref.readUInt64LE`. */
readUInt64LE(offset?: number): string;
/** Shorthand for `ref.ref`. */
ref(): Buffer;
/** Shorthand for `ref.reinterpret`. */
reinterpret(size: number, offset?: number): Buffer;
/** Shorthand for `ref.reinterpretUntilZeros`. */
reinterpretUntilZeros(size: number, offset?: number): Buffer;
/** Shorthand for `ref.writeCString`. */
writeCString(offset: number, input: string, encoding?: string): void;
/** Shorthand for `ref.writeInt64BE`. */
writeInt64BE(offset: number, input: number | string): any;
/** Shorthand for `ref.writeInt64LE`. */
writeInt64LE(offset: number, input: number | string): any;
/** Shorthand for `ref.writeObject`. */
writeObject(offset: number, object: object): void;
/** Shorthand for `ref.writePointer`. */
writePointer(offset: number, pointer: Buffer): void;
/** Shorthand for `ref.writeUInt64BE`. */
writeUInt64BE(offset: number, input: number | string): any;
/** Shorthand for `ref.writeUInt64LE`. */
writeUInt64LE(offset: number, input: number | string): any;
/**
* Generate string for inspecting.
* String includes the hex-encoded memory address of the Buffer instance.
*/
inspect(): string;
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"node-ffi-napi-buffer.d.ts",
"ffi-napi-tests.ts"
]
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "dtslint/dt.json",
"rules": {
"no-consecutive-blank-lines": [true, 3],
"ban-types": [false]
}
}
+4
View File
@@ -7,3 +7,7 @@ getPort().then(port => {
getPort({ port: 3000 }).then(port => {
console.log(port);
});
getPort({ port: [3000, 3001] }).then(port => {
console.log(port);
});
+2 -2
View File
@@ -1,9 +1,9 @@
// Type definitions for get-port 3.2
// Type definitions for get-port 4.0
// Project: https://github.com/sindresorhus/get-port
// Definitions by: York Yao <https://github.com/plantain-00/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "get-port" {
var getPort: (options?: { port?: number, host?: string }) => PromiseLike<number>
var getPort: (options?: { port?: number | ReadonlyArray<number>, host?: string }) => PromiseLike<number>
export = getPort;
}
+5
View File
@@ -0,0 +1,5 @@
import * as GulpJsonmin from 'gulp-jsonmin';
GulpJsonmin();
GulpJsonmin({});
GulpJsonmin({ verbose: true });
+18
View File
@@ -0,0 +1,18 @@
// Type definitions for gulp-jsonmin 1.1
// Project: https://github.com/englercj/gulp-jsonmin
// Definitions by: Romain Faust <https://github.com/romain-faust>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { Transform } from 'stream';
declare function jsonmin(options?: jsonmin.Options): Transform;
declare namespace jsonmin {
interface Options {
verbose?: boolean;
}
}
export = jsonmin;
+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",
"gulp-jsonmin-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+66 -1
View File
@@ -474,6 +474,26 @@ declare namespace Highcharts {
skipNullPoints?: boolean;
}
interface AnimationOptions {
/**
* The animation duration in milliseconds.
*/
duration: number;
/**
* The name of an easing function as defined on the Math object.
*/
easing?: string;
/**
* A callback function to exectute when the animation finishes.
*/
complete?: () => void;
/**
* A callback function to execute on each step of each attribute or CSS property that's being animated.
* The first argument contains information about the animation and progress.
*/
step?: () => void;
}
interface AxisTitle {
/**
* Alignment of the title relative to the axis values. Possible values are 'low', 'middle' or 'high'.
@@ -5692,6 +5712,46 @@ declare namespace Highcharts {
y?: number | null;
}
interface TimeOptions {
/**
* A custom Date class for advanced date handling. For example, JDate can be hooked in to handle Jalali dates.
* @default undefined
* @since 4.0.4
*/
Date?: Date;
/**
* A callback to return the time zone offset for a given datetime. It takes the timestamp in terms of milliseconds since
* January 1 1970, and returns the timezone offset in minutes. This provides a hook for drawing time based charts in
* specific time zones using their local DST crossover dates, with the help of external libraries.
* @default undefined
* @since 4.1.0
*/
getTimezoneOffset?: (timestamp: Date) => number;
/**
* Requires moment.js. If the timezone option is specified, it creates a default getTimezoneOffset function that looks
* up the specified timezone in moment.js. If moment.js is not included, this throws a Highcharts error in the console,
* but does not crash the chart.
* @default undefined
* @since 5.0.7
*/
timezone?: string;
/**
* The timezone offset in minutes. Positive values are west, negative values are east of UTC, as in the ECMAScript
* getTimezoneOffset method. Use this to display UTC based data in a predefined time zone.
* @default 0
* @since 3.0.8
*/
timezoneOffset?: number;
/**
* Whether to use UTC time for axis scaling, tickmark placement and time display in Highcharts.dateFormat.
* Advantages of using UTC is that the time displays equally regardless of the user agent's time zone settings.
* Local time can be used when the data is loaded in real time or when correct Daylight Saving Time transitions are required.
* @default undefined
* @since 6.0.5
*/
useUTC?: boolean;
}
interface TitleOptions {
/**
* The horizontal alignment of the title. Can be one of 'left', 'center' and 'right'.
@@ -6118,6 +6178,10 @@ declare namespace Highcharts {
* The chart's subtitle
*/
subtitle?: SubtitleOptions;
/**
* The chart's time options
*/
time?: TimeOptions;
/**
* The chart's main title.
*/
@@ -6487,9 +6551,10 @@ declare namespace Highcharts {
* @param [boolean] redraw Whether to redraw the chart. Defaults to true.
* @param [boolean] oneToOne When true, the series, xAxis and yAxis collections will be updated one to one, and
* items will be either added or removed to match the new updated options. Defaults to false.
* @param [(boolean | AnimationOptions)] animation Whether to apply animation, and optionally animation configuration.
* @since 5.0.0
*/
update(options: Options, redraw?: boolean, oneToOne?: boolean): void;
update(options: Options, redraw?: boolean, oneToOne?: boolean, animation?: boolean | AnimationOptions): void;
/**
* This method is deprecated as of 2.0.1. Updating the chart position after a move operation is no longer necessary.
* @since 1.2.5
+4
View File
@@ -2457,6 +2457,10 @@ function test_ChartObject() {
chart.update(<Highcharts.Options> {});
chart.update(<Highcharts.Options> {}, true);
chart.update(<Highcharts.Options> {}, true, true);
chart.update(<Highcharts.Options> {}, true, true, true);
chart.update(<Highcharts.Options> {}, true, true, {
duration: 3000,
});
}
function test_ElementObject() {
+8
View File
@@ -20,6 +20,14 @@ br.compress(Buffer.from('foo', 'utf8'), onCompress);
br.compress(Buffer.from('foo', 'utf8'), opts, onCompress);
br
.compress(Buffer.from('foobar'))
.then(compressedData => {
br.decompress(compressedData).then(data => {
console.log(data.equals(Buffer.from('foobar')));
});
});
const stream = br.compressStream();
stream.flush();
+4 -1
View File
@@ -1,6 +1,7 @@
// Type definitions for iltorb 2.0
// Type definitions for iltorb 2.3
// Project: https://github.com/MayhemYDG/iltorb
// Definitions by: Arturas Molcanovas <https://github.com/Alorel>
// Francis Gulotta <https://github.com/reconbot>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -25,8 +26,10 @@ export type IltorbCallback = (err: Error | null | undefined, output: Buffer) =>
export function compress(buffer: Buffer, options: BrotliEncodeParams, callback: IltorbCallback): void;
export function compress(buffer: Buffer, callback: IltorbCallback): void;
export function compress(buffer: Buffer, options?: BrotliEncodeParams): Promise<Buffer>;
export function decompress(buffer: Buffer, callback: IltorbCallback): void;
export function decompress(buffer: Buffer): Promise<Buffer>;
export function compressSync(buffer: Buffer, options?: BrotliEncodeParams): Buffer;
export function decompressSync(buffer: Buffer): Buffer;
+14
View File
@@ -0,0 +1,14 @@
// Type definitions for intrinsic-scale 3.0
// Project: https://github.com/bfred-it/intrinsic-scale#readme
// Definitions by: shalomdotnet <https://github.com/shalomdotnet>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export function contain(parentWidth: number, parentHeight: number, childWidth: number, childHeight: number): IntrinsicScale;
export function cover(parentWidth: number, parentHeight: number, childWidth: number, childHeight: number): IntrinsicScale;
export interface IntrinsicScale {
width: number;
height: number;
x: number;
y: number;
}
@@ -0,0 +1,4 @@
import { cover, contain } from "intrinsic-scale";
const intrinsicScale = cover(100, 100, 50, 50);
const { x, y, width, height } = contain(1, 2, 3, 4);
+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",
"intrinsic-scale-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1
View File
@@ -149,4 +149,5 @@ export type Algorithm = 'HS256' | 'HS384' | 'HS512' | 'RS256' |
export interface Header {
alg: Algorithm;
[name: string]: string;
}
+7
View File
@@ -20,6 +20,13 @@ const signature = jws.sign({
secret: 'has a van',
});
// jws.sign with extra header values
const signatureWithHeaderParams = jws.sign({
header: { alg: 'HS256', foo: 'bar' },
payload: 'h. jon benjamin',
secret: 'has a van',
});
// jws.decode
const message = jws.decode('djfakdid');
+5 -2
View File
@@ -20300,16 +20300,19 @@ interface JQueryPromise<T> {
interface JQuery {
data(key: any): any;
kendoDraggable(): JQuery;
kendoDraggable(options: kendo.ui.DraggableOptions): JQuery;
data(key: "kendoDraggable"): kendo.ui.Draggable;
kendoDropTarget(): JQuery;
kendoDropTarget(options: kendo.ui.DropTargetOptions): JQuery;
data(key: "kendoDropTarget"): kendo.ui.DropTarget;
kendoDropTargetArea(): JQuery;
kendoDropTargetArea(options: kendo.ui.DropTargetAreaOptions): JQuery;
data(key: any): any;
data(key: "kendoDropTargetArea"): kendo.ui.DropTargetArea;
kendoAlert(): JQuery;
kendoAlert(options: kendo.ui.AlertOptions): JQuery;
+94
View File
@@ -0,0 +1,94 @@
// Type definitions for koa-redis-cache 3.0
// Project: https://github.com/coderhaoxin/koa-redis-cache
// Definitions by: Dima Mukhin <https://github.com/dimamukhin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import * as Koa from "koa";
import * as Redis from "redis";
type onErrorCallback = (error: Error) => void;
type getPrefixCallback = (ctx: Koa.Context) => string;
declare namespace cache {
interface CacheOptions {
/**
* redis key prefix, default is koa-redis-cache:
* If a function is supplied, its signature should be function(ctx) {} and it should return a string to use as the redis key prefix
*/
prefix?: string | getPrefixCallback;
/**
* redis expire time (second), default is 30 * 60 (30 min)
*/
expire?: number;
/**
* if the passParam exists in the query string, skip the cache
*/
passParam?: string;
/**
* max length of body size (in bytes) to cache.
* if the size of the body exceeds maxLength, the body will not be cached.
* default is: Infinity
*/
maxLength?: number;
/**
* the routes to cache, default is ['(.*)'].
* can be set to an array of routes (string), or an array of RouteOptions
*/
routes?: RouteOptions[] | string[];
/**
* the routes to exclude, default is [].
* example: ['/api/(.*)', '/view/:id']
*/
exclude?: string[];
/**
* callback function for error, default is function() {}
*/
onerror?: onErrorCallback;
/**
* redis options
*/
redis?: RedisOptions;
}
interface RouteOptions {
/**
* the route to cache, example: '/api/(.*)'
*/
route: string;
/**
* expiration time in seconds for cached responses for the route
*/
expire?: number;
}
interface RedisOptions {
/**
* host name of the redis server, default: 'localhost'
*/
host?: string;
/**
* port number of the redis server, default: 6379
*/
port?: number;
/**
* node_redis options
*/
options?: Redis.ClientOpts;
}
}
declare function cache(opts?: cache.CacheOptions): Koa.Middleware;
export = cache;
@@ -0,0 +1,34 @@
import * as Koa from "koa";
import * as cache from 'koa-redis-cache';
const app = new Koa();
const routeOptions: cache.RouteOptions[] = [
{
route: '/api/test',
expire: 60
},
{
route: '/api/users'
}
];
const redisOptions: cache.RedisOptions = {
port: 6379,
host: 'localhost'
};
const options: cache.CacheOptions = {
prefix: (ctx: Koa.Context) => 'koa-redis-cache:',
expire: 30 * 30,
passParam: 'skip',
maxLength: 1024,
routes: routeOptions,
exclude: ['/api/(.*)', '/view/:id'],
onerror: (error: Error) => console.log(error),
redis: redisOptions
};
app.use(cache(options));
app.listen(80);
+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",
"koa-redis-cache-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+3 -8
View File
@@ -6,6 +6,9 @@
/// <reference types="geojson" />
export = mapboxgl;
export as namespace mapboxgl;
declare namespace mapboxgl {
let accessToken: string;
let version: string;
@@ -1286,11 +1289,3 @@ declare namespace mapboxgl {
'hillshade-accent-color-transition'?: Transition;
}
}
declare module 'mapbox-gl' {
export = mapboxgl;
}
declare module 'mapbox-gl/dist/mapbox-gl' {
export = mapboxgl;
}
+4 -3
View File
@@ -1,4 +1,4 @@
// Type definitions for Mongoose 5.2.1
// Type definitions for Mongoose 5.2.2
// Project: http://mongoosejs.com/
// Definitions by: horiuchi <https://github.com/horiuchi>
// sindrenm <https://github.com/sindrenm>
@@ -10,6 +10,7 @@
// jussikinnula <https://github.com/jussikinnula>
// ondratra <https://github.com/ondratra>
// alfirin <https://github.com/alfirin>
// Idan Dardikman <https://github.com/idandrd>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -769,8 +770,8 @@ declare module "mongoose" {
* @param key option name
* @param value if not passed, the current option value is returned
*/
set(key: string): any;
set(key: string, value: any): this;
set<T extends keyof SchemaOptions>(key: T): SchemaOptions[T];
set<T extends keyof SchemaOptions>(key: T, value: SchemaOptions[T]): this;
/**
* Adds static "class" methods to Models compiled from this schema.
+1 -1
View File
@@ -429,7 +429,7 @@ schema.queue('m1', [1, 2, 3]).queue('m2', [[]]);
schema.remove('path');
schema.remove(['path1', 'path2', 'path3']);
schema.requiredPaths(true)[0].toLowerCase();
schema.set('key', 999).set('key');
schema.set('id', true).set('id');
schema.static('static', cb).static({
s1: cb,
s2: cb
+14
View File
@@ -1,9 +1,11 @@
// Type definitions for mosca 2.8
// Project: https://github.com/mcollina/mosca
// Definitions by: Joao Gabriel Gouveia <https://github.com/GabrielGouv>
// Jerray Fu <https://github.com/jerray>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export class Server {
id: string;
opts: any;
modernOpts: any;
clients: any;
@@ -83,3 +85,15 @@ export interface Message {
qos: number;
retain: boolean;
}
export namespace persistence {
interface Persistence {
wire(server: Server): void;
}
type FactoryFunc = (options: { [key: string]: any }) => Persistence;
const Redis: FactoryFunc;
const Mongo: FactoryFunc;
const LevelUp: FactoryFunc;
const Memory: FactoryFunc;
}
+14
View File
@@ -0,0 +1,14 @@
// Type definitions for nanoevents 1.0
// Project: https://github.com/ai/nanoevents#readme
// Definitions by: nju33 <https://github.com/nju33>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
declare function unbind(): void;
declare class NanoEvents<T extends object> {
on<U extends keyof T>(name: U, callBack: (arg: T[U]) => any): typeof unbind;
emit<U extends keyof T>(name: U, value: T[U]): void;
}
export = NanoEvents;
+8
View File
@@ -0,0 +1,8 @@
import NanoEvents = require('nanoevents');
import unbindAll = require('nanoevents/unbind-all');
const emitter = new NanoEvents<{foo: {foo: string}, bar: {bar: string}}>();
const unbind = emitter.on('foo', action => action.foo);
emitter.emit('bar', {bar: 'test'});
unbind();
unbindAll(emitter);
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"nanoevents-tests.ts",
"unbind-all.d.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+5
View File
@@ -0,0 +1,5 @@
import NanoEmitter = require('.');
declare function unbindAll(emitter: NanoEmitter<any>): void;
export = unbindAll;
+13 -2
View File
@@ -1,4 +1,4 @@
// Type definitions for nunjucks 3.0
// Type definitions for nunjucks 3.1
// Project: http://mozilla.github.io/nunjucks/
// Definitions by: Ruben Slabbert <https://github.com/RubenSlabbert>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -95,6 +95,7 @@ export function installJinjaCompat(): void;
export interface ILoader {
async?: boolean;
getSource(name: string): LoaderSource;
getSource(name: string, callback: (err?: any, result?: LoaderSource) => void): void;
extend?(extender: ILoader): ILoader;
}
@@ -128,7 +129,7 @@ export class FileSystemLoader extends Loader implements ILoader {
constructor(searchPaths?: string | string[], opts?: FileSystemLoaderOptions);
}
export class WebLoader implements ILoader {
export class WebLoader extends Loader implements ILoader {
constructor(baseUrl: string, opts?: any);
getSource(name: string): LoaderSource;
}
@@ -137,3 +138,13 @@ export class PrecompiledLoader extends Loader implements ILoader {
init(searchPaths: string[], opts: any): void;
getSource(name: string): LoaderSource;
}
export namespace runtime {
class SafeString {
constructor(val: string);
val: string;
length: number;
valueOf(): string;
toString(): string;
}
}
+2
View File
@@ -52,3 +52,5 @@ class MyLoader extends nunjucks.Loader implements nunjucks.ILoader {
}
env = new nunjucks.Environment(new MyLoader());
new nunjucks.runtime.SafeString("an unsafe string");
+2 -1
View File
@@ -1,6 +1,7 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": false
"interface-name": false,
"no-unnecessary-class": false // to allow SafeString class
}
}
+2 -2
View File
@@ -13728,7 +13728,7 @@ declare namespace Office {
* asyncContext: Any state data that is passed to the asynchronous method.
* @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. The token is provided as a string in the asyncResult.value property.
*/
getCallbackTokenAsync(options: Office.AsyncContextOptions, callback: (result: AsyncResult) => void): void;
getCallbackTokenAsync(options: Office.AsyncContextOptions & { isRest?: boolean }, callback: (result: AsyncResult) => void): void;
/**
* Gets a string that contains a token used to get an attachment or item from an Exchange Server.
*
@@ -60632,4 +60632,4 @@ declare namespace Visio {
////////////////////////////////////////////////////////////////
////////////////////// End PowerPoint APIs /////////////////////
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
+12 -6
View File
@@ -1,7 +1,9 @@
// Type definitions for page v1.5.0
// Project: http://visionmedia.github.io/page.js/
// Definitions by: Alan Norbauer <http://alan.norbauer.com/>
// James Garbutt <https://github.com/43081j>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
declare namespace PageJS {
interface Static {
@@ -64,7 +66,7 @@ declare namespace PageJS {
*
* If you wish to load serve initial content from the server you likely will want to set dispatch to false.
*/
(options: Options): void;
(options: Partial<Options>): void;
/**
* Register page's popstate / click bindings. If you're doing selective binding you'll like want to pass { click: false } to specify this yourself. The following options are available:
*
@@ -125,7 +127,7 @@ declare namespace PageJS {
*
* Identical to page([options]).
*/
start(options: Options): void;
start(options: Partial<Options>): void;
/**
* Register page's popstate / click bindings. If you're doing selective binding you'll like want to pass { click: false } to specify this yourself. The following options are available:
*
@@ -205,19 +207,23 @@ declare namespace PageJS {
/**
* bind to click events (default = true)
*/
click?: boolean;
click: boolean;
/**
* bind to popstate (default = true)
*/
popstate?: boolean;
popstate: boolean;
/**
* perform initial dispatch (default = true)
*/
dispatch?: boolean;
dispatch: boolean;
/**
* add #!before urls (default = false)
*/
hashbang?: boolean;
hashbang: boolean;
/**
* remove URL encoding frfrom path components
*/
decodeURLComponents: boolean;
}
interface Callback {
+11 -1
View File
@@ -13,6 +13,16 @@ page('/contact', contact);
page('/contact/:contactName', contact);
page('/contact/inline/:contactName', ctx => { });
page();
page({
click: false,
popstate: true,
dispatch: false,
hashbang: true,
decodeURLComponents: false
});
page({
hashbang: true
});
var index: PageJS.Callback = function() {
document.querySelector('p')
@@ -82,4 +92,4 @@ var show: PageJS.Callback = function (ctx) {
function notfound() {
document.querySelector('p')
.textContent = 'not found';
}
}
+2 -2
View File
@@ -526,7 +526,7 @@ declare var Media: {
new(src: string, onSuccess: (arg: any) => any, onError: (error: any) => any): Media;
}
interface Notification {
interface PhonegapNotification {
alert(message: string, alertCallback: Function, title?: string, buttonName?: string): void;
confirm(message: string, confirmCallback: Function, title?: string, buttonLabels?: string): void;
confirm(message: string, confirmCallback: Function, title?: string, buttonLabels?: string[]): void;
@@ -614,7 +614,7 @@ interface /*PhoneGapNavigator extends*/ Navigator {
contacts: Contacts;
device: Device;
globalization: Globalization;
notification: Notification;
notification: PhonegapNotification;
splashscreen: Splashscreen;
}
+1 -1
View File
@@ -58,7 +58,7 @@ declare namespace polymer {
setScrollDirection(direction: string, node: HTMLElement): void;
shift(path: string, value: any): any;
splice(path: string, start: number, deleteCount: number, ...items: any[]): any;
toggleAttribute(name: string, bool: boolean, node?: HTMLElement): void;
toggleAttribute(name: string, force?: boolean, node?: HTMLElement): boolean;
toggleClass(name: string, bool: boolean, node?: HTMLElement): void;
transform(transform: string, node?: HTMLElement): void;
translate3d(x: any, y: any, z: any, node?: HTMLElement): void;
+2 -2
View File
@@ -27,8 +27,8 @@ import * as puppeteer from "puppeteer";
// Get the "viewport" of the page, as reported by the page.
const dimensions = await page.evaluate(() => {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
width: document.documentElement!.clientWidth,
height: document.documentElement!.clientHeight,
deviceScaleFactor: window.devicePixelRatio
};
});
+371
View File
@@ -0,0 +1,371 @@
// Type definitions for qiniu-js 2.4
// Project: https://github.com/qiniu/js-sdk#readme
// Definitions by: taoqf <https://github.com/taoqf>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
export as namespace qiniu;
export interface Next {
total: {
loaded: number; // 已上传大小,单位为字节。
total: number; // 本次上传的总量控制信息,单位为字节,注意这里的 total 跟文件大小并不一致。
percent: number; // 当前上传进度,范围:0~100。
};
}
export interface Error {
code: number; // 请求错误状态码,只有在 err.isRequestError 为 true 的时候才有效。可查阅码值对应说明。
message: string; // 错误信息,包含错误码,当后端返回提示信息时也会有相应的错误信息。
isRequestError: true | undefined; // 用于区分是否 xhr 请求错误;当 xhr 请求出现错误并且后端通过 HTTP 状态码返回了错误信息时,该参数为 true;否则为 undefined 。
reqId: string; // xhr请求错误的 X-Reqid。
}
export interface AudioInfo {
bit_rate: string;
channels: number;
codec_name: string;
codec_type: string;
duration: string;
index: number;
nb_frames: string;
r_frame_rate: string;
sample_fmt: string;
sample_rate: string;
start_time: string;
tags: {
creation_time: string;
[key: string]: string;
};
}
export interface AvFormat {
bit_rate: string;
duration: string;
format_long_name: string;
format_name: string;
nb_streams: number;
size: string;
start_time: string;
tags: {
creation_time: string;
[key: string]: string;
};
}
export interface VideoInfo {
bit_rate: string;
codec_name: string;
codec_type: string;
display_aspect_ratio: string;
duration: string;
height: number;
index: number;
nb_frames: string;
pix_fmt: string;
r_frame_rate: string;
sample_aspect_ratio: string;
start_time: string;
tags: {
creation_time: string;
[key: string]: string;
};
width: number;
}
export interface AvAudioInfo {
audio: AudioInfo;
format: AvFormat;
video: VideoInfo;
}
export interface AvImageInfo {
format: string;
width: number;
height: number;
colorModel: string;
}
export interface CompletedResult {
avinfo?: AvAudioInfo;
imageInfo?: AvImageInfo;
key: string;
name: string;
size: number;
persistentid: string;
sec: string;
ext: string;
bucket: string;
}
export interface Observer {
next(res: Next): void;
error(err: Error | string): void;
complete(res: CompletedResult): void;
}
export interface Subscription {
unsubscribe(): void;
}
export interface Observable {
subscribe(options: Observer): Subscription;
/**
* 订阅
*
* @param next 接收上传进度信息
* @param error 上传错误后触发;自动重试本身并不会触发该错误,而当重试次数到达上限后则可以触发。当不是 xhr 请求错误时,会把当前错误产生原因直接抛出,诸如 JSON 解析异常等;当产生 xhr 请求错误时,参数 err 为一个包含 code、message、isRequestError 三个属性的 object
* @param complete 接收上传完成后的后端返回信息,具体返回结构取决于后端sdk的配置,可参考[上传策略](https://developer.qiniu.com/kodo/manual/1206/put-policy)。
* @returns
*/
subscribe(next: (obj: Next) => void, error?: (err: Error | string) => void, complete?: (obj: CompletedResult) => void): Subscription;
}
export interface Extra {
fname: string; // 文件原文件名
params: any; // 用来放置自定义变量
mimeType: string[] | null; // 用来限制上传文件类型,为 null 时表示不对文件类型限制;限制类型放到数组里: ["image/png", "image/jpeg", "image/gif"]
}
export interface Config {
useCdnDomain: boolean;
region: Region | string;
}
/**
* 上传文件
* @param file Blob 对象,上传的文件
* @param key 文件资源名
* @param token 上传验证信息,前端通过接口请求后端获得
* @param putExtra
* @param config
*/
export function upload(file: Blob, key: string | null | undefined, token: string, putExtra: Partial<Extra>, config: Partial<Config>): Observable;
/**
* 返回创建文件的 url;当分片上传时,我们需要把分片返回的 ctx 信息拼接后通过该 url 上传给七牛以创建文件。
*
* @param url 上传域名,可以通过qiniu.getUploadUrl()获得
* @param size 文件大小
* @param key 文件资源名
* @param putExtra
* @returns
*/
export function createMkFileUrl(url: string, size: number, key: string, putExtra: Partial<Extra>): string;
export enum Region {
z0, // 代表华东区域
z1, // 代表华北区域
z2, // 代表华南区域
na0, // 代表北美区域
as0 // 代表新加坡区域
}
export namespace region {
const z0: Region;
const z1: Region;
const z2: Region;
const na0: Region;
const as0: Region;
}
/**
* 接收参数为 config 对象,返回根据 config 里所配置信息的上传域名
*
* @param config
* @param token
* @returns
*/
export function getUploadUrl(config: Partial<Config>, token: string): Promise<string>;
export interface Headers {
[key: string]: string;
}
/**
* 返回 object,包含用来获得分片上传设置的头信息,参数为 token 字符串;当分片上传时,请求需要带该函数返回的头信息
*
* @param token
* @returns
*/
export function getHeadersForChunkUpload(token: string): Headers;
/**
* 返回 object,包含用来获得文件创建的头信息,参数为 token 字符串;当分片上传完需要把 ctx 信息传给七牛用来创建文件时,请求需要带该函数返回的头信息
*
* @param token
* @returns
*/
export function getHeadersForMkFile(token: string): Headers;
/**
* 返回[[k, v],...]格式的数组,k 为自定义变量 key 名,v 为自定义变量值,用来提取 putExtra.params 包含的自定义变量
*
* @param params
* @returns
*/
export function filterParams(params: any): Array<[string, any]>;
export interface CompressOptions {
quality: number; // 图片压缩质量,在图片格式为 image/jpeg 或 image/webp 的情况下生效,其他格式不会生效,可以从 0 到 1 的区间内选择图片的质量。默认值 0.92
maxWidh: number; // 压缩图片的最大宽度值
maxHeight: number; // 压缩图片的最大高度值 (注意:当 maxWidth 和 maxHeight 都不设置时,则采用原图尺寸大小)
noCompressIfLarger: boolean; // 为 true 时如果发现压缩后图片大小比原来还大,则返回源图片(即输出的 dist 直接返回了输入的 file);默认 false,即保证图片尺寸符合要求,但不保证压缩后的图片体积一定变小
}
/**
* 上传前图片压缩
*
* @param file 要压缩的源图片,为 blob 对象,支持 image/png、image/jpeg、image/bmp、image/webp 这几种图片类型
* @param options
* @returns
*/
export function compressImage(file: Blob, options: Partial<CompressOptions>): Promise<{
dist: Blob; // 压缩后输出的 blob 对象,或原始的 file,具体看下面的 options 配置
width: number; // 压缩后的图片宽度
height: number; // 压缩后的图片高度
}>;
export interface WaterMarkOptions1 {
mode: 1; // 图片水印
image: string; // 图片水印的Url,mode = 1 时 **必需**
dissolve: number; // 透明度,取值范围1-100,非必需,下同
gravity: 'NorthWest' | 'North' | 'NorthEast' | 'West' | 'Center' | 'East' | 'SouthWest' | 'South' | 'SouthEast'; // 水印位置
dx: number; // 横轴边距,单位:像素(px)
dy: number; // 纵轴边距,单位:像素(px)
}
export interface WaterMarkOptions2 {
mode: 2; // 文字水印
text: string; // 水印文字,mode = 2 时 **必需**
dissolve: number; // 透明度,取值范围1-100,非必需,下同
gravity: 'NorthWest' | 'North' | 'NorthEast' | 'West' | 'Center' | 'East' | 'SouthWest' | 'South' | 'SouthEast'; // 水印位置
fontsize: number; // 字体大小,单位: 缇
font: string; // 水印文字字体
dx: number; // 横轴边距,单位:像素(px)
dy: number; // 纵轴边距,单位:像素(px)
fill: string; // 水印文字颜色,RGB格式,可以是颜色名称
}
/**
* 水印
*
* @param options 包含的具体水印参数解释见水印([watermark](https://developer.qiniu.com/dora/manual/1316/image-watermarking-processing-watermark))
* @param key 文件资源名
* @param domain 为七牛空间(bucket)对应的域名,选择某个空间后,可通过"空间设置->基本设置->域名设置"查看获取,前端可以通过接口请求后端得到
* @returns 返回添加水印后的图片地址,可以赋值给 html 的 img 元素的 src 属性, 若未指定key,可以通过以下方式获得完整的 imgLink
* `imgLink = '<domain>/<key>?' + imgLink`
* <domain> 为七牛空间(bucket)对应的域名,选择某个空间后,可通过"空间设置->基本设置->域名设置"查看获取
*/
export function watermark(options: WaterMarkOptions1 | WaterMarkOptions2, key?: string, domain?: string): string;
export interface ImageView2Options {
mode: 0 | 1 | 2 | 3 | 4 | 5; // 缩略模式,共6种[0-5]
w: number; // 具体含义由缩略模式决定
h: number; // 具体含义由缩略模式决定
q: number; // 新图的图像质量,取值范围:1-100
format: 'jpg' | 'gif' | 'png' | 'webp' | string; // 新图的输出格式,取值范围:jpg,gif,png,webp等
}
/**
* 缩略
*
* @param options 具体缩略参数解释见[图片基本处理(imageView2)](https://developer.qiniu.com/dora/manual/1279/basic-processing-images-imageview2)
* @param key
* @param domain
* @returns 返回处理后的图片url
*/
export function imageView2(options: Partial<ImageView2Options>, key: string, domain: string): string;
export interface ImageMogr2Options {
'auto-orient': boolean; // 布尔值,是否根据原图EXIF信息自动旋正,便于后续处理,建议放在首位。
strip: boolean; // 布尔值,是否去除图片中的元信息
thumbnail: string; // 缩放操作参数
crop: string; // 裁剪操作参数
gravity: string; // 裁剪锚点参数
quality: number; // 图片质量,取值范围1-100
rotate: number; // 旋转角度,取值范围1-360,缺省为不旋转。
format: string; // 新图的输出格式,取值范围:jpg,gif,png,webp等
blur: string; // 高斯模糊参数
}
/**
* 返回处理后的图片url
*
* @param optoins 具体高级图像处理参数解释见[图像高级处理(imageMogr2)](https://developer.qiniu.com/dora/manual/1270/the-advanced-treatment-of-images-imagemogr2)
* @param key
* @param domain
* @returns 返回处理后的图片url
*/
export function imageMogr2(optoins: Partial<ImageMogr2Options>, key: string, domain: string): string;
export interface ImageInfo {
size: number; // 文件大小,单位:Bytes
format: 'png' | 'jpeg' | 'gif' | 'bmp'; // 图片类型,如png、jpeg、gif、bmp等。
width: number; // 图片宽度,单位:像素(px) 。
height: number; // 图片高度,单位:像素(px) 。
colorModel: string; // 彩色空间,如palette16、ycbcr等。
frameNumber: number; // 帧数,gif 图片会返回此项。
}
/**
*
* 图片基本信息
* 具体 imageInfo 解释见[图片基本信息(imageInfo)](https://developer.qiniu.com/dora/manual/1269/pictures-basic-information-imageinfo)
*
* @param key
* @param domain
* @returns
*/
export function imageInfo(key: string, domain: string): Promise<ImageInfo>;
export interface ExtendedInfo {
code: number;
error: string;
[key: string]: {
type: number;
val: string;
} | number | string;
}
export interface ExtentInfoValue {
type: number;
val: string;
}
export interface ExtentInfo {
[key: string]: ExtentInfoValue;
DateTime: ExtentInfoValue;
ExposureBiasValue: ExtentInfoValue;
ExposureTime: ExtentInfoValue;
Model: ExtentInfoValue;
ISOSpeedRatings: ExtentInfoValue;
ResolutionUnit: ExtentInfoValue;
}
/**
* EXIF 信息
* 具体 exif 解释见[图片 EXIF 信息(exif)](https://developer.qiniu.com/dora/manual/1260/photo-exif-information-exif)
* @param key
* @param domain
* @returns
*/
export function exif(key: string, domain: string): Promise<ExtentInfo>;
export interface WaterMarkFopOptions1 extends WaterMarkOptions1 {
fop: 'watermark';
}
export interface WaterMarkFopOptions2 extends WaterMarkOptions2 {
fop: 'watermark';
}
export interface ImageView2FopOptions extends ImageView2Options {
fop: 'imageView2';
}
export interface ImageMogr2FopOptions extends ImageMogr2Options {
fop: 'imageMogr2';
}
export function pipeline(fos: Array<(WaterMarkFopOptions1 | WaterMarkFopOptions2 | ImageView2FopOptions | ImageMogr2FopOptions)>, key: string, domain: string): string;
+50
View File
@@ -0,0 +1,50 @@
import { compressImage, region, upload } from 'qiniu-js';
const file: Blob = null as any;
const config = {
useCdnDomain: true,
region: region.z2
};
const key = 'key';
const token = 'token';
const putExtra = {
fname: "",
params: {},
mimeType: [] || null
};
(() => {
const observable = upload(file, key, token, putExtra, config);
const subscription = observable.subscribe({
next(res) { },
complete(res) { },
error(err) { }
}); // 上传开始
subscription.unsubscribe(); // 上传取消
})();
(() => {
const observable = upload(file, key, token, putExtra, config);
const subscription = observable.subscribe((res) => { }, (err) => { }, (res) => { }); // 这样传参形式也可以
})();
(async () => {
// 图片上传前压缩:
const options = {
quality: 0.92,
noCompressIfLarger: true
// maxWidth: 1000,
// maxHeight: 618
};
const data = await compressImage(file, options);
const observable = upload(data.dist, key, token, putExtra, config);
const subscription = observable.subscribe({
next(res) { },
complete(res) { },
error(err) { }
}); // 上传开始
})();
@@ -0,0 +1,48 @@
const file: Blob = null as any;
const config = {
useCdnDomain: true,
region: qiniu.region.z2
};
const key = 'key';
const token = 'token';
const putExtra = {
fname: "",
params: {},
mimeType: [] || null
};
(() => {
const observable = qiniu.upload(file, key, token, putExtra, config);
const subscription = observable.subscribe({
next(res) { },
complete(res) { },
error(err) { }
}); // 上传开始
subscription.unsubscribe(); // 上传取消
})();
(() => {
const observable = qiniu.upload(file, key, token, putExtra, config);
const subscription = observable.subscribe((res) => { }, (err) => { }, (res) => { }); // 这样传参形式也可以
})();
(async () => {
// 图片上传前压缩:
const options = {
quality: 0.92,
noCompressIfLarger: true
// maxWidth: 1000,
// maxHeight: 618
};
const data = await qiniu.compressImage(file, options);
const observable = qiniu.upload(data.dist, key, token, putExtra, config);
const subscription = observable.subscribe({
next(res) { },
complete(res) { },
error(err) { }
}); // 上传开始
})();
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "commonjs",
"strictFunctionTypes": true,
"lib": [
"dom",
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"qiniu-js-tests.ts",
"test/qiniu-js-global-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+63 -39
View File
@@ -1,49 +1,73 @@
// Type definitions for react-input-mask 1.2
// Type definitions for react-input-mask 2.0
// Project: https://github.com/sanniassin/react-input-mask
// Definitions by: Alexandre Paré <https://github.com/apare>
// Dima Danylyuk <https://github.com/dima7a14>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
// TypeScript Version: 2.9
import * as React from "react";
import * as React from 'react';
declare namespace ReactInputMask {
interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
/**
* Mask string. Format characters are:
* * `9`: `0-9`
* * `a`: `A-Z, a-z`
* * `\*`: `A-Z, a-z, 0-9`
*
* Any character can be escaped with backslash, which usually will appear as double backslash in JS strings.
* For example, German phone mask with unremoveable prefix +49 will look like `mask="+4\\9 99 999 99"` or `mask={"+4\\\\9 99 999 99"}`
*/
mask: string;
/**
* Character to cover unfilled editable parts of mask. Default character is "_". If set to null, unfilled parts will be empty, like in ordinary input.
*/
maskChar?: string | null;
/**
* Defines format characters with characters as keys and corresponding RegExp string as values. Default ones:
* ```
* {
* "9": "[0-9]",
* "a": "[A-Za-z]",
* "*": "[A-Za-z0-9]"
* }```
*/
formatChars?: { [key: string]: string };
/**
* Show mask even in empty input without focus.
*/
alwaysShowMask?: boolean;
/**
* Use inputRef instead of ref if you need input node to manage focus, selection, etc.
*/
inputRef?: React.Ref<HTMLInputElement>;
}
export interface InputState {
value: string;
selection: Selection;
}
declare class ReactInputMask extends React.Component<ReactInputMask.Props> {
export interface MaskOptions {
mask: string;
maskChar: string;
alwaysShowMask: boolean;
formatChars: Record<string, string>;
permanents: number[];
}
interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
/**
* Mask string. Format characters are:
* * `9`: `0-9`
* * `a`: `A-Z, a-z`
* * `\*`: `A-Z, a-z, 0-9`
*
* Any character can be escaped with backslash, which usually will appear as double backslash in JS strings.
* For example, German phone mask with unremoveable prefix +49 will look like `mask="+4\\9 99 999 99"` or `mask={"+4\\\\9 99 999 99"}`
*/
mask: string;
/**
* Character to cover unfilled editable parts of mask. Default character is "_". If set to null, unfilled parts will be empty, like in ordinary input.
*/
maskChar?: string | null;
/**
* Defines format characters with characters as keys and corresponding RegExp string as values. Default ones:
* ```
* {
* "9": "[0-9]",
* "a": "[A-Za-z]",
* "*": "[A-Za-z0-9]"
* }```
*/
formatChars?: { [key: string]: string };
/**
* Show mask even in empty input without focus.
*/
alwaysShowMask?: boolean;
/**
* Use inputRef instead of ref if you need input node to manage focus, selection, etc.
*/
inputRef?: React.Ref<HTMLInputElement>;
/**
* In case you need to implement more complex masking behavior, you can provide
* beforeMaskedValueChange function to change masked value and cursor position
* before it will be applied to the input.
*/
beforeMaskedValueChange?(
newState: InputState,
oldState: InputState,
userInput: string,
maskOptions: MaskOptions,
): InputState;
}
export class ReactInputMask extends React.Component<Props> {
}
export default ReactInputMask;
@@ -4,10 +4,10 @@ import * as React from 'react';
let ref: HTMLInputElement | null = null;
<div>
<ReactInputMask mask="+4\9 99 999 99" maskChar={null} />
<ReactInputMask mask="+7 (999) 999-99-99" />
<ReactInputMask mask="99-99-9999" defaultValue= "13-00-2017" />
<ReactInputMask mask="99/99/9999" placeholder= "Enter birthdate" />
<ReactInputMask mask="+7 (999) 999-99-99" />
<ReactInputMask mask="+7 (999) 999-99-99" inputRef={(node) => ref = node} />
<ReactInputMask mask="+4\9 99 999 99" maskChar={null} />
<ReactInputMask mask="+7 (999) 999-99-99" />
<ReactInputMask mask="99-99-9999" defaultValue="13-00-2017" />
<ReactInputMask mask="99/99/9999" placeholder="Enter birthdate" />
<ReactInputMask mask="+7 (999) 999-99-99" />
<ReactInputMask mask="+7 (999) 999-99-99" inputRef={(node) => ref = node} />
</div>;
+3 -1
View File
@@ -1 +1,3 @@
{ "extends": "dtslint/dt.json" }
{
"extends": "dtslint/dt.json"
}
+49
View File
@@ -0,0 +1,49 @@
// Type definitions for react-input-mask 1.2
// Project: https://github.com/sanniassin/react-input-mask
// Definitions by: Alexandre Paré <https://github.com/apare>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import * as React from "react";
declare namespace ReactInputMask {
interface Props extends React.InputHTMLAttributes<HTMLInputElement> {
/**
* Mask string. Format characters are:
* * `9`: `0-9`
* * `a`: `A-Z, a-z`
* * `\*`: `A-Z, a-z, 0-9`
*
* Any character can be escaped with backslash, which usually will appear as double backslash in JS strings.
* For example, German phone mask with unremoveable prefix +49 will look like `mask="+4\\9 99 999 99"` or `mask={"+4\\\\9 99 999 99"}`
*/
mask: string;
/**
* Character to cover unfilled editable parts of mask. Default character is "_". If set to null, unfilled parts will be empty, like in ordinary input.
*/
maskChar?: string | null;
/**
* Defines format characters with characters as keys and corresponding RegExp string as values. Default ones:
* ```
* {
* "9": "[0-9]",
* "a": "[A-Za-z]",
* "*": "[A-Za-z0-9]"
* }```
*/
formatChars?: { [key: string]: string };
/**
* Show mask even in empty input without focus.
*/
alwaysShowMask?: boolean;
/**
* Use inputRef instead of ref if you need input node to manage focus, selection, etc.
*/
inputRef?: React.Ref<HTMLInputElement>;
}
}
declare class ReactInputMask extends React.Component<ReactInputMask.Props> {
}
export default ReactInputMask;
@@ -0,0 +1,13 @@
import ReactInputMask from 'react-input-mask';
import * as React from 'react';
let ref: HTMLInputElement | null = null;
<div>
<ReactInputMask mask="+4\9 99 999 99" maskChar={null} />
<ReactInputMask mask="+7 (999) 999-99-99" />
<ReactInputMask mask="99-99-9999" defaultValue= "13-00-2017" />
<ReactInputMask mask="99/99/9999" placeholder= "Enter birthdate" />
<ReactInputMask mask="+7 (999) 999-99-99" />
<ReactInputMask mask="+7 (999) 999-99-99" inputRef={(node) => ref = node} />
</div>;
+28
View File
@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"jsx": "react",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"paths": {
"react-input-mask": ["react-input-mask/v1"]
}
},
"files": [
"index.d.ts",
"react-input-mask-tests.tsx"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+332 -283
View File
@@ -1,170 +1,92 @@
// Type definitions for react-native-calendars 1.20
// Project: https://github.com/wix/react-native-calendars#readme
// Definitions by: Tyler Zhang <https://github.com/Tyler-Zhang>
// David Noreña <https://github.com/DavidNorena>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import * as React from 'react';
import { ViewProps, StyleProp } from 'react-native';
import { StyleProp, TextStyle, ViewStyle } from 'react-native';
export import LocaleConfig = require('xdate');
export interface DateObject {
year: number;
month: number;
day: number;
timestamp: number;
dateString: string;
month: number;
timestamp: number;
year: number;
}
export interface CalendarTheme {
backgroundColor?: string;
calendarBackground?: string;
textSectionTitleColor?: string;
selectedDayBackgroundColor?: string;
selectedDayTextColor?: string;
todayTextColor?: string;
dayTextColor?: string;
textDisabledColor?: string;
dotColor?: string;
selectedDotColor?: string;
arrowColor?: string;
monthTextColor?: string;
textDayFontFamily?: string;
textMonthFontFamily?: string;
textDayHeaderFontFamily?: string;
textMonthFontWeight?: string;
textDayFontSize?: number;
textMonthFontSize?: number;
textDayHeaderFontSize?: number;
}
export interface DayComponentProps {
state: '' | 'selected' | 'disabled' | 'today';
theme: CalendarTheme;
onPress: () => any;
onLongPress: () => any;
date: DateObject;
marking: false | Marking[];
}
export interface CalendarBaseProps {
/**
* Styles for the view
*/
style?: StyleProp<ViewProps>;
/**
* Specify theme properties to override specific styles for calendar parts. Default = {}
*/
theme?: CalendarTheme;
/**
* Initially visible month. Default = Date()
*/
current?: Date | string;
/**
* Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined
*/
minDate?: Date | string;
/**
* Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined
*/
maxDate?: Date | string;
/**
* Handler which gets executed on day press. Default = undefined
*/
onDayPress?: (day: number) => void;
/**
* Handler which gets executed on day long press. Default = undefined
*/
onDayLongPress?: (day: number) => void;
/**
* Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting
*/
monthFormat?: string;
/**
* Handler which gets executed when visible month changes in calendar. Default = undefined
*/
onMonthChange?: (month: number) => void;
/**
* Hide month navigation arrows. Default = false
*/
hideArrows?: boolean;
/**
* Replace default arrows with custom ones (direction can be 'left' or 'right')
*/
renderArrow?: (direction: 'left' | 'right') => React.ReactNode;
/**
* Do not show days of other months in month page. Default = false
*/
hideExtraDays?: boolean;
/**
* If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out
* day from another month that is visible in calendar page. Default = false
*/
disableMonthChange?: boolean;
/**
* If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday.
*/
firstDay?: number;
/**
* Hide day names. Default = false
*/
hideDayNames?: boolean;
/**
* Show week numbers to the left. Default = false
*/
showWeekNumbers?: boolean;
/**
* Handler which gets executed when press arrow icon left. It receive a callback can go back month
*/
onPressArrowLeft?: (month: number) => void;
/**
* Handler which gets executed when press arrow icon left. It receive a callback can go next month
*/
onPressArrowRight?: (month: number) => void;
/**
* Custom day renderer
*/
dayComponent?: React.Component<DayComponentProps> | React.SFC<DayComponentProps>;
}
export interface DotForMultiDot {
export interface CalendarDot {
key: string;
color: string;
selectedDotColor?: string;
}
export interface MultiDotMarking {
dots: DotForMultiDot[];
selected?: boolean;
selectedColor?: string;
disabled?: boolean;
export interface CalendarTheme {
arrowColor?: string;
backgroundColor?: string;
calendarBackground?: string;
dayTextColor?: string;
dotColor?: string;
monthTextColor?: string;
selectedDayBackgroundColor?: string;
selectedDayTextColor?: string;
selectedDotColor?: string;
textDayFontFamily?: string;
textDayFontSize?: number;
textDayHeaderFontFamily?: string;
textDayHeaderFontSize?: number;
textDisabledColor?: string;
textMonthFontFamily?: string;
textMonthFontWeight?: string;
textMonthFontSize?: number;
textSectionTitleColor?: string;
todayTextColor?: string;
}
export type DateCallbackHandler = (date: DateObject) => void;
export type TCalendarDate = Date | DateObject | number | string | XDate;
export interface MarkedDateCustomStyles {
container: StyleProp<ViewStyle>;
text: StyleProp<TextStyle>;
}
export interface CalendarDot {
key: string;
color: string;
selectedDotColor?: string;
}
export interface CustomMarking {
customStyles: MarkedDateCustomStyles;
}
export interface DotMarking {
selected?: boolean;
marked?: boolean;
selectedColor?: string;
dotColor?: string;
activeOpacity?: number;
disabled?: boolean;
disableTouchEvent?: boolean;
dotColor?: string;
marked?: boolean;
selected?: boolean;
selectedColor?: string;
}
export interface MultiDotMarking {
disabled?: boolean;
dots: CalendarDot[];
selected?: boolean;
selectedColor?: string;
}
export interface MultiPeriodMarking {
periods: Array<{
startingDay?: boolean;
endingDay?: boolean;
color?: string;
}>;
}
export interface PeriodMarking {
@@ -176,29 +98,15 @@ export interface PeriodMarking {
disabled?: boolean;
}
export interface MultiPeriodMarking {
periods: Array<{
startingDay?: boolean;
endingDay?: boolean;
color?: string;
}>;
}
export interface CustomMarking {
customStyles: any;
}
export type Marking =
MultiDotMarking |
DotMarking |
PeriodMarking |
MultiPeriodMarking |
CustomMarking;
CustomMarking | DotMarking |
MultiDotMarking | MultiPeriodMarking |
PeriodMarking;
export interface MultiDotMarkingProps {
markingType: 'multi-dot';
export interface CustomMarkingProps {
markingType: 'custom';
markedDates: {
[date: string]: MultiDotMarking;
[date: string]: CustomMarking;
};
}
@@ -209,17 +117,10 @@ export interface DotMarkingProps {
};
}
export interface PeriodMarkingProps {
markingType: 'period';
export interface MultiDotMarkingProps {
markingType: 'multi-dot';
markedDates: {
[date: string]: PeriodMarking;
};
}
export interface CustomMarkingProps {
markingType: 'custom';
markedDates: {
[date: string]: CustomMarking;
[date: string]: MultiDotMarking;
};
}
@@ -234,6 +135,13 @@ export interface MultiPeriodMarkingProps {
};
}
export interface PeriodMarkingProps {
markingType: 'period';
markedDates: {
[date: string]: PeriodMarking;
};
}
export type CalendarMarkingProps =
MultiDotMarkingProps |
DotMarkingProps |
@@ -242,61 +150,217 @@ export type CalendarMarkingProps =
CustomMarkingProps |
{};
export class Calendar extends React.Component<CalendarMarkingProps & CalendarBaseProps> {}
export interface DayComponentProps {
date: DateObject;
marking: false | Marking[];
onPress: () => any;
onLongPress: () => any;
state: '' | 'selected' | 'disabled' | 'today';
theme: CalendarTheme;
}
export interface CalendarBaseProps {
/**
* Initially visible month. Default = Date()
*/
current?: TCalendarDate;
/**
* Provide custom day rendering component.
*/
dayComponent?: React.Component<DayComponentProps> | React.SFC<DayComponentProps>;
/**
* Disable days by default. Default = false
*/
disabledByDefault?: boolean;
/**
* If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out
* day from another month that is visible in calendar page. Default = false
*/
disableMonthChange?: boolean;
/**
* Display loading indicator. Default = false
*/
displayLoadingIndicator?: boolean;
/**
* If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday.
*/
firstDay?: number;
/**
* Hide month navigation arrows. Default = false
*/
hideArrows?: boolean;
/**
* Hide day names. Default = false
*/
hideDayNames?: boolean;
/**
* Do not show days of other months in month page. Default = false
*/
hideExtraDays?: boolean;
/**
* Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined
*/
maxDate?: TCalendarDate;
/**
* Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined
*/
minDate?: TCalendarDate;
/**
* Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting
*/
monthFormat?: string;
/**
* Handler which gets executed on day press. Default = undefined
*/
onDayPress?: DateCallbackHandler;
/**
* Handler which gets executed on day long press. Default = undefined
*/
onDayLongPress?: DateCallbackHandler;
/**
* Handler which gets executed when press arrow icon left. It receive a callback can go back month
*/
onPressArrowLeft?: (substractMonth: () => void) => void;
/**
* Handler which gets executed when press arrow icon left. It receive a callback can go next month
*/
onPressArrowRight?: (addMonth: () => void) => void;
/**
* Handler which gets executed when visible month changes in calendar. Default = undefined
*/
onMonthChange?: DateCallbackHandler;
export interface CalendarListBaseProps extends CalendarBaseProps {
/**
* Callback which gets executed when visible months change in scroll view. Default = undefined
*/
onVisibleMonthsChange?: (months: number) => void;
onVisibleMonthsChange?: (months: DateObject[]) => void;
/**
* Max amount of months allowed to scroll to the past. Default = 50
* Replace default arrows with custom ones (direction can be 'left' or 'right')
*/
pastScrollRange?: number;
renderArrow?: (direction: 'left' | 'right') => React.ReactNode;
/**
* Show week numbers to the left. Default = false
*/
showWeekNumbers?: boolean;
/**
* Calendar container style.
*/
style?: StyleProp<ViewStyle>;
/**
* Specify theme properties to override specific styles for calendar parts. Default = {}
*/
theme?: CalendarTheme;
}
export class Calendar extends React.Component<CalendarMarkingProps & CalendarBaseProps> { }
export interface CalendarListBaseProps extends CalendarBaseProps {
/**
* Set custom calendar heigth.
*/
calendarHeight?: number;
/**
* Set custom calendar width.
*/
calendarWidth?: number;
/**
* Max amount of months allowed to scroll to the future. Default = 50
*/
futureScrollRange?: number;
/**
* Enable horizontal scrolling, default = false
*/
horizontal?: boolean;
/**
* Enable paging on horizontal, default = false
*/
pagingEnabled?: boolean;
/**
* Max amount of months allowed to scroll to the past. Default = 50
*/
pastScrollRange?: number;
/**
* Enable or disable scrolling of calendar list
*/
scrollEnabled?: boolean;
/**
* When true, the calendar list scrolls to top when the status bar is tapped. Default = true
*/
scrollsToTop?: boolean;
/**
* Enable or disable vertical scroll indicator. Default = false
*/
showScrollIndicator?: boolean;
/**
* Enable horizontal scrolling, default = false
*/
horizontal?: boolean;
/**
* Enable paging on horizontal, default = false
*/
pagingEnabled?: boolean;
/**
* Set custom calendarWidth.
*/
calendarWidth?: boolean;
}
export class CalendarList extends React.Component<CalendarListBaseProps & CalendarMarkingProps> {}
export class CalendarList extends React.Component<CalendarListBaseProps> { }
export interface AgendaProps<T> {
export interface AgendaThemeStyle extends CalendarTheme {
agendaDayNumColor?: string;
agendaDayTextColor?: string;
agendaKnobColor?: string;
agendaTodayColor?: string;
}
export interface AgendaItemsMap<TItem> {
[date: string]: TItem[];
}
export interface AgendaProps<TItem> {
/**
* the list of items that have to be displayed in agenda. If you want to render item as empty date
* the value of date key kas to be an empty array []. If there exists no value for date key it is
* considered that the date in question is not yet loaded
* Display loading indicator. Default = false
*/
items: {
[key: string]: T[];
};
displayLoadingIndicator?: boolean;
/**
* If firstDay = 1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday.
*/
firstDay?: number;
/**
* Max amount of months allowed to scroll to the future. Default = 50
*/
futureScrollRange?: number;
/**
* Hide knob button. Default = false
*/
hideKnob?: boolean;
/**
* The list of items that have to be displayed in agenda. If you want to render item as empty date
* the value of date key kas to be an empty array []. If there exists no value for date key it is
* considered that the date in question is not yet loaded
*/
items?: AgendaItemsMap<TItem>;
/**
* callback that gets called when items for a certain month should be loaded (month became visible)
@@ -304,115 +368,100 @@ export interface AgendaProps<T> {
loadItemsForMonth?: (date: DateObject) => void;
/**
* callback that fires when the calendar is opened or closed
* Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined
*/
onCalendarToggled?: (calendarOpened: boolean) => void;
/**
* callback that gets called on day press
*/
onDayPress?: (day: number) => void;
/**
* callback that gets called when day changes while scrolling agenda list
*/
onDayChange?: (day: number) => void;
/**
* initially selected day
*/
selected?: Date | string;
maxDate?: TCalendarDate;
/**
* Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined
*/
minDate?: Date | string;
minDate?: TCalendarDate;
/**
* Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined
* Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting
*/
maxDate?: Date | string;
monthFormat?: string;
/**
* Max amount of months allowed to scroll to the past. Default = 50
* Handler which gets executed on day press. Default = undefined
*/
onDayPress?: DateCallbackHandler;
/**
* Handler which gets executed when the calendar is opened or closed. Default = undefined
*/
onCalendarToggled?: (calendarOpened: boolean) => void;
/**
* Handler that gets called when day changes while scrolling agenda list. Default = undefined
*/
onDayChange?: DateCallbackHandler;
/**
* If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality.
* Make sure to also set the refreshing prop correctly. Default = undefined
*/
onRefresh?: () => void;
/**
* Max amount of months allowed to scroll to the past. Default = 50
*/
pastScrollRange?: number;
/**
* Max amount of months allowed to scroll to the future. Default = 50
*/
futureScrollRange?: number;
/**
* specify how each item should be rendered in agenda
*/
renderItem: (item: T, firstItemInDay?: T) => React.ReactNode;
/**
* specify how each date should be rendered. day can be undefined if the item is not first in that day.
*/
renderDay?: (day: DateObject | undefined, item: T) => React.ReactNode;
/**
* specify how empty date content with no items should be rendered
*/
renderEmptyDate?: () => React.ReactNode;
/**
* specify how agenda knob should look like
*/
renderKnob?: () => React.ReactNode;
/**
* specify what should be rendered instead of ActivityIndicator
*/
renderEmptyData?: () => React.ReactNode;
/**
* specify your item comparison function for increased performance
*/
rowHasChanged?: (r1: any, r2: any) => boolean;
/**
* Hide knob button. Default = false
*/
hideKnob?: boolean;
/**
* A RefreshControl component, used to provide pull-to-refresh funtionality for the ScrollView
* A RefreshControl component, used to provide pull-to-refresh funtionality for the ScrollView.
*/
refreshControl?: React.ReactNode;
/**
* If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality.
* Make sure to also set the refreshing prop correctly.
*/
onRefresh?: () => any;
/**
* Set this true while waiting for new data from a refresh
* Set this true while waiting for new data from a refresh.
*/
refreshing?: boolean;
/**
* Display loading indicator. Default = false
* Specify how each day should be rendered.
* Date can be undefined if the item has not property date.
*/
displayLoadingIndicator?: boolean;
renderDay?: (date: DateObject | undefined, item: TItem) => React.ReactNode;
/**
* agenda theme
* Specify what should be rendered instead of ActivityIndicator
*/
theme?: {
agendaDayTextColor?: string;
agendaDayNumColor?: string;
agendaTodayColor?: string;
agendaKnobColor?: string;
} & CalendarTheme;
renderEmptyData?: () => React.ReactNode;
/**
* agenda container style
* Specify how empty date content with no items should be rendered.
*/
style?: StyleProp<ViewProps>;
renderEmptyDate: () => React.ReactNode;
/**
* Specify how each item should be rendered in agenda.
*/
renderItem: (item: TItem, firstDayInDay: boolean) => React.ReactNode;
/**
* Specify how agenda knob should look like.
*/
renderKnob?: () => React.ReactNode;
/**
* specify your item comparison function for increased performance
*/
rowHasChanged: (r1: TItem, r2: TItem) => boolean;
/**
* Initially visible month. Default = Date()
*/
selected?: TCalendarDate;
/**
* Agenda container style.
*/
style?: StyleProp<ViewStyle>;
/**
* Specify theme properties to override specific styles for agenda parts. Default = {}
*/
theme?: AgendaThemeStyle;
}
export class Agenda<T> extends React.Component<AgendaProps<T> & CalendarMarkingProps> {}
export class Agenda<TItem> extends React.Component<AgendaProps<TItem> & CalendarMarkingProps> { }
@@ -10,23 +10,23 @@ import { Calendar, CalendarList, Agenda } from "react-native-calendars";
// Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined
maxDate={"2012-05-30"}
// Handler which gets executed on day press. Default = undefined
onDayPress={day => {
console.log("selected day", day);
onDayPress={date => {
console.log("selected day", date.day);
}}
// Handler which gets executed on day long press. Default = undefined
onDayLongPress={day => {
console.log("selected day", day);
onDayLongPress={date => {
console.log("selected day", date.day);
}}
// Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting
monthFormat={"yyyy MM"}
// Handler which gets executed when visible month changes in calendar. Default = undefined
onMonthChange={month => {
console.log("month changed", month);
onMonthChange={date => {
console.log("month changed", date.month);
}}
// Hide month navigation arrows. Default = false
hideArrows={true}
// Replace default arrows with custom ones (direction can be 'left' or 'right')
renderArrow={direction => <div />}
renderArrow={direction => <View />}
// Do not show days of other months in month page. Default = false
hideExtraDays={true}
// If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out
@@ -42,6 +42,7 @@ import { Calendar, CalendarList, Agenda } from "react-native-calendars";
onPressArrowLeft={substractMonth => console.log(substractMonth)}
// Handler which gets executed when press arrow icon left. It receive a callback can go next month
onPressArrowRight={addMonth => console.log(addMonth)}
disabledByDefault={true}
/>;
<Calendar
@@ -52,23 +53,23 @@ import { Calendar, CalendarList, Agenda } from "react-native-calendars";
// Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined
maxDate={"2012-05-30"}
// Handler which gets executed on day press. Default = undefined
onDayPress={day => {
console.log("selected day", day);
onDayPress={date => {
console.log("selected day", date.day);
}}
// Handler which gets executed on day long press. Default = undefined
onDayLongPress={day => {
console.log("selected day", day);
onDayLongPress={date => {
console.log("selected day", date.day);
}}
// Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting
monthFormat={"yyyy MM"}
// Handler which gets executed when visible month changes in calendar. Default = undefined
onMonthChange={month => {
console.log("month changed", month);
onMonthChange={date => {
console.log("month changed", date.month);
}}
// Hide month navigation arrows. Default = false
hideArrows={true}
// Replace default arrows with custom ones (direction can be 'left' or 'right')
renderArrow={direction => <div />}
renderArrow={direction => <View />}
// Do not show days of other months in month page. Default = false
hideExtraDays={true}
// If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out
@@ -267,7 +268,7 @@ const workout = { key: "workout", color: "green" };
// Hide month navigation arrows. Default = false
hideArrows={true}
// Replace default arrows with custom ones (direction can be 'left' or 'right')
renderArrow={direction => <div />}
renderArrow={direction => <View />}
// Do not show days of other months in month page. Default = false
hideExtraDays={true}
// If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out
@@ -283,6 +284,29 @@ const workout = { key: "workout", color: "green" };
onPressArrowLeft={substractMonth => console.log(substractMonth)}
// Handler which gets executed when press arrow icon left. It receive a callback can go next month
onPressArrowRight={addMonth => console.log(addMonth)}
// Disable days by default. Default = false
disabledByDefault={true}
// Display loading indicator. Default = false
displayLoadingIndicator={true}
// When true, the calendar list scrolls to top when the status bar is tapped. Default = true
scrollsToTop={true}
// Enable paging on horizontal, default = false
pagingEnabled={true}
// Provide custom day rendering component.
dayComponent={({ date, state }) => {
return (
<View style={{ flex: 1 }}>
<Text
style={{
textAlign: "center",
color: state === "disabled" ? "gray" : "black"
}}
>
{date.day}
</Text>
</View>
);
}}
/>;
<Agenda
@@ -326,7 +350,7 @@ const workout = { key: "workout", color: "green" };
futureScrollRange={50}
// specify how each item should be rendered in agenda
renderItem={(item, firstItemInDay) => {
return <View />;
return firstItemInDay ? <View /> : <View />;
}}
// specify how each date should be rendered. day can be undefined if the item is not first in that day.
renderDay={(day, item) => {
@@ -371,4 +395,10 @@ const workout = { key: "workout", color: "green" };
}}
// agenda container style
style={{}}
// Display loading indicator. Default = false
displayLoadingIndicator={true}
// If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday.
firstDay={1}
// Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting
monthFormat={"yyyy MM"}
/>;
+6 -1
View File
@@ -1 +1,6 @@
{ "extends": "dtslint/dt.json" }
{
"extends": "dtslint/dt.json",
"rules": {
"file-name-casing": [true, "kebab-case"]
}
}
+1
View File
@@ -281,6 +281,7 @@ export class Ripple extends Component<{
color?: string,
background?: string,
disabled?: boolean,
modifier?: string,
}, any> {}
/*** Forms ***/
+4 -3
View File
@@ -1,9 +1,10 @@
// Type definitions for react-paginate 4.3
// Type definitions for react-paginate 5.2
// Project: https://github.com/AdeleD/react-paginate
// Definitions by: Simon Hartcher <https://github.com/deevus>
// Wouter Hardeman <https://github.com/wouterhardeman>
// pegel03 <https://github.com/pegel03>
// Simon Archer <https://github.com/archy-bold>
// Yasunori Ohoka <https://github.com/yasupeke>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
@@ -48,7 +49,7 @@ interface ReactPaginateProps {
/**
* The method to call when a page is clicked. Exposes the current page object as an argument.
*/
onPageChange?(selectedItem: {selected: number}): void;
onPageChange?(selectedItem: { selected: number }): void;
/**
* The initial page selected.
@@ -122,4 +123,4 @@ interface ReactPaginateProps {
}
declare const ReactPaginate: React.ComponentClass<ReactPaginateProps>;
export = ReactPaginate;
export default ReactPaginate;
@@ -1,5 +1,5 @@
import * as React from "react";
import ReactPaginate = require("react-paginate");
import * as React from 'react';
import ReactPaginate from 'react-paginate';
class Test extends React.Component {
render() {
+6 -6
View File
@@ -1,8 +1,4 @@
{
"files": [
"index.d.ts",
"react-paginate-tests.tsx"
],
"compilerOptions": {
"module": "commonjs",
"lib": [
@@ -21,5 +17,9 @@
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"jsx": "react"
}
}
},
"files": [
"index.d.ts",
"react-paginate-tests.tsx"
]
}
+125
View File
@@ -0,0 +1,125 @@
// Type definitions for react-paginate 4.3
// Project: https://github.com/AdeleD/react-paginate
// Definitions by: Simon Hartcher <https://github.com/deevus>
// Wouter Hardeman <https://github.com/wouterhardeman>
// pegel03 <https://github.com/pegel03>
// Simon Archer <https://github.com/archy-bold>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import * as React from 'react';
interface ReactPaginateProps {
/**
* The total number of pages.
*/
pageCount: number;
/**
* The range of pages displayed.
*/
pageRangeDisplayed: number;
/**
* The number of pages to display for margins.
*/
marginPagesDisplayed: number;
/**
* Label for the `previous` button.
*/
previousLabel?: string | JSX.Element;
/**
* Label for the `next` button.
*/
nextLabel?: string | JSX.Element;
/**
* Label for ellipsis.
*/
breakLabel?: string | JSX.Element;
/**
* The classname on tag `li` of the ellipsis element.
*/
breakClassName?: string | JSX.Element;
/**
* The method to call when a page is clicked. Exposes the current page object as an argument.
*/
onPageChange?(selectedItem: { selected: number }): void;
/**
* The initial page selected.
*/
initialPage?: number;
/**
* To override selected page with parent prop.
*/
forcePage?: number;
/**
* Disable onPageChange callback with initial page. Default: false
*/
disableInitialCallback?: boolean;
/**
* The classname of the pagination container.
*/
containerClassName?: string;
/**
* The classname on tag `li` of each page element.
*/
pageClassName?: string;
/**
* The classname on tag `a` of each page element.
*/
pageLinkClassName?: string;
/**
* The classname for the active page.
*/
activeClassName?: string;
/**
* The classname on tag `li` of the `previous` button.
*/
previousClassName?: string;
/**
* The classname on tag `li` of the `next` button.
*/
nextClassName?: string;
/**
* The classname on tag `a` of the `previous` button.
*/
previousLinkClassName?: string;
/**
* The classname on tag `a` of the `next` button.
*/
nextLinkClassName?: string;
/**
* The classname for disabled `previous` and `next` buttons.
*/
disabledClassName?: string;
/**
* The method is called to generate the href attribute value on tag a of each page element.
*/
hrefBuilder?(pageIndex: number): void;
/**
* Extra context to add to the aria-label HTML attribute.
*/
extraAriaContext?: string;
}
declare const ReactPaginate: React.ComponentClass<ReactPaginateProps>;
export = ReactPaginate;
@@ -0,0 +1,33 @@
import * as React from 'react';
import ReactPaginate = require('react-paginate');
class Test extends React.Component {
render() {
return (
<ReactPaginate
pageCount={1}
pageRangeDisplayed={10}
marginPagesDisplayed={2}
previousLabel={'previous'}
nextLabel={'next'}
breakLabel={'break-me'}
breakClassName={'break-class'}
onPageChange={(selectedItem: {selected: number}) => null}
initialPage={2}
forcePage={3}
disableInitialCallback={false}
containerClassName={'container'}
pageClassName={'page-li'}
pageLinkClassName={'page-a'}
activeClassName={'active'}
previousClassName={'previous-li'}
nextClassName={'next-li'}
previousLinkClassName={'previous-a'}
nextLinkClassName={'next-a'}
disabledClassName={'disabled'}
hrefBuilder={(pageIndex: number) => null}
extraAriaContext={'aria'}
/>
);
}
}
+30
View File
@@ -0,0 +1,30 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"paths": {
"react-paginate": [
"react-paginate/v4"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"jsx": "react"
},
"files": [
"index.d.ts",
"react-paginate-tests.tsx"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+8
View File
@@ -3,6 +3,7 @@
// Definitions by: Wouter Hardeman <https://github.com/wouterhardeman>
// Jovica Zoric <https://github.com/jzoric>
// Kevin Perrine <https://github.com/kevinsperrine>
// Alex Maclean <https://github.com/acemac>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
@@ -70,6 +71,12 @@ export interface OnDragPreviousAndNextLocation extends PreviousAndNextLocation {
nextParent: TreeItem | null;
}
export interface ShouldCopyData {
node: TreeNode;
prevPath: NumberArrayOrStringArray;
prevTreeIndex: number;
}
export interface OnMovePreviousAndNextLocation extends PreviousAndNextLocation {
nextParentNode: TreeItem | null;
}
@@ -186,6 +193,7 @@ export interface ReactSortableTreeProps {
dndType?: string;
placeholderRenderer?: PlaceholderRenderer;
theme?: ThemeProps;
shouldCopyOnOutsideDrop?: boolean | ((data: ShouldCopyData) => boolean);
}
declare const SortableTree: React.ComponentClass<ReactSortableTreeProps>;
@@ -69,11 +69,13 @@ class Test extends React.Component {
dndType="testNodeType"
placeholderRenderer={PlaceholderRenderer}
theme={theme}
shouldCopyOnOutsideDrop={true}
/>
<SortableTreeWithoutDndContext
treeData={[{title: "Title", subtitle: "Subtitle", children: []}]}
onChange={(treeData: TreeItem[]) => {}}
style={{width: "100px"}}
shouldCopyOnOutsideDrop={() => false}
/>
</div>
);
+62
View File
@@ -0,0 +1,62 @@
// Type definitions for ref-array-di 1.2
// Project: https://github.com/node-ffi-napi/ref-array-di
// Definitions by: Keerthi Niranjan <https://github.com/keerthi16>, Kiran Niranjan <https://github.com/KiranNiranjan>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import ref = require('ref-napi');
interface ArrayType<T> extends ref.Type {
BYTES_PER_ELEMENT: number;
fixedLength: number;
/** The reference to the base type. */
type: ref.Type;
/**
* Accepts a Buffer instance that should be an already-populated with data
* for the ArrayType. The "length" of the Array is determined by searching
* through the buffer's contents until an aligned NULL pointer is encountered.
*/
untilZeros(buffer: Buffer): {
[i: number]: T; length: number; toArray(): T[];
toJSON(): T[]; inspect(): string; buffer: Buffer; ref(): Buffer;
};
new (length?: number): {
[i: number]: T; length: number; toArray(): T[];
toJSON(): T[]; inspect(): string; buffer: Buffer; ref(): Buffer;
};
new (data: number[], length?: number): {
[i: number]: T; length: number; toArray(): T[];
toJSON(): T[]; inspect(): string; buffer: Buffer; ref(): Buffer;
};
new (data: Buffer, length?: number): {
[i: number]: T; length: number; toArray(): T[];
toJSON(): T[]; inspect(): string; buffer: Buffer; ref(): Buffer;
};
(length?: number): {
[i: number]: T; length: number; toArray(): T[];
toJSON(): T[]; inspect(): string; buffer: Buffer; ref(): Buffer;
};
(data: number[], length?: number): {
[i: number]: T; length: number; toArray(): T[];
toJSON(): T[]; inspect(): string; buffer: Buffer; ref(): Buffer;
};
(data: Buffer, length?: number): {
[i: number]: T; length: number; toArray(): T[];
toJSON(): T[]; inspect(): string; buffer: Buffer; ref(): Buffer;
};
}
/**
* The array type meta-constructor.
* The returned constructor's API is highly influenced by the WebGL
* TypedArray API.
*/
declare var ArrayType: {
new <T>(type: ref.Type, length?: number): ArrayType<T>;
new <T>(type: string, length?: number): ArrayType<T>;
<T>(type: ref.Type, length?: number): ArrayType<T>;
<T>(type: string, length?: number): ArrayType<T>;
};
export = ArrayType;
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts"
]
}
+79
View File
@@ -0,0 +1,79 @@
{
"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,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": 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
}
}
+188
View File
@@ -0,0 +1,188 @@
// Type definitions for ref-napi 1.4
// Project: https://github.com/node-ffi-napi/ref-napi
// Definitions by: Keerthi Niranjan <https://github.com/keerthi16>, Kiran Niranjan <https://github.com/KiranNiranjan>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
export interface Type {
/** The size in bytes required to hold this datatype. */
size: number;
/** The current level of indirection of the buffer. */
indirection: number;
/** To invoke when `ref.get` is invoked on a buffer of this type. */
get(buffer: Buffer, offset: number): any;
/** To invoke when `ref.set` is invoked on a buffer of this type. */
set(buffer: Buffer, offset: number, value: any): void;
/** The name to use during debugging for this datatype. */
name?: string;
/** The alignment of this datatype when placed inside a struct. */
alignment?: number;
}
/** A Buffer that references the C NULL pointer. */
export declare var NULL: Buffer;
/** A pointer-sized buffer pointing to NULL. */
export declare var NULL_POINTER: Buffer;
/** Get the memory address of buffer. */
export declare function address(buffer: Buffer): number;
/** Allocate the memory with the given value written to it. */
export declare function alloc(type: Type, value?: any): Buffer;
/** Allocate the memory with the given value written to it. */
export declare function alloc(type: string, value?: any): Buffer;
/**
* Allocate the memory with the given string written to it with the given
* encoding (defaults to utf8). The buffer is 1 byte longer than the
* string itself, and is NULL terminated.
*/
export declare function allocCString(string: string, encoding?: string): Buffer;
/** Coerce a type.*/
export declare function coerceType(type: Type): Type;
/** Coerce a type. String are looked up from the ref.types object. */
export declare function coerceType(type: string): Type;
/**
* Get value after dereferencing buffer.
* That is, first it checks the indirection count of buffer's type, and
* if it's greater than 1 then it merely returns another Buffer, but with
* one level less indirection.
*/
export declare function deref(buffer: Buffer): any;
/** Create clone of the type, with decremented indirection level by 1. */
export declare function derefType(type: Type): Type;
/** Create clone of the type, with decremented indirection level by 1. */
export declare function derefType(type: string): Type;
/** Represents the native endianness of the processor ("LE" or "BE"). */
export declare var endianness: string;
/** Check the indirection level and return a dereferenced when necessary. */
export declare function get(buffer: Buffer, offset?: number, type?: Type): any;
/** Check the indirection level and return a dereferenced when necessary. */
export declare function get(buffer: Buffer, offset?: number, type?: string): any;
/** Get type of the buffer. Create a default type when none exists. */
export declare function getType(buffer: Buffer): Type;
/** Check the NULL. */
export declare function isNull(buffer: Buffer): boolean;
/** Read C string until the first NULL. */
export declare function readCString(buffer: Buffer, offset?: number): string;
/**
* Read a big-endian signed 64-bit int.
* If there is losing precision, then return a string, otherwise a number.
* @return {number|string}
*/
export declare function readInt64BE(buffer: Buffer, offset?: number): any;
/**
* Read a little-endian signed 64-bit int.
* If there is losing precision, then return a string, otherwise a number.
* @return {number|string}
*/
export declare function readInt64LE(buffer: Buffer, offset?: number): any;
/** Read a JS Object that has previously been written. */
export declare function readObject(buffer: Buffer, offset?: number): Object;
/** Read data from the pointer. */
export declare function readPointer(buffer: Buffer, offset?: number,
length?: number): Buffer;
/**
* Read a big-endian unsigned 64-bit int.
* If there is losing precision, then return a string, otherwise a number.
* @return {number|string}
*/
export declare function readUInt64BE(buffer: Buffer, offset?: number): any;
/**
* Read a little-endian unsigned 64-bit int.
* If there is losing precision, then return a string, otherwise a number.
* @return {number|string}
*/
export declare function readUInt64LE(buffer: Buffer, offset?: number): any;
/** Create pointer to buffer. */
export declare function ref(buffer: Buffer): Buffer;
/** Create clone of the type, with incremented indirection level by 1. */
export declare function refType(type: Type): Type;
/** Create clone of the type, with incremented indirection level by 1. */
export declare function refType(type: string): Type;
/**
* Create buffer with the specified size, with the same address as source.
* This function "attaches" source to the returned buffer to prevent it from
* being garbage collected.
*/
export declare function reinterpret(buffer: Buffer, size: number,
offset?: number): Buffer;
/**
* Scan past the boundary of the buffer's length until it finds size number
* of aligned NULL bytes.
*/
export declare function reinterpretUntilZeros(buffer: Buffer, size: number,
offset?: number): Buffer;
/** Write pointer if the indirection is 1, otherwise write value. */
export declare function set(buffer: Buffer, offset: number, value: any, type?: Type): void;
/** Write pointer if the indirection is 1, otherwise write value. */
export declare function set(buffer: Buffer, offset: number, value: any, type?: string): void;
/** Write the string as a NULL terminated. Default encoding is utf8. */
export declare function writeCString(buffer: Buffer, offset: number,
string: string, encoding?: string): void;
/** Write a big-endian signed 64-bit int. */
export declare function writeInt64BE(buffer: Buffer, offset: number, input: number): void;
/** Write a big-endian signed 64-bit int. */
export declare function writeInt64BE(buffer: Buffer, offset: number, input: string): void;
/** Write a little-endian signed 64-bit int. */
export declare function writeInt64LE(buffer: Buffer, offset: number, input: number): void;
/** Write a little-endian signed 64-bit int. */
export declare function writeInt64LE(buffer: Buffer, offset: number, input: string): void;
/**
* Write the JS Object. This function "attaches" object to buffer to prevent
* it from being garbage collected.
*/
export declare function writeObject(buffer: Buffer, offset: number, object: Object): void;
/**
* Write the memory address of pointer to buffer at the specified offset. This
* function "attaches" object to buffer to prevent it from being garbage collected.
*/
export declare function writePointer(buffer: Buffer, offset: number,
pointer: Buffer): void;
/** Write a little-endian unsigned 64-bit int. */
export declare function writeUInt64BE(buffer: Buffer, offset: number, input: number): void;
/** Write a little-endian unsigned 64-bit int. */
export declare function writeUInt64BE(buffer: Buffer, offset: number, input: string): void;
/**
* Attach object to buffer such.
* It prevents object from being garbage collected until buffer does.
*/
export declare function _attach(buffer: Buffer, object: Object): void;
/** Same as ref.reinterpret, except that this version does not attach buffer. */
export declare function _reinterpret(buffer: Buffer, size: number,
offset?: number): Buffer;
/** Same as ref.reinterpretUntilZeros, except that this version does not attach buffer. */
export declare function _reinterpretUntilZeros(buffer: Buffer, size: number,
offset?: number): Buffer;
/** Same as ref.writePointer, except that this version does not attach pointer. */
export declare function _writePointer(buffer: Buffer, offset: number,
pointer: Buffer): void;
/** Same as ref.writeObject, except that this version does not attach object. */
export declare function _writeObject(buffer: Buffer, offset: number, object: Object): void;
/** Default types. */
export declare var types: {
void: Type; int64: Type; ushort: Type;
int: Type; uint64: Type; float: Type;
uint: Type; long: Type; double: Type;
int8: Type; ulong: Type; Object: Type;
uint8: Type; longlong: Type; CString: Type;
int16: Type; ulonglong: Type; bool: Type;
uint16: Type; char: Type; byte: Type;
int32: Type; uchar: Type; size_t: Type;
uint32: Type; short: Type;
};
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts"
]
}

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