Merge pull request #1 from DefinitelyTyped/master

Merge
This commit is contained in:
arichter83
2019-01-14 14:13:13 +01:00
committed by GitHub
1639 changed files with 146470 additions and 24468 deletions
+1
View File
@@ -3343,6 +3343,7 @@
/types/oembed-parser/ @BendingBender
/types/ofe/ @Morfent
/types/office-js/ @OfficeDev @LanceEA @Zlatkovsky @kbrandl @Rick-Kirkham @AlexJerabek @ElizabethSamuel-MSFT
/types/office-js-preview @OfficeDev @Zlatkovsky @kbrandl @Rick-Kirkham @AlexJerabek @ElizabethSamuel-MSFT
/types/office-runtime/ @Zlatkovsky @mscharlock
/types/offline-js/ @cgwrench
/types/oibackoff/ @geoffreak
+4 -4
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) and [Korean!](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md)*
*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md), [Korean](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md), and [Russian](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md)!*
## What are declaration files?
@@ -169,10 +169,10 @@ If a package was never on DefinitelyTyped, it does not need to be added to `notN
#### Lint
All new packages must be linted. To lint a package, add a `tslint.json` to that package containing
All new packages must be linted. To lint a package, add a `tslint.json` to that package containing
```js
{
"extends": "dtslint/dt.json"
{
"extends": "dtslint/dt.json"
}
```
+353
View File
@@ -0,0 +1,353 @@
<!-- markdownlint-disable MD001 MD012 MD026 -->
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
[![Join the chat at 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.
Также посетите веб-сайт [definitelytyped.org](http://definitelytyped.org), хотя информация в этом README более свежая.
*Вы также можете прочитать этот README на [английском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md), [испанском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) and [корейском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md).*
## Что такое файлы декларации (файлы описания/объявления типов)?
Смотрите [руководство по TypeScript](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html).
## Как их получить?
### npm
Это предпочтительный метод. Это доступно только для пользователей TypeScript 2.0+. Например:
```sh
npm install --save-dev @types/node
```
Затем типы должны автоматически включаться компилятором.
Подробнее смотрите в [справочнике](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html).
Для пакета NPM "foo", описания будут находиться в "@types/foo".
Если вы не можете найти свой пакет, ищите его в [TypeSearch](https://microsoft.github.io/TypeSearch/).
Если вы все еще не можете найти его, проверьте [включает](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) ли пакет собственную типизацию.
Обычно это отражается в поле `"types"` или `"typings"` файла `package.json`, или просто ищите любые файлы ".d.ts" в пакете и вручную включайте их в `/// <reference path="" />`.
### Другие методы
Эти методы могут быть использованы TypeScript 1.0.
* [Typings](https://github.com/typings/typings)
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (используйте предпочтительные альтернативы, публикация типа nuget DT отключена)
* Вручную загрузите из ветки `master` этого репозитория
Возможно, вам придется добавить ручные [ссылки](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
## Как я могу внести свой вклад?
DefinitelyTyped работает только благодаря вкладу таких пользователей, как вы!
### Тестирование
Прежде чем поделиться своим улучшением с миром, используйте его сами.
#### Тестирование редактирования существующего пакета
Для добавления новых функций вы можете использовать [разрешение модулей](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"],
```
(Вы также можете использовать `src/types`.)
Создайте `types/foo/index.d.ts` содержащие объявления для модуля "foo".
Теперь вы сможете импортировать из `"foo"` в свой код, и он будет направлен к новому определению типа.
Затем запустите сборку (build) *и* запустите код, чтобы убедиться, что ваше определение типа действительно соответствует тому, что происходит во время выполнения.
После того как вы проверили свои определения с реальным кодом, создайте [Запрос на принятие изменений (PR)](#make-a-pull-request)
и следуйте инструкциям [чтобы отредактировать существующий](#edit-an-existing-package) или
[создать новый пакет](#create-a-new-package).
### Запрос на принятие изменений (PR)
После того, как вы проверили ваш пакет, вы можете поделиться им с DefinitelyTyped.
Во-первых, [разветвите](https://guides.github.com/activities/forking/) этот репозиторий, установите [node](https://nodejs.org/), и запустите `npm install`.
#### Изменение существующего пакета
* `cd types/my-package-to-edit`
* Внесите изменения. Не забудьте отредактировать тесты.
Если вы вносите критические изменения, не забудьте [обновить основную версию](#i-want-to-update-a-package-to-a-new-major-version).
* Вы также можете добавить себя в раздел "Definitions by" заголовка пакета.
* Это приведет к тому, что вы будете уведомлены (через ваше имя пользователя GitHub) о том, что кто-то делает запрос на принятие изменений (PR) или проблему с пакетом.
* Сделайте это, добавив свое имя в конец строки, например `// 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` in в директории пакета.
Когда вы создаете PR для редактирования существующего пакета, `dt-bot` должен @-уведомить previous authors.
предыдущих авторов. Если этого не произойдет, вы можете сделать это самостоятельно в комментарии, связанном с PR.
#### Созданое нового пакета
Если вы являетесь автором библиотеки и ваш пакет написан на TypeScript, [свяжите автоматически сгенерированные файлы объявлений](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) в вашем пакете, а не публикуйте в DefinitelyTyped.
Если вы добавляете типизацию для пакета NPM, создайте директорию с тем же именем.
Если пакет, для которого вы добавляете типизацию, отсутствует в NPM, убедитесь, что выбранное вами имя не конфликтует с именем пакета в NPM.
(Вы можете использовать `npm info foo` чтобы проверить наличие пакета `foo`.)
Ваш пакет должен иметь такую ​​структуру:
| Файл | Назначение |
| ------------- | ---------------------------------------------------------------------------------------------------- |
| index.d.ts | Содержит типизацию для пакета. |
| foo-tests.ts | Содержит пример кода, который проверяет типизацию. Этот код *не* запускается, но он проверен на тип. |
| tsconfig.json | Позволяет вам запускать `tsc` внутри пакета. |
| tslint.json | Включает linting. |
Создайте их, запустив `npx dts-gen --dt --name my-package-name --template module` если у вас ≥ 5.2.0, `npm install -g dts-gen` и `dts-gen --dt --name my-package-name --template module` в противном случае.
Посмотреть все варианты на [dts-gen](https://github.com/Microsoft/dts-gen).
Вы можете отредактировать `tsconfig.json` чтобы добавить новые файлы, добавить `"target": "es6"` (необходимо для асинхронных функций), добавить в `"lib"`, или добавить опцию компилятора `"jsx"`.
Члены группы DefinitelyTyped регулярно следят за новыми PR, но имейте в виду, что количество других PR может замедлить ход событий.
Хороший пример пакета смотрите [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).
* Форматирование: либо используйте все табы, либо всегда используйте 4 пробела.
* `function sum(nums: number[]): number`: используйте `ReadonlyArray` если функция не записывает свои параметры.
* `interface Foo { new(): Foo; }`:
Это определяет тип объектов, с методом `new`. Вы, вероятно, хотите объявить `declare class Foo { constructor(); }`.
* `const Class: { new(): IClass; }`:
Предпочитайте использовать объявление класса `class Class { constructor(); }` вместо `new`.
* `getMeAT<T>(): T`:
Если параметр типа не отображается в типах каких-либо параметров, у вас нет универсальной функции, а просто замаскированное утверждение типа.
Предпочитайте использовать утверждение реального типа, например, `getMeAT() as number`.
Пример, где допустим параметр типа: `function id<T>(value: T): T;`.
Пример, где это недопустимо: `function parseJson<T>(json: string): T;`.
Исключение: `new Map<string, number>()` все ОК.
* Использование типов `Function` and `Object` почти никогда не является хорошей идеей. В 99% случаев можно указать более конкретный тип. Примеры: `(x: number) => number` для [функций](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) and `{ x: number, y: number }` для объектов. Если нет никакой уверенности в типе, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) является правильным выбором, а не `Object`. Если единственным известным фактом о типе является то, что это какой-то объект, используйте тип [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), а не `Object` или `{ [key: string]: any }`.
* `var foo: string | any`:
когда `any` используется в типе объединения, результирующий тип все еще `any`. Таким образом, хотя `string` часть аннотации этого типа может _выглядеть_ полезной, на самом деле она не предлагает никакой дополнительной проверки типов по сравнению с простым использованием `any`.
В зависимости от намерения, приемлемыми альтернативами могут быть `any`, `string`, или `string | object`.
#### Удаление пакета
Когда пакет [объединяет](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) свои собственные типы, типы должны быть удалены из DefinitelyTyped чтобы избежать путаницы.
Вы можете удалить его, запустив `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]`.
* `typingsPackageName`: название директории, который нужно удалить.
* `asOfVersion`: заглушка будет опубликована в `@types/foo` с этой версией. Должна быть выше, чем любая опубликованная на данный момент версия
* `sourceRepoURL`: Это должно указывать на репозиторий, который содержит типизации.
* `libraryName`: описательное имя библиотеки, например, "Angular 2" вместо "angular2". (Если опущено, будет идентично "typingsPackageName".)
Любые другие пакеты в DefinitelyTyped которые ссылаются на удаленный пакет, должны быть обновлены для ссылки на связанные типы. Для этого добавьте в `package.json` ссыклу `"dependencies": { "foo": "x.y.z" }`.
Если пакет никогда не был в DefinitelyTyped, его не нужно добавлять в `notNeededPackages.json`.
#### Lint
Все новые пакеты должны быть проанализированы lint. Для этого добавьте `tslint.json` в этот пакет, содержащий
```js
{
"extends": "dtslint/dt.json"
}
```
Это должно быть единственным содержимым в файле `tslint.json` готового проекта. Если `tslint.json` отключает правила, это потому, что это еще не исправлено. Например:
```js
{
"extends": "dtslint/dt.json",
"rules": {
// This package uses the Function type, and it will take effort to fix.
"ban-types": false
}
}
```
(Чтобы указать, что правило lint действительно не применяется, используйте `// tslint:disable rule-name` или лучше, `//tslint:disable-next-line rule-name`.)
Чтобы проверить, что выражение имеет заданный тип, используйте `$ExpectType`. Чтобы проверить, что выражение вызывает ошибку компиляции, используйте `$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` в NPM?
Ветвь `master` автоматически публикуется в область `@types` на NPM благодаря [types-publisher](https://github.com/Microsoft/types-publisher).
#### Я отправил PR. Когда он сольется?
Это зависит, но большинство запросов на получение данных будут объединены в течение недели. PR, утвержденные автором, указанным в заголовке определения, обычно объединяются быстрее; PR для новых определений займет больше времени, так как они требуют большего количества проверок от сопровождающих. Каждый PR проверяется членом команды TypeScript или DefinitelyTyped перед объединением, поэтому будьте терпеливы, так как человеческий фактор может вызвать задержки. Посмотрите на [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) чтобы увидеть, как сопровождающие работают через открытые PR.
#### Мой PR слит; когда будет обновлен пакет `@types` NPM?
Пакеты NPM должны обновиться в течение нескольких часов. Если прошло более 24 часов, пингуйте @RyanCavanaugh и @andy-ms в PR, чтобы расследовать.
#### Я пишу определение, которое зависит от другого определения. Должен ли я использовать `<reference types="" />` или import?
Если модуль, на который вы ссылаетесь, является внешним модулем (использует `export`), используйте import.
Если модуль, на который вы ссылаетесь, является окружающим модулем (использует `declare module`, или просто объявляет глобальные переменные), используйте `<reference types="" />`.
#### Я заметил, что у некоторых пакетов есть `package.json`.
Обычно вам это не нужно. При публикации пакета мы обычно автоматически создаем `package.json`.
`package.json` может быть включен для определения зависимостей. Вот [пример](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json).
Мы не разрешаем определять другие поля, такие как "description", вручную.
Кроме того, если вам нужно сослаться на более старую версию типизаций, вы должны сделать это, добавив в `package.json` строки `"dependencies": { "@types/foo": "x.y.z" }`.
#### В некоторых пакетах отсутствует `tslint.json`, а в некоторых `tsconfig.json` отсутствует `"noImplicitAny": true`, `"noImplicitThis": true`, или `"strictNullChecks": true`.
Тогда они не правы. Вы можете помочь, отправив PR, чтобы исправить их.
#### Могу ли я запросить определение?
Вот [текущие запрошенные определения](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest).
#### Как насчет определений типов для DOM?
Если типы являются частью веб-стандарта, они должны быть добавлены в [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) чтобы они могли стать частью `lib.dom.d.ts` по умолчанию.
#### Пакет использует export `export =`, но я предпочитаю использовать импорт по умолчанию. Могу ли я изменить `export =` на `export default`?
Если вы используете TypeScript 2.7 или более позднюю версию, используйте `--esModuleInterop` в вашем проекте.
В противном случае, если импорт по умолчанию работает в вашей среде (например, Webpack, SystemJS, esm), рассмотрите возможность включения опции компилятора [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html).
Не меняйте определение типа, если оно точное.
Для пакета NPM, `export =` является точным, если `node -p 'require("foo")'` является экспортом, а `export default` является точным, если `node -p 'require("foo").default'` является экспортом.
#### Я хочу использовать функции из TypeScript 2.1 или выше.
В таком случае вам нужно будет добавить комментарий к последней строке заголовка вашего определения (после `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`.
#### Я хочу добавить DOM API, отсутствующий в TypeScript по умолчанию.
Это может принадлежать [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). Смотрите инструкции там.
Если стандарт все еще является черновиком, добавляйте сюда.
Используйте имя, начинающееся с `dom-` и включите ссылку на стандарт в качестве ссылки "Project" в заголовке.
Когда он завершает черновой режим, мы можем удалить его из DefinitelyTyped и объявить устаревшим связанный пакет `@types`.
#### Я хочу обновить пакет новой старшей версии
Если вы намерены продолжить обновление старой версии пакета, вы можете создать новую подпапку с текущей версией, например, `v2` и скопируйте в него существующие файлы. Если это так, вам необходимо:
1. Обновите относительные пути в `tsconfig.json` а также в `tslint.json`.
2. Добавьте правила сопоставления путей, чтобы убедиться, что тесты выполняются для предполагаемой версии.
Например [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like:
```json
{
"compilerOptions": {
"baseUrl": "../../",
"typeRoots": ["../../"],
"paths": {
"history": [ "history/v2" ]
},
},
"files": [
"index.d.ts",
"history-tests.ts"
]
}
```
Если в DefinitelyTyped есть другие пакеты, несовместимые с новой версией, вам нужно будет добавить сопоставления путей к старой версии. Вам также нужно будет сделать это для пакетов в зависимости от пакетов в зависимости от старой версии.
Например, `react-router` зависит от `history@2`, поэтому [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) есть сопоставление пути с `"history": [ "history/v2" ]`;
транзитивно `react-router-bootstrap` (который зависит от `react-router`) также добавляет отображение пути в свой [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).
Также, `/// <reference types=".." />` не будет работать с отображением пути, поэтому зависимости должны использовать `import`.
#### Как мне написать определения для пакетов, которые могут использоваться и глобально и в качестве модуля?
Руководство TypeScript содержит отличную [общую информацию о написании определений](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, а также указаны объекты, доступные для глобальной области. Этот метод демонстрируется практически в определении для [definition for big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), библиотекой, которую можно загружать глобально с помощью тега скрипта на веб-странице или импортировать с помощью импорта по требованию или в стиле ES6.
Чтобы проверить, как ваше определение может использоваться как при глобальных ссылках, так и в качестве импортированного модуля, создайте тестовую папку `test`, и поместите туда два тестовых файла. Назовите один `YourLibraryName-global.test.ts` а другой `YourLibraryName-module.test.ts`. *Глобальный* тестовый файл должен использовать определение в соответствии с тем, как он будет использоваться в скрипте, загруженном на веб-страницу, где библиотека доступна в глобальной области видимости - в этом сценарии не следует указывать оператор импорта. Тестовый файл *модуля* должен использовать определение в соответствии с тем, как оно будет использоваться при импорте (включая оператор(ы) `import`). Если вы указали свойство `files` в файле `tsconfig.json`, обязательно включите оба тестовых файла. [Практический пример этого](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) также доступен в определении big.js.
Обратите внимание, что не требуется полностью использовать определение в каждом тестовом файле - достаточно протестировать только глобально доступные элементы в глобальном тестовом файле и полностью выполнить определение в тестовом файле модуля, или наоборот.
#### А как насчет областных пакетов?
Типы для пакета с областью `@foo/bar` должны указываться в `types/foo__bar`. Обратите внимание на двойное подчеркивание.
Когда `dts-gen` используется для компоновки пакета с областью действия, свойство `paths` должно быть вручную адаптировано в сгенерированном файле
`tsconfig.json` для правильной ссылки на пакет с областью действия:
```json
{
"paths":{
"@foo/bar": ["foo__bar"]
}
}
```
#### История файлов в GitHub выглядит неполной.
GitHub не [поддерживает](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).
#### Должен ли я добавить пустой namespace в пакет, который не экспортирует модуль для использования импорта в стиле ES6?
Некоторые пакеты, такие как [chai-http](https://github.com/chaijs/chai-http), экспортируют функцию.
Импорт этого модуля с импортом в стиле ES6 в форме `import * as foo from "foo";` приводит к ошибке:
> 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 foo from "foo";` при использовании флага `--allowSyntheticDefaultImports`, если среда выполнения вашего модуля поддерживает схему взаимодействия для модулей не-ECMAScript как таковых.
## Лицензия
Этот проект лицензирован по лицензии MIT.
Авторские права на файлы определений принадлежат каждому участнику, указанному в начале каждого файла определения.
[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon)
[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) В среднем пакеты публикуются на npm менее чем за 10000 секунд?
[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Был ли typescript-bot активным на DefinitelyTyped в последние два часа?
+27
View File
@@ -0,0 +1,27 @@
// Type definitions for node-gettext 2.0
// Project: http://github.com/alexanderwallin/node-gettext
// Definitions by: Sameer K.C. <https://github.com/sameercaresu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = GetText;
declare class GetText {
constructor(options?: { debug: boolean; });
addTranslations(locale: string, domain: string, translations: object): void;
dgettext(domain: string, msgid: string): string;
dngettext(domain: string, msgid: string, msgidPlural: string, count: number): string;
dnpgettext(domain: string, msgctxt: string, msgid: string, msgidPlural: string, count: number): string;
dpgettext(domain: string, msgctxt: string, msgid: string): string;
emit(eventName: string, eventData: any): void;
getComment(domain: string, msgctxt: string, msgid: string): object | boolean;
gettext(msgid: string): string;
ngettext(msgid: string, msgidPlural: string, count: number): string;
npgettext(msgctxt: string, msgid: string, msgidPlural: string, count: number): string;
off(eventName: string, callback: (params: any) => void): string;
on(eventName: string, callback: (params: any) => void): void;
pgettext(msgctxt: string, msgid: string): string;
setLocale(locale: string): void;
setTextDomain(domain: string): void;
static getLanguageCode(locale: string): string;
textdomain(domain: string): void;
warn(message: string): void;
}
+34
View File
@@ -0,0 +1,34 @@
// with tsc v 2.7 & esModuleInterop & allowSyntheticDefaultImports enabled in tsconfig.json
import Gettext from 'node-gettext';
// or without
// import Gettext = require('node-getttext');
const translations = {};
const gt = new Gettext({ debug: true });
const msgid = 'Get translation';
const msgidPlural = 'Get translations';
const domain = 'domain';
const msgctxt = 'context';
const count = 2;
gt.addTranslations('en-US', 'messages', translations);
gt.setTextDomain(domain);
gt.textdomain(domain);
gt.setLocale('en-US');
gt.gettext(msgid);
gt.dgettext('', msgid);
gt.dngettext(domain, msgid, msgidPlural, count);
gt.dnpgettext(domain, msgctxt, msgid, msgidPlural, count);
gt.dpgettext(domain, msgctxt, msgid);
gt.getComment(domain, msgctxt, msgid);
gt.ngettext(msgid, msgidPlural, count);
gt.npgettext(msgctxt, msgid, msgidPlural, count);
gt.pgettext(msgctxt, msgid);
Gettext.getLanguageCode('en-US');
gt.warn('warning');
const errorListener = (error: string) => {
// do something;
};
gt.on('error', errorListener);
gt.emit('error', 'Error occurred');
gt.off('error', errorListener);
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
},
"files": [
"index.d.ts",
"node-gettext-tests.ts"
]
}
+18
View File
@@ -684,6 +684,12 @@
"sourceRepoURL": "https://handsontable.com/",
"asOfVersion": "0.35.0"
},
{
"libraryName": "hibp",
"typingsPackageName": "hibp",
"sourceRepoURL": "https://github.com/wKovacs64/hibp",
"asOfVersion": "7.3.0"
},
{
"libraryName": "homeworks",
"typingsPackageName": "homeworks",
@@ -1482,6 +1488,12 @@
"sourceRepoURL": "https://github.com/zeh/simplesignal",
"asOfVersion": "1.0.0"
},
{
"libraryName": "sip.js",
"typingsPackageName": "sip.js",
"sourceRepoURL": "https://github.com/onsip/SIP.js",
"asOfVersion": "0.12.0"
},
{
"libraryName": "smooth-scrollbar",
"typingsPackageName": "smooth-scrollbar",
@@ -1512,6 +1524,12 @@
"sourceRepoURL": "https://github.com/mozilla/source-map",
"asOfVersion": "0.5.7"
},
{
"libraryName": "Spectacle",
"typingsPackageName": "spectacle",
"sourceRepoURL": "http://github.com/FormidableLabs/spectacle/",
"asOfVersion": "5.2.3"
},
{
"libraryName": "Spin.js",
"typingsPackageName": "spin.js",
+2 -1
View File
@@ -23,5 +23,6 @@
"devDependencies": {
"dtslint": "github:Microsoft/dtslint#production",
"types-publisher": "github:Microsoft/types-publisher#production"
}
},
"dependencies": {}
}
+2
View File
@@ -14,6 +14,8 @@ accept.language("en;q=0.7, en-GB;q=0.8", ["en-gb"]); // language === "en-GB"
const languages = accept.languages("da, en;q=0.7, en-GB;q=0.8"); // languages === ["da", "en-GB", "en"]
languages.lastIndexOf('');
accept.mediaType("text/plain, application/json;q=0.5, text/html, */*;q=0.1");
accept.mediaType("text/plain, application/json;q=0.5, text/html, */*;q=0.1", ["application/json", "text/html"]);
const mediaTypes = accept.mediaTypes("text/plain, application/json;q=0.5, text/html, */*;q=0.1");
// mediaTypes === ["text/plain", "text/html", "application/json", "*/*"]
mediaTypes.lastIndexOf('');
+1
View File
@@ -10,6 +10,7 @@ export function encoding(encodingHeader?: string, preferences?: string[]): strin
export function encodings(encodingHeader?: string): string[];
export function language(languageHeader?: string, preferences?: string[]): string;
export function languages(languageHeader?: string): string[];
export function mediaType(mediaTypeHeader?: string, preferences?: string[]): string;
export function mediaTypes(mediaTypeHeader?: string): string[];
export function parseAll(
headers: Record<string, string | string[] | undefined>
+10
View File
@@ -549,6 +549,16 @@ declare namespace AceAjax {
getFoldsInRange(range: Range): any;
highlight(text: string): void;
/**
* Highlight lines from `startRow` to `EndRow`.
* @param startRow Define the start line of the highlight
* @param endRow Define the end line of the highlight
* @param clazz Set the CSS class for the marker
* @param inFront Set to `true` to establish a front marker
**/
highlightLines(startRow:number, endRow: number, clazz: string, inFront: boolean): Range;
/**
* Sets the `EditSession` to point to a new `Document`. If a `BackgroundTokenizer` exists, it also points to `doc`.
+1 -3
View File
@@ -246,9 +246,7 @@ declare namespace acorn {
let LooseParser: ILooseParserClass | undefined;
let pluginsLoose: PluginsObject | undefined;
interface ILooseParserClass {
new (input: string, options?: Options): ILooseParser;
}
type ILooseParserClass = new (input: string, options?: Options) => ILooseParser;
interface ILooseParser {}
+17
View File
@@ -0,0 +1,17 @@
import activeWin = require('active-win');
// $ExpectType Promise<Result>
activeWin();
// $ExpectType Result
activeWin.sync();
let win = {
title: 'Unicorns - Google Search',
id: 5762,
owner: {
name: 'Google Chrome',
processId: 310,
},
};
win = activeWin.sync();
+30
View File
@@ -0,0 +1,30 @@
// Type definitions for active-win 4.0
// Project: https://github.com/sindresorhus/active-win#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = activeWin;
declare function activeWin(): Promise<activeWin.Result>;
declare namespace activeWin {
function sync(): Result;
interface Result {
title: string;
id: number;
bounds?: {
x: number;
y: number;
width: number;
height: number;
};
owner: {
name: string;
processId: number;
bundleId?: number;
path?: string;
};
memoryUsage?: number;
}
}
+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",
"active-win-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+16
View File
@@ -319,6 +319,22 @@ export interface Utils {
delimiter?: string
): void;
};
device: {
isWebXRAvailable: boolean;
getVRDisplay(): VRDisplay[];
checkHeadsetConnected(): boolean;
checkHasPositionalTracking(): boolean;
isMobile(): boolean;
isTablet(): boolean;
isIOS(): boolean;
isGearVR(): boolean;
isOculusGo(): boolean;
isR7(): boolean;
isLandscape(): boolean;
isBrowserEnvironment(): boolean;
isNodeEnvironment(): boolean;
PolyfillControls(object3D: THREE.Object3D): void;
};
styleParser: {
parse(value: string): object;
stringify(data: object): string;
+4 -1
View File
@@ -18,6 +18,7 @@ declare namespace OSS {
internal?: boolean; // access OSS with aliyun internal network or not, default is false. If your servers are running on aliyun too, you can set true to save lot of money.
secure?: boolean; // instruct OSS client to use HTTPS (secure: true) or HTTP (secure: false) protocol.
timeout?: string | number; // instance level timeout for all operations, default is 60s
cname?: boolean; // use custom domain name
}
interface Bucket {
@@ -29,7 +30,7 @@ declare namespace OSS {
type StorageType = "Standard" | "IA" | "Archive";
type ACLType = "public-read-write" | "public-read" | "and private";
type ACLType = "public-read-write" | "public-read" | "private";
type HTTPMethods = "GET" | "POST" | "DELETE" | "PUT";
@@ -174,6 +175,7 @@ declare namespace OSS {
mime?: string; // custom mime, will send with Content-Type entity header
meta?: UserMeta; // user meta, will send with x-oss-meta- prefix string e.g.: { uid: 123, pid: 110 }
callback: ObjectCallback;
headers?: object;
}
interface PutObjectResult {
@@ -188,6 +190,7 @@ declare namespace OSS {
mime: string; // custom mime, will send with Content-Type entity header
meta: UserMeta;
callback: ObjectCallback;
headers?: object;
}
interface AppendObjectOptions {
@@ -0,0 +1,4 @@
import allPropertyNames = require('all-property-names');
// $ExpectType Set<string>
allPropertyNames(Symbol.prototype);
+9
View File
@@ -0,0 +1,9 @@
// Type definitions for all-property-names 1.0
// Project: https://github.com/sindresorhus/all-property-names#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
export = allPropertyNames;
declare function allPropertyNames(input: object): Set<string>;
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"all-property-names-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+2 -2
View File
@@ -58,8 +58,8 @@ declare namespace AltJS {
remote(state:any, ...args: any[]):Promise<S>;
shouldFetch?(fetchFn:(...args:Array<any>) => boolean):void;
loading?:(args:any) => void;
success?:(state:S) => void;
error?:(args:any) => void;
success:(state:S) => void;
error:(args:any) => void;
interceptResponse?(response:any, action:Action<any>, ...args:Array<any>):any;
}
+25 -13
View File
@@ -1502,16 +1502,28 @@ interface MyScope extends ng.IScope {
foo: string;
}
const directiveCompileFnWithGeneric: ng.IDirectiveCompileFn<MyScope> = (
templateElement: JQLite,
templateAttributes: ng.IAttributes,
transclude: ng.ITranscludeFunction
): ng.IDirectiveLinkFn<MyScope> => {
return (
scope: MyScope,
instanceElement: JQLite,
instanceAttributes: ng.IAttributes
) => {
return null;
};
};
interface MyElement extends JQLite {
foo: string;
}
interface MyAttributes extends ng.IAttributes {
foo: string;
}
interface MyController extends ng.INgModelController {
foo: string;
}
angular.module('WithGenerics', [])
.directive('directiveUsingGenerics', () => {
return {
restrict: 'E',
link(scope: MyScope, element: MyElement, templateAttributes: MyAttributes, controller: MyController) {
scope['name'] = 'Jeff';
}
};
})
.directive('linkFunctionUsingGenerics', () => {
return (scope: MyScope, element: MyElement, templateAttributes: MyAttributes, controller: MyController) => {
scope['name'] = 'Jeff';
};
});
+25 -22
View File
@@ -240,8 +240,9 @@ declare namespace angular {
* @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind)
* @param directiveFactory An injectable directive factory function.
*/
directive<TScope extends IScope = IScope>(name: string, directiveFactory: Injectable<IDirectiveFactory<TScope>>): IModule;
directive<TScope extends IScope = IScope>(object: {[directiveName: string]: Injectable<IDirectiveFactory<TScope>>}): IModule;
directive<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController>(name: string, directiveFactory: Injectable<IDirectiveFactory<TScope, TElement, TAttributes, TController>>): IModule;
directive<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController>(object: {[directiveName: string]: Injectable<IDirectiveFactory<TScope, TElement, TAttributes, TController>>}): IModule;
/**
* Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider.
*
@@ -1346,8 +1347,8 @@ declare namespace angular {
}
interface ICompileProvider extends IServiceProvider {
directive<TScope extends IScope = IScope>(name: string, directiveFactory: Injectable<IDirectiveFactory<TScope>>): ICompileProvider;
directive<TScope extends IScope = IScope>(object: {[directiveName: string]: Injectable<IDirectiveFactory<TScope>>}): ICompileProvider;
directive<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController>(name: string, directiveFactory: Injectable<IDirectiveFactory<TScope, TElement, TAttributes, TController>>): ICompileProvider;
directive<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController>(object: {[directiveName: string]: Injectable<IDirectiveFactory<TScope, TElement, TAttributes, TController>>}): ICompileProvider;
component(name: string, options: IComponentOptions): ICompileProvider;
component(object: {[componentName: string]: IComponentOptions}): ICompileProvider;
@@ -2066,29 +2067,31 @@ declare namespace angular {
// and http://docs.angularjs.org/guide/directive
///////////////////////////////////////////////////////////////////////////
interface IDirectiveFactory<TScope extends IScope = IScope> {
(...args: any[]): IDirective<TScope> | IDirectiveLinkFn<TScope>;
type IDirectiveController = IController | IController[] | {[key: string]: IController};
interface IDirectiveFactory<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController> {
(...args: any[]): IDirective<TScope, TElement, TAttributes, TController> | IDirectiveLinkFn<TScope, TElement, TAttributes, TController>;
}
interface IDirectiveLinkFn<TScope extends IScope = IScope> {
interface IDirectiveLinkFn<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController> {
(
scope: TScope,
instanceElement: JQLite,
instanceAttributes: IAttributes,
controller?: IController | IController[] | {[key: string]: IController},
instanceElement: TElement,
instanceAttributes: TAttributes,
controller?: TController,
transclude?: ITranscludeFunction
): void;
}
interface IDirectivePrePost<TScope extends IScope = IScope> {
pre?: IDirectiveLinkFn<TScope>;
post?: IDirectiveLinkFn<TScope>;
interface IDirectivePrePost<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController> {
pre?: IDirectiveLinkFn<TScope, TElement, TAttributes, TController>;
post?: IDirectiveLinkFn<TScope, TElement, TAttributes, TController>;
}
interface IDirectiveCompileFn<TScope extends IScope = IScope> {
interface IDirectiveCompileFn<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController> {
(
templateElement: JQLite,
templateAttributes: IAttributes,
templateElement: TElement,
templateAttributes: TAttributes,
/**
* @deprecated
* Note: The transclude function that is passed to the compile function is deprecated,
@@ -2096,11 +2099,11 @@ declare namespace angular {
* that is passed to the link function instead.
*/
transclude: ITranscludeFunction
): void | IDirectiveLinkFn<TScope> | IDirectivePrePost<TScope>;
): void | IDirectiveLinkFn<TScope, TElement, TAttributes, TController> | IDirectivePrePost<TScope, TElement, TAttributes, TController>;
}
interface IDirective<TScope extends IScope = IScope> {
compile?: IDirectiveCompileFn<TScope>;
interface IDirective<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController> {
compile?: IDirectiveCompileFn<TScope, TElement, TAttributes, TController>;
controller?: string | Injectable<IControllerConstructor>;
controllerAs?: string;
/**
@@ -2109,7 +2112,7 @@ declare namespace angular {
* relies upon bindings inside a $onInit method on the controller, instead.
*/
bindToController?: boolean | {[boundProperty: string]: string};
link?: IDirectiveLinkFn<TScope> | IDirectivePrePost<TScope>;
link?: IDirectiveLinkFn<TScope, TElement, TAttributes, TController> | IDirectivePrePost<TScope, TElement, TAttributes, TController>;
multiElement?: boolean;
priority?: number;
/**
@@ -2119,9 +2122,9 @@ declare namespace angular {
require?: string | string[] | {[controller: string]: string};
restrict?: string;
scope?: boolean | {[boundProperty: string]: string};
template?: string | ((tElement: JQLite, tAttrs: IAttributes) => string);
template?: string | ((tElement: TElement, tAttrs: TAttributes) => string);
templateNamespace?: string;
templateUrl?: string | ((tElement: JQLite, tAttrs: IAttributes) => string);
templateUrl?: string | ((tElement: TElement, tAttrs: TAttributes) => string);
terminal?: boolean;
transclude?: boolean | 'element' | {[slot: string]: string};
}
+6 -2
View File
@@ -774,6 +774,7 @@ interface BaseJQueryEventObject extends Event {
pageY: number;
/**
* For key or mouse events, this property indicates the specific key or button that was pressed.
* @deprecated Use `key` for KeyEvents or `button` for MouseEvents instead.
* @see {@link https://api.jquery.com/event.which/}
*/
which: number;
@@ -804,9 +805,12 @@ interface JQueryMouseEventObject extends JQueryInputEventObject {
}
interface JQueryKeyEventObject extends JQueryInputEventObject {
char: any;
/** @deprecated */
char: string;
/** @deprecated */
charCode: number;
key: any;
key: string;
/** @deprecated */
keyCode: number;
}
+33 -28
View File
@@ -1,30 +1,35 @@
import * as colors from 'ansi-colors';
import colors = require('ansi-colors');
let s: string;
colors.red('This is a red string!'); // $ExpectType string
colors.green('This is a red string!'); // $ExpectType string
colors.cyan('This is a cyan string!'); // $ExpectType string
colors.yellow('This is a yellow string!'); // $ExpectType string
s = colors.bgblack("hello");
s = colors.bgblue("hello");
s = colors.bgcyan("hello");
s = colors.bggreen("hello");
s = colors.bgmagenta("hello");
s = colors.bgred("hello");
s = colors.bgwhite("hello");
s = colors.bgyellow("hello");
s = colors.black("hello");
s = colors.blue("hello");
s = colors.bold("hello");
s = colors.cyan("hello");
s = colors.dim("hello");
s = colors.gray("hello");
s = colors.green("hello");
s = colors.grey("hello");
s = colors.hidden("hello");
s = colors.inverse("hello");
s = colors.italic("hello");
s = colors.magenta("hello");
s = colors.red("hello");
s = colors.reset("hello");
s = colors.strikethrough("hello");
s = colors.underline("hello");
s = colors.white("hello");
s = colors.yellow("hello");
colors.bold.red('this is a bold red message'); // $ExpectType string
colors.bold.yellow.italic('this is a bold yellow italicized message'); // $ExpectType string
colors.green.bold.underline('this is a bold green underlined message'); // $ExpectType string
colors.yellow(`foo ${colors.red.bold('red')} bar ${colors.cyan('cyan')} baz`); // $ExpectType string
colors.bold(`foo ${colors.red.dim('bar')} baz`); // $ExpectType string
colors.enabled = false;
colors.visible = false;
colors.hasAnsi(colors.blue('foo')); // $ExpectType boolean
colors.hasColor(colors.blue('foo')); // $ExpectType boolean
colors.unstyle(colors.blue.bold('foo bar baz')); // $ExpectType string
colors.stripColor(colors.blue.bold('foo bar baz')); // $ExpectType string
colors.none('foo'); // $ExpectType string
colors.clear('foo'); // $ExpectType string
colors.noop('foo'); // $ExpectType string
colors.define('reset', [0, 0], 'modifier');
colors.symbols.ballotCross; // $ExpectType string | undefined
colors.symbols.windows.ballotCross; // $ExpectError
colors.symbols.other.ballotCross; // $ExpectType string
colors.symbols.cross; // $ExpectType string
colors.symbols.windows.cross; // $ExpectType string
colors.symbols.other.cross; // $ExpectType string
+107 -27
View File
@@ -1,31 +1,111 @@
// Type definitions for ansi-colors 1.0
// Type definitions for ansi-colors 3.2
// Project: https://github.com/doowb/ansi-colors
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
export function bgblack(s: string): string;
export function bgblue(s: string): string;
export function bgcyan(s: string): string;
export function bggreen(s: string): string;
export function bgmagenta(s: string): string;
export function bgred(s: string): string;
export function bgwhite(s: string): string;
export function bgyellow(s: string): string;
export function black(s: string): string;
export function blue(s: string): string;
export function bold(s: string): string;
export function cyan(s: string): string;
export function dim(s: string): string;
export function gray(s: string): string;
export function green(s: string): string;
export function grey(s: string): string;
export function hidden(s: string): string;
export function inverse(s: string): string;
export function italic(s: string): string;
export function magenta(s: string): string;
export function red(s: string): string;
export function reset(s: string): string;
export function strikethrough(s: string): string;
export function underline(s: string): string;
export function white(s: string): string;
export function yellow(s: string): string;
export = colors;
declare const colors: colors.Colors;
declare namespace colors {
type ColorFn = ((text: string) => string) & Colors;
interface Colors {
enabled: boolean;
visible: boolean;
reset: ColorFn;
bold: ColorFn;
dim: ColorFn;
italic: ColorFn;
underline: ColorFn;
inverse: ColorFn;
hidden: ColorFn;
strikethrough: ColorFn;
black: ColorFn;
red: ColorFn;
green: ColorFn;
yellow: ColorFn;
blue: ColorFn;
magenta: ColorFn;
cyan: ColorFn;
white: ColorFn;
gray: ColorFn;
grey: ColorFn;
bgBlack: ColorFn;
bgRed: ColorFn;
bgGreen: ColorFn;
bgYellow: ColorFn;
bgBlue: ColorFn;
bgMagenta: ColorFn;
bgCyan: ColorFn;
bgWhite: ColorFn;
blackBright: ColorFn;
redBright: ColorFn;
greenBright: ColorFn;
yellowBright: ColorFn;
blueBright: ColorFn;
magentaBright: ColorFn;
cyanBright: ColorFn;
whiteBright: ColorFn;
bgBlackBright: ColorFn;
bgRedBright: ColorFn;
bgGreenBright: ColorFn;
bgYellowBright: ColorFn;
bgBlueBright: ColorFn;
bgMagentaBright: ColorFn;
bgCyanBright: ColorFn;
bgWhiteBright: ColorFn;
hasColor(text: string): boolean;
hasAnsi(text: string): boolean;
unstyle(text: string): string;
stripColor(text: string): string;
none(text: string): string;
clear(text: string): string;
noop(text: string): string;
symbols: Symbols & {
windows: WindowsSymbols;
other: OtherPlatformsSymbols;
};
define(
name: string,
codes: [number, number],
type: 'modifier' | 'color' | 'bg' | 'bright' | 'bgBright'
): void;
}
interface WindowsSymbols {
bullet: string;
check: string;
cross: string;
ellipsis: string;
heart: string;
info: string;
line: string;
middot: string;
minus: string;
plus: string;
question: string;
questionSmall: string;
pointer: string;
pointerSmall: string;
warning: string;
}
interface ExtendedSymbols {
ballotCross: string;
questionFull: string;
}
type Symbols = WindowsSymbols & Partial<ExtendedSymbols>;
type OtherPlatformsSymbols = WindowsSymbols & ExtendedSymbols;
}
+1 -1
View File
@@ -20,4 +20,4 @@
"index.d.ts",
"ansi-colors-tests.ts"
]
}
}
+30
View File
@@ -0,0 +1,30 @@
import * as colors from 'ansi-colors';
let s: string;
s = colors.bgblack("hello");
s = colors.bgblue("hello");
s = colors.bgcyan("hello");
s = colors.bggreen("hello");
s = colors.bgmagenta("hello");
s = colors.bgred("hello");
s = colors.bgwhite("hello");
s = colors.bgyellow("hello");
s = colors.black("hello");
s = colors.blue("hello");
s = colors.bold("hello");
s = colors.cyan("hello");
s = colors.dim("hello");
s = colors.gray("hello");
s = colors.green("hello");
s = colors.grey("hello");
s = colors.hidden("hello");
s = colors.inverse("hello");
s = colors.italic("hello");
s = colors.magenta("hello");
s = colors.red("hello");
s = colors.reset("hello");
s = colors.strikethrough("hello");
s = colors.underline("hello");
s = colors.white("hello");
s = colors.yellow("hello");
+31
View File
@@ -0,0 +1,31 @@
// Type definitions for ansi-colors 1.0
// Project: https://github.com/doowb/ansi-colors
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export function bgblack(s: string): string;
export function bgblue(s: string): string;
export function bgcyan(s: string): string;
export function bggreen(s: string): string;
export function bgmagenta(s: string): string;
export function bgred(s: string): string;
export function bgwhite(s: string): string;
export function bgyellow(s: string): string;
export function black(s: string): string;
export function blue(s: string): string;
export function bold(s: string): string;
export function cyan(s: string): string;
export function dim(s: string): string;
export function gray(s: string): string;
export function green(s: string): string;
export function grey(s: string): string;
export function hidden(s: string): string;
export function inverse(s: string): string;
export function italic(s: string): string;
export function magenta(s: string): string;
export function red(s: string): string;
export function reset(s: string): string;
export function strikethrough(s: string): string;
export function underline(s: string): string;
export function white(s: string): string;
export function yellow(s: string): string;
+28
View File
@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"paths": {
"ansi-colors": [
"ansi-colors/v1"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"ansi-colors-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+3
View File
@@ -9,5 +9,8 @@ ansiRegex().test('\u001B[4mcake\u001B[0m'); // $ExpectType boolean
ansiRegex().test('cake'); // $ExpectType boolean
// => false
ansiRegex({onlyFirst: true}).test('cake'); // $ExpectType boolean
// => false
'\u001B[4mcake\u001B[0m'.match(ansiRegex()); // $ExpectType RegExpMatchArray | null
// => ['\u001B[4m', '\u001B[0m']
+12 -3
View File
@@ -1,7 +1,16 @@
// Type definitions for ansi-regex 3.0
// Type definitions for ansi-regex 4.0
// Project: https://github.com/chalk/ansi-regex#readme
// Definitions by: Manish Vachharajani <https://github.com/mvachhar>
// Florian Keller <https://github.com/ffflorian>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function r(): RegExp;
export = r;
declare namespace ansiRegex {
interface Options {
/** Match only the first ANSI escape. */
onlyFirst?: boolean;
}
}
declare function ansiRegex(options?: ansiRegex.Options): RegExp;
export = ansiRegex;
+17547 -13504
View File
File diff suppressed because it is too large Load Diff
+68 -6
View File
@@ -1,4 +1,4 @@
// Type definitions for ArcGIS API for JavaScript 3.26
// Type definitions for ArcGIS API for JavaScript 3.27
// Project: https://developers.arcgis.com/javascript/3/
// Definitions by: Esri <https://github.com/Esri>
// Bjorn Svensson <https://github.com/bsvensson>
@@ -560,7 +560,7 @@ declare module "esri" {
/** An array of driving time break values. */
breakValues?: number[];
/** The point feature layer around which drive-time areas will be drawn. */
inputLayer: FeatureLayer;
inputLayers: FeatureLayer[];
/** The geometry type of the input layer. */
inputType?: string;
/** Reference to the map object. */
@@ -1351,6 +1351,8 @@ declare module "esri" {
clip?: number;
/** If the widget is enabled and layers can be swiped. */
enabled?: boolean;
/** Indicates whether layer placement should be inverted (switched). */
invertPlacement?: boolean;
/** The layers to be swiped. */
layers: Layer[];
/** The number of pixels to place the tool from the left of the map. */
@@ -2532,7 +2534,7 @@ declare module "esri/Credential" {
class Credential {
/** Token expiration time specified as number of milliseconds since 1 January 1970 00:00:00 UTC. */
expires: number;
/** Indicates whether this credential belongs to a user with admin privileges. */
/** Indicates that this credential was created to access the ArcGIS REST Admin service */
isAdmin: boolean;
/** The Identity Manager's setOAuthRedirectionHandler returns an object that contains a "state" parameter. */
oAuthState: any;
@@ -2600,6 +2602,12 @@ declare module "esri/IdentityManagerBase" {
tokenValidity: number;
/** If your application is on the same domain as *.arcgis.com or ArcGIS Enterprise Server, the IdentityManager will redirect the user to its sign-in page. */
useSignInPage: boolean;
/**
* Returns a Credential object if the user has already signed in to access the given resource and is allowed to do so when using the given application id.
* @param resUrl The resource URL.
* @param appId The registered OAuth application id.
*/
checkAppAccess(resUrl: string, appId: string): any;
/**
* Returns the credential (via Deferred) if the user has already signed in to access the given resource.
* @param resUrl The resource URL.
@@ -2891,7 +2899,7 @@ declare module "esri/SnappingManager" {
}
declare module "esri/SpatialReference" {
/** The spatial reference of a map, layer, or inputs to and outputs from a task. */
/** Defines the spatial reference of a map, layer, or task parameters. */
class SpatialReference {
/** The well-known ID of a spatial reference. */
wkid: number;
@@ -2953,6 +2961,54 @@ declare module "esri/TimeExtent" {
export = TimeExtent;
}
declare module "esri/arcadeProfiles/fieldCalculateProfile" {
/** Module that implements the Arcade field calculate profile in web apps that calculate field values using Arcade expressions. */
var fieldCalculateProfile: {
/**
* Initializes the field calculate profile for the given Arcade expressions.
* @param expressions An array of Arcade expressions intended for use in the calculate profile.
*/
initialize(expressions: string[]): any;
};
export = fieldCalculateProfile;
}
declare module "esri/arcadeProfiles/labelingProfile" {
/** Module that implements the Arcade labeling profile in web apps that label features using Arcade expressions. */
var labelingProfile: {
/**
* Initializes the labeling profile for the given Arcade expressions.
* @param expressions An array of Arcade expressions intended for use in a label class.
*/
initialize(expressions: string[]): any;
};
export = labelingProfile;
}
declare module "esri/arcadeProfiles/popupProfile" {
/** Module that implements the Arcade popup profile for web apps that contain popups that reference Arcade expressions. */
var popupProfile: {
/**
* Initializes the popup profile for the given Arcade expressions.
* @param expressions An array of Arcade expressions intended for use in a popup template.
*/
initialize(expressions: string[]): any;
};
export = popupProfile;
}
declare module "esri/arcadeProfiles/visualizationProfile" {
/** Module that implements the Arcade visualization profile in web apps that render features using Arcade expressions. */
var visualizationProfile: {
/**
* Initializes the visualization profile for the given Arcade expressions.
* @param expressions An array of Arcade expressions intended for use in a renderer.
*/
initialize(expressions: string[]): any;
};
export = visualizationProfile;
}
declare module "esri/arcgis/OAuthInfo" {
import esri = require("esri");
@@ -4827,6 +4883,8 @@ declare module "esri/dijit/LayerSwipe" {
clip: number;
/** If the widget is enabled and layers can be swiped. */
enabled: boolean;
/** Indicates whether layer placement should be inverted (switched). */
invertPlacement: boolean;
/** The layers to be swiped. */
layers: Layer[];
/** The number of pixels to place the tool from the left of the map. */
@@ -6285,7 +6343,7 @@ declare module "esri/dijit/analysis/CreateDriveTimeAreas" {
/** An array of driving time break values. */
breakValues: number[];
/** The point feature layer around which drive-time areas will be drawn. */
inputLayer: FeatureLayer;
inputLayers: FeatureLayer[];
/** The geometry type of the input layer. */
inputType: string;
/** Reference to the map object. */
@@ -9073,6 +9131,8 @@ declare module "esri/graphic" {
getNode(): any;
/** Returns one or more DOM nodes used to draw the graphic. */
getNodes(): any;
/** Applicable to label graphics. */
getParentGraphic(): Graphic;
/** Returns the dojox/gfx/shape.Shape of the Esri graphic. */
getShape(): any;
/** Returns one or more dojox/gfx/shape.Shape used to draw the graphic. */
@@ -10314,6 +10374,8 @@ declare module "esri/layers/FeatureLayer" {
on(type: "query-limit-exceeded", listener: (event: { target: FeatureLayer }) => void): esri.Handle;
/** Fires when queryRelatedFeatures() is complete. */
on(type: "query-related-features-complete", listener: (event: { relatedFeatures: any; target: FeatureLayer }) => void): esri.Handle;
/** Fires right before the actual refresh kicks in for the layer, and only fires when the refresh is triggered by the refreshInterval. */
on(type: "refresh-tick", listener: (event: { target: FeatureLayer }) => void): esri.Handle;
/** Fires when a layer resumes drawing. */
on(type: "resume", listener: (event: { target: FeatureLayer }) => void): esri.Handle;
/** Fires when a layer's minScale and/or maxScale is changed. */
@@ -12419,7 +12481,7 @@ declare module "esri/map" {
getMinScale(): number;
/** Returns the minimum zoom level of the map. */
getMinZoom(): number;
/** Returns the current map scale. */
/** Returns the map scale at the center of the view. */
getScale(): number;
/** Returns the current zoom level of the map. */
getZoom(): number;
+8
View File
@@ -0,0 +1,8 @@
import diff = require('arr-diff');
const a = ['a', 'b', 'c', 'd'];
const b = [1, 2];
diff(['a']); // $ExpectType string[]
diff(['a'], [1]); // $ExpectType string[]
diff([1], ['a']); // $ExpectType number[]
+8
View File
@@ -0,0 +1,8 @@
// Type definitions for arr-diff 4.0
// Project: https://github.com/jonschlinkert/arr-diff
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = arrDiff;
declare function arrDiff<T>(first: T[], ...args: any[][]): T[];
+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",
"arr-diff-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+16
View File
@@ -0,0 +1,16 @@
import Koa = require('koa');
import asyncBusboy = require('async-busboy');
async function middleware(ctx: Koa.Context, next: () => Promise<any>) {
const {files, fields} = await asyncBusboy(ctx.req);
}
async function middleware2(ctx: Koa.Context, next: () => Promise<any>) {
const {fields} = await asyncBusboy(ctx.req, {
limits: {
fileSize: 2 * 1024 * 1024,
},
onFile: (fieldname: string, file: NodeJS.ReadableStream, filename: string, encoding: string, mimetype: string) => {
}
});
}
+28
View File
@@ -0,0 +1,28 @@
// Type definitions for async-busboy 0.7
// Project: https://github.com/m4nuC/async-busboy#readme
// Definitions by: Hiroshi Ioka <https://github.com/hirochachacha>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import * as fs from 'fs';
import * as http from 'http';
import busboy = require('busboy');
interface Options extends busboy.BusboyConfig {
onFile: (
fieldname: string,
file: NodeJS.ReadableStream,
filename: string,
encoding: string,
mimetype: string) => void;
}
type AsyncBusboy = (
req: http.IncomingMessage,
options?: Options
) => Promise<{fields: {[key: string]: any}; files?: fs.ReadStream[]}>;
declare const asyncBusboy: AsyncBusboy;
export = asyncBusboy;
+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",
"async-busboy-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+6
View File
@@ -136,6 +136,12 @@ webAuth.passwordlessStart({
send: 'code'
}, (err, data) => {});
webAuth.passwordlessLogin({
connection: 'the_connection',
phoneNumber: '123',
verificationCode: '456'
}, (err, data) => {});
webAuth.signupAndAuthorize({
connection: 'the_connection',
email: 'me@example.com',
+14
View File
@@ -270,6 +270,13 @@ export class WebAuth {
*/
passwordlessVerify(options: PasswordlessVerifyOptions, callback: Auth0Callback<any>): void;
/**
* Logs in a user with the verification code sent to the user
* @param options
* @param callback
*/
passwordlessLogin(options: PasswordlessLoginOptions, callback: Auth0Callback<any>): void;
/**
* Renews an existing session on Auth0's servers using `response_mode=web_message` (i.e. Auth0's hosted login page)
*
@@ -615,6 +622,13 @@ export interface PasswordlessVerifyOptions {
send?: string;
}
export interface PasswordlessLoginOptions {
connection: string;
verificationCode: string;
phoneNumber?: string;
email?: string;
}
export interface Auth0UserProfile {
name: string;
nickname: string;
+3 -1
View File
@@ -43,5 +43,7 @@ function test_client() {
});
};
connection.open();
if (!connection.isOpen && !connection.isRetrying && connection.session == null) {
connection.open();
}
}
+5 -3
View File
@@ -1,6 +1,6 @@
// Type definitions for AutobahnJS v0.9.7
// Type definitions for AutobahnJS 0.9
// Project: http://autobahn.ws/js/
// Definitions by: Elad Zelingher <https://github.com/darkl>, Andy Hawkins <https://github.com/a904guy/,http://a904guy.com/,http://www.bmbsqd.com>, Wladimir Totino <https://github.com/valepu>, Mathias Teier <https://github.com/glenroy37/,http://kagent.at>
// Definitions by: Elad Zelingher <https://github.com/darkl>, Andy Hawkins <https://github.com/a904guy>, Wladimir Totino <https://github.com/valepu>, Mathias Teier <https://github.com/glenroy37>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="when" />
@@ -191,7 +191,9 @@ declare namespace autobahn {
constructor(options?: IConnectionOptions);
isOpen: boolean;
isRetrying: boolean;
session?: Session;
open(): void;
close(reason?: string, message?: string): void;
-1
View File
@@ -7,7 +7,6 @@
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
+27
View File
@@ -118,12 +118,18 @@ str = apiGwEvt.resource;
str = customAuthorizerEvt.type;
str = customAuthorizerEvt.methodArn;
strOrUndefined = customAuthorizerEvt.authorizationToken;
strOrUndefined = customAuthorizerEvt.resource;
strOrUndefined = customAuthorizerEvt.path;
strOrUndefined = customAuthorizerEvt.httpMethod;
str = customAuthorizerEvt.headers!["example"];
str = customAuthorizerEvt.multiValueHeaders!["example"][0];
str = customAuthorizerEvt.pathParameters!["example"];
str = customAuthorizerEvt.queryStringParameters!["example"];
str = customAuthorizerEvt.multiValueQueryStringParameters!["example"][0];
str = customAuthorizerEvt.stageVariables!["example"];
apiGwEvtReqCtxOpt = customAuthorizerEvt.requestContext;
strOrUndefined = customAuthorizerEvt.domainName;
strOrUndefined = customAuthorizerEvt.apiId;
/* DynamoDB Stream Event */
const dynamoDBStreamEvent: AWSLambda.DynamoDBStreamEvent = {
@@ -599,6 +605,27 @@ const CodePipelineEvent: AWSLambda.CodePipelineEvent = {
CodePipelineEvent["CodePipeline.job"].data.encryptionKey = { type: 'KMS', id: 'key' };
/* CodePipeline CloudWatch Events
* see https://docs.aws.amazon.com/codepipeline/latest/userguide/detect-state-changes-cloudwatch-events.html
* Their documentation says that detail.version is a string, but it is actually an integer
*/
const CodePipelineCloudWatchEvent: AWSLambda.CodePipelineCloudWatchEvent = {
version: '0',
id: 'event_Id',
'detail-type': 'CodePipeline Pipeline Execution State Change',
source: 'aws.codepipeline',
account: 'Pipeline_Account',
time: 'TimeStamp',
region: 'us-east-1',
resources: ['arn:aws:codepipeline:us-east-1:account_ID:myPipeline'],
detail: {
pipeline: 'myPipeline',
version: 1,
state: 'STARTED',
'execution-id': 'execution_Id',
},
};
/* CloudFront events, see http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html */
const CloudFrontRequestWithCustomOriginEvent: AWSLambda.CloudFrontRequestEvent = {
Records: [
+115
View File
@@ -24,6 +24,7 @@
// Oliver Hookins <https://github.com/ohookins>
// Trevor Leach <https://github.com/trevor-leach>
// James Gregory <https://github.com/jagregory>
// Erik Dalén <https://github.com/dalen>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -78,12 +79,18 @@ export interface CustomAuthorizerEvent {
type: string;
methodArn: string;
authorizationToken?: string;
resource?: string;
path?: string;
httpMethod?: string;
headers?: { [name: string]: string };
multiValueHeaders?: { [name: string]: string[] };
pathParameters?: { [name: string]: string } | null;
queryStringParameters?: { [name: string]: string } | null;
multiValueQueryStringParameters?: { [name: string]: string[] } | null;
stageVariables?: { [name: string]: string };
requestContext?: APIGatewayEventRequestContext;
domainName?: string;
apiId?: string;
}
// Context
@@ -576,6 +583,109 @@ export interface CodePipelineEvent {
};
}
/**
* CodePipeline CloudWatch Events
* https://docs.aws.amazon.com/codepipeline/latest/userguide/detect-state-changes-cloudwatch-events.html
*
* The above CodePipelineEvent is when a lambda is invoked by a CodePipeline.
* These events are when you subsribe to CodePipeline events in CloudWatch.
*
* Their documentation says that detail.version is a string, but it is actually an integer
*/
export type CodePipelineState =
| 'STARTED'
| 'SUCCEEDED'
| 'RESUMED'
| 'FAILED'
| 'CANCELED'
| 'SUPERSEDED';
export type CodePipelineStageState =
| 'STARTED'
| 'SUCCEEDED'
| 'RESUMED'
| 'FAILED'
| 'CANCELED';
export type CodePipelineActionState =
| 'STARTED'
| 'SUCCEEDED'
| 'FAILED'
| 'CANCELED';
export interface CodePipelineCloudWatchPipelineEvent {
version: string;
id: string;
'detail-type': 'CodePipeline Pipeline Execution State Change';
source: 'aws.codepipeline';
account: string;
time: string;
region: string;
resources: string[];
detail: {
pipeline: string;
version: number;
state: CodePipelineState;
'execution-id': string;
};
}
export interface CodePipelineCloudWatchStageEvent {
version: string;
id: string;
'detail-type': 'CodePipeline Stage Execution State Change';
source: 'aws.codepipeline';
account: string;
time: string;
region: string;
resources: string[];
detail: {
pipeline: string;
version: number;
'execution-id': string;
stage: string;
state: CodePipelineStageState;
};
}
export type CodePipelineActionCategory =
| 'Approval'
| 'Build'
| 'Deploy'
| 'Invoke'
| 'Source'
| 'Test';
export interface CodePipelineCloudWatchActionEvent {
version: string;
id: string;
'detail-type': 'CodePipeline Action Execution State Change';
source: 'aws.codepipeline';
account: string;
time: string;
region: string;
resources: string[];
detail: {
pipeline: string;
version: number;
'execution-id': string;
stage: string;
action: string;
state: CodePipelineActionState;
type: {
owner: 'AWS' | 'Custom' | 'ThirdParty';
category: CodePipelineActionCategory;
provider: string;
version: number;
};
};
}
export type CodePipelineCloudWatchEvent =
| CodePipelineCloudWatchPipelineEvent
| CodePipelineCloudWatchStageEvent
| CodePipelineCloudWatchActionEvent;
/**
* CloudFront events
* http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html
@@ -837,6 +947,11 @@ export type ProxyCallback = APIGatewayProxyCallback; // Old name
export type CodePipelineHandler = Handler<CodePipelineEvent, void>;
export type CodePipelineCloudWatchHandler = Handler<CodePipelineCloudWatchEvent, void>;
export type CodePipelineCloudWatchPipelineHandler = Handler<CodePipelineCloudWatchPipelineEvent, void>;
export type CodePipelineCloudWatchStageHandler = Handler<CodePipelineCloudWatchStageEvent, void>;
export type CodePipelineCloudWatchActionHandler = Handler<CodePipelineCloudWatchActionEvent, void>;
export type CloudFrontRequestHandler = Handler<CloudFrontRequestEvent, CloudFrontRequestResult>;
export type CloudFrontRequestCallback = Callback<CloudFrontRequestResult>;
@@ -0,0 +1,6 @@
import { BdApi } from 'bandagedbd__bdapi';
BdApi.React; // $ExpectType typeof React
BdApi.ReactDOM.render; // $ExpectType Renderer
BdApi.alert('foo', 'bar'); // $ExpectType void
BdApi.showToast('hello', { timeout: 2000 }); // $ExpectType void
+176
View File
@@ -0,0 +1,176 @@
// Type definitions for bdapi 0.2
// Project: https://github.com/rauenzi/BetterDiscordApp
// Definitions by: Ari Seyhun <https://github.com/Acidic9>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
// Documentation: https://github.com/rauenzi/BetterDiscordApp/wiki/Creating-Plugins#bdapi
import * as ReactInstance from 'react';
import * as ReactDOMInstance from 'react-dom';
export const BdApi: typeof BdApiModule;
/**
* Function with no arguments and no return value that may be called to revert changes made by monkeyPatch method,
* restoring (unpatching) original method.
*/
export type CancelPatch = () => void;
/**
* A callback that modifies method logic.
* This callback is called on each call of the original method and is provided all data about original call.
* Any of the data can be modified if necessary, but do so wisely.
*/
export type PatchFunction = (data: PatchData) => any;
/**
* A callback that modifies method logic.
* This callback is called on each call of the original method and is provided all data about original call.
* Any of the data can be modified if necessary, but do so wisely.
*/
export interface PatchData {
thisObject: object;
methodArguments: any[];
CancelPatch: CancelPatch;
originalMethod: () => void;
callOriginalMethod: () => void;
returnValue: any;
}
export interface MonkeyPatchOptions {
once?: boolean;
silent?: boolean;
displayName?: string;
before?: PatchFunction;
after?: PatchFunction;
instead?: PatchFunction;
}
export interface ToastOptions {
type?: string;
icon?: boolean;
timeout?: number;
}
export namespace BdApiModule {
/**
* The React module being used inside Discord.
*/
const React: typeof ReactInstance;
/**
* The ReactDOM module being used inside Discord.
*/
const ReactDOM: typeof ReactDOMInstance;
/**
* Creates an shows an alert modal to the user. A preview of how it may look can be found [here](https://i.zackrauen.com/7qnnNC.png).
*/
function alert(title: string, content: string): void;
/**
* Removes a style added with [`injectCSS`](#injectcssid-css) below.
*/
function clearCSS(id: string): void;
/**
* Deletes some saved data for plugin `pluginName` with key `key`.
*/
function deleteData(pluginName: string, key: string): void;
/**
* Searches for an internal Discord webpack module based on `filter`.
*/
function findModule(filter: () => void): any;
/**
* Searches for multiple internal Discord webpack module based on `filter`. It's the same as [`findModule`](#findmodulefilter) but will return all matches
*/
function findAllModules(filter: () => void): any[];
/**
* Searches for an internal Discord webpack module that has every property passed.
*/
function findModuleByProps(...props: string[]): any;
/**
* Returns BandagedBD's instance of the core module. Only use this if you know what you are doing.
*/
function getCore(): any; // TODO: This should not return 'any' but instead 'Core'
/**
* Alias for [loadData(pluginName, key)](#loaddatapluginname-key)
*/
function getData(pluginName: string, key: string): any;
/**
* Gets the internal react instance for a particular node.
*/
function getInternalInstance(node: HTMLElement): object|undefined;
/**
* Gets the instance of another plugin with the name `name`.
*/
function getPlugin(name: string): object|null;
/**
* Adds a block of css to the current document's `head`.
*/
function injectCSS(id: string, css: string): object|null;
/**
* Links some remote JavaScript to be added to the page. Useful for libraries like `Sortable.js`.
*/
function linkJS(id: string, url: string): void;
/**
* Gets some saved data for plugin `pluginName` with key `key`. Data can be saved with [`saveData`](#savedatapluginname-key-data).
*/
function loadData(pluginName: string, key: string): any;
/**
* This function monkey-patches a method on an object. The patching callback may be run before, after or instead of target method.
* - Be careful when monkey-patching. Think not only about original functionality of target method and your changes,
* but also about developers of other plugins, who may also patch this method before or after you.
* Try to change target method behaviour as little as possible, and avoid changing method signatures.
* - Display name of patched method is changed, so you can see if a function has been patched (and how many times) while debugging or in the stack trace.
* Also, patched methods have property `__monkeyPatched` set to `true`, in case you want to check something programmatically.
*/
function monkeyPatch(module: object, methodName: string, options: MonkeyPatchOptions): CancelPatch;
/**
* Adds a listener for when the node is removed from the document body.
*/
function onRemoved(node: HTMLElement, callback: () => void): void;
/**
* Saved some `data` for plugin `pluginName` under `key` key. Gets saved in the plugins folder under `pluginName.config.json`. Data can be saved with [`loadData`](#loaddatapluginname-key).
*/
function saveData(pluginName: string, key: string, data: any): void;
/**
* Alias for [saveData(pluginName, key, data)](#savedatapluginname-key-data)
*
*/
function setData(pluginName: string, key: string, data: any): void;
/**
* Shows a simple toast message similar to on Android. An example of the `success` toast can be seen [here](https://i.zackrauen.com/zIagVa.png).
*/
function showToast(content: string, options?: ToastOptions): void;
/**
* Wraps a function in a try catch block.
*/
function suppressErrors(method: () => void, message?: string): () => void;
/**
* Determines if the input is valid and parseable JSON.
*/
function testJSON(data: string): boolean;
/**
* Removes some previously linked JS by [`linkJS`](#linkjsid-url).
*/
function unlinkJS(id: string): void;
}
@@ -7,7 +7,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
@@ -20,6 +20,6 @@
},
"files": [
"index.d.ts",
"spectacle-tests.tsx"
"bandagedbd__bdapi-tests.ts"
]
}
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+7 -10
View File
@@ -1,13 +1,10 @@
import * as baseX from 'base-x';
import * as basex from 'base-x';
const BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
const bs58 = baseX(BASE58);
let bs16 = basex('0123456789ABCDEF');
const decoded = bs58.decode('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr');
decoded; // $ExpectType Buffer
bs58.decodeUnsafe('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr'); // $ExpectType Buffer | undefined
{
let encoded: string;
encoded = bs16.encode([255]);
encoded = bs16.encode({0: 255, length: 1});
}
let decoded: number[] = bs16.decode('FF');
bs58.encode(decoded); // $ExpectType string
+13 -15
View File
@@ -1,23 +1,21 @@
// Type definitions for base-x v1.0.1
// Type definitions for base-x 3.0
// Project: https://github.com/cryptocoinjs/base-x
// Definitions by: Ilya Mochalov <https://github.com/chrootsu>
// BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare var BaseX: BaseX.Base;
export = BaseX;
/// <reference types="node" />
declare namespace BaseX {
interface EncodeBuffer {
[index: number]: number;
length: number;
}
import { Buffer } from 'buffer';
interface BaseConverter {
encode: (buffer: EncodeBuffer) => string;
decode: (string: string) => number[];
}
export = baseX;
interface Base {
(ALPHABET: string): BaseX.BaseConverter
}
declare function baseX(ALPHABET: string): baseX.BaseConverter;
declare namespace baseX {
interface BaseConverter {
encode(buffer: Buffer): string;
decodeUnsafe(string: string): Buffer | undefined;
decode(string: string): Buffer;
}
}
+2 -2
View File
@@ -6,7 +6,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
@@ -20,4 +20,4 @@
"index.d.ts",
"base-x-tests.ts"
]
}
}
+1 -77
View File
@@ -1,79 +1,3 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
"extends": "dtslint/dt.json"
}
+12
View File
@@ -0,0 +1,12 @@
import * as basex from 'base-x';
const bs16 = basex('0123456789ABCDEF');
{
let encoded: string;
encoded = bs16.encode([255]);
encoded = bs16.encode({0: 255, length: 1});
}
const decoded: number[] = bs16.decode('FF');
+21
View File
@@ -0,0 +1,21 @@
// Type definitions for base-x 1.0
// Project: https://github.com/cryptocoinjs/base-x
// Definitions by: Ilya Mochalov <https://github.com/chrootsu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare var BaseX: BaseX.Base;
export = BaseX;
declare namespace BaseX {
interface EncodeBuffer {
[index: number]: number;
length: number;
}
interface BaseConverter {
encode: (buffer: EncodeBuffer) => string;
decode: (string: string) => number[];
}
type Base = (ALPHABET: string) => BaseConverter;
}
+28
View File
@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"paths": {
"base-x": [
"base-x/v1"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"base-x-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+24
View File
@@ -0,0 +1,24 @@
import b64 = require('base64-async');
import * as fs from 'fs';
const buffer: Buffer = fs.readFileSync('somehugefile.jpg');
const b64String = 'aGkgbXVt...';
b64.encode(buffer).then(b64String => {
b64String; // $ExpectType string
});
b64.encode(buffer, { chunkSize: 10 }).then(b64String => {
b64String; // $ExpectType string
});
b64.decode(b64String).then(buffer => {
buffer; // $ExpectType Buffer
});
b64.decode(b64String, { chunkSize: 10 }).then(buffer => {
buffer; // $ExpectType Buffer
});
b64(buffer); // $ExpectType Promise<string>
b64(buffer, { chunkSize: 10 }); // $ExpectType Promise<string>
b64(b64String); // $ExpectType Promise<Buffer>
b64(b64String, { chunkSize: 10 }); // $ExpectType Promise<Buffer>
+20
View File
@@ -0,0 +1,20 @@
// Type definitions for base64-async 2.1
// Project: https://github.com/lukechilds/base64-async
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
export = base64Async;
declare function base64Async(input: Buffer, options?: base64Async.Options): Promise<string>;
declare function base64Async(input: string, options?: base64Async.Options): Promise<Buffer>;
declare namespace base64Async {
function encode(input: Buffer, options?: Options): Promise<string>;
function decode(input: string, options?: Options): Promise<Buffer>;
interface Options {
chunkSize?: number;
}
}
+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",
"base64-async-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
@@ -0,0 +1,4 @@
import batteryLevel = require('battery-level');
// $ExpectType Promise<number>
batteryLevel();
+8
View File
@@ -0,0 +1,8 @@
// Type definitions for battery-level 3.0
// Project: https://github.com/gillstrom/battery-level#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = batteryLevel;
declare function batteryLevel(): Promise<number>;
+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",
"battery-level-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+19 -10
View File
@@ -1,17 +1,17 @@
import Database = require('better-sqlite3');
import Sqlite = require('better-sqlite3');
const integer = Database.Integer(1);
const err = new Database.SqliteError('ok', 'ok');
const result: Database.RunResult = { changes: 1, lastInsertRowid: 1 };
const options: Database.Options = { fileMustExist: true, memory: true, readonly: true };
const registrationOptions: Database.RegistrationOptions = {
const integer = Sqlite.Integer(1);
const err = new Sqlite.SqliteError('ok', 'ok');
const result: Sqlite.RunResult = { changes: 1, lastInsertRowid: 1 };
const options: Sqlite.Options = { fileMustExist: true, memory: true, readonly: true };
const registrationOptions: Sqlite.RegistrationOptions = {
deterministic: true,
safeIntegers: true,
varargs: true
};
let db = Database('.');
db = new Database('.', { memory: true });
let db: Sqlite.Database = Sqlite('.');
db = new Sqlite('.', { memory: true });
db.exec('CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL);');
db.exec('INSERT INTO test(name) VALUES("name");');
db.pragma('data_version', { simple: true });
@@ -41,7 +41,7 @@ db.aggregate('addAll', {
db.defaultSafeIntegers();
db.defaultSafeIntegers(true);
const stmt = db.prepare('SELECT * FROM test WHERE name == ?;');
const stmt: Sqlite.Statement = db.prepare('SELECT * FROM test WHERE name == ?;');
stmt.get(['name']);
stmt.all({ name: 'name' });
for (const row of stmt.iterate('name')) {
@@ -53,8 +53,17 @@ stmt.expand(true);
stmt.bind('name');
stmt.safeIntegers();
stmt.safeIntegers(true);
stmt.raw();
stmt.raw(true);
stmt.raw(false);
let col: Sqlite.ColumnDefinition;
for (col of stmt.columns()) {
col.name;
col.column;
col.type;
}
const trans = db.transaction((param) => stmt.all(param));
const trans: Sqlite.Transaction = db.transaction((param) => stmt.all(param));
trans('name');
trans.default('name');
trans.deferred('name');
+67 -48
View File
@@ -1,4 +1,4 @@
// Type definitions for better-sqlite3 5.0
// Type definitions for better-sqlite3 5.2
// Project: http://github.com/JoshuaWise/better-sqlite3
// Definitions by: Ben Davies <https://github.com/Morfent>
// Mathew Rumsey <https://github.com/matrumz>
@@ -8,47 +8,68 @@
import Integer = require("integer");
interface Statement {
database: Database;
source: string;
reader: boolean;
declare namespace BetterSqlite3 {
interface Statement {
database: Database;
source: string;
reader: boolean;
run(...params: any[]): Database.RunResult;
get(...params: any[]): any;
all(...params: any[]): any[];
iterate(...params: any[]): IterableIterator<any>;
pluck(toggleState?: boolean): this;
expand(toggleState?: boolean): this;
bind(...params: any[]): this;
safeIntegers(toggleState?: boolean): this;
}
run(...params: any[]): Database.RunResult;
get(...params: any[]): any;
all(...params: any[]): any[];
iterate(...params: any[]): IterableIterator<any>;
pluck(toggleState?: boolean): this;
expand(toggleState?: boolean): this;
raw(toggleState?: boolean): this;
bind(...params: any[]): this;
columns(): ColumnDefinition[];
safeIntegers(toggleState?: boolean): this;
}
interface Transaction {
(...params: any[]): any;
default(...params: any[]): any;
deferred(...params: any[]): any;
immediate(...params: any[]): any;
exclusive(...params: any[]): any;
}
interface ColumnDefinition {
name: string;
column: string | null;
table: string | null;
database: string | null;
type: string | null;
}
interface Database {
memory: boolean;
readonly: boolean;
name: string;
open: boolean;
inTransaction: boolean;
interface Transaction {
(...params: any[]): any;
default(...params: any[]): any;
deferred(...params: any[]): any;
immediate(...params: any[]): any;
exclusive(...params: any[]): any;
}
prepare(source: string): Statement;
transaction(fn: (...params: any[]) => any): Transaction;
exec(source: string): this;
pragma(source: string, options?: Database.PragmaOptions): any;
checkpoint(databaseName?: string): this;
function(name: string, cb: (...params: any[]) => any): this;
function(name: string, options: Database.RegistrationOptions, cb: (...params: any[]) => any): this;
aggregate(name: string, options: Database.AggregateOptions): this;
loadExtension(path: string): this;
close(): this;
defaultSafeIntegers(toggleState?: boolean): this;
interface Database {
memory: boolean;
readonly: boolean;
name: string;
open: boolean;
inTransaction: boolean;
prepare(source: string): Statement;
transaction(fn: (...params: any[]) => any): Transaction;
exec(source: string): this;
pragma(source: string, options?: Database.PragmaOptions): any;
checkpoint(databaseName?: string): this;
function(name: string, cb: (...params: any[]) => any): this;
function(name: string, options: Database.RegistrationOptions, cb: (...params: any[]) => any): this;
aggregate(name: string, options: Database.AggregateOptions): this;
loadExtension(path: string): this;
close(): this;
defaultSafeIntegers(toggleState?: boolean): this;
}
interface DatabaseConstructor {
new(filename: string, options?: Database.Options): Database;
(filename: string, options?: Database.Options): Database;
prototype: Database;
Integer: typeof Integer;
SqliteError: typeof SqliteError;
}
}
declare class SqliteError implements Error {
@@ -58,15 +79,6 @@ declare class SqliteError implements Error {
constructor(message: string, code: string);
}
interface DatabaseConstructor {
new (filename: string, options?: Database.Options): Database;
(filename: string, options?: Database.Options): Database;
prototype: Database;
Integer: typeof Integer;
SqliteError: typeof SqliteError;
}
declare namespace Database {
interface RunResult {
changes: number;
@@ -96,7 +108,14 @@ declare namespace Database {
inverse?: (total: any, dropped: any) => any;
result?: (total: any) => any;
}
type Integer = typeof Integer;
type SqliteError = typeof SqliteError;
type Statement = BetterSqlite3.Statement;
type ColumnDefinition = BetterSqlite3.ColumnDefinition;
type Transaction = BetterSqlite3.Transaction;
type Database = BetterSqlite3.Database;
}
declare const Database: DatabaseConstructor;
declare const Database: BetterSqlite3.DatabaseConstructor;
export = Database;
@@ -0,0 +1,3 @@
import extensions = require('binaryextensions');
extensions; // $ExpectType string[]
+8
View File
@@ -0,0 +1,8 @@
// Type definitions for binaryextensions 2.1
// Project: https://github.com/bevry/binaryextensions
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = extensions;
declare const extensions: string[];
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"binaryextensions-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
-4
View File
@@ -285,7 +285,6 @@ declare namespace BlissNS {
addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T;
addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T;
addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T;
addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): T;
addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T;
addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T;
addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T;
@@ -555,18 +554,15 @@ declare namespace BlissNS {
getElementsByTagName(name: "video"): NodeListOf<HTMLVideoElement>;
getElementsByTagName(name: "view"): NodeListOf<SVGViewElement>;
getElementsByTagName(name: "wbr"): NodeListOf<HTMLElement>;
getElementsByTagName(name: "x-ms-webview"): NodeListOf<MSHTMLWebViewElement>;
getElementsByTagName(name: "xmp"): NodeListOf<HTMLElement>;
getElementsByTagName(name: string): NodeListOf<Element>;
getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf<Element>;
hasAttribute(name: string): boolean;
hasAttributeNS(namespaceURI: string, localName: string): boolean;
msGetRegionContent(): MSRangeCollection;
msGetUntransformedBounds(): ClientRect;
msMatchesSelector(selectors: string): boolean;
msReleasePointerCapture(pointerId: number): T;
msSetPointerCapture(pointerId: number): T;
msZoomTo(args: MsZoomToOptions): T;
releasePointerCapture(pointerId: number): T;
removeAttribute(name?: string): T;
removeAttributeNS(namespaceURI: string, localName: string): T;
+45 -9
View File
@@ -34,12 +34,16 @@ $("#carousel").carousel("pause");
$("#carousel").carousel(100);
$("#carousel").on("slide.bs.carousel", function(ev) {
$("#carousel").on("slide.bs.carousel", function(e) {
const that: HTMLElement = this;
const from: number = ev.from;
const to: number = ev.to;
const direction: string = ev.direction;
const data: undefined = ev.data;
const data: undefined = e.data;
const carousel: HTMLElement = e.target;
const direction: string = e.direction;
const relatedTarget: HTMLElement = e.relatedTarget;
const from: number = e.from;
const to: number = e.to;
});
$("#carousel").carousel({
@@ -48,6 +52,7 @@ $("#carousel").carousel({
slide: false,
pause: "hover",
wrap: true,
touch: false,
});
$("#carousel").carousel({
@@ -101,7 +106,11 @@ $("#dropdown").dropdown();
// $ExpectType JQuery<HTMLElement>
$("#dropdown").dropdown("update");
$("#dropdown").on("hide.bs.dropdown", () => {});
$("#dropdown").on("hide.bs.dropdown", (e) => {
const data: undefined = e.data;
const container: HTMLElement = e.target;
const togglingAnchorElement: HTMLElement = e.relatedTarget;
});
$("#dropdown").dropdown({
offset: 10,
@@ -141,7 +150,13 @@ $("#modal").modal();
// $ExpectType JQuery<HTMLElement>
$("#modal").modal("show");
$("#modal").on("hide.bs.modal", () => {});
$("#modal").on("show.bs.modal", (e) => {
const data: undefined = e.data;
const modal: HTMLElement = e.target;
if (e.relatedTarget) {
const clickedElement: HTMLElement = e.relatedTarget;
}
});
$("#modal").modal({
backdrop: false,
@@ -226,10 +241,31 @@ $("#scrollspy").scrollspy({
$("#someListItem").tab("show");
$("a[data-toggle=\"list\"]").on("shown.bs.tab", (e) => {
e.target; // newly activated tab
e.relatedTarget; // previous active tab
const data: undefined = e.data;
const newlyActivatedTab: HTMLElement = e.target;
const previousActiveTab: HTMLElement = e.relatedTarget;
});
// --------------------------------------------------------------------------------------
// Toast
// --------------------------------------------------------------------------------------
// $ExpectType JQuery<HTMLElement>
$("#toast").toast();
// $ExpectType JQuery<HTMLElement>
$("#toast").toast("show");
$("#toast").on("shown.bs.toast", () => {});
$("#toast").toast({
animation: false,
autohide: false,
delay: 100,
});
$("#toast").toast({});
// --------------------------------------------------------------------------------------
// Tooltip
// --------------------------------------------------------------------------------------
+231 -10
View File
@@ -1,4 +1,4 @@
// Type definitions for Bootstrap 4.1
// Type definitions for Bootstrap 4.2
// Project: https://github.com/twbs/bootstrap/
// Definitions by: denisname <https://github.com/denisname>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -64,9 +64,10 @@ export interface CarouselOption {
slide?: "next" | "prev" | false;
/**
* If set to "hover", pauses the cycling of the carousel on mouseenter and resumes the cycling of the carousel on mouseleave.
* If set to "hover", pauses the cycling of the carousel on `mouseenter` and resumes the cycling of the carousel on `mouseleave`.
* If set to false, hovering over the carousel won't pause it.
* On touch-enabled devices, when set to "hover", cycling will pause on touchend (once the user finished interacting with the carousel)
*
* On touch-enabled devices, when set to "hover", cycling will pause on `touchend` (once the user finished interacting with the carousel)
* for two intervals, before automatically resuming. Note that this is in addition to the above mouse behavior.
*
* @default "hover"
@@ -79,6 +80,13 @@ export interface CarouselOption {
* @default true
*/
wrap?: boolean;
/**
* Whether the carousel should support left/right swipe interactions on touchscreen devices.
*
* @default true
*/
touch?: boolean;
}
export interface CollapseOption {
@@ -185,7 +193,10 @@ export interface PopoverOption extends TooltipOption {
export interface ScrollspyOption {
/**
* TODO: https://github.com/twbs/bootstrap/issues/25799
* Finds which section the spied element is in:
* * `auto` will choose the best method get scroll coordinates.
* * `offset` will use jQuery offset method to get scroll coordinates.
* * `position` will use jQuery position method to get scroll coordinates.
*
* @default "auto"
*/
@@ -207,6 +218,29 @@ export interface ScrollspyOption {
target?: string | Element;
}
export interface ToastOption {
/**
* Apply a CSS fade transition to the toast.
*
* @default true
*/
animation?: boolean;
/**
* Auto hide the toast.
*
* @default true
*/
autohide?: boolean;
/**
* Delay hiding the toast in millisecond.
*
* @default 500
*/
delay?: number;
}
export interface TooltipOption {
/**
* Apply a CSS fade transition to the tooltip or popover.
@@ -322,12 +356,22 @@ export interface TooltipOption {
// Events
// --------------------------------------------------------------------------------------
export interface CarouselEventHandler<TElement> extends JQuery.TriggeredEvent<TElement, undefined> {
export interface CarouselEventHandler<TElement> extends JQuery.TriggeredEvent<TElement, undefined, HTMLElement, HTMLElement> {
/**
* The carousel dom element.
*/
target: HTMLElement; // overridden only for better JsDoc
/**
* The direction in which the carousel is sliding.
*/
direction: "left" | "right";
/**
* The DOM element that is being slid into place as the active item.
*/
relatedTarget: HTMLElement;
/**
* The index of the current item.
*/
@@ -339,7 +383,44 @@ export interface CarouselEventHandler<TElement> extends JQuery.TriggeredEvent<TE
to: number;
}
export interface TapEventHandler<TElement> extends JQuery.TriggeredEvent<TElement, undefined> {
export interface DropdownsEventHandler<TElement> extends JQuery.TriggeredEvent<TElement, undefined, HTMLElement, HTMLElement> {
/**
* The the dropdown's toggle and the dropdown menu container (the `.dropdown` element).
*/
target: HTMLElement; // overridden only for better JsDoc
/**
* The toggling anchor element.
*/
relatedTarget: HTMLElement;
}
export interface ModalEventHandler<TElement> extends JQuery.TriggeredEvent<TElement, undefined, HTMLElement, HTMLElement> {
/**
* The modal dom element.
*/
target: HTMLElement; // overridden only for better JsDoc
/**
* For `show.bs.modal` and `shown.bs.modal` is the clicked element, when caused by a _click_.
* Otherwise is undefined.
*/
relatedTarget: HTMLElement | undefined;
}
export interface TapEventHandler<TElement> extends JQuery.TriggeredEvent<TElement, undefined, HTMLElement, HTMLElement> {
/**
* * For `show.bs.tab` and `shown.bs.tab`, is the newly activated tab.
* * For `hide.bs.tab`, is the current active tab.
* * For `hidden.bs.tab`, is the previous active tab.
*/
target: HTMLElement; // overridden only for better JsDoc
/**
* * For `show.bs.tab` and `shown.bs.tab`, is the previous active tab.
* * For `hide.bs.tab`, is the new soon-to-be-active tab.
* * For `hidden.bs.tab`, is the new active tab.
*/
relatedTarget: HTMLElement;
}
@@ -351,6 +432,7 @@ export type ModalEvent = "show.bs.modal" | "shown.bs.modal" | "hide.bs.modal" |
export type PopoverEvent = "show.bs.popover" | "shown.bs.popover" | "hide.bs.popover" | "hidden.bs.popover" | "inserted.bs.popover";
export type ScrollspyEvent = "activate.bs.scrollspy";
export type TapEvent = "show.bs.tab" | "shown.bs.tab" | "hide.bs.tab" | "hidden.bs.tab";
export type ToastEvent = "show.bs.toast" | "shown.bs.toast" | "hide.bs.toast" | "hidden.bs.toast";
export type TooltipEvent = "show.bs.tooltip" | "shown.bs.tooltip" | "hide.bs.tooltip" | "hidden.bs.tooltip" | "inserted.bs.tooltip";
// --------------------------------------------------------------------------------------
@@ -359,38 +441,177 @@ export type TooltipEvent = "show.bs.tooltip" | "shown.bs.tooltip" | "hide.bs.too
declare global {
interface JQuery<TElement = HTMLElement> {
/**
* If no _method_ is specified, makes an alert listen for click events on descendant elements which have the `data-dismiss="alert"` attribute.
* (Not necessary when using the data-api's auto-initialization.)
* Otherwise, call the method on the alert element:
* * `close` — Closes an alert by removing it from the DOM. If the `.fade` and `.show` classes are present on the element, the alert will fade out before it is removed.
* * `dispose` — Destroys an element's alert.
*/
alert(action?: "close" | "dispose"): this;
/**
* Call a method on the button element:
* * `toggle` — Toggles push state. Gives the button the appearance that it has been activated.
* * `dispose` — Destroys an element's button.
*/
button(action: "toggle" | "dispose"): this;
/**
* Call a method on the carousel element:
* * `cycle` — Cycles through the carousel items from left to right.
* * `pause` — Stops the carousel from cycling through items.
* * _number_ — Cycles the carousel to a particular frame (0 based, similar to an array).
* * `prev` — Cycles to the previous item.
* * `next` — Cycles to the next item.
* * `dispose` — Destroys an element's carousel.
*
* Returns to the caller before the target item has been shown (i.e. before the `slid.bs.carousel` event occurs).
*/
carousel(action: "cycle" | "pause" | number | "prev" | "next" | "dispose"): this;
/**
* Initializes the carousel and starts cycling through items.
*/
carousel(options?: CarouselOption): this;
/**
* Call a method on the collapsible element:
* * `toggle` – Toggles a collapsible element to shown or hidden.
* * `show` – Shows a collapsible element.
* * `hide` – Hides a collapsible element.
* * `dispose` – Destroys an element's collapse.
*
* Returns to the caller before the collapsible element has actually been shown or hidden (i.e. before the `shown.bs.collapse` or `hidden.bs.collapse` event occurs).
*/
collapse(action: "toggle" | "show" | "hide" | "dispose"): this;
/**
* Activates a content as a collapsible element.
*/
collapse(options?: CollapseOption): this;
/**
* Call a method on the dropdown element:
* * `toggle` – Toggles the dropdown menu of a given navbar or tabbed navigation.
* * `update` – Updates the position of an element's dropdown.
* * `dispose` — Destroys an element's dropdown.
*/
dropdown(action: "toggle" | "update" | "dispose"): this;
/**
* Toggle contextual overlays for displaying lists of links.
*
* The data-api, `data-toggle="dropdown"` is always required to be present on the dropdown's trigger element.
*/
dropdown(options?: DropdownOption): this;
/**
* Call a method on the modal element:
* * `toggle` – Manually toggles a modal.
* * `show` – Manually opens a modal.
* * `hide` – Manually hides a modal.
* * `handleUpdate` – Manually readjust the modal's position if the height of a modal changes while it is open (i.e. in case a scrollbar appears).
* * `dispose` – Destroys an element's modal.
*
* Returns to the caller before the modal has actually been shown or hidden (i.e. before the `shown.bs.modal` or `hidden.bs.modal` event occurs).
*/
modal(action: "toggle" | "show" | "hide" | "handleUpdate" | "dispose"): this;
/**
* Activates a content as a modal.
*/
modal(options?: ModalOption): this;
/**
* Call a method on the popover element:
* * `show` – Reveals an element's popover.
* * `hide` – Hides an element's popover.
* * `toggle` – Toggles an element's popover.
* * `dispose` – Hides and destroys an element's popover.
* Popovers that use delegation (which are created using the `selector` option) cannot be individually destroyed on descendant trigger elements.
* * `enable` – Gives an element's popover the ability to be shown. Popovers are enabled by default.
* * `disable` – Removes the ability for an element's popover to be shown. The popover will only be able to be shown if it is re-enabled.
* * `toggleEnabled` – Toggles the ability for an element's popover to be shown or hidden.
* * `update` – Updates the position of an element's popover.
*
* Returns to the caller before the popover has actually been shown or hidden (i.e. before the `shown.bs.popover` or `hidden.bs.popover` event occurs).
* This is considered a "manual" triggering of the popover. Popovers whose both title and content are zero-length are never displayed.
*/
popover(action: "show" | "hide" | "toggle" | "dispose" | "enable" | "disable" | "toggleEnabled" | "update"): this;
/**
* Initializes popovers for an element collection.
*/
popover(options?: PopoverOption): this;
// tslint:disable:jsdoc-format
/**
* Call a method on the scrollspy element:
* * `refresh` – When using scrollspy in conjunction with adding or removing of elements from the DOM, you'll need to call the refresh, see example.
* * `dispose` – Destroys an element's scrollspy.
*
* @example
```javascript
$('[data-spy="scroll"]').each(function () {
var $spy = $(this).scrollspy('refresh')
})
```
*/
// tslint:enable:jsdoc-format
scrollspy(action: "refresh" | "dispose"): this;
/**
* Add scrollspy behavior to a topbar navigation.
*/
scrollspy(options?: ScrollspyOption): this;
/**
* Call a method on the list item or tab element:
* * `show` – Selects the given list item or tab and shows its associated pane.
* Any other list item or tab that was previously selected becomes unselected and its associated pane is hidden.
* * `dispose` – Destroys an element's tab.
*
* Returns to the caller before the tab pane has actually been shown (i.e. before the `shown.bs.tab` event occurs).
*/
tab(action: "show" | "dispose"): this;
/**
* Call a method on the toast element:
* * `show` – Reveals an element's toast. You have to manually call this method, instead your toast won't show.
* * `hide` – Hides an element's toast. You have to manually call this method if you made `autohide` to false.
* * `dispose` – Hides an element's toast. Your toast will remain on the DOM but won't show anymore.
*
* Returns to the caller before the toast has actually been shown or hidden (i.e. before the `shown.bs.toast` or `hidden.bs.toast` event occurs).
*/
toast(action: "show" | "hide" | "dispose"): this;
/**
* Attaches a toast handler to an element collection.
*/
toast(options?: ToastOption): this;
/**
* Call a method on the tooltip element:
* * `show` – Reveals an element's tooltip.
* * `hide` – Hides an element's tooltip.
* * `toggle` – Toggles an element's tooltip.
* * `dispose` – Hides and destroys an element's tooltip.
* Tooltips that use delegation (which are created using `selector` option) cannot be individually destroyed on descendant trigger elements.
* * `enable` – Gives an element's tooltip the ability to be shown. Tooltips are enabled by default.
* * `disable` – Removes the ability for an element's tooltip to be shown. The tooltip will only be able to be shown if it is re-enabled.
* * `toggleEnabled` – Toggles the ability for an element's tooltip to be shown or hidden.
* * `update` – Updates the position of an element's tooltip.
*
* Returns to the caller before the tooltip has actually been shown or hidden (i.e. before the `shown.bs.tooltip` or `hidden.bs.tooltip` event occurs).
* This is considered a "manual" triggering of the tooltip.
*/
tooltip(action: "show" | "hide" | "toggle" | "dispose" | "enable" | "disable" | "toggleEnabled" | "update"): this;
/**
* Attaches a tooltip handler to an element collection.
*/
tooltip(options?: TooltipOption): this;
on(events: CarouselEvent, handler: JQuery.EventHandlerBase<TElement, CarouselEventHandler<TElement>>): this;
on(events: DropdownEvent, handler: JQuery.EventHandlerBase<TElement, DropdownsEventHandler<TElement>>): this;
on(events: ModalEvent, handler: JQuery.EventHandlerBase<TElement, ModalEventHandler<TElement>>): this;
on(events: TapEvent, handler: JQuery.EventHandlerBase<TElement, TapEventHandler<TElement>>): this;
on(events:
AlertEvent | CollapseEvent | DropdownEvent | ModalEvent |
PopoverEvent | ScrollspyEvent | TooltipEvent,
handler: JQuery.EventHandler<TElement>): this;
on(
events: AlertEvent | CollapseEvent | PopoverEvent | ScrollspyEvent | ToastEvent | TooltipEvent,
handler: JQuery.EventHandler<TElement>
): this;
}
}
+37
View File
@@ -0,0 +1,37 @@
import boxen = require('boxen');
boxen('unicorn'); // $ExpectType string
boxen('unicorn', { borderColor: 'black' }); // $ExpectType string
boxen('unicorn', { borderStyle: 'double' }); // $ExpectType string
boxen('unicorn', { borderStyle: 'foo' }); // $ExpectError
// $ExpectType string
boxen('unicorn', {
borderStyle: {
topLeft: '+',
topRight: '+',
bottomLeft: '+',
bottomRight: '+',
horizontal: '-',
vertical: '|',
},
});
boxen('unicorn', { dimBorder: true }); // $ExpectType string
boxen('unicorn', { padding: 1 }); // $ExpectType string
boxen('unicorn', { padding: { top: 1 } }); // $ExpectType string
boxen('unicorn', { padding: { right: 1 } }); // $ExpectType string
boxen('unicorn', { padding: { bottom: 1 } }); // $ExpectType string
boxen('unicorn', { padding: { left: 1 } }); // $ExpectType string
boxen('unicorn', { margin: 1 }); // $ExpectType string
boxen('unicorn', { margin: { top: 1 } }); // $ExpectType string
boxen('unicorn', { margin: { right: 1 } }); // $ExpectType string
boxen('unicorn', { margin: { bottom: 1 } }); // $ExpectType string
boxen('unicorn', { margin: { left: 1 } }); // $ExpectType string
boxen('unicorn', { float: 'right' }); // $ExpectType string
boxen('unicorn', { float: 'center' }); // $ExpectType string
boxen('unicorn', { float: 'left' }); // $ExpectType string
boxen('unicorn', { float: 'foo' }); // $ExpectError
boxen('unicorn', { backgroundColor: 'white' }); // $ExpectType string
boxen('unicorn', { align: 'left' }); // $ExpectType string
boxen('unicorn', { align: 'center' }); // $ExpectType string
boxen('unicorn', { align: 'right' }); // $ExpectType string
boxen('unicorn', { align: 'foo' }); // $ExpectError
+114
View File
@@ -0,0 +1,114 @@
// Type definitions for boxen 2.1
// Project: https://github.com/sindresorhus/boxen#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
import { BoxDefinition, BoxNames } from 'cli-boxes';
export = boxen;
/**
* Create boxes in the terminal
* @param input Text inside the box.
*/
declare function boxen(input: string, options?: boxen.Options): string;
declare namespace boxen {
interface Options {
/**
* Color of the box border.
* Values: `black` `red` `green` `yellow` `blue` `magenta` `cyan` `white` `gray` or a hex value like `#ff0000`
*/
borderColor?: string;
/**
* Style of the box border.
* Can be any of the above predefined styles or an object.
*
* Predefined values:
* - `single`
* ```
* ┌───┐
* │foo│
* └───┘
* ```
* - `double`
* ```
* ╔═══╗
* ║foo║
* ╚═══╝
* ```
* - `round` (`single` sides with round corners)
* ```
* ╭───╮
* │foo│
* ╰───╯
* ```
* - `single-double` (`single` on top and bottom, `double` on right and left)
* ```
* ╓───╖
* ║foo║
* ╙───╜
* ```
* - `double-single` (`double` on top and bottom, `single` on right and left)
* ```
* ╒═══╕
* │foo│
* ╘═══╛
* ```
* - `classic`
* ```
* +---+
* |foo|
* +---+
* ```
*/
borderStyle?: BoxNames | BoxDefinition;
/**
* Reduce opacity of the border.
* @default false
*/
dimBorder?: boolean;
/**
* Space between the text and box border.
* When a number is specified, the left/right padding is 3 times the top/bottom to make it look nice.
* @default 0
*/
padding?: number | PositionOptions;
/**
* Space around the box.
* When a number is specified, the left/right margin is 3 times the top/bottom to make it look nice.
* @default 0
*/
margin?: number | PositionOptions;
/**
* Float the box on the available terminal screen space.
* @default 'left'
*/
float?: 'right' | 'center' | 'left';
/**
* Color of the background.
* Values: `black` `red` `green` `yellow` `blue` `magenta` `cyan` `white` `gray` or a hex value like `#ff0000`
*/
backgroundColor?: string;
/**
* Align the text in the box based on the widest line.
* @default 'left'
*/
align?: 'left' | 'center' | 'right';
}
interface PositionOptions {
top?: number;
right?: number;
bottom?: number;
left?: number;
}
}
+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",
"boxen-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
@@ -23,3 +23,19 @@ const myObject = { x: 1, y: 2 };
log.info({ obj: myObject }, 'This is my object:');
new bunyan.ConsoleFormattedStream({ logByLevel: true });
const style = {
levels: {
trace: 'color: DeepPink',
debug: 'color: GoldenRod',
info: 'color: DarkTurquoise',
warn: 'color: Purple',
error: 'color: Crimson',
fatal: 'color: Black',
},
def: 'color: DimGray',
msg: 'color: SteelBlue',
src: 'color: DimGray; font-style: italic; font-size: 0.9em',
};
new bunyan.ConsoleFormattedStream({ css: style });
+19 -6
View File
@@ -10,17 +10,30 @@
import * as bunyan from 'bunyan';
declare namespace BrowserBunyan {
interface ConsoleFormattedStreamLevelStyle {
trace: string;
debug: string;
info: string;
warn: string;
error: string;
fatal: string;
}
interface ConsoleFormattedStreamStyle {
levels: Partial<ConsoleFormattedStreamLevelStyle>;
def: string;
msg: string;
src: string;
}
interface ConsoleFormattedStreamOptions {
logByLevel?: boolean;
css?: Partial<ConsoleFormattedStreamStyle>;
}
interface ConsoleFormattedStream {
new(options?: ConsoleFormattedStreamOptions): NodeJS.WritableStream;
}
type ConsoleFormattedStream = new(options?: ConsoleFormattedStreamOptions) => NodeJS.WritableStream;
interface ConsoleRawStream {
new(options?: ConsoleFormattedStreamOptions): NodeJS.WritableStream;
}
type ConsoleRawStream = new(options?: ConsoleFormattedStreamOptions) => NodeJS.WritableStream;
}
type BrowserBunyan = typeof bunyan & {
+6 -9
View File
@@ -1,11 +1,8 @@
import bs58 = require('bs58');
import * as bs58 from 'bs58';
const bytes = Buffer.from('003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187', 'hex');
const address = bs58.encode(bytes);
address; // $ExpectType string
{
let encoded: string;
encoded = bs58.encode([255]);
encoded = bs58.encode({0: 255, length: 1});
}
let decoded: number[] = bs58.decode('5Q');
bs58.decode(address); // $ExpectType Buffer
bs58.decodeUnsafe(address); // $ExpectType Buffer | undefined
+4 -7
View File
@@ -1,14 +1,11 @@
// Type definitions for bs58 3.0.0
// Type definitions for bs58 4.0
// Project: https://github.com/cryptocoinjs/bs58
// Definitions by: Ilya Mochalov <https://github.com/chrootsu>
// BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="base-x" />
import { BaseConverter } from 'base-x';
import * as BaseX from 'base-x';
declare namespace base58 { }
declare let base58: BaseX.BaseConverter;
declare const base58: BaseConverter;
export = base58;
+2 -2
View File
@@ -6,7 +6,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
@@ -20,4 +20,4 @@
"index.d.ts",
"bs58-tests.ts"
]
}
}
+1 -77
View File
@@ -1,79 +1,3 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
"extends": "dtslint/dt.json"
}
+10
View File
@@ -0,0 +1,10 @@
import * as bs58 from 'bs58';
{
let encoded: string;
encoded = bs58.encode([255]);
encoded = bs58.encode({0: 255, length: 1});
}
const decoded: number[] = bs58.decode('5Q');
+12
View File
@@ -0,0 +1,12 @@
// Type definitions for bs58 3.0
// Project: https://github.com/cryptocoinjs/bs58
// Definitions by: Ilya Mochalov <https://github.com/chrootsu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import * as BaseX from 'base-x';
declare namespace base58 { }
declare let base58: BaseX.BaseConverter;
export = base58;
+31
View File
@@ -0,0 +1,31 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"paths": {
"bs58": [
"bs58/v3"
],
"base-x": [
"base-x/v1"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"bs58-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+11
View File
@@ -0,0 +1,11 @@
import crc32 = require('buffer-crc32');
const buf = new Buffer([0x00, 0x73, 0x75, 0x70, 0x20, 0x62, 0x72, 0x6f, 0x00]);
crc32(buf); // $ExpectType Buffer
crc32('自動販売機'); // $ExpectType Buffer
crc32.signed(buf); // $ExpectType number
crc32.unsigned(buf); // $ExpectType number
const partialCrc = crc32('hey');
crc32(' ', partialCrc); // $ExpectType Buffer
+15
View File
@@ -0,0 +1,15 @@
// Type definitions for buffer-crc32 0.2
// Project: https://github.com/brianloveswords/buffer-crc32
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
export = crc32;
declare function crc32(input: string | Buffer, partialCrc?: Buffer): Buffer;
declare namespace crc32 {
function signed(buffer: Buffer): number;
function unsigned(buffer: Buffer): number;
}
+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",
"buffer-crc32-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

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