cloesce 0.0.4-unstable.8 → 0.0.5-unstable.0

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,681 +1,882 @@
1
- import { Node as MorphNode, SyntaxKind, Scope, } from "ts-morph";
2
- import { Either, HttpVerb, ExtractorError, ExtractorErrorCode, CloesceApp, } 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()));
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;
98
48
  }
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,
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();
107
55
  });
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.name) {
127
- return Either.right(sourceFile.getFilePath().toString());
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;
128
67
  }
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);
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;
145
79
  }
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
- });
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;
302
90
  }
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(),
328
- });
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
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;
98
+ }
99
+ const result = CidlExtractor.env(classDecl, sourceFile);
100
+ if (result.isLeft()) {
101
+ return result;
102
+ }
103
+ wranglerEnvs.push(result.unwrap());
352
104
  }
353
- return Either.right({
354
- name,
355
- attributes,
356
- source_path: sourceFile.getFilePath().toString(),
357
- });
105
+ }
358
106
  }
359
- static env(classDecl, sourceFile) {
360
- const binding = classDecl.getProperties().find((p) => {
361
- return (p
362
- .getType()
363
- .getText(undefined, TypeFormatFlags.UseAliasDefinedOutsideCurrentScope) === "D1Database");
364
- });
365
- if (!binding) {
366
- return err(ExtractorErrorCode.MissingDatabaseBinding);
367
- }
368
- return Either.right({
369
- name: classDecl.getName(),
370
- source_path: sourceFile.getFilePath().toString(),
371
- db_binding: binding.getName(),
372
- });
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);
373
130
  }
374
- static primTypeMap = {
375
- number: "Real",
376
- Number: "Real",
377
- Integer: "Integer",
378
- string: "Text",
379
- String: "Text",
380
- boolean: "Boolean",
381
- Boolean: "Boolean",
382
- 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
+ );
383
143
  };
