##// END OF EJS Templates
minor fixes, code cleanup...
cin -
r33:58f57bdfc295 di-typescript
parent child
Show More
@@ -0,0 +1,17
1 <?xml version="1.0" encoding="UTF-8"?>
2 <projectDescription>
3 <name>core</name>
4 <comment>Project core created by Buildship.</comment>
5 <projects>
6 </projects>
7 <buildSpec>
8 <buildCommand>
9 <name>org.eclipse.buildship.core.gradleprojectbuilder</name>
10 <arguments>
11 </arguments>
12 </buildCommand>
13 </buildSpec>
14 <natures>
15 <nature>org.eclipse.buildship.core.gradleprojectnature</nature>
16 </natures>
17 </projectDescription>
@@ -0,0 +1,2
1 connection.project.dir=
2 eclipse.preferences.version=1
@@ -0,0 +1,4
1 {
2 "java.configuration.updateBuildConfiguration": "disabled",
3 "tslint.enable": true
4 } No newline at end of file
@@ -0,0 +1,126
1 import { TraceSource } from "./log/TraceSource";
2 import { argumentNotNull, argumentNotEmptyString, isPrimitive, each, isNull } from "./safe";
3 import { Uuid } from './Uuid';
4 import {ActivationContext} from "./di/ActivationContext";
5
6 let trace = TraceSource.get("di");
7
8 export interface Descriptor {
9 activate(context: ActivationContext, name: string): any
10 }
11
12 export function isDescriptor(value: any): value is Descriptor {
13 return ("activate" in value);
14 }
15
16 export interface ServiceMap {
17 [s: string] : Descriptor
18 }
19
20 export class ActivationContextInfo {
21 name: string
22
23 service: string
24
25 scope: ServiceMap
26 }
27
28 export class ActivationError {
29 activationStack: ActivationContextInfo[]
30
31 service: string
32
33 innerException: any
34
35 message: string
36
37 constructor(service: string, activationStack: ActivationContextInfo[], innerException) {
38 this.message = "Failed to activate the service";
39 this.activationStack = activationStack;
40 this.service = service;
41 this.innerException = innerException;
42 }
43
44 toString() {
45 var parts = [this.message];
46 if (this.service)
47 parts.push("when activating: " + this.service.toString());
48
49 if (this.innerException)
50 parts.push("caused by: " + this.innerException.toString());
51
52 if (this.activationStack) {
53 parts.push("at");
54 this.activationStack.forEach(function (x) {
55 parts.push(" " + x.name + " " +
56 (x.service ? x.service.toString() : ""));
57 });
58 }
59
60 return parts.join("\n");
61 }
62 }
63
64
65 export enum ActivationType {
66 SINGLETON,
67 CONTAINER,
68 HIERARCHY,
69 CONTEXT,
70 CALL
71 }
72
73
74
75 interface ServiceDescriptorParams {
76
77 }
78
79 class ServiceDescriptor extends Descriptor {
80 constructor(opts: ServiceDescriptorParams) {
81 super();
82 }
83
84 activate(context: ActivationContext, name: string) {
85 throw new Error("Method not implemented.");
86 }
87 isInstanceCreated(): boolean {
88 throw new Error("Method not implemented.");
89 }
90 getInstance() {
91 throw new Error("Method not implemented.");
92 }
93 }
94
95
96
97 class AggregateDescriptor<T> extends Descriptor {
98 constructor(value: T) {
99 super();
100 }
101
102 activate(context: ActivationContext, name: string) {
103 throw new Error("Method not implemented.");
104 }
105 isInstanceCreated(): boolean {
106 throw new Error("Method not implemented.");
107 }
108 getInstance(): T {
109 throw new Error("Method not implemented.");
110 }
111 }
112
113 class ValueDescriptor<T> implements Descriptor {
114 activate(context: ActivationContext, name: string) {
115 throw new Error("Method not implemented.");
116 }
117 isInstanceCreated(): boolean {
118 throw new Error("Method not implemented.");
119 }
120 getInstance(): T {
121 throw new Error("Method not implemented.");
122 }
123 constructor(value: T) {
124
125 }
126 } No newline at end of file
@@ -0,0 +1,132
1 import { TraceSource } from "../log/TraceSource";
2 import { argumentNotNull, argumentNotEmptyString, isPrimitive, each, isNull } from "../safe";
3 import { Uuid } from '../Uuid';
4 import { Container, ActivationContextInfo, ServiceMap, Descriptor, isDescriptor } from "../di";
5
6 let trace = TraceSource.get("di");
7
8
9 export class ActivationContext {
10 _cache: object
11
12 _services: ServiceMap
13
14 _stack: ActivationContextInfo[]
15
16 _visited: any
17
18 container: any
19
20
21 constructor(container: Container, services: ServiceMap, cache?: object, visited?) {
22 argumentNotNull(container, "container");
23 argumentNotNull(services, "services");
24
25 this._visited = visited || {};
26 this._stack = [];
27 this._cache = cache || {};
28 this._services = services;
29 this.container = container;
30 }
31
32 getService(name, def?): any {
33 let d = this._services[name];
34
35 if (!d)
36 if (arguments.length > 1)
37 return def;
38 else
39 throw new Error("Service '" + name + "' not found");
40
41 return d.activate(this, name);
42 }
43
44 /**
45 * registers services local to the the activation context
46 *
47 * @name{string} the name of the service
48 * @service{string} the service descriptor to register
49 */
50 register(name: string, service: Descriptor) {
51 argumentNotEmptyString(name, "name");
52
53 this._services[name] = service;
54 }
55
56 clone() {
57 return new ActivationContext(
58 this.container,
59 Object.create(this._services),
60 this._cache,
61 this._visited
62 );
63
64 }
65
66 has(id) {
67 return id in this._cache;
68 }
69
70 get(id) {
71 return this._cache[id];
72 }
73
74 store(id, value) {
75 return (this._cache[id] = value);
76 }
77
78 parse(data: any, name) {
79 var me = this;
80 if (isPrimitive(data))
81 return data;
82
83 if (isDescriptor(data)) {
84 return data.activate(this, name);
85 } else if (data instanceof Array) {
86 me.enter(name);
87 var v = data.map(function (x, i) {
88 return me.parse(x, "." + i);
89 });
90 me.leave();
91 return v;
92 } else {
93 me.enter(name);
94 var result = {};
95 for (var p in data)
96 result[p] = me.parse(data[p], "." + p);
97 me.leave();
98 return result;
99 }
100 }
101
102 visit(id) {
103 var count = this._visited[id] || 0;
104 this._visited[id] = count + 1;
105 return count;
106 }
107
108 getStack() {
109 return this._stack.slice().reverse();
110 }
111
112 enter(name, d?, localize?) {
113 if (trace.isLogEnabled())
114 trace.log("enter " + name + " " + (d || "") +
115 (localize ? " localize" : ""));
116 this._stack.push({
117 name: name,
118 service: d,
119 scope: this._services
120 });
121 if (localize)
122 this._services = Object.create(this._services);
123 }
124
125 leave() {
126 var ctx = this._stack.pop();
127 this._services = ctx.scope;
128
129 if (trace.isLogEnabled())
130 trace.log("leave " + ctx.name + " " + (ctx.service || ""));
131 }
132 } No newline at end of file
@@ -0,0 +1,282
1 import { Uuid } from "../Uuid";
2 import { ActivationContext } from "./ActivationContext";
3 import { ActivationError } from "../di";
4
5
6 export class Container {
7 _services
8
9 _cache
10
11 _cleanup: any[]
12
13 _root: Container
14
15 _parent: Container
16
17 constructor(parent?: Container) {
18 this._parent = parent;
19 this._services = parent ? Object.create(parent._services) : {};
20 this._cache = {};
21 this._cleanup = [];
22 this._root = parent ? parent.getRootContainer() : this;
23 this._services.container = new ValueDescriptor(this);
24 }
25
26 getRootContainer() {
27 return this._root;
28 }
29
30 getParent() {
31 return this._parent;
32 }
33
34 getService<T = any>(name: string, def?: T) {
35 let d = this._services[name];
36 if (!d)
37 if (arguments.length > 1)
38 return def;
39 else
40 throw new Error("Service '" + name + "' isn't found");
41
42 if (d.isInstanceCreated())
43 return d.getInstance();
44
45 var context = new ActivationContext(this, this._services);
46
47 try {
48 return d.activate(context, name);
49 } catch (error) {
50 throw new ActivationError(name, context.getStack(), error);
51 }
52 }
53
54 register(nameOrCollection, service?) {
55 if (arguments.length == 1) {
56 var data = nameOrCollection;
57 for (let name in data)
58 this.register(name, data[name]);
59 } else {
60 if (!(service instanceof Descriptor))
61 service = new ValueDescriptor(service);
62 this._services[nameOrCollection] = service;
63 }
64 return this;
65 }
66
67 onDispose(callback) {
68 if (!(callback instanceof Function))
69 throw new Error("The callback must be a function");
70 this._cleanup.push(callback);
71 }
72
73 dispose() {
74 if (this._cleanup) {
75 for (var i = 0; i < this._cleanup.length; i++)
76 this._cleanup[i].call(null);
77 this._cleanup = null;
78 }
79 }
80
81 /**
82 * @param{String|Object} config
83 * The configuration of the contaier. Can be either a string or an object,
84 * if the configuration is an object it's treated as a collection of
85 * services which will be registed in the contaier.
86 *
87 * @param{Function} opts.contextRequire
88 * The function which will be used to load a configuration or types for services.
89 *
90 */
91 async configure(config, opts) {
92 var me = this,
93 contextRequire = (opts && opts.contextRequire);
94
95 if (typeof (config) === "string") {
96 let args;
97 if (!contextRequire) {
98 var shim = [config, Uuid()].join(config.indexOf("/") != -1 ? "-" : "/");
99 args = await new Promise((resolve, reject) => {
100 define(shim, ["require", config], function (ctx, data) {
101 resolve([data, {
102 contextRequire: ctx
103 }]);
104 })
105 });
106 require([shim]);
107 } else {
108 // TODO how to get correct contextRequire for the relative config module?
109 args = await new Promise((resolve, reject) => {
110 contextRequire([config], function (data) {
111 resolve([data, {
112 contextRequire: contextRequire
113 }]);
114 });
115 });
116 }
117
118 return me._configure.apply(me, args);
119 } else {
120 return me._configure(config, opts);
121 }
122 }
123
124 createChildContainer() {
125 return new Container(this);
126 }
127
128 has(id) {
129 return id in this._cache;
130 }
131
132 get(id) {
133 return this._cache[id];
134 }
135
136 store(id, value) {
137 return (this._cache[id] = value);
138 }
139
140 async _configure(data, opts) {
141 var typemap = {},
142 me = this,
143 p,
144 contextRequire = (opts && opts.contextRequire) || require;
145
146 var services = {};
147
148 for (p in data) {
149 var service = me._parse(data[p], typemap);
150 if (!(service instanceof Descriptor))
151 service = new AggregateDescriptor(service);
152 services[p] = service;
153 }
154
155 me.register(services);
156
157 var names = [];
158
159 for (p in typemap)
160 names.push(p);
161
162 return new Promise((resolve, reject) => {
163 if (names.length) {
164 contextRequire(names, function () {
165 for (var i = 0; i < names.length; i++)
166 typemap[names[i]] = arguments[i];
167 resolve(me);
168 });
169 } else {
170 resolve(me);
171 }
172 });
173
174 }
175
176 _parse(data, typemap) {
177 if (isPrimitive(data) || data instanceof Descriptor)
178 return data;
179 if (data.$dependency) {
180 return new ReferenceDescriptor(
181 data.$dependency,
182 data.lazy,
183 data.optional,
184 data["default"],
185 data.services && this._parseObject(data.services, typemap));
186 } else if (data.$value) {
187 return !data.parse ?
188 new ValueDescriptor(data.$value) :
189 new AggregateDescriptor(this._parse(data.$value, typemap));
190 } else if (data.$type || data.$factory) {
191 return this._parseService(data, typemap);
192 } else if (data instanceof Array) {
193 return this._parseArray(data, typemap);
194 }
195
196 return this._parseObject(data, typemap);
197 }
198
199 _parseService(data, typemap) {
200 var me = this,
201 opts: any = {
202 owner: this
203 };
204 if (data.$type) {
205
206 opts.type = data.$type;
207
208 if (typeof (data.$type) === "string") {
209 typemap[data.$type] = null;
210 opts.typeMap = typemap;
211 }
212 }
213
214 if (data.$factory)
215 opts.factory = data.$factory;
216
217 if (data.services)
218 opts.services = me._parseObject(data.services, typemap);
219 if (data.inject)
220 opts.inject = data.inject instanceof Array ? data.inject.map(function (x) {
221 return me._parseObject(x, typemap);
222 }) : me._parseObject(data.inject, typemap);
223 if (data.params)
224 opts.params = me._parse(data.params, typemap);
225
226 if (data.activation) {
227 if (typeof (data.activation) === "string") {
228 switch (data.activation.toLowerCase()) {
229 case "singleton":
230 opts.activation = ActivationType.SINGLETON;
231 break;
232 case "container":
233 opts.activation = ActivationType.CONTAINER;
234 break;
235 case "hierarchy":
236 opts.activation = ActivationType.HIERARCHY;
237 break;
238 case "context":
239 opts.activation = ActivationType.CONTEXT;
240 break;
241 case "call":
242 opts.activation = ActivationType.CALL;
243 break;
244 default:
245 throw new Error("Unknown activation type: " +
246 data.activation);
247 }
248 } else {
249 opts.activation = Number(data.activation);
250 }
251 }
252
253 if (data.cleanup)
254 opts.cleanup = data.cleanup;
255
256 return new ServiceDescriptor(opts);
257 }
258
259 _parseObject(data, typemap) {
260 if (data.constructor &&
261 data.constructor.prototype !== Object.prototype)
262 return new ValueDescriptor(data);
263
264 var o = {};
265
266 for (var p in data)
267 o[p] = this._parse(data[p], typemap);
268
269 return o;
270 }
271
272 _parseArray(data, typemap) {
273 if (data.constructor &&
274 data.constructor.prototype !== Array.prototype)
275 return new ValueDescriptor(data);
276
277 var me = this;
278 return data.map(function (x) {
279 return me._parse(x, typemap);
280 });
281 }
282 } No newline at end of file
@@ -0,0 +1,11
1 import { ActivationContext } from "./ActivationContext";
2 import { isNull } from "../safe";
3
4 export interface Descriptor {
5 activate(context: ActivationContext, name?: string);
6 }
7
8 export function isDescriptor(instance): instance is Descriptor {
9 return (!isNull(instance)) &&
10 ('activate' in instance);
11 } No newline at end of file
@@ -0,0 +1,98
1 import { isNull, argumentNotEmptyString, each } from "../safe";
2
3 class ReferenceDescriptor extends Descriptor {
4 _name: string
5
6 _lazy = false
7
8 _optional = false
9
10 _default: any
11
12 _services: object
13
14 constructor(name: string, lazy: boolean, optional: boolean, def, services: object) {
15 super();
16 argumentNotEmptyString(name, "name");
17 this._name = name;
18 this._lazy = Boolean(lazy);
19 this._optional = Boolean(optional);
20 this._default = def;
21 this._services = services;
22 }
23
24 activate(context: ActivationContext, name: string) {
25 var me = this;
26
27 context.enter(name, this, true);
28
29 // добавляем сервисы
30 if (me._services) {
31 for (var p in me._services) {
32 var sv = me._services[p];
33 context.register(p, sv instanceof Descriptor ? sv : new AggregateDescriptor(sv));
34 }
35 }
36
37 if (me._lazy) {
38 // сохраняем контекст активации
39 context = context.clone();
40 return function (cfg) {
41 // защищаем контекст на случай исключения в процессе
42 // активации
43 var ct = context.clone();
44 try {
45 if (cfg)
46 each(cfg, function (v, k) {
47 ct.register(k, v instanceof Descriptor ? v : new AggregateDescriptor(v));
48 });
49 return me._optional ? ct.getService(me._name, me._default) : ct
50 .getService(me._name);
51 } catch (error) {
52 throw new ActivationError(me._name, ct.getStack(), error);
53 }
54 };
55 }
56
57 var v = me._optional ?
58 context.getService(me._name, me._default) :
59 context.getService(me._name);
60
61 context.leave();
62 return v;
63 }
64
65 isInstanceCreated() {
66 return false;
67 }
68
69 getInstance() {
70 throw new Error("The reference descriptor doesn't allowed to hold an instance");
71 }
72
73 toString() {
74 var opts = [];
75 if (this._optional)
76 opts.push("optional");
77 if (this._lazy)
78 opts.push("lazy");
79
80 var parts = [
81 "@ref "
82 ];
83 if (opts.length) {
84 parts.push("{");
85 parts.push(opts.join());
86 parts.push("} ");
87 }
88
89 parts.push(this._name);
90
91 if (!isNull(this._default)) {
92 parts.push(" = ");
93 parts.push(this._default);
94 }
95
96 return parts.join("");
97 }
98 } No newline at end of file
@@ -0,0 +1,15
1 {
2 "compilerOptions": {
3 "target": "es5",
4 "module": "amd",
5 "sourceMap": true,
6 "outDir" : "build/dist",
7 "declaration": true,
8 "lib": [
9 "es2015"
10 ]
11 },
12 "include" : [
13 "src/ts/**/*.ts"
14 ]
15 } No newline at end of file
@@ -0,0 +1,15
1 {
2 "compilerOptions": {
3 "target": "es5",
4 "module": "amd",
5 "sourceMap": true,
6 "outDir" : "build/test",
7 "moduleResolution": "node",
8 "lib": [
9 "ES2015"
10 ]
11 },
12 "include" : [
13 "test/ts/**/*.ts"
14 ]
15 } No newline at end of file
@@ -1,94 +1,94
1 1 if (release != 'rtm') {
2 2 version += "-$release"
3 3 }
4 4
5 5 println "version: $version"
6 6
7 7 def distDir = "$buildDir/dist"
8 8 def testDir = "$buildDir/test"
9 9
10 10 task clean {
11 11 doLast {
12 12 delete buildDir
13 13 delete 'node_modules/@implab'
14 14 }
15 15 }
16 16
17 17 task cleanNpm {
18 18 doLast {
19 19 delete 'node_modules'
20 20 }
21 21 }
22 22
23 23 task _npmInstall() {
24 24 inputs.file("package.json")
25 25 outputs.dir("node_modules")
26 26 doLast {
27 27 exec {
28 28 commandLine 'npm', 'install'
29 29 }
30 30 }
31 31 }
32 32
33 33 task _legacyJs(type:Copy) {
34 34 from 'src/js/'
35 35 into distDir
36 36 }
37 37
38 38 task _buildTs(dependsOn: _npmInstall, type:Exec) {
39 39 inputs.dir('src/ts')
40 40 inputs.file('tsc.json')
41 41 outputs.dir(distDir)
42 42
43 commandLine 'node_modules/.bin/tsc', '-p', 'tsc.json'
43 commandLine 'node_modules/.bin/tsc', '-p', 'tsconfig.json'
44 44 }
45 45
46 46 task _packageMeta(type: Copy) {
47 47 inputs.property("version", version)
48 48 from('.') {
49 49 include 'package.json', '.npmignore', 'readme.md', 'license', 'history.md'
50 50 }
51 51 into distDir
52 52 doLast {
53 53 exec {
54 54 workingDir distDir
55 55 commandLine 'npm', 'version', version
56 56 }
57 57 }
58 58 }
59 59
60 60 task build(dependsOn: [_npmInstall, _buildTs, _legacyJs, _packageMeta]) {
61 61
62 62 }
63 63
64 64 task _localInstall(dependsOn: build, type: Exec) {
65 65 inputs.file("$distDir/package.json")
66 66 outputs.upToDateWhen {
67 67 new File("$projectDir/node_modules/@implab/core").exists()
68 68 }
69 69
70 70 commandLine 'npm', 'install', '--no-save', '--force', distDir
71 71 }
72 72
73 73 task copyJsTests(type: Copy) {
74 74 from 'test/js'
75 75 into testDir
76 76 }
77 77
78 78 task buildTests(dependsOn: _localInstall, type: Exec) {
79 79 inputs.dir('test/ts')
80 80 inputs.file('tsc.test.json')
81 81 outputs.dir(testDir)
82 82
83 commandLine 'node_modules/.bin/tsc', '-p', 'tsc.test.json'
83 commandLine 'node_modules/.bin/tsc', '-p', 'tsconfig.test.json'
84 84 }
85 85
86 86 task test(dependsOn: [copyJsTests, buildTests], type: Exec) {
87 87 commandLine 'node', 'run-amd-tests.js'
88 88 }
89 89
90 90 task pack(dependsOn: build, type: Exec) {
91 91 workingDir = distDir
92 92
93 93 commandLine 'npm', 'pack'
94 94 } No newline at end of file
@@ -1,445 +1,445
1 1 {
2 2 "name": "@implab/core",
3 3 "version": "0.0.1-dev",
4 4 "lockfileVersion": 1,
5 5 "requires": true,
6 6 "dependencies": {
7 7 "@types/node": {
8 8 "version": "10.5.1",
9 9 "resolved": "https://registry.npmjs.org/@types/node/-/node-10.5.1.tgz",
10 10 "integrity": "sha512-AFLl1IALIuyt6oK4AYZsgWVJ/5rnyzQWud7IebaZWWV3YmgtPZkQmYio9R5Ze/2pdd7XfqF5bP+hWS11mAKoOQ==",
11 11 "dev": true
12 12 },
13 13 "@types/tape": {
14 14 "version": "4.2.32",
15 15 "resolved": "https://registry.npmjs.org/@types/tape/-/tape-4.2.32.tgz",
16 16 "integrity": "sha512-xil0KO5wkPoixdBWGIGolPv9dekf6dVkjjJLAFYchfKcd4DICou67rgGCIO7wAh3i5Ff/6j9IDgZz+GU9cMaqQ==",
17 17 "dev": true,
18 18 "requires": {
19 "@types/node": "10.5.1"
19 "@types/node": "*"
20 20 }
21 21 },
22 22 "balanced-match": {
23 23 "version": "1.0.0",
24 24 "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
25 25 "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=",
26 26 "dev": true
27 27 },
28 28 "brace-expansion": {
29 29 "version": "1.1.11",
30 30 "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
31 31 "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
32 32 "dev": true,
33 33 "requires": {
34 "balanced-match": "1.0.0",
34 "balanced-match": "^1.0.0",
35 35 "concat-map": "0.0.1"
36 36 }
37 37 },
38 38 "concat-map": {
39 39 "version": "0.0.1",
40 40 "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
41 41 "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=",
42 42 "dev": true
43 43 },
44 44 "core-util-is": {
45 45 "version": "1.0.2",
46 46 "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
47 47 "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=",
48 48 "dev": true
49 49 },
50 50 "deep-equal": {
51 51 "version": "1.0.1",
52 52 "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz",
53 53 "integrity": "sha1-9dJgKStmDghO/0zbyfCK0yR0SLU=",
54 54 "dev": true
55 55 },
56 56 "define-properties": {
57 57 "version": "1.1.2",
58 58 "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.2.tgz",
59 59 "integrity": "sha1-g6c/L+pWmJj7c3GTyPhzyvbUXJQ=",
60 60 "dev": true,
61 61 "requires": {
62 "foreach": "2.0.5",
63 "object-keys": "1.0.12"
62 "foreach": "^2.0.5",
63 "object-keys": "^1.0.8"
64 64 }
65 65 },
66 66 "defined": {
67 67 "version": "1.0.0",
68 68 "resolved": "https://registry.npmjs.org/defined/-/defined-1.0.0.tgz",
69 69 "integrity": "sha1-yY2bzvdWdBiOEQlpFRGZ45sfppM=",
70 70 "dev": true
71 71 },
72 72 "dojo": {
73 73 "version": "1.13.0",
74 74 "resolved": "https://registry.npmjs.org/dojo/-/dojo-1.13.0.tgz",
75 75 "integrity": "sha512-mGoGvsXAbPkUrBnxCoO7m6CFH8jvWq7rAL7fP7jrhJEOyswA/bZwWdXwEH0ovs68t8S0+xOpV/3V7addYbaiAA=="
76 76 },
77 77 "duplexer": {
78 78 "version": "0.1.1",
79 79 "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.1.tgz",
80 80 "integrity": "sha1-rOb/gIwc5mtX0ev5eXessCM0z8E=",
81 81 "dev": true
82 82 },
83 83 "es-abstract": {
84 84 "version": "1.12.0",
85 85 "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.12.0.tgz",
86 86 "integrity": "sha512-C8Fx/0jFmV5IPoMOFPA9P9G5NtqW+4cOPit3MIuvR2t7Ag2K15EJTpxnHAYTzL+aYQJIESYeXZmDBfOBE1HcpA==",
87 87 "dev": true,
88 88 "requires": {
89 "es-to-primitive": "1.1.1",
90 "function-bind": "1.1.1",
91 "has": "1.0.3",
92 "is-callable": "1.1.3",
93 "is-regex": "1.0.4"
89 "es-to-primitive": "^1.1.1",
90 "function-bind": "^1.1.1",
91 "has": "^1.0.1",
92 "is-callable": "^1.1.3",
93 "is-regex": "^1.0.4"
94 94 }
95 95 },
96 96 "es-to-primitive": {
97 97 "version": "1.1.1",
98 98 "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.1.1.tgz",
99 99 "integrity": "sha1-RTVSSKiJeQNLZ5Lhm7gfK3l13Q0=",
100 100 "dev": true,
101 101 "requires": {
102 "is-callable": "1.1.3",
103 "is-date-object": "1.0.1",
104 "is-symbol": "1.0.1"
102 "is-callable": "^1.1.1",
103 "is-date-object": "^1.0.1",
104 "is-symbol": "^1.0.1"
105 105 }
106 106 },
107 107 "faucet": {
108 108 "version": "0.0.1",
109 109 "resolved": "https://registry.npmjs.org/faucet/-/faucet-0.0.1.tgz",
110 110 "integrity": "sha1-WX3PHSGJosBiMhtZHo8VHtIDnZw=",
111 111 "dev": true,
112 112 "requires": {
113 113 "defined": "0.0.0",
114 "duplexer": "0.1.1",
114 "duplexer": "~0.1.1",
115 115 "minimist": "0.0.5",
116 "sprintf": "0.1.5",
117 "tap-parser": "0.4.3",
118 "tape": "2.3.3",
119 "through2": "0.2.3"
116 "sprintf": "~0.1.3",
117 "tap-parser": "~0.4.0",
118 "tape": "~2.3.2",
119 "through2": "~0.2.3"
120 120 },
121 121 "dependencies": {
122 122 "deep-equal": {
123 123 "version": "0.1.2",
124 124 "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-0.1.2.tgz",
125 125 "integrity": "sha1-skbCuApXCkfBG+HZvRBw7IeLh84=",
126 126 "dev": true
127 127 },
128 128 "defined": {
129 129 "version": "0.0.0",
130 130 "resolved": "https://registry.npmjs.org/defined/-/defined-0.0.0.tgz",
131 131 "integrity": "sha1-817qfXBekzuvE7LwOz+D2SFAOz4=",
132 132 "dev": true
133 133 },
134 134 "minimist": {
135 135 "version": "0.0.5",
136 136 "resolved": "http://registry.npmjs.org/minimist/-/minimist-0.0.5.tgz",
137 137 "integrity": "sha1-16oye87PUY+RBqxrjwA/o7zqhWY=",
138 138 "dev": true
139 139 },
140 140 "tape": {
141 141 "version": "2.3.3",
142 142 "resolved": "https://registry.npmjs.org/tape/-/tape-2.3.3.tgz",
143 143 "integrity": "sha1-Lnzgox3wn41oUWZKcYQuDKUFevc=",
144 144 "dev": true,
145 145 "requires": {
146 "deep-equal": "0.1.2",
147 "defined": "0.0.0",
148 "inherits": "2.0.3",
149 "jsonify": "0.0.0",
150 "resumer": "0.0.0",
151 "through": "2.3.8"
146 "deep-equal": "~0.1.0",
147 "defined": "~0.0.0",
148 "inherits": "~2.0.1",
149 "jsonify": "~0.0.0",
150 "resumer": "~0.0.0",
151 "through": "~2.3.4"
152 152 }
153 153 }
154 154 }
155 155 },
156 156 "for-each": {
157 157 "version": "0.3.3",
158 158 "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz",
159 159 "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==",
160 160 "dev": true,
161 161 "requires": {
162 "is-callable": "1.1.3"
162 "is-callable": "^1.1.3"
163 163 }
164 164 },
165 165 "foreach": {
166 166 "version": "2.0.5",
167 167 "resolved": "https://registry.npmjs.org/foreach/-/foreach-2.0.5.tgz",
168 168 "integrity": "sha1-C+4AUBiusmDQo6865ljdATbsG5k=",
169 169 "dev": true
170 170 },
171 171 "fs.realpath": {
172 172 "version": "1.0.0",
173 173 "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
174 174 "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=",
175 175 "dev": true
176 176 },
177 177 "function-bind": {
178 178 "version": "1.1.1",
179 179 "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
180 180 "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==",
181 181 "dev": true
182 182 },
183 183 "glob": {
184 184 "version": "7.1.2",
185 185 "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz",
186 186 "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==",
187 187 "dev": true,
188 188 "requires": {
189 "fs.realpath": "1.0.0",
190 "inflight": "1.0.6",
191 "inherits": "2.0.3",
192 "minimatch": "3.0.4",
193 "once": "1.4.0",
194 "path-is-absolute": "1.0.1"
189 "fs.realpath": "^1.0.0",
190 "inflight": "^1.0.4",
191 "inherits": "2",
192 "minimatch": "^3.0.4",
193 "once": "^1.3.0",
194 "path-is-absolute": "^1.0.0"
195 195 }
196 196 },
197 197 "has": {
198 198 "version": "1.0.3",
199 199 "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz",
200 200 "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==",
201 201 "dev": true,
202 202 "requires": {
203 "function-bind": "1.1.1"
203 "function-bind": "^1.1.1"
204 204 }
205 205 },
206 206 "inflight": {
207 207 "version": "1.0.6",
208 208 "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
209 209 "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=",
210 210 "dev": true,
211 211 "requires": {
212 "once": "1.4.0",
213 "wrappy": "1.0.2"
212 "once": "^1.3.0",
213 "wrappy": "1"
214 214 }
215 215 },
216 216 "inherits": {
217 217 "version": "2.0.3",
218 218 "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
219 219 "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=",
220 220 "dev": true
221 221 },
222 222 "is-callable": {
223 223 "version": "1.1.3",
224 224 "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.3.tgz",
225 225 "integrity": "sha1-hut1OSgF3cM69xySoO7fdO52BLI=",
226 226 "dev": true
227 227 },
228 228 "is-date-object": {
229 229 "version": "1.0.1",
230 230 "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.1.tgz",
231 231 "integrity": "sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=",
232 232 "dev": true
233 233 },
234 234 "is-regex": {
235 235 "version": "1.0.4",
236 236 "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.4.tgz",
237 237 "integrity": "sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=",
238 238 "dev": true,
239 239 "requires": {
240 "has": "1.0.3"
240 "has": "^1.0.1"
241 241 }
242 242 },
243 243 "is-symbol": {
244 244 "version": "1.0.1",
245 245 "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.1.tgz",
246 246 "integrity": "sha1-PMWfAAJRlLarLjjbrmaJJWtmBXI=",
247 247 "dev": true
248 248 },
249 249 "isarray": {
250 250 "version": "0.0.1",
251 251 "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",
252 252 "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=",
253 253 "dev": true
254 254 },
255 255 "jsonify": {
256 256 "version": "0.0.0",
257 257 "resolved": "https://registry.npmjs.org/jsonify/-/jsonify-0.0.0.tgz",
258 258 "integrity": "sha1-LHS27kHZPKUbe1qu6PUDYx0lKnM=",
259 259 "dev": true
260 260 },
261 261 "minimatch": {
262 262 "version": "3.0.4",
263 263 "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz",
264 264 "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
265 265 "dev": true,
266 266 "requires": {
267 "brace-expansion": "1.1.11"
267 "brace-expansion": "^1.1.7"
268 268 }
269 269 },
270 270 "minimist": {
271 271 "version": "1.2.0",
272 272 "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz",
273 273 "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=",
274 274 "dev": true
275 275 },
276 276 "object-inspect": {
277 277 "version": "1.6.0",
278 278 "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.6.0.tgz",
279 279 "integrity": "sha512-GJzfBZ6DgDAmnuaM3104jR4s1Myxr3Y3zfIyN4z3UdqN69oSRacNK8UhnobDdC+7J2AHCjGwxQubNJfE70SXXQ==",
280 280 "dev": true
281 281 },
282 282 "object-keys": {
283 283 "version": "1.0.12",
284 284 "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.0.12.tgz",
285 285 "integrity": "sha512-FTMyFUm2wBcGHnH2eXmz7tC6IwlqQZ6mVZ+6dm6vZ4IQIHjs6FdNsQBuKGPuUUUY6NfJw2PshC08Tn6LzLDOag==",
286 286 "dev": true
287 287 },
288 288 "once": {
289 289 "version": "1.4.0",
290 290 "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
291 291 "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=",
292 292 "dev": true,
293 293 "requires": {
294 "wrappy": "1.0.2"
294 "wrappy": "1"
295 295 }
296 296 },
297 297 "path-is-absolute": {
298 298 "version": "1.0.1",
299 299 "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
300 300 "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=",
301 301 "dev": true
302 302 },
303 303 "path-parse": {
304 304 "version": "1.0.5",
305 305 "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.5.tgz",
306 306 "integrity": "sha1-PBrfhx6pzWyUMbbqK9dKD/BVxME=",
307 307 "dev": true
308 308 },
309 309 "readable-stream": {
310 310 "version": "1.1.14",
311 311 "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz",
312 312 "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=",
313 313 "dev": true,
314 314 "requires": {
315 "core-util-is": "1.0.2",
316 "inherits": "2.0.3",
315 "core-util-is": "~1.0.0",
316 "inherits": "~2.0.1",
317 317 "isarray": "0.0.1",
318 "string_decoder": "0.10.31"
318 "string_decoder": "~0.10.x"
319 319 }
320 320 },
321 321 "requirejs": {
322 322 "version": "2.3.6",
323 323 "resolved": "https://registry.npmjs.org/requirejs/-/requirejs-2.3.6.tgz",
324 324 "integrity": "sha512-ipEzlWQe6RK3jkzikgCupiTbTvm4S0/CAU5GlgptkN5SO6F3u0UD0K18wy6ErDqiCyP4J4YYe1HuAShvsxePLg==",
325 325 "dev": true
326 326 },
327 327 "resolve": {
328 328 "version": "1.7.1",
329 329 "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.7.1.tgz",
330 330 "integrity": "sha512-c7rwLofp8g1U+h1KNyHL/jicrKg1Ek4q+Lr33AL65uZTinUZHe30D5HlyN5V9NW0JX1D5dXQ4jqW5l7Sy/kGfw==",
331 331 "dev": true,
332 332 "requires": {
333 "path-parse": "1.0.5"
333 "path-parse": "^1.0.5"
334 334 }
335 335 },
336 336 "resumer": {
337 337 "version": "0.0.0",
338 338 "resolved": "https://registry.npmjs.org/resumer/-/resumer-0.0.0.tgz",
339 339 "integrity": "sha1-8ej0YeQGS6Oegq883CqMiT0HZ1k=",
340 340 "dev": true,
341 341 "requires": {
342 "through": "2.3.8"
342 "through": "~2.3.4"
343 343 }
344 344 },
345 345 "sprintf": {
346 346 "version": "0.1.5",
347 347 "resolved": "https://registry.npmjs.org/sprintf/-/sprintf-0.1.5.tgz",
348 348 "integrity": "sha1-j4PjmpMXwaUCy324BQ5Rxnn27c8=",
349 349 "dev": true
350 350 },
351 351 "string.prototype.trim": {
352 352 "version": "1.1.2",
353 353 "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.1.2.tgz",
354 354 "integrity": "sha1-0E3iyJ4Tf019IG8Ia17S+ua+jOo=",
355 355 "dev": true,
356 356 "requires": {
357 "define-properties": "1.1.2",
358 "es-abstract": "1.12.0",
359 "function-bind": "1.1.1"
357 "define-properties": "^1.1.2",
358 "es-abstract": "^1.5.0",
359 "function-bind": "^1.0.2"
360 360 }
361 361 },
362 362 "string_decoder": {
363 363 "version": "0.10.31",
364 364 "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz",
365 365 "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=",
366 366 "dev": true
367 367 },
368 368 "tap-parser": {
369 369 "version": "0.4.3",
370 370 "resolved": "https://registry.npmjs.org/tap-parser/-/tap-parser-0.4.3.tgz",
371 371 "integrity": "sha1-pOrhkMENdsehEZIf84u+TVjwnuo=",
372 372 "dev": true,
373 373 "requires": {
374 "inherits": "2.0.3",
375 "readable-stream": "1.1.14"
374 "inherits": "~2.0.1",
375 "readable-stream": "~1.1.11"
376 376 }
377 377 },
378 378 "tape": {
379 379 "version": "4.9.1",
380 380 "resolved": "https://registry.npmjs.org/tape/-/tape-4.9.1.tgz",
381 381 "integrity": "sha512-6fKIXknLpoe/Jp4rzHKFPpJUHDHDqn8jus99IfPnHIjyz78HYlefTGD3b5EkbQzuLfaEvmfPK3IolLgq2xT3kw==",
382 382 "dev": true,
383 383 "requires": {
384 "deep-equal": "1.0.1",
385 "defined": "1.0.0",
386 "for-each": "0.3.3",
387 "function-bind": "1.1.1",
388 "glob": "7.1.2",
389 "has": "1.0.3",
390 "inherits": "2.0.3",
391 "minimist": "1.2.0",
392 "object-inspect": "1.6.0",
393 "resolve": "1.7.1",
394 "resumer": "0.0.0",
395 "string.prototype.trim": "1.1.2",
396 "through": "2.3.8"
384 "deep-equal": "~1.0.1",
385 "defined": "~1.0.0",
386 "for-each": "~0.3.3",
387 "function-bind": "~1.1.1",
388 "glob": "~7.1.2",
389 "has": "~1.0.3",
390 "inherits": "~2.0.3",
391 "minimist": "~1.2.0",
392 "object-inspect": "~1.6.0",
393 "resolve": "~1.7.1",
394 "resumer": "~0.0.0",
395 "string.prototype.trim": "~1.1.2",
396 "through": "~2.3.8"
397 397 }
398 398 },
399 399 "through": {
400 400 "version": "2.3.8",
401 401 "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz",
402 402 "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=",
403 403 "dev": true
404 404 },
405 405 "through2": {
406 406 "version": "0.2.3",
407 407 "resolved": "https://registry.npmjs.org/through2/-/through2-0.2.3.tgz",
408 408 "integrity": "sha1-6zKE2k6jEbbMis42U3SKUqvyWj8=",
409 409 "dev": true,
410 410 "requires": {
411 "readable-stream": "1.1.14",
412 "xtend": "2.1.2"
411 "readable-stream": "~1.1.9",
412 "xtend": "~2.1.1"
413 413 }
414 414 },
415 415 "typescript": {
416 416 "version": "3.0.3",
417 417 "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.0.3.tgz",
418 418 "integrity": "sha512-kk80vLW9iGtjMnIv11qyxLqZm20UklzuR2tL0QAnDIygIUIemcZMxlMWudl9OOt76H3ntVzcTiddQ1/pAAJMYg==",
419 419 "dev": true
420 420 },
421 421 "wrappy": {
422 422 "version": "1.0.2",
423 423 "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
424 424 "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=",
425 425 "dev": true
426 426 },
427 427 "xtend": {
428 428 "version": "2.1.2",
429 429 "resolved": "https://registry.npmjs.org/xtend/-/xtend-2.1.2.tgz",
430 430 "integrity": "sha1-bv7MKk2tjmlixJAbM3znuoe10os=",
431 431 "dev": true,
432 432 "requires": {
433 "object-keys": "0.4.0"
433 "object-keys": "~0.4.0"
434 434 },
435 435 "dependencies": {
436 436 "object-keys": {
437 437 "version": "0.4.0",
438 438 "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-0.4.0.tgz",
439 439 "integrity": "sha1-KKaq50KN0sOpLz2V8hM13SBOAzY=",
440 440 "dev": true
441 441 }
442 442 }
443 443 }
444 444 }
445 445 }
@@ -1,282 +1,270
1 1 // Typescript port of the uuid.js
2 2 // Copyright (c) 2018 Sergey Smirnov
3 3 // BSD-2-Clause License https://opensource.org/licenses/BSD-2-Clause
4 4 //
5 5 // uuid.js
6 6 // Copyright (c) 2010-2012 Robert Kieffer
7 7 // MIT License - http://opensource.org/licenses/mit-license.php
8 8
9 9 declare var window: any;
10 10
11 let _window : any = 'undefined' !== typeof window ? window : null;
11 let _window: any = 'undefined' !== typeof window ? window : null;
12 12
13 13 // Unique ID creation requires a high quality random # generator. We
14 14 // feature
15 15 // detect to determine the best RNG source, normalizing to a function
16 16 // that
17 17 // returns 128-bits of randomness, since that's what's usually required
18 18 let _rng;
19 19
20 20 function setupBrowser() {
21 21 // Allow for MSIE11 msCrypto
22 22 let _crypto = _window.crypto || _window.msCrypto;
23 23
24 24 if (!_rng && _crypto && _crypto.getRandomValues) {
25 25 // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
26 26 //
27 27 // Moderately fast, high quality
28 28 try {
29 29 let _rnds8 = new Uint8Array(16);
30 30 _rng = function whatwgRNG() {
31 31 _crypto.getRandomValues(_rnds8);
32 32 return _rnds8;
33 33 };
34 34 _rng();
35 35 } catch (e) { /**/ }
36 36 }
37 37
38 38 if (!_rng) {
39 39 // Math.random()-based (RNG)
40 40 //
41 41 // If all else fails, use Math.random(). It's fast, but is of
42 42 // unspecified
43 43 // quality.
44 let _rnds = new Array(16);
44 let _rnds = new Array(16);
45 45 _rng = function () {
46 46 for (var i = 0, r; i < 16; i++) {
47 47 if ((i & 0x03) === 0) {
48 48 r = Math.random() * 0x100000000;
49 49 }
50 50 _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
51 51 }
52 52
53 53 return _rnds;
54 54 };
55 55 if ('undefined' !== typeof console && console.warn) {
56 56 console.warn("[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()");
57 57 }
58 58 }
59 59 }
60 60
61 61 function setupNode() {
62 62 // Node.js crypto-based RNG -
63 63 // http://nodejs.org/docs/v0.6.2/api/crypto.html
64 64 //
65 65 // Moderately fast, high quality
66 66 if ('function' === typeof require) {
67 67 try {
68 68 let _rb = require('crypto').randomBytes;
69 69 _rng = _rb && function () {
70 70 return _rb(16);
71 71 };
72 72 _rng();
73 73 } catch (e) { /**/ }
74 74 }
75 75 }
76 76
77 77 if (_window) {
78 78 setupBrowser();
79 79 } else {
80 80 setupNode();
81 81 }
82 82
83 83 // Buffer class to use
84 84 let BufferClass = ('function' === typeof Buffer) ? Buffer : Array;
85 85
86 86 // Maps for number <-> hex string conversion
87 87 let _byteToHex = [];
88 88 let _hexToByte = {};
89 89 for (let i = 0; i < 256; i++) {
90 90 _byteToHex[i] = (i + 0x100).toString(16).substr(1);
91 91 _hexToByte[_byteToHex[i]] = i;
92 92 }
93 93
94 94 // **`parse()` - Parse a UUID into it's component bytes**
95 function parse(s, buf?, offset?) : Array<string> {
96 let i = (buf && offset) || 0, ii = 0;
95 function _parse(s, buf?, offset?): Array<string> {
96 let i = (buf && offset) || 0, ii = 0;
97 97
98 98 buf = buf || [];
99 99 s.toLowerCase().replace(/[0-9a-f]{2}/g, function (oct) {
100 100 if (ii < 16) { // Don't overflow!
101 101 buf[i + ii++] = _hexToByte[oct];
102 102 }
103 103 });
104 104
105 105 // Zero out remaining bytes if string was short
106 106 while (ii < 16) {
107 107 buf[i + ii++] = 0;
108 108 }
109 109
110 110 return buf;
111 111 }
112 112
113 113 // **`unparse()` - Convert UUID byte array (ala parse()) into a string**
114 function unparse(buf, offset?) : string {
115 let i = offset || 0, bth = _byteToHex;
114 function _unparse(buf, offset?): string {
115 let i = offset || 0, bth = _byteToHex;
116 116 return bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] +
117 117 bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' +
118 118 bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] +
119 119 bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] +
120 120 bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]];
121 121 }
122 122
123 123 // **`v1()` - Generate time-based UUID**
124 124 //
125 125 // Inspired by https://github.com/LiosK/UUID.js
126 126 // and http://docs.python.org/library/uuid.html
127 127
128 128 // random #'s we need to init node and clockseq
129 129 let _seedBytes = _rng();
130 130
131 131 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit =
132 132 // 1)
133 133 let _nodeId = [
134 134 _seedBytes[0] | 0x01,
135 135 _seedBytes[1],
136 136 _seedBytes[2],
137 137 _seedBytes[3],
138 138 _seedBytes[4],
139 139 _seedBytes[5]
140 140 ];
141 141
142 142 // Per 4.2.2, randomize (14 bit) clockseq
143 143 let _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
144 144
145 145 // Previous uuid creation time
146 let _lastMSecs = 0, _lastNSecs = 0;
146 let _lastMSecs = 0, _lastNSecs = 0;
147 147
148 148 // See https://github.com/broofa/node-uuid for API details
149 function v1(options?, buf?, offset?) : string {
149 function _v1(options?, buf?, offset?): string {
150 150 let i = buf && offset || 0;
151 151 let b = buf || [];
152 152
153 153 options = options || {};
154 154
155 155 let clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;
156 156
157 157 // UUID timestamps are 100 nano-second units since the Gregorian
158 158 // epoch,
159 159 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
160 160 // time is handled internally as 'msecs' (integer milliseconds) and
161 161 // 'nsecs'
162 162 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01
163 163 // 00:00.
164 164 let msecs = (options.msecs != null) ? options.msecs : new Date()
165 165 .getTime();
166 166
167 167 // Per 4.2.1.2, use count of uuid's generated during the current
168 168 // clock
169 169 // cycle to simulate higher resolution clock
170 170 let nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;
171 171
172 172 // Time since last uuid creation (in msecs)
173 173 let dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs) / 10000;
174 174
175 175 // Per 4.2.1.2, Bump clockseq on clock regression
176 176 if (dt < 0 && options.clockseq == null) {
177 177 clockseq = clockseq + 1 & 0x3fff;
178 178 }
179 179
180 180 // Reset nsecs if clock regresses (new clockseq) or we've moved onto
181 181 // a new
182 182 // time interval
183 183 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {
184 184 nsecs = 0;
185 185 }
186 186
187 187 // Per 4.2.1.2 Throw error if too many uuids are requested
188 188 if (nsecs >= 10000) {
189 189 throw new Error(
190 190 'uuid.v1(): Can\'t create more than 10M uuids/sec');
191 191 }
192 192
193 193 _lastMSecs = msecs;
194 194 _lastNSecs = nsecs;
195 195 _clockseq = clockseq;
196 196
197 197 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
198 198 msecs += 12219292800000;
199 199
200 200 // `time_low`
201 201 let tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
202 202 b[i++] = tl >>> 24 & 0xff;
203 203 b[i++] = tl >>> 16 & 0xff;
204 204 b[i++] = tl >>> 8 & 0xff;
205 205 b[i++] = tl & 0xff;
206 206
207 207 // `time_mid`
208 208 let tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
209 209 b[i++] = tmh >>> 8 & 0xff;
210 210 b[i++] = tmh & 0xff;
211 211
212 212 // `time_high_and_version`
213 213 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
214 214 b[i++] = tmh >>> 16 & 0xff;
215 215
216 216 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
217 217 b[i++] = clockseq >>> 8 | 0x80;
218 218
219 219 // `clock_seq_low`
220 220 b[i++] = clockseq & 0xff;
221 221
222 222 // `node`
223 223 let node = options.node || _nodeId;
224 224 for (let n = 0; n < 6; n++) {
225 225 b[i + n] = node[n];
226 226 }
227 227
228 return buf ? buf : unparse(b);
228 return buf ? buf : _unparse(b);
229 229 }
230 230
231 231 // **`v4()` - Generate random UUID**
232 232
233 233 // See https://github.com/broofa/node-uuid for API details
234 function v4(options?, buf?, offset?) : string {
234 function _v4(options?, buf?, offset?): string {
235 235 // Deprecated - 'format' argument, as supported in v1.2
236 236 let i = buf && offset || 0;
237 237
238 238 if (typeof (options) === 'string') {
239 239 buf = (options === 'binary') ? new BufferClass(16) : null;
240 240 options = null;
241 241 }
242 242 options = options || {};
243 243
244 244 let rnds = options.random || (options.rng || _rng)();
245 245
246 246 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
247 247 rnds[6] = (rnds[6] & 0x0f) | 0x40;
248 248 rnds[8] = (rnds[8] & 0x3f) | 0x80;
249 249
250 250 // Copy bytes to buffer, if provided
251 251 if (buf) {
252 252 for (let ii = 0; ii < 16; ii++) {
253 253 buf[i + ii] = rnds[ii];
254 254 }
255 255 }
256 256
257 return buf || unparse(rnds);
257 return buf || _unparse(rnds);
258 }
259
260 export function Uuid() {
261
258 262 }
259 263
260 // Export public API
261 const empty = "00000000-0000-0000-0000-000000000000";
262
263 interface uuid {
264 (options?, buf?, offset?) : string;
265 v1(options?, buf?, offset?) : string;
266 v4(options?, buf?, offset?) : string;
267 readonly empty: string;
268 parse(s, buf?, offset?) : Array<string>;
269 unparse(buf, offset?) : string;
270 }
271
272 export = <uuid>(() =>{
273 var f : any = function(options?, buf?, offset?) : string {
274 return v4(options, buf, offset);
275 };
276 f.v1 = v1;
277 f.v4 = v4;
278 f.empty = empty;
279 f.parse = parse;
280 f.unparse = unparse;
281 return f;
282 })(); No newline at end of file
264 export namespace Uuid {
265 export const v4 = _v4;
266 export const v1 = _v1;
267 export const empty = "00000000-0000-0000-0000-000000000000";
268 export const parse = _parse;
269 export const unparse = _unparse;
270 } No newline at end of file
@@ -1,236 +1,279
1 1 export function argumentNotNull(arg, name) {
2 2 if (arg === null || arg === undefined)
3 3 throw new Error("The argument " + name + " can't be null or undefined");
4 4 }
5 5
6 6 export function argumentNotEmptyString(arg, name) {
7 7 if (typeof (arg) !== "string" || !arg.length)
8 8 throw new Error("The argument '" + name + "' must be a not empty string");
9 9 }
10 10
11 11 export function argumentNotEmptyArray(arg, name) {
12 12 if (!(arg instanceof Array) || !arg.length)
13 13 throw new Error("The argument '" + name + "' must be a not empty array");
14 14 }
15 15
16 16 export function argumentOfType(arg, type, name) {
17 17 if (!(arg instanceof type))
18 18 throw new Error("The argument '" + name + "' type doesn't match");
19 19 }
20 20
21 21 export function isNull(arg) {
22 22 return (arg === null || arg === undefined);
23 23 }
24 24
25 25 export function isPrimitive(arg) {
26 26 return (arg === null || arg === undefined || typeof (arg) === "string" ||
27 27 typeof (arg) === "number" || typeof (arg) === "boolean");
28 28 }
29 29
30 30 export function isInteger(arg) {
31 31 return parseInt(arg) == arg;
32 32 }
33 33
34 34 export function isNumber(arg) {
35 35 return parseFloat(arg) == arg;
36 36 }
37 37
38 38 export function isString(val) {
39 39 return typeof (val) == "string" || val instanceof String;
40 40 }
41 41
42 42 export function isNullOrEmptyString(str) {
43 43 if (str === null || str === undefined ||
44 44 ((typeof (str) == "string" || str instanceof String) && str.length === 0))
45 45 return true;
46 46 }
47 47
48 export function isNotEmptyArray(arg) {
48 export function isNotEmptyArray(arg): arg is Array<any> {
49 49 return (arg instanceof Array && arg.length > 0);
50 50 }
51 51
52 52 /**
53 53 * Выполняет метод для каждого элемента массива, останавливается, когда
54 54 * либо достигнут конец массива, либо функция <c>cb</c> вернула
55 55 * значение.
56 56 *
57 57 * @param {Array | Object} obj массив элементов для просмотра
58 58 * @param {Function} cb функция, вызываемая для каждого элемента
59 59 * @param {Object} thisArg значение, которое будет передано в качестве
60 60 * <c>this</c> в <c>cb</c>.
61 61 * @returns Результат вызова функции <c>cb</c>, либо <c>undefined</c>
62 62 * если достигнут конец массива.
63 63 */
64 export function each(obj, cb, thisArg) {
64 export function each(obj, cb, thisArg?) {
65 65 argumentNotNull(cb, "cb");
66 66 var i, x;
67 67 if (obj instanceof Array) {
68 68 for (i = 0; i < obj.length; i++) {
69 69 x = cb.call(thisArg, obj[i], i);
70 70 if (x !== undefined)
71 71 return x;
72 72 }
73 73 } else {
74 74 var keys = Object.keys(obj);
75 75 for (i = 0; i < keys.length; i++) {
76 76 var k = keys[i];
77 77 x = cb.call(thisArg, obj[k], k);
78 78 if (x !== undefined)
79 79 return x;
80 80 }
81 81 }
82 82 }
83 83
84 /** Copies property values from a source object to the destination and returns
85 * the destination onject.
86 *
87 * @param dest The destination object into which properties from the source
88 * object will be copied.
89 * @param source The source of values which will be copied to the destination
90 * object.
91 * @param template An optional parameter specifies which properties should be
92 * copied from the source and how to map them to the destination. If the
93 * template is an array it contains the list of property names to copy from the
94 * source to the destination. In case of object the templates contains the map
95 * where keys are property names in the source and the values are property
96 * names in the destination object. If the template isn't specified then the
97 * own properties of the source are entirely copied to the destination.
98 *
99 */
100 export function mixin<T,S>(dest: T, source: S, template?: string[] | object) : T & S {
101 argumentNotNull(dest, "to");
102 let _res = <T & S>dest;
103
104 if (template instanceof Array) {
105 for(let i = 0; i < template.length; i++) {
106 let p = template[i];
107 if (p in source)
108 _res[p] = source[p];
109 }
110 } else if (template) {
111 let keys = Object.keys(source);
112 for(let i = 0; i < keys.length; i++) {
113 let p = keys[i];
114 if (p in template)
115 _res[template[p]] = source[p];
116 }
117 } else {
118 let keys = Object.keys(source);
119 for(let i = 0; i < keys.length; i++) {
120 let p = keys[i];
121 _res[p] = source[p];
122 }
123 }
124
125 return _res;
126 }
127
84 128 /** Wraps the specified function to emulate an asynchronous execution.
85 129 * @param{Object} thisArg [Optional] Object which will be passed as 'this' to the function.
86 130 * @param{Function|String} fn [Required] Function wich will be wrapped.
87 131 */
88 export function async(_fn: (...args: any[]) => any, thisArg) : (...args: any[]) => PromiseLike<any> {
132 export function async(_fn: (...args: any[]) => any, thisArg): (...args: any[]) => PromiseLike<any> {
89 133 let fn = _fn;
90 134
91 135 if (arguments.length == 2 && !(fn instanceof Function))
92 136 fn = thisArg[fn];
93 137
94 138 if (fn == null)
95 139 throw new Error("The function must be specified");
96 140
97 function wrapresult(x, e?) : PromiseLike<any> {
141 function wrapresult(x, e?): PromiseLike<any> {
98 142 if (e) {
99 143 return {
100 144 then: function (cb, eb) {
101 145 try {
102 146 return eb ? wrapresult(eb(e)) : this;
103 147 } catch (e2) {
104 148 return wrapresult(null, e2);
105 149 }
106 150 }
107 151 };
108 152 } else {
109 153 if (x && x.then)
110 154 return x;
111 155 return {
112 156 then: function (cb) {
113 157 try {
114 158 return cb ? wrapresult(cb(x)) : this;
115 159 } catch (e2) {
116 160 return wrapresult(e2);
117 161 }
118 162 }
119 163 };
120 164 }
121 165 }
122 166
123 167 return function () {
124 168 try {
125 169 return wrapresult(fn.apply(thisArg, arguments));
126 170 } catch (e) {
127 171 return wrapresult(null, e);
128 172 }
129 173 };
130 174 }
131 175
132 export function delegate(target, _method: (string | Function)) {
133 let method : Function;
176 export function delegate<T, K extends keyof T>(target: T, _method: (K | Function)) {
177 let method;
134 178
135 179 if (!(_method instanceof Function)) {
136 180 argumentNotNull(target, "target");
137 181 method = target[_method];
182 if (!(method instanceof Function))
183 throw new Error("'method' argument must be a Function or a method name");
138 184 } else {
139 185 method = _method;
140 186 }
141 187
142 if (!(method instanceof Function))
143 throw new Error("'method' argument must be a Function or a method name");
144
145 188 return function () {
146 189 return method.apply(target, arguments);
147 190 };
148 191 }
149 192
150 193 /**
151 194 * Для каждого элемента массива вызывает указанную функцию и сохраняет
152 195 * возвращенное значение в массиве результатов.
153 196 *
154 197 * @remarks cb может выполняться асинхронно, при этом одновременно будет
155 198 * только одна операция.
156 199 *
157 200 * @async
158 201 */
159 202 export function pmap(items, cb) {
160 203 argumentNotNull(cb, "cb");
161 204
162 205 if (items && items.then instanceof Function)
163 206 return items.then(function (data) {
164 207 return pmap(data, cb);
165 208 });
166 209
167 210 if (isNull(items) || !items.length)
168 211 return items;
169 212
170 213 var i = 0,
171 214 result = [];
172 215
173 216 function next() {
174 217 var r, ri;
175 218
176 219 function chain(x) {
177 220 result[ri] = x;
178 221 return next();
179 222 }
180 223
181 224 while (i < items.length) {
182 225 r = cb(items[i], i);
183 226 ri = i;
184 227 i++;
185 228 if (r && r.then) {
186 229 return r.then(chain);
187 230 } else {
188 231 result[ri] = r;
189 232 }
190 233 }
191 234 return result;
192 235 }
193 236
194 237 return next();
195 238 }
196 239
197 240 /**
198 241 * Выбирает первый элемент из последовательности, или обещания, если в
199 242 * качестве параметра используется обещание, оно должно вернуть массив.
200 243 *
201 244 * @param {Function} cb обработчик результата, ему будет передан первый
202 245 * элемент последовательности в случае успеха
203 246 * @param {Function} err обработчик исключения, если массив пустой, либо
204 247 * не массив
205 248 *
206 249 * @remarks Если не указаны ни cb ни err, тогда функция вернет либо
207 250 * обещание, либо первый элемент.
208 251 * @async
209 252 */
210 253 export function first(sequence: any, cb: Function, err: Function) {
211 254 if (sequence) {
212 255 if (sequence.then instanceof Function) {
213 256 return sequence.then(function (res) {
214 257 return first(res, cb, err);
215 258 }, err);
216 259 } else if (sequence && "length" in sequence) {
217 260 if (sequence.length === 0) {
218 261 if (err)
219 262 return err(new Error("The sequence is empty"));
220 263 else
221 264 throw new Error("The sequence is empty");
222 265 }
223 266 return cb ? cb(sequence[0]) : sequence[0];
224 267 }
225 268 }
226 269
227 270 if (err)
228 271 return err(new Error("The sequence is required"));
229 272 else
230 273 throw new Error("The sequence is required");
231 274 }
232 275
233 276 export function destroy(d: any) {
234 277 if (d && 'destroy' in d)
235 278 d.destroy();
236 279 } No newline at end of file
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
1 NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now