Updated for Meteor 1.3. Added more tests to verify recent updates to definitions.

This commit is contained in:
Dave Allen
2016-03-30 11:16:17 -07:00
parent bf4ecf5b68
commit 34c761bb51
3 changed files with 165 additions and 140 deletions
+18 -87
View File
@@ -1,52 +1,20 @@
# Meteor Type Definitions
These are the definitions for version 1.2.0.2 of Meteor.
Although these definitions can be downloaded separately for use, the recommended way to use these definitions in a Meteor application is by installing the
[typescript-libs](https://atmospherejs.com/meteortypescript/typescript-libs) Meteor smart package from atmosphere. The smart package contains TypeScript
definitions forMeteor, common third-party libraries (e.g. jquery, underscore, d3 etc.), and common smart packages (e.g. iron-router, etc).
From within any Meteor application that is version 0.9.0 or later, install this package in the standard manner:
$ meteor add meteortypescript:typescript-libs
These definitions were generated from the from the same [Meteor data.js file] (https://github.com/meteor/meteor/blob/devel/docs/client/data.js) that is used
to generate the official [Meteor docs] (http://docs.meteor.com/).
These are the definitions for version 1.3 of Meteor. These definitions were generated from the from the same [Meteor data.js file] (https://github.com/meteor/meteor/blob/devel/docs/client/data.js) that is used to generate the official [Meteor docs] (http://docs.meteor.com/). The code that generates these definitions can be found [here](https://github.com/meteor-typescript/meteor-typescript-libs/).
## Usage (OSX/Linux)
## Upcoming Meteor `typescript` package
1. Add a symbolic link to the definitions from within some directory within your project (e.g. ".typescript" or "lib"). The definitions can be found somewhere deep within `<project_root_dir>/.meteor/...`. The following will probably work:
There is currently an effort supported by the Meteor Development Group to create a TypeScript build compiler package, and an early version of the package can be tested using [`barbatus:typescript`](https://atmospherejs.com/barbatus/typescript).
$ ln -s ../.meteor/local/build/programs/server/assets/packages/meteortypescript_typescript-libs/definitions package_defs
From within any Meteor application that is version 1.2.1 or later, install this package in the standard manner:
If the definitions can't be found within the .meteor directory, you will have to manually pull down the definitions from github and add them to your project:
<https://github.com/meteor-typescript/meteor-typescript-libs>
$ meteor add barbatus:typescript
2. Install the [Typescript compiler for Meteor](https://github.com/meteor-typescript/meteor-typescript-compiler) or an [IDE which can transpile TypeScript to JavaScript](#transpiling-typescript).
3. From the typescript files, add references. Reference the definition files with a single line:
This package will eventually incorporated as a Meteor core package (e.g. like the `coffeescript` package). It appears that the eventual recommended practice for adding definitions using that package will be to add them using the [`typings`](https://github.com/typings/typings) tool.
/// <reference path=".typescript/package_defs/all-definitions.d.ts" /> (substitute path in your project)
You can follow discussion about this effort [here](https://github.com/Urigo/angular2-meteor/issues/102#issuecomment-200915763).
Or you can reference definition files individually:
/// <reference path=".typescript/package_defs/meteor.d.ts" /> (substitute path in your project)
/// <reference path=".typescript/package_defs/underscore.d.ts" />
/// <reference path=".typescript/package_defs/jquery.d.ts" />
Meteor core definitions can be referenced in an "all-in-one" definition file ( *meteor.d.ts* ) or definition files specific to the locus of execution:
- *meteor.d.ts*: all meteor core definitions
- *meteor.common.d.ts*: meteor core code running on both client and server
- *meteor.client.d.ts*: meteor core client-only code
- *meteor.server.d.ts*: meteor core server-only code
- *meteor.package.d.ts*: meteor core package-only code
- *meteor.build.d.ts*: meteor core build-only code
*meteor.d.ts* contains all of the definitions found in *meteor.common.d.ts*, *meteor.client.d.ts*, *meteor.server.d.ts*, *meteor.package.d.ts*, and *meteor.build.d.ts*
4. Be aware of differences in coding styles when using TypeScript (see below)
## TypeScript/Meteor coding style
@@ -55,15 +23,14 @@ to generate the official [Meteor docs] (http://docs.meteor.com/).
Meteor code can run on the client and the server, for this reason you should try to stay away from referencing *file.ts* directly: you may get unexpected results.
Rather generate a *file.d.ts* using `tsc --declaration file.ts`, and reference it in your file.
Rather generate a *file.d.ts* using `tsc --declaration file.ts`, and reference it in your file.
Compilation will be much faster and code will be cleaner - it's always better to split definition from implementation anyways.
### Templates
With the exception of the **body** and **head** templates, Meteor's Template dot notation cannot be used (ie. *Template.mytemplate*). Thanks to Typescript static typing checks, you will need to use the *bracket notation* to access the Template.
Template['myTemplateName'].helpers({
foo: function () {
return Session.get("foo");
@@ -71,20 +38,27 @@ With the exception of the **body** and **head** templates, Meteor's Template dot
});
Template['myTemplateName'].onRendered(function ( ) { ... });
The same is true for `Meteor.settings`:
Meteor.settings.public['<some config>']
### Form fields
Form fields typically need to be cast to `<HTMLInputElement>`. For instance to read a form field value, use `(<HTMLInputElement>evt.target).value`.
### Global variables
Preface any global variable declarations with a TypeScript "declare var" statement (or place the statement in a definition file):
Preface any global variable declarations with a TypeScript `declare var` statement (or place the statement in a definition file):
declare var NavbarHelpers;
NavbarHelpers = {};
NavbarHelpers.someMethod = function() {...}
### Collections
The majority of extra work required to use TypeScript with Meteor is creating and maintaining the collection interfaces. However, doing so also provides the additional benefit of succinctly documenting collection schema definitions (that are actually enforced).
@@ -106,46 +80,3 @@ Finally, any TypeScript file using collections will need to contain a reference
/// <reference path=".typescript/package_defs/meteor.d.ts"/>
/// <reference path=".typescript/custom_defs/collections.ts"/>
### Creating definition files
Here is a guide to creating definitions: <http://www.typescriptlang.org/Handbook#writing-dts-files>
If you have lots of custom definitions for a project, you can:
- Create multiple definition files and include individual references to each definition file.
- Create one huge monolithic definition file so you only have to refer to that file.
- Create multiple definition files, and create a definition file with references to the other definitions files so that you only have to maintain one reference for all of you custom definitions. e.g. contents of ".typescript/custom_defs/custom-definitions.d.ts":
/// <reference path='collections.ts' />
/// <reference path='paraview_helpers.d.ts'/>
/// <reference path='handsontable.d.ts'/>
/// <reference path='utility_helpers.ts'/>
## Transpiling TypeScript
### Meteor plugin
One solution for transpiling typescript is to install the following meteor package: [https://github.com/meteor-typescript/meteor-typescript-compiler](https://github.com/meteor-typescript/meteor-typescript-compiler)
### IDE/Editor Transpilation
WebStorm, SublimeText, Atom, and VisualStudio all support TypeScript. They can automatically transpile your TypeScript code into JavaScript every time you save a file.
#### WebStorm ####
To support TypeScript in WebStorm on OSX, first install the TypeScript transpiler on your system:
$ [sudo -H] npm install -g typescript
On version 10 of WebStorm or later, got to Preferences -> Languages & Frameworks -> TypeScript and check "Enable TypeScript Compiler"
On older versions of WebStorm (9 or earlier), go to Preferences -> File Watchers -> "+" symbol and add TypeScript.
#### SublimeText, Atom, and VisualStudio ####
Please refer to the documentation for these editors.
### Command line
The last option is to compile code from the command line. With node and the TypeScript compiler installed:
$ tsc *.ts
+58 -5
View File
@@ -131,12 +131,15 @@ Meteor.methods({
/**
* From Methods, Meteor.Error section
*/
throw new Meteor.Error("logged-out",
"The user must be logged in to post a comment.");
throw new Meteor.Error(403,
"The user must be logged in to post a comment.");
function meteorErrorTestFunction1() {
throw new Meteor.Error("logged-out",
"The user must be logged in to post a comment.");
}
function meteorErrorTestFunction2() {
throw new Meteor.Error(403,
"The user must be logged in to post a comment.");
}
Meteor.call("methodName", function (error: Meteor.Error) {
if (error.error === "logged-out") {
@@ -623,3 +626,53 @@ var reactiveVar2 = new ReactiveVar<string>('test value', function(oldVal:any) {
var varValue: string = reactiveVar1.get();
reactiveVar1.set('new value');
// Covers this PR: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/8233
var isConfigured: boolean = Accounts.loginServicesConfigured();
Accounts.onPageLoadLogin(function() {
// do something
});
// Covers this PR: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/8065
var loginOpts: Meteor.LoginWithExternalServiceOptions = {
requestPermissions: ["a", "b"],
requestOfflineToken: true,
loginUrlParameters: {asdf: 1, qwer: "1234"},
loginHint: "Help me",
loginStyle: "Bold and powerful",
redirectUrl: "popup",
profile: "asdfasdf",
email: "asdf@ASDf.com"
};
Meteor.loginWithMeteorDeveloperAccount(loginOpts, function(error, result) {});
Accounts.emailTemplates.siteName = "AwesomeSite";
Accounts.emailTemplates.from = "AwesomeSite Admin <accounts@example.com>";
Accounts.emailTemplates.headers = { asdf: 'asdf', qwer: 'qwer' };
Accounts.emailTemplates.enrollAccount.subject = function (user) {
return "Welcome to Awesome Town, " + user.profile.name;
};
Accounts.emailTemplates.enrollAccount.html = function (user, url) {
return "<h1>Some html here</h1>";
};
Accounts.emailTemplates.enrollAccount.from = function() {
return "asdf@asdf.com";
};
Accounts.emailTemplates.enrollAccount.text = function (user, url) {
return "You have been selected to participate in building a better future!"
+ " To activate your account, simply click the link below:\n\n"
+ url;
};
var handle = Accounts.validateLoginAttempt(function(attemptInfoObject: Accounts.IValidateLoginAttemptCbOpts) {
var type: string = attemptInfoObject.type;
var allowed: boolean = attemptInfoObject.allowed;
var error: Meteor.Error = attemptInfoObject.error;
var user: Meteor.User = attemptInfoObject.user;
var connection: Meteor.Connection = attemptInfoObject.connection;
var methodName: string = attemptInfoObject.methodName;
var methodArguments: any[] = attemptInfoObject.methodArguments;
return true;
});
handle.stop();
+89 -48
View File
@@ -1,4 +1,4 @@
// Type definitions for Meteor 1.2.0.2
// Type definitions for Meteor 1.3
// Project: http://www.meteor.com/
// Definitions by: Dave Allen <https://github.com/fullflavedave>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -15,7 +15,7 @@ interface JSONable {
}
interface EJSON extends EJSONable {}
declare namespace Match {
declare module Match {
var Any: any;
var String: any;
var Integer: any;
@@ -29,7 +29,7 @@ declare namespace Match {
function Where(condition: any): any;
}
declare namespace Meteor {
declare module Meteor {
interface UserEmail {
address:string;
verified:boolean;
@@ -57,7 +57,7 @@ declare namespace Meteor {
}
}
declare namespace DDP {
declare module DDP {
interface DDPStatic {
subscribe(name: string, ...rest: any[]): Meteor.SubscriptionHandle;
call(method: string, ...parameters: any[]):void;
@@ -79,7 +79,7 @@ declare namespace DDP {
}
}
declare namespace Mongo {
declare module Mongo {
interface Selector {
[key: string]:any;
}
@@ -91,7 +91,7 @@ declare namespace Mongo {
}
}
declare namespace HTTP {
declare module HTTP {
interface HTTPRequest {
content?:string;
@@ -118,7 +118,7 @@ declare namespace HTTP {
function put(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse;
}
declare namespace Random {
declare module Random {
function id(numberOfChars?: number): string;
function secret(numberOfChars?: number): string;
function fraction():number;
@@ -127,13 +127,18 @@ declare namespace Random {
function choice(str:string):string; // @param str, @return a random char in str
}
declare module Accounts {
function loginServicesConfigured(): boolean;
function onPageLoadLogin(func: Function): void;
}
/**
* These are the client modules and interfaces that can't be automatically generated from the Meteor data.js file
*/
declare namespace Meteor {
declare module Meteor {
/** Start definitions for Template **/
interface Event {
export interface Event {
type:string;
target:HTMLElement;
currentTarget:HTMLElement;
@@ -157,10 +162,13 @@ declare namespace Meteor {
interface LoginWithExternalServiceOptions {
requestPermissions?: string[];
requestOfflineToken?: Boolean;
forceApprovalPrompt?: Boolean;
userEmail?: string;
requestOfflineToken?: boolean;
loginUrlParameters?: {[param: string]: any}
loginHint?: string;
loginStyle?: string;
redirectUrl?: "popup" | "redirect";
profile?: any;
email?: string;
}
function loginWithMeteorDeveloperAccount(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void;
@@ -170,6 +178,7 @@ declare namespace Meteor {
function loginWithMeetup(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void;
function loginWithTwitter(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void;
function loginWithWeibo(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void;
function _sleepForMs(milliseconds: number): void;
interface SubscriptionHandle {
stop(): void;
@@ -177,7 +186,7 @@ declare namespace Meteor {
}
}
declare namespace Blaze {
declare module Blaze {
interface View {
name: string;
parentView: Blaze.View;
@@ -201,7 +210,7 @@ declare namespace Blaze {
}
}
declare namespace BrowserPolicy {
declare module BrowserPolicy {
interface framing {
disallow():void;
@@ -242,18 +251,21 @@ declare namespace BrowserPolicy {
* These are the server modules and interfaces that can't be automatically generated from the Meteor data.js file
*/
declare namespace Meteor {
declare module Meteor {
interface EmailFields {
subject?: Function;
text?: Function;
from?: () => string;
subject?: (user: Meteor.User) => string;
text?: (user: Meteor.User, url: string) => string;
html?: (user: Meteor.User, url: string) => string;
}
interface EmailTemplates {
from: string;
siteName: string;
resetPassword: Meteor.EmailFields;
enrollAccount: Meteor.EmailFields;
verifyEmail: Meteor.EmailFields;
from?: string;
siteName?: string;
headers?: { [id: string]: string }; // TODO: should define IHeaders interface
resetPassword?: Meteor.EmailFields;
enrollAccount?: Meteor.EmailFields;
verifyEmail?: Meteor.EmailFields;
}
interface Connection {
@@ -263,9 +275,19 @@ declare namespace Meteor {
clientAddress: string;
httpHeaders: Object;
}
interface IValidateLoginAttemptCbOpts {
type: string;
allowed: boolean;
error: Error;
user: Meteor.User;
connection: Meteor.Connection;
methodName: string;
methodArguments: any[];
}
}
declare namespace Mongo {
declare module Mongo {
interface AllowDenyOptions {
insert?: (userId: string, doc: any) => boolean;
update?: (userId: string, doc: any, fieldNames: string[], modifier: any) => boolean;
@@ -275,6 +297,18 @@ declare namespace Mongo {
}
}
declare module Accounts {
interface IValidateLoginAttemptCbOpts {
type?: string;
allowed?: boolean;
error?: Meteor.Error;
user?: Meteor.User;
connection?: Meteor.Connection;
methodName?: string;
methodArguments?: any[];
}
}
interface MailComposerOptions {
escapeSMTP: boolean;
encoding: string;
@@ -328,20 +362,20 @@ interface ITinytestAssertions {
_stringEqual(actual: string, expected: string, msg?: string): void;
}
declare namespace Tinytest {
declare module Tinytest {
function add(description : string , func : (test : ITinytestAssertions) => void) : void;
function addAsync(description : string , func : (test : ITinytestAssertions) => void) : void;
}
// Kept in for backwards compatibility
declare namespace Meteor {
declare module Meteor {
interface Tinytest {
add(description : string , func : (test : ITinytestAssertions) => void) : void;
addAsync(description : string , func : (test : ITinytestAssertions) => void) : void;
}
}
declare namespace Accounts {
declare module Accounts {
function addEmail(userId: string, newEmail: string, verified?: boolean): void;
function changePassword(oldPassword: string, newPassword: string, callback?: Function): void;
function createUser(options: {
@@ -392,14 +426,13 @@ declare namespace Accounts {
function logout(callback?: Function): void;
function logoutOtherClients(callback?: Function): void;
function onCreateUser(func: Function): void;
function validateLoginAttempt(func: Function): { stop: () => void };
function validateLoginAttempt(cb: (params: Accounts.IValidateLoginAttemptCbOpts) => boolean): { stop: () => void };
function validateNewUser(func: Function): boolean;
function loginServicesConfigured(): boolean;
function onPageLoadLogin(func: Function): void;
}
declare namespace App {
function accessRule(domainRule: string, options?: {
declare module App {
function accessRule(pattern: string, options?: {
type?: string;
launchExternal?: boolean;
}): void;
function configurePlugin(id: string, config: Object): void;
@@ -417,12 +450,12 @@ declare namespace App {
function setPreference(name: string, value: string, platform?: string): void;
}
declare namespace Assets {
declare module Assets {
function getBinary(assetPath: string, asyncCallback?: Function): EJSON;
function getText(assetPath: string, asyncCallback?: Function): string;
}
declare namespace Blaze {
declare module Blaze {
function Each(argFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View;
function If(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View;
function Let(bindings: Function, contentFunc: Function): Blaze.View;
@@ -476,20 +509,20 @@ declare namespace Blaze {
function toHTMLWithData(templateOrView: Template | Blaze.View, data: Object | Function): string;
}
declare namespace Cordova {
declare module Cordova {
function depends(dependencies:{[id:string]:string}): void;
}
declare namespace DDP {
declare module DDP {
function connect(url: string): DDP.DDPStatic;
}
declare namespace DDPCommon {
declare module DDPCommon {
function MethodInvocation(options: {
}): any;
}
declare namespace EJSON {
declare module EJSON {
var CustomType: CustomTypeStatic;
interface CustomTypeStatic {
new(): CustomType;
@@ -517,11 +550,11 @@ declare namespace EJSON {
function toJSONValue(val: EJSON): JSONable;
}
declare namespace Match {
declare module Match {
function test(value: any, pattern: any): boolean;
}
declare namespace Meteor {
declare module Meteor {
var Error: ErrorStatic;
interface ErrorStatic {
new(error: string | number, reason?: string, details?: string): Error;
@@ -546,13 +579,15 @@ declare namespace Meteor {
function disconnect(): void;
var isClient: boolean;
var isCordova: boolean;
var isDevelopment: boolean;
var isProduction: boolean;
var isServer: boolean;
function loggingIn(): boolean;
function loginWith<ExternalService>(options?: {
requestPermissions?: string[];
requestOfflineToken?: boolean;
loginUrlParameters?: Object;
userEmail?: string;
loginHint?: string;
loginStyle?: string;
redirectUrl?: string;
}, callback?: Function): void;
@@ -566,7 +601,7 @@ declare namespace Meteor {
var release: string;
function setInterval(func: Function, delay: number): number;
function setTimeout(func: Function, delay: number): number;
var settings: {[id:string]: any};
var settings: { public: {[id:string]: any}, private: {[id:string]: any}, [id:string]: any};
function startup(func: Function): void;
function status(): Meteor.StatusEnum;
function subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle;
@@ -576,7 +611,7 @@ declare namespace Meteor {
function wrapAsync(func: Function, context?: Object): any;
}
declare namespace Mongo {
declare module Mongo {
var Collection: CollectionStatic;
interface CollectionStatic {
new<T>(name: string, options?: {
@@ -607,6 +642,9 @@ declare namespace Mongo {
fields?: Mongo.FieldSpecifier;
reactive?: boolean;
transform?: Function;
disableOplog?: boolean;
pollingIntervalMs?: number;
pollingThrottleMs?: number;
}): Mongo.Cursor<T>;
findOne(selector?: Mongo.Selector | Mongo.ObjectID | string, options?: {
sort?: Mongo.SortSpecifier;
@@ -651,12 +689,12 @@ declare namespace Mongo {
}
declare namespace Npm {
declare module Npm {
function depends(dependencies:{[id:string]:string}): void;
function require(name: string): any;
}
declare namespace Package {
declare module Package {
function describe(options: {
summary?: string;
version?: string;
@@ -665,6 +703,7 @@ declare namespace Package {
documentation?: string;
debugOnly?: boolean;
prodOnly?: boolean;
testOnly?: boolean;
}): void;
function onTest(func: Function): void;
function onUse(func: Function): void;
@@ -676,7 +715,7 @@ declare namespace Package {
}): void;
}
declare namespace Tracker {
declare module Tracker {
function Computation(): void;
interface Computation {
firstRun: boolean;
@@ -709,14 +748,14 @@ declare namespace Tracker {
function onInvalidate(callback: Function): void;
}
declare namespace Session {
declare module Session {
function equals(key: string, value: string | number | boolean | any /** Null **/ | any /** Undefined **/): boolean;
function get(key: string): any;
function set(key: string, value: EJSONable | any /** Undefined **/): void;
function setDefault(key: string, value: EJSONable | any /** Undefined **/): void;
}
declare namespace HTTP {
declare module HTTP {
function call(method: string, url: string, options?: {
content?: string;
data?: Object;
@@ -731,11 +770,12 @@ declare namespace HTTP {
}, asyncCallback?: Function): HTTP.HTTPResponse;
function del(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse;
function get(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse;
function patch(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse;
function post(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse;
function put(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse;
}
declare namespace Email {
declare module Email {
function send(options: {
from?: string;
to?: string | string[];
@@ -837,6 +877,7 @@ interface TemplateStatic {
$:any;
body: Template;
currentData(): {};
deregisterHelper(name: string): void;
instance(): Blaze.TemplateInstance;
parentData(numLevels?: number): {};
registerHelper(name: string, helperFunction: Function): void;