384
- static cidlType(type, inject = false) {
385
- // Void
386
- if (type.isVoid()) {
387
- return Either.right("Void");
388
- }
389
- // Null
390
- if (type.isNull()) {
391
- return Either.right({ Nullable: "Void" });
392
- }
393
- // Nullable via union
394
- const [unwrappedType, nullable] = unwrapNullable(type);
395
- const tyText = unwrappedType
396
- .getText(undefined, TypeFormatFlags.UseAliasDefinedOutsideCurrentScope)
397
- .split("|")[0]
398
- .trim();
399
- // Primitives
400
- const prim = this.primTypeMap[tyText];
401
- if (prim) {
402
- return Either.right(wrapNullable(prim, nullable));
403
- }
404
- const generics = [
405
- ...unwrappedType.getAliasTypeArguments(),
406
- ...unwrappedType.getTypeArguments(),
407
- ];
408
- // Error: can't handle multiple generics
409
- if (generics.length > 1) {
410
- return err(ExtractorErrorCode.MultipleGenericType);
411
- }
412
- // No generics -> inject or object
413
- if (generics.length === 0) {
414
- const base = inject ? { Inject: tyText } : { Object: tyText };
415
- return Either.right(wrapNullable(base, nullable));
416
- }
417
- // Single generic
418
- const genericTy = generics[0];
419
- const symbolName = unwrappedType.getSymbol()?.getName();
420
- const aliasName = unwrappedType.getAliasSymbol()?.getName();
421
- if (aliasName === "DataSourceOf") {
422
- return Either.right(wrapNullable({
423
- DataSource: genericTy.getText(undefined, TypeFormatFlags.UseAliasDefinedOutsideCurrentScope),
424
- }, nullable));
425
- }
426
- if (aliasName === "DeepPartial") {
427
- const [_, genericTyNullable] = unwrapNullable(genericTy);
428
- const genericTyGenerics = [
429
- ...genericTy.getAliasTypeArguments(),
430
- ...genericTy.getTypeArguments(),
431
- ];
432
- // Expect partials to be of the exact form DeepPartial<Model>
433
- if (genericTyNullable ||
434
- genericTy.isUnion() ||
435
- genericTyGenerics.length > 0) {
436
- return err(ExtractorErrorCode.InvalidPartialType);
437
- }
438
- return Either.right(wrapNullable({
439
- Partial: genericTy
440
- .getText(undefined, TypeFormatFlags.UseAliasDefinedOutsideCurrentScope)
441
- .split("|")[0]
442
- .trim(),
443
- }, nullable));
444
- }
445
- if (symbolName === "Promise" || aliasName === "IncludeTree") {
446
- return wrapGeneric(genericTy, nullable, (inner) => inner);
447
- }
448
- if (unwrappedType.isArray()) {
449
- return wrapGeneric(genericTy, nullable, (inner) => ({ Array: inner }));
450
- }
451
- if (aliasName === "HttpResult") {
452
- return wrapGeneric(genericTy, nullable, (inner) => ({
453
- HttpResult: inner,
454
- }));
455
- }
456
- // Error: unknown type
457
- return err(ExtractorErrorCode.UnknownType);
458
- function wrapNullable(inner, isNullable) {
459
- if (isNullable) {
460
- return { Nullable: inner };
461
- }
462
- else {
463
- return inner;
464
- }
144
+ const typeText = getTypeText();
145
+ if (typeText === "CloesceApp") {
146
+ return Either.right(sourceFile.getFilePath().toString());
147
+ }
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;
465
181
  }
466
- function wrapGeneric(t, isNullable, wrapper) {
467
- const res = CidlExtractor.cidlType(t, inject);
468
- // Error: propogated from `cidlType`
469
- return res.map((inner) => wrapNullable(wrapper(inner), isNullable));
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;
470
211
  }
471
- function unwrapNullable(ty) {
472
- if (!ty.isUnion())
473
- return [ty, false];
474
- const unions = ty.getUnionTypes();
475
- const nonNulls = unions.filter((t) => !t.isNull() && !t.isUndefined());
476
- const hasNullable = nonNulls.length < unions.length;
477
- // Booleans seperate into [null, true, false] from the `getUnionTypes` call
478
- if (nonNulls.length === 2 &&
479
- nonNulls.every((t) => t.isBooleanLiteral())) {
480
- return [nonNulls[0].getApparentType(), hasNullable];
481
- }
482
- return [nonNulls[0] ?? ty, hasNullable];
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;
483
221
  }
484
- }
485
- static includeTree(expr, currentClass, sf) {
486
- // Include trees must be of the expected form
487
- if (!expr ||
488
- !expr.isKind ||
489
- !expr.isKind(SyntaxKind.ObjectLiteralExpression)) {
490
- return err(ExtractorErrorCode.InvalidIncludeTree);
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;
491
251
  }
492
- const result = {};
493
- for (const prop of expr.getProperties()) {
494
- if (!prop.isKind(SyntaxKind.PropertyAssignment))
495
- continue;
496
- // Error: navigation property not found
497
- const navProp = findPropertyByName(currentClass, prop.getName());
498
- if (!navProp) {
499
- return err(ExtractorErrorCode.UnknownNavigationPropertyReference, (e) => {
500
- e.snippet = expr.getText();
501
- e.context = prop.getName();
502
- });
503
- }
504
- const typeRes = CidlExtractor.cidlType(navProp.getType());
505
- // Error: invalid referenced nav prop type
506
- if (typeRes.isLeft()) {
507
- typeRes.value.snippet = navProp.getText();
508
- typeRes.value.context = prop.getName();
509
- return typeRes;
510
- }
511
- // Error: invalid referenced nav prop type
512
- const cidl_type = typeRes.unwrap();
513
- if (typeof cidl_type === "string") {
514
- return err(ExtractorErrorCode.InvalidNavigationPropertyReference, (e) => {
515
- ((e.snippet = navProp.getText()), (e.context = prop.getName()));
516
- });
517
- }
518
- // Recurse for nested includes
519
- const initializer = prop.getInitializer?.();
520
- let nestedTree = {};
521
- if (initializer?.isKind?.(SyntaxKind.ObjectLiteralExpression)) {
522
- const targetModel = getObjectName(cidl_type);
523
- const targetClass = currentClass
524
- .getSourceFile()
525
- .getProject()
526
- .getSourceFiles()
527
- .flatMap((f) => f.getClasses())
528
- .find((c) => c.getName() === targetModel);
529
- if (targetClass) {
530
- const treeRes = CidlExtractor.includeTree(initializer, targetClass, sf);
531
- // Error: Propogated from `includeTree`
532
- if (treeRes.isLeft()) {
533
- treeRes.value.snippet = expr.getText();
534
- return treeRes;
535
- }
536
- nestedTree = treeRes.unwrap();
537
- }
538
- }
539
- result[navProp.getName()] = nestedTree;
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;
540
281
  }
541
- return Either.right(result);
542
- }
543
- static method(modelName, method, httpVerb) {
544
- // Error: invalid method scope, must be public
545
- if (method.getScope() != Scope.Public) {
546
- return err(ExtractorErrorCode.InvalidApiMethodModifier, (e) => {
547
- e.context = method.getName();
548
- e.snippet = method.getText();
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();
549
289
  });
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;
550
307
  }
551
- let needsDataSource = !method.isStatic();
552
- const parameters = [];
553
- for (const param of method.getParameters()) {
554
- // Handle injected param
555
- if (param.getDecorator(ParameterDecoratorKind.Inject)) {
556
- const typeRes = CidlExtractor.cidlType(param.getType(), true);
557
- // Error: invalid type
558
- if (typeRes.isLeft()) {
559
- typeRes.value.snippet = method.getText();
560
- typeRes.value.context = param.getName();
561
- return typeRes;
562
- }
563
- parameters.push({
564
- name: param.getName(),
565
- cidl_type: typeRes.unwrap(),
566
- });
567
- continue;
568
- }
569
- // Handle all other params
570
- const typeRes = CidlExtractor.cidlType(param.getType());
571
- // Error: invalid type
572
- if (typeRes.isLeft()) {
573
- typeRes.value.snippet = method.getText();
574
- typeRes.value.context = param.getName();
575
- return typeRes;
576
- }
577
- if (typeof typeRes.value !== "string" && "DataSource" in typeRes.value) {
578
- needsDataSource = false;
579
- }
580
- parameters.push({
581
- name: param.getName(),
582
- cidl_type: typeRes.unwrap(),
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();
583
321
  });
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;
584
339
  }
585
- const typeRes = CidlExtractor.cidlType(method.getReturnType());
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);
586
388
  // Error: invalid type
587
389
  if (typeRes.isLeft()) {
588
- typeRes.value.snippet = method.getText();
589
- return typeRes;
390
+ typeRes.value.snippet = method.getText();
391
+ typeRes.value.context = param.getName();
392
+ return typeRes;
590
393
  }
591
- // Sugaring: add data source
592
- if (needsDataSource) {
593
- parameters.push({
594
- name: "__dataSource",
595
- cidl_type: { DataSource: modelName },
596
- });
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;
597
507
  }
598
- return Either.right({
599
- name: method.getName(),
600
- is_static: method.isStatic(),
601
- http_verb: httpVerb,
602
- return_type: typeRes.unwrap(),
603
- parameters,
508
+ parameters.push({
509
+ name: param.getName(),
510
+ cidl_type: typeRes.unwrap(),
604
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
+ });
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);
605
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
+ }
606
807
  }
607
808
  function err(code, fn) {
608
- let e = new ExtractorError(code);
609
- if (fn) {
610
- fn(e);
611
- }
612
- return Either.left(e);
809
+ let e = new ExtractorError(code);
810
+ if (fn) {
811
+ fn(e);
812
+ }
813
+ return Either.left(e);
613
814
  }
614
815
  function getDecoratorName(decorator) {
615
- const name = decorator.getName() ?? decorator.getExpression().getText();
616
- return String(name).replace(/\(.*\)$/, "");
816
+ const name = decorator.getName() ?? decorator.getExpression().getText();
817
+ return String(name).replace(/\(.*\)$/, "");
617
818
  }
618
819
  function getDecoratorArgument(decorator, index) {
619
- const args = decorator.getArguments();
620
- if (!args[index])
621
- return undefined;
622
- const arg = args[index];
623
- if (arg.getKind?.() === SyntaxKind.Identifier) {
624
- return arg.getText();
625
- }
626
- 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();
627
827
  }
628
828
  function getRootType(t) {
629
- if (typeof t === "string") {
630
- return t;
631
- }
632
- if ("Nullable" in t) {
633
- return getRootType(t.Nullable);
634
- }
635
- if ("Array" in t) {
636
- return getRootType(t.Array);
637
- }
638
- if ("HttpResult" in t) {
639
- return getRootType(t.HttpResult);
640
- }
829
+ if (typeof t === "string") {
641
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;
642
842
  }
643
843
  function getObjectName(t) {
644
- const root = getRootType(t);
645
- if (typeof root !== "string" && "Object" in root) {
646
- return root["Object"];
647
- }
648
- return undefined;
844
+ const root = getRootType(t);
845
+ if (typeof root !== "string" && "Object" in root) {
846
+ return root["Object"];
847
+ }
848
+ return undefined;
649
849
  }
650
850
  function setCrudKinds(d, cruds) {
651
- const arg = d.getArguments()[0];
652
- if (!arg) {
653
- return;
654
- }
655
- if (MorphNode.isArrayLiteralExpression(arg)) {
656
- for (const a of arg.getElements()) {
657
- cruds.add((MorphNode.isStringLiteral(a)
658
- ? a.getLiteralValue()
659
- : a.getText()));
660
- }
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
+ );
661
860
  }
861
+ }
662
862
  }
663
863
  function findPropertyByName(cls, name) {
664
- const exactMatch = cls.getProperties().find((p) => p.getName() === name);
665
- return exactMatch;
864
+ const exactMatch = cls.getProperties().find((p) => p.getName() === name);
865
+ return exactMatch;
666
866
  }
667
867
  function hasDecorator(node, name) {
668
- return node.getDecorators().some((d) => {
669
- const decoratorName = getDecoratorName(d);
670
- return decoratorName === name || decoratorName.endsWith("." + name);
671
- });
868
+ return node.getDecorators().some((d) => {
869
+ const decoratorName = getDecoratorName(d);
870
+ return decoratorName === name || decoratorName.endsWith("." + name);
871
+ });
672
872
  }
673
873
  function checkAttributeModifier(prop) {
674
- // Error: attributes must be just 'public'
675
- if (prop.getScope() != Scope.Public || prop.isReadonly() || prop.isStatic()) {
676
- return err(ExtractorErrorCode.InvalidAttributeModifier, (e) => {
677
- e.context = prop.getName();
678
- e.snippet = prop.getText();
679
- });
680
- }
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);
681
882
  }