This repository was archived by the owner on Feb 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathyok.ts
435 lines (358 loc) · 13.2 KB
/
yok.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
import * as path from "path";
import { annotate, isPromise } from "./helpers";
import { ERROR_NO_VALID_SUBCOMMAND_FORMAT } from "./constants";
import { CommandsDelimiters } from "./constants";
let indent = "";
function trace(formatStr: string, ...args: any[]) {
// uncomment following lines when debugging dependency injection
// var args = [];
// for (var _i = 1; _i < arguments.length; _i++) {
// args[_i - 1] = arguments[_i];
// }
// var util = require("util");
// console.log(util.format.apply(util, [indent + formatStr].concat(args)));
}
function pushIndent() {
indent += " ";
}
function popIndent() {
indent = indent.slice(0, -2);
}
function forEachName(names: any, action: (name: string) => void): void {
if (_.isString(names)) {
action(names);
} else {
names.forEach(action);
}
}
export function register(...rest: any[]) {
return function (target: any): void {
// TODO: Check if 'rest' has more arguments that have to be registered
$injector.register(rest[0], target);
};
}
export interface IDependency {
require?: string;
resolver?: () => any;
instance?: any;
shared?: boolean;
}
export class Yok implements IInjector {
public overrideAlreadyRequiredModule: boolean = false;
constructor() {
this.register("injector", this);
}
private COMMANDS_NAMESPACE: string = "commands";
private modules: {
[name: string]: IDependency;
} = {};
private resolutionProgress: any = {};
private hierarchicalCommands: IDictionary<string[]> = {};
public requireCommand(names: any, file: string): void {
forEachName(names, (commandName) => {
const commands = commandName.split(CommandsDelimiters.HierarchicalCommand);
if (commands.length > 1) {
if (_.startsWith(commands[1], '*') && this.modules[this.createCommandName(commands[0])]) {
throw new Error("Default commands should be required before child commands");
}
const parentCommandName = commands[0];
if (!this.hierarchicalCommands[parentCommandName]) {
this.hierarchicalCommands[parentCommandName] = [];
}
this.hierarchicalCommands[parentCommandName].push(_.tail(commands).join(CommandsDelimiters.HierarchicalCommand));
}
if (commands.length > 1 && !this.modules[this.createCommandName(commands[0])]) {
this.require(this.createCommandName(commands[0]), file);
if (commands[1] && !commandName.match(/\|\*/)) {
this.require(this.createCommandName(commandName), file);
}
} else {
this.require(this.createCommandName(commandName), file);
}
});
}
public require(names: any, file: string): void {
forEachName(names, (name) => this.requireOne(name, file));
}
public publicApi: any = {
__modules__: {}
};
public requirePublic(names: any, file: string): void {
forEachName(names, (name) => {
this.requireOne(name, file);
this.resolvePublicApi(name, file);
});
}
public requirePublicClass(names: any, file: string): void {
forEachName(names, (name) => {
this.requireOne(name, file);
this.addClassToPublicApi(name, file);
});
}
private addClassToPublicApi(name: string, file: string): void {
Object.defineProperty(this.publicApi, name, {
get: () => {
return this.resolveInstance(name);
}
});
}
private resolvePublicApi(name: string, file: string): void {
Object.defineProperty(this.publicApi, name, {
get: () => {
this.resolveInstance(name);
return this.publicApi.__modules__[name];
}
});
}
private resolveInstance(name: string): any {
let classInstance = this.modules[name].instance;
if (!classInstance) {
classInstance = this.resolve(name);
}
return classInstance;
}
private requireOne(name: string, file: string): void {
const relativePath = path.join("../", file);
const dependency: IDependency = {
require: require("fs").existsSync(path.join(__dirname, relativePath + ".js")) ? relativePath : file,
shared: true
};
if (!this.modules[name] || this.overrideAlreadyRequiredModule) {
this.modules[name] = dependency;
} else {
throw new Error(`module '${name}' require'd twice.`);
}
}
public registerCommand(names: any, resolver: any): void {
forEachName(names, (name) => {
const commands = name.split(CommandsDelimiters.HierarchicalCommand);
this.register(this.createCommandName(name), resolver);
if (commands.length > 1) {
this.createHierarchicalCommand(commands[0]);
}
});
}
private getDefaultCommand(name: string, commandArguments: string[]) {
const subCommands = this.hierarchicalCommands[name];
const defaultCommand = _.find(subCommands, command => _.some(command.split(CommandsDelimiters.HierarchicalCommand), c => _.startsWith(c, CommandsDelimiters.DefaultCommandSymbol)));
return defaultCommand;
}
public buildHierarchicalCommand(parentCommandName: string, commandLineArguments: string[]): any {
let currentSubCommandName: string, finalSubCommandName: string, matchingSubCommandName: string;
const subCommands = this.hierarchicalCommands[parentCommandName];
let remainingArguments = commandLineArguments;
let finalRemainingArguments = commandLineArguments;
_.each(commandLineArguments, arg => {
arg = arg.toLowerCase();
currentSubCommandName = currentSubCommandName ? this.getHierarchicalCommandName(currentSubCommandName, arg) : arg;
remainingArguments = _.tail(remainingArguments);
if (matchingSubCommandName = _.find(subCommands, sc => sc === currentSubCommandName || sc === `${CommandsDelimiters.DefaultCommandSymbol}${currentSubCommandName}`)) {
finalSubCommandName = matchingSubCommandName;
finalRemainingArguments = remainingArguments;
}
});
if (!finalSubCommandName) {
finalSubCommandName = this.getDefaultCommand(parentCommandName, commandLineArguments) || "";
finalRemainingArguments = _.difference(commandLineArguments, finalSubCommandName
.split(CommandsDelimiters.HierarchicalCommand)
.map(command => _.startsWith(command, CommandsDelimiters.DefaultCommandSymbol) ? command.substr(1) : command));
}
if (finalSubCommandName) {
return { commandName: this.getHierarchicalCommandName(parentCommandName, finalSubCommandName), remainingArguments: finalRemainingArguments };
}
}
private createHierarchicalCommand(name: string) {
const factory = () => {
return {
disableAnalytics: true,
isHierarchicalCommand: true,
execute: async (args: string[]): Promise<void> => {
const commandsService = $injector.resolve("commandsService");
let commandName: string = null;
const defaultCommand = this.getDefaultCommand(name, args);
let commandArguments: ICommandArgument[] = [];
if (args.length > 0) {
const hierarchicalCommand = this.buildHierarchicalCommand(name, args);
if (hierarchicalCommand) {
commandName = hierarchicalCommand.commandName;
commandArguments = hierarchicalCommand.remainingArguments;
} else {
commandName = defaultCommand ? this.getHierarchicalCommandName(name, defaultCommand) : "help";
// If we'll execute the default command, but it's full name had been written by the user
// for example "appbuilder cloud list", we have to remove the "list" option from the arguments that we'll pass to the command.
if (_.includes(this.hierarchicalCommands[name], CommandsDelimiters.DefaultCommandSymbol + args[0])) {
commandArguments = _.tail(args);
} else {
commandArguments = args;
}
}
} else {
//Execute only default command without arguments
if (defaultCommand) {
commandName = this.getHierarchicalCommandName(name, defaultCommand);
} else {
commandName = "help";
// Show command-line help
const options = this.resolve("options");
options.help = true;
}
}
await commandsService.tryExecuteCommand(commandName, commandName === "help" ? [name] : commandArguments);
}
};
};
$injector.registerCommand(name, factory);
}
private getHierarchicalCommandName(parentCommandName: string, subCommandName: string) {
return [parentCommandName, subCommandName].join(CommandsDelimiters.HierarchicalCommand);
}
public async isValidHierarchicalCommand(commandName: string, commandArguments: string[]): Promise<boolean> {
if (_.includes(Object.keys(this.hierarchicalCommands), commandName)) {
const subCommands = this.hierarchicalCommands[commandName];
if (subCommands) {
const fullCommandName = this.buildHierarchicalCommand(commandName, commandArguments);
if (!fullCommandName) {
// In case buildHierarchicalCommand doesn't find a valid command
// there isn't a valid command or default with those arguments
const errors = $injector.resolve("errors");
errors.fail(ERROR_NO_VALID_SUBCOMMAND_FORMAT, commandName);
}
return true;
}
}
return false;
}
public isDefaultCommand(commandName: string): boolean {
return commandName.indexOf(CommandsDelimiters.DefaultCommandSymbol) > 0 && commandName.indexOf(CommandsDelimiters.HierarchicalCommand) > 0;
}
public register(name: string, resolver: any, shared?: boolean): void {
shared = shared === undefined ? true : shared;
trace("registered '%s'", name);
const dependency: any = this.modules[name] || {};
dependency.shared = shared;
if (_.isFunction(resolver)) {
dependency.resolver = resolver;
} else {
dependency.instance = resolver;
}
this.modules[name] = dependency;
}
public resolveCommand(name: string): ICommand {
let command: ICommand;
const commandModuleName = this.createCommandName(name);
if (!this.modules[commandModuleName]) {
return null;
}
command = this.resolve(commandModuleName);
return command;
}
public resolve(param: any, ctorArguments?: IDictionary<any>): any {
if (_.isFunction(param)) {
return this.resolveConstructor(<Function>param, ctorArguments);
} else {
return this.resolveByName(<string>param, ctorArguments);
}
}
/* Regex to match dynamic calls in the following format:
#{moduleName.functionName} or
#{moduleName.functionName(param1)} or
#{moduleName.functionName(param1, param2)} - multiple parameters separated with comma are supported
Check dynamicCall method for sample usage of this regular expression and see how to determine the passed parameters
*/
public get dynamicCallRegex(): RegExp {
return /#{([^.]+)\.([^}]+?)(\((.+)\))*}/;
}
public getDynamicCallData(call: string, args?: any[]): any {
const parsed = call.match(this.dynamicCallRegex);
const module = this.resolve(parsed[1]);
if (!args && parsed[3]) {
args = _.map(parsed[4].split(","), arg => arg.trim());
}
return module[parsed[2]].apply(module, args);
}
public async dynamicCall(call: string, args?: any[]): Promise<any> {
const data = this.getDynamicCallData(call, args);
if (isPromise(data)) {
return await data;
}
return data;
}
private resolveConstructor(ctor: Function, ctorArguments?: { [key: string]: any }): any {
annotate(ctor);
const resolvedArgs = ctor.$inject.args.map(paramName => {
if (ctorArguments && ctorArguments.hasOwnProperty(paramName)) {
return ctorArguments[paramName];
} else {
return this.resolve(paramName);
}
});
const name = ctor.$inject.name;
if (name && name[0] === name[0].toUpperCase()) {
return new (<any>ctor)(...resolvedArgs);
} else {
return ctor.apply(null, resolvedArgs);
}
}
private resolveByName(name: string, ctorArguments?: IDictionary<any>): any {
if (name[0] === "$") {
name = name.substr(1);
}
if (this.resolutionProgress[name]) {
throw new Error(`Cyclic dependency detected on dependency '${name}'`);
}
this.resolutionProgress[name] = true;
trace("resolving '%s'", name);
pushIndent();
let dependency: IDependency;
try {
dependency = this.resolveDependency(name);
if (!dependency) {
throw new Error("unable to resolve " + name);
}
if (!dependency.instance || !dependency.shared) {
if (!dependency.resolver) {
throw new Error("no resolver registered for " + name);
}
dependency.instance = this.resolveConstructor(dependency.resolver, ctorArguments);
}
} finally {
popIndent();
delete this.resolutionProgress[name];
}
return dependency.instance;
}
private resolveDependency(name: string): IDependency {
const module = this.modules[name];
if (!module) {
throw new Error("unable to resolve " + name);
}
if (module.require) {
require(module.require);
}
return module;
}
public getRegisteredCommandsNames(includeDev: boolean): string[] {
const modulesNames: string[] = _.keys(this.modules);
const commandsNames: string[] = _.filter(modulesNames, moduleName => _.startsWith(moduleName, `${this.COMMANDS_NAMESPACE}.`));
let commands = _.map(commandsNames, (commandName: string) => commandName.substr(this.COMMANDS_NAMESPACE.length + 1));
if (!includeDev) {
commands = _.reject(commands, (command) => _.startsWith(command, "dev-"));
}
return commands;
}
public getChildrenCommandsNames(commandName: string): string[] {
return this.hierarchicalCommands[commandName];
}
private createCommandName(name: string) {
return `${this.COMMANDS_NAMESPACE}.${name}`;
}
public dispose(): void {
Object.keys(this.modules).forEach((moduleName) => {
const instance = this.modules[moduleName].instance;
if (instance && instance.dispose && instance !== this) {
instance.dispose();
}
});
}
}
export let injector = new Yok();