-
-
Notifications
You must be signed in to change notification settings - Fork 201
Expand file tree
/
Copy pathconfig-transformer.ts
More file actions
403 lines (347 loc) · 10.1 KB
/
config-transformer.ts
File metadata and controls
403 lines (347 loc) · 10.1 KB
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
import {
BooleanLiteral,
ExportAssignment,
ExpressionStatement,
Identifier,
Node,
NumericLiteral,
ObjectLiteralElementLike,
ObjectLiteralExpression,
Project,
PropertyAccessExpression,
PropertyAssignment,
ScriptKind,
ShorthandPropertyAssignment,
SourceFile,
StringLiteral,
SyntaxKind,
} from "ts-morph";
export type SupportedConfigValues =
| string
| number
| boolean
| { [key: string]: SupportedConfigValues }
| any[];
export interface IConfigTransformer {
/**
* Sets or updates the value at `path` and returns the updated content
* @param {string} path path to the property, supports dot notation.
* @param {SupportedConfigValues} value the value to set at `path`.
* @returns {string} the updated content
*/
setValue(path: string, value: SupportedConfigValues): string;
}
export class ConfigTransformer implements IConfigTransformer {
private project: Project;
private config: SourceFile;
private readonly scriptKind: ScriptKind;
constructor(content: string) {
this.project = new Project({
compilerOptions: {
allowJs: true,
},
});
this.scriptKind = content.includes("module.exports")
? ScriptKind.JS
: ScriptKind.TS;
this.config = this.project.createSourceFile(
"virtual_nativescript.config.ts",
content,
{
scriptKind: this.scriptKind,
},
);
}
private getDefaultExportValue(): ObjectLiteralExpression {
let exportValue;
if (this.scriptKind === ScriptKind.JS) {
this.config.getStatements().find((statement: any) => {
try {
if (statement.getKind() === SyntaxKind.ExpressionStatement) {
const expression = (
statement as ExpressionStatement
).getExpressionIfKind(SyntaxKind.BinaryExpression);
const leftSide = expression.getLeft() as PropertyAccessExpression;
if (leftSide.getFullText().trim() === "module.exports") {
exportValue = expression.getRight();
return true;
}
}
} catch (err) {
return false;
}
});
} else {
const exports = this.config
.getDefaultExportSymbolOrThrow()
.getDeclarations()[0] as ExportAssignment;
const expr = exports.getExpression();
exportValue =
expr.getChildCount() > 0
? (expr.getChildAtIndex(0) as ObjectLiteralExpression)
: expr;
}
if (!Node.isObjectLiteralExpression(exportValue)) {
throw new Error("default export must be an object!");
}
return exportValue;
}
private getProperty(
key: string,
parent: ObjectLiteralExpression = null,
): ObjectLiteralElementLike {
if (key.includes(".")) {
const parts = key.split(".");
const name = parts.shift();
const property = this.getProperty(name, parent);
// no android key, add it to parent to root
if (!property) {
return undefined;
}
const _parent: any = property.getLastChild((child: any) => {
return Node.isObjectLiteralExpression(child);
}) as ObjectLiteralExpression;
if (!_parent) {
return undefined;
}
// add nonExistent.deep to android: {}
return this.getProperty(parts.join("."), _parent);
}
// if we have a parent, we are reading the property from it
if (parent) {
return parent.getProperty(key);
}
// otherwise we just read it from the root exports object
return this.getProperty(key, this.getDefaultExportValue());
}
private addProperty(
key: string,
value: SupportedConfigValues | {},
parent: ObjectLiteralExpression = null,
): any {
if (key.includes(".")) {
const parts = key.split(".");
const name = parts.shift();
let property = this.getProperty(name, parent);
if (!property) {
property = this.addProperty(
name,
{},
parent || this.getDefaultExportValue(),
);
}
const _parent: any = property.getLastChild((child: any) => {
return Node.isObjectLiteralExpression(child);
}) as ObjectLiteralExpression;
if (!_parent) {
throw new Error(`Could not add property '${parts[0]}'.`);
}
return this.addProperty(parts.join("."), value, _parent);
}
if (parent) {
return parent.addPropertyAssignment({
name: key,
initializer: this.createInitializer(value),
});
}
return this.addProperty(key, value, this.getDefaultExportValue());
}
private createInitializer(value: SupportedConfigValues): any {
if (typeof value === "string") {
return `'${value}'`;
} else if (typeof value === "number" || typeof value === "boolean") {
return `${value}`;
} else if (Array.isArray(value)) {
return `[${value.map((v) => this.createInitializer(v)).join(", ")}]`;
} else if (typeof value === "object" && value !== null) {
const properties = Object.entries(value)
.map(([key, val]) => `${key}: ${this.createInitializer(val)}`)
.join(", ");
return `{ ${properties} }`;
}
return `{}`;
}
private isBooleanLiteralNode(initializer: any): boolean {
return (
initializer?.getKind() === SyntaxKind.TrueKeyword ||
initializer?.getKind() === SyntaxKind.FalseKeyword
);
}
private replaceInitializer(
initializer: any,
newValue: SupportedConfigValues,
) {
return initializer.replaceWithText(this.createInitializer(newValue));
}
private setInitializerValue(
initializer: any,
newValue: SupportedConfigValues,
) {
if (Node.isStringLiteral(initializer)) {
if (typeof newValue !== "string") {
return this.replaceInitializer(initializer, newValue);
}
return (initializer as StringLiteral).setLiteralValue(newValue as string);
}
if (Node.isNumericLiteral(initializer)) {
if (typeof newValue !== "number") {
return this.replaceInitializer(initializer, newValue);
}
return (initializer as NumericLiteral).setLiteralValue(
newValue as number,
);
}
if (this.isBooleanLiteralNode(initializer)) {
if (typeof newValue !== "boolean") {
return this.replaceInitializer(initializer, newValue);
}
return (initializer as BooleanLiteral).setLiteralValue(
newValue as boolean,
);
}
if (
Node.isArrayLiteralExpression(initializer) ||
Node.isObjectLiteralExpression(initializer)
) {
return this.replaceInitializer(initializer, newValue);
}
if (Node.isIdentifier(initializer)) {
return this.setIdentifierValue(initializer as Identifier, newValue);
}
throw new Error("Unsupported value type: " + initializer.getKindName());
}
private getInitializerValue(initializer: any): any {
if (Node.isStringLiteral(initializer)) {
return (initializer as StringLiteral).getLiteralValue();
}
if (Node.isNumericLiteral(initializer)) {
return (initializer as NumericLiteral).getLiteralValue();
}
if (this.isBooleanLiteralNode(initializer)) {
return (initializer as BooleanLiteral).getLiteralValue();
}
if (Node.isArrayLiteralExpression(initializer)) {
return initializer
.getElements()
.map((element: any) => this.getInitializerValue(element));
}
if (Node.isObjectLiteralExpression(initializer)) {
const result: Record<string, SupportedConfigValues> = {};
for (const property of initializer.getProperties()) {
if (!Node.isPropertyAssignment(property)) {
continue;
}
const name = property.getNameNode().getText().replace(/['\"]/g, "");
result[name] = this.getInitializerValue(
property.getInitializerOrThrow(),
);
}
return result;
}
if (Node.isIdentifier(initializer)) {
return this.getIdentifierValue(initializer as Identifier);
}
throw new Error("Unsupported value type: " + initializer.getKindName());
}
private getIdentifierValue(identifier: Identifier): any {
const decl = this.config.getVariableDeclarationOrThrow(
identifier.getText(),
);
const initializer = decl.getInitializerOrThrow();
return this.getInitializerValue(initializer);
}
private setIdentifierValue(
identifier: Identifier,
newValue: SupportedConfigValues,
) {
const decl = this.config.getVariableDeclarationOrThrow(
identifier.getText(),
);
const initializer = decl.getInitializerOrThrow();
this.setInitializerValue(initializer, newValue);
}
private getPropertyValue(objectProperty: ObjectLiteralElementLike) {
if (!objectProperty) {
return undefined;
}
let initializer;
if (
objectProperty instanceof PropertyAssignment ||
objectProperty instanceof ShorthandPropertyAssignment
) {
initializer = objectProperty.getInitializer();
} else {
throw new Error(
"getPropertyValue Unsupported value found: " +
objectProperty.getKindName(),
);
}
if (Node.isStringLiteral(initializer)) {
return (initializer as StringLiteral).getLiteralValue();
}
if (Node.isNumericLiteral(initializer)) {
return (initializer as NumericLiteral).getLiteralValue();
}
if (this.isBooleanLiteralNode(initializer)) {
return (initializer as BooleanLiteral).getLiteralValue();
}
if (Node.isArrayLiteralExpression(initializer)) {
return initializer
.getElements()
.map((element: any) => this.getInitializerValue(element));
}
if (Node.isObjectLiteralExpression(initializer)) {
const result: Record<string, SupportedConfigValues> = {};
for (const property of initializer.getProperties()) {
if (!Node.isPropertyAssignment(property)) {
continue;
}
const name = property.getNameNode().getText().replace(/['\"]/g, "");
result[name] = this.getInitializerValue(
property.getInitializerOrThrow(),
);
}
return result;
}
if (Node.isIdentifier(initializer)) {
return this.getIdentifierValue(initializer as Identifier);
}
}
private setPropertyValue(
objectProperty: any,
newValue: SupportedConfigValues,
) {
let initializer;
if (
objectProperty instanceof PropertyAssignment ||
objectProperty instanceof ShorthandPropertyAssignment
) {
initializer = objectProperty.getInitializer();
} else {
throw new Error("Unsupported value found.");
}
this.setInitializerValue(initializer, newValue);
}
/**
* @internal
*/
getFullText() {
return this.config.getFullText();
}
/**
* @internal
*/
getValue(key: string) {
return this.getPropertyValue(this.getProperty(key));
}
public setValue(key: string, value: SupportedConfigValues): string {
const property = this.getProperty(key);
if (!property) {
// add new property
this.addProperty(key, value);
} else {
this.setPropertyValue(property, value);
}
return this.getFullText();
}
}