Commit 22ccc678 authored by 神楽坂玲奈's avatar 神楽坂玲奈

init

parents
FROM node
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
ARG NODE_ENV
ENV NODE_ENV $NODE_ENV
COPY package.json /usr/src/app/
RUN npm install
COPY . /usr/src/app
RUN node_modules/.bin/tsc
CMD [ "npm", "start" ]
#!/usr/bin/env node
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments)).next());
});
};
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const child_process = require("child_process");
const Mustache = require("mustache");
require("promised-node");
// const vercomp = require('vercomp');
let database;
try {
database = require('/data/apps/data.json');
}
catch (error) {
database = {};
}
const release_path = '/data/release';
function readdirRecursive(_path) {
return __awaiter(this, void 0, void 0, function* () {
let files = yield fs.readdirAsync(_path);
let result = files;
for (let file of files) {
let child = path.join(_path, file);
let stat = yield fs.statAsync(child);
if (stat.isDirectory()) {
result = result.concat((yield readdirRecursive(child)).map((_file) => path.join(file, _file)));
}
}
return result;
});
}
function caculateSHA256(file) {
return new Promise((resolve, reject) => {
let input = fs.createReadStream(file);
const hash = crypto.createHash("sha256");
hash.on("error", (error) => {
reject(error);
});
input.on("error", (error) => {
reject(error);
});
hash.on('readable', () => {
let data = hash.read();
if (data) {
resolve(data.toString("hex"));
}
});
input.pipe(hash);
});
}
function archive(archive, files, directory) {
return new Promise((resolve, reject) => {
let child = child_process.spawn("tar", ["-zcvf", archive, '-C', directory].concat(files), { stdio: 'inherit' });
child.on('exit', (code) => {
if (code == 0) {
resolve();
}
else {
reject(code);
}
});
child.on('error', (error) => {
reject(error);
});
});
}
function nothing() {
}
function main(package_id, version) {
return __awaiter(this, void 0, void 0, function* () {
console.log(`package ${package_id} version ${version}`);
yield fs.mkdirAsync(release_path).catch(nothing);
yield fs.mkdirAsync(path.join(release_path, "downloads")).catch(nothing);
yield fs.mkdirAsync(path.join(release_path, "metalinks")).catch(nothing);
yield fs.mkdirAsync(path.join(release_path, "checksums")).catch(nothing);
yield fs.mkdirAsync(path.join(release_path, "dist")).catch(nothing);
yield fs.unlinkAsync(path.join(release_path, "downloads", `${package_id}.tar.gz`)).catch(nothing);
const template = yield fs.readFileAsync("template.meta4", { encoding: 'utf8' });
// 列目录
let package_path = path.join('/data/apps', package_id);
let files = yield readdirRecursive(package_path);
files.unshift('.');
// 计算checksum
let checksums = new Map();
for (let file of files) {
let stat = yield fs.statAsync(path.join(package_path, file));
if (stat.isDirectory()) {
checksums.set(file, '');
}
else {
checksums.set(file, yield caculateSHA256(path.join(package_path, file)));
}
}
// 生成checksum文件
let checksum = Array.from(checksums).map(([file, checksum]) => `${checksum} ${file}`).join("\n");
fs.writeFileAsync(path.join(release_path, "checksums", package_id), checksum);
// 打整包
yield fs.mkdirAsync(path.join(release_path, "downloads", package_id)).catch(nothing);
yield fs.mkdirAsync(path.join(release_path, "downloads", package_id, 'full')).catch(nothing);
let archive_file = path.join(release_path, 'downloads', package_id, 'full', `${package_id}.tar.gz`);
yield fs.unlinkAsync(archive_file).catch(nothing);
yield archive(archive_file, yield fs.readdirAsync(package_path), package_path);
let archive_checksum = yield caculateSHA256(archive_file);
let checksum_file = path.join(release_path, 'downloads', package_id, 'full', `${package_id}.checksum.txt`);
yield fs.writeFileAsync(checksum_file, archive_checksum);
let size_file = path.join(release_path, 'downloads', package_id, 'full', `${package_id}.size.txt`);
yield fs.writeFileAsync(size_file, (yield fs.statAsync(archive_file)).size.toString());
let link_file = path.join(release_path, 'dist', `${archive_checksum}.tar.gz`);
yield fs.unlinkAsync(link_file).catch(nothing);
yield fs.symlinkAsync(archive_file, link_file);
// 整包的meta4
let metalink = Mustache.render(template, {
name: `${package_id}.tar.gz`,
size: (yield fs.statAsync(archive_file)).size,
hash: archive_checksum
});
yield fs.writeFileAsync(path.join(release_path, "metalinks", `${package_id}.meta4`), metalink);
// TODO: 打近期包
// 打散包
yield fs.mkdirAsync(path.join(release_path, "downloads", package_id, 'sand')).catch(nothing);
let sand_path = path.join(release_path, 'downloads', package_id, 'sand');
// TODO: 保留跟上一个版本相比没改动过的散包文件,无需重复打包
for (let file of yield readdirRecursive(sand_path)) {
yield fs.unlinkAsync(file).catch(nothing);
}
for (let file of files) {
let stat = yield fs.statAsync(path.join(package_path, file));
if (!stat.isDirectory()) {
let archive_file = path.join(release_path, 'downloads', package_id, 'sand', `${file.replace(/\//g, '__')}.tar.gz`);
yield archive(archive_file, [file], package_path);
let checksum_file = path.join(release_path, 'downloads', package_id, 'sand', `${file.replace(/\//g, '__')}.checksum.txt`);
let checksum = yield caculateSHA256(archive_file);
yield fs.writeFileAsync(checksum_file, checksum);
let size_file = path.join(release_path, 'downloads', package_id, 'sand', `${file.replace(/\//g, '__')}.size.txt`);
yield fs.writeFileAsync(size_file, (yield fs.statAsync(archive_file)).size.toString());
let link_file = path.join(release_path, 'dist', `${checksum}.tar.gz`);
yield fs.unlinkAsync(link_file).catch(nothing);
yield fs.symlinkAsync(archive_file, link_file);
}
}
// TODO: 分发
});
}
if (process.argv[2] && process.argv[3]) {
main(process.argv[2], process.argv[3]);
}
else {
console.log(`param: <package> <version>`);
}
//# sourceMappingURL=main.js.map
\ No newline at end of file
{"version":3,"file":"main.js","sourceRoot":"","sources":["main.ts"],"names":[],"mappings":";;;;;;;;;;AAIA,yBAAyB;AACzB,6BAA6B;AAC7B,iCAAiC;AACjC,+CAA+C;AAC/C,qCAAqC;AACrC,yBAAuB;AACvB,sCAAsC;AAEtC,IAAI,QAAQ,CAAC;AACb,IAAI,CAAC;IACD,QAAQ,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAAC;AAC/C,CAAE;AAAA,KAAK,CAAC,CAAC,KAAK,CAA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I,CAAC,IAAI,CAAC,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;gBAClH,MAAM,EAAE,CAAC,cAAc,CAAC,SAAS,EAAE,CAAC,MAAM,EAAE,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAC;gBACvF,IAAI,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,MAAM,EAAE,GAAG,QAAQ,SAAS,CAAC,CAAC;gBACtE,MAAM,EAAE,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;gBAC/C,MAAM,EAAE,CAAC,YAAY,CAAC,YAAY,EAAE,SAAS,CAAC,CAAC;YACnD,CAAC;QACL,CAAC;QAED,WAAW;IAEf,CAAC;CAAA;AAED,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACrC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAA;AAC1C,CAAC;AAAC,IAAI,CAAC,CAAC;IACJ,OAAO,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAA;AAC7C,CAAC"}
\ No newline at end of file
#!/usr/bin/env node
/**
* Created by zh99998 on 2016/12/12.
*/
import * as fs from "fs";
import * as path from "path";
import * as crypto from "crypto";
import * as child_process from "child_process";
import * as Mustache from "mustache";
import "promised-node";
// const vercomp = require('vercomp');
let database;
try {
database = require('/data/apps/data.json');
} catch (error) {
database = {}
}
const release_path = '/data/release';
async function readdirRecursive(_path: string | Buffer): Promise<string[]> {
let files = await fs.readdirAsync(_path);
let result = files;
for (let file of files) {
let child = path.join(_path, file);
let stat = await fs.statAsync(child);
if (stat.isDirectory()) {
result = result.concat((await readdirRecursive(child)).map((_file) => path.join(file, _file)))
}
}
return result;
}
function caculateSHA256(file: string): Promise<string> {
return new Promise((resolve, reject) => {
let input = fs.createReadStream(file);
const hash = crypto.createHash("sha256");
hash.on("error", (error: Error) => {
reject(error)
});
input.on("error", (error: Error) => {
reject(error);
});
hash.on('readable', () => {
let data = hash.read();
if (data) {
resolve((<Buffer>data).toString("hex"));
}
});
input.pipe(hash);
});
}
function archive(archive: string, files: string[], directory: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
let child = child_process.spawn("tar", ["-zcvf", archive, '-C', directory].concat(files), {stdio: 'inherit'});
child.on('exit', (code) => {
if (code == 0) {
resolve()
} else {
reject(code);
}
});
child.on('error', (error) => {
reject(error);
})
});
}
function nothing() {
}
async function main(package_id, version) {
console.log(`package ${package_id} version ${version}`);
await fs.mkdirAsync(release_path).catch(nothing);
await fs.mkdirAsync(path.join(release_path, "downloads")).catch(nothing);
await fs.mkdirAsync(path.join(release_path, "metalinks")).catch(nothing);
await fs.mkdirAsync(path.join(release_path, "checksums")).catch(nothing);
await fs.mkdirAsync(path.join(release_path, "dist")).catch(nothing);
await fs.unlinkAsync(path.join(release_path, "downloads", `${package_id}.tar.gz`)).catch(nothing);
const template = await fs.readFileAsync("template.meta4", {encoding: 'utf8'});
// 列目录
let package_path = path.join('/data/apps', package_id);
let files = await readdirRecursive(package_path);
files.unshift('.');
// 计算checksum
let checksums = new Map<string, string>();
for (let file of files) {
let stat = await fs.statAsync(path.join(package_path, file));
if (stat.isDirectory()) {
checksums.set(file, '')
} else {
checksums.set(file, await caculateSHA256(path.join(package_path, file)))
}
}
// 生成checksum文件
let checksum = Array.from(checksums).map(([file, checksum]) => `${checksum} ${file}`).join("\n");
fs.writeFileAsync(path.join(release_path, "checksums", package_id), checksum);
// 打整包
await fs.mkdirAsync(path.join(release_path, "downloads", package_id)).catch(nothing);
await fs.mkdirAsync(path.join(release_path, "downloads", package_id, 'full')).catch(nothing);
let archive_file = path.join(release_path, 'downloads', package_id, 'full', `${package_id}.tar.gz`);
await fs.unlinkAsync(archive_file).catch(nothing);
await archive(archive_file, await fs.readdirAsync(package_path), package_path);
let archive_checksum = await caculateSHA256(archive_file);
let checksum_file = path.join(release_path, 'downloads', package_id, 'full', `${package_id}.checksum.txt`);
await fs.writeFileAsync(checksum_file, archive_checksum);
let size_file = path.join(release_path, 'downloads', package_id, 'full', `${package_id}.size.txt`);
await fs.writeFileAsync(size_file, (await fs.statAsync(archive_file)).size.toString());
let link_file = path.join(release_path, 'dist', `${archive_checksum}.tar.gz`);
await fs.unlinkAsync(link_file).catch(nothing);
await fs.symlinkAsync(path.relative(path.join(release_path, 'dist'), archive_file), link_file);
// 整包的meta4
let metalink = Mustache.render(template, {
name: `${package_id}.tar.gz`,
size: (await fs.statAsync(archive_file)).size,
hash: archive_checksum
});
await fs.writeFileAsync(path.join(release_path, "metalinks", `${package_id}.meta4`), metalink);
// TODO: 打近期包
// 打散包
await fs.mkdirAsync(path.join(release_path, "downloads", package_id, 'sand')).catch(nothing);
let sand_path = path.join(release_path, 'downloads', package_id, 'sand');
// TODO: 保留跟上一个版本相比没改动过的散包文件,无需重复打包
for (let file of await readdirRecursive(sand_path)) {
await fs.unlinkAsync(file).catch(nothing);
}
for (let file of files) {
let stat = await fs.statAsync(path.join(package_path, file));
if (!stat.isDirectory()) {
let archive_file = path.join(release_path, 'downloads', package_id, 'sand', `${file.replace(/\//g, '__')}.tar.gz`);
await archive(archive_file, [file], package_path);
let checksum_file = path.join(release_path, 'downloads', package_id, 'sand', `${file.replace(/\//g, '__')}.checksum.txt`);
let checksum = await caculateSHA256(archive_file);
await fs.writeFileAsync(checksum_file, checksum);
let size_file = path.join(release_path, 'downloads', package_id, 'sand', `${file.replace(/\//g, '__')}.size.txt`);
await fs.writeFileAsync(size_file, (await fs.statAsync(archive_file)).size.toString());
let link_file = path.join(release_path, 'dist', `${checksum}.tar.gz`);
await fs.unlinkAsync(link_file).catch(nothing);
await fs.symlinkAsync(path.relative(path.join(release_path, 'dist'), archive_file), link_file);
}
}
// TODO: 分发
}
if (process.argv[2] && process.argv[3]) {
main(process.argv[2], process.argv[3])
} else {
console.log(`param: <package> <version>`)
}
# Installation
> `npm install --save @types/mustache`
# Summary
This package contains type definitions for Mustache 0.8.2 (https://github.com/janl/mustache.js).
# Details
Files were exported from https://www.github.com/DefinitelyTyped/DefinitelyTyped/tree/types-2.0/mustache
Additional Details
* Last updated: Mon, 19 Sep 2016 17:28:59 GMT
* File structure: Mixed
* Library Dependencies: none
* Module Dependencies: none
* Global values: Mustache
# Credits
These definitions were written by Mark Ashley Bell <https://github.com/markashleybell/>.
// Type definitions for Mustache 0.8.2
// Project: https://github.com/janl/mustache.js
// Definitions by: Mark Ashley Bell <https://github.com/markashleybell/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface MustacheScanner {
string: string;
tail: string;
pos: number;
eos(): boolean;
scan(re: RegExp): string;
scanUntil(re: RegExp): string;
}
interface MustacheContext {
view: any;
parentContext: MustacheContext;
push(view: any): MustacheContext;
lookup(name: string): any;
}
interface MustacheWriter {
(view: any): string;
clearCache(): void;
parse(template: string, tags?: any): any;
render(template: string, view: any, partials: any): string;
renderTokens(tokens: string[], context: MustacheContext, partials: any, originalTemplate: any): string;
}
interface MustacheStatic {
name: string;
version: string;
tags: string;
Scanner: MustacheScanner;
Context: MustacheContext;
Writer: MustacheWriter;
escape: any;
clearCache(): MustacheWriter;
parse(template: string, tags?: any): any;
render(template: string, view: any, partials?: any): string;
to_html(template: string, view: any, partials?: any, send?: any): any;
}
declare var Mustache: MustacheStatic;
declare module 'mustache' {
export = Mustache;
}
{
"_args": [
[
{
"raw": "@types/mustache",
"scope": "@types",
"escapedName": "@types%2fmustache",
"name": "@types/mustache",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"/Users/zh99998/mycard-console-lazy"
]
],
"_from": "@types/mustache@latest",
"_id": "@types/mustache@0.8.29",
"_inCache": true,
"_location": "/@types/mustache",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/mustache-0.8.29.tgz_1474307704885_0.8454168690368533"
},
"_npmUser": {
"name": "types",
"email": "ts-npm-types@microsoft.com"
},
"_phantomChildren": {},
"_requested": {
"raw": "@types/mustache",
"scope": "@types",
"escapedName": "@types%2fmustache",
"name": "@types/mustache",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/@types/mustache/-/mustache-0.8.29.tgz",
"_shasum": "7a6f13e8f23ff5bcbaaec484888400b2a4427b41",
"_shrinkwrap": null,
"_spec": "@types/mustache",
"_where": "/Users/zh99998/mycard-console-lazy",
"author": {
"name": "Mark Ashley Bell",
"email": "https://github.com/markashleybell/"
},
"dependencies": {},
"description": "TypeScript definitions for Mustache 0.8.2",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "7a6f13e8f23ff5bcbaaec484888400b2a4427b41",
"tarball": "https://registry.npmjs.org/@types/mustache/-/mustache-0.8.29.tgz"
},
"license": "MIT",
"main": "",
"maintainers": [
{
"name": "types",
"email": "ryan.cavanaugh@microsoft.com"
}
],
"name": "@types/mustache",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "https://www.github.com/DefinitelyTyped/DefinitelyTyped.git"
},
"scripts": {},
"typesPublisherContentHash": "47c97f7d46db91b2cb16977c9a8476e8f689c1ba632dcbad086d70f7af68f9bb",
"typings": "index.d.ts",
"version": "0.8.29"
}
{
"authors": "Mark Ashley Bell <https://github.com/markashleybell/>",
"definitionFilename": "index.d.ts",
"libraryDependencies": [],
"moduleDependencies": [],
"libraryMajorVersion": "0",
"libraryMinorVersion": "8",
"libraryName": "Mustache 0.8.2",
"typingsPackageName": "mustache",
"projectName": "https://github.com/janl/mustache.js",
"sourceRepoURL": "https://www.github.com/DefinitelyTyped/DefinitelyTyped",
"sourceBranch": "types-2.0",
"kind": "Mixed",
"globals": [
"Mustache"
],
"declaredModules": [
"mustache"
],
"files": [
"index.d.ts"
],
"hasPackageJson": false,
"contentHash": "47c97f7d46db91b2cb16977c9a8476e8f689c1ba632dcbad086d70f7af68f9bb"
}
\ No newline at end of file
# Installation
> `npm install --save @types/node`
# Summary
This package contains type definitions for Node.js v6.x (http://nodejs.org/).
# Details
Files were exported from https://www.github.com/DefinitelyTyped/DefinitelyTyped/tree/types-2.0/node
Additional Details
* Last updated: Wed, 30 Nov 2016 23:08:30 GMT
* File structure: ModuleAugmentation
* Library Dependencies: none
* Module Dependencies: child_process, crypto, events, http, net, readline, stream, tls
* Global values: Buffer, NodeJS, SlowBuffer, __dirname, __filename, clearImmediate, clearInterval, clearTimeout, console, exports, global, module, process, require, setImmediate, setInterval, setTimeout
# Credits
These definitions were written by Microsoft TypeScript <http://typescriptlang.org>, DefinitelyTyped <https://github.com/DefinitelyTyped/DefinitelyTyped>.
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"_args": [
[
{
"raw": "@types/node",
"scope": "@types",
"escapedName": "@types%2fnode",
"name": "@types/node",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"/Users/zh99998/mycard-console-lazy"
]
],
"_from": "@types/node@latest",
"_id": "@types/node@0.0.2",
"_inCache": true,
"_location": "/@types/node",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/node-0.0.2.tgz_1480547365734_0.3248825690243393"
},
"_npmUser": {
"name": "types",
"email": "ts-npm-types@microsoft.com"
},
"_phantomChildren": {},
"_requested": {
"raw": "@types/node",
"scope": "@types",
"escapedName": "@types%2fnode",
"name": "@types/node",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/@types/node/-/node-0.0.2.tgz",
"_shasum": "0da4934902fbf68a97a0f53204a35ad2224917bc",
"_shrinkwrap": null,
"_spec": "@types/node",
"_where": "/Users/zh99998/mycard-console-lazy",
"author": {
"name": "Microsoft TypeScript",
"email": "http://typescriptlang.org"
},
"dependencies": {},
"description": "TypeScript definitions for Node.js v6.x",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "0da4934902fbf68a97a0f53204a35ad2224917bc",
"tarball": "https://registry.npmjs.org/@types/node/-/node-0.0.2.tgz"
},
"license": "MIT",
"main": "",
"maintainers": [
{
"name": "types",
"email": "ryan.cavanaugh@microsoft.com"
}
],
"name": "@types/node",
"optionalDependencies": {},
"peerDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "https://www.github.com/DefinitelyTyped/DefinitelyTyped.git"
},
"scripts": {},
"typesPublisherContentHash": "1f5ba7b7576eacddad88c13a4b358e5d26c1ab78278672cdb52e00908cc6757f",
"version": "0.0.2"
}
{
"authors": "Microsoft TypeScript <http://typescriptlang.org>, DefinitelyTyped <https://github.com/DefinitelyTyped/DefinitelyTyped>",
"libraryDependencies": [],
"moduleDependencies": [
"child_process",
"crypto",
"events",
"http",
"net",
"readline",
"stream",
"tls"
],
"libraryMajorVersion": 0,
"libraryMinorVersion": 0,
"libraryName": "Node.js v6.x",
"typingsPackageName": "node",
"projectName": "http://nodejs.org/",
"sourceRepoURL": "https://www.github.com/DefinitelyTyped/DefinitelyTyped",
"sourceBranch": "types-2.0",
"kind": "ModuleAugmentation",
"globals": [
"Buffer",
"NodeJS",
"SlowBuffer",
"__dirname",
"__filename",
"clearImmediate",
"clearInterval",
"clearTimeout",
"console",
"exports",
"global",
"module",
"process",
"require",
"setImmediate",
"setInterval",
"setTimeout"
],
"declaredModules": [
"buffer",
"querystring",
"events",
"http",
"cluster",
"zlib",
"os",
"https",
"punycode",
"repl",
"readline",
"vm",
"child_process",
"url",
"dns",
"net",
"dgram",
"fs",
"path",
"string_decoder",
"tls",
"crypto",
"stream",
"util",
"assert",
"tty",
"domain",
"constants",
"process",
"v8",
"timers",
"console"
],
"files": [
"index.d.ts"
],
"hasPackageJson": false,
"contentHash": "1f5ba7b7576eacddad88c13a4b358e5d26c1ab78278672cdb52e00908cc6757f"
}
\ No newline at end of file
This diff is collapsed.
The MIT License
Copyright (c) 2009 Chris Wanstrath (Ruby)
Copyright (c) 2010-2014 Jan Lehnardt (JavaScript)
Copyright (c) 2010-2015 The mustache.js community
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
This diff is collapsed.
#!/usr/bin/env node
var fs = require('fs'),
path = require('path');
var Mustache = require('..');
var pkg = require('../package');
var partials = {};
var partialsPaths = [];
var partialArgIndex = -1;
while ((partialArgIndex = process.argv.indexOf('-p')) > -1) {
partialsPaths.push(process.argv.splice(partialArgIndex, 2)[1]);
}
var viewArg = process.argv[2];
var templateArg = process.argv[3];
var outputArg = process.argv[4];
if (hasVersionArg()) {
return console.log(pkg.version);
}
if (!templateArg || !viewArg) {
console.error('Syntax: mustache <view> <template> [output]');
process.exit(1);
}
run(readPartials, readView, readTemplate, render, toStdout);
/**
* Runs a list of functions as a waterfall.
* Functions are runned one after the other in order, providing each
* function the returned values of all the previously invoked functions.
* Each function is expected to exit the process if an error occurs.
*/
function run (/*args*/) {
var values = [];
var fns = Array.prototype.slice.call(arguments);
function invokeNextFn (val) {
values.unshift(val);
if (fns.length === 0) return;
invoke(fns.shift());
}
function invoke (fn) {
fn.apply(null, [invokeNextFn].concat(values));
}
invoke(fns.shift());
}
function readView (cb) {
var view = isStdin(viewArg) ? process.openStdin() : fs.createReadStream(viewArg);
streamToStr(view, function onDone (str) {
cb(parseView(str));
});
}
function parseView (str) {
try {
return JSON.parse(str);
} catch (ex) {
console.error(
'Shooot, could not parse view as JSON.\n' +
'Tips: functions are not valid JSON and keys / values must be surround with double quotes.\n\n' +
ex.stack);
process.exit(1);
}
}
function readPartials (cb) {
if (!partialsPaths.length) return cb();
var partialPath = partialsPaths.pop();
var partial = fs.createReadStream(partialPath);
streamToStr(partial, function onDone (str) {
partials[getPartialName(partialPath)] = str;
readPartials(cb);
});
}
function readTemplate (cb) {
var template = fs.createReadStream(templateArg);
streamToStr(template, cb);
}
function render (cb, templateStr, jsonView) {
cb(Mustache.render(templateStr, jsonView, partials));
}
function toStdout (cb, str) {
if (outputArg) {
cb(fs.writeFileSync(outputArg, str));
} else {
cb(process.stdout.write(str));
}
}
function streamToStr (stream, cb) {
var data = '';
stream.on('data', function onData (chunk) {
data += chunk;
}).once('end', function onEnd () {
cb(data.toString());
}).on('error', function onError (err) {
if (wasNotFound(err)) {
console.error('Could not find file:', err.path);
} else {
console.error('Error while reading file:', err.message);
}
process.exit(1);
});
}
function isStdin (view) {
return view === '-';
}
function wasNotFound (err) {
return err.code && err.code === 'ENOENT';
}
function hasVersionArg () {
return ['--version', '-v'].some(function matchInArgs (opt) {
return process.argv.indexOf(opt) > -1;
});
}
function getPartialName (filename) {
return path.basename(filename, '.mustache');
}
This diff is collapsed.
(function defineMustache(global,factory){if(typeof exports==="object"&&exports&&typeof exports.nodeName!=="string"){factory(exports)}else if(typeof define==="function"&&define.amd){define(["exports"],factory)}else{global.Mustache={};factory(global.Mustache)}})(this,function mustacheFactory(mustache){var objectToString=Object.prototype.toString;var isArray=Array.isArray||function isArrayPolyfill(object){return objectToString.call(object)==="[object Array]"};function isFunction(object){return typeof object==="function"}function typeStr(obj){return isArray(obj)?"array":typeof obj}function escapeRegExp(string){return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function hasProperty(obj,propName){return obj!=null&&typeof obj==="object"&&propName in obj}var regExpTest=RegExp.prototype.test;function testRegExp(re,string){return regExpTest.call(re,string)}var nonSpaceRe=/\S/;function isWhitespace(string){return!testRegExp(nonSpaceRe,string)}var entityMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function escapeHtml(string){return String(string).replace(/[&<>"'`=\/]/g,function fromEntityMap(s){return entityMap[s]})}var whiteRe=/\s*/;var spaceRe=/\s+/;var equalsRe=/\s*=/;var curlyRe=/\s*\}/;var tagRe=/#|\^|\/|>|\{|&|=|!/;function parseTemplate(template,tags){if(!template)return[];var sections=[];var tokens=[];var spaces=[];var hasTag=false;var nonSpace=false;function stripSpace(){if(hasTag&&!nonSpace){while(spaces.length)delete tokens[spaces.pop()]}else{spaces=[]}hasTag=false;nonSpace=false}var openingTagRe,closingTagRe,closingCurlyRe;function compileTags(tagsToCompile){if(typeof tagsToCompile==="string")tagsToCompile=tagsToCompile.split(spaceRe,2);if(!isArray(tagsToCompile)||tagsToCompile.length!==2)throw new Error("Invalid tags: "+tagsToCompile);openingTagRe=new RegExp(escapeRegExp(tagsToCompile[0])+"\\s*");closingTagRe=new RegExp("\\s*"+escapeRegExp(tagsToCompile[1]));closingCurlyRe=new RegExp("\\s*"+escapeRegExp("}"+tagsToCompile[1]))}compileTags(tags||mustache.tags);var scanner=new Scanner(template);var start,type,value,chr,token,openSection;while(!scanner.eos()){start=scanner.pos;value=scanner.scanUntil(openingTagRe);if(value){for(var i=0,valueLength=value.length;i<valueLength;++i){chr=value.charAt(i);if(isWhitespace(chr)){spaces.push(tokens.length)}else{nonSpace=true}tokens.push(["text",chr,start,start+1]);start+=1;if(chr==="\n")stripSpace()}}if(!scanner.scan(openingTagRe))break;hasTag=true;type=scanner.scan(tagRe)||"name";scanner.scan(whiteRe);if(type==="="){value=scanner.scanUntil(equalsRe);scanner.scan(equalsRe);scanner.scanUntil(closingTagRe)}else if(type==="{"){value=scanner.scanUntil(closingCurlyRe);scanner.scan(curlyRe);scanner.scanUntil(closingTagRe);type="&"}else{value=scanner.scanUntil(closingTagRe)}if(!scanner.scan(closingTagRe))throw new Error("Unclosed tag at "+scanner.pos);token=[type,value,start,scanner.pos];tokens.push(token);if(type==="#"||type==="^"){sections.push(token)}else if(type==="/"){openSection=sections.pop();if(!openSection)throw new Error('Unopened section "'+value+'" at '+start);if(openSection[1]!==value)throw new Error('Unclosed section "'+openSection[1]+'" at '+start)}else if(type==="name"||type==="{"||type==="&"){nonSpace=true}else if(type==="="){compileTags(value)}}openSection=sections.pop();if(openSection)throw new Error('Unclosed section "'+openSection[1]+'" at '+scanner.pos);return nestTokens(squashTokens(tokens))}function squashTokens(tokens){var squashedTokens=[];var token,lastToken;for(var i=0,numTokens=tokens.length;i<numTokens;++i){token=tokens[i];if(token){if(token[0]==="text"&&lastToken&&lastToken[0]==="text"){lastToken[1]+=token[1];lastToken[3]=token[3]}else{squashedTokens.push(token);lastToken=token}}}return squashedTokens}function nestTokens(tokens){var nestedTokens=[];var collector=nestedTokens;var sections=[];var token,section;for(var i=0,numTokens=tokens.length;i<numTokens;++i){token=tokens[i];switch(token[0]){case"#":case"^":collector.push(token);sections.push(token);collector=token[4]=[];break;case"/":section=sections.pop();section[5]=token[2];collector=sections.length>0?sections[sections.length-1][4]:nestedTokens;break;default:collector.push(token)}}return nestedTokens}function Scanner(string){this.string=string;this.tail=string;this.pos=0}Scanner.prototype.eos=function eos(){return this.tail===""};Scanner.prototype.scan=function scan(re){var match=this.tail.match(re);if(!match||match.index!==0)return"";var string=match[0];this.tail=this.tail.substring(string.length);this.pos+=string.length;return string};Scanner.prototype.scanUntil=function scanUntil(re){var index=this.tail.search(re),match;switch(index){case-1:match=this.tail;this.tail="";break;case 0:match="";break;default:match=this.tail.substring(0,index);this.tail=this.tail.substring(index)}this.pos+=match.length;return match};function Context(view,parentContext){this.view=view;this.cache={".":this.view};this.parent=parentContext}Context.prototype.push=function push(view){return new Context(view,this)};Context.prototype.lookup=function lookup(name){var cache=this.cache;var value;if(cache.hasOwnProperty(name)){value=cache[name]}else{var context=this,names,index,lookupHit=false;while(context){if(name.indexOf(".")>0){value=context.view;names=name.split(".");index=0;while(value!=null&&index<names.length){if(index===names.length-1)lookupHit=hasProperty(value,names[index]);value=value[names[index++]]}}else{value=context.view[name];lookupHit=hasProperty(context.view,name)}if(lookupHit)break;context=context.parent}cache[name]=value}if(isFunction(value))value=value.call(this.view);return value};function Writer(){this.cache={}}Writer.prototype.clearCache=function clearCache(){this.cache={}};Writer.prototype.parse=function parse(template,tags){var cache=this.cache;var tokens=cache[template];if(tokens==null)tokens=cache[template]=parseTemplate(template,tags);return tokens};Writer.prototype.render=function render(template,view,partials){var tokens=this.parse(template);var context=view instanceof Context?view:new Context(view);return this.renderTokens(tokens,context,partials,template)};Writer.prototype.renderTokens=function renderTokens(tokens,context,partials,originalTemplate){var buffer="";var token,symbol,value;for(var i=0,numTokens=tokens.length;i<numTokens;++i){value=undefined;token=tokens[i];symbol=token[0];if(symbol==="#")value=this.renderSection(token,context,partials,originalTemplate);else if(symbol==="^")value=this.renderInverted(token,context,partials,originalTemplate);else if(symbol===">")value=this.renderPartial(token,context,partials,originalTemplate);else if(symbol==="&")value=this.unescapedValue(token,context);else if(symbol==="name")value=this.escapedValue(token,context);else if(symbol==="text")value=this.rawValue(token);if(value!==undefined)buffer+=value}return buffer};Writer.prototype.renderSection=function renderSection(token,context,partials,originalTemplate){var self=this;var buffer="";var value=context.lookup(token[1]);function subRender(template){return self.render(template,context,partials)}if(!value)return;if(isArray(value)){for(var j=0,valueLength=value.length;j<valueLength;++j){buffer+=this.renderTokens(token[4],context.push(value[j]),partials,originalTemplate)}}else if(typeof value==="object"||typeof value==="string"||typeof value==="number"){buffer+=this.renderTokens(token[4],context.push(value),partials,originalTemplate)}else if(isFunction(value)){if(typeof originalTemplate!=="string")throw new Error("Cannot use higher-order sections without the original template");value=value.call(context.view,originalTemplate.slice(token[3],token[5]),subRender);if(value!=null)buffer+=value}else{buffer+=this.renderTokens(token[4],context,partials,originalTemplate)}return buffer};Writer.prototype.renderInverted=function renderInverted(token,context,partials,originalTemplate){var value=context.lookup(token[1]);if(!value||isArray(value)&&value.length===0)return this.renderTokens(token[4],context,partials,originalTemplate)};Writer.prototype.renderPartial=function renderPartial(token,context,partials){if(!partials)return;var value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null)return this.renderTokens(this.parse(value),context,partials,value)};Writer.prototype.unescapedValue=function unescapedValue(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function escapedValue(token,context){var value=context.lookup(token[1]);if(value!=null)return mustache.escape(value)};Writer.prototype.rawValue=function rawValue(token){return token[1]};mustache.name="mustache.js";mustache.version="2.3.0";mustache.tags=["{{","}}"];var defaultWriter=new Writer;mustache.clearCache=function clearCache(){return defaultWriter.clearCache()};mustache.parse=function parse(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function render(template,view,partials){if(typeof template!=="string"){throw new TypeError('Invalid template! Template should be a "string" '+'but "'+typeStr(template)+'" was given as the first '+"argument for mustache#render(template, view, partials)")}return defaultWriter.render(template,view,partials)};mustache.to_html=function to_html(template,view,partials,send){var result=mustache.render(template,view,partials);if(isFunction(send)){send(result)}else{return result}};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;return mustache});
{
"_args": [
[
{
"raw": "mustache",
"scope": null,
"escapedName": "mustache",
"name": "mustache",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"/Users/zh99998/mycard-console-lazy"
]
],
"_from": "mustache@latest",
"_id": "mustache@2.3.0",
"_inCache": true,
"_location": "/mustache",
"_nodeVersion": "7.0.0",
"_npmOperationalInternal": {
"host": "packages-18-east.internal.npmjs.com",
"tmp": "tmp/mustache-2.3.0.tgz_1478622318106_0.5297125231008977"
},
"_npmUser": {
"name": "dasilvacontin",
"email": "dasilvacontin@gmail.com"
},
"_npmVersion": "3.10.8",
"_phantomChildren": {},
"_requested": {
"raw": "mustache",
"scope": null,
"escapedName": "mustache",
"name": "mustache",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/mustache/-/mustache-2.3.0.tgz",
"_shasum": "4028f7778b17708a489930a6e52ac3bca0da41d0",
"_shrinkwrap": null,
"_spec": "mustache",
"_where": "/Users/zh99998/mycard-console-lazy",
"author": {
"name": "mustache.js Authors",
"email": "http://github.com/janl/mustache.js"
},
"bin": {
"mustache": "./bin/mustache"
},
"bugs": {
"url": "https://github.com/janl/mustache.js/issues"
},
"dependencies": {},
"description": "Logic-less {{mustache}} templates with JavaScript",
"devDependencies": {
"chai": "^3.4.0",
"eslint": "^2.5.1",
"mocha": "^3.0.2",
"zuul": "^3.11.0"
},
"directories": {},
"dist": {
"shasum": "4028f7778b17708a489930a6e52ac3bca0da41d0",
"tarball": "https://registry.npmjs.org/mustache/-/mustache-2.3.0.tgz"
},
"engines": {
"npm": ">=1.4.0"
},
"files": [
"mustache.js",
"mustache.min.js",
"bin",
"wrappers",
"LICENSE"
],
"gitHead": "23beb3a8805c9a857e3ea777431481599fab503e",
"greenkeeper": {
"ignore": [
"eslint"
]
},
"homepage": "https://github.com/janl/mustache.js",
"keywords": [
"mustache",
"template",
"templates",
"ejs"
],
"license": "MIT",
"main": "./mustache.js",
"maintainers": [
{
"name": "dasilvacontin",
"email": "dasilvacontin@gmail.com"
},
{
"name": "flipp",
"email": "johphi@gmail.com"
},
{
"name": "jan",
"email": "jan@apache.org"
},
{
"name": "mjackson",
"email": "mjijackson@gmail.com"
},
{
"name": "nathan",
"email": "nrstott@gmail.com"
}
],
"name": "mustache",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/janl/mustache.js.git"
},
"scripts": {
"pre-test-browser": "node test/create-browser-suite.js",
"pretest": "eslint mustache.js bin/mustache",
"test": "mocha --reporter spec test/*-test.js",
"test-browser": "npm run pre-test-browser && zuul -- test/context-test.js test/parse-test.js test/scanner-test.js test/render-test-browser.js",
"test-browser-local": "npm run pre-test-browser && zuul --local 8080 -- test/context-test.js test/scanner-test.js test/parse-test.js test/render-test-browser.js",
"test-render": "mocha --reporter spec test/render-test"
},
"spm": {
"main": "mustache.js",
"ignore": [
"test",
"wrappers"
]
},
"version": "2.3.0",
"volo": {
"url": "https://raw.github.com/janl/mustache.js/{version}/mustache.js"
}
}
dojox.mustache = dojo.hitch(Mustache, "render");
})();
\ No newline at end of file
/*
Shameless port of a shameless port
@defunkt => @janl => @aq => @voodootikigod
See http://github.com/defunkt/mustache for more info.
*/
dojo.provide("dojox.mustache._base");
(function(){
$.mustache = function (template, view, partials) {
return Mustache.render(template, view, partials);
};
$.fn.mustache = function (view, partials) {
return $(this).map(function (i, elm) {
var template = $.trim($(elm).html());
var output = $.mustache(template, view, partials);
return $(output).get();
});
};
})(jQuery);
/*
Shameless port of a shameless port
@defunkt => @janl => @aq
See http://github.com/defunkt/mustache for more info.
*/
;(function($) {
Object.implement('mustache', function(view, partials){
return Mustache.render(view, this, partials);
});
})();
/**
* Above is the original mustache code.
*/
// EXPOSE qooxdoo variant
qx.bom.Template.version = this.Mustache.version;
qx.bom.Template.render = this.Mustache.render;
}).call({});
\ No newline at end of file
/* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2004-2012 1&1 Internet AG, Germany, http://www.1und1.de
License:
LGPL: http://www.gnu.org/licenses/lgpl.html
EPL: http://www.eclipse.org/org/documents/epl-v10.php
See the LICENSE file in the project's top-level directory for details.
Authors:
* Martin Wittemann (martinwittemann)
======================================================================
This class contains code based on the following work:
* Mustache.js version 0.8.0
Code:
https://github.com/janl/mustache.js
Copyright:
(c) 2009 Chris Wanstrath (Ruby)
(c) 2010 Jan Lehnardt (JavaScript)
License:
MIT: http://www.opensource.org/licenses/mit-license.php
----------------------------------------------------------------------
Copyright (c) 2009 Chris Wanstrath (Ruby)
Copyright (c) 2010 Jan Lehnardt (JavaScript)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
************************************************************************ */
/**
* The is a template class which can be used for HTML templating. In fact,
* this is a wrapper for mustache.js which is a "framework-agnostic way to
* render logic-free views".
*
* Here is a basic example how to use it:
* Template:
* <pre class="javascript">
* var template = "Hi, my name is {{name}}!";
* var view = {name: "qooxdoo"};
* qx.bom.Template.render(template, view);
* // return "Hi, my name is qooxdoo!"
* </pre>
*
* For further details, please visit the mustache.js documentation here:
* https://github.com/janl/mustache.js/blob/master/README.md
*
* @ignore(module)
*/
qx.Bootstrap.define("qx.bom.Template", {
statics : {
/** Contains the mustache.js version. */
version: null,
/**
* Original and only template method of mustache.js. For further
* documentation, please visit https://github.com/janl/mustache.js
*
* @signature function(template, view, partials)
* @param template {String} The String containing the template.
* @param view {Object} The object holding the data to render.
* @param partials {Object} Object holding parts of a template.
* @return {String} The parsed template.
*/
render: null,
/**
* Combines {@link #render} and {@link #get}. Input is equal to {@link #render}
* and output is equal to {@link #get}. The advantage over {@link #get}
* is that you don't need a HTML template but can use a template
* string and still get a DOM element. Keep in mind that templates
* can only have one root element.
*
* @param template {String} The String containing the template.
* @param view {Object} The object holding the data to render.
* @param partials {Object} Object holding parts of a template.
* @return {Element} A DOM element holding the parsed template data.
*/
renderToNode : function(template, view, partials) {
var renderedTmpl = this.render(template, view, partials);
return this._createNodeFromTemplate(renderedTmpl);
},
/**
* Helper method which provides you with a direct access to templates
* stored as HTML in the DOM. The DOM node with the given ID will be used
* as a template, parsed and a new DOM node will be returned containing the
* parsed data. Keep in mind to have only one root DOM element in the the
* template.
* Additionally, you should not put the template into a regular, hidden
* DOM element because the template may not be valid HTML due to the containing
* mustache tags. We suggest to put it into a script tag with the type
* <code>text/template</code>.
*
* @param id {String} The id of the HTML template in the DOM.
* @param view {Object} The object holding the data to render.
* @param partials {Object} Object holding parts of a template.
* @return {Element} A DOM element holding the parsed template data.
*/
get : function(id, view, partials) {
// get the content stored in the DOM
var template = document.getElementById(id);
return this.renderToNode(template.innerHTML, view, partials);
},
/**
* Accepts a parsed template and returns a (potentially nested) node.
*
* @param template {String} The String containing the template.
* @return {Element} A DOM element holding the parsed template data.
*/
_createNodeFromTemplate : function(template) {
// template is text only (no html elems) so use text node
if (template.search(/<|>/) === -1) {
return document.createTextNode(template);
}
// template has html elems so convert string into DOM nodes
var helper = qx.dom.Element.create("div");
helper.innerHTML = template;
return helper.children[0];
}
}
});
(function() {
// prevent using CommonJS exports object,
// by shadowing global exports object
var exports;
// prevent using AMD compatible loader,
// by shadowing global define function
var define;
/**
* Below is the original mustache.js code. Snapshot date is mentioned in
* the head of this file.
* @ignore(exports)
* @ignore(define.*)
* @ignore(module.*)
* @lint ignoreNoLoopBlock()
*/
Y.mustache = Mustache.render;
}, "0");
declare module "fs" {
/**
* Asynchronous rename.
* @param oldPath
* @param newPath
* @param callback No arguments other than a possible exception are given to the completion callback.
*/
export function renameAsync(oldPath: string, newPath: string): Promise<void>;
export function truncateAsync(path: string | Buffer, len?: number): Promise<void>;
export function ftruncateAsync(fd: number, len?: number): Promise<void>;
export function chownAsync(path: string | Buffer, uid: number, gid: number): Promise<void>;
export function fchownAsync(fd: number, uid: number, gid: number): Promise<void>;
export function lchownAsync(path: string | Buffer, uid: number, gid: number): Promise<void>;
export function chmodAsync(path: string | Buffer, mode: number): Promise<void>;
export function chmodAsync(path: string | Buffer, mode: string): Promise<void>;
export function fchmodAsync(fd: number, mode: number): Promise<void>;
export function fchmodAsync(fd: number, mode: string): Promise<void>;
export function lchmodAsync(path: string | Buffer, mode: number): Promise<void>;
export function lchmodAsync(path: string | Buffer, mode: string): Promise<void>;
export function statAsync(path: string | Buffer): Promise<Stats>;
export function lstatAsync(path: string | Buffer): Promise<Stats>;
export function fstatAsync(fd: number): Promise<Stats>;
export function linkAsync(srcpath: string | Buffer, dstpath: string | Buffer): Promise<void>;
export function symlinkAsync(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): Promise<void>;
export function readlinkAsync(path: string | Buffer): Promise<string>;
export function realpathAsync(path: string | Buffer, cache?: { [path: string]: string }): Promise<string>;
/*
* Asynchronous unlink - deletes the file specified in {path}
*
* @param path
*/
export function unlinkAsync(path: string | Buffer): Promise<void>;
/*
* Asynchronous rmdir - removes the directory specified in {path}
*
* @param path
*/
export function rmdirAsync(path: string | Buffer): Promise<void>;
/*
* Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777.
*
* @param path
* @param mode
*/
export function mkdirAsync(path: string | Buffer, mode?: number): Promise<void>;
/*
* Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777.
*
* @param path
* @param mode
*/
export function mkdirAsync(path: string | Buffer, mode?: string): Promise<void>;
/*
* Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
*
* @param prefix
* @returns Returns the created folder path.
*/
export function mkdtempAsync(prefix: string): Promise<string>;
export function readdirAsync(path: string | Buffer): Promise<string[]>;
export function closeAsync(fd: number): Promise<void>;
export function openAsync(path: string | Buffer, flags: string | number, mode?: number): Promise<number>;
export function utimesAsync(path: string | Buffer, atime: number, mtime: number): Promise<void>;
export function utimesAsync(path: string | Buffer, atime: Date, mtime: Date): Promise<void>;
export function futimesAsync(fd: number, atime: number, mtime: number): Promise<void>;
export function futimesAsync(fd: number, atime: Date, mtime: Date): Promise<void>;
export function fsyncAsync(fd: number): Promise<void>;
export function writeAsync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): Promise<number>;
export function writeAsync(fd: number, data: any, position?: number, enconding?: string): Promise<number>;
export function readAsync(fd: number, buffer: Buffer, offset: number, length: number, position: number): Promise<number>;
/*
* Asynchronous readFile - Asynchronously reads the entire contents of a file.
*
* @param fileName
* @param encoding
*/
export function readFileAsync(filename: string, encoding: string): Promise<string>;
/*
* Asynchronous readFile - Asynchronously reads the entire contents of a file.
*
* @param fileName
* @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileAsync returns a string; otherwise it returns a Buffer.
*/
export function readFileAsync(filename: string, options: { encoding: string; flag?: string; }): Promise<string>;
/*
* Asynchronous readFile - Asynchronously reads the entire contents of a file.
*
* @param fileName
* @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileAsync returns a string; otherwise it returns a Buffer.
*/
export function readFileAsync(filename: string, options?: { flag?: string; }): Promise<Buffer>;
export function writeFileAsync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): Promise<void>;
export function writeFileAsync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): Promise<void>;
export function appendFileAsync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): Promise<void>;
export function appendFileAsync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): Promise<void>;
export function existsAsync(path: string | Buffer): Promise<boolean>;
}
declare module 'child_process' {
export function execFileAsync(command: string): Buffer;
export function execFileAsync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string;
export function execFileAsync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer;
export function execFileAsync(command: string, options?: ExecFileSyncOptions): Buffer;
export function execFileSAsnc(command: string, args?: string[], options?: ExecFileSyncOptionsWithStringEncoding): string;
export function execFileSyAsc(command: string, args?: string[], options?: ExecFileSyncOptionsWithBufferEncoding): Buffer;
export function execFileSynAs(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer;
}
\ No newline at end of file
/**
* Created by zh99998 on 2016/12/12.
*/
const fs = require('fs');
const promisify = require('es6-promisify');
fs.renameAsync = promisify(fs.rename);
fs.truncateAsync = promisify(fs.truncate)
fs.ftruncateAsync = promisify(fs.ftruncate)
fs.chownAsync = promisify(fs.chown)
fs.fchownAsync = promisify(fs.fchown)
fs.lchownAsync = promisify(fs.lchown)
fs.chmodAsync = promisify(fs.chmod)
fs.chmodAsync = promisify(fs.chmod)
fs.fchmodAsync = promisify(fs.fchmod)
fs.fchmodAsync = promisify(fs.fchmod)
fs.lchmodAsync = promisify(fs.lchmod)
fs.lchmodAsync = promisify(fs.lchmod)
fs.statAsync = promisify(fs.stat)
fs.lstatAsync = promisify(fs.lstat)
fs.fstatAsync = promisify(fs.fstat)
fs.linkAsync = promisify(fs.link)
fs.symlinkAsync = promisify(fs.symlink)
fs.readlinkAsync = promisify(fs.readlink)
fs.realpathAsync = promisify(fs.realpath)
fs.unlinkAsync = promisify(fs.unlink)
fs.rmdirAsync = promisify(fs.rmdir)
fs.mkdirAsync = promisify(fs.mkdir)
fs.mkdirAsync = promisify(fs.mkdir)
fs.mkdtempAsync = promisify(fs.mkdtemp)
fs.readdirAsync = promisify(fs.readdir)
fs.closeAsync = promisify(fs.close)
fs.openAsync = promisify(fs.open)
fs.utimesAsync = promisify(fs.utimes)
fs.utimesAsync = promisify(fs.utimes)
fs.futimesAsync = promisify(fs.futimes)
fs.futimesAsync = promisify(fs.futimes)
fs.fsyncAsync = promisify(fs.fsync)
fs.writeAsync = promisify(fs.write)
fs.writeAsync = promisify(fs.write)
fs.readAsync = promisify(fs.read)
fs.readFileAsync = promisify(fs.readFile)
fs.readFileAsync = promisify(fs.readFile)
fs.readFileAsync = promisify(fs.readFile)
fs.writeFileAsync = promisify(fs.writeFile)
fs.writeFileAsync = promisify(fs.writeFile)
fs.appendFileAsync = promisify(fs.appendFile)
fs.appendFileAsync = promisify(fs.appendFile)
fs.existsAsync = promisify(fs.exists)
fs.mkdirAsync = promisify(fs.mkdir);
fs.accessAsync = promisify(fs.access);
fs.unlinkAsync = promisify(fs.unlink);
# Master
# 4.0.5
* fix require('es6-promise/auto') for Node < 4
# 4.0.4
* fix asap when using https://github.com/Kinvey/titanium-sdk
# 4.0.3
* fix Readme links
# 4.0.2
* fix require('es6-promise/auto');
# 4.0.0
* no longer polyfill automatically, if needed one can still invoke
`require('es6-promise/auto')` directly.
# 3.3.1
* fix links in readme
# 3.3.0
* support polyfil on WebMAF (playstation env)
* fix tampering related bug global `constructor` was referenced by mistake.
* provide TS Typings
* increase compatibliity with sinon.useFakeTimers();
* update build tools (use rollup)
* directly export promise;
# 3.2.2
* IE8: use isArray
* update build dependencies
# 3.2.1
* fix race tampering issue
* use eslint
* fix Promise.all tampering
* remove unused code
* fix issues with NWJS/electron
# 3.2.0
* improve tamper resistence of Promise.all Promise.race and
Promise.prototype.then (note, this isn't complete, but addresses an exception
when used \w core-js, follow up work will address entirely)
* remove spec incompatible then chaining fast-path
* add eslint
* update build deps
# 3.1.2
* fix node detection issues with NWJS/electron
# 3.1.0
* improve performance of Promise.all when it encounters a non-promise input object input
* then/resolve tamper protection
* reduce AST size of promise constructor, to facilitate more inlining
* Update README.md with details about PhantomJS requirement for running tests
* Mangle and compress the minified version
# 3.0.1
* no longer include dist/test in npm releases
# 3.0.0
* use nextTick() instead of setImmediate() to schedule microtasks with node 0.10. Later versions of
nodes are not affected as they were already using nextTick(). Note that using nextTick() might
trigger a depreciation warning on 0.10 as described at https://github.com/cujojs/when/issues/410.
The reason why nextTick() is preferred is that is setImmediate() would schedule a macrotask
instead of a microtask and might result in a different scheduling.
If needed you can revert to the former behavior as follow:
var Promise = require('es6-promise').Promise;
Promise._setScheduler(setImmediate);
# 2.3.0
* #121: Ability to override the internal asap implementation
* #120: Use an ascii character for an apostrophe, for source maps
# 2.2.0
* #116: Expose asap() and a way to override the scheduling mechanism on Promise
* Lock to v0.2.3 of ember-cli
# 2.1.1
* Fix #100 via #105: tell browserify to ignore vertx require
* Fix #101 via #102: "follow thenable state, not own state"
# 2.1.0
* #59: Automatic polyfill. No need to invoke `ES6Promise.polyfill()` anymore.
* ... (see the commit log)
# 2.0.0
* re-sync with RSVP. Many large performance improvements and bugfixes.
# 1.0.0
* first subset of RSVP
Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# ES6-Promise (subset of [rsvp.js](https://github.com/tildeio/rsvp.js)) [![Build Status](https://travis-ci.org/stefanpenner/es6-promise.svg?branch=master)](https://travis-ci.org/stefanpenner/es6-promise)
This is a polyfill of the [ES6 Promise](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-constructor). The implementation is a subset of [rsvp.js](https://github.com/tildeio/rsvp.js) extracted by @jakearchibald, if you're wanting extra features and more debugging options, check out the [full library](https://github.com/tildeio/rsvp.js).
For API details and how to use promises, see the <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">JavaScript Promises HTML5Rocks article</a>.
## Downloads
* [es6-promise 27.86 KB (7.33 KB gzipped)](https://raw.githubusercontent.com/stefanpenner/es6-promise/master/dist/es6-promise.js)
* [es6-promise-auto 27.78 KB (7.3 KB gzipped)](https://raw.githubusercontent.com/stefanpenner/es6-promise/master/dist/es6-promise.auto.js) - Automatically provides/replaces `Promise` if missing or broken.
* [es6-promise-min 6.17 KB (2.4 KB gzipped)](https://raw.githubusercontent.com/stefanpenner/es6-promise/master/dist/es6-promise.min.js)
* [es6-promise-auto-min 6.19 KB (2.4 KB gzipped)](https://raw.githubusercontent.com/stefanpenner/es6-promise/master/dist/es6-promise.auto.min.js) - Minified version of `es6-promise-auto` above.
## Node.js
To install:
```sh
npm install es6-promise
```
To use:
```js
var Promise = require('es6-promise').Promise;
```
## Bower
To install:
```sh
bower install es6-promise --save
```
## Usage in IE<9
`catch` is a reserved word in IE<9, meaning `promise.catch(func)` throws a syntax error. To work around this, you can use a string to access the property as shown in the following example.
However, please remember that such technique is already provided by most common minifiers, making the resulting code safe for old browsers and production:
```js
promise['catch'](function(err) {
// ...
});
```
Or use `.then` instead:
```js
promise.then(undefined, function(err) {
// ...
});
```
## Auto-polyfill
To polyfill the global environment (either in Node or in the browser via CommonJS) use the following code snippet:
```js
require('es6-promise').polyfill();
```
Alternatively
```js
require('es6-promise/auto');
```
Notice that we don't assign the result of `polyfill()` to any variable. The `polyfill()` method will patch the global environment (in this case to the `Promise` name) when called.
## Building & Testing
You will need to have PhantomJS installed globally in order to run the tests.
`npm install -g phantomjs`
* `npm run build` to build
* `npm test` to run tests
* `npm start` to run a build watcher, and webserver to test
* `npm run test:server` for a testem test runner and watching builder
// This file can be required in Browserify and Node.js for automatic polyfill
// To use it: require('es6-promise/auto');
'use strict';
module.exports = require('./').polyfill();
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.ES6Promise=e()}(this,function(){"use strict";function t(t){return"function"==typeof t||"object"==typeof t&&null!==t}function e(t){return"function"==typeof t}function n(t){I=t}function r(t){J=t}function o(){return function(){return process.nextTick(a)}}function i(){return"undefined"!=typeof H?function(){H(a)}:c()}function s(){var t=0,e=new V(a),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}function u(){var t=new MessageChannel;return t.port1.onmessage=a,function(){return t.port2.postMessage(0)}}function c(){var t=setTimeout;return function(){return t(a,1)}}function a(){for(var t=0;t<G;t+=2){var e=$[t],n=$[t+1];e(n),$[t]=void 0,$[t+1]=void 0}G=0}function f(){try{var t=require,e=t("vertx");return H=e.runOnLoop||e.runOnContext,i()}catch(n){return c()}}function l(t,e){var n=arguments,r=this,o=new this.constructor(p);void 0===o[et]&&k(o);var i=r._state;return i?!function(){var t=n[i-1];J(function(){return x(i,o,t,r._result)})}():E(r,o,t,e),o}function h(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var n=new e(p);return g(n,t),n}function p(){}function v(){return new TypeError("You cannot resolve a promise with itself")}function d(){return new TypeError("A promises callback cannot return that same promise.")}function _(t){try{return t.then}catch(e){return it.error=e,it}}function y(t,e,n,r){try{t.call(e,n,r)}catch(o){return o}}function m(t,e,n){J(function(t){var r=!1,o=y(n,e,function(n){r||(r=!0,e!==n?g(t,n):S(t,n))},function(e){r||(r=!0,j(t,e))},"Settle: "+(t._label||" unknown promise"));!r&&o&&(r=!0,j(t,o))},t)}function b(t,e){e._state===rt?S(t,e._result):e._state===ot?j(t,e._result):E(e,void 0,function(e){return g(t,e)},function(e){return j(t,e)})}function w(t,n,r){n.constructor===t.constructor&&r===l&&n.constructor.resolve===h?b(t,n):r===it?j(t,it.error):void 0===r?S(t,n):e(r)?m(t,n,r):S(t,n)}function g(e,n){e===n?j(e,v()):t(n)?w(e,n,_(n)):S(e,n)}function A(t){t._onerror&&t._onerror(t._result),P(t)}function S(t,e){t._state===nt&&(t._result=e,t._state=rt,0!==t._subscribers.length&&J(P,t))}function j(t,e){t._state===nt&&(t._state=ot,t._result=e,J(A,t))}function E(t,e,n,r){var o=t._subscribers,i=o.length;t._onerror=null,o[i]=e,o[i+rt]=n,o[i+ot]=r,0===i&&t._state&&J(P,t)}function P(t){var e=t._subscribers,n=t._state;if(0!==e.length){for(var r=void 0,o=void 0,i=t._result,s=0;s<e.length;s+=3)r=e[s],o=e[s+n],r?x(n,r,o,i):o(i);t._subscribers.length=0}}function T(){this.error=null}function M(t,e){try{return t(e)}catch(n){return st.error=n,st}}function x(t,n,r,o){var i=e(r),s=void 0,u=void 0,c=void 0,a=void 0;if(i){if(s=M(r,o),s===st?(a=!0,u=s.error,s=null):c=!0,n===s)return void j(n,d())}else s=o,c=!0;n._state!==nt||(i&&c?g(n,s):a?j(n,u):t===rt?S(n,s):t===ot&&j(n,s))}function C(t,e){try{e(function(e){g(t,e)},function(e){j(t,e)})}catch(n){j(t,n)}}function O(){return ut++}function k(t){t[et]=ut++,t._state=void 0,t._result=void 0,t._subscribers=[]}function Y(t,e){this._instanceConstructor=t,this.promise=new t(p),this.promise[et]||k(this.promise),B(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?S(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&S(this.promise,this._result))):j(this.promise,q())}function q(){return new Error("Array Methods must be provided an Array")}function F(t){return new Y(this,t).promise}function D(t){var e=this;return new e(B(t)?function(n,r){for(var o=t.length,i=0;i<o;i++)e.resolve(t[i]).then(n,r)}:function(t,e){return e(new TypeError("You must pass an array to race."))})}function K(t){var e=this,n=new e(p);return j(n,t),n}function L(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function N(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function U(t){this[et]=O(),this._result=this._state=void 0,this._subscribers=[],p!==t&&("function"!=typeof t&&L(),this instanceof U?C(this,t):N())}function W(){var t=void 0;if("undefined"!=typeof global)t=global;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var n=t.Promise;if(n){var r=null;try{r=Object.prototype.toString.call(n.resolve())}catch(e){}if("[object Promise]"===r&&!n.cast)return}t.Promise=U}var z=void 0;z=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var B=z,G=0,H=void 0,I=void 0,J=function(t,e){$[G]=t,$[G+1]=e,G+=2,2===G&&(I?I(a):tt())},Q="undefined"!=typeof window?window:void 0,R=Q||{},V=R.MutationObserver||R.WebKitMutationObserver,X="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),Z="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,$=new Array(1e3),tt=void 0;tt=X?o():V?s():Z?u():void 0===Q&&"function"==typeof require?f():c();var et=Math.random().toString(36).substring(16),nt=void 0,rt=1,ot=2,it=new T,st=new T,ut=0;return Y.prototype._enumerate=function(){for(var t=this.length,e=this._input,n=0;this._state===nt&&n<t;n++)this._eachEntry(e[n],n)},Y.prototype._eachEntry=function(t,e){var n=this._instanceConstructor,r=n.resolve;if(r===h){var o=_(t);if(o===l&&t._state!==nt)this._settledAt(t._state,e,t._result);else if("function"!=typeof o)this._remaining--,this._result[e]=t;else if(n===U){var i=new n(p);w(i,t,o),this._willSettleAt(i,e)}else this._willSettleAt(new n(function(e){return e(t)}),e)}else this._willSettleAt(r(t),e)},Y.prototype._settledAt=function(t,e,n){var r=this.promise;r._state===nt&&(this._remaining--,t===ot?j(r,n):this._result[e]=n),0===this._remaining&&S(r,this._result)},Y.prototype._willSettleAt=function(t,e){var n=this;E(t,void 0,function(t){return n._settledAt(rt,e,t)},function(t){return n._settledAt(ot,e,t)})},U.all=F,U.race=D,U.resolve=h,U.reject=K,U._setScheduler=n,U._setAsap=r,U._asap=J,U.prototype={constructor:U,then:l,"catch":function(t){return this.then(null,t)}},U.polyfill=W,U.Promise=U,U}),ES6Promise.polyfill();
\ No newline at end of file
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.ES6Promise=e()}(this,function(){"use strict";function t(t){return"function"==typeof t||"object"==typeof t&&null!==t}function e(t){return"function"==typeof t}function n(t){I=t}function r(t){J=t}function o(){return function(){return process.nextTick(a)}}function i(){return"undefined"!=typeof H?function(){H(a)}:c()}function s(){var t=0,e=new V(a),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}function u(){var t=new MessageChannel;return t.port1.onmessage=a,function(){return t.port2.postMessage(0)}}function c(){var t=setTimeout;return function(){return t(a,1)}}function a(){for(var t=0;t<G;t+=2){var e=$[t],n=$[t+1];e(n),$[t]=void 0,$[t+1]=void 0}G=0}function f(){try{var t=require,e=t("vertx");return H=e.runOnLoop||e.runOnContext,i()}catch(n){return c()}}function l(t,e){var n=arguments,r=this,o=new this.constructor(p);void 0===o[et]&&k(o);var i=r._state;return i?!function(){var t=n[i-1];J(function(){return x(i,o,t,r._result)})}():E(r,o,t,e),o}function h(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var n=new e(p);return g(n,t),n}function p(){}function v(){return new TypeError("You cannot resolve a promise with itself")}function d(){return new TypeError("A promises callback cannot return that same promise.")}function _(t){try{return t.then}catch(e){return it.error=e,it}}function y(t,e,n,r){try{t.call(e,n,r)}catch(o){return o}}function m(t,e,n){J(function(t){var r=!1,o=y(n,e,function(n){r||(r=!0,e!==n?g(t,n):S(t,n))},function(e){r||(r=!0,j(t,e))},"Settle: "+(t._label||" unknown promise"));!r&&o&&(r=!0,j(t,o))},t)}function b(t,e){e._state===rt?S(t,e._result):e._state===ot?j(t,e._result):E(e,void 0,function(e){return g(t,e)},function(e){return j(t,e)})}function w(t,n,r){n.constructor===t.constructor&&r===l&&n.constructor.resolve===h?b(t,n):r===it?j(t,it.error):void 0===r?S(t,n):e(r)?m(t,n,r):S(t,n)}function g(e,n){e===n?j(e,v()):t(n)?w(e,n,_(n)):S(e,n)}function A(t){t._onerror&&t._onerror(t._result),T(t)}function S(t,e){t._state===nt&&(t._result=e,t._state=rt,0!==t._subscribers.length&&J(T,t))}function j(t,e){t._state===nt&&(t._state=ot,t._result=e,J(A,t))}function E(t,e,n,r){var o=t._subscribers,i=o.length;t._onerror=null,o[i]=e,o[i+rt]=n,o[i+ot]=r,0===i&&t._state&&J(T,t)}function T(t){var e=t._subscribers,n=t._state;if(0!==e.length){for(var r=void 0,o=void 0,i=t._result,s=0;s<e.length;s+=3)r=e[s],o=e[s+n],r?x(n,r,o,i):o(i);t._subscribers.length=0}}function M(){this.error=null}function P(t,e){try{return t(e)}catch(n){return st.error=n,st}}function x(t,n,r,o){var i=e(r),s=void 0,u=void 0,c=void 0,a=void 0;if(i){if(s=P(r,o),s===st?(a=!0,u=s.error,s=null):c=!0,n===s)return void j(n,d())}else s=o,c=!0;n._state!==nt||(i&&c?g(n,s):a?j(n,u):t===rt?S(n,s):t===ot&&j(n,s))}function C(t,e){try{e(function(e){g(t,e)},function(e){j(t,e)})}catch(n){j(t,n)}}function O(){return ut++}function k(t){t[et]=ut++,t._state=void 0,t._result=void 0,t._subscribers=[]}function Y(t,e){this._instanceConstructor=t,this.promise=new t(p),this.promise[et]||k(this.promise),B(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?S(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&S(this.promise,this._result))):j(this.promise,q())}function q(){return new Error("Array Methods must be provided an Array")}function F(t){return new Y(this,t).promise}function D(t){var e=this;return new e(B(t)?function(n,r){for(var o=t.length,i=0;i<o;i++)e.resolve(t[i]).then(n,r)}:function(t,e){return e(new TypeError("You must pass an array to race."))})}function K(t){var e=this,n=new e(p);return j(n,t),n}function L(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function N(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function U(t){this[et]=O(),this._result=this._state=void 0,this._subscribers=[],p!==t&&("function"!=typeof t&&L(),this instanceof U?C(this,t):N())}function W(){var t=void 0;if("undefined"!=typeof global)t=global;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var n=t.Promise;if(n){var r=null;try{r=Object.prototype.toString.call(n.resolve())}catch(e){}if("[object Promise]"===r&&!n.cast)return}t.Promise=U}var z=void 0;z=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var B=z,G=0,H=void 0,I=void 0,J=function(t,e){$[G]=t,$[G+1]=e,G+=2,2===G&&(I?I(a):tt())},Q="undefined"!=typeof window?window:void 0,R=Q||{},V=R.MutationObserver||R.WebKitMutationObserver,X="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),Z="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,$=new Array(1e3),tt=void 0;tt=X?o():V?s():Z?u():void 0===Q&&"function"==typeof require?f():c();var et=Math.random().toString(36).substring(16),nt=void 0,rt=1,ot=2,it=new M,st=new M,ut=0;return Y.prototype._enumerate=function(){for(var t=this.length,e=this._input,n=0;this._state===nt&&n<t;n++)this._eachEntry(e[n],n)},Y.prototype._eachEntry=function(t,e){var n=this._instanceConstructor,r=n.resolve;if(r===h){var o=_(t);if(o===l&&t._state!==nt)this._settledAt(t._state,e,t._result);else if("function"!=typeof o)this._remaining--,this._result[e]=t;else if(n===U){var i=new n(p);w(i,t,o),this._willSettleAt(i,e)}else this._willSettleAt(new n(function(e){return e(t)}),e)}else this._willSettleAt(r(t),e)},Y.prototype._settledAt=function(t,e,n){var r=this.promise;r._state===nt&&(this._remaining--,t===ot?j(r,n):this._result[e]=n),0===this._remaining&&S(r,this._result)},Y.prototype._willSettleAt=function(t,e){var n=this;E(t,void 0,function(t){return n._settledAt(rt,e,t)},function(t){return n._settledAt(ot,e,t)})},U.all=F,U.race=D,U.resolve=h,U.reject=K,U._setScheduler=n,U._setAsap=r,U._asap=J,U.prototype={constructor:U,then:l,"catch":function(t){return this.then(null,t)}},U.polyfill=W,U.Promise=U,U});
\ No newline at end of file
export interface Thenable <R> {
then <U> (onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Thenable<U>;
then <U> (onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => void): Thenable<U>;
}
export class Promise <R> implements Thenable <R> {
/**
* If you call resolve in the body of the callback passed to the constructor,
* your promise is fulfilled with result object passed to resolve.
* If you call reject your promise is rejected with the object passed to resolve.
* For consistency and debugging (eg stack traces), obj should be an instanceof Error.
* Any errors thrown in the constructor callback will be implicitly passed to reject().
*/
constructor (callback: (resolve : (value?: R | Thenable<R>) => void, reject: (error?: any) => void) => void);
/**
* onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects.
* Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called.
* Both callbacks have a single parameter , the fulfillment value or rejection reason.
* "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve.
* If an error is thrown in the callback, the returned promise rejects with that error.
*
* @param onFulfilled called when/if "promise" resolves
* @param onRejected called when/if "promise" rejects
*/
then <U> (onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Promise<U>;
then <U> (onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => void): Promise<U>;
/**
* Sugar for promise.then(undefined, onRejected)
*
* @param onRejected called when/if "promise" rejects
*/
catch <U> (onRejected?: (error: any) => U | Thenable<U>): Promise<U>;
/**
* Make a new promise from the thenable.
* A thenable is promise-like in as far as it has a "then" method.
*/
static resolve (): Promise<void>;
static resolve <R> (value: R | Thenable<R>): Promise<R>;
/**
* Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error
*/
static reject <R> (error: any): Promise<R>;
/**
* Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects.
* the array passed to all can be a mixture of promise-like objects and other objects.
* The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value.
*/
static all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>, T6 | Thenable<T6>, T7 | Thenable<T7>, T8 | Thenable<T8>, T9 | Thenable<T9>, T10 | Thenable<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
static all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>, T6 | Thenable<T6>, T7 | Thenable<T7>, T8 | Thenable<T8>, T9 | Thenable<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
static all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>, T6 | Thenable<T6>, T7 | Thenable<T7>, T8 | Thenable<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
static all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>, T6 | Thenable<T6>, T7 | Thenable<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
static all<T1, T2, T3, T4, T5, T6>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>, T6 | Thenable<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
static all<T1, T2, T3, T4, T5>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>, T5 | Thenable<T5>]): Promise<[T1, T2, T3, T4, T5]>;
static all<T1, T2, T3, T4>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>, T4 | Thenable <T4>]): Promise<[T1, T2, T3, T4]>;
static all<T1, T2, T3>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>, T3 | Thenable<T3>]): Promise<[T1, T2, T3]>;
static all<T1, T2>(values: [T1 | Thenable<T1>, T2 | Thenable<T2>]): Promise<[T1, T2]>;
static all<T1>(values: [T1 | Thenable<T1>]): Promise<[T1]>;
static all<TAll>(values: Array<TAll | Thenable<TAll>>): Promise<TAll[]>;
/**
* Make a Promise that fulfills when any item fulfills, and rejects if any item rejects.
*/
static race <R> (promises: (R | Thenable<R>)[]): Promise<R>;
}
/**
* The polyfill method will patch the global environment (in this case to the Promise name) when called.
*/
export function polyfill (): void;
import Promise from './es6-promise/promise';
import polyfill from './es6-promise/polyfill';
// Strange compat..
Promise.polyfill = polyfill;
Promise.Promise = Promise;
export default Promise;
import {
objectOrFunction,
isFunction
} from './utils';
import {
asap
} from './asap';
import originalThen from './then';
import originalResolve from './promise/resolve';
export const PROMISE_ID = Math.random().toString(36).substring(16);
function noop() {}
const PENDING = void 0;
const FULFILLED = 1;
const REJECTED = 2;
const GET_THEN_ERROR = new ErrorObject();
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function getThen(promise) {
try {
return promise.then;
} catch(error) {
GET_THEN_ERROR.error = error;
return GET_THEN_ERROR;
}
}
function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch(e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then) {
asap(promise => {
var sealed = false;
var error = tryThen(then, thenable, value => {
if (sealed) { return; }
sealed = true;
if (thenable !== value) {
resolve(promise, value);
} else {
fulfill(promise, value);
}
}, reason => {
if (sealed) { return; }
sealed = true;
reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, value => resolve(promise, value),
reason => reject(promise, reason))
}
}
function handleMaybeThenable(promise, maybeThenable, then) {
if (maybeThenable.constructor === promise.constructor &&
then === originalThen &&
maybeThenable.constructor.resolve === originalResolve) {
handleOwnThenable(promise, maybeThenable);
} else {
if (then === GET_THEN_ERROR) {
reject(promise, GET_THEN_ERROR.error);
} else if (then === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then)) {
handleForeignThenable(promise, maybeThenable, then);
} else {
fulfill(promise, maybeThenable);
}
}
}
function resolve(promise, value) {
if (promise === value) {
reject(promise, selfFulfillment());
} else if (objectOrFunction(value)) {
handleMaybeThenable(promise, value, getThen(value));
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) { return; }
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length !== 0) {
asap(publish, promise);
}
}
function reject(promise, reason) {
if (promise._state !== PENDING) { return; }
promise._state = REJECTED;
promise._result = reason;
asap(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
let { _subscribers } = parent;
let { length } = _subscribers;
parent._onerror = null;
_subscribers[length] = child;
_subscribers[length + FULFILLED] = onFulfillment;
_subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
asap(publish, parent);
}
}
function publish(promise) {
let subscribers = promise._subscribers;
let settled = promise._state;
if (subscribers.length === 0) { return; }
let child, callback, detail = promise._result;
for (let i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function ErrorObject() {
this.error = null;
}
const TRY_CATCH_ERROR = new ErrorObject();
function tryCatch(callback, detail) {
try {
return callback(detail);
} catch(e) {
TRY_CATCH_ERROR.error = e;
return TRY_CATCH_ERROR;
}
}
function invokeCallback(settled, promise, callback, detail) {
let hasCallback = isFunction(callback),
value, error, succeeded, failed;
if (hasCallback) {
value = tryCatch(callback, detail);
if (value === TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value = null;
} else {
succeeded = true;
}
if (promise === value) {
reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (failed) {
reject(promise, error);
} else if (settled === FULFILLED) {
fulfill(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
}
function initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value){
resolve(promise, value);
}, function rejectPromise(reason) {
reject(promise, reason);
});
} catch(e) {
reject(promise, e);
}
}
let id = 0;
function nextId() {
return id++;
}
function makePromise(promise) {
promise[PROMISE_ID] = id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
export {
nextId,
makePromise,
getThen,
noop,
resolve,
reject,
fulfill,
subscribe,
publish,
publishRejection,
initializePromise,
invokeCallback,
FULFILLED,
REJECTED,
PENDING,
handleMaybeThenable
};
let len = 0;
let vertxNext;
let customSchedulerFn;
export var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
}
export function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
export function setAsap(asapFn) {
asap = asapFn;
}
const browserWindow = (typeof window !== 'undefined') ? window : undefined;
const browserGlobal = browserWindow || {};
const BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
const isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
// test for web worker but not in IE10
const isWorker = typeof Uint8ClampedArray !== 'undefined' &&
typeof importScripts !== 'undefined' &&
typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return () => process.nextTick(flush);
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function() {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
let iterations = 0;
const observer = new BrowserMutationObserver(flush);
const node = document.createTextNode('');
observer.observe(node, { characterData: true });
return () => {
node.data = (iterations = ++iterations % 2);
};
}
// web worker
function useMessageChannel() {
const channel = new MessageChannel();
channel.port1.onmessage = flush;
return () => channel.port2.postMessage(0);
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
const globalSetTimeout = setTimeout;
return () => globalSetTimeout(flush, 1);
}
const queue = new Array(1000);
function flush() {
for (let i = 0; i < len; i+=2) {
let callback = queue[i];
let arg = queue[i+1];
callback(arg);
queue[i] = undefined;
queue[i+1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
const r = require;
const vertx = r('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch(e) {
return useSetTimeout();
}
}
let scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}
import {
isArray,
isMaybeThenable
} from './utils';
import {
noop,
reject,
fulfill,
subscribe,
FULFILLED,
REJECTED,
PENDING,
getThen,
handleMaybeThenable
} from './-internal';
import then from './then';
import Promise from './promise';
import originalResolve from './promise/resolve';
import originalThen from './then';
import { makePromise, PROMISE_ID } from './-internal';
export default Enumerator;
function Enumerator(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this._input = input;
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate();
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
reject(this.promise, validationError());
}
}
function validationError() {
return new Error('Array Methods must be provided an Array');
};
Enumerator.prototype._enumerate = function() {
let { length, _input } = this;
for (let i = 0; this._state === PENDING && i < length; i++) {
this._eachEntry(_input[i], i);
}
};
Enumerator.prototype._eachEntry = function(entry, i) {
let c = this._instanceConstructor;
let { resolve } = c;
if (resolve === originalResolve) {
let then = getThen(entry);
if (then === originalThen &&
entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise) {
let promise = new c(noop);
handleMaybeThenable(promise, entry, then);
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(resolve => resolve(entry)), i);
}
} else {
this._willSettleAt(resolve(entry), i);
}
};
Enumerator.prototype._settledAt = function(state, i, value) {
let { promise } = this;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
};
Enumerator.prototype._willSettleAt = function(promise, i) {
let enumerator = this;
subscribe(promise, undefined, value => enumerator._settledAt(FULFILLED, i, value),
reason => enumerator._settledAt(REJECTED, i, reason));
};
/*global self*/
import Promise from './promise';
export default function polyfill() {
let local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
let P = local.Promise;
if (P) {
var promiseToString = null;
try {
promiseToString = Object.prototype.toString.call(P.resolve());
} catch(e) {
// silently ignored
}
if (promiseToString === '[object Promise]' && !P.cast){
return;
}
}
local.Promise = Promise;
}
import {
noop,
reject as _reject
} from '../-internal';
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
export default function reject(reason) {
/*jshint validthis:true */
let Constructor = this;
let promise = new Constructor(noop);
_reject(promise, reason);
return promise;
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
#!/usr/bin/env node
require('../lib/tsc.js')
#!/usr/bin/env node
require('../lib/tsserver.js')
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment