cloesce 0.0.4-unstable.9 → 0.0.5-unstable.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,694 +1,882 @@
1
- import { Node as MorphNode, SyntaxKind, Scope, } from "ts-morph";
2
- import { Either, HttpVerb, ExtractorError, ExtractorErrorCode, } from "../common.js";
1
+ import { Node as MorphNode, SyntaxKind, Scope } from "ts-morph";
2
+ import { HttpVerb, defaultMediaType } from "../ast.js";
3
3
  import { TypeFormatFlags } from "typescript";
4
+ import { ExtractorError, ExtractorErrorCode } from "./err.js";
5
+ import { Either } from "../ui/common.js";
4
6
  var AttributeDecoratorKind;
5
7
  (function (AttributeDecoratorKind) {
6
- AttributeDecoratorKind["PrimaryKey"] = "PrimaryKey";
7
- AttributeDecoratorKind["ForeignKey"] = "ForeignKey";
8
- AttributeDecoratorKind["OneToOne"] = "OneToOne";
9
- AttributeDecoratorKind["OneToMany"] = "OneToMany";
10
- AttributeDecoratorKind["ManyToMany"] = "ManyToMany";
11
- AttributeDecoratorKind["DataSource"] = "DataSource";
8
+ AttributeDecoratorKind["PrimaryKey"] = "PrimaryKey";
9
+ AttributeDecoratorKind["ForeignKey"] = "ForeignKey";
10
+ AttributeDecoratorKind["OneToOne"] = "OneToOne";
11
+ AttributeDecoratorKind["OneToMany"] = "OneToMany";
12
+ AttributeDecoratorKind["ManyToMany"] = "ManyToMany";
13
+ AttributeDecoratorKind["DataSource"] = "DataSource";
12
14
  })(AttributeDecoratorKind || (AttributeDecoratorKind = {}));
13
15
  var ClassDecoratorKind;
14
16
  (function (ClassDecoratorKind) {
15
- ClassDecoratorKind["D1"] = "D1";
16
- ClassDecoratorKind["WranglerEnv"] = "WranglerEnv";
17
- ClassDecoratorKind["PlainOldObject"] = "PlainOldObject";
18
- ClassDecoratorKind["CRUD"] = "CRUD";
17
+ ClassDecoratorKind["D1"] = "D1";
18
+ ClassDecoratorKind["WranglerEnv"] = "WranglerEnv";
19
+ ClassDecoratorKind["PlainOldObject"] = "PlainOldObject";
20
+ ClassDecoratorKind["Service"] = "Service";
21
+ ClassDecoratorKind["CRUD"] = "CRUD";
19
22
  })(ClassDecoratorKind || (ClassDecoratorKind = {}));
20
23
  var ParameterDecoratorKind;
21
24
  (function (ParameterDecoratorKind) {
22
- ParameterDecoratorKind["Inject"] = "Inject";
25
+ ParameterDecoratorKind["Inject"] = "Inject";
23
26
  })(ParameterDecoratorKind || (ParameterDecoratorKind = {}));
24
27
  export class CidlExtractor {
25
- projectName;
26
- version;
27
- constructor(projectName, version) {
28
- this.projectName = projectName;
29
- this.version = version;
30
- }
31
- extract(project) {
32
- const models = {};
33
- const poos = {};
34
- const wranglerEnvs = [];
35
- let app_source = null;
36
- for (const sourceFile of project.getSourceFiles()) {
37
- if (sourceFile.getBaseName() === "app.cloesce.ts" ||
38
- sourceFile.getBaseName() === "seed__app.cloesce.ts" // hardcoding for tests
39
- ) {
40
- const app = CidlExtractor.app(sourceFile);
41
- if (app.isLeft()) {
42
- return app;
43
- }
44
- app_source = app.unwrap();
45
- }
46
- for (const classDecl of sourceFile.getClasses()) {
47
- const notExportedErr = err(ExtractorErrorCode.MissingExport, (e) => {
48
- e.context = classDecl.getName();
49
- e.snippet = classDecl.getText();
50
- });
51
- if (hasDecorator(classDecl, ClassDecoratorKind.D1)) {
52
- if (!classDecl.isExported())
53
- return notExportedErr;
54
- const result = CidlExtractor.model(classDecl, sourceFile);
55
- // Error: propogate from models
56
- if (result.isLeft()) {
57
- result.value.addContext((prev) => `${classDecl.getName()}.${prev}`);
58
- return result;
59
- }
60
- models[result.unwrap().name] = result.unwrap();
61
- continue;
62
- }
63
- if (hasDecorator(classDecl, ClassDecoratorKind.PlainOldObject)) {
64
- if (!classDecl.isExported())
65
- return notExportedErr;
66
- const result = CidlExtractor.poo(classDecl, sourceFile);
67
- // Error: propogate from models
68
- if (result.isLeft()) {
69
- result.value.addContext((prev) => `${classDecl.getName()}.${prev}`);
70
- return result;
71
- }
72
- poos[result.unwrap().name] = result.unwrap();
73
- continue;
74
- }
75
- if (hasDecorator(classDecl, ClassDecoratorKind.WranglerEnv)) {
76
- // Error: invalid attribute modifier
77
- for (const prop of classDecl.getProperties()) {
78
- const modifierRes = checkAttributeModifier(prop);
79
- if (modifierRes) {
80
- return modifierRes;
81
- }
82
- }
83
- const result = CidlExtractor.env(classDecl, sourceFile);
84
- if (result.isLeft()) {
85
- return result;
86
- }
87
- wranglerEnvs.push(result.unwrap());
88
- }
89
- }
90
- }
91
- // Error: A wrangler environment is required
92
- if (wranglerEnvs.length < 1) {
93
- return err(ExtractorErrorCode.MissingWranglerEnv);
94
- }
95
- // Error: Only one wrangler environment can exist
96
- if (wranglerEnvs.length > 1) {
97
- return err(ExtractorErrorCode.TooManyWranglerEnvs, (e) => (e.context = wranglerEnvs.map((w) => w.name).toString()));
98
- }
99
- return Either.right({
100
- version: this.version,
101
- project_name: this.projectName,
102
- language: "TypeScript",
103
- wrangler_env: wranglerEnvs[0],
104
- models,
105
- poos,
106
- app_source,
107
- });
108
- }
109
- static app(sourceFile) {
110
- const symbol = sourceFile.getDefaultExportSymbol();
111
- const decl = symbol?.getDeclarations()[0];
112
- if (!decl) {
113
- return err(ExtractorErrorCode.AppMissingDefaultExport);
114
- }
115
- const getTypeText = () => {
116
- let type = undefined;
117
- if (MorphNode.isExportAssignment(decl)) {
118
- type = decl.getExpression()?.getType();
119
- }
120
- if (MorphNode.isVariableDeclaration(decl)) {
121
- type = decl.getInitializer()?.getType();
122
- }
123
- return type?.getText(undefined, TypeFormatFlags.UseAliasDefinedOutsideCurrentScope);
124
- };
125
- const typeText = getTypeText();
126
- if (typeText === "CloesceApp") {
127
- return Either.right(sourceFile.getFilePath().toString());
128
- }
129
- return err(ExtractorErrorCode.AppMissingDefaultExport);
130
- }
131
- static model(classDecl, sourceFile) {
132
- const name = classDecl.getName();
133
- const attributes = [];
134
- const navigation_properties = [];
135
- const data_sources = {};
136
- const methods = {};
137
- const cruds = new Set();
138
- let primary_key = undefined;
139
- // Extract crud methods
140
- const crudDecorator = classDecl
141
- .getDecorators()
142
- .find((d) => getDecoratorName(d) === ClassDecoratorKind.CRUD);
143
- if (crudDecorator) {
144
- setCrudKinds(crudDecorator, cruds);
145
- }
146
- // Iterate attribtutes
147
- for (const prop of classDecl.getProperties()) {
148
- const decorators = prop.getDecorators();
149
- const typeRes = CidlExtractor.cidlType(prop.getType());
150
- // Error: invalid property type
151
- if (typeRes.isLeft()) {
152
- typeRes.value.context = prop.getName();
153
- typeRes.value.snippet = prop.getText();
154
- return typeRes;
155
- }
156
- const checkModifierRes = checkAttributeModifier(prop);
157
- // No decorators means this is a standard attribute
158
- if (decorators.length === 0) {
159
- // Error: invalid attribute modifier
160
- if (checkModifierRes !== undefined) {
161
- return checkModifierRes;
162
- }
163
- const cidl_type = typeRes.unwrap();
164
- attributes.push({
165
- foreign_key_reference: null,
166
- value: {
167
- name: prop.getName(),
168
- cidl_type,
169
- },
170
- });
171
- continue;
172
- }
173
- // TODO: Limiting to one decorator. Can't get too fancy on us.
174
- const decorator = decorators[0];
175
- const decoratorName = getDecoratorName(decorator);
176
- // Error: invalid attribute modifier
177
- if (checkModifierRes !== undefined &&
178
- decoratorName !== AttributeDecoratorKind.DataSource) {
179
- return checkModifierRes;
180
- }
181
- // Process decorator
182
- const cidl_type = typeRes.unwrap();
183
- switch (decoratorName) {
184
- case AttributeDecoratorKind.PrimaryKey: {
185
- primary_key = {
186
- name: prop.getName(),
187
- cidl_type,
188
- };
189
- break;
190
- }
191
- case AttributeDecoratorKind.ForeignKey: {
192
- attributes.push({
193
- foreign_key_reference: getDecoratorArgument(decorator, 0) ?? null,
194
- value: {
195
- name: prop.getName(),
196
- cidl_type,
197
- },
198
- });
199
- break;
200
- }
201
- case AttributeDecoratorKind.OneToOne: {
202
- const reference = getDecoratorArgument(decorator, 0);
203
- // Error: One to one navigation properties requre a reference
204
- if (!reference) {
205
- return err(ExtractorErrorCode.MissingNavigationPropertyReference, (e) => {
206
- e.snippet = prop.getText();
207
- e.context = prop.getName();
208
- });
209
- }
210
- let model_name = getObjectName(cidl_type);
211
- // Error: navigation properties require a model reference
212
- if (!model_name) {
213
- return err(ExtractorErrorCode.MissingNavigationPropertyReference, (e) => {
214
- e.snippet = prop.getText();
215
- e.context = prop.getName();
216
- });
217
- }
218
- navigation_properties.push({
219
- var_name: prop.getName(),
220
- model_name,
221
- kind: { OneToOne: { reference } },
222
- });
223
- break;
224
- }
225
- case AttributeDecoratorKind.OneToMany: {
226
- const reference = getDecoratorArgument(decorator, 0);
227
- // Error: One to one navigation properties requre a reference
228
- if (!reference) {
229
- return err(ExtractorErrorCode.MissingNavigationPropertyReference, (e) => {
230
- e.snippet = prop.getText();
231
- e.context = prop.getName();
232
- });
233
- }
234
- let model_name = getObjectName(cidl_type);
235
- // Error: navigation properties require a model reference
236
- if (!model_name) {
237
- return err(ExtractorErrorCode.MissingNavigationPropertyReference, (e) => {
238
- e.snippet = prop.getText();
239
- e.context = prop.getName();
240
- });
241
- }
242
- navigation_properties.push({
243
- var_name: prop.getName(),
244
- model_name,
245
- kind: { OneToMany: { reference } },
246
- });
247
- break;
248
- }
249
- case AttributeDecoratorKind.ManyToMany: {
250
- const unique_id = getDecoratorArgument(decorator, 0);
251
- // Error: many to many attribtues require a unique id
252
- if (!unique_id)
253
- return err(ExtractorErrorCode.MissingManyToManyUniqueId, (e) => {
254
- e.snippet = prop.getText();
255
- e.context = prop.getName();
256
- });
257
- // Error: navigation properties require a model reference
258
- let model_name = getObjectName(cidl_type);
259
- if (!model_name) {
260
- return err(ExtractorErrorCode.MissingNavigationPropertyReference, (e) => {
261
- e.snippet = prop.getText();
262
- e.context = prop.getName();
263
- });
264
- }
265
- navigation_properties.push({
266
- var_name: prop.getName(),
267
- model_name,
268
- kind: { ManyToMany: { unique_id } },
269
- });
270
- break;
271
- }
272
- case AttributeDecoratorKind.DataSource: {
273
- const isIncludeTree = prop
274
- .getType()
275
- .getText(undefined, TypeFormatFlags.UseAliasDefinedOutsideCurrentScope) === `IncludeTree<${name}>`;
276
- // Error: data sources must be static include trees
277
- if (!prop.isStatic() || !isIncludeTree) {
278
- return err(ExtractorErrorCode.InvalidDataSourceDefinition, (e) => {
279
- e.snippet = prop.getText();
280
- e.context = prop.getName();
281
- });
282
- }
283
- const initializer = prop.getInitializer();
284
- const treeRes = CidlExtractor.includeTree(initializer, classDecl, sourceFile);
285
- if (treeRes.isLeft()) {
286
- treeRes.value.addContext((prev) => `${prop.getName()} ${prev}`);
287
- treeRes.value.snippet = prop.getText();
288
- return treeRes;
289
- }
290
- data_sources[prop.getName()] = {
291
- name: prop.getName(),
292
- tree: treeRes.unwrap(),
293
- };
294
- break;
295
- }
296
- }
297
- }
298
- if (primary_key == undefined) {
299
- return err(ExtractorErrorCode.MissingPrimaryKey, (e) => {
300
- e.snippet = classDecl.getText();
301
- });
302
- }
303
- // Process methods
304
- for (const m of classDecl.getMethods()) {
305
- const httpVerb = m
306
- .getDecorators()
307
- .map((d) => getDecoratorName(d))
308
- .find((name) => Object.values(HttpVerb).includes(name));
309
- if (!httpVerb) {
310
- continue;
311
- }
312
- const result = CidlExtractor.method(name, m, httpVerb);
313
- if (result.isLeft()) {
314
- result.value.addContext((prev) => `${m.getName()} ${prev}`);
315
- return result;
316
- }
317
- methods[result.unwrap().name] = result.unwrap();
318
- }
319
- return Either.right({
320
- name,
321
- attributes,
322
- primary_key,
323
- navigation_properties,
324
- methods,
325
- data_sources,
326
- cruds: Array.from(cruds).sort(),
327
- source_path: sourceFile.getFilePath().toString(),
28
+ projectName;
29
+ version;
30
+ constructor(projectName, version) {
31
+ this.projectName = projectName;
32
+ this.version = version;
33
+ }
34
+ extract(project) {
35
+ const models = {};
36
+ const poos = {};
37
+ const wranglerEnvs = [];
38
+ const services = {};
39
+ let app_source = null;
40
+ for (const sourceFile of project.getSourceFiles()) {
41
+ if (
42
+ sourceFile.getBaseName() === "app.cloesce.ts" ||
43
+ sourceFile.getBaseName() === "seed__app.cloesce.ts" // hardcoding for tests
44
+ ) {
45
+ const app = CidlExtractor.app(sourceFile);
46
+ if (app.isLeft()) {
47
+ return app;
48
+ }
49
+ app_source = app.unwrap();
50
+ }
51
+ for (const classDecl of sourceFile.getClasses()) {
52
+ const notExportedErr = err(ExtractorErrorCode.MissingExport, (e) => {
53
+ e.context = classDecl.getName();
54
+ e.snippet = classDecl.getText();
328
55
  });
329
- }
330
- static poo(classDecl, sourceFile) {
331
- const name = classDecl.getName();
332
- const attributes = [];
333
- for (const prop of classDecl.getProperties()) {
334
- const typeRes = CidlExtractor.cidlType(prop.getType());
335
- // Error: invalid property type
336
- if (typeRes.isLeft()) {
337
- typeRes.value.context = prop.getName();
338
- typeRes.value.snippet = prop.getText();
339
- return typeRes;
340
- }
341
- // Error: invalid attribute modifier
56
+ if (hasDecorator(classDecl, ClassDecoratorKind.D1)) {
57
+ if (!classDecl.isExported()) return notExportedErr;
58
+ const result = CidlExtractor.model(classDecl, sourceFile);
59
+ // Error: propogate from models
60
+ if (result.isLeft()) {
61
+ result.value.addContext((prev) => `${classDecl.getName()}.${prev}`);
62
+ return result;
63
+ }
64
+ const model = result.unwrap();
65
+ models[model.name] = model;
66
+ continue;
67
+ }
68
+ if (hasDecorator(classDecl, ClassDecoratorKind.Service)) {
69
+ if (!classDecl.isExported()) return notExportedErr;
70
+ const result = CidlExtractor.service(classDecl, sourceFile);
71
+ // Error: propogate from service
72
+ if (result.isLeft()) {
73
+ result.value.addContext((prev) => `${classDecl.getName()}.${prev}`);
74
+ return result;
75
+ }
76
+ const service = result.unwrap();
77
+ services[service.name] = service;
78
+ continue;
79
+ }
80
+ if (hasDecorator(classDecl, ClassDecoratorKind.PlainOldObject)) {
81
+ if (!classDecl.isExported()) return notExportedErr;
82
+ const result = CidlExtractor.poo(classDecl, sourceFile);
83
+ // Error: propogate from models
84
+ if (result.isLeft()) {
85
+ result.value.addContext((prev) => `${classDecl.getName()}.${prev}`);
86
+ return result;
87
+ }
88
+ poos[result.unwrap().name] = result.unwrap();
89
+ continue;
90
+ }
91
+ if (hasDecorator(classDecl, ClassDecoratorKind.WranglerEnv)) {
92
+ // Error: invalid attribute modifier
93
+ for (const prop of classDecl.getProperties()) {
342
94
  const modifierRes = checkAttributeModifier(prop);
343
- if (modifierRes) {
344
- return modifierRes;
95
+ if (modifierRes.isLeft()) {
96
+ return modifierRes;
345
97
  }
346
- const cidl_type = typeRes.unwrap();
347
- attributes.push({
348
- name: prop.getName(),
349
- cidl_type,
350
- });
351
- continue;
352
- }
353
- return Either.right({
354
- name,
355
- attributes,
356
- source_path: sourceFile.getFilePath().toString(),
357
- });
98
+ }
99
+ const result = CidlExtractor.env(classDecl, sourceFile);
100
+ if (result.isLeft()) {
101
+ return result;
102
+ }
103
+ wranglerEnvs.push(result.unwrap());
104
+ }
105
+ }
358
106
  }
359
- static env(classDecl, sourceFile) {
360
- const vars = {};
361
- let binding;
362
- for (const prop of classDecl.getProperties()) {
363
- if (prop
364
- .getType()
365
- .getText(undefined, TypeFormatFlags.UseAliasDefinedOutsideCurrentScope) === "D1Database") {
366
- binding = prop.getName();
367
- continue;
368
- }
369
- const ty = CidlExtractor.cidlType(prop.getType());
370
- if (ty.isLeft()) {
371
- ty.value.context = prop.getName();
372
- ty.value.snippet = prop.getText();
373
- return ty;
374
- }
375
- vars[prop.getName()] = ty.unwrap();
376
- }
377
- if (!binding) {
378
- return err(ExtractorErrorCode.MissingDatabaseBinding);
379
- }
380
- return Either.right({
381
- name: classDecl.getName(),
382
- source_path: sourceFile.getFilePath().toString(),
383
- db_binding: binding,
384
- vars,
385
- });
107
+ // Error: Only one wrangler environment can exist
108
+ if (wranglerEnvs.length > 1) {
109
+ return err(
110
+ ExtractorErrorCode.TooManyWranglerEnvs,
111
+ (e) => (e.context = wranglerEnvs.map((w) => w.name).toString()),
112
+ );
113
+ }
114
+ return Either.right({
115
+ version: this.version,
116
+ project_name: this.projectName,
117
+ language: "TypeScript",
118
+ wrangler_env: wranglerEnvs[0],
119
+ models,
120
+ poos,
121
+ services,
122
+ app_source,
123
+ });
124
+ }
125
+ static app(sourceFile) {
126
+ const symbol = sourceFile.getDefaultExportSymbol();
127
+ const decl = symbol?.getDeclarations()[0];
128
+ if (!decl) {
129
+ return err(ExtractorErrorCode.AppMissingDefaultExport);
386
130
  }
387
- static primTypeMap = {
388
- number: "Real",
389
- Number: "Real",
390
- Integer: "Integer",
391
- string: "Text",
392
- String: "Text",
393
- boolean: "Boolean",
394
- Boolean: "Boolean",
395
- Date: "DateIso",
131
+ const getTypeText = () => {
132
+ let type = undefined;
133
+ if (MorphNode.isExportAssignment(decl)) {
134
+ type = decl.getExpression()?.getType();
135
+ }
136
+ if (MorphNode.isVariableDeclaration(decl)) {
137
+ type = decl.getInitializer()?.getType();
138
+ }
139
+ return type?.getText(
140
+ undefined,
141
+ TypeFormatFlags.UseAliasDefinedOutsideCurrentScope,
142
+ );
396
143
  };
397
- static cidlType(type, inject = false) {
398
- // Void
399
- if (type.isVoid()) {
400
- return Either.right("Void");
401
- }
402
- // Null
403
- if (type.isNull()) {
404
- return Either.right({ Nullable: "Void" });
405
- }
406
- // Nullable via union
407
- const [unwrappedType, nullable] = unwrapNullable(type);
408
- const tyText = unwrappedType
409
- .getText(undefined, TypeFormatFlags.UseAliasDefinedOutsideCurrentScope)
410
- .split("|")[0]
411
- .trim();
412
- // Primitives
413
- const prim = this.primTypeMap[tyText];
414
- if (prim) {
415
- return Either.right(wrapNullable(prim, nullable));
416
- }
417
- const generics = [
418
- ...unwrappedType.getAliasTypeArguments(),
419
- ...unwrappedType.getTypeArguments(),
420
- ];
421
- // Error: can't handle multiple generics
422
- if (generics.length > 1) {
423
- return err(ExtractorErrorCode.MultipleGenericType);
424
- }
425
- // No generics -> inject or object
426
- if (generics.length === 0) {
427
- const base = inject ? { Inject: tyText } : { Object: tyText };
428
- return Either.right(wrapNullable(base, nullable));
429
- }
430
- // Single generic
431
- const genericTy = generics[0];
432
- const symbolName = unwrappedType.getSymbol()?.getName();
433
- const aliasName = unwrappedType.getAliasSymbol()?.getName();
434
- if (aliasName === "DataSourceOf") {
435
- return Either.right(wrapNullable({
436
- DataSource: genericTy.getText(undefined, TypeFormatFlags.UseAliasDefinedOutsideCurrentScope),
437
- }, nullable));
438
- }
439
- if (aliasName === "DeepPartial") {
440
- const [_, genericTyNullable] = unwrapNullable(genericTy);
441
- const genericTyGenerics = [
442
- ...genericTy.getAliasTypeArguments(),
443
- ...genericTy.getTypeArguments(),
444
- ];
445
- // Expect partials to be of the exact form DeepPartial<Model>
446
- if (genericTyNullable ||
447
- genericTy.isUnion() ||
448
- genericTyGenerics.length > 0) {
449
- return err(ExtractorErrorCode.InvalidPartialType);
450
- }
451
- return Either.right(wrapNullable({
452
- Partial: genericTy
453
- .getText(undefined, TypeFormatFlags.UseAliasDefinedOutsideCurrentScope)
454
- .split("|")[0]
455
- .trim(),
456
- }, nullable));
457
- }
458
- if (symbolName === "Promise" || aliasName === "IncludeTree") {
459
- return wrapGeneric(genericTy, nullable, (inner) => inner);
460
- }
461
- if (unwrappedType.isArray()) {
462
- return wrapGeneric(genericTy, nullable, (inner) => ({ Array: inner }));
463
- }
464
- if (aliasName === "HttpResult") {
465
- return wrapGeneric(genericTy, nullable, (inner) => ({
466
- HttpResult: inner,
467
- }));
468
- }
469
- // Error: unknown type
470
- return err(ExtractorErrorCode.UnknownType);
471
- function wrapNullable(inner, isNullable) {
472
- if (isNullable) {
473
- return { Nullable: inner };
474
- }
475
- else {
476
- return inner;
477
- }
478
- }
479
- function wrapGeneric(t, isNullable, wrapper) {
480
- const res = CidlExtractor.cidlType(t, inject);
481
- // Error: propogated from `cidlType`
482
- return res.map((inner) => wrapNullable(wrapper(inner), isNullable));
483
- }
484
- function unwrapNullable(ty) {
485
- if (!ty.isUnion())
486
- return [ty, false];
487
- const unions = ty.getUnionTypes();
488
- const nonNulls = unions.filter((t) => !t.isNull() && !t.isUndefined());
489
- const hasNullable = nonNulls.length < unions.length;
490
- // Booleans seperate into [null, true, false] from the `getUnionTypes` call
491
- if (nonNulls.length === 2 &&
492
- nonNulls.every((t) => t.isBooleanLiteral())) {
493
- return [nonNulls[0].getApparentType(), hasNullable];
494
- }
495
- return [nonNulls[0] ?? ty, hasNullable];
496
- }
144
+ const typeText = getTypeText();
145
+ if (typeText === "CloesceApp") {
146
+ return Either.right(sourceFile.getFilePath().toString());
497
147
  }
498
- static includeTree(expr, currentClass, sf) {
499
- // Include trees must be of the expected form
500
- if (!expr ||
501
- !expr.isKind ||
502
- !expr.isKind(SyntaxKind.ObjectLiteralExpression)) {
503
- return err(ExtractorErrorCode.InvalidIncludeTree);
504
- }
505
- const result = {};
506
- for (const prop of expr.getProperties()) {
507
- if (!prop.isKind(SyntaxKind.PropertyAssignment))
508
- continue;
509
- // Error: navigation property not found
510
- const navProp = findPropertyByName(currentClass, prop.getName());
511
- if (!navProp) {
512
- return err(ExtractorErrorCode.UnknownNavigationPropertyReference, (e) => {
513
- e.snippet = expr.getText();
514
- e.context = prop.getName();
515
- });
516
- }
517
- const typeRes = CidlExtractor.cidlType(navProp.getType());
518
- // Error: invalid referenced nav prop type
519
- if (typeRes.isLeft()) {
520
- typeRes.value.snippet = navProp.getText();
521
- typeRes.value.context = prop.getName();
522
- return typeRes;
523
- }
524
- // Error: invalid referenced nav prop type
525
- const cidl_type = typeRes.unwrap();
526
- if (typeof cidl_type === "string") {
527
- return err(ExtractorErrorCode.InvalidNavigationPropertyReference, (e) => {
528
- ((e.snippet = navProp.getText()), (e.context = prop.getName()));
529
- });
530
- }
531
- // Recurse for nested includes
532
- const initializer = prop.getInitializer?.();
533
- let nestedTree = {};
534
- if (initializer?.isKind?.(SyntaxKind.ObjectLiteralExpression)) {
535
- const targetModel = getObjectName(cidl_type);
536
- const targetClass = currentClass
537
- .getSourceFile()
538
- .getProject()
539
- .getSourceFiles()
540
- .flatMap((f) => f.getClasses())
541
- .find((c) => c.getName() === targetModel);
542
- if (targetClass) {
543
- const treeRes = CidlExtractor.includeTree(initializer, targetClass, sf);
544
- // Error: Propogated from `includeTree`
545
- if (treeRes.isLeft()) {
546
- treeRes.value.snippet = expr.getText();
547
- return treeRes;
548
- }
549
- nestedTree = treeRes.unwrap();
550
- }
551
- }
552
- result[navProp.getName()] = nestedTree;
553
- }
554
- return Either.right(result);
555
- }
556
- static method(modelName, method, httpVerb) {
557
- // Error: invalid method scope, must be public
558
- if (method.getScope() != Scope.Public) {
559
- return err(ExtractorErrorCode.InvalidApiMethodModifier, (e) => {
560
- e.context = method.getName();
561
- e.snippet = method.getText();
148
+ return err(ExtractorErrorCode.AppMissingDefaultExport);
149
+ }
150
+ static model(classDecl, sourceFile) {
151
+ const name = classDecl.getName();
152
+ const attributes = [];
153
+ const navigation_properties = [];
154
+ const data_sources = {};
155
+ const methods = {};
156
+ const cruds = new Set();
157
+ let primary_key = undefined;
158
+ // Extract crud methods
159
+ const crudDecorator = classDecl
160
+ .getDecorators()
161
+ .find((d) => getDecoratorName(d) === ClassDecoratorKind.CRUD);
162
+ if (crudDecorator) {
163
+ setCrudKinds(crudDecorator, cruds);
164
+ }
165
+ // Iterate attribtutes
166
+ for (const prop of classDecl.getProperties()) {
167
+ const decorators = prop.getDecorators();
168
+ const typeRes = CidlExtractor.cidlType(prop.getType());
169
+ // Error: invalid property type
170
+ if (typeRes.isLeft()) {
171
+ typeRes.value.context = prop.getName();
172
+ typeRes.value.snippet = prop.getText();
173
+ return typeRes;
174
+ }
175
+ const checkModifierRes = checkAttributeModifier(prop);
176
+ // No decorators means this is a standard attribute
177
+ if (decorators.length === 0) {
178
+ // Error: invalid attribute modifier
179
+ if (checkModifierRes.isLeft()) {
180
+ return checkModifierRes;
181
+ }
182
+ const cidl_type = typeRes.unwrap();
183
+ attributes.push({
184
+ foreign_key_reference: null,
185
+ value: {
186
+ name: prop.getName(),
187
+ cidl_type,
188
+ },
189
+ });
190
+ continue;
191
+ }
192
+ // TODO: Limiting to one decorator. Can't get too fancy on us.
193
+ const decorator = decorators[0];
194
+ const decoratorName = getDecoratorName(decorator);
195
+ // Error: invalid attribute modifier
196
+ if (
197
+ checkModifierRes.isLeft() &&
198
+ decoratorName !== AttributeDecoratorKind.DataSource
199
+ ) {
200
+ return checkModifierRes;
201
+ }
202
+ // Process decorator
203
+ const cidl_type = typeRes.unwrap();
204
+ switch (decoratorName) {
205
+ case AttributeDecoratorKind.PrimaryKey: {
206
+ primary_key = {
207
+ name: prop.getName(),
208
+ cidl_type,
209
+ };
210
+ break;
211
+ }
212
+ case AttributeDecoratorKind.ForeignKey: {
213
+ attributes.push({
214
+ foreign_key_reference: getDecoratorArgument(decorator, 0) ?? null,
215
+ value: {
216
+ name: prop.getName(),
217
+ cidl_type,
218
+ },
219
+ });
220
+ break;
221
+ }
222
+ case AttributeDecoratorKind.OneToOne: {
223
+ const reference = getDecoratorArgument(decorator, 0);
224
+ // Error: One to one navigation properties requre a reference
225
+ if (!reference) {
226
+ return err(
227
+ ExtractorErrorCode.MissingNavigationPropertyReference,
228
+ (e) => {
229
+ e.snippet = prop.getText();
230
+ e.context = prop.getName();
231
+ },
232
+ );
233
+ }
234
+ let model_name = getObjectName(cidl_type);
235
+ // Error: navigation properties require a model reference
236
+ if (!model_name) {
237
+ return err(
238
+ ExtractorErrorCode.MissingNavigationPropertyReference,
239
+ (e) => {
240
+ e.snippet = prop.getText();
241
+ e.context = prop.getName();
242
+ },
243
+ );
244
+ }
245
+ navigation_properties.push({
246
+ var_name: prop.getName(),
247
+ model_name,
248
+ kind: { OneToOne: { reference } },
249
+ });
250
+ break;
251
+ }
252
+ case AttributeDecoratorKind.OneToMany: {
253
+ const reference = getDecoratorArgument(decorator, 0);
254
+ // Error: One to one navigation properties requre a reference
255
+ if (!reference) {
256
+ return err(
257
+ ExtractorErrorCode.MissingNavigationPropertyReference,
258
+ (e) => {
259
+ e.snippet = prop.getText();
260
+ e.context = prop.getName();
261
+ },
262
+ );
263
+ }
264
+ let model_name = getObjectName(cidl_type);
265
+ // Error: navigation properties require a model reference
266
+ if (!model_name) {
267
+ return err(
268
+ ExtractorErrorCode.MissingNavigationPropertyReference,
269
+ (e) => {
270
+ e.snippet = prop.getText();
271
+ e.context = prop.getName();
272
+ },
273
+ );
274
+ }
275
+ navigation_properties.push({
276
+ var_name: prop.getName(),
277
+ model_name,
278
+ kind: { OneToMany: { reference } },
279
+ });
280
+ break;
281
+ }
282
+ case AttributeDecoratorKind.ManyToMany: {
283
+ const unique_id = getDecoratorArgument(decorator, 0);
284
+ // Error: many to many attribtues require a unique id
285
+ if (!unique_id)
286
+ return err(ExtractorErrorCode.MissingManyToManyUniqueId, (e) => {
287
+ e.snippet = prop.getText();
288
+ e.context = prop.getName();
562
289
  });
563
- }
564
- let needsDataSource = !method.isStatic();
565
- const parameters = [];
566
- for (const param of method.getParameters()) {
567
- // Handle injected param
568
- if (param.getDecorator(ParameterDecoratorKind.Inject)) {
569
- const typeRes = CidlExtractor.cidlType(param.getType(), true);
570
- // Error: invalid type
571
- if (typeRes.isLeft()) {
572
- typeRes.value.snippet = method.getText();
573
- typeRes.value.context = param.getName();
574
- return typeRes;
575
- }
576
- parameters.push({
577
- name: param.getName(),
578
- cidl_type: typeRes.unwrap(),
579
- });
580
- continue;
581
- }
582
- // Handle all other params
583
- const typeRes = CidlExtractor.cidlType(param.getType());
584
- // Error: invalid type
585
- if (typeRes.isLeft()) {
586
- typeRes.value.snippet = method.getText();
587
- typeRes.value.context = param.getName();
588
- return typeRes;
589
- }
590
- if (typeof typeRes.value !== "string" && "DataSource" in typeRes.value) {
591
- needsDataSource = false;
592
- }
593
- parameters.push({
594
- name: param.getName(),
595
- cidl_type: typeRes.unwrap(),
290
+ // Error: navigation properties require a model reference
291
+ let model_name = getObjectName(cidl_type);
292
+ if (!model_name) {
293
+ return err(
294
+ ExtractorErrorCode.MissingNavigationPropertyReference,
295
+ (e) => {
296
+ e.snippet = prop.getText();
297
+ e.context = prop.getName();
298
+ },
299
+ );
300
+ }
301
+ navigation_properties.push({
302
+ var_name: prop.getName(),
303
+ model_name,
304
+ kind: { ManyToMany: { unique_id } },
305
+ });
306
+ break;
307
+ }
308
+ case AttributeDecoratorKind.DataSource: {
309
+ const isIncludeTree =
310
+ prop
311
+ .getType()
312
+ .getText(
313
+ undefined,
314
+ TypeFormatFlags.UseAliasDefinedOutsideCurrentScope,
315
+ ) === `IncludeTree<${name}>`;
316
+ // Error: data sources must be static include trees
317
+ if (!prop.isStatic() || !isIncludeTree) {
318
+ return err(ExtractorErrorCode.InvalidDataSourceDefinition, (e) => {
319
+ e.snippet = prop.getText();
320
+ e.context = prop.getName();
596
321
  });
597
- }
598
- const typeRes = CidlExtractor.cidlType(method.getReturnType());
322
+ }
323
+ const initializer = prop.getInitializer();
324
+ const treeRes = CidlExtractor.includeTree(
325
+ initializer,
326
+ classDecl,
327
+ sourceFile,
328
+ );
329
+ if (treeRes.isLeft()) {
330
+ treeRes.value.addContext((prev) => `${prop.getName()} ${prev}`);
331
+ treeRes.value.snippet = prop.getText();
332
+ return treeRes;
333
+ }
334
+ data_sources[prop.getName()] = {
335
+ name: prop.getName(),
336
+ tree: treeRes.unwrap(),
337
+ };
338
+ break;
339
+ }
340
+ }
341
+ }
342
+ if (primary_key == undefined) {
343
+ return err(ExtractorErrorCode.MissingPrimaryKey, (e) => {
344
+ e.snippet = classDecl.getText();
345
+ });
346
+ }
347
+ // Process methods
348
+ for (const m of classDecl.getMethods()) {
349
+ const httpVerb = m
350
+ .getDecorators()
351
+ .map((d) => getDecoratorName(d))
352
+ .find((name) => Object.values(HttpVerb).includes(name));
353
+ if (!httpVerb) {
354
+ continue;
355
+ }
356
+ const result = CidlExtractor.modelMethod(name, m, httpVerb);
357
+ if (result.isLeft()) {
358
+ result.value.addContext((prev) => `${m.getName()} ${prev}`);
359
+ return result;
360
+ }
361
+ methods[result.unwrap().name] = result.unwrap();
362
+ }
363
+ return Either.right({
364
+ name,
365
+ attributes,
366
+ primary_key,
367
+ navigation_properties,
368
+ methods,
369
+ data_sources,
370
+ cruds: Array.from(cruds).sort(),
371
+ source_path: sourceFile.getFilePath().toString(),
372
+ });
373
+ }
374
+ static modelMethod(modelName, method, verb) {
375
+ // Error: invalid method scope, must be public
376
+ if (method.getScope() != Scope.Public) {
377
+ return err(ExtractorErrorCode.InvalidApiMethodModifier, (e) => {
378
+ e.context = method.getName();
379
+ e.snippet = method.getText();
380
+ });
381
+ }
382
+ let needsDataSource = !method.isStatic();
383
+ const parameters = [];
384
+ for (const param of method.getParameters()) {
385
+ // Handle injected param
386
+ if (param.getDecorator(ParameterDecoratorKind.Inject)) {
387
+ const typeRes = CidlExtractor.cidlType(param.getType(), true);
599
388
  // Error: invalid type
600
389
  if (typeRes.isLeft()) {
601
- typeRes.value.snippet = method.getText();
602
- return typeRes;
390
+ typeRes.value.snippet = method.getText();
391
+ typeRes.value.context = param.getName();
392
+ return typeRes;
603
393
  }
604
- // Sugaring: add data source
605
- if (needsDataSource) {
606
- parameters.push({
607
- name: "__dataSource",
608
- cidl_type: { DataSource: modelName },
609
- });
394
+ parameters.push({
395
+ name: param.getName(),
396
+ cidl_type: typeRes.unwrap(),
397
+ });
398
+ continue;
399
+ }
400
+ // Handle all other params
401
+ const typeRes = CidlExtractor.cidlType(param.getType());
402
+ // Error: invalid type
403
+ if (typeRes.isLeft()) {
404
+ typeRes.value.snippet = method.getText();
405
+ typeRes.value.context = param.getName();
406
+ return typeRes;
407
+ }
408
+ if (typeof typeRes.value !== "string" && "DataSource" in typeRes.value) {
409
+ needsDataSource = false;
410
+ }
411
+ parameters.push({
412
+ name: param.getName(),
413
+ cidl_type: typeRes.unwrap(),
414
+ });
415
+ }
416
+ const typeRes = CidlExtractor.cidlType(method.getReturnType());
417
+ // Error: invalid type
418
+ if (typeRes.isLeft()) {
419
+ typeRes.value.snippet = method.getText();
420
+ return typeRes;
421
+ }
422
+ // Sugaring: add data source
423
+ if (needsDataSource) {
424
+ parameters.push({
425
+ name: "__dataSource",
426
+ cidl_type: { DataSource: modelName },
427
+ });
428
+ }
429
+ return Either.right({
430
+ name: method.getName(),
431
+ is_static: method.isStatic(),
432
+ http_verb: verb,
433
+ return_media: defaultMediaType(),
434
+ return_type: typeRes.unwrap(),
435
+ parameters_media: defaultMediaType(),
436
+ parameters,
437
+ });
438
+ }
439
+ static service(classDecl, sourceFile) {
440
+ const attributes = [];
441
+ const methods = {};
442
+ // Attributes
443
+ for (const prop of classDecl.getProperties()) {
444
+ const typeRes = CidlExtractor.cidlType(prop.getType(), true);
445
+ // Error: invalid property type
446
+ if (typeRes.isLeft()) {
447
+ typeRes.value.context = prop.getName();
448
+ typeRes.value.snippet = prop.getText();
449
+ return typeRes;
450
+ }
451
+ if (typeof typeRes.value === "string" || !("Inject" in typeRes.value)) {
452
+ return err(ExtractorErrorCode.InvalidServiceAttribute, (e) => {
453
+ e.context = prop.getName();
454
+ e.snippet = prop.getText();
455
+ });
456
+ }
457
+ const checkModifierRes = checkAttributeModifier(prop);
458
+ if (checkModifierRes.isLeft()) {
459
+ return checkModifierRes;
460
+ }
461
+ attributes.push({
462
+ var_name: prop.getName(),
463
+ injected: typeRes.value.Inject,
464
+ });
465
+ }
466
+ // Methods
467
+ for (const m of classDecl.getMethods()) {
468
+ const httpVerb = m
469
+ .getDecorators()
470
+ .map((d) => getDecoratorName(d))
471
+ .find((name) => Object.values(HttpVerb).includes(name));
472
+ if (!httpVerb) {
473
+ continue;
474
+ }
475
+ const res = CidlExtractor.serviceMethod(m, httpVerb);
476
+ if (res.isLeft()) {
477
+ return res;
478
+ }
479
+ const serviceMethod = res.unwrap();
480
+ methods[serviceMethod.name] = serviceMethod;
481
+ }
482
+ return Either.right({
483
+ name: classDecl.getName(),
484
+ attributes,
485
+ methods,
486
+ source_path: sourceFile.getFilePath().toString(),
487
+ });
488
+ }
489
+ static serviceMethod(method, verb) {
490
+ // Error: invalid method scope, must be public
491
+ if (method.getScope() != Scope.Public) {
492
+ return err(ExtractorErrorCode.InvalidApiMethodModifier, (e) => {
493
+ e.context = method.getName();
494
+ e.snippet = method.getText();
495
+ });
496
+ }
497
+ const parameters = [];
498
+ for (const param of method.getParameters()) {
499
+ // Handle injected param
500
+ if (param.getDecorator(ParameterDecoratorKind.Inject)) {
501
+ const typeRes = CidlExtractor.cidlType(param.getType(), true);
502
+ // Error: invalid type
503
+ if (typeRes.isLeft()) {
504
+ typeRes.value.snippet = method.getText();
505
+ typeRes.value.context = param.getName();
506
+ return typeRes;
610
507
  }
611
- return Either.right({
612
- name: method.getName(),
613
- is_static: method.isStatic(),
614
- http_verb: httpVerb,
615
- return_type: typeRes.unwrap(),
616
- parameters,
508
+ parameters.push({
509
+ name: param.getName(),
510
+ cidl_type: typeRes.unwrap(),
617
511
  });
512
+ continue;
513
+ }
514
+ // Handle all other params
515
+ const typeRes = CidlExtractor.cidlType(param.getType());
516
+ // Error: invalid type
517
+ if (typeRes.isLeft()) {
518
+ typeRes.value.snippet = method.getText();
519
+ typeRes.value.context = param.getName();
520
+ return typeRes;
521
+ }
522
+ parameters.push({
523
+ name: param.getName(),
524
+ cidl_type: typeRes.unwrap(),
525
+ });
618
526
  }
527
+ const typeRes = CidlExtractor.cidlType(method.getReturnType());
528
+ // Error: invalid type
529
+ if (typeRes.isLeft()) {
530
+ typeRes.value.snippet = method.getText();
531
+ return typeRes;
532
+ }
533
+ return Either.right({
534
+ name: method.getName(),
535
+ http_verb: verb,
536
+ is_static: method.isStatic(),
537
+ return_media: defaultMediaType(),
538
+ return_type: typeRes.unwrap(),
539
+ parameters_media: defaultMediaType(),
540
+ parameters,
541
+ });
542
+ }
543
+ static poo(classDecl, sourceFile) {
544
+ const name = classDecl.getName();
545
+ const attributes = [];
546
+ for (const prop of classDecl.getProperties()) {
547
+ const typeRes = CidlExtractor.cidlType(prop.getType());
548
+ // Error: invalid property type
549
+ if (typeRes.isLeft()) {
550
+ typeRes.value.context = prop.getName();
551
+ typeRes.value.snippet = prop.getText();
552
+ return typeRes;
553
+ }
554
+ // Error: invalid attribute modifier
555
+ const modifierRes = checkAttributeModifier(prop);
556
+ if (modifierRes.isLeft()) {
557
+ return modifierRes;
558
+ }
559
+ const cidl_type = typeRes.unwrap();
560
+ attributes.push({
561
+ name: prop.getName(),
562
+ cidl_type,
563
+ });
564
+ continue;
565
+ }
566
+ return Either.right({
567
+ name,
568
+ attributes,
569
+ source_path: sourceFile.getFilePath().toString(),
570
+ });
571
+ }
572
+ static env(classDecl, sourceFile) {
573
+ const vars = {};
574
+ let binding;
575
+ for (const prop of classDecl.getProperties()) {
576
+ if (
577
+ prop
578
+ .getType()
579
+ .getText(
580
+ undefined,
581
+ TypeFormatFlags.UseAliasDefinedOutsideCurrentScope,
582
+ ) === "D1Database"
583
+ ) {
584
+ binding = prop.getName();
585
+ continue;
586
+ }
587
+ const ty = CidlExtractor.cidlType(prop.getType());
588
+ if (ty.isLeft()) {
589
+ ty.value.context = prop.getName();
590
+ ty.value.snippet = prop.getText();
591
+ return ty;
592
+ }
593
+ vars[prop.getName()] = ty.unwrap();
594
+ }
595
+ if (!binding) {
596
+ return err(ExtractorErrorCode.MissingDatabaseBinding);
597
+ }
598
+ return Either.right({
599
+ name: classDecl.getName(),
600
+ source_path: sourceFile.getFilePath().toString(),
601
+ db_binding: binding,
602
+ vars,
603
+ });
604
+ }
605
+ static primTypeMap = {
606
+ number: "Real",
607
+ Number: "Real",
608
+ Integer: "Integer",
609
+ string: "Text",
610
+ String: "Text",
611
+ boolean: "Boolean",
612
+ Boolean: "Boolean",
613
+ Date: "DateIso",
614
+ Uint8Array: "Blob",
615
+ Stream: "Stream",
616
+ };
617
+ static cidlType(type, inject = false) {
618
+ // Void
619
+ if (type.isVoid()) {
620
+ return Either.right("Void");
621
+ }
622
+ // Null
623
+ if (type.isNull()) {
624
+ return Either.right({ Nullable: "Void" });
625
+ }
626
+ // Nullable via union
627
+ const [unwrappedType, nullable] = unwrapNullable(type);
628
+ const tyText = unwrappedType
629
+ .getText(undefined, TypeFormatFlags.UseAliasDefinedOutsideCurrentScope)
630
+ .split("|")[0]
631
+ .trim();
632
+ // Primitives
633
+ const prim = this.primTypeMap[tyText];
634
+ if (prim) {
635
+ return Either.right(wrapNullable(prim, nullable));
636
+ }
637
+ const generics = [
638
+ ...unwrappedType.getAliasTypeArguments(),
639
+ ...unwrappedType.getTypeArguments(),
640
+ ];
641
+ // Error: can't handle multiple generics
642
+ if (generics.length > 1) {
643
+ return err(ExtractorErrorCode.MultipleGenericType);
644
+ }
645
+ // No generics -> inject or object
646
+ if (generics.length === 0) {
647
+ const base = inject ? { Inject: tyText } : { Object: tyText };
648
+ return Either.right(wrapNullable(base, nullable));
649
+ }
650
+ // Single generic
651
+ const genericTy = generics[0];
652
+ const symbolName = unwrappedType.getSymbol()?.getName();
653
+ const aliasName = unwrappedType.getAliasSymbol()?.getName();
654
+ if (aliasName === "DataSourceOf") {
655
+ return Either.right(
656
+ wrapNullable(
657
+ {
658
+ DataSource: genericTy.getText(
659
+ undefined,
660
+ TypeFormatFlags.UseAliasDefinedOutsideCurrentScope,
661
+ ),
662
+ },
663
+ nullable,
664
+ ),
665
+ );
666
+ }
667
+ if (aliasName === "DeepPartial") {
668
+ const [_, genericTyNullable] = unwrapNullable(genericTy);
669
+ const genericTyGenerics = [
670
+ ...genericTy.getAliasTypeArguments(),
671
+ ...genericTy.getTypeArguments(),
672
+ ];
673
+ // Expect partials to be of the exact form DeepPartial<Model>
674
+ if (
675
+ genericTyNullable ||
676
+ genericTy.isUnion() ||
677
+ genericTyGenerics.length > 0
678
+ ) {
679
+ return err(ExtractorErrorCode.InvalidPartialType);
680
+ }
681
+ return Either.right(
682
+ wrapNullable(
683
+ {
684
+ Partial: genericTy
685
+ .getText(
686
+ undefined,
687
+ TypeFormatFlags.UseAliasDefinedOutsideCurrentScope,
688
+ )
689
+ .split("|")[0]
690
+ .trim(),
691
+ },
692
+ nullable,
693
+ ),
694
+ );
695
+ }
696
+ if (symbolName === "Promise" || aliasName === "IncludeTree") {
697
+ // Unwrap promises
698
+ return wrapGeneric(genericTy, nullable, (inner) => inner);
699
+ }
700
+ if (unwrappedType.isArray()) {
701
+ return wrapGeneric(genericTy, nullable, (inner) => ({ Array: inner }));
702
+ }
703
+ if (symbolName === "HttpResult") {
704
+ return wrapGeneric(genericTy, nullable, (inner) => ({
705
+ HttpResult: inner,
706
+ }));
707
+ }
708
+ // Error: unknown type
709
+ return err(ExtractorErrorCode.UnknownType);
710
+ function wrapNullable(inner, isNullable) {
711
+ if (isNullable) {
712
+ return { Nullable: inner };
713
+ } else {
714
+ return inner;
715
+ }
716
+ }
717
+ function wrapGeneric(t, isNullable, wrapper) {
718
+ const res = CidlExtractor.cidlType(t, inject);
719
+ // Error: propogated from `cidlType`
720
+ return res.map((inner) => wrapNullable(wrapper(inner), isNullable));
721
+ }
722
+ function unwrapNullable(ty) {
723
+ if (!ty.isUnion()) return [ty, false];
724
+ const unions = ty.getUnionTypes();
725
+ const nonNulls = unions.filter((t) => !t.isNull() && !t.isUndefined());
726
+ const hasNullable = nonNulls.length < unions.length;
727
+ // Booleans seperate into [null, true, false] from the `getUnionTypes` call
728
+ if (
729
+ nonNulls.length === 2 &&
730
+ nonNulls.every((t) => t.isBooleanLiteral())
731
+ ) {
732
+ return [nonNulls[0].getApparentType(), hasNullable];
733
+ }
734
+ return [nonNulls[0] ?? ty, hasNullable];
735
+ }
736
+ }
737
+ static includeTree(expr, currentClass, sf) {
738
+ // Include trees must be of the expected form
739
+ if (
740
+ !expr ||
741
+ !expr.isKind ||
742
+ !expr.isKind(SyntaxKind.ObjectLiteralExpression)
743
+ ) {
744
+ return err(ExtractorErrorCode.InvalidIncludeTree);
745
+ }
746
+ const result = {};
747
+ for (const prop of expr.getProperties()) {
748
+ if (!prop.isKind(SyntaxKind.PropertyAssignment)) continue;
749
+ // Error: navigation property not found
750
+ const navProp = findPropertyByName(currentClass, prop.getName());
751
+ if (!navProp) {
752
+ return err(
753
+ ExtractorErrorCode.UnknownNavigationPropertyReference,
754
+ (e) => {
755
+ e.snippet = expr.getText();
756
+ e.context = prop.getName();
757
+ },
758
+ );
759
+ }
760
+ const typeRes = CidlExtractor.cidlType(navProp.getType());
761
+ // Error: invalid referenced nav prop type
762
+ if (typeRes.isLeft()) {
763
+ typeRes.value.snippet = navProp.getText();
764
+ typeRes.value.context = prop.getName();
765
+ return typeRes;
766
+ }
767
+ // Error: invalid referenced nav prop type
768
+ const cidl_type = typeRes.unwrap();
769
+ if (typeof cidl_type === "string") {
770
+ return err(
771
+ ExtractorErrorCode.InvalidNavigationPropertyReference,
772
+ (e) => {
773
+ e.snippet = navProp.getText();
774
+ e.context = prop.getName();
775
+ },
776
+ );
777
+ }
778
+ // Recurse for nested includes
779
+ const initializer = prop.getInitializer?.();
780
+ let nestedTree = {};
781
+ if (initializer?.isKind?.(SyntaxKind.ObjectLiteralExpression)) {
782
+ const targetModel = getObjectName(cidl_type);
783
+ const targetClass = currentClass
784
+ .getSourceFile()
785
+ .getProject()
786
+ .getSourceFiles()
787
+ .flatMap((f) => f.getClasses())
788
+ .find((c) => c.getName() === targetModel);
789
+ if (targetClass) {
790
+ const treeRes = CidlExtractor.includeTree(
791
+ initializer,
792
+ targetClass,
793
+ sf,
794
+ );
795
+ // Error: Propogated from `includeTree`
796
+ if (treeRes.isLeft()) {
797
+ treeRes.value.snippet = expr.getText();
798
+ return treeRes;
799
+ }
800
+ nestedTree = treeRes.unwrap();
801
+ }
802
+ }
803
+ result[navProp.getName()] = nestedTree;
804
+ }
805
+ return Either.right(result);
806
+ }
619
807
  }
620
808
  function err(code, fn) {
621
- let e = new ExtractorError(code);
622
- if (fn) {
623
- fn(e);
624
- }
625
- return Either.left(e);
809
+ let e = new ExtractorError(code);
810
+ if (fn) {
811
+ fn(e);
812
+ }
813
+ return Either.left(e);
626
814
  }
627
815
  function getDecoratorName(decorator) {
628
- const name = decorator.getName() ?? decorator.getExpression().getText();
629
- return String(name).replace(/\(.*\)$/, "");
816
+ const name = decorator.getName() ?? decorator.getExpression().getText();
817
+ return String(name).replace(/\(.*\)$/, "");
630
818
  }
631
819
  function getDecoratorArgument(decorator, index) {
632
- const args = decorator.getArguments();
633
- if (!args[index])
634
- return undefined;
635
- const arg = args[index];
636
- if (arg.getKind?.() === SyntaxKind.Identifier) {
637
- return arg.getText();
638
- }
639
- return arg.getLiteralValue();
820
+ const args = decorator.getArguments();
821
+ if (!args[index]) return undefined;
822
+ const arg = args[index];
823
+ if (arg.getKind?.() === SyntaxKind.Identifier) {
824
+ return arg.getText();
825
+ }
826
+ return arg.getLiteralValue();
640
827
  }
641
828
  function getRootType(t) {
642
- if (typeof t === "string") {
643
- return t;
644
- }
645
- if ("Nullable" in t) {
646
- return getRootType(t.Nullable);
647
- }
648
- if ("Array" in t) {
649
- return getRootType(t.Array);
650
- }
651
- if ("HttpResult" in t) {
652
- return getRootType(t.HttpResult);
653
- }
829
+ if (typeof t === "string") {
654
830
  return t;
831
+ }
832
+ if ("Nullable" in t) {
833
+ return getRootType(t.Nullable);
834
+ }
835
+ if ("Array" in t) {
836
+ return getRootType(t.Array);
837
+ }
838
+ if ("HttpResult" in t) {
839
+ return getRootType(t.HttpResult);
840
+ }
841
+ return t;
655
842
  }
656
843
  function getObjectName(t) {
657
- const root = getRootType(t);
658
- if (typeof root !== "string" && "Object" in root) {
659
- return root["Object"];
660
- }
661
- return undefined;
844
+ const root = getRootType(t);
845
+ if (typeof root !== "string" && "Object" in root) {
846
+ return root["Object"];
847
+ }
848
+ return undefined;
662
849
  }
663
850
  function setCrudKinds(d, cruds) {
664
- const arg = d.getArguments()[0];
665
- if (!arg) {
666
- return;
667
- }
668
- if (MorphNode.isArrayLiteralExpression(arg)) {
669
- for (const a of arg.getElements()) {
670
- cruds.add((MorphNode.isStringLiteral(a)
671
- ? a.getLiteralValue()
672
- : a.getText()));
673
- }
851
+ const arg = d.getArguments()[0];
852
+ if (!arg) {
853
+ return;
854
+ }
855
+ if (MorphNode.isArrayLiteralExpression(arg)) {
856
+ for (const a of arg.getElements()) {
857
+ cruds.add(
858
+ MorphNode.isStringLiteral(a) ? a.getLiteralValue() : a.getText(),
859
+ );
674
860
  }
861
+ }
675
862
  }
676
863
  function findPropertyByName(cls, name) {
677
- const exactMatch = cls.getProperties().find((p) => p.getName() === name);
678
- return exactMatch;
864
+ const exactMatch = cls.getProperties().find((p) => p.getName() === name);
865
+ return exactMatch;
679
866
  }
680
867
  function hasDecorator(node, name) {
681
- return node.getDecorators().some((d) => {
682
- const decoratorName = getDecoratorName(d);
683
- return decoratorName === name || decoratorName.endsWith("." + name);
684
- });
868
+ return node.getDecorators().some((d) => {
869
+ const decoratorName = getDecoratorName(d);
870
+ return decoratorName === name || decoratorName.endsWith("." + name);
871
+ });
685
872
  }
686
873
  function checkAttributeModifier(prop) {
687
- // Error: attributes must be just 'public'
688
- if (prop.getScope() != Scope.Public || prop.isReadonly() || prop.isStatic()) {
689
- return err(ExtractorErrorCode.InvalidAttributeModifier, (e) => {
690
- e.context = prop.getName();
691
- e.snippet = prop.getText();
692
- });
693
- }
874
+ // Error: attributes must be just 'public'
875
+ if (prop.getScope() != Scope.Public || prop.isReadonly() || prop.isStatic()) {
876
+ return err(ExtractorErrorCode.InvalidAttributeModifier, (e) => {
877
+ e.context = prop.getName();
878
+ e.snippet = prop.getText();
879
+ });
880
+ }
881
+ return Either.right(null);
694
882
  }