Merge branch 'master' into master

This commit is contained in:
hosomichi
2018-08-09 10:57:12 +09:00
committed by GitHub
936 changed files with 35742 additions and 10247 deletions
+1
View File
@@ -4293,6 +4293,7 @@
/types/timer-machine/ @dolanmiu
/types/timezone-js/ @bonnici
/types/tinajs__tina/ @Jimexist
/types/tinajs__tina-redux/ @Jimexist
/types/tinder/ @pingec
/types/tiny-slider-react/ @screendriver
/types/tinycolor2/ @M-Zuber @geertjansen @nvh
+338
View File
@@ -0,0 +1,338 @@
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
[![깃터(https://gitter.im/borisyankov/DefinitelyTyped)에서 대화에 참여해보세요](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
> 이 저장소는 고품질의 타입스크립트(TypeScript) 자료형 정의(Type definition)를 위한 저장소입니다.
이 문서가 가장 최신 내용을 담고있긴 하지만, [공식 사이트(definitelytyped.org)](http://definitelytyped.org)도 확인해보시면 좋습니다.
## 선언 파일(Declaration file)이 뭔가요?
[타입스크립트 안내서(TypeScript handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)를 읽어보세요.
## 선언 파일(Declaration file)을 어떻게 받을 수 있나요??
### npm 사용하기
아래 방법은 타입스크립트(TypeScript) 2.0+ 이상의 버전을 사용하는 사람들만 사용할 수 있는 방법이기는 합니다만, 이 방법을 사용하기를 장려합니다.
```sh
npm install --save-dev @types/node
```
`node` 를 위한 자료형(Typing)이 컴파일 과정에 자동으로 포함될 겁니다.
더 자세한 내용은 [안내서(Handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html)에서 확인해보실 수 있습니다.
NPM 의 "foo" 패키지에 대응되는 자료형 패키지는 "@types/foo" 입니다.
원하시는 패키지를 찾을 수 없는 경우, [타입서치(TypeSearch)](https://microsoft.github.io/TypeSearch/) 사이트에서 한 번 찾아보세요.
타입서치(TypeSearch)에서도 찾을 수 없는 경우, 찾고 있는 패키지가 자료형(Typing)을
[함께 제공](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)하고 있지는 않은지 확인해보세요.
패키지에 포함된 자료형(Typing)은 주로 `package.json` 파일의 `"types"` 나 `"typings"` 필드(Field)를 통해 제공되지만,
`/// <reference path="" />` 같은 주석을 사용하여 패키지 안의 ".d.ts" 파일들을 직접 가져와야 할 수도 있습니다.
### 그 외의 방법들
타입스크립트(TypeScript) 1.0 버전에서 사용할 수 있는 방법은 다음과 같습니다.
* [Typings](https://github.com/typings/typings) 을 사용하기
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped) 을 사용하기~~ (다른 방법을 사용해주세요. NuGet 은 더 이상 DT 자료형(Typing)을 제공하지 않습니다.)
* 이 저장소의 `master` 브랜치를 직접 내려받기
위 방법을 사용할 경우 수동으로 [참조(Reference)](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html)를 추가해주어야 할 수 있습니다.
## 어떻게 이곳에 기여할 수 있나요?
여러분과 같은 많은 기여자들의 도움 덕분에 이 저장소가 돌아가고 있습니다. 감사합니다.
### 테스트
여러분이 만든 자료형 선언(Type declation)을 세상에 공유하기에 앞서, 여러분이 스스로 여러분의 자료형 선언(Type declation)을 사용하고 확인해주세요.
#### 이미 존재하는 자료형 패키지를 임시로 수정하기
이미 존재하는 패키지의 자료형 선언(Type declaration)에 새로운 기능을 추가하려면 [모듈 증강(module augmentation)](http://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation)를 사용할 수 있습니다.
물론 `node_modules/@types/foo/index.d.ts` 를 직접 수정하실 수도 있으며, 이 파일을 복사한 다음 아래의 과정을 따라하실 수도 있습니다.
#### 새 자료형 패키지를 임시로 추가하기
사용하고 계신 `tsconfig.json` 에 다음 내용을 추가해주세요.
```json
"baseUrl": "types",
"typeRoots": ["types"],
```
(`types` 대신 `src/types` 을 사용하실 수도 있습니다.)
그리고 "foo" 모듈(Module)에 대한 선언(Declaration)을 포함하는 `types/foo/index.d.ts` 파일을 만들어주세요.
이제 코드 안에서 여러분의 새 자료형 선언(Type declaration)을 사용하는 `"foo"` 모듈(Module)을 임포트(Import)하실 수 있을 겁니다.
코드를 컴파일하고 실행시켜서 여러분의 자료형(Typing)이 실행 중에 실제로 벌어지는 일과 잘 맞아떨어지는지 확인해주세요.
실제 코드를 통한 확인이 끝나면, [풀 리퀘스트(Pull request)](#풀-리퀘스트pull-request-만들기)를 만들어주세요.
[이미 존재하는 패키지를 수정](#이미-존재하는-패키지를-수정하기)하거나 [새 패키지를 만들기](#새-패키지-만들기)위한 과정들을 따라하시면 됩니다.
### 풀 리퀘스트(Pull request) 만들기
여러분의 자료형 선언이 잘 작동하는지 확인하셨다면, DefinitelyTyped 에 공유해주세요.
우선, 이 저장소를 [포크(fork)](https://guides.github.com/activities/forking/)해 주시고, [node](https://nodejs.org/) 를 설치하신 뒤, `npm install` 명령을 실행해주세요.
#### 이미 존재하는 패키지를 수정하기
* `cd types/my-package-to-edit` 명령을 실행합니다.
* 자료형(Typing) 파일들을 수정합니다. 테스트를 추가하는 것도 잊지마세요!
만약 브레이킹 체인지(Breaking change)를 만드셨다면, [메이저 버전(major version)](#i-want-to-update-a-package-to-a-new-major-version)을 꼭 올려주세요.
* 패키지 머릿주석의 "Definitions by" 부분에 여러분의 이름을 추가하실 수도 있습니다.
- 이름을 추가하시면 다른 사람들이 그 패키지에 대한 풀 리퀘스트(Pull request)나 이슈(Issue)를 만들 때 여러분에게 알람이 갑니다.
- `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>` 와 같이 여러분의 이름을 줄의 맨 마지막에 추가할 수 있습니다.
- 사람이 너무 많을 경우엔, 다음과 같이 여러 줄로 쓰실 수도 있습니다.
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* `tslint.json` 파일이 있는 경우에는, `npm run lint package-name` 명령을 실행시키고 결과를 확인해주세요. 그렇지 않은 경우에는, 해당 패키지가 있는 디렉토리 안에서 `tsc` 명령을 실행시키고 결과를 확인해주세요.
이미 존재하는 패키지에 대한 풀 리퀘스트(Pull request)를 만들었을 경우에는, `dt-bot` 이 이전 저자들을 자동으로 호출하는지 확인해주세요.
그렇지 않은 경우에는, 여러분이 직접 풀 리퀘스트(Pull request)와 관계있는 사람들을 호출할 수도 있습니다.
#### 새 패키지를 만들기
만약 라이브러리를 만드는 중이고 라이브러리가 타입스크립트(TypeScript)로 쓰여있다면, DefinitelyTyped 에 선언(Declaration)을 올리는 대신 패키지에 [자동생성된 선언(Declaration) 파일을 포함](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)시킬 수 있습니다.
NPM 패키지를 위한 자료형(Typing) 패키지를 만드시려면, 패키지의 이름과 같은 이름의 디렉토리를 만들어주세요.
NPM 에 올라가 있지 않은 패키지를 위한 자료형(Typing) 패키지를 만드시려면, 그 패키지가 NPM 에 올라와 있는 패키지와 이름이 겹치지 않는지 확인해주세요.
(`npm info foo` 명령어를 사용하여 `foo` 패키지가 NPM 에 있는지 확인할 수 있습니다.)
새 자료형 패키지는 다음과 같은 구조로 구성되어있어야만 합니다.
| 파일 이름 | 용도 |
| --- | --- |
| index.d.ts | 패키지를 위한 자료형(Typing)을 포함하는 파일입니다. |
| foo-tests.ts | 자료형(Typing)의 테스트를 위한 파일입니다. 이 파일의 코드는 실행되지는 않지만, 자료형 검사(Type checking)를 통과해야 합니다. |
| tsconfig.json | `tsc` 명령을 돌릴 수 있게 해주는 파일입니다. |
| tslint.json | 린터(Linter)를 사용할 수 있게 해주는 파일입니다. |
이 파일들은, npm ≥ 5.2.0 에서는 `npx dts-gen --dt --name my-package-name --template module` 명령으로,
그 이하 경우에는 `npm install -g dts-gen` 와 `dts-gen --dt --name my-package-name --template module` 명령으로 만들 수 있습니다.
`dts-gen` 의 모든 옵션(Option)을 보고싶으시면 [dts-gen](https://github.com/Microsoft/dts-gen) 저장소를 확인해주세요.
자료형(Typing) 패키지에 새 파일을 추가하거나, `async` 키워드를 사용하기 위해 `"target"` 을 `"es6"` 로 설정하거나, `"lib"` 를 추가하거나, `jsx` 지원을 추가하기 위해서 `tsconfig.json` 파일을 변경해야 할 수도 있습니다.
DefinitelyTyped 의 관리자들이 주기적으로 새로운 풀 리퀘스트(Pull request)들을 확인하기는 하지만,
다른 풀 리퀘스트(Pull request)가 많을 경우 확인이 느려질 수 있다는 걸 알아주세요.
[base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js) 패키지는 좋은 예시 중 하나입니다.
#### 많이 저지르는 실수들
* 우선, [안내서(Handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html)에 나와있는 내용들을 따라주세요.
* 코드에서는 모든 곳에서 탭(Tab)을 사용하거나, 항상 4 개의 띄어쓰기를 사용해주세요.
* `function sum(nums: number[]): number`의 경우, 만약 함수가 인자를 변경하지 않는다면 `ReadonlyArray` 를 사용해주세요.
* `interface Foo { new(): Foo; }`의 경우,
이런 선언은 이 형(Type)을 가진 객체(Object)에 `new` 를 사용할 수 있도록 만듭니다. 많은 경우 여러분은 `declare class Foo { constructor(); }` 를 사용하려는 것일 겁니다.
* `const Class: { new(): IClass; }`의 경우,
`new` 를 사용할 수 있는 상수를 만드는 대신, `class Class { constructor(); }` 와 같이 클래스 선언(Class declaration)을 사용하는 게 더 좋습니다.
* `getMeAT<T>(): T`의 경우,
만일 자료형 매개변수(Type parameter)가 함수의 매개변수에 등장하지 않는다면, 그런 제너릭(Generic) 함수를 사용할 필요가 없습니다.
그 제너릭(Generic) 함수는 단순히 자료형 단언(Type assertion)을 위장시킨 것뿐입니다. 이 경우 `getMeAT() as number` 와 같이 진짜 자료형 단언(Type assertion) 을 사용하는 게 더 좋습니다.
다음은 괜찮은 제너릭(Generic)의 예시입니다. `function id<T>(value: T): T;`.
다음은 문제가 있는 제너릭(Generic)의 예시입니다. `function parseJson<T>(json: string): T;`.
예외적으로, `new Map<string, number>()` 와 같은 경우는 괜찮습니다.
* `Function` 이나 `Object` 와 같은 형(Type)을 사용하는 것은 대부분의 경우 문제를 일으킵니다. 99% 의 경우 더 구체적인 형(Type)을 사용하는게 가능합니다. [함수(Function)](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) 를 위해서는 `(x: number) => number` 와 같은, 객체를 위해서는 `{ x: number, y: number }` 와 같은 형(Type)들을 사용할 수 있습니다. 형(Type)에 대한 정보가 전혀 없을 경우에는, `Object` 형(Type)이 아니라 [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) 형(Type)을 사용해야 합니다. 만일 어떤 형(Type)이 객체라는 사실만 알고 있는 경우, `Object` 나 `{ [key: string]: any }` 가 아니라 [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type) 를 사용해주세요.
* `var foo: string | any`의 경우,
`any` 가 합 자료형(Union type)의 안에서 사용될 경우, 결과 형(Type)은 언제나 `any` 가 됩니다. 따라서 형(Type)의 `string` 부분이 유용해 보인다 하더라도, 사실은 자료형 검사(Type checking)의 측면에서 `any` 와 다른 것이 없습니다.
대신, `any`, `string`, 나 `string | object` 중 하나를 필요에 맞게 골라서 사용해주세요.
#### 패키지 삭제하기
패키지가 스스로의 형(Type)을 [포함](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)하게 되면, DefinitelyTyped 에 있는 자료형(Typing) 패키지를 삭제하는 것이 좋습니다.
`npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]` 명령어를 사용하여 자료형(Typing) 패키지를 삭제할 수 있습니다.
- `typingsPackageName` 는 삭제할 디렉토리의 이름입니다.
- `asOfVersion` 는 새 스텁(Stub) 용 `@types/foo` 를 퍼블리시(Publish)할 버전입니다. 이 버전은 현재 NPM 에 올라간 버전보다 더 높은 버전이어야 합니다.
- `sourceRepoURL` 는 자료형(Typing)을 포함하게 된 저장소의 주소입니다.
- `libraryName` 는 패키지의 이름을 읽기 쉽게 쓴 것입니다. 즉, "angular2" 대신에 "Angular 2" 와 같이 쓰는 것이 좋습니다. (생략했을 경우에는 "typingsPackageName" 와 같은 것으로 취급됩니다.)
DefinitelyTyped 의 다른 패키지들이 삭제된 자료형(Typing) 패키지를 사용하고 있을 경우, 형(Type)을 포함하기 시작한 원래 패키지를 사용하도록 수정해야합니다. 삭제된 자료형(Typing) 패키지를 사용하는 각 DefinitelyTyped 패키지들의 `package.json` 파일에 `"dependencies": { "foo": "x.y.z" }` 를 추가해주시면 됩니다.
DefinitelyTyped 에 한 번도 올라온 적 없는 패키지가 형(Type)을 포함하게 되었다면, `notNeededPackages.json` 파일에 추가할 필요도 없습니다.
#### 린트(Lint)하기
자료형(Typing) 패키지를 린트(Lint)하려면, 패키지 디렉토리에 `{ "extends": "dtslint/dt.json" }` 를 포함하고 있는 `tslint.json` 파일을 추가해주시면 됩니다. 모든 새 패키지는 해당 파일을 가지고 있어야 합니다.
고쳐야 하지만 아직 고쳐지지 않은 린트(Lint) 결과가 있을 때에만 `tslint.json` 에서 린트 규칙(Lint rule)을 사용하지 않도록 설정할 수 있습니다. 예를 들어,
```js
{
"extends": "dtslint/dt.json",
"rules": {
// 이 패키지는 Function 형을 사용하고 있으며, 고치는 게 쉽지 않다.
"ban-types": false
}
}
```
(린트 규칙(Lint rule)이 절대로 적용되서는 안되는 경우에는, `// tslint:disable rule-name` 나 `//tslint:disable-next-line rule-name` 를 사용하는 것이 좋습니다. 후자가 더 나은 방식입니다.)
어떤 표현식(Expression)이 특정한 형(Type)을 가진다고 단언(Assert)하고 싶을 때에는 `$ExpectType` 를 사용하시면 됩니다. 어떤 표현식(Expression)이 컴파일에 실패해야하는 경우에는 `$ExpectError` 를 하시면 됩니다.
```js
// $ExpectType void
f(1);
// $ExpectError
f("one");
```
[dtslint](https://github.com/Microsoft/dtslint#write-tests) 저장소의 README 파일에서 더 자세한 내용을 확인하실 수 있습니다.
이런 테스트들은 `npm run lint package-name` 명령으로 실행해볼 수 있습니다. 이 때, `package-name` 은 테스트하고 싶은 패키지의 이름입니다.
테스트 스크립트는 [dtslint](https://github.com/Microsoft/dtslint) 를 사용하고 있습니다.
## 자주 하는 질문들
#### 이 저장소와 `@types` 패키지들이 대체 무슨 관계가 있는 건가요?
`master` 브랜치(Branch)의 내용들이 [types-publisher](https://github.com/Microsoft/types-publisher) 를 사용해 자동으로 `@types` 퍼블리시(Publish)됩니다.
#### 풀 리퀘스트(Pull request)를 제출했습니다. 이게 합쳐질 때까지 얼마나 걸리나요?
상황에 따라 다르지만, 대부분의 풀 리퀘스트(Pull request)들은 일주일 안에 합쳐집니다. 머릿주석에 있는 저자 중 한명에 의해 승인된 풀 리퀘스트(Pull request)는 보통 더 빨리 합쳐집니다. 새로운 패키지에 대한 풀 리퀘스트(Pull request)는 관리자의 세세한 코드 리뷰를 필요로 하기 때문에 더 오래 걸리는 경우가 많습니다. 각 PR 들은 합쳐지기 전에 TypeScript or DefinitelyTyped 팀 구성원의 코드 리뷰를 받아야 하며, 이는 사람이 하는 일이기 때문에 느려질 수도 있으니 양해를 바랍니다. [풀 리퀘스트 번다운 보드(PR Burndown Board)](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen)에서 열린 풀 리퀘스트에 대한 관리자들의 진행도를 확인하실 수 있습니다.
#### 내 풀 리퀘스트(Pull request)는 합쳐졌습니다. 언제 NPM 에 `@types` 패키지가 갱신되나요?
NPM 의 패키지들은 수시간 안에 갱신될 겁니다. 만약 24 시간이 지나도 갱신되지 않으면, 문제를 파악하기 위해 @RyanCavanaugh 나 @andy-ms 를 풀 리퀘스트(Pull request)에서 호출해주세요.
#### 다른 자료형 정의(Type definition)에 의존하는 자료형 정의(Type definition)을 만들고 있습니다. `<reference types="" />` 와 임포트(import) 중 무엇을 사용해야하나요?
외부 모듈(`export` 를 사용하는 모듈)을 사용할 경우, 임포트(import)를 사용해주세요.
환경과 관련된 모듈(ambient module)(`declare module` 를 쓰거나 전역 변수들을 선언한 모듈)을 사용할 경우, `<reference types="" />` 를 사용해주세요.
#### `package.json` 파일이 가끔 보이던데?
일반적으로는 `package.json` 파일을 사용할 필요가 없습니다. 패키지가 퍼블리시(Publish)될 때 패키지를 위한 `package.json` 파일은 자동으로 생성됩니다.
가끔 보이는 `package.json` 파일은 의존하는 것들을 표시하기 위해 사용됩니다. [예시](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json)를 한 번 보세요.
의존성을 제외한 다른 필드(Field)들, 그러니까 `"description"` 같은 것들은 사용해서는 안됩니다.
옛날 `@types` 패키지를 사용하고 싶으실 경우에도 `"dependencies": { "@types/foo": "x.y.z" }` 와 같은 내용을 `package.json` 파일에 넣으셔야 합니다.
#### 어떤 패키지들에 `tslint.json` 이 없거나, `tsconfig.json` 에 `"noImplicitAny": true`, `"noImplicitThis": true`, 나 `"strictNullChecks": true` 가 없어요.
그럼 그 패키지들이 잘못된 겁니다. 고쳐서 풀 리퀘스트(Pull request)를 제출해주시면 고맙겠습니다.
#### 자료형 정의(Type definition)을 요청할 수 있나요?
이미 요청된 자료형 정의(Type definition)들을 [여기서](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest) 보실 수 있습니다.
#### DOM 을 위한 자료형 정의(Type definitions)는요?
웹 표준(Web standard)과 관련이 있는 자료형(Typing)들은 [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) 저장소에 기여해서 고치실 수 있습니다. 고쳐진 자료형(Typing)은 `lib.dom.d.ts` 파일에 포함될 겁니다.
#### 어떤 패키지가 `export =` 를 쓰고 있는데, 저는 디폴트 임포트(Default import)가 더 좋습니다. `export =` 를 `export default` 로 바꿔도 되나요?
타입스크립트(TypeScript) 2.7 이상을 사용하고 계시면 프로젝트 안에서 `--esModuleInterop` 를 사용해주세요.
그 이하의 경우, 디폴트 임포트(Default import)가 동작하는 환경(Webpack, SystemJS, esm)에서 작업 중이시면 [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) 를 사용하는 걸 고려해보세요.
자료형 정의(Type definition)가 맞는 경우에는 자료형 정의(Type definition)을 수정하지 마세요.
NPM 패키지의 경우, `node -p 'require("foo")'` 가 원하는 값이라면 `export =` 이 맞고, `node -p 'require("foo").default'` 이 원하는 값이라면 `export default` 이 맞습니다.
#### 자료형 선언(Type declaration)에서 타입스크립트(TypeScript) 2.1 이상의 기능을 사용하고 싶습니다.
정의(Definition) 머릿주석(`// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`) 뒤에 `// TypeScript Version: 2.1` 를 추가해주시면 됩니다.
#### 타입스크립트(TypeScript)에 기본으로 포함되지 않은 DOM API 를 추가하고 싶어요.
[TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme) 저장소가 관련되어있을 가능성이 있습니다. 해당 저장소의 안내를 따라주세요.
해당 표준이 아직 초안인 상태라면, 이 저장소와 관련된 일입니다.
`dom-` 으로 시작하는 패키지를 만드신 뒤, "Project" 머릿주석 부분에 해당 표준의 링크를 써 주세요.
다만 표준이 초안을 벗어나면 DefinitelyTyped 에서 삭제되고 `@types` 패키지가 지원이 중단된(Deprecated) 것으로 표시될 수도 있습니다.
#### 패키지를 새 메이저 버전(major version)에 맞게 갱신하고 싶어요.
옛날 버전도 계속해서 수정할 예정이라면, 이전 버전에 해당하는 새 디렉토리(예를 들어 `2.` 버전을 위해서는 `v2`)를 만들고 현재 파일들을 그 디렉토리로 옮겨야 합니다. 새 디렉토리로 옮긴 뒤에는
1. `tsconfig.json` 와 `tslint.json` 에 포함된 상대경로들을 수정해주어야 합니다.
2. 경로 대응 규칙(Path mapping rule)을 추가하여 테스트가 올바른 버전을 검사하도록 해야합니다.
예를 들어, [history 패키지의 2 버전의 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) 파일은 다음과 같이 생겼습니다.
```json
{
"compilerOptions": {
"baseUrl": "../../",
"typeRoots": ["../../"],
"paths": {
"history": [ "history/v2" ]
},
},
"files": [
"index.d.ts",
"history-tests.ts"
]
}
```
수정 중인 패키지에 의존하는 DefinitelyTyped 의 다른 패키지들이 새 버전과 호환되지 않을 경우, 그 패키지들에도 옛날 버전으로의 경로 대응 규칙(Path mapping rule)을 추가해주어야 합니다. 수정 중인 패키지에 의존하는 패키지에 의존하는 패키지들에도 똑같은 작업을 해 주셔야 합니다.
예를 들어, `react-router` 패키지는 `history@2` 패키지에 의존하고 있기 때문에, [react-router 패키지의 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) 파일이 `"history": [ "history/v2" ]` 와 같은 경로 대응 규칙(Path mapping rule)을 가지고 있는 걸 볼 수 있습니다.
이어서 (`react-router` 패키지에 의존하는 패키지인) `react-router-bootstrap` 또한 [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json) 파일 안에 경로 대응 규칙(Path mapping rule)을 가지고 있는 것을 보실 수 있습니다.
`/// <reference types=".." />` 에서는 경로 대응 규칙(Path mapping rule)이 동작하지 않기 때문에, DefinitelyTyped 패키지로에 의존할 때에는 임포트(import) 를 사용해야 합니다.
#### 전역적으로도 모듈로도 사용될 수 있는 패키지의 자료형 선언(Type declaration)은 어떻게 쓰나요?
타입스크립트 안내서(TypeScript Handbook)은 [선언(Declaration)을 쓰는 방법에 대한 전반적인 정보](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)와 [예시들](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html)을 포함하고 있습니다. 이 내용에는 ES6 식의 모듈 문법을 사용할 수 있는 자료형 선언(Type declaration)을 만드는 방법과 객체를 전역에서 사용할 수 있도록 하는 방법이 포함되어 있습니다. [big.js 패키지의 자료형 선언(Type declaration)](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts)이 실례입니다. 이 패키지는 웹 페이지의 스크립트 태그를 사용해 불러올 수 있으며, 또한 ES6 식의 임포트(Import) 구문을 사용해서 불러올 수도 있습니다.
여러분의 패키지가 임포트(Import) 구문을 사용했을 때와 전역적으로 불렀을 때를 테스트 해보고 싶다면, `test` 디렉토리를 추가하고 `YourLibraryName-global.test.ts` 그리고 `YourLibraryName-module.test.ts` 라는 이름으로 테스트 파일 두 개를 추가해주세요. **전역(Global)** 테스트 파일은 웹 페이지에서 전역적으로 사용될 때를 테스트하는 파일입니다. 이 파일에서는 임포트(Import) 구문을 사용하지 않아야 합니다. **모듈(Module)** 테스트 파일은 임포트(Import) 구문을 사용할 때를 테스트 하는 파일입니다. 만약 여러분의 `tsconfig.json` 파일이 `files` 필드(Field)를 가지고 있다면, 이 필드(Field)는 반드시 두 테스트 파일을 모두 포함해야 합니다. [이 방식을 사용하는 실례](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) 또한 big.js 패키지의 자료형 선언(Type declaration)에서 확인해보실 수 있습니다.
각각의 테스트 파일에 모든 상황을 테스트할 필요는 없다는 걸 잊지마세요. 전역 테스트 파일에서는 전역적으로 사용될 때만 테스트하고, 모듈 테스트 파일에서 나머지 상황들을 모두 테스트 할 수 있으며, 그 반대의 경우도 괜찮습니다.
#### 지역 패키지(Scoped package)의 경우는 어떻게 하죠?
`@foo/bar` 패키지와 같은 지역 패키지(Scoped package)를 위한 자료형 패키지(Type package)는 `types/foo__bar` 디렉토리에 추가하면 됩니다. 밑줄 문자가 두 번 있는 것에 주의하세요.
지역 패키지(Scoped package)를 위한 자료형 패키지(Type package)를 생성하기 위해 `dts-gen` 를 사용한 경우에는,
다음과 같이 생성된 `tsconfig.json` 안에 지역 패키지(Scoped package)를 위한 적절한 경로 대응 규칙(Path mapping rule)을 추가해주어야 합니다.
```json
{
"paths":{
"@foo/bar": ["foo__bar"]
}
}
```
#### 깃헙(GitHub)이 보여주는 파일 히스토리(History)가 불완전해요.
깃헙은 이름이 바뀐 파일의 히스토리(History)를 [지원하지 않습니다](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames). 대신 [`git log --follow`](https://www.git-scm.com/docs/git-log) 명령을 사용하세요.
#### ES6 에서 사용하는 임포트(Import)를 사용하기 위해 모듈을 익스포트(Export)하지 않는 패키지들에 빈 이름공간을 추가해야 하나요?
[chai-http](https://github.com/chaijs/chai-http) 패키지와 같은 몇몇 패키지들은 함수를 익스포트(Export)합니다.
이런 패키지들을 `import * as foo from "foo";` 와 같이 임포트(Import)하면 다음과 같은 오류가 발생합니다.
> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct
이 오류는 함수의 이름과 똑같은 빈 이름공간(Namespace)을 정의해서 없앨 수 있으나, 좋은 방법은 아닙니다.
[스택오버플로(Stack Overflow)의 이 질문의 답변](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this)이 이 문제와 관련되어 자주 언급됩니다.
`import foo = require("foo");` 를 사용하여 모듈을 임포트(Import)하거나, 환경에서 ES6 모듈 변환(Module interop)을 지원한다면 `--allowSyntheticDefaultImports` 와 함께 `import foo from "foo";` 같은 디폴트 임포트(Default import)를 사용하는 것이 더 나은 방법입니다.
## 라이센스
이 프로젝트는 MIT license 가 적용되어 있습니다.
각 자료형 정의(Type definition) 파일들의 저작권은 각 기여자들에게 있으며, 기여자들은 해당 자료형 정의(Type definition) 파일들의 맨 위에 나열되어 있습니다.
[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon)
+1 -1
View File
@@ -6,7 +6,7 @@
Also see the [definitelytyped.org](http://definitelytyped.org) website, although information in this README is more up-to-date.
*[You can also read this README in Spanish!](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md)*
*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) and [Korean!](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md)*
## What are declaration files?
+12
View File
@@ -678,6 +678,12 @@
"sourceRepoURL": "https://github.com/facebook/immutable-js",
"asOfVersion": "3.8.7"
},
{
"libraryName": "interactjs",
"typingsPackageName": "interact.js",
"sourceRepoURL": "https://github.com/taye/interact.js",
"asOfVersion": "1.3.0"
},
{
"libraryName": "inversify",
"typingsPackageName": "inversify",
@@ -1224,6 +1230,12 @@
"sourceRepoURL": "https://github.com/tomkp/react-split-pane",
"asOfVersion": "0.1.67"
},
{
"libraryName": "react-svg",
"typingsPackageName": "react-svg",
"sourceRepoURL": "https://github.com/tanem/react-svg",
"asOfVersion": "5.0.0"
},
{
"libraryName": "realm",
"typingsPackageName": "realm",
+3
View File
@@ -67,6 +67,9 @@ var mongoConnectionString = "mongodb://127.0.0.1/agenda";
await job.save();
const jobs = await agenda.jobs({ name: 'printAnalyticsReport' });
jobs.forEach((job) => {
job.save();
});
let numRemoved = await agenda.cancel({ name: 'printAnalyticsReport' });
+1 -1
View File
@@ -96,7 +96,7 @@ declare class Agenda extends EventEmitter {
* Find all Jobs matching `query` and pass same back in cb().
* @param query
*/
jobs<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(query: any): Promise<void>;
jobs<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(query: any): Promise<Agenda.Job<T>[]>;
/**
* Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want
+23
View File
@@ -0,0 +1,23 @@
import agent = require('agent-base');
agent(); // $ExpectType Agent
agent({ timeout: 1000 }); // $ExpectType Agent
agent((req, opts) => {}); // $ExpectType Agent
agent((req, opts) => {}, { timeout: 1000 }); // $ExpectType Agent
agent(async (req, opts) => {}); // $ExpectType Agent
agent(async (req, opts) => {}, { timeout: 1000 }); // $ExpectType Agent
agent(0); // $ExpectError
agent(1); // $ExpectError
agent(''); // $ExpectError
agent(true); // $ExpectError
agent(null); // $ExpectError
agent((req, opts) => {}, 0); // $ExpectError
agent((req, opts) => {}, 1); // $ExpectError
agent((req, opts) => {}, ''); // $ExpectError
agent((req, opts) => {}, true); // $ExpectError
agent((req, opts) => {}, null); // $ExpectError
agent((req, opts) => {}, (req, opts) => {}); // $ExpectError
+44
View File
@@ -0,0 +1,44 @@
// Type definitions for agent-base 4.2
// Project: https://github.com/TooTallNate/node-agent-base#readme
// Definitions by: Christopher Quadflieg <https://github.com/Shinigami92>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { EventEmitter } from 'events';
declare namespace Agent {
type AgentCallback = (
req?: any,
opts?: {
secureEndpoint: boolean;
}
) => void;
interface AgentOptions {
timeout?: number;
host?: string;
port?: number;
[key: string]: any;
}
interface Agent extends EventEmitter {
_promisifiedCallback: boolean;
timeout: number | null;
options?: AgentOptions;
callback: AgentCallback;
addRequest: (req?: any, opts?: any) => void;
freeSocket: (socket: any, opts: any) => void;
}
}
/**
* Base `http.Agent` implementation.
* No pooling/keep-alive is implemented by default.
*/
declare function Agent(opts?: Agent.AgentOptions): Agent.Agent;
declare function Agent(
callback: Agent.AgentCallback,
opts?: Agent.AgentOptions
): Agent.Agent;
export = Agent;
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"agent-base-tests.ts"
]
}
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://github.com/goatslacker/alt
// Definitions by: Michael Shearer <https://github.com/Shearerbeard>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
// TypeScript Version: 2.8
///<reference types="react"/>
+1 -1
View File
@@ -32,7 +32,7 @@ new Stream({
highWaterMark: 1,
decodeStrings: true,
objectMode: true,
destroy: (error?: Error) => {
destroy: (error: Error | null) => {
return 'handle error';
},
final: (callback: (error?: Error) => void) => {
+2 -2
View File
@@ -22,7 +22,7 @@ declare module 'angular' {
* This is an experimental technology
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/badge
*/
badge?: USVString;
badge?: string;
/**
* The data read-only property of the Notification interface returns a structured clone of the notification's data,
@@ -40,7 +40,7 @@ declare module 'angular' {
* Note: This feature is available in Web Workers.
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/image
*/
image?: USVString;
image?: string;
/**
* The renotify read-only property of the Notification interface specifies whether the user should be notified after a
@@ -24,6 +24,8 @@ angular.module("myApp").controller("helloController", function (gettextCatalog:
angular.module("myApp").controller("helloController", function (gettextCatalog: angular.gettext.gettextCatalog) {
var myString2: string = gettextCatalog.getPlural(3, "Bird", "Birds");
var myStringWithScope: string = gettextCatalog.getPlural(4, "{{color}} Bird", "{{color}} Birds", {color: 'Blue'});
var myStringWithContext: string = gettextCatalog.getPlural(5, "pick", "picks", null, 'noun');
});
angular.module("myApp").controller("helloController", function (gettextCatalog: angular.gettext.gettextCatalog) {
+2 -2
View File
@@ -1,4 +1,4 @@
// Type definitions for angular-gettext v2.1.0
// Type definitions for angular-gettext v2.1.1
// Project: https://angular-gettext.rocketeer.be/
// Definitions by: Ákos Lukács <https://github.com/AkosLukacs>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -66,7 +66,7 @@ declare module 'angular' {
getString(string: string, scope?: any, context?: string): string;
/** Translate a plural string with the given context. */
getPlural(n: number, string: string, stringPlural: string, context?: any): string;
getPlural(n: number, string: string, stringPlural: string, scope?: any, context?: string): string;
/** Load a set of translation strings from a given URL.This should be a JSON catalog generated with grunt-angular-gettext. More details https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ */
loadRemote(url: string): ng.IHttpPromise<any>;
+17 -1
View File
@@ -87,7 +87,6 @@ timeoutService.verifyNoPendingTasks();
let intervalService: ng.IIntervalService;
let intervalServiceTimeActuallyAdvanced: number;
intervalServiceTimeActuallyAdvanced = intervalService.flush();
intervalServiceTimeActuallyAdvanced = intervalService.flush(1234);
///////////////////////////////////////
@@ -1516,6 +1515,23 @@ requestHandler.respond(404, { key: 'value' });
requestHandler.respond(404, { key: 'value' }, { header: 'value' });
requestHandler.respond(404, { key: 'value' }, { header: 'value' }, 'responseText');
///////////////////////////////////////
// IFlushPendingTasksService
///////////////////////////////////////
let $flushPendingTasks: ng.IFlushPendingTasksService;
$flushPendingTasks();
$flushPendingTasks(42);
///////////////////////////////////////
// IVerifyNoPendingTasksService
///////////////////////////////////////
let $verifyNoPendingTasks: ng.IVerifyNoPendingTasksService;
$verifyNoPendingTasks();
$verifyNoPendingTasks('task type');
///////////////////////////////////////
// browserTrigger
///////////////////////////////////////
browserTrigger(document.body, 'click');
browserTrigger(angular.element(document.body), 'click');
browserTrigger(angular.element(document.body), 'click', { which: 1, keys: ['ctrl'] });
+111 -7
View File
@@ -1,6 +1,8 @@
// Type definitions for Angular JS (ngMock, ngMockE2E module) 1.6
// Type definitions for Angular JS (ngMock, ngMockE2E module) 1.7
// Project: http://angularjs.org
// Definitions by: Diego Vilar <https://github.com/diegovilar>, Tony Curtis <https://github.com/daltin>
// Definitions by: Diego Vilar <https://github.com/diegovilar>
// Tony Curtis <https://github.com/daltin>
// Georgii Dolzhykov <https://github.com/thorn0>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
@@ -59,7 +61,38 @@ declare module 'angular' {
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface ITimeoutService {
/**
* **Deprecated** since version 1.7.3. (Use `$flushPendingTasks` instead.)
*
* ---
* Flushes the queue of pending tasks.
*
* _This method is essentially an alias of `$flushPendingTasks`._
*
* > For historical reasons, this method will also flush non-`$timeout` pending tasks, such as
* > `$q` promises and tasks scheduled via `$applyAsync` and `$evalAsync`.
*
* @param delay - The maximum timeout amount to flush up until.
*/
flush(delay?: number): void;
/**
* **Deprecated** since version 1.7.3. (Use `$verifyNoPendingTasks` instead.)
*
* ---
* Verifies that there are no pending tasks that need to be flushed. It throws an error if there
* are still pending tasks.
*
* _This method is essentially an alias of `$verifyNoPendingTasks` (called with no arguments)._
*
* > For historical reasons, this method will also verify non-`$timeout` pending tasks, such as
* > pending `$http` requests, in-progress `$route` transitions, unresolved `$q` promises and
* > tasks scheduled via `$applyAsync` and `$evalAsync`.
* >
* > It is recommended to use `$verifyNoPendingTasks` instead, which additionally supports
* > verifying a specific type of tasks. For example, you can verify there are no pending
* > timeouts with `$verifyNoPendingTasks('$timeout')`.
*/
verifyNoPendingTasks(): void;
}
@@ -69,7 +102,13 @@ declare module 'angular' {
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface IIntervalService {
flush(millis?: number): number;
/**
* Runs interval tasks scheduled to be run in the next `millis` milliseconds.
*
* @param millis - The maximum timeout amount to flush up until.
* @return The amount of time moved forward.
*/
flush(millis: number): number;
}
///////////////////////////////////////////////////////////////////////////
@@ -413,6 +452,65 @@ declare module 'angular' {
whenRoute(method: string, url: string): mock.IRequestHandler;
}
///////////////////////////////////////////////////////////////////////////
// FlushPendingTasksService
// see https://docs.angularjs.org/api/ngMock/service/$flushPendingTasks
///////////////////////////////////////////////////////////////////////////
interface IFlushPendingTasksService {
/**
* Flushes all currently pending tasks and executes the corresponding callbacks.
*
* Optionally, you can also pass a `delay` argument to only flush tasks that are scheduled to be
* executed within `delay` milliseconds. Currently, `delay` only applies to timeouts, since all
* other tasks have a delay of 0 (i.e. they are scheduled to be executed as soon as possible, but
* still asynchronously).
*
* If no delay is specified, it uses a delay such that all currently pending tasks are flushed.
*
* The types of tasks that are flushed include:
*
* - Pending timeouts (via `$timeout`).
* - Pending tasks scheduled via `$applyAsync`.
* - Pending tasks scheduled via `$evalAsync`.
* These include tasks scheduled via `$evalAsync()` indirectly (such as `$q` promises).
*
* > Periodic tasks scheduled via `$interval` use a different queue and are not flushed by
* > `$flushPendingTasks()`. Use `$interval.flush(millis)` instead.
*
* @param millis - The number of milliseconds to flush.
*/
(delay?: number): void;
}
///////////////////////////////////////////////////////////////////////////
// VerifyNoPendingTasksService
// see https://docs.angularjs.org/api/ngMock/service/$verifyNoPendingTasks
///////////////////////////////////////////////////////////////////////////
interface IVerifyNoPendingTasksService {
/**
* Verifies that there are no pending tasks that need to be flushed. It throws an error if there
* are still pending tasks.
*
* You can check for a specific type of tasks only, by specifying a `taskType`.
*
* Available task types:
*
* - `$timeout`: Pending timeouts (via `$timeout`).
* - `$http`: Pending HTTP requests (via `$http`).
* - `$route`: In-progress route transitions (via `$route`).
* - `$applyAsync`: Pending tasks scheduled via `$applyAsync`.
* - `$evalAsync`: Pending tasks scheduled via `$evalAsync`.
* These include tasks scheduled via `$evalAsync()` indirectly (such as `$q` promises).
*
* > Periodic tasks scheduled via `$interval` use a different queue and are not taken into
* > account by `$verifyNoPendingTasks()`. There is currently no way to verify that there are no
* > pending `$interval` tasks.
*
* @param taskType - The type of tasks to check for.
*/
(taskType?: string): void;
}
///////////////////////////////////////////////////////////////////////////
// AnimateService
// see https://docs.angularjs.org/api/ngMock/service/$animate
@@ -513,6 +611,11 @@ declare module 'angular' {
* for keyboard events (keydown, keypress, and keyup).
*/
charcode?: number;
/**
* [data](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent/data) for
* [CompositionEvents](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent).
*/
data?: string;
/**
* The elapsedTime for
* [TransitionEvent](https://developer.mozilla.org/docs/Web/API/TransitionEvent)
@@ -566,10 +669,11 @@ declare global {
* This is a global (window) function that is only available when the `ngMock` module is included.
* It can be used to trigger a native browser event on an element, which is useful for unit testing.
*
* @param element Either a wrapped jQuery/jqLite node or a DOM element
* @param eventType Optional event type. If none is specified, the function tries to determine
* the right event type for the element, e.g. `change` for `input[text]`.
* @param eventData An optional object which contains additional event data used when creating the event.
* @param element Either a wrapped jQuery/jqLite node or a DOM element.
* @param eventType Optional event type. If none is specified, the function tries to determine the
* right event type for the element, e.g. `change` for `input[text]`.
* @param eventData An optional object which contains additional event data used when creating the
* event.
*/
function browserTrigger(
element: JQuery | Element,
@@ -39,6 +39,21 @@ $routeProvider
return "I return a string"
}
})
.when('/projects/:projectId/dashboard6', {
resolve: {
foo: () => 'foo',
bar: () => 'bar',
},
resolveAs: 'baz',
resolveRedirectTo: [
'$http',
($http: ng.IHttpService) => $http.get('/is-admin').then(() => '/admin/lounge', () => undefined),
],
})
.when('/projects/:projectId/dashboard7', {
reloadOnUrl: false,
resolveRedirectTo: () => (Math.random() < 0.5) ? '/some/route' : undefined,
})
.otherwise({ redirectTo: '/' })
.otherwise({ redirectTo: ($routeParams?: ng.route.IRouteParamsService, $locationPath?: string, $locationSearch?: any) => "" })
.otherwise("/");
+94 -27
View File
@@ -1,6 +1,7 @@
// Type definitions for Angular JS (ngRoute module) 1.3
// Type definitions for Angular JS (ngRoute module) 1.7
// Project: http://angularjs.org
// Definitions by: Jonathan Park <https://github.com/park9140>
// George Kalpakas <https://github.com/gkalpak>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -52,7 +53,7 @@ declare module 'angular' {
*/
interface IRoute {
/**
* {(string|function()=}
* {(string|Function)=}
* Controller fn that should be associated with newly created scope or the name of a registered controller if passed as a string.
*/
controller?: string | InlineAnnotatedFunction;
@@ -61,56 +62,122 @@ declare module 'angular' {
*/
controllerAs?: string;
/**
* Undocumented?
*/
name?: string;
/**
* {string=|function()=}
* {(string|Function)=}
* Html template as a string or a function that returns an html template as a string which should be used by ngView or ngInclude directives. This property takes precedence over templateUrl.
*
* If template is a function, it will be called with the following parameters:
*
* {Array.<Object>} - route parameters extracted from the current $location.path() by applying the current route
*/
template?: string | { ($routeParams?: angular.route.IRouteParamsService): string; }
template?: string | { ($routeParams?: IRouteParamsService): string; }
/**
* {string=|function()=}
* {(string|Function)=}
* Path or function that returns a path to an html template that should be used by ngView.
*
* If templateUrl is a function, it will be called with the following parameters:
*
* {Array.<Object>} - route parameters extracted from the current $location.path() by applying the current route
*/
templateUrl?: string | { ($routeParams?: angular.route.IRouteParamsService): string; }
templateUrl?: string | { ($routeParams?: IRouteParamsService): string; }
/**
* {Object.<string, function>=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired. The map object is:
* {Object.<string, Function>=}
* An optional map of dependencies which should be injected into the controller. If any of these
* dependencies are promises, the router will wait for them all to be resolved or one to be rejected before
* the controller is instantiated.
* If all the promises are resolved successfully, the values of the resolved promises are injected and
* `$routeChangeSuccess` event is fired. If any of the promises are rejected the `$routeChangeError` event
* is fired.
* For easier access to the resolved dependencies from the template, the `resolve` map will be available on
* the scope of the route, under `$resolve` (by default) or a custom name specified by the `resolveAs`
* property (see below). This can be particularly useful, when working with components as route templates.
*
* - key - {string}: a name of a dependency to be injected into the controller.
* - factory - {string|function}: If string then it is an alias for a service. Otherwise if function, then it is injected and the return value is treated as the dependency. If the result is a promise, it is resolved before its value is injected into the controller. Be aware that ngRoute.$routeParams will still refer to the previous route within these resolve functions. Use $route.current.params to access the new route parameters, instead.
* > **Note:** If your scope already contains a property with this name, it will be hidden or overwritten.
* > Make sure, you specify an appropriate name for this property, that does not collide with other
* > properties on the scope.
*
* The map object is:
*
* - `key` – `{string}`: a name of a dependency to be injected into the controller.
* - `factory` - `{string|Function}`: If `string` then it is an alias for a service. Otherwise if function,
* then it is called with `$injector#invoke()` and the return value is treated as the dependency. If the
* result is a promise, it is resolved before its value is injected into the controller. Be aware that
* `ngRoute.$routeParams` will still refer to the previous route within these resolve functions. Use
* `$route.current.params` to access the new route parameters, instead.
*/
resolve?: { [key: string]: any };
/**
* {(string|function())=}
* Value to update $location path with and trigger route redirection.
*
* If redirectTo is a function, it will be called with the following parameters:
*
* - {Object.<string>} - route parameters extracted from the current $location.path() by applying the current route templateUrl.
* - {string} - current $location.path()
* - {Object} - current $location.search()
* - The custom redirectTo function is expected to return a string which will be used to update $location.path() and $location.search().
* {string=}
* The name under which the `resolve` map will be available on the scope of the route. If omitted, defaults
* to `$resolve`.
*/
redirectTo?: string | { ($routeParams?: angular.route.IRouteParamsService, $locationPath?: string, $locationSearch?: any): string };
resolveAs?: string;
/**
* Reload route when only $location.search() or $location.hash() changes.
* {(string|Function)=}
* Value to update `$location` path with and trigger route redirection.
*
* This option defaults to true. If the option is set to false and url in the browser changes, then $routeUpdate event is broadcasted on the root scope.
* If `redirectTo` is a function, it will be called with the following parameters:
*
* - `{Object.<string>}` - route parameters extracted from the current `$location.path()` by applying the
* current route templateUrl.
* - `{string}` - current `$location.path()`
* - `{Object}` - current `$location.search()`
*
* The custom `redirectTo` function is expected to return a string which will be used to update
* `$location.url()`. If the function throws an error, no further processing will take place and the
* `$routeChangeError` event will be fired.
*
* Routes that specify `redirectTo` will not have their controllers, template functions or resolves called,
* the `$location` will be changed to the redirect url and route processing will stop. The exception to this
* is if the `redirectTo` is a function that returns `undefined`. In this case the route transition occurs
* as though there was no redirection.
*/
redirectTo?: string | { ($routeParams?: IRouteParamsService, $locationPath?: string, $locationSearch?: any): string };
/**
* {Function=}
* A function that will (eventually) return the value to update `$location` URL with and trigger route
* redirection. In contrast to `redirectTo`, dependencies can be injected into `resolveRedirectTo` and the
* return value can be either a string or a promise that will be resolved to a string.
*
* Similar to `redirectTo`, if the return value is `undefined` (or a promise that gets resolved to
* `undefined`), no redirection takes place and the route transition occurs as though there was no
* redirection.
*
* If the function throws an error or the returned promise gets rejected, no further processing will take
* place and the `$routeChangeError` event will be fired.
*
* `redirectTo` takes precedence over `resolveRedirectTo`, so specifying both on the same route definition,
* will cause the latter to be ignored.
*/
resolveRedirectTo?: angular.Injectable<(...deps: any[]) => angular.IPromise<string | undefined> | string | undefined>;
/**
* {boolean=true}
* Reload route when any part of the URL changes (including the path) even if the new URL maps to the same
* route.
*
* If the option is set to `false` and the URL in the browser changes, but the new URL maps to the same
* route, then a `$routeUpdate` event is broadcasted on the root scope (without reloading the route).
*
* Defaults to `true`.
*/
reloadOnUrl?: boolean;
/**
* {boolean=true}
* Reload route when only `$location.search()` or `$location.hash()` changes.
*
* If the option is set to `false` and the URL in the browser changes, then a `$routeUpdate` event is
* broadcasted on the root scope (without reloading the route).
*
* > Note: This option has no effect if `reloadOnUrl` is set to `false`.
*
* Defaults to `true`.
*/
reloadOnSearch?: boolean;
/**
* Match routes without being case sensitive
* {boolean=false}
* Match routes without being case sensitive.
* If the option is set to `true`, then the particular route can be matched without being case sensitive.
*
* This option defaults to false. If the option is set to true, then the particular route can be matched without being case sensitive
* Defaults to `false`.
*/
caseInsensitiveMatch?: boolean;
}
+4 -3
View File
@@ -731,11 +731,12 @@ function test_angular_forEach() {
this.push(`${key}: ${value}`);
}, log);
// expect(log).toEqual(['name: misko', 'gender: male']);
// $ExpectType NodeListOf<HTMLImageElement>
angular.forEach(document.getElementsByTagName('img'), (value, key, obj) => {
// TODO: Set minimum version to ts3.1 where this is always HTMLCollectionOf
type Collection = NodeListOf<HTMLImageElement> | HTMLCollectionOf<HTMLImageElement>;
const collection: Collection = angular.forEach(document.getElementsByTagName('img'), (value, key, obj) => {
value; // $ExpectType HTMLImageElement
key; // $ExpectType number
obj; // $ExpectType NodeListOf<HTMLImageElement>
const collection: Collection = obj;
});
// $ExpectType number[]
angular.forEach([1, 2, 3], (value, key, obj) => {
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://github.com/Khan/aphrodite
// Definitions by: Alexey Svetliakov <https://github.com/asvetliakov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
// TypeScript Version: 2.8
import * as CSS from "csstype";
+10
View File
@@ -96,3 +96,13 @@ console.log(
RETURN u
`.toArray()
);
const view = db._view("yolo")!;
view.properties({
locale: "C",
commit: {
consolidate: {
bytes: { segmentThreshold: 20 }
}
}
});
+66 -9
View File
@@ -837,11 +837,68 @@ declare namespace ArangoDB {
// Views
interface View {
// TODO
[key: string]: any;
interface ArangoSearchView {
_dbName: string;
_id: string;
name(): string;
type(): ViewType;
rename(newName: string): void;
properties(
newProperties?: ArangoSearchViewPropertiesOptions
): ArangoSearchViewProperties;
}
interface ArangoSearchViewConsolidate {
threshold: number;
segmentThreshold: number;
}
interface ArangoSearchViewCollectionLink {
analyzers?: string[];
fields?: { [key: string]: ArangoSearchViewCollectionLink | undefined };
includeAllFields?: boolean;
trackListPositions?: boolean;
storeValues?: "none" | "id";
}
interface ArangoSearchViewProperties {
id: string;
name: string;
type: "arangosearch";
commit: {
cleanupIntervalStep: number;
commitIntervalMsec: number;
consolidate: {
bytes?: ArangoSearchViewConsolidate;
bytes_accum?: ArangoSearchViewConsolidate;
count?: ArangoSearchViewConsolidate;
fill?: ArangoSearchViewConsolidate;
};
};
locale: string;
links: {
[key: string]: ArangoSearchViewCollectionLink | undefined;
};
}
interface ArangoSearchViewPropertiesOptions {
locale?: string;
commit?: {
consolidate?:
| "none"
| {
count?: Partial<ArangoSearchViewConsolidate>;
bytes?: Partial<ArangoSearchViewConsolidate>;
bytes_accum?: Partial<ArangoSearchViewConsolidate>;
fill?: Partial<ArangoSearchViewConsolidate>;
};
commitIntervalMsec?: number;
cleanupIntervalStep?: number;
};
links?: {
[key: string]: ArangoSearchViewCollectionLink | undefined;
};
}
type ViewProperties = object; // TODO
// Global
@@ -923,13 +980,13 @@ declare namespace ArangoDB {
): DocumentMetadata;
// Views
_view(name: string): View | null;
_views(): View[];
_view(name: string): ArangoSearchView | null;
_views(): ArangoSearchView[];
_createView(
name: string,
type: ViewType,
properties: ViewProperties
): View;
properties: ArangoSearchViewPropertiesOptions
): ArangoSearchView;
_dropView(name: string): void;
// Global
@@ -1392,7 +1449,7 @@ declare module "@arangodb/foxx/router" {
}
declare module "@arangodb/foxx/graphql" {
import { GraphQLSchema, formatError } from "graphql";
import { formatError, GraphQLSchema } from "graphql";
type GraphQLModule = object;
type GraphQLFormatErrorFunction = typeof formatError;
interface GraphQLOptions {
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://github.com/thejameskyle/assert-equal-jsx
// Definitions by: Josh Toft <https://github.com/seryl>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
// TypeScript Version: 2.8
import * as React from 'react';
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://bitbucket.org/atlassian/atlaskit-mk-2/
// Definitions by: Jimmy Luong <https://github.com/dijimsta>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
// TypeScript Version: 2.8
import {
Component,
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://bitbucket.org/atlassian/atlaskit-mk-2/src/master/
// Definitions by: Lee Standen <https://github.com/lstanden>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
// TypeScript Version: 2.8
import { Component, HTMLAttributes, FocusEvent } from 'react';
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://bitbucket.org/atlassian/atlaskit-mk-2/
// Definitions by: Lee Standen <https://github.com/lstanden>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
// TypeScript Version: 2.8
import { ReactElement, Component } from 'react';
export default class InlineEdit extends Component<StatefulProps> {}
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://bitbucket.org/atlassian/atlaskit-mk-2/src/master/
// Definitions by: Lee Standen <https://github.com/lstanden>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
// TypeScript Version: 2.8
import { Component, ReactNode } from 'react';
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://bitbucket.org/atlassian/atlaskit-mk-2/src/master/
// Definitions by: Lee Standen <https://github.com/lstanden>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
// TypeScript Version: 2.8
import { Component, ReactNode, SyntheticEvent } from 'react';
+3 -1
View File
@@ -9,7 +9,9 @@ webAuth.authorize({
audience: 'https://mystore.com/api/v2',
scope: 'read:order write:order',
responseType: 'token',
redirectUri: 'https://example.com/auth/callback'
redirectUri: 'https://example.com/auth/callback',
language: 'en',
prompt: 'login',
});
webAuth.parseHash((err, authResult) => {
+2
View File
@@ -760,6 +760,8 @@ export interface AuthorizeOptions {
nonce?: string;
scope?: string;
audience?: string;
language?: string;
prompt?: string;
}
export interface CheckSessionOptions extends AuthorizeOptions {
+50 -22
View File
@@ -479,6 +479,7 @@ str = cloudwatchLogsDecodedData.messageType;
str = cloudwatchLogsDecodedData.logEvents[0].id;
num = cloudwatchLogsDecodedData.logEvents[0].timestamp;
str = cloudwatchLogsDecodedData.logEvents[0].message;
str = cloudwatchLogsDecodedData.logEvents[0].extractedFields!["example"];
/* ClientContext */
clientContextClient = clientCtx.client;
@@ -585,7 +586,9 @@ const CloudFrontRequestEvent: AWSLambda.CloudFrontRequestEvent = {
{
cf: {
config: {
distributionDomainName: "d123.cloudfront.net",
distributionId: "EDFDVBD6EXAMPLE",
eventType: "viewer-request",
requestId: "MRVMF7KydIvxMWfJIglgwHQwZsbG2IhRJ07sn9AkKUFSHS9EXAMPLE=="
},
request: {
@@ -654,7 +657,9 @@ const CloudFrontResponseEvent: AWSLambda.CloudFrontResponseEvent = {
{
cf: {
config: {
distributionDomainName: "d123.cloudfront.net",
distributionId: "EDFDVBD6EXAMPLE",
eventType: "viewer-response",
requestId: "xGN7KWpVEmB9Dp7ctcVFQC4E-nrcOcEKS3QyAez--06dV7TEXAMPLE=="
},
request: {
@@ -737,7 +742,7 @@ context.fail(error);
context.fail(str);
/* Handler */
let handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => { };
const handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => { };
/* In node8.10 runtime, handlers may return a promise for the result value, so existing async
* handlers that return Promise<void> before calling the callback will now have a `null` result.
@@ -745,7 +750,7 @@ let handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AW
* since the upgrade effort should be pretty low in most cases, and it points them at a nicer solution.
*/
// $ExpectError
let legacyAsyncHandler: AWSLambda.APIGatewayProxyHandler = async (
const legacyAsyncHandler: AWSLambda.APIGatewayProxyHandler = async (
event: AWSLambda.APIGatewayProxyEvent,
context: AWSLambda.Context,
cb: AWSLambda.Callback<AWSLambda.APIGatewayProxyResult>,
@@ -753,7 +758,7 @@ let legacyAsyncHandler: AWSLambda.APIGatewayProxyHandler = async (
cb(null, { statusCode: 200, body: 'No longer valid' });
};
let node8AsyncHandler: AWSLambda.APIGatewayProxyHandler = async (
const node8AsyncHandler: AWSLambda.APIGatewayProxyHandler = async (
event: AWSLambda.APIGatewayProxyEvent,
context: AWSLambda.Context,
cb: AWSLambda.Callback<AWSLambda.APIGatewayProxyResult>,
@@ -761,7 +766,7 @@ let node8AsyncHandler: AWSLambda.APIGatewayProxyHandler = async (
return { statusCode: 200, body: 'Is now valid!' };
};
let inferredHandler: AWSLambda.S3Handler = (event, context, cb) => {
const inferredHandler: AWSLambda.S3Handler = (event, context, cb) => {
// $ExpectType S3Event
event;
str = event.Records[0].eventName;
@@ -778,35 +783,35 @@ let inferredHandler: AWSLambda.S3Handler = (event, context, cb) => {
};
// Test using default Callback type still works.
let defaultCallbackHandler: AWSLambda.APIGatewayProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => { };
const defaultCallbackHandler: AWSLambda.APIGatewayProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => { };
// Specific types
let s3Handler: AWSLambda.S3Handler = (event: AWSLambda.S3Event, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => {};
// Test old name
let s3CreateHandler: AWSLambda.S3Handler = (event: AWSLambda.S3CreateEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => {};
const s3CreateHandler: AWSLambda.S3Handler = (event: AWSLambda.S3CreateEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => {};
s3Handler = s3CreateHandler;
let dynamoDBStreamHandler: AWSLambda.DynamoDBStreamHandler = (event: AWSLambda.DynamoDBStreamEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => {};
const dynamoDBStreamHandler: AWSLambda.DynamoDBStreamHandler = (event: AWSLambda.DynamoDBStreamEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => {};
let snsHandler: AWSLambda.SNSHandler = (event: AWSLambda.SNSEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => {};
const snsHandler: AWSLambda.SNSHandler = (event: AWSLambda.SNSEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => {};
let cognitoUserPoolHandler: AWSLambda.CognitoUserPoolTriggerHandler = (event: AWSLambda.CognitoUserPoolEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => {};
const cognitoUserPoolHandler: AWSLambda.CognitoUserPoolTriggerHandler = (event: AWSLambda.CognitoUserPoolEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => {};
let cloudFormationCustomResourceHandler: AWSLambda.CloudFormationCustomResourceHandler =
const cloudFormationCustomResourceHandler: AWSLambda.CloudFormationCustomResourceHandler =
(event: AWSLambda.CloudFormationCustomResourceEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => {};
let cloudWatchLogsHandler: AWSLambda.CloudWatchLogsHandler = (event: AWSLambda.CloudWatchLogsEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => {};
const cloudWatchLogsHandler: AWSLambda.CloudWatchLogsHandler = (event: AWSLambda.CloudWatchLogsEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => {};
let scheduledHandler: AWSLambda.ScheduledHandler = (event: AWSLambda.ScheduledEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => {};
const scheduledHandler: AWSLambda.ScheduledHandler = (event: AWSLambda.ScheduledEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => {};
let apiGtwProxyHandler: AWSLambda.APIGatewayProxyHandler = (event: AWSLambda.APIGatewayProxyEvent, context: AWSLambda.Context, cb: AWSLambda.APIGatewayProxyCallback) => { };
// Test old names
let proxyHandler: AWSLambda.ProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.ProxyCallback) => { };
const proxyHandler: AWSLambda.ProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.ProxyCallback) => { };
apiGtwProxyHandler = proxyHandler;
let codePipelineHandler: AWSLambda.CodePipelineHandler = (event: AWSLambda.CodePipelineEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => {};
const codePipelineHandler: AWSLambda.CodePipelineHandler = (event: AWSLambda.CodePipelineEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => {};
let cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLambda.CloudFrontRequestEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontRequestCallback) => {
const cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLambda.CloudFrontRequestEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontRequestCallback) => {
cb();
cb(null);
cb(new Error(''));
@@ -816,14 +821,14 @@ let cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLa
cb(null, { });
};
let cloudFrontResponseHandler: AWSLambda.CloudFrontResponseHandler = (event: AWSLambda.CloudFrontResponseEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontResponseCallback) => { };
const cloudFrontResponseHandler: AWSLambda.CloudFrontResponseHandler = (event: AWSLambda.CloudFrontResponseEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontResponseCallback) => { };
let customAuthorizerHandler: AWSLambda.CustomAuthorizerHandler = (event: AWSLambda.CustomAuthorizerEvent, context: AWSLambda.Context, cb: AWSLambda.CustomAuthorizerCallback) => { };
const customAuthorizerHandler: AWSLambda.CustomAuthorizerHandler = (event: AWSLambda.CustomAuthorizerEvent, context: AWSLambda.Context, cb: AWSLambda.CustomAuthorizerCallback) => { };
interface CustomEvent { eventString: string; eventBool: boolean; }
interface CustomResult { resultString: string; resultBool?: boolean; }
type CustomCallback = AWSLambda.Callback<CustomResult>;
let customHandler: AWSLambda.Handler<CustomEvent, CustomResult> = (event, context, cb) => {
const customHandler: AWSLambda.Handler<CustomEvent, CustomResult> = (event, context, cb) => {
// $ExpectType CustomEvent
event;
str = event.eventString;
@@ -837,9 +842,9 @@ let customHandler: AWSLambda.Handler<CustomEvent, CustomResult> = (event, contex
cb(null, { resultString: bool });
};
let kinesisStreamHandler: AWSLambda.KinesisStreamHandler = (event: AWSLambda.KinesisStreamEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => { };
const kinesisStreamHandler: AWSLambda.KinesisStreamHandler = (event: AWSLambda.KinesisStreamEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => { };
let SQSMessageHandler: AWSLambda.SQSHandler = (event: AWSLambda.SQSEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => { };
const SQSMessageHandler: AWSLambda.SQSHandler = (event: AWSLambda.SQSEvent, context: AWSLambda.Context, cb: AWSLambda.Callback<void>) => { };
// See https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-sqs
const SQSEvent: AWSLambda.SQSEvent = {
@@ -863,7 +868,7 @@ const SQSEvent: AWSLambda.SQSEvent = {
]
};
let SQSMessageLegacyAsyncHandler: AWSLambda.SQSHandler = async (
const SQSMessageLegacyAsyncHandler: AWSLambda.SQSHandler = async (
event: AWSLambda.SQSEvent,
context: AWSLambda.Context,
cb: AWSLambda.Callback<void>,
@@ -882,7 +887,7 @@ let SQSMessageLegacyAsyncHandler: AWSLambda.SQSHandler = async (
cb(new Error());
};
let SQSMessageNode8AsyncHandler: AWSLambda.SQSHandler = async (
const SQSMessageNode8AsyncHandler: AWSLambda.SQSHandler = async (
event: AWSLambda.SQSEvent,
context: AWSLambda.Context
) => {
@@ -895,3 +900,26 @@ let SQSMessageNode8AsyncHandler: AWSLambda.SQSHandler = async (
str = context.functionName;
return;
};
const firehoseEventHandler: AWSLambda.FirehoseTransformationHandler = (
event: AWSLambda.FirehoseTransformationEvent,
context: AWSLambda.Context,
callback: AWSLambda.FirehoseTransformationCallback
) => {
// $ExpectType FirehoseTransformationEvent
event;
str = event.records[0].recordId;
// $ExpectType Context
context;
str = context.functionName;
callback(null, {
records: [
{
recordId: event.records[0].recordId,
result: 'Ok' as AWSLambda.FirehoseRecordTransformationStatus,
data: 'eyJmb28iOiJiYXIifQ==',
}
]
});
};
+77 -30
View File
@@ -19,6 +19,8 @@
// Chris Redekop <https://github.com/repl-chris>
// Aneil Mallavarapu <https://github.com/aneilbaboo>
// Jeremy Nagel <https://github.com/jeznag>
// Louis Larry <https://github.com/louislarry>
// Daniel Papukchiev <https://github.com/dpapukchiev>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -211,27 +213,27 @@ export type S3CreateEvent = S3Event; // old name
export interface CognitoUserPoolTriggerEvent {
version: number;
triggerSource:
| "PreSignUp_SignUp"
| "PostConfirmation_ConfirmSignUp"
| "PreAuthentication_Authentication"
| "PostAuthentication_Authentication"
| "CustomMessage_SignUp"
| "CustomMessage_AdminCreateUser"
| "CustomMessage_ResendCode"
| "CustomMessage_ForgotPassword"
| "CustomMessage_UpdateUserAttribute"
| "CustomMessage_VerifyUserAttribute"
| "CustomMessage_Authentication"
| "DefineAuthChallenge_Authentication"
| "CreateAuthChallenge_Authentication"
| "VerifyAuthChallengeResponse_Authentication"
| "PreSignUp_AdminCreateUser"
| "PostConfirmation_ConfirmForgotPassword"
| "TokenGeneration_HostedAuth"
| "TokenGeneration_Authentication"
| "TokenGeneration_NewPasswordChallenge"
| "TokenGeneration_AuthenticateDevice"
| "TokenGeneration_RefreshTokens";
| "PreSignUp_SignUp"
| "PostConfirmation_ConfirmSignUp"
| "PreAuthentication_Authentication"
| "PostAuthentication_Authentication"
| "CustomMessage_SignUp"
| "CustomMessage_AdminCreateUser"
| "CustomMessage_ResendCode"
| "CustomMessage_ForgotPassword"
| "CustomMessage_UpdateUserAttribute"
| "CustomMessage_VerifyUserAttribute"
| "CustomMessage_Authentication"
| "DefineAuthChallenge_Authentication"
| "CreateAuthChallenge_Authentication"
| "VerifyAuthChallengeResponse_Authentication"
| "PreSignUp_AdminCreateUser"
| "PostConfirmation_ConfirmForgotPassword"
| "TokenGeneration_HostedAuth"
| "TokenGeneration_Authentication"
| "TokenGeneration_NewPasswordChallenge"
| "TokenGeneration_AuthenticateDevice"
| "TokenGeneration_RefreshTokens";
region: string;
userPoolId: string;
userName?: string;
@@ -240,8 +242,8 @@ export interface CognitoUserPoolTriggerEvent {
clientId: string;
};
request: {
userAttributes: {[key: string]: string};
validationData?: {[key: string]: string};
userAttributes: { [key: string]: string };
validationData?: { [key: string]: string };
codeParameter?: string;
usernameParameter?: string;
newDeviceUsed?: boolean;
@@ -251,8 +253,8 @@ export interface CognitoUserPoolTriggerEvent {
challengeMetaData?: string;
}>;
challengeName?: string;
privateChallengeParameters?: {[key: string]: string};
challengeAnswer?: {[key: string]: string};
privateChallengeParameters?: { [key: string]: string };
challengeAnswer?: { [key: string]: string };
};
response: {
autoConfirmUser?: boolean;
@@ -262,8 +264,8 @@ export interface CognitoUserPoolTriggerEvent {
challengeName?: string;
issueTokens?: boolean;
failAuthentication?: boolean;
publicChallengeParameters?: {[key: string]: string};
privateChallengeParameters?: {[key: string]: string};
publicChallengeParameters?: { [key: string]: string };
privateChallengeParameters?: { [key: string]: string };
challengeMetaData?: string;
answerCorrect?: boolean;
};
@@ -369,6 +371,7 @@ export interface CloudWatchLogsLogEvent {
id: string;
timestamp: number;
message: string;
extractedFields?: {[key: string]: string};
}
// Context
@@ -549,7 +552,7 @@ export interface CodePipelineEvent {
inputArtifacts: Artifact[];
outputArtifacts: Artifact[];
artifactCredentials: Credentials;
encryptionKey?: EncryptionKey & {type: 'KMS'};
encryptionKey?: EncryptionKey & { type: 'KMS' };
continuationToken?: string;
};
};
@@ -582,7 +585,9 @@ export interface CloudFrontRequest {
export interface CloudFrontEvent {
config: {
distributionDomainName: string;
distributionId: string;
eventType: 'origin-request' | 'origin-response' | 'viewer-request' | 'viewer-response';
requestId: string;
};
}
@@ -642,6 +647,47 @@ export interface KinesisStreamEvent {
Records: KinesisStreamRecord[];
}
// Kinesis Data Firehose Event
// https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-kinesis-firehose
// https://docs.aws.amazon.com/firehose/latest/dev/data-transformation.html
// https://aws.amazon.com/blogs/compute/amazon-kinesis-firehose-data-transformation-with-aws-lambda/
// Examples in the lambda blueprints
export interface FirehoseTransformationEvent {
invocationId: string;
deliveryStreamArn: string;
region: string;
records: FirehoseTransformationEventRecord[];
}
export interface FirehoseTransformationEventRecord {
recordId: string;
approximateArrivalTimestamp: number;
/** Base64 encoded */
data: string;
kinesisRecordMetadata?: FirehoseRecordMetadata;
}
export interface FirehoseRecordMetadata {
shardId: string;
partitionKey: string;
approximateArrivalTimestamp: string;
sequenceNumber: string;
subsequenceNumber: string;
}
export type FirehoseRecordTransformationStatus = 'Ok' | 'Dropped' | 'ProcessingFailed';
export interface FirehoseTransformationResultRecord {
recordId: string;
result: FirehoseRecordTransformationStatus;
/** Encode in Base64 */
data: string;
}
export interface FirehoseTransformationResult {
records: FirehoseTransformationResultRecord[];
}
// SQS
// https://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-function.html#supported-event-source-sqs
export interface SQSRecord {
@@ -654,7 +700,7 @@ export interface SQSRecord {
eventSource: string;
eventSourceARN: string;
awsRegion: string;
}
}
export interface SQSEvent {
Records: SQSRecord[];
@@ -754,7 +800,8 @@ export type CloudFrontResponseCallback = Callback<CloudFrontResponseResult>;
export type KinesisStreamHandler = Handler<KinesisStreamEvent, void>;
// TODO: Kinesis Firehose
export type FirehoseTransformationCallback = Callback<FirehoseTransformationResult>;
export type FirehoseTransformationHandler = Handler<FirehoseTransformationEvent, FirehoseTransformationResult>;
export type CustomAuthorizerHandler = Handler<CustomAuthorizerEvent, CustomAuthorizerResult>;
export type CustomAuthorizerCallback = Callback<CustomAuthorizerResult>;
+3 -3
View File
@@ -10,10 +10,10 @@ import { GeneratorOptions } from "@babel/generator";
import traverse, { Visitor, NodePath } from "@babel/traverse";
import template from "@babel/template";
import * as t from "@babel/types";
import { BabylonOptions } from "babylon";
import { ParseOptions } from "@babel/parser";
export {
BabylonOptions,
ParseOptions,
GeneratorOptions,
t as types,
template,
@@ -217,7 +217,7 @@ export interface TransformOptions {
*
* Default: `{}`
*/
parserOpts?: BabylonOptions | null;
parserOpts?: ParseOptions | null;
/**
* List of plugins to load and use
+3
View File
@@ -22,6 +22,9 @@
"@babel/generator": [
"babel__generator"
],
"@babel/parser": [
"babel__parser"
],
"@babel/template": [
"babel__template"
],
@@ -135,6 +135,15 @@ class MyView extends Marionette.View<MyModel> {
}
}
class MyOtherView extends MyView {
private readonly foo: string;
constructor(model: MyModel) {
super(model);
this.foo = 'bar';
}
}
class MainRegion extends Marionette.Region {
constructor() {
super();
@@ -185,10 +194,20 @@ class MyHtmlElRegion extends Marionette.Region {
}
}
class MyCollectionView extends Marionette.CollectionView<MyModel, MyView> {
class MyCollectionView extends Marionette.CollectionView<MyModel, MyView | MyOtherView> {
constructor() {
super();
this.childView = (model: MyModel) => {
if (model.get('isFoo')) {
return MyView;
}
return MyOtherView;
};
this.childView = MyView;
this.childViewEvents = {
render() {
console.log('a childView has been rendered');
@@ -282,7 +301,7 @@ function CollectionViewTests() {
cv.collection.add(new MyModel());
app.mainRegion.show(cv);
cv.emptyView = MyView;
const view: Marionette.CollectionView<MyModel, MyView> = cv.destroy();
const view: Marionette.CollectionView<MyModel, MyView | MyOtherView> = cv.destroy();
}
class MyController {
+4 -3
View File
@@ -3,7 +3,8 @@
// Definitions by: Zeeshan Hamid <https://github.com/zhamid>,
// Natan Vivo <https://github.com/nvivo>,
// Sven Tschui <https://github.com/sventschui>,
// Volker Nauruhn <https://github.com/razorness>
// Volker Nauruhn <https://github.com/razorness>,
// Ard Timmerman <https://github.com/confususs>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -1157,7 +1158,7 @@ export interface CollectionViewOptions<
/**
* Specify a child view to use.
*/
childView?: (() => typeof Backbone.View) | typeof Backbone.View;
childView?: ((model: TModel) => typeof Backbone.View) | typeof Backbone.View;
/**
* Define options to pass to the childView constructor.
@@ -1219,7 +1220,7 @@ export class CollectionView<TModel extends Backbone.Model, TView extends View<TM
/**
* Specify a child view to use.
*/
childView: (() => { new(...args: any[]): TView }) | { new(...args: any[]): TView };
childView: ((model: TModel) => { new(...args: any[]): TView }) | { new(...args: any[]): TView };
/**
* Define options to pass to the childView constructor.
+1 -1
View File
@@ -38,7 +38,7 @@ var tester: BlazyInstance = new Blazy({
/* Functions tests */
tester.revalidate();
var elements = <NodeList>document.getElementsByTagName('img');
var elements = document.getElementsByTagName('img');
tester.load(elements, true);
tester.destroy();
+1 -1
View File
@@ -53,7 +53,7 @@ interface BlazyInstance {
* Forces the given element(s) to load if not collapsed. If you also want to load a collapsed/hidden elements you can add true as the second parameter.
* You can pass a single element or a list of elements. Tested with getElementById, getElementsByClassName, querySelectorAll, querySelector and jQuery selector.
*/
load(elements: Element|Element[]|HTMLElement|HTMLElement[]|NodeList, force: boolean): void;
load(elements: Element|Element[]|HTMLElement|HTMLElement[]|HTMLCollection|NodeList, force: boolean): void;
/**
* Unbind events and resets image array.
+6 -4
View File
@@ -1,3 +1,5 @@
declare let aHtmlElement: HTMLElement;
// --------------------------------------------------------------------------------------
// Alert
// --------------------------------------------------------------------------------------
@@ -78,7 +80,7 @@ $("#collapse").collapse({
});
$("#collapse").collapse({
parent: document.body,
parent: aHtmlElement,
});
$("#collapse").collapse({
@@ -122,11 +124,11 @@ $("#dropdown").dropdown({
});
$("#dropdown").dropdown({
boundary: document.body,
boundary: aHtmlElement,
});
$("#dropdown").dropdown({
reference: document.body,
reference: aHtmlElement,
});
// --------------------------------------------------------------------------------------
@@ -340,5 +342,5 @@ $("#tooltip").tooltip({
});
$("#tooltip").tooltip({
boundary: document.body,
boundary: aHtmlElement,
});
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://github.com/margox/braft#readme
// Definitions by: My Self <https://github.com/me>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
// TypeScript Version: 2.8
import * as React from "react";
import { RawDraftContentState } from 'draft-js';
+4 -1
View File
@@ -6,7 +6,10 @@ import Redis = require("ioredis");
import Queue = require("bull");
const videoQueue = new Queue('video transcoding', 'redis://127.0.0.1:6379');
const audioQueue = new Queue('audio transcoding', {redis: {port: 6379, host: '127.0.0.1'}}); // Specify Redis connection using object
const audioQueue = new Queue('audio transcoding', {
redis: {port: 6379, host: '127.0.0.1'}, // Specify Redis connection using object
settings: {},
});
const imageQueue: Queue.Queue<{ image: string }> = new Queue('image transcoding');
videoQueue.process((job, done) => {
+9 -2
View File
@@ -84,6 +84,13 @@ declare namespace Bull {
* Delay before processing next job in case of internal error
*/
retryProcessDelay?: number;
/**
* Define a custom backoff strategy
*/
backoffStrategies?: {
[key: string]: (attemptsMade: number, err: typeof Error) => number;
};
}
type DoneCallback = (error?: Error | null, value?: any) => void;
@@ -167,12 +174,12 @@ declare namespace Bull {
/**
* Backoff type, which can be either `fixed` or `exponential`
*/
type: 'fixed' | 'exponential';
type: string;
/**
* Backoff delay, in milliseconds
*/
delay: number;
delay?: number;
}
interface RepeatOptions {
+1 -1
View File
@@ -6,7 +6,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
@@ -0,0 +1,53 @@
import * as captureconsole from "capture-console";
captureconsole.capture(process.stdout, () => { }); // $ExpectType string[]
captureconsole.capture(process.stdout, {}, () => { }); // $ExpectType string[]
captureconsole.capture(process.stdout, { quiet: true }, () => { }); // $ExpectType string[]
captureconsole.capture([process.stdout, process.stdin], () => { }); // $ExpectType string[]
captureconsole.capture([process.stdout, process.stdin], {}, () => { }); // $ExpectType string[]
captureconsole.capture([process.stdout, process.stdin], { quiet: true }, () => { }); // $ExpectType string[]
captureconsole.captureStderr(() => { }); // $ExpectType string
captureconsole.captureStderr({}, () => { }); // $ExpectType string
captureconsole.captureStderr({ quiet: true }, () => { }); // $ExpectType string
captureconsole.captureStdio(() => { }); // $ExpectType { stdout: string; stderr: string; }
captureconsole.captureStdio({}, () => { }); // $ExpectType { stdout: string; stderr: string; }
captureconsole.captureStdio({ quiet: true }, () => { }); // $ExpectType { stdout: string; stderr: string; }
captureconsole.captureStdout(() => { }); // $ExpectType string
captureconsole.captureStdout({}, () => { }); // $ExpectType string
captureconsole.captureStdout({ quiet: true }, () => { }); // $ExpectType string
captureconsole.hook(process.stdout, (string: string, encoding?: string, fd?: (error?: any) => void) => { }); // $ExpectType () => boolean
captureconsole.hook(process.stdout, {}, (string: string, encoding?: string, fd?: (error?: any) => void) => { }); // $ExpectType () => boolean
captureconsole.hook(process.stdout, { quiet: true }, (string: string, encoding?: string, fd?: (error?: any) => void) => { }); // $ExpectType () => boolean
captureconsole.intercept(process.stdout, () => { }); // $ExpectType string[]
captureconsole.intercept(process.stdout, {}, () => { }); // $ExpectType string[]
captureconsole.intercept(process.stdout, { quiet: true }, () => { }); // $ExpectType string[]
captureconsole.interceptStderr(() => { }); // $ExpectType string
captureconsole.interceptStderr({}, () => { }); // $ExpectType string
captureconsole.interceptStderr({ quiet: true }, () => { }); // $ExpectType string
captureconsole.interceptStdio(() => { }); // $ExpectType { stdout: string; stderr: string; }
captureconsole.interceptStdio({}, () => { }); // $ExpectType { stdout: string; stderr: string; }
captureconsole.interceptStdio({ quiet: true }, () => { }); // $ExpectType { stdout: string; stderr: string; }
captureconsole.interceptStdout(() => { }); // $ExpectType string
captureconsole.interceptStdout({}, () => { }); // $ExpectType string
captureconsole.interceptStdout({ quiet: true }, () => { }); // $ExpectType string
captureconsole.startCapture(process.stdout, (string: string, encoding?: string, fd?: (error?: any) => void) => { }); // $ExpectType boolean
captureconsole.startCapture(process.stdout, {}, (string: string, encoding?: string, fd?: (error?: any) => void) => { }); // $ExpectType boolean
captureconsole.startCapture(process.stdout, { quiet: true }, (string: string, encoding?: string, fd?: (error?: any) => void) => { }); // $ExpectType boolean
captureconsole.startIntercept(process.stdout, () => { }); // $ExpectType boolean
captureconsole.startIntercept(process.stdout, {}, () => { }); // $ExpectType boolean
captureconsole.startIntercept(process.stdout, { quiet: true }, () => { }); // $ExpectType boolean
captureconsole.stopCapture(process.stdout); // $ExpectType boolean
captureconsole.stopIntercept(process.stdout); // $ExpectType boolean
+190
View File
@@ -0,0 +1,190 @@
// Type definitions for capture-console 1.0
// Project: https://github.com/zackehh/capture-console
// Definitions by: Auston Zahrt <https://github.com/AustonZ>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node"/>
/**
* Options controlling behavior when capturing
*/
export interface CaptureOptions {
/**
* Option to silence the output going to the console
*/
quiet?: boolean;
}
/**
* Executes the provided function with the output
* on the provided streams.
*/
export function capture(
streams: ReadonlyArray<NodeJS.WritableStream> | NodeJS.WritableStream,
exec: () => void
): string[];
/**
* Executes the provided function with the output
* on the provided streams. Accepts options to silence
* the output going to the console.
*/
export function capture(
streams: ReadonlyArray<NodeJS.WritableStream> | NodeJS.WritableStream,
opts: CaptureOptions,
exec: () => void
): string[];
/**
* Captures stderr for the provided execution scope.
*/
export function captureStderr(exec: () => void): string;
/**
* Captures stderr for the provided execution scope.
*/
export function captureStderr(opts: CaptureOptions, exec: () => void): string;
/**
* Captures stdout and stderr into an object for
* the provided execution scope.
*/
export function captureStdio(exec: () => void): { stdout: string; stderr: string; };
/**
* Captures stdout and stderr into an object for
* the provided execution scope.
*/
export function captureStdio(opts: CaptureOptions, exec: () => void): { stdout: string; stderr: string; };
/**
* Captures stdout for the provided execution scope.
*/
export function captureStdout(exec: () => void): string;
/**
* Captures stdout for the provided execution scope.
*/
export function captureStdout(opts: CaptureOptions, exec: () => void): string;
/**
* Listens to a provided stream, and executes the provided
* function for every write call. Accepts options to silence
* the output going to the console.
*
* Returns a function to call when you wish to stop listening
* to the call.
*/
export function hook(
stream: NodeJS.WritableStream,
exec: (
string: string,
encoding?: string,
fd?: (error?: any) => void
) => void
): () => boolean;
/**
* Listens to a provided stream, and executes the provided
* function for every write call. Accepts options to silence
* the output going to the console.
*
* Returns a function to call when you wish to stop listening
* to the call.
*/
export function hook(
stream: NodeJS.WritableStream,
opts: CaptureOptions,
exec: (
string: string,
encoding?: string,
fd?: (error?: any) => void
) => void
): () => boolean;
/**
* Delegate to #capture with a quiet passthrough.
*/
export function intercept(stream: NodeJS.WritableStream, exec: () => void): string[];
/**
* Delegate to #capture with a quiet passthrough.
*/
export function intercept(stream: NodeJS.WritableStream, opts: CaptureOptions, exec: () => void): string[];
/**
* Delegate to #captureStderr with a quiet passthrough.
*/
export function interceptStderr(exec: () => void): string;
/**
* Delegate to #captureStderr with a quiet passthrough.
*/
export function interceptStderr(opts: CaptureOptions, exec: () => void): string;
/**
* Delegate to #captureStdio with a quiet passthrough.
*/
export function interceptStdio(exec: () => void): { stdout: string; stderr: string; };
/**
* Delegate to #captureStdio with a quiet passthrough.
*/
export function interceptStdio(opts: CaptureOptions, exec: () => void): { stdout: string; stderr: string; };
/**
* Delegate to #captureStdout with a quiet passthrough.
*/
export function interceptStdout(exec: () => void): string;
/**
* Delegate to #captureStdout with a quiet passthrough.
*/
export function interceptStdout(opts: CaptureOptions, exec: () => void): string;
/**
* Starts a capture on the provided stream using the
* provided options and stream execution.
*/
export function startCapture(
stream: NodeJS.WritableStream,
exec: (
string: string,
encoding?: string,
fd?: (error?: any) => void
) => void
): boolean;
/**
* Starts a capture on the provided stream using the
* provided options and stream execution.
*/
export function startCapture(
stream: NodeJS.WritableStream,
opts: CaptureOptions,
exec: (
string: string,
encoding?: string,
fd?: (error?: any) => void
) => void
): boolean;
/**
* Delegate to #startCapture with a quiet passthrough.
*/
export function startIntercept(stream: NodeJS.WritableStream, exec: () => void): boolean;
/**
* Delegate to #startCapture with a quiet passthrough.
*/
export function startIntercept(stream: NodeJS.WritableStream, opts: CaptureOptions, exec: () => void): boolean;
/**
* Stops a capture on the provided stream.
*/
export function stopCapture(stream: NodeJS.WritableStream): boolean;
/**
* Delegate to #stopCapture with a quiet passthrough.
*/
export function stopIntercept(stream: NodeJS.WritableStream): boolean;
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"strictFunctionTypes": true
},
"files": [
"index.d.ts",
"capture-console-tests.ts"
]
}
+12
View File
@@ -0,0 +1,12 @@
import * as CatbotRedis from 'catbox-redis';
const cache = new CatbotRedis({
host: 'localhost',
partition: 'test',
port: 2018,
});
cache.get({
segment: 'test',
id: 'test',
});
+60
View File
@@ -0,0 +1,60 @@
// Type definitions for catbox-redis 4.1
// Project: https://github.com/hapijs/catbox-redis#readme
// Definitions by: Simon Schick <https://github.com/SimonSchick>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
// tslint:disable-next-line
declare module 'catbox-redis' {
import { Redis } from 'ioredis';
import { EnginePrototype, ClientOptions, Client } from 'catbox';
namespace CatboxRedis {
interface CatboxRedisOptions extends ClientOptions {
/**
* Raw client.
*/
client?: Redis;
/**
* the Redis server URL (if url is provided, host, port, and socket are ignored)
*/
url?: string;
/**
* the Redis server hostname.
* Defaults to '127.0.0.1'.
*/
host?: string;
/**
* the Redis server port or unix domain socket path.
* Defaults to 6379.
*/
port?: number;
/**
* the unix socket string to connect to (if socket is provided, host and port are ignored)
*/
socket?: string;
/**
* the Redis authentication password when required.
*/
password?: string;
/**
* the Redis database.
*/
database?: string;
/**
* an array of redis sentinel addresses to connect to.
*/
sentinels?: Array<{
host: string;
}>;
/**
* the name of the sentinel master.
* (Only needed when sentinels is specified)
*/
sentinelName?: string;
}
}
class CatboxRedis extends Client {
constructor(options: CatboxRedis.CatboxRedisOptions);
}
export = CatboxRedis;
}
@@ -18,6 +18,6 @@
},
"files": [
"index.d.ts",
"meteor-univserse-i18n-tests.ts"
"catbox-redis-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+3
View File
@@ -112,6 +112,9 @@ export interface CachedObject {
export type CacheItem = any;
export interface ClientOptions {
/**
* this will store items under keys that start with this value.
*/
partition: string;
}
+27 -26
View File
@@ -1,8 +1,9 @@
// Type definitions for cesium 1.46
// Type definitions for cesium 1.47
// Project: http://cesiumjs.org
// Definitions by: Aigars Zeiza <https://github.com/Zuzon>
// Harry Nicholls <https://github.com/hnipps>
// Jared Szechy <https://github.com/szechyjs>
// Radek Goláň jr. <https://github.com/golyalpha>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -1934,15 +1935,15 @@ declare namespace Cesium {
semiMinorAxis: Property;
rotation: Property;
show: Property;
material: MaterialProperty;
material: MaterialProperty | Color;
height: Property;
extrudedHeight: Property;
granularity: Property;
stRotation: Property;
fill: Property;
outline: Property;
outlineColor: Property;
outlineWidth: Property;
fill: boolean;
outline: boolean;
outlineColor: Color;
outlineWidth: number;
numberOfVerticalLines: Property;
constructor(options?: {
semiMajorAxis?: number;
@@ -1950,11 +1951,11 @@ declare namespace Cesium {
height?: Property;
extrudedHeight?: Property;
show?: Property;
fill?: Property;
material?: MaterialProperty;
outline?: Property;
outlineColor?: Property;
outlineWidth?: Property;
fill?: boolean;
material?: MaterialProperty | Color
outline?: boolean;
outlineColor?: Color;
outlineWidth?: number;
numberOfVerticalLines?: Property;
rotation?: Property;
stRotation?: Property;
@@ -2206,11 +2207,11 @@ declare namespace Cesium {
class LabelGraphics {
definitionChanged: Event;
text: Property;
font: Property;
font: string;
style: Property;
fillColor: Property;
outlineColor: Property;
outlineWidth: Property;
fillColor: Color;
outlineColor: Color;
outlineWidth: number;
horizontalOrigin: Property;
verticalOrigin: Property;
eyeOffset: Property;
@@ -2221,11 +2222,11 @@ declare namespace Cesium {
pixelOffsetScaleByDistance: Property;
constructor(options?: {
text?: Property;
font?: Property;
font?: string;
style?: Property;
fillColor?: Property;
outlineColor?: Property;
outlineWidth?: Property;
fillColor?: Color;
outlineColor?: Color;
outlineWidth?: number;
show?: Property;
scale?: Property;
horizontalOrigin?: Property;
@@ -2361,16 +2362,16 @@ declare namespace Cesium {
class PolygonGraphics {
definitionChanged: Event;
show: Property;
material: MaterialProperty;
material: MaterialProperty | Color;
positions: Property;
hierarchy: Property;
height: Property;
extrudedHeight: Property;
granularity: Property;
stRotation: Property;
fill: Property;
fill: boolean;
outline: Property;
outlineColor: Property;
outlineColor: Color;
outlineWidth: Property;
perPositionHeight: Property;
constructor(options?: {
@@ -2378,10 +2379,10 @@ declare namespace Cesium {
height?: number;
extrudedHeight?: Property;
show?: Property;
fill?: Property;
material?: MaterialProperty;
fill?: boolean;
material?: MaterialProperty | Color;
outline?: boolean;
outlineColor?: Property;
outlineColor?: Color;
outlineWidth?: number;
stRotation?: Property;
granularity?: Property;
@@ -3592,7 +3593,7 @@ declare namespace Cesium {
cull?: boolean;
asynchronous?: boolean;
debugShowBoundingVolume?: boolean;
shadows: ShadowMode
shadows?: ShadowMode
});
destroy(): void;
getGeometryInstanceAttributes(id: any): any;
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://github.com/producthunt/chai-enzyme
// Definitions by: Alexey Svetliakov <https://github.com/asvetliakov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
// TypeScript Version: 2.8
/// <reference types="enzyme" />
+1 -1
View File
@@ -584,7 +584,7 @@ declare namespace Chart {
position?: string;
ticks?: TickOptions;
gridLines?: GridLineOptions;
barThickness?: number | string;
barThickness?: number | "flex";
maxBarThickness?: number;
scaleLabel?: ScaleTitleOptions;
time?: TimeScale;
+4695 -2042
View File
File diff suppressed because it is too large Load Diff
+202 -29
View File
@@ -1,8 +1,8 @@
import runtime = chrome.app.runtime;
import cwindow = chrome.app.window;
const cwindow = chrome.app.window;
const createOptions: cwindow.CreateWindowOptions = {
id: "My Window",
const createOptions: chrome.app.CreateWindowOptions = {
id: 'My Window',
bounds: {
left: 0,
top: 0,
@@ -14,7 +14,7 @@ const createOptions: cwindow.CreateWindowOptions = {
//Create new window on app launch
chrome.app.runtime.onLaunched.addListener(function (launchData: runtime.LaunchData) {
chrome.app.window.create('app/url', createOptions, function (created_window: cwindow.AppWindow) {
chrome.app.window.create('app/url', createOptions, function (created_window: chrome.app.AppWindow) {
return;
});
});
@@ -22,9 +22,9 @@ chrome.app.runtime.onLaunched.addListener(function (launchData: runtime.LaunchDa
chrome.app.runtime.onRestarted.addListener(function () { return; });
// retrieving windows
var currentWindow: cwindow.AppWindow = chrome.app.window.current();
var otherWindow: cwindow.AppWindow = chrome.app.window.get('some-string');
var allWindows: cwindow.AppWindow[] = chrome.app.window.getAll();
var currentWindow: chrome.app.AppWindow = chrome.app.window.current();
var otherWindow: chrome.app.AppWindow = chrome.app.window.get('some-string');
var allWindows: chrome.app.AppWindow[] = chrome.app.window.getAll();
// listening to window events
currentWindow.onBoundsChanged.addListener(function () { return; });
@@ -42,11 +42,11 @@ var visibleEverywhere: boolean = chrome.app.window.canSetVisibleOnAllWorkspaces(
function test_fileSystem(): void {
var accepts: chrome.fileSystem.AcceptOptions[] = [
{ mimeTypes: ["text/*"], extensions: ['js', 'css', 'txt', 'html', 'xml', 'tsv', 'csv', 'rtf'] }
{ mimeTypes: ['text/*'], extensions: ['js', 'css', 'txt', 'html', 'xml', 'tsv', 'csv', 'rtf'] }
];
var chooseOption: chrome.fileSystem.ChooseEntryOptions = {
type: "openFile",
suggestedName: "foo.txt",
type: 'openFile',
suggestedName: 'foo.txt',
accepts: accepts,
acceptsAllTypes: false,
acceptsMultiple: false
@@ -98,7 +98,7 @@ function test_socketsTcp(): void {
chrome.sockets.tcp.setNoDelay(socketId, true, (result: number) => { });
// connect
chrome.sockets.tcp.connect(socketId, "192.168.0.1", 8080, (result: number) => { });
chrome.sockets.tcp.connect(socketId, '192.168.0.1', 8080, (result: number) => { });
// disconnect
chrome.sockets.tcp.disconnect(socketId);
@@ -132,7 +132,7 @@ function testSocketsTcpTypes(): void {
properties = {
persistent: true,
name: "test",
name: 'test',
bufferSize: 1024
};
@@ -146,11 +146,11 @@ function testSocketsTcpTypes(): void {
connected: false
};
socketInfo.name = "test";
socketInfo.name = 'test';
socketInfo.bufferSize = 1024;
socketInfo.localAddress = "192.168.0.2";
socketInfo.localAddress = '192.168.0.2';
socketInfo.localPort = 8000;
socketInfo.peerAddress = "192.168.0.3";
socketInfo.peerAddress = '192.168.0.3';
socketInfo.peerPort = 1000;
}
@@ -178,10 +178,10 @@ function test_socketsUdp(): void {
chrome.sockets.udp.setPaused(socketId, true, () => { });
// bind
chrome.sockets.udp.bind(socketId, "0.0.0.0", 8080, (result: number) => { });
chrome.sockets.udp.bind(socketId, '0.0.0.0', 8080, (result: number) => { });
// send
chrome.sockets.udp.send(socketId, buffer, "172.21.0.1", 10080, (info: chrome.sockets.udp.SendInfo) => { });
chrome.sockets.udp.send(socketId, buffer, '172.21.0.1', 10080, (info: chrome.sockets.udp.SendInfo) => { });
// close
chrome.sockets.udp.close(socketId);
@@ -194,10 +194,10 @@ function test_socketsUdp(): void {
chrome.sockets.udp.getSockets((infos: chrome.sockets.udp.SocketInfo[]) => { });
// joinGroup
chrome.sockets.udp.joinGroup(socketId, "224.0.0.1", (result: number) => { });
chrome.sockets.udp.joinGroup(socketId, '224.0.0.1', (result: number) => { });
// leaveGroup
chrome.sockets.udp.leaveGroup(socketId, "224.0.0.1", (result: number) => { });
chrome.sockets.udp.leaveGroup(socketId, '224.0.0.1', (result: number) => { });
// setMulticastTimeToLive
chrome.sockets.udp.setMulticastTimeToLive(socketId, 100, (result: number) => { });
@@ -223,7 +223,7 @@ function testSocketsUdpTypes(): void {
properties = {
persistent: true,
name: "test",
name: 'test',
bufferSize: 1024
};
@@ -236,9 +236,9 @@ function testSocketsUdpTypes(): void {
paused: true
};
socketInfo.name = "test";
socketInfo.name = 'test';
socketInfo.bufferSize = 1024;
socketInfo.localAddress = "192.168.0.2";
socketInfo.localAddress = '192.168.0.2';
socketInfo.localPort = 8000;
}
@@ -266,8 +266,8 @@ function test_socketsTcpServer(): void {
chrome.sockets.tcpServer.setPaused(socketId, true, () => { });
// listen
chrome.sockets.tcpServer.listen(socketId, "0.0.0.0", 80, (result: number) => { });
chrome.sockets.tcpServer.listen(socketId, "0.0.0.0", 80, 128, (result: number) => { });
chrome.sockets.tcpServer.listen(socketId, '0.0.0.0', 80, (result: number) => { });
chrome.sockets.tcpServer.listen(socketId, '0.0.0.0', 80, 128, (result: number) => { });
// disconnect
chrome.sockets.tcp.disconnect(socketId);
@@ -298,7 +298,7 @@ function testSocketsTcpServerTypes(): void {
properties = {
persistent: true,
name: "test"
name: 'test'
};
// SocketInfo
@@ -310,8 +310,8 @@ function testSocketsTcpServerTypes(): void {
paused: true
};
socketInfo.name = "test";
socketInfo.localAddress = "192.168.0.2";
socketInfo.name = 'test';
socketInfo.localAddress = '192.168.0.2';
socketInfo.localPort = 8000;
}
@@ -340,7 +340,7 @@ wve.addEventListener('close', () => {
return;
});
wve.addEventListener('consolemessage', (ev) => {
if (ev.level === chrome.webview.ConsoleMessageLevel.LOG_ERROR) {
if (ev.level === 2) {
const msg = ev.message;
}
});
@@ -360,4 +360,177 @@ wve.addEventListener('loadredirect', (ev) => {
return ev.newUrl || ev.oldUrl;
});
chrome.bluetoothLowEnergy.connect('1111111', () => { });
chrome.bluetooth.getAdapterState((adapter) => {
console.log('Adapter ' + adapter.address + ': ' + adapter.name);
});
chrome.bluetooth.getDevices((devices) => {
for (const device of devices) {
console.log(device.address);
}
});
chrome.bluetooth.onDeviceAdded.addListener((device) => {
let uuid = '0000180d-0000-1000-8000-00805f9b34fb';
if (!device.uuids || device.uuids.indexOf(uuid) < 0)
return;
// The device has a service with the desired UUID.
chrome.bluetoothLowEnergy.connect(device.address, () => {
if (chrome.runtime.lastError) {
console.log('Failed to connect: ' + chrome.runtime.lastError.message);
return;
}
// Connected! Do stuff...
});
});
const uuid = '1105';
chrome.bluetooth.getDevices((devices) => {
chrome.bluetoothSocket.create((createInfo) => {
chrome.bluetoothSocket.connect(createInfo.socketId,
devices[0].address, uuid, () => {
if (chrome.runtime.lastError) {
console.log('Connection failed: ' + chrome.runtime.lastError.message);
} else {
chrome.bluetoothSocket.send(createInfo.socketId, new ArrayBuffer(4096), (bytes_sent) => {
if (chrome.runtime.lastError) {
console.log('Send failed: ' + chrome.runtime.lastError.message);
} else {
console.log('Sent ' + bytes_sent + ' bytes')
}
});
}
});
chrome.bluetoothSocket.onReceive.addListener((receiveInfo) => {
if (receiveInfo.socketId != createInfo.socketId)
return;
// receiveInfo.data is an ArrayBuffer.
});
});
});
chrome.hid.getDevices({
filters: [
{ vendorId: 5 }
]
}, (devices) => {
const productId = devices[0].productId;
chrome.hid.getUserSelectedDevices((selectedDevices) => {
const hmm = selectedDevices.productId == productId ? selectedDevices.vendorId : selectedDevices.maxFeatureReportSize;
});
});
chrome.syncFileSystem.getConflictResolutionPolicy((policy) => {
if (policy === 'manual') {
chrome.syncFileSystem.requestFileSystem((fs) => {
if (fs.root.isFile) {
throw new Error('It was a file!');
}
});
}
})
chrome.contextMenus.ACTION_MENU_TOP_LEVEL_LIMIT;
chrome.i18n.getMessage('click_here', ['string1', 'string2']);
const TLSFormatExample = {
NetworkConfigurations: <chrome.networking.onc.NetworkConfigProperties>
{
GUID: '{00f79111-51e0-e6e0-76b3b55450d80a1b}',
Name: 'MyTTLSNetwork',
Type: 'WiFi',
WiFi: {
AutoConnect: false,
EAP: {
ClientCertPattern: {
EnrollmentURI: [
'http://fetch-my-certificate.com'
],
IssuerCARef: [
'{6ed8dce9-64c8-d568-d225d7e467e37828}'
]
},
'ClientCertType': 'Pattern',
'Outer': 'EAP-TLS',
'ServerCARef': '{6ed8dce9-64c8-d568-d225d7e467e37828}',
'UseSystemCAs': true
},
'HiddenSSID': false,
'SSID': 'MyTTLSNetwork',
'Security': 'WPA-EAP'
}
}
}
let serviceId: any = null;
const runApp = () => {
var options = {
'id': 'Bluetooth Sample App',
'bounds': {
'width': 1024,
'height': 768
}
};
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.serviceId) {
serviceId = request.serviceId;
console.log('Received registered service Id: ' + serviceId);
}
});
chrome.app.window.create('test.html', options, (theWindow) => {
theWindow.onClosed.addListener(() => {
if (serviceId) {
console.log('Unregistering service: ' + serviceId);
chrome.bluetoothLowEnergy.unregisterService(serviceId, (status) => {
console.log('Unregister service status = ' + status);
});
}
});
});
}
chrome.app.runtime.onLaunched.addListener(runApp);
chrome.app.runtime.onRestarted.addListener(runApp);
// networking.onc
chrome.networking.onc.getNetworks({ 'networkType': 'All' }, (networkList) => {
console.log('Length of Network list: ' + networkList.length);
for (let networkObj of networkList) {
console.log('GUID: ' + networkObj.GUID);
console.log('Connectable: ' + networkObj.Connectable);
if (networkObj.WiFi) {
// WiFi active :)
console.log('Wifi BSID: ' + networkObj.WiFi.BSSID);
}
chrome.networking.onc.setProperties(networkObj.GUID || '', {
WiFi: {
Passphrase: 'Can be set :) but not get?'
}
})
// Test that we can't get passphrase
chrome.networking.onc.getProperties(networkObj.GUID || '', (props) => {
const WiFiResult = props.WiFi;
});
}
});
//// AUDIO
chrome.audio.getDevices({}, (audioDeviceInfoList) => {
for (let audioObj of audioDeviceInfoList) {
console.log('ID: ' + audioObj.id);
console.log('Audio Stream Type: ' + audioObj.streamType);
console.log('Audio Device Name: ' + audioObj.deviceName);
}
});
chrome.desktopCapture.chooseDesktopMedia(["screen", "window", "tab"], () => { });
chrome.desktopCapture.chooseDesktopMedia([chrome.desktopCapture.DesktopCaptureSourceType.AUDIO], () => { });
+6
View File
@@ -19,6 +19,12 @@ export interface CleaveOptions {
datePattern?: ReadonlyArray<string>;
}
// Time Options
export interface CleaveOptions {
time?: boolean;
timePattern?: ReadonlyArray<string>;
}
// Numeral Options
export type NumeralThousandsGroupStyleType = "lakh" | "thousand" | "wan" | "none";
+6
View File
@@ -14,6 +14,12 @@ const cb5 = new ClipboardJS(".btn", {
action: elem => "copy",
target: elem => null
});
const cb6 = new ClipboardJS(".btn", {
action: elem => "copy",
text: trigger => trigger.getAttribute('aria-label'),
target: trigger => trigger.nextElementSibling,
container: document.getElementById('modal')
});
cb1.destroy();
ClipboardJS.isSupported();
+8
View File
@@ -49,6 +49,14 @@ declare namespace ClipboardJS {
* @returns Text to be copied.
*/
text?(elem: Element): string;
/**
* For use in Bootstrap Modals or with any
* other library that changes the focus
* you'll want to set the focused element
* as the container value.
*/
container?: Element;
}
interface Event {
+2 -2
View File
@@ -104,11 +104,11 @@ declare namespace connectMongo {
}
export class MongoStore extends session.Store {
get: (sid: string, callback: (err: any, session: Express.Session) => void) => void;
get: (sid: string, callback: (err: any, session: Express.Session | null) => void) => void;
set: (sid: string, session: Express.Session, callback?: (err: any) => void) => void;
destroy: (sid: string, callback?: (err: any) => void) => void;
length: (callback: (err: any, length: number) => void) => void;
clear: (callback?: (err: any) => void) => void;
clear: (callback?: (err?: any) => void) => void;
touch: (sid: string, session: Express.Session, callback?: (err: any) => void) => void;
}
}
+5
View File
@@ -31,6 +31,11 @@ bucket.manager().createPrimaryIndex(function() {
});
});
// Ensure bucket.upsert is composable with normal callbacks
function composable(callback: (err?: Error) => void) {
bucket.upsert('key', {value: 1}, callback);
}
// From https://developer.couchbase.com/documentation/server/current/sdk/nodejs/n1ql-queries-with-sdk.html
function n1ql_a() {
const n1qlquery = N1qlQuery.fromString('SELECT name, email FROM users WHERE name=$1');
+2 -2
View File
@@ -2019,10 +2019,10 @@ declare namespace Bucket {
*/
interface OpCallback {
/**
* @param error The error for the operation. This can either be an Error object or a value which evaluates to false (null, undefined, 0 or false).
* @param error The error for the operation. This can either be an Error object or a value which evaluates to false.
* @param result The result of the operation that was executed. This usually contains at least a cas property, and on some operations will contain a value property as well.
*/
(error: CouchbaseError | number, result: any): void;
(error: CouchbaseError | null, result: any): void;
}
/**
+2 -2
View File
@@ -252,7 +252,7 @@ declare namespace Domain {
/**
* @param data is the command data
* @callback callback is optional, if not defined as function argument you can throw errors or return errors here (sync way)
* @param callback is optional, if not defined as function argument you can throw errors or return errors here (sync way)
*/
type preLoadConditionHandler = (data: any, callback?: (err: string | Error) => string | Error) => void | string | Error;
@@ -295,7 +295,7 @@ declare namespace Domain {
/**
* @param data is the command data
* @param aggregate is the aggregate object
* @callback callback is optional, if not defined as function argument you can throw errors or return errors here (sync way)
* @param callback is optional, if not defined as function argument you can throw errors or return errors here (sync way)
*/
type preConditionHandler = (data: any, aggregate: AggregateModel, callback?: (err: string | Error) => string | Error) => void | string | Error;
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://facebook.github.io/react/
// Definitions by: John Gozde <https://github.com/jgoz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
// TypeScript Version: 2.8
import { ComponentSpec, ClassicComponentClass } from "react";
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Asana <https://github.com/Asana>
// Vincent Siao <https://github.com/vsiao>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
// TypeScript Version: 2.8
import * as React from "react";
@@ -0,0 +1,4 @@
import generate = require('crypto-random-string');
// $ExpectType string
generate(10);
+13
View File
@@ -0,0 +1,13 @@
// Type definitions for crypto-random-string 1.0
// Project: https://github.com/sindresorhus/crypto-random-string
// Definitions by: Manuel Warum <https://github.com/MrManny>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* Generate a hexadecimal string of the given length.
* @param length the length of the random string.
* @return a string of the specified length.
*/
declare function cryptoRandomString(length: number): string;
export = cryptoRandomString;
+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",
"crypto-random-string-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+17
View File
@@ -0,0 +1,17 @@
import cssnano = require('cssnano');
import { Transformer } from 'postcss';
const nano1: Transformer = cssnano();
const nano2: Transformer = cssnano({
configFile: '/path/to/config',
});
const nano3: Transformer = cssnano({
preset: 'default',
});
const nano4: Transformer = cssnano({
preset: ['default', {
discardComments: {
removeAll: true,
},
}],
});
+19
View File
@@ -0,0 +1,19 @@
// Type definitions for cssnano 4.0
// Project: https://github.com/cssnano/cssnano
// Definitions by: Armando Meziat <https://github.com/odnamrataizem>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
import { Plugin } from 'postcss';
declare namespace cssnano {
interface CssNanoOptions {
configFile?: string;
preset?: [string, object] | string;
}
type CssNano = Plugin<CssNanoOptions>;
}
declare const cssnano: cssnano.CssNano;
export = cssnano;
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"postcss": "5 - 7"
}
}
+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",
"cssnano-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+3 -3
View File
@@ -2819,13 +2819,13 @@ declare namespace cytoscape {
/**
* The handler returns true when it finds the desired node, and it returns false to cancel the search.
* i - The index indicating this node is the ith visited node.
* depth - How many edge hops away this node is from the root nodes.
* v - The current node.
* e - The edge connecting the previous node to the current node.
* u - The previous node.
* i - The index indicating this node is the ith visited node.
* depth - How many edge hops away this node is from the root nodes.
*/
type SearchVisitFunction = (i: number, depth: number, v: NodeCollection, e: EdgeCollection, u: NodeCollection) => boolean;
type SearchVisitFunction = (v: NodeCollection, e: EdgeCollection, u: NodeCollection, i: number, depth: number) => boolean | void;
interface SearchFirstOptions {
/**
* The root nodes (selector or collection) to start the search from.
+8 -7
View File
@@ -189,6 +189,10 @@ stratificatorizer = d3Hierarchy.stratify<TabularHierarchyDatum>();
// id(...)
stratificatorizer = stratificatorizer.id((d) => {
return d.name; // d is of type TabularHierarchyDatum
});
stratificatorizer = stratificatorizer.id((d, i, data) => {
console.log('Length of tabular array: ', data.length);
console.log('Name of first entry in tabular array: ', data[0].name); // data of type Array<TabularHierarchyDatum>
@@ -199,6 +203,10 @@ idStringAccessor = stratificatorizer.id();
// parentId(...)
stratificatorizer = stratificatorizer.parentId((d) => {
return d.parentId; // d is of type TabularHierarchyDatum
});
stratificatorizer = stratificatorizer.parentId((d, i, data) => {
console.log('Length of tabular array: ', data.length);
console.log('Name of first entry in tabular array: ', data[0].name); // data of type Array<TabularHierarchyDatum>
@@ -225,14 +233,12 @@ clusterLayout = d3Hierarchy.cluster<HierarchyDatumWithParentId>();
// size() ----------------------------------------------------------------
clusterLayout = clusterLayout.size(null);
clusterLayout = clusterLayout.size([200, 200]);
size = clusterLayout.size();
// nodeSize() ------------------------------------------------------------
clusterLayout = clusterLayout.nodeSize(null);
clusterLayout = clusterLayout.nodeSize([10, 10]);
size = clusterLayout.nodeSize();
@@ -358,14 +364,12 @@ treeLayout = d3Hierarchy.tree<HierarchyDatumWithParentId>();
// size() ----------------------------------------------------------------
treeLayout = treeLayout.size(null);
treeLayout = treeLayout.size([200, 200]);
size = treeLayout.size();
// nodeSize() ------------------------------------------------------------
treeLayout = treeLayout.nodeSize(null);
treeLayout = treeLayout.nodeSize([10, 10]);
size = treeLayout.nodeSize();
@@ -416,7 +420,6 @@ tilingFn = treemapLayout.tile();
// size() ----------------------------------------------------------------
treemapLayout = treemapLayout.size(null);
treemapLayout = treemapLayout.size([400, 200]);
size = treemapLayout.size();
@@ -635,7 +638,6 @@ partitionLayout = d3Hierarchy.partition<HierarchyDatumWithParentId>();
// size() ----------------------------------------------------------------
partitionLayout = partitionLayout.size(null);
partitionLayout = partitionLayout.size([400, 200]);
size = partitionLayout.size();
@@ -674,7 +676,6 @@ packLayout = d3Hierarchy.pack<HierarchyDatumWithParentId>();
// size() ----------------------------------------------------------------
packLayout = packLayout.size(null);
packLayout = packLayout.size([400, 400]);
size = packLayout.size();
+626 -98
View File
@@ -1,65 +1,208 @@
// Type definitions for D3JS d3-hierarchy module 1.1
// Project: https://github.com/d3/d3-hierarchy/
// Definitions by: Tom Wanzek <https://github.com/tomwanzek>, Alex Ford <https://github.com/gustavderdrache>, Boris Yankov <https://github.com/borisyankov>
// Definitions by: Tom Wanzek <https://github.com/tomwanzek>
// Alex Ford <https://github.com/gustavderdrache>
// Boris Yankov <https://github.com/borisyankov>
// denisname <https://github.com/denisname>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Last module patch version validated against: 1.1.1
// Last module patch version validated against: 1.1.6
// -----------------------------------------------------------------------
// Hierarchy
// -----------------------------------------------------------------------
export interface HierarchyLink<Datum> {
/**
* The source of the link.
*/
source: HierarchyNode<Datum>;
/**
* The target of the link.
*/
target: HierarchyNode<Datum>;
}
export interface HierarchyNode<Datum> {
data: Datum;
readonly depth: number;
readonly height: number;
parent: HierarchyNode<Datum> | null;
children?: Array<HierarchyNode<Datum>>;
/**
* Aggregated numeric value as calculated by sum(value) or count(),
* if previously invoked.
* The associated data, as specified to the constructor.
*/
data: Datum;
/**
* Zero for the root node, and increasing by one for each descendant generation.
*/
readonly depth: number;
/**
* Zero for leaf nodes, and the greatest distance from any descendant leaf for internal nodes.
*/
readonly height: number;
/**
* The parent node, or null for the root node.
*/
parent: this | null;
/**
* An array of child nodes, if any; undefined for leaf nodes.
*/
children?: this[];
/**
* Aggregated numeric value as calculated by `sum(value)` or `count()`, if previously invoked.
*/
readonly value?: number;
/**
* Optional Node Id string set by StratifyOperator, if
* hierarchical data was created from tabular data using stratify()
* Optional node id string set by `StratifyOperator`, if hierarchical data was created from tabular data using stratify().
*/
readonly id?: string;
ancestors(): Array<HierarchyNode<Datum>>;
descendants(): Array<HierarchyNode<Datum>>;
leaves(): Array<HierarchyNode<Datum>>;
path(target: HierarchyNode<Datum>): Array<HierarchyNode<Datum>>;
/**
* Returns the array of ancestors nodes, starting with this node, then followed by each parent up to the root.
*/
ancestors(): this[];
/**
* Returns the array of descendant nodes, starting with this node, then followed by each child in topological order.
*/
descendants(): this[];
/**
* Returns the array of leaf nodes in traversal order; leaves are nodes with no children.
*/
leaves(): this[];
/**
* Returns the shortest path through the hierarchy from this node to the specified target node.
* The path starts at this node, ascends to the least common ancestor of this node and the target node, and then descends to the target node.
*
* @param target The target node.
*/
path(target: this): this[];
/**
* Returns an array of links for this node, where each link is an object that defines source and target properties.
* The source of each link is the parent node, and the target is a child node.
*/
links(): Array<HierarchyLink<Datum>>;
/**
* Evaluates the specified value function for this node and each descendant in post-order traversal, and returns this node.
* The `node.value` property of each node is set to the numeric value returned by the specified function plus the combined value of all descendants.
*
* @param value The value function is passed the node’s data, and must return a non-negative number.
*/
sum(value: (d: Datum) => number): this;
/**
* Computes the number of leaves under this node and assigns it to `node.value`, and similarly for every descendant of node.
* If this node is a leaf, its count is one. Returns this node.
*/
count(): this;
sort(compare: (a: HierarchyNode<Datum>, b: HierarchyNode<Datum>) => number): this;
each(func: (node: HierarchyNode<Datum>) => void): this;
eachAfter(func: (node: HierarchyNode<Datum>) => void): this;
eachBefore(func: (node: HierarchyNode<Datum>) => void): this;
copy(): HierarchyNode<Datum>;
/**
* Sorts the children of this node, if any, and each of this node’s descendants’ children,
* in pre-order traversal using the specified compare function, and returns this node.
*
* @param compare The compare function is passed two nodes a and b to compare.
* If a should be before b, the function must return a value less than zero;
* if b should be before a, the function must return a value greater than zero;
* otherwise, the relative order of a and b are not specified. See `array.sort` for more.
*/
sort(compare: (a: this, b: this) => number): this;
/**
* Invokes the specified function for node and each descendant in breadth-first order,
* such that a given node is only visited if all nodes of lesser depth have already been visited,
* as well as all preceding nodes of the same depth.
*
* @param func The specified function is passed the current node.
*/
each(func: (node: this) => void): this;
/**
* Invokes the specified function for node and each descendant in post-order traversal,
* such that a given node is only visited after all of its descendants have already been visited.
*
* @param func The specified function is passed the current node.
*/
eachAfter(func: (node: this) => void): this;
/**
* Invokes the specified function for node and each descendant in pre-order traversal,
* such that a given node is only visited after all of its ancestors have already been visited.
*
* @param func The specified function is passed the current node.
*/
eachBefore(func: (node: this) => void): this;
/**
* Return a deep copy of the subtree starting at this node. The returned deep copy shares the same data, however.
* The returned node is the root of a new tree; the returned node’s parent is always null and its depth is always zero.
*/
copy(): this;
}
/**
* Constructs a root node from the specified hierarchical data.
*
* @param data The root specified data.
* @param children The specified children accessor function invoked for each datum, starting with the root data.
* Must return an array of data representing the children, and return null or undefined if the current datum has no children.
* If children is not specified, it defaults to: `(d) => d.children`.
*/
export function hierarchy<Datum>(data: Datum, children?: (d: Datum) => (Datum[] | null)): HierarchyNode<Datum>;
// -----------------------------------------------------------------------
// Stratify
// -----------------------------------------------------------------------
// TODO: Review the comment in the API documentation related to 'reserved properties': id, parentId, children. If this is referring to the element on node, it should be 'parent'?
export interface StratifyOperator<Datum> {
/**
* Generates a new hierarchy from the specified tabular data. Each node in the returned object has a shallow copy of the properties
* from the corresponding data object, excluding the following reserved properties: id, parentId, children.
*
* @param data The root specified data.
* @throws Error on missing id, ambiguous id, cycle, multiple roots or no root.
*/
(data: Datum[]): HierarchyNode<Datum>;
/**
* Returns the current id accessor, which defaults to: `(d) => d.id`.
*/
id(): (d: Datum, i: number, data: Datum[]) => (string | null | '' | undefined);
/**
* Sets the id accessor to the given function.
* The id accessor is invoked for each element in the input data passed to the stratify operator.
* The returned string is then used to identify the node's relationships in conjunction with the parent id.
* For leaf nodes, the id may be undefined, null or the empty string; otherwise, the id must be unique.
*
* @param id The id accessor.
*/
id(id: (d: Datum, i?: number, data?: Datum[]) => (string | null | '' | undefined)): this;
/**
* Returns the current parent id accessor, which defaults to: `(d) => d.parentId`.
*/
parentId(): (d: Datum, i: number, data: Datum[]) => (string | null | '' | undefined);
/**
* Sets the parent id accessor to the given function.
* The parent id accessor is invoked for each element in the input data passed to the stratify operator.
* The returned string is then used to identify the node's relationships in conjunction with the id.
* For the root node, the parent id should be undefined, null or the empty string.
* There must be exactly one root node in the input data, and no circular relationships.
*
* @param parentId The parent id accessor.
*/
parentId(parentId: (d: Datum, i?: number, data?: Datum[]) => (string | null | '' | undefined)): this;
}
/**
* Constructs a new stratify operator with the default settings.
*/
export function stratify<Datum>(): StratifyOperator<Datum>;
// -----------------------------------------------------------------------
@@ -67,52 +210,86 @@ export function stratify<Datum>(): StratifyOperator<Datum>;
// -----------------------------------------------------------------------
export interface HierarchyPointLink<Datum> {
/**
* The source of the link.
*/
source: HierarchyPointNode<Datum>;
/**
* The target of the link.
*/
target: HierarchyPointNode<Datum>;
}
export interface HierarchyPointNode<Datum> {
export interface HierarchyPointNode<Datum> extends HierarchyNode<Datum> {
/**
* The x-coordinate of the node.
*/
x: number;
/**
* The y-coordinate of the node.
*/
y: number;
data: Datum;
readonly depth: number;
readonly height: number;
parent: HierarchyPointNode<Datum> | null;
children?: Array<HierarchyPointNode<Datum>>;
/**
* Aggregated numeric value as calculated by sum(value) or count(),
* if previously invoked.
* Returns an array of links for this node, where each link is an object that defines source and target properties.
* The source of each link is the parent node, and the target is a child node.
*/
readonly value?: number;
/**
* Optional Node Id string set by StratifyOperator, if
* hierarchical data was created from tabular data using stratify()
*/
readonly id?: string;
ancestors(): Array<HierarchyPointNode<Datum>>;
descendants(): Array<HierarchyPointNode<Datum>>;
leaves(): Array<HierarchyPointNode<Datum>>;
path(target: HierarchyPointNode<Datum>): Array<HierarchyPointNode<Datum>>;
links(): Array<HierarchyPointLink<Datum>>;
sum(value: (d: Datum) => number): this;
count(): this;
sort(compare: (a: HierarchyPointNode<Datum>, b: HierarchyPointNode<Datum>) => number): this;
each(func: (node: HierarchyPointNode<Datum>) => void): this;
eachAfter(func: (node: HierarchyPointNode<Datum>) => void): this;
eachBefore(func: (node: HierarchyPointNode<Datum>) => void): this;
copy(): HierarchyPointNode<Datum>;
}
export interface ClusterLayout<Datum> {
/**
* Lays out the specified root hierarchy.
* You may want to call `root.sort` before passing the hierarchy to the cluster layout.
*
* @param root The specified root hierarchy.
*/
(root: HierarchyNode<Datum>): HierarchyPointNode<Datum>;
/**
* Returns the current layout size, which defaults to [1, 1]. A layout size of null indicates that a node size will be used instead.
*/
size(): [number, number] | null;
/**
* Sets this cluster layout’s size to the specified [width, height] array and returns the cluster layout.
* The size represent an arbitrary coordinate system; for example, to produce a radial layout,
* a size of [360, radius] corresponds to a breadth of 360° and a depth of radius.
*
* @param size The specified two-element size array.
*/
size(size: [number, number]): this;
/**
* Returns the current node size, which defaults to null. A node size of null indicates that a layout size will be used instead.
*/
nodeSize(): [number, number] | null;
/**
* Sets this cluster layout’s node size to the specified [width, height] array and returns this cluster layout.
* When a node size is specified, the root node is always positioned at <0, 0>.
*
* @param size The specified two-element size array.
*/
nodeSize(size: [number, number]): this;
/**
* Returns the current separation accessor, which defaults to: `(a, b) => a.parent == b.parent ? 1 : 2`.
*/
separation(): (a: HierarchyPointNode<Datum>, b: HierarchyPointNode<Datum>) => number;
/**
* Sets the separation accessor to the specified function and returns this cluster layout.
* The separation accessor is used to separate neighboring leaves.
*
* @param separation The separation function is passed two leaves a and b, and must return the desired separation.
* The nodes are typically siblings, though the nodes may be more distantly related if the layout decides to place such nodes adjacent.
*/
separation(separation: (a: HierarchyPointNode<Datum>, b: HierarchyPointNode<Datum>) => number): this;
}
/**
* Creates a new cluster layout with default settings.
*/
export function cluster<Datum>(): ClusterLayout<Datum>;
// -----------------------------------------------------------------------
@@ -120,15 +297,56 @@ export function cluster<Datum>(): ClusterLayout<Datum>;
// -----------------------------------------------------------------------
export interface TreeLayout<Datum> {
/**
* Lays out the specified root hierarchy.
* You may want to call `root.sort` before passing the hierarchy to the tree layout.
*
* @param root The specified root hierarchy.
*/
(root: HierarchyNode<Datum>): HierarchyPointNode<Datum>;
/**
* Returns the current layout size, which defaults to [1, 1]. A layout size of null indicates that a node size will be used instead.
*/
size(): [number, number] | null;
/**
* Sets this tree layout’s size to the specified [width, height] array and returns the tree layout.
* The size represent an arbitrary coordinate system; for example, to produce a radial layout,
* a size of [360, radius] corresponds to a breadth of 360° and a depth of radius.
*
* @param size The specified two-element size array.
*/
size(size: [number, number]): this;
/**
* Returns the current node size, which defaults to null. A node size of null indicates that a layout size will be used instead.
*/
nodeSize(): [number, number] | null;
/**
* Sets this tree layout’s node size to the specified [width, height] array and returns this tree layout.
* When a node size is specified, the root node is always positioned at <0, 0>.
*
* @param size The specified two-element size array.
*/
nodeSize(size: [number, number]): this;
/**
* Returns the current separation accessor, which defaults to: `(a, b) => a.parent == b.parent ? 1 : 2`.
*/
separation(): (a: HierarchyPointNode<Datum>, b: HierarchyPointNode<Datum>) => number;
/**
* Sets the separation accessor to the specified function and returns this tree layout.
* The separation accessor is used to separate neighboring nodes.
*
* @param separation The separation function is passed two nodes a and b, and must return the desired separation.
* The nodes are typically siblings, though the nodes may be more distantly related if the layout decides to place such nodes adjacent.
*/
separation(separation: (a: HierarchyPointNode<Datum>, b: HierarchyPointNode<Datum>) => number): this;
}
/**
* Creates a new tree layout with default settings.
*/
export function tree<Datum>(): TreeLayout<Datum>;
// -----------------------------------------------------------------------
@@ -136,91 +354,283 @@ export function tree<Datum>(): TreeLayout<Datum>;
// -----------------------------------------------------------------------
export interface HierarchyRectangularLink<Datum> {
/**
* The source of the link.
*/
source: HierarchyRectangularNode<Datum>;
/**
* The target of the link.
*/
target: HierarchyRectangularNode<Datum>;
}
export interface HierarchyRectangularNode<Datum> {
export interface HierarchyRectangularNode<Datum> extends HierarchyNode<Datum> {
/**
* The left edge of the rectangle.
*/
x0: number;
/**
* The top edge of the rectangle
*/
y0: number;
/**
* The right edge of the rectangle.
*/
x1: number;
/**
* The bottom edge of the rectangle.
*/
y1: number;
data: Datum;
readonly depth: number;
readonly height: number;
parent: HierarchyRectangularNode<Datum> | null;
children?: Array<HierarchyRectangularNode<Datum>>;
/**
* Aggregated numeric value as calculated by sum(value) or count(),
* if previously invoked.
* Returns an array of links for this node, where each link is an object that defines source and target properties.
* The source of each link is the parent node, and the target is a child node.
*/
readonly value?: number;
/**
* Optional Node Id string set by StratifyOperator, if
* hierarchical data was created from tabular data using stratify()
*/
readonly id?: string;
ancestors(): Array<HierarchyRectangularNode<Datum>>;
descendants(): Array<HierarchyRectangularNode<Datum>>;
leaves(): Array<HierarchyRectangularNode<Datum>>;
path(target: HierarchyRectangularNode<Datum>): Array<HierarchyRectangularNode<Datum>>;
links(): Array<HierarchyRectangularLink<Datum>>;
sum(value: (d: Datum) => number): this;
count(): this;
sort(compare: (a: HierarchyRectangularNode<Datum>, b: HierarchyRectangularNode<Datum>) => number): this;
each(func: (node: HierarchyRectangularNode<Datum>) => void): this;
eachAfter(func: (node: HierarchyRectangularNode<Datum>) => void): this;
eachBefore(func: (node: HierarchyRectangularNode<Datum>) => void): this;
copy(): HierarchyRectangularNode<Datum>;
}
export interface TreemapLayout<Datum> {
/**
* Lays out the specified root hierarchy.
* You must call `root.sum` before passing the hierarchy to the treemap layout.
* You probably also want to call `root.sort` to order the hierarchy before computing the layout.
*
* @param root The specified root hierarchy.
*/
(root: HierarchyNode<Datum>): HierarchyRectangularNode<Datum>;
/**
* Returns the current tiling method, which defaults to `d3.treemapSquarify` with the golden ratio.
*/
tile(): (node: HierarchyRectangularNode<Datum>, x0: number, y0: number, x1: number, y1: number) => void;
/**
* Sets the tiling method to the specified function and returns this treemap layout.
*
* @param tile The specified tiling function.
*/
tile(tile: (node: HierarchyRectangularNode<Datum>, x0: number, y0: number, x1: number, y1: number) => void): this;
/**
* Returns the current size, which defaults to [1, 1].
*/
size(): [number, number];
/**
* Sets this treemap layout’s size to the specified [width, height] array and returns this treemap layout.
*
* @param size The specified two-element size array.
*/
size(size: [number, number]): this;
/**
* Returns the current rounding state, which defaults to false.
*/
round(): boolean;
/**
* Enables or disables rounding according to the given boolean and returns this treemap layout.
*
* @param round The specified boolean flag.
*/
round(round: boolean): this;
/**
* Returns the current inner padding function.
*/
padding(): (node: HierarchyRectangularNode<Datum>) => number;
/**
* Sets the inner and outer padding to the specified number and returns this treemap layout.
*
* @param padding The specified padding value.
*/
padding(padding: number): this;
/**
* Sets the inner and outer padding to the specified function and returns this treemap layout.
*
* @param padding The specified padding function.
*/
padding(padding: (node: HierarchyRectangularNode<Datum>) => number): this;
/**
* Returns the current inner padding function, which defaults to the constant zero.
*/
paddingInner(): (node: HierarchyRectangularNode<Datum>) => number;
/**
* Sets the inner padding to the specified number and returns this treemap layout.
* The inner padding is used to separate a node’s adjacent children.
*
* @param padding The specified inner padding value.
*/
paddingInner(padding: number): this;
/**
* Sets the inner padding to the specified function and returns this treemap layout.
* The function is invoked for each node with children, being passed the current node.
* The inner padding is used to separate a node’s adjacent children.
*
* @param padding The specified inner padding function.
*/
paddingInner(padding: (node: HierarchyRectangularNode<Datum>) => number): this;
/**
* Returns the current top padding function.
*/
paddingOuter(): (node: HierarchyRectangularNode<Datum>) => number;
/**
* Sets the top, right, bottom and left padding to the specified function and returns this treemap layout.
*
* @param padding The specified padding outer value.
*/
paddingOuter(padding: number): this;
/**
* Sets the top, right, bottom and left padding to the specified function and returns this treemap layout.
*
* @param padding The specified padding outer function.
*/
paddingOuter(padding: (node: HierarchyRectangularNode<Datum>) => number): this;
/**
* Returns the current top padding function, which defaults to the constant zero.
*/
paddingTop(): (node: HierarchyRectangularNode<Datum>) => number;
/**
* Sets the top padding to the specified number and returns this treemap layout.
* The top padding is used to separate the top edge of a node from its children.
*
* @param padding The specified top padding value.
*/
paddingTop(padding: number): this;
/**
* Sets the top padding to the specified function and returns this treemap layout.
* The function is invoked for each node with children, being passed the current node.
* The top padding is used to separate the top edge of a node from its children.
*
* @param padding The specified top padding function.
*/
paddingTop(padding: (node: HierarchyRectangularNode<Datum>) => number): this;
/**
* Returns the current right padding function, which defaults to the constant zero.
*/
paddingRight(): (node: HierarchyRectangularNode<Datum>) => number;
/**
* Sets the right padding to the specified number and returns this treemap layout.
* The right padding is used to separate the right edge of a node from its children.
*
* @param padding The specified right padding value.
*/
paddingRight(padding: number): this;
/**
* Sets the right padding to the specified function and returns this treemap layout.
* The function is invoked for each node with children, being passed the current node.
* The right padding is used to separate the right edge of a node from its children.
*
* @param padding The specified right padding function.
*/
paddingRight(padding: (node: HierarchyRectangularNode<Datum>) => number): this;
/**
* Returns the current bottom padding function, which defaults to the constant zero.
*/
paddingBottom(): (node: HierarchyRectangularNode<Datum>) => number;
/**
* Sets the bottom padding to the specified number and returns this treemap layout.
* The bottom padding is used to separate the bottom edge of a node from its children.
*
* @param padding The specified bottom padding value.
*/
paddingBottom(padding: number): this;
/**
* Sets the bottom padding to the specified function and returns this treemap layout.
* The function is invoked for each node with children, being passed the current node.
* The bottom padding is used to separate the bottom edge of a node from its children.
*
* @param padding The specified bottom padding function.
*/
paddingBottom(padding: (node: HierarchyRectangularNode<Datum>) => number): this;
/**
* Returns the current left padding function, which defaults to the constant zero.
*/
paddingLeft(): (node: HierarchyRectangularNode<Datum>) => number;
/**
* Sets the left padding to the specified number and returns this treemap layout.
* The left padding is used to separate the left edge of a node from its children.
*
* @param padding The specified left padding value.
*/
paddingLeft(padding: number): this;
/**
* Sets the left padding to the specified function and returns this treemap layout.
* The function is invoked for each node with children, being passed the current node.
* The left padding is used to separate the left edge of a node from its children.
*
* @param padding The specified left padding function.
*/
paddingLeft(padding: (node: HierarchyRectangularNode<Datum>) => number): this;
}
/**
* Creates a new treemap layout with default settings.
*/
export function treemap<Datum>(): TreemapLayout<Datum>;
// Tiling functions ---------------------------------------------------------------------------------
// Tiling functions -----------------------------------------------------------------------
/**
* Recursively partitions the specified nodes into an approximately-balanced binary tree,
* choosing horizontal partitioning for wide rectangles and vertical partitioning for tall rectangles.
*/
export function treemapBinary(node: HierarchyRectangularNode<any>, x0: number, y0: number, x1: number, y1: number): void;
/**
* Divides the rectangular area specified by x0, y0, x1, y1 horizontally according the value of each of the specified node’s children.
* The children are positioned in order, starting with the left edge (x0) of the given rectangle.
* If the sum of the children’s values is less than the specified node’s value (i.e., if the specified node has a non-zero internal value),
* the remaining empty space will be positioned on the right edge (x1) of the given rectangle.
*/
export function treemapDice(node: HierarchyRectangularNode<any>, x0: number, y0: number, x1: number, y1: number): void;
/**
* Divides the rectangular area specified by x0, y0, x1, y1 vertically according the value of each of the specified node’s children.
* The children are positioned in order, starting with the top edge (y0) of the given rectangle.
* If the sum of the children’s values is less than the specified node’s value (i.e., if the specified node has a non-zero internal value),
* the remaining empty space will be positioned on the bottom edge (y1) of the given rectangle.
*/
export function treemapSlice(node: HierarchyRectangularNode<any>, x0: number, y0: number, x1: number, y1: number): void;
/**
* If the specified node has odd depth, delegates to treemapSlice; otherwise delegates to treemapDice.
*/
export function treemapSliceDice(node: HierarchyRectangularNode<any>, x0: number, y0: number, x1: number, y1: number): void;
// TODO: Test Factory code
export interface RatioSquarifyTilingFactory {
(node: HierarchyRectangularNode<any>, x0: number, y0: number, x1: number, y1: number): void;
/**
* Specifies the desired aspect ratio of the generated rectangles.
* Note that the orientation of the generated rectangles (tall or wide) is not implied by the ratio.
* Furthermore, the rectangles ratio are not guaranteed to have the exact specified aspect ratio.
* If not specified, the aspect ratio defaults to the golden ratio, φ = (1 + sqrt(5)) / 2, per Kong et al.
*
* @param ratio The specified ratio value greater than or equal to one.
*/
ratio(ratio: number): RatioSquarifyTilingFactory;
}
/**
* Implements the squarified treemap algorithm by Bruls et al., which seeks to produce rectangles of a given aspect ratio.
*/
export const treemapSquarify: RatioSquarifyTilingFactory;
/**
* Like `d3.treemapSquarify`, except preserves the topology (node adjacencies) of the previous layout computed by `d3.treemapResquarify`,
* if there is one and it used the same target aspect ratio. This tiling method is good for animating changes to treemaps because
* it only changes node sizes and not their relative positions, thus avoiding distracting shuffling and occlusion.
* The downside of a stable update, however, is a suboptimal layout for subsequent updates: only the first layout uses the Bruls et al. squarified algorithm.
*/
export const treemapResquarify: RatioSquarifyTilingFactory;
// -----------------------------------------------------------------------
@@ -228,15 +638,53 @@ export const treemapResquarify: RatioSquarifyTilingFactory;
// -----------------------------------------------------------------------
export interface PartitionLayout<Datum> {
/**
* Lays out the specified root hierarchy.
* You must call `root.sum` before passing the hierarchy to the partition layout.
* You probably also want to call `root.sort` to order the hierarchy before computing the layout.
*
* @param root The specified root hierarchy.
*/
(root: HierarchyNode<Datum>): HierarchyRectangularNode<Datum>;
/**
* Returns the current size, which defaults to [1, 1].
*/
size(): [number, number];
/**
* Sets this partition layout’s size to the specified [width, height] array and returns this partition layout.
*
* @param size The specified two-element size array.
*/
size(size: [number, number]): this;
/**
* Returns the current rounding state, which defaults to false.
*/
round(): boolean;
/**
* Enables or disables rounding according to the given boolean and returns this partition layout.
*
* @param round The specified boolean flag.
*/
round(round: boolean): this;
/**
* Returns the current padding, which defaults to zero.
*/
padding(): number;
/**
* Sets the padding to the specified number and returns this partition layout.
* The padding is used to separate a node’s adjacent children.
*
* @param padding The specified padding value.
*/
padding(padding: number): this;
}
/**
* Creates a new partition layout with the default settings.
*/
export function partition<Datum>(): PartitionLayout<Datum>;
// -----------------------------------------------------------------------
@@ -244,54 +692,110 @@ export function partition<Datum>(): PartitionLayout<Datum>;
// -----------------------------------------------------------------------
export interface HierarchyCircularLink<Datum> {
/**
* The source of the link.
*/
source: HierarchyCircularNode<Datum>;
/**
* The target of the link.
*/
target: HierarchyCircularNode<Datum>;
}
export interface HierarchyCircularNode<Datum> {
export interface HierarchyCircularNode<Datum> extends HierarchyNode<Datum> {
/**
* The x-coordinate of the circle’s center.
*/
x: number;
/**
* The y-coordinate of the circle’s center.
*/
y: number;
/**
* The radius of the circle.
*/
r: number;
data: Datum;
readonly depth: number;
readonly height: number;
parent: HierarchyCircularNode<Datum> | null;
children?: Array<HierarchyCircularNode<Datum>>;
/**
* Aggregated numeric value as calculated by sum(value) or count(),
* if previously invoked.
* Returns an array of links for this node, where each link is an object that defines source and target properties.
* The source of each link is the parent node, and the target is a child node.
*/
readonly value?: number;
/**
* Optional Node Id string set by StratifyOperator, if
* hierarchical data was created from tabular data using stratify()
*/
readonly id?: string;
ancestors(): Array<HierarchyCircularNode<Datum>>;
descendants(): Array<HierarchyCircularNode<Datum>>;
leaves(): Array<HierarchyCircularNode<Datum>>;
path(target: HierarchyCircularNode<Datum>): Array<HierarchyCircularNode<Datum>>;
links(): Array<HierarchyCircularLink<Datum>>;
sum(value: (d: Datum) => number): this;
count(): this;
sort(compare: (a: HierarchyCircularNode<Datum>, b: HierarchyCircularNode<Datum>) => number): this;
each(func: (node: HierarchyCircularNode<Datum>) => void): this;
eachAfter(func: (node: HierarchyCircularNode<Datum>) => void): this;
eachBefore(func: (node: HierarchyCircularNode<Datum>) => void): this;
copy(): HierarchyCircularNode<Datum>;
}
export interface PackLayout<Datum> {
/**
* Lays out the specified root hierarchy.
* You must call `root.sum` before passing the hierarchy to the pack layout.
* You probably also want to call `root.sort` to order the hierarchy before computing the layout.
*
* @param root The specified root hierarchy.
*/
(root: HierarchyNode<Datum>): HierarchyCircularNode<Datum>;
/**
* Returns the current radius accessor, which defaults to null.
*/
radius(): null | ((node: HierarchyCircularNode<Datum>) => number);
/**
* Sets the pack layout’s radius accessor to the specified function and returns this pack layout.
* If the radius accessor is null, the radius of each leaf circle is derived from the leaf `node.value` (computed by `node.sum`);
* the radii are then scaled proportionally to fit the layout size.
* If the radius accessor is not null, the radius of each leaf circle is specified exactly by the function.
*
* @param radius The specified radius accessor.
*/
radius(radius: (node: HierarchyCircularNode<Datum>) => number): this;
/**
* Returns the current size, which defaults to [1, 1].
*/
size(): [number, number];
/**
* Sets this pack layout’s size to the specified [width, height] array and returns this pack layout.
*
* @param size The specified two-element size array.
*/
size(size: [number, number]): this;
/**
* Returns the current padding accessor, which defaults to the constant zero.
*/
padding(): (node: HierarchyCircularNode<Datum>) => number;
/**
* Sets this pack layout’s padding accessor to the specified number and returns this pack layout.
* Returns the current padding accessor, which defaults to the constant zero.
*
* When siblings are packed, tangent siblings will be separated by approximately the specified padding;
* the enclosing parent circle will also be separated from its children by approximately the specified padding.
* If an explicit radius is not specified, the padding is approximate because a two-pass algorithm
* is needed to fit within the layout size: the circles are first packed without padding;
* a scaling factor is computed and applied to the specified padding; and lastly the circles are re-packed with padding.
*
* @param padding The specified padding value.
*/
padding(padding: number): this;
/**
* Sets this pack layout’s padding accessor to the specified function and returns this pack layout.
* Returns the current padding accessor, which defaults to the constant zero.
*
* When siblings are packed, tangent siblings will be separated by approximately the specified padding;
* the enclosing parent circle will also be separated from its children by approximately the specified padding.
* If an explicit radius is not specified, the padding is approximate because a two-pass algorithm
* is needed to fit within the layout size: the circles are first packed without padding;
* a scaling factor is computed and applied to the specified padding; and lastly the circles are re-packed with padding.
*
* @param padding The specified padding function.
*/
padding(padding: (node: HierarchyCircularNode<Datum>) => number): this;
}
/**
* Creates a new pack layout with the default settings.
*/
export function pack<Datum>(): PackLayout<Datum>;
// -----------------------------------------------------------------------
@@ -299,8 +803,19 @@ export function pack<Datum>(): PackLayout<Datum>;
// -----------------------------------------------------------------------
export interface PackCircle {
/**
* The radius of the circle.
*/
r: number;
/**
* The x-coordinate of the circle’s center.
*/
x?: number;
/**
* The y-coordinate of the circle’s center.
*/
y?: number;
}
@@ -309,6 +824,19 @@ export interface PackCircle {
// For invocation of packEnclose the x and y coordinates are mandatory. It seems easier to just comment
// on the mandatory nature, then to create separate interfaces and having to deal with recasting.
/**
* Packs the specified array of circles, each of which must have a `circle.r` property specifying the circle’s radius.
* The circles are positioned according to the front-chain packing algorithm by Wang et al.
*
* @param circles The specified array of circles to pack.
*/
export function packSiblings<Datum extends PackCircle>(circles: Datum[]): Datum[];
/**
* Computes the smallest circle that encloses the specified array of circles, each of which must have
* a `circle.r` property specifying the circle’s radius, and `circle.x` and `circle.y` properties specifying the circle’s center.
* The enclosing circle is computed using the Matoušek-Sharir-Welzl algorithm. (See also Apollonius’ Problem.)
*
* @param circles The specified array of circles to pack.
*/
export function packEnclose<Datum extends PackCircle>(circles: Datum[]): { r: number, x: number, y: number };
+26 -10
View File
@@ -13,19 +13,21 @@ import * as d3Quadtree from 'd3-quadtree';
// ---------------------------------------------------------------------------
// custom type guard
function isLeaf(a: any): a is d3Quadtree.QuadtreeLeaf<any> {
return a.data !== undefined;
function isLeaf<T>(a: d3Quadtree.QuadtreeInternalNode<T> | d3Quadtree.QuadtreeLeaf<T>): a is d3Quadtree.QuadtreeLeaf<T> {
return a.length === undefined;
}
let num: number;
let extent: [[number, number], [number, number]];
let num4: 4;
let undef: undefined;
let extent: [[number, number], [number, number]] | undefined;
interface TestDatum {
x: number;
y: number;
}
let testDatum: TestDatum;
let testDatum: TestDatum | undefined;
let testData: TestDatum[] = [
{ x: 10, y: 20 },
@@ -83,7 +85,6 @@ quadtree = d3Quadtree.quadtree<TestDatum>(testData); // explicitly typed to Test
// test without data
quadtree = d3Quadtree.quadtree<TestDatum>();
// quadtree = d3Quadtree.quadtree(); fails, wrong underlying data type
// Configure Quadtree ========================================================
@@ -111,12 +112,14 @@ quadtree = quadtree.cover(50, 90);
// add(...) ------------------------------------------------------------------
quadtree = quadtree.add({ x: 35, y: 35 });
// quadtree = quadtree.add({x: 35}); // fails, incompatible data type
// $ExpectError
quadtree = quadtree.add({x: 35}); // fails, incompatible data type
// addAll(...) ---------------------------------------------------------------
quadtree = quadtree.addAll(testData);
// quadtree = quadtree.addAll([{x: 35}, {x: 55, y: 13}]); // fails, incompatible data type
// $ExpectError
quadtree = quadtree.addAll([{x: 35}, {x: 55, y: 13}]); // fails, incompatible data type
// remove(...) ---------------------------------------------------------------
@@ -191,9 +194,10 @@ quadtree = quadtree.visit((node, x0, y0, x1, y1) => {
}
});
// quadtree = quadtree.visit(function (node, x0, y0, x1, y1) {
// return 10; // fails wrong return type
// });
// $ExpectError
quadtree = quadtree.visit((node, x0, y0, x1, y1) => {
return 10; // fails wrong return type
});
// visitAfter() ---------------------------------------------------------------
@@ -232,3 +236,15 @@ quadNode = internalNode[0];
quadNode = internalNode[1];
quadNode = internalNode[2];
quadNode = internalNode[3];
num = internalNode.length;
num4 = internalNode.length;
quadtree = quadtree.visit((node, x0, y0, x1, y1) => {
if (isLeaf(node)) {
undef = node.length;
} else {
num = node.length;
num4 = node.length;
}
});
+165 -10
View File
@@ -1,17 +1,34 @@
// Type definitions for D3JS d3-quadtree module 1.0
// Project: https://github.com/d3/d3-quadtree/
// Definitions by: Tom Wanzek <https://github.com/tomwanzek>, Alex Ford <https://github.com/gustavderdrache>, Boris Yankov <https://github.com/borisyankov>
// Definitions by: Tom Wanzek <https://github.com/tomwanzek>
// Alex Ford <https://github.com/gustavderdrache>
// Boris Yankov <https://github.com/borisyankov>
// denisname <https://github.com/denisname>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// Last module patch version validated against: 1.0.1
// Last module patch version validated against: 1.0.3
/**
* Leaf node of the quadtree.
*/
export interface QuadtreeLeaf<T> {
/**
* The data associated with this point, as passed to quadtree.add.
*/
data: T;
/**
* The next datum in this leaf, if any.
*/
next?: QuadtreeLeaf<T>;
/**
* The length property may be used to distinguish leaf nodes from internal nodes: it is undefined for leaf nodes, and 4 for internal nodes.
*/
length?: undefined;
}
/**
* Internal nodes of the quadtree are represented as four-element arrays in left-to-right, top-to-bottom order:
*
@@ -22,32 +39,170 @@ export interface QuadtreeLeaf<T> {
*
* A child quadrant may be undefined if it is empty.
*/
export interface QuadtreeInternalNode<T> extends Array<QuadtreeInternalNode<T> | QuadtreeLeaf<T> | undefined> { }
export interface QuadtreeInternalNode<T> extends Array<QuadtreeInternalNode<T> | QuadtreeLeaf<T> | undefined> {
/**
* The length property may be used to distinguish leaf nodes from internal nodes: it is undefined for leaf nodes, and 4 for internal nodes.
*/
length: 4;
}
export interface Quadtree<T> {
/**
* Returns the current x-accessor, which defaults to: `x(d) => d[0]`.
*/
x(): (d: T) => number;
/**
* Sets the current x-coordinate accessor and returns the quadtree.
* The x-accessors must be consistent, returning the same value given the same input.
*
* @param x The x-coordinate accessor.
*/
x(x: (d: T) => number): this;
/**
* Returns the current y-accessor, which defaults to: `y(d) => d[1]`.
*/
y(): (d: T) => number;
/**
* Sets the current y-coordinate accessor and returns the quadtree.
* The y-accessors must be consistent, returning the same value given the same input.
*
* @param y The y-coordinate accessor.
*/
y(y: (d: T) => number): this;
/**
* Returns the quadtree's current extent `[[x0, y0], [x1, y1]]`,
* where `x0` and `y0` are the inclusive lower bounds and `x1` and `y1` are the inclusive upper bounds,
* or `undefined` if the quadtree has no extent.
*/
extent(): [[number, number], [number, number]] | undefined;
/**
* Expands the quadtree to cover the specified points `[[x0, y0], [x1, y1]]` and returns the quadtree.
* The extent may also be expanded by calling `quadtree.cover` or `quadtree.add`.
*
* @param extend The specified points to cover.
*/
extent(extend: [[number, number], [number, number]]): this;
/**
* Expands the quadtree to cover the specified point ⟨x,y⟩, and returns the quadtree.
* * If the quadtree’s extent already covers the specified point, this method does nothing.
* * If the quadtree has an extent, the extent is repeatedly doubled to cover the specified point, wrapping the root node as necessary.
* * If the quadtree is empty, the extent is initialized to the extent `[[⌊x⌋, ⌊y⌋], [⌈x⌉, ⌈y⌉]]`.
* Rounding is necessary such that if the extent is later doubled, the boundaries of existing quadrants do not change due to floating point error.
*
* @param x The x-coordinate for the specified point to cover.
* @param y The y-coordinate for the specified point to cover.
*/
cover(x: number, y: number): this;
/**
* Adds the specified datum to the quadtree, deriving its coordinates ⟨x,y⟩ using the current x- and y-accessors, and returns the quadtree.
* If the new point is outside the current extent of the quadtree, the quadtree is automatically expanded to cover the new point.
*
* @param datum The specified datum to add.
*/
add(datum: T): this;
/**
* Adds the specified array of data to the quadtree, deriving each element’s coordinates ⟨x,y⟩ using the current x- and y-accessors, and return this quadtree.
* This is approximately equivalent to calling quadtree.add repeatedly.
* However, this method results in a more compact quadtree because the extent of the data is computed first before adding the data.
*
* @param data The specified array of data to add.
*/
addAll(data: T[]): this;
/**
* Removes the specified datum to the quadtree, deriving its coordinates ⟨x,y⟩ using the current x- and y-accessors, and returns the quadtree.
* If the specified datum does not exist in this quadtree, this method does nothing.
*
* @param datum The specified datum to remove.
*/
remove(datum: T): this;
/**
* Removes the specified data to the quadtree, deriving their coordinates ⟨x,y⟩ using the current x- and y-accessors, and returns the quadtree.
* If a specified datum does not exist in this quadtree, it is ignored.
*
* @param data The specified array of data to remove.
*/
removeAll(data: T[]): this;
/**
* Returns a copy of the quadtree. All nodes in the returned quadtree are identical copies of the corresponding node in the quadtree;
* however, any data in the quadtree is shared by reference and not copied.
*/
copy(): Quadtree<T>;
/**
* Returns the root node of the quadtree.
*/
root(): QuadtreeInternalNode<T> | QuadtreeLeaf<T>;
/**
* Returns an array of all data in the quadtree.
*/
data(): T[];
/**
* Returns the total number of data in the quadtree.
*/
size(): number;
/**
* Returns the datum closest to the position ⟨x,y⟩ with the given search radius. If radius is not specified, it defaults to infinity.
* If there is no datum within the search area, returns undefined.
*
* @param x The x-coordinate for the search position.
* @param y The y-coordinate for the search position.
* @param radius The optional search radius.
*/
find(x: number, y: number, radius?: number): T | undefined;
// TODO: Review below, when validating to strictNullChecks.
// tslint:disable-next-line:void-return
visit(callback: (node: QuadtreeInternalNode<T> | QuadtreeLeaf<T>, x0: number, y0: number, x1: number, y1: number) => (void | boolean)): this;
/**
* Visits each node in the quadtree in pre-order traversal, invoking the specified callback with arguments `node`, `x0`, `y0`, `x1`, `y1` for each node,
* where `node` is the node being visited, ⟨x0, y0⟩ are the lower bounds of the node, and ⟨x1, y1⟩ are the upper bounds, and returns the quadtree.
*
* If the callback returns true for a given node, then the children of that node are not visited; otherwise, all child nodes are visited.
* This can be used to quickly visit only parts of the tree.
* Note, however, that child quadrants are always visited in sibling order: top-left, top-right, bottom-left, bottom-right.
* In cases such as search, visiting siblings in a specific order may be faster.
*
* @param callback The callback invoked for each node.
*/
visit(callback: (node: QuadtreeInternalNode<T> | QuadtreeLeaf<T>, x0: number, y0: number, x1: number, y1: number) => void | boolean): this;
/**
* Visits each node in the quadtree in post-order traversal, invoking the specified callback with arguments `node`, `x0`, `y0`, `x1`, `y1` for each node,
* where `node` is the node being visited, ⟨x0, y0⟩ are the lower bounds of the node, and ⟨x1, y1⟩ are the upper bounds, and returns the quadtree.
*
* @param callback The callback invoked for each node.
*/
visitAfter(callback: (node: QuadtreeInternalNode<T> | QuadtreeLeaf<T>, x0: number, y0: number, x1: number, y1: number) => void): this;
}
export function quadtree(): Quadtree<[number, number]>;
export function quadtree(data: Array<[number, number]>): Quadtree<[number, number]>;
export function quadtree<T>(): Quadtree<T>;
export function quadtree<T>(data: T[], x?: (d: T) => number, y?: (d: T) => number): Quadtree<T>;
/**
* Creates a new, empty quadtree with an empty extent and the default x- and y-accessors.
*
* The generic refers to the data type. If omitted, the default setting assumes that,
* the data used with the quadtree are two-element arrays.
* The first element corresponds to the x-dimension, the second to the y-dimension.
* When using another type, The x- and y-accessors must be specified.
*/
export function quadtree<T = [number, number]>(): Quadtree<T>;
/**
* Creates a new quadtree with the specified array of data.
* If `x` and `y` are also specified, sets the x- and y- accessors to the specified functions before adding the specified array of data to the quadtree, otherwise use the default x- and y-accessors.
*
* The generic refers to the data type. If omitted, the default setting assumes that,
* the data used with the quadtree are two-element arrays.
* The first element corresponds to the x-dimension, the second to the y-dimension.
* When using another type, The x- and y-accessors must be specified.
*
* @param data The specified array of data to add.
* @param x The x-coordinate accessor.
* @param y The y-coordinate accessor.
*/
export function quadtree<T = [number, number]>(data: T[], x?: (d: T) => number, y?: (d: T) => number): Quadtree<T>;
+1 -1
View File
@@ -7,7 +7,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
+2 -2
View File
@@ -796,7 +796,7 @@ newDiv2 = body.append(function(d, i, g) {
const index: number = i;
const group: HTMLBodyElement[] | d3Selection.ArrayLike<HTMLBodyElement> = g;
console.log('Body element foo property: ', d.foo); // data of type BodyDatum
return this.ownerDocument.createElement('div'); // this-type HTMLBodyElement
return this.ownerDocument!.createElement('div'); // this-type HTMLBodyElement
});
// newDiv2 = body.append<HTMLDivElement>(function(d) {
@@ -828,7 +828,7 @@ const typeValueFunction = function(
i: number,
g: HTMLBodyElement[] | d3Selection.ArrayLike<HTMLBodyElement>
) {
return this.ownerDocument.createElement('p'); // this-type HTMLParagraphElement
return this.ownerDocument!.createElement('p'); // this-type HTMLParagraphElement
};
const beforeValueFunction = function(
+1 -1
View File
@@ -22,7 +22,7 @@ export type BaseType = Element | EnterElement | Document | Window | null;
*/
export interface ArrayLike<T> {
length: number;
item(index: number): T;
item(index: number): T | null;
[index: number]: T;
}
@@ -1073,3 +1073,92 @@ const util_1: boolean = dt.any();
const util_2: number = dt.count();
//#endregion "Methods-Util"
//#region "ExtSettings"
const ext_classes_settings: DataTables.ExtClassesSettings = {
};
const ext_classes_settings_full: DataTables.ExtClassesSettings = {
sFilter: "",
sFilterInput: "",
sFooterTH: "",
sHeaderTH: "",
sInfo: "",
sJUIFooter: "",
sJUIHeader: "",
sLength: "",
sLengthSelect: "",
sNoFooter: "",
sPageButton: "",
sPageButtonActive: "",
sPageButtonDisabled: "",
sPaging: "",
sProcessing: "",
sRowEmpty: "",
sScrollBody: "",
sScrollFoot: "",
sScrollFootInner: "",
sScrollHead: "",
sScrollHeadInner: "",
sScrollWrapper: "",
sSortable: "",
sSortableAsc: "",
sSortableDesc: "",
sSortableNone: "",
sSortAsc: "",
sSortColumn: "",
sSortDesc: "",
sSortIcon: "",
sSortJUI: "",
sSortJUIAsc: "",
sSortJUIAscAllowed: "",
sSortJUIDesc: "",
sSortJUIDescAllowed: "",
sSortJUIWrapper: "",
sStripeEven: "",
sStripeOdd: "",
sTable: "",
sWrapper: ""
};
const ext_type_settings: DataTables.ExtTypeSettings = {
detect: [],
search: {},
order: {}
};
ext_type_settings.detect.push((d: string, s: DataTables.Settings) => {
return null;
});
ext_type_settings.detect.push((d: string, s: DataTables.Settings) => {
return "";
});
const ext_settings: DataTables.ExtSettings = {
aTypes: [],
afnFiltering: [],
afnSortData: {},
aoFeatures: [],
builder: "",
classes: ext_classes_settings,
errMode: "",
feature: [],
fnVersionCheck: (version: string) => "",
iApiIndex: 0,
internal: {},
legacy: {},
oApi: {},
oJUIClasses: {},
oPagination: {},
oSort: {},
oStdClasses: ext_classes_settings,
ofnSearch: {},
order: {},
pager: {},
renderer: {},
sVersion: "",
search: [],
selector: {},
type: ext_type_settings
};
//#endregion "ExtSettings"
+36 -1
View File
@@ -2026,7 +2026,10 @@ declare namespace DataTables {
sVersion: string;
search: any[];
selector: object;
type: object;
/**
* Type based plug-ins.
*/
type: ExtTypeSettings;
}
interface ExtClassesSettings {
@@ -2208,4 +2211,36 @@ declare namespace DataTables {
sJUIFooter?: string;
}
//#endregion "ext internal"
interface ExtTypeSettings {
/**
* Type detection functions for plug-in development.
*
* @see https://datatables.net/manual/plug-ins/type-detection
*/
detect: FunctionExtTypeSettingsDetect[];
/**
* Type based ordering functions for plug-in development.
*
* @see https://datatables.net/manual/plug-ins/sorting
* @default {}
*/
order: object;
/**
* Type based search formatting for plug-in development.
*
* @default {}
* @example
* $.fn.dataTable.ext.type.search['title-numeric'] = function ( d ) {
* return d.replace(/\n/g," ").replace( /<.*?>/g, "" );
* }
*/
search: object;
}
/**
* @param data Data from the column cell to be analysed.
* @param DataTables settings object.
*/
type FunctionExtTypeSettingsDetect = (data: any, settings: Settings) => (string | null);
}
+3
View File
@@ -0,0 +1,3 @@
import isNode = require("detect-node");
isNode;
+8
View File
@@ -0,0 +1,8 @@
// Type definitions for detect-node 2.0
// Project: https://github.com/iliakan/detect-node
// Definitions by: Leonid Logvinov <https://github.com/LogvinovLeon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
declare const isNode: boolean;
export = isNode;
+16
View File
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": ["index.d.ts", "detect-node-tests.ts"]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+21
View File
@@ -0,0 +1,21 @@
import * as di from "di";
const emptyInjector = new di.Injector();
const moduleSpecifications = [{}];
const fullInjector = new di.Injector(moduleSpecifications);
const childInjector = new di.Injector(moduleSpecifications, emptyInjector);
const dep: {} = fullInjector.get('foo');
const factory = (context: {}, deps: Array<{}>) => {
return {};
};
const invoked: {} = fullInjector.invoke(factory, {});
const oldTimeyClass = {prototype: {}};
const instance: {} = fullInjector.instantiate(oldTimeyClass);
const anotherChildInjector: di.Injector =
fullInjector.createChild(moduleSpecifications);
+15
View File
@@ -0,0 +1,15 @@
// Type definitions for di 0.0
// Project: https://github.com/vojtajina/node-di
// Definitions by: John J Barton <https://github.com/johnjbarton>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
/// <reference types="node" />
export class Injector {
get(dep: string): {};
invoke(fn: (context: {}, deps: Array<{}>) => {}, context: {}): {};
instantiate({prototype: {}}): {};
createChild(modules: Array<{}>): Injector;
constructor(modules?: Array<{}>, parent?: Injector);
}
+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",
"di-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1 -1
View File
@@ -1,6 +1,6 @@
import * as dnssd from 'dnssd';
const serviceType = new dnssd.ServiceType(dnssd.tcp('_mqtt'), dnssd.udp('_mqtt'));
const serviceType = dnssd.ServiceType.tcp('_mqtt', '_mqtt._udp');
const advertisement = new dnssd.Advertisement(serviceType, 1883, { name: 'broker' });
const browser: dnssd.Browser = new dnssd.Browser(serviceType);
+42 -32
View File
@@ -1,30 +1,40 @@
// Type definitions for dnssd 0.3
// Type definitions for dnssd 0.4
// Project: https://github.com/DeMille/dnssd.js#readme
// Definitions by: Angel Merino <https://github.com/angelmerino>
// Max Rumpf <https://github.com/Maxr1998>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/// <reference types="node" />
import { EventEmitter } from 'events';
/** Declaration file generated by dts-gen */
export class Advertisement {
constructor(type: any, port: any, ...args: any[]);
export class Advertisement extends EventEmitter {
constructor(type: string | string[] | ServiceType, port: number, ...args: any[]);
start(): any;
start(): Advertisement;
stop(forceImmediate: any, callback: any): void;
stop(forceImmediate?: boolean, callback?: () => any): void;
updateTXT(txtObj: any): void;
}
export class Options {
name?: string;
host?: string;
txt?: any;
subtypes?: string[];
interface?: string;
}
/**
* A service entry as returned by serviceUp
*/
export class Service {
fullname: string; // 'InstanceName._googlecast._tcp.local.'
name: string; // 'InstanceName'
type: SType; // { name: 'googlecast'; protocol: 'tcp' }
type: ServiceType; // { name: 'googlecast'; protocol: 'tcp' }
domain: string; // 'local'
host: string; // 'Hostname.local.'
port: number; // 8009
@@ -33,47 +43,47 @@ export class Service {
txtRaw: any;
}
export class SType {
export class ServiceType {
constructor(...args: Array<string | string[]>)
constructor(args: ServiceType);
name: string;
protocol: string;
subtypes: string[];
toString(): string;
static all(): ServiceType;
static tcp(...args: string[]): ServiceType;
static udp(...args: string[]): ServiceType;
}
export class Browser extends EventEmitter {
constructor(type: any, ...args: any[]);
constructor(type: string | string[] | ServiceType, ...args: any[]);
list(): any;
start(): Browser;
start(): any;
stop(): void;
stop(): any;
list(): any[];
}
export class ServiceType {
constructor(...args: any[]);
export function resolve(name: string, type: string, args: object): Promise<any>;
toString(): any;
export function resolve4(name: string, type: string, args: object): Promise<string>;
static all(): any;
export function resolve6(name: string, type: string, args: object): Promise<string>;
static tcp(...args: any[]): any;
export function resolveSRV(name: string, args: object): Promise<any>;
static udp(...args: any[]): any;
}
export function resolveTXT(name: string, args: object): Promise<any>;
export const resolveA: any;
export function resolveService(name: string, args: object): Promise<any>;
export const resolveAAAA: any;
export function tcp(...args: string[]): ServiceType;
export function all(): any;
export function udp(...args: string[]): ServiceType;
export function resolve(name: any, type: any, ...args: any[]): any;
export function resolveSRV(name: any, opts: any): any;
export function resolveService(name: any, ...args: any[]): any;
export function resolveTXT(name: any, opts: any): any;
export function tcp(...args: any[]): any;
export function udp(...args: any[]): any;
export function all(): ServiceType;
+3 -3
View File
@@ -60,11 +60,11 @@ interface Element extends ParentNode {
matches(selectors: string): boolean;
}
interface Elements extends ElementTraversal, ParentNode, Array<Element> {
interface Elements extends ParentNode, Array<Element> {
}
interface Document extends ElementTraversal, ParentNode {
interface Document extends ParentNode {
}
interface DocumentFragment extends ElementTraversal, ParentNode {
interface DocumentFragment extends ParentNode {
}
+1 -1
View File
@@ -7,6 +7,6 @@ download(new Blob(['hello world']), 'dlTextBlob.txt', 'text/plain');
download('/robots.txt');
download(document.documentElement.outerHTML, 'dlHTML.html', 'text/html');
download(document.documentElement!.outerHTML, 'dlHTML.html', 'text/html');
download(new Blob(['hello world'.bold()]), 'dlHtmlBlob.html', 'text/html');
download('/diff6.png');
+1 -1
View File
@@ -9,7 +9,7 @@
// Santiago Vilar <https://github.com/smvilar>
// Ulf Schwekendiek <https://github.com/sulf>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
// TypeScript Version: 2.8
import * as React from 'react';
import * as Immutable from 'immutable';
+49 -3
View File
@@ -328,11 +328,11 @@ declare module 'ember' {
*/
resolveRegistration(fullName: string): Function;
/**
* Registers a factory that can be used for dependency injection (with
* Registers a factory or value that can be used for dependency injection (with
* `inject`) or for service lookup. Each factory is registered with
* a full name including two parts: `type:name`.
*/
register(fullName: string, factory: Function, options?: { singleton?: boolean, instantiate?: boolean }): any;
register(fullName: string, factory: any, options?: { singleton?: boolean, instantiate?: boolean }): any;
/**
* Unregister a factory.
*/
@@ -3372,7 +3372,48 @@ declare module 'ember' {
/**
* The Router service is the public API that provides component/view layer access to the router.
*/
class RouterService extends Ember.Service {
export class RouterService extends Ember.Service {
//
/**
Name of the current route.
This property represent the logical name of the route,
which is comma separated.
For the following router:
```app/router.js
Router.map(function() {
this.route('about');
this.route('blog', function () {
this.route('post', { path: ':post_id' });
});
});
```
It will return:
* `index` when you visit `/`
* `about` when you visit `/about`
* `blog.index` when you visit `/blog`
* `blog.post` when you visit `/blog/some-post-id`
*/
readonly currentRouteName: string;
//
/**
Current URL for the application.
This property represent the URL path for this route.
For the following router:
```app/router.js
Router.map(function() {
this.route('about');
this.route('blog', function () {
this.route('post', { path: ':post_id' });
});
});
```
It will return:
* `/` when you visit `/`
* `/about` when you visit `/about`
* `/blog` when you visit `/blog`
* `/blog/some-post-id` when you visit `/blog/some-post-id`
*/
readonly currentURL: string;
//
/**
* Determines whether a route is active.
@@ -3776,6 +3817,11 @@ declare module '@ember/routing/router' {
export default class EmberRouter extends Ember.Router { }
}
declare module '@ember/routing/router-service' {
import { RouterService } from 'ember';
export default class extends RouterService { }
}
declare module '@ember/runloop' {
import Ember from 'ember';
export const begin: typeof Ember.run.begin;

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