uql-codemod 0.54.0 → 0.56.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.
- package/README.md +3 -2
- package/dist/clientCalls.d.ts +8 -0
- package/dist/clientCalls.js +76 -0
- package/dist/definedEntity.js +1 -1
- package/dist/edits.d.ts +4 -3
- package/dist/edits.js +7 -3
- package/dist/imports.js +28 -7
- package/dist/relationTargets.d.ts +2 -0
- package/dist/relationTargets.js +31 -0
- package/dist/syntax.d.ts +1 -0
- package/dist/syntax.js +6 -0
- package/dist/transform.js +42 -15
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -26,12 +26,13 @@ Only `--flag=value` is read, and anything unrecognised is an error. It exits `0`
|
|
|
26
26
|
|
|
27
27
|
- `virtual` to `computed` (on `@Field` and in `defineEntity`'s `fields`), a check's `expression` and a filter's `condition` to `where` (`@Entity`, `defineEntity`, `@Filter`), `raw('...')` to the `sql` tagged template, and a second argument onto `.as()`.
|
|
28
28
|
- A column's options to its builder, last, after the rewrites above: `@Id()` and `@Field({ type: String, nullable: true, length: 80 })` to `@Field(f.number().autoIncrement())` and `@Field(f.string().nullable().length(80))`, a NOT NULL column losing its `nullable: false`, `computed` to `@Computed((row) => f.string().as(...))` or `@Computed((row) => row.books.count())`, and a defined entity's `fields` likewise; its other options to the sections chained after it, and its `aggregates` to `.relations()`' second callback. A defined column's foreign key becomes a relation: its `references` is dropped where a relation joins on the column (by `(order) => order.customerId`, by `[{ local, foreign }]` pairs, or as the ORM infers the one column naming its target, written into it), its `onDelete` moved into that relation, and where none joins, a `manyToOne` named as the column less its `Id` is written for it: `customer: () => rel.manyToOne(Customer, { references: (order) => order.customerId })`. Then each index, check and trigger entry, in `@Entity` and `defineEntity`, goes to the helper its callback is handed: `(post, index) => [index([post.title], 'by_title')]`.
|
|
29
|
+
- A relation decorator's target first, as `defineEntity`'s `rel.*` take it: `@ManyToOne({ entity: () => User, references })` to `@ManyToOne(() => User, { references })`, and `@OneToMany({ entity: () => Post })` to `@OneToMany(() => Post)`, last, after the rewrites reading its options.
|
|
29
30
|
- A migration's columns to the same methods: `table.string('email', { length: 80, nullable: true })` to `table.string('email').length(80).nullable()`, `.defaultValue()` to `.default()`, `.primaryKey()` to `.id()`, `.computed()` to `.as()`, and `.notNullable()` dropped.
|
|
30
31
|
- `@Index`, `@Trigger` and `@Filter` into `@Entity`'s `indexes`, `triggers` and `filters`, each decorator's comments kept above its entry; a class with no `@Entity` becomes `@Entity({ abstract: true, ... })`, a base that is never a table.
|
|
31
32
|
- Members named by string to callbacks: `mappedBy: 'author'` to `(post) => post.author`, and `include`, `references` and `@Entity`/`defineEntity`'s `indexes` and `hooks` likewise: `{ columns: (post) => [post.title] }`.
|
|
32
33
|
- `references: (post) => post.authorId` on a to-one (`@ManyToOne`, `@OneToOne`, or in `defineEntity`) that names no foreign key, declaring `@Field({ references: () => User }) authorId` first on a decorated class that has no such column, typed as the key it points at.
|
|
33
34
|
- A partial-index `where` string to `sql`, importing it, on entities and in the migration builder.
|
|
34
|
-
- A class registered with `defineEntity(Post, { ... })` to the `defineEntity({ ... })` call it stands for, whole or not at all: `export const Post = defineEntity({ name: 'Post', fields })` with its sections chained, as a defined entity's options are above, and `export
|
|
35
|
+
- A class registered with `defineEntity(Post, { ... })` to the `defineEntity({ ... })` call it stands for, whole or not at all: `export const Post = defineEntity({ name: 'Post', fields })` with its sections chained, as a defined entity's options are above, and `export interface Post extends InstanceType<typeof Post> {}`. The class is removed and a table it named kept as `table`; a field stating no `type` takes the one its property declares (`authorId?: number | null` is `f.number().nullable()`), each relation becomes `author: () => rel.manyToOne(User, { ... })`, a relation aggregate an aggregate field (`(post) => ({ total: () => post.comments.count() })`), a hook's method a function of the row (`this` read as the row), and the same class's `defineField`, `defineId`, `defineRelation`, `defineHook`, `defineIndex`, `defineTrigger` and `defineFilter` are folded in.
|
|
35
36
|
- A JSON index entry to the path read off the column's ref: `{ column: post.kind, jsonPath: { path: 'theme', type: Number } }` to `{ column: post.kind.theme, type: Number }`, and a `jsonArray`'s element type to `type: [String]`.
|
|
36
37
|
- `col('cost')` to the ref it names, ``(product) => sql`${product.cost}` `` in a `computed` and `refs(Item).cost` in a statement, and `$lock: { wait: 'skip' }` to `{ $wait: 'skip' }`, or to `true` for `{}` and a `'block'` wait.
|
|
37
38
|
- `$exclude` to a `$select` leaving its fields out: `$exclude: { password: true }` to `$select: { password: false }`, at every depth of `$populate`.
|
|
@@ -64,7 +65,7 @@ Reported with what to do, never guessed:
|
|
|
64
65
|
- A file that already names something the codemod would write (`sql`, `refs`, `idKey`, `f`, a renamed export): left unchanged and reported, since the new import would shadow it or be shadowed.
|
|
65
66
|
- A property whose type maps to no column (`Json<T>`, a vector, a mixed union).
|
|
66
67
|
- A column option it cannot write as a method: a `shape` a JSON column no longer takes, a migration column's options passed as a variable, or a flag such as `unique: isUnique` that no literal states.
|
|
67
|
-
- A `@Field`/`@Id` with no `type`, and a relation with no
|
|
68
|
+
- A `@Field`/`@Id` with no `type`, and a relation with no target: declare the column as a builder (`f.string()`) and pass the target first (`@ManyToOne(() => Target)`). A branded string id's column, `f.uuid()` or `f.string()`, is yours to pick.
|
|
68
69
|
- `Relation<T>` imported from `uql-orm`, which no longer exports it: write the property's type without it, and drop the import.
|
|
69
70
|
|
|
70
71
|
## After it runs
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import ts from 'typescript';
|
|
2
|
+
import type { Context } from './context.js';
|
|
3
|
+
/**
|
|
4
|
+
* `await client.findMany(...)`, which resolved to `{ data, count }` and now resolves to the value, as the pool's
|
|
5
|
+
* does: `(await ...).data` loses its `.data` (a `findManyAndCount`'s reads `[0]`, its `.count` `[1]`), `const { data: users } = await ...` becomes `const users = await ...`,
|
|
6
|
+
* and a `findManyAndCount`'s `{ data, count }` its `[data, count]`, a pair. Any other read of the result is reported.
|
|
7
|
+
*/
|
|
8
|
+
export declare function rewriteClientAwait(node: ts.AwaitExpression, ctx: Context): void;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import ts from 'typescript';
|
|
2
|
+
import { original, replaced } from './edits.js';
|
|
3
|
+
/** The browser client's types: what each of its reads and writes once resolved to an envelope. */
|
|
4
|
+
const CLIENTS = new Set(['HttpQuerier', 'ClientQuerier']);
|
|
5
|
+
/** The method of uql's browser client `call` makes, `undefined` for any other call. */
|
|
6
|
+
function clientMethod(call, ctx) {
|
|
7
|
+
const callee = call.expression;
|
|
8
|
+
if (!ts.isPropertyAccessExpression(callee)) {
|
|
9
|
+
return undefined;
|
|
10
|
+
}
|
|
11
|
+
const declarations = ctx.checker.getSymbolAtLocation(callee.name)?.declarations ?? [];
|
|
12
|
+
if (!declarations.some((it) => it.getSourceFile().fileName.includes('/node_modules/uql-orm/'))) {
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
const receiver = ctx.checker.getTypeAtLocation(callee.expression);
|
|
16
|
+
const name = receiver.getSymbol()?.getName();
|
|
17
|
+
return name && CLIENTS.has(name) ? callee.name.text : undefined;
|
|
18
|
+
}
|
|
19
|
+
/** What each envelope key a result read reads now: the value itself, or where `findManyAndCount`'s pair holds it. */
|
|
20
|
+
const ENVELOPE = new Map([['data', '']]);
|
|
21
|
+
const PAIR = new Map([
|
|
22
|
+
['data', '[0]'],
|
|
23
|
+
['count', '[1]'],
|
|
24
|
+
]);
|
|
25
|
+
/** `node` with the parentheses around it, the expression its parent reads. */
|
|
26
|
+
function outermost(node) {
|
|
27
|
+
return ts.isParenthesizedExpression(node.parent) ? outermost(node.parent) : node;
|
|
28
|
+
}
|
|
29
|
+
/** The binding of `key` in `pattern`, as `{ key }` or `{ key: local }` write it. */
|
|
30
|
+
function bindingOf(pattern, key) {
|
|
31
|
+
return pattern.elements.find((element) => (element.propertyName ?? element.name).getText() === key);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* `await client.findMany(...)`, which resolved to `{ data, count }` and now resolves to the value, as the pool's
|
|
35
|
+
* does: `(await ...).data` loses its `.data` (a `findManyAndCount`'s reads `[0]`, its `.count` `[1]`), `const { data: users } = await ...` becomes `const users = await ...`,
|
|
36
|
+
* and a `findManyAndCount`'s `{ data, count }` its `[data, count]`, a pair. Any other read of the result is reported.
|
|
37
|
+
*/
|
|
38
|
+
export function rewriteClientAwait(node, ctx) {
|
|
39
|
+
const call = node.expression;
|
|
40
|
+
const method = ts.isCallExpression(call) ? clientMethod(call, ctx) : undefined;
|
|
41
|
+
if (!method) {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
const pair = method === 'findManyAndCount';
|
|
45
|
+
const read = outermost(node);
|
|
46
|
+
const parent = read.parent;
|
|
47
|
+
// A result nobody reads, such as a delete's, changes nothing.
|
|
48
|
+
if (ts.isExpressionStatement(parent)) {
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if (ts.isPropertyAccessExpression(parent) && parent.expression === read) {
|
|
52
|
+
const at = (pair ? PAIR : ENVELOPE).get(parent.name.text);
|
|
53
|
+
if (at !== undefined) {
|
|
54
|
+
ctx.edits.push(replaced(parent, [original(read), at]));
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (ts.isVariableDeclaration(parent) && parent.initializer === read && ts.isObjectBindingPattern(parent.name)) {
|
|
59
|
+
const pattern = parent.name;
|
|
60
|
+
const data = bindingOf(pattern, 'data');
|
|
61
|
+
const count = bindingOf(pattern, 'count');
|
|
62
|
+
const bound = [data, count].filter(Boolean).length;
|
|
63
|
+
if (pair && bound && bound === pattern.elements.length) {
|
|
64
|
+
const rows = data ? [original(data.name)] : [];
|
|
65
|
+
const total = count ? [', ', original(count.name)] : [];
|
|
66
|
+
ctx.edits.push(replaced(pattern, ['[', ...rows, ...total, ']']));
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (data && pattern.elements.length === 1 && !pair) {
|
|
70
|
+
ctx.edits.push(replaced(pattern, [original(data.name)]));
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
ctx.report(node, `'${method}' answers the value now, not \`{ data, count }\`: read its result as it is` +
|
|
75
|
+
(pair ? ', `[rows, count]`' : ''));
|
|
76
|
+
}
|
package/dist/definedEntity.js
CHANGED
|
@@ -263,7 +263,7 @@ function definedOf(name, cls, calls, entityCall, unit) {
|
|
|
263
263
|
}
|
|
264
264
|
const prefix = exported ? 'export ' : '';
|
|
265
265
|
return {
|
|
266
|
-
text: `${prefix}const ${name} = defineEntity({\n${lines.map((line) => `${unit}${line},`).join('\n')}\n});\n${prefix}
|
|
266
|
+
text: `${prefix}const ${name} = defineEntity({\n${lines.map((line) => `${unit}${line},`).join('\n')}\n});\n${prefix}interface ${name} extends InstanceType<typeof ${name}> {}`,
|
|
267
267
|
notes,
|
|
268
268
|
};
|
|
269
269
|
}
|
package/dist/edits.d.ts
CHANGED
|
@@ -39,14 +39,15 @@ export declare function reparsedAgain(fileName: string, pass: Pass, edits: (sour
|
|
|
39
39
|
*/
|
|
40
40
|
export declare function editedText(source: string, edits: readonly Edit[]): Pass;
|
|
41
41
|
export declare function replaced(node: ts.Node, text: Replacement): Edit;
|
|
42
|
-
export declare function inserted(node: ts.Node, text:
|
|
42
|
+
export declare function inserted(node: ts.Node, text: Replacement): Edit;
|
|
43
43
|
export declare function appended(node: ts.Node, text: string): Edit;
|
|
44
44
|
/** `node`'s text with each of `uses`, the nodes inside it, written as `text`. */
|
|
45
45
|
export declare function replacingUses(node: ts.Node, uses: readonly ts.Node[], text: string): string;
|
|
46
46
|
/**
|
|
47
47
|
* Removes elements of a comma-separated list, at least one of them kept, with the separators that would dangle.
|
|
48
|
-
* Each removed element takes the text up to the next item; the removed run at the end
|
|
49
|
-
* it, so the ranges never overlap. `source` is passed because a tree from
|
|
48
|
+
* Each removed element takes the text up to the next item, short of that item's comments; the removed run at the end
|
|
49
|
+
* takes the separator before it, so the ranges never overlap. `source` is passed because a tree from
|
|
50
|
+
* `ts.parseJsonText` has no `getStart()`.
|
|
50
51
|
*/
|
|
51
52
|
export declare function removeFromList(items: readonly ts.Node[], removed: readonly ts.Node[], source: ts.SourceFile): readonly Edit[];
|
|
52
53
|
/**
|
package/dist/edits.js
CHANGED
|
@@ -92,15 +92,19 @@ export function replacingUses(node, uses, text) {
|
|
|
92
92
|
}
|
|
93
93
|
/**
|
|
94
94
|
* Removes elements of a comma-separated list, at least one of them kept, with the separators that would dangle.
|
|
95
|
-
* Each removed element takes the text up to the next item; the removed run at the end
|
|
96
|
-
* it, so the ranges never overlap. `source` is passed because a tree from
|
|
95
|
+
* Each removed element takes the text up to the next item, short of that item's comments; the removed run at the end
|
|
96
|
+
* takes the separator before it, so the ranges never overlap. `source` is passed because a tree from
|
|
97
|
+
* `ts.parseJsonText` has no `getStart()`.
|
|
97
98
|
*/
|
|
98
99
|
export function removeFromList(items, removed, source) {
|
|
99
100
|
const kept = items.map((item) => !removed.includes(item));
|
|
100
101
|
const lastKept = kept.lastIndexOf(true);
|
|
102
|
+
const upTo = (item, next) => ts.getLeadingCommentRanges(source.text, next.pos)?.length
|
|
103
|
+
? { start: item.pos, end: next.pos }
|
|
104
|
+
: { start: item.getStart(source), end: next.getStart(source) };
|
|
101
105
|
const between = items
|
|
102
106
|
.slice(0, lastKept + 1)
|
|
103
|
-
.flatMap((item, at) => kept[at] ? [] : [{
|
|
107
|
+
.flatMap((item, at) => (kept[at] ? [] : [{ ...upTo(item, items[at + 1]), text: '' }]));
|
|
104
108
|
const trailing = items.slice(lastKept + 1);
|
|
105
109
|
if (!trailing.length) {
|
|
106
110
|
return between;
|
package/dist/imports.js
CHANGED
|
@@ -7,13 +7,34 @@ import { inserted, removeFromList, removeStatement, replaced } from './edits.js'
|
|
|
7
7
|
*/
|
|
8
8
|
const REMOVED_EXPORTS = new Map([
|
|
9
9
|
['Relation', "write the property's type without it, and drop the import"],
|
|
10
|
-
[
|
|
11
|
-
'setQuerierPool',
|
|
12
|
-
'pass the pool where it is used: `createFetchHandler({ pool, include })`, `querierMiddleware({ pool, include })`',
|
|
13
|
-
],
|
|
10
|
+
['setQuerierPool', 'pass the pool where it is used: `createApi({ pool, include })`'],
|
|
14
11
|
['getQuerierPool', 'take the pool from the module that builds it, or from Nest DI'],
|
|
15
12
|
['getQuerier', 'use `pool.withQuerier(...)` / `pool.transaction(...)`, which release the connection'],
|
|
16
|
-
['ClientQuerierPool', "
|
|
13
|
+
['ClientQuerierPool', "build the client where it is used: `createClientQuerier(httpTransport('/api/v1'))`"],
|
|
14
|
+
[
|
|
15
|
+
'HttpQuerier',
|
|
16
|
+
'use `createClientQuerier(httpTransport(url, defaults))`, which answers what the pool answers: `rows`, not `{ data }`',
|
|
17
|
+
],
|
|
18
|
+
['HttpQuerierDefaults', '`httpTransport` takes `headers` and `readMethod`; `createClientQuerier` takes `entityPath`'],
|
|
19
|
+
['createRequestHandler', 'build the API with `createApi(opts)`, then `toRequestHandler(api)`'],
|
|
20
|
+
[
|
|
21
|
+
'createFetchHandler',
|
|
22
|
+
'build the API with `createApi(opts)`, then `toFetchHandler(api)`, mounted on a catch-all under the base',
|
|
23
|
+
],
|
|
24
|
+
['querierMiddleware', 'build the API with `createApi(opts)`, then `toExpress(api)`'],
|
|
25
|
+
['errorHandler', '`toExpress` answers every failure itself'],
|
|
26
|
+
['RequestHandlerOptions', 'use `ApiOptions`'],
|
|
27
|
+
['MiddlewareOptions', 'use `ApiOptions`'],
|
|
28
|
+
...['RequestHook', 'RequestHookContext', 'ResponseHook'].map((name) => [
|
|
29
|
+
name,
|
|
30
|
+
'write a middleware, `(call, context, next) => next(call)`, in `use` or `serve(Entity, { use })`',
|
|
31
|
+
]),
|
|
32
|
+
['RequestFindOptions', '`findManyAndCount` reads the count; a call takes `CallOptions`'],
|
|
33
|
+
['RequestNotification', 'wrap the transport: `createClientQuerier((call, opts) => ...)`'],
|
|
34
|
+
['RequestCallback', 'wrap the transport: `createClientQuerier((call, opts) => ...)`'],
|
|
35
|
+
['WireFlags', "a call's `hardDelete` is a field of the `WireCall`; `findManyAndCount` is an op of its own"],
|
|
36
|
+
...['RequestSuccessResponse', 'RequestCountedSuccessResponse', 'QuerierResult', 'QuerierCountedResult'].map((name) => [name, 'the client answers what the server does: the value, not an envelope']),
|
|
37
|
+
...['CRUD_ROUTES', 'CrudRoute', 'HttpMethod'].map((name) => [name, 'a call is `POST {base}/:entity/:op`, a read also `GET {base}/:entity/:op?q=`: see `encodeCall`']),
|
|
17
38
|
['QueryWhereFieldMap', 'use `QueryWhere`'],
|
|
18
39
|
['QueryStreamProjected', 'use `QueryProjected`'],
|
|
19
40
|
['RelationMappedBy', "a 'mappedBy' is `(keys: KeyMap<E>) => Key<E>` now"],
|
|
@@ -116,8 +137,8 @@ const RENAMED_EXPORTS = new Map([
|
|
|
116
137
|
['UqlLockUsageError', { to: 'UqlUsageError' }],
|
|
117
138
|
[LEGACY_SQL_TAG, { to: SQL_TAG }],
|
|
118
139
|
[`uql-orm/util#${LEGACY_SQL_TAG}`, { to: SQL_TAG, from: 'uql-orm' }],
|
|
119
|
-
['uql-orm/http#
|
|
120
|
-
['uql-orm/
|
|
140
|
+
['uql-orm/http#CrudOperation', { to: 'ApiOp' }],
|
|
141
|
+
['uql-orm/browser#RequestOptions', { to: 'CallOptions' }],
|
|
121
142
|
...UTIL_ROOT_EXPORTS.map((name) => [`uql-orm/util#${name}`, { to: name, from: 'uql-orm' }]),
|
|
122
143
|
]);
|
|
123
144
|
/** What the root exported that is internal now, and what to write instead. */
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import ts from 'typescript';
|
|
2
|
+
import { applyEdits, inserted, original, removeFromList, replaced } from './edits.js';
|
|
3
|
+
import { decoratorName, namedProperty, RELATION_DECORATORS } from './syntax.js';
|
|
4
|
+
/** `@ManyToOne(() => User, { references })` from `@ManyToOne({ entity: () => User, references })`, the rest kept as written. */
|
|
5
|
+
function targetFirst(options) {
|
|
6
|
+
const entity = namedProperty(options, 'entity');
|
|
7
|
+
if (!entity)
|
|
8
|
+
return [];
|
|
9
|
+
const target = original(ts.isPropertyAssignment(entity) ? entity.initializer : entity.name);
|
|
10
|
+
if (options.properties.length === 1)
|
|
11
|
+
return [replaced(options, [target])];
|
|
12
|
+
return [inserted(options, [target, ', ']), ...removeFromList(options.properties, [entity], options.getSourceFile())];
|
|
13
|
+
}
|
|
14
|
+
/** Passes each relation decorator's target first, as `defineEntity`'s `rel.*` take it. Off the text the other passes wrote. */
|
|
15
|
+
export function toRelationTargets(fileName, text) {
|
|
16
|
+
if (!/@(?:OneToOne|ManyToOne|OneToMany|ManyToMany)\(\s*\{/.test(text))
|
|
17
|
+
return text;
|
|
18
|
+
const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true);
|
|
19
|
+
const edits = [];
|
|
20
|
+
const visit = (node) => {
|
|
21
|
+
if (ts.isDecorator(node) && ts.isCallExpression(node.expression) && RELATION_DECORATORS.has(decoratorName(node))) {
|
|
22
|
+
const [options, ...rest] = node.expression.arguments;
|
|
23
|
+
if (options && !rest.length && ts.isObjectLiteralExpression(options)) {
|
|
24
|
+
edits.push(...targetFirst(options));
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
ts.forEachChild(node, visit);
|
|
28
|
+
};
|
|
29
|
+
visit(source);
|
|
30
|
+
return applyEdits(text, edits);
|
|
31
|
+
}
|
package/dist/syntax.d.ts
CHANGED
|
@@ -74,6 +74,7 @@ export declare function decoratorsOf(node: ts.Node): readonly ts.Decorator[];
|
|
|
74
74
|
export declare function decoratorName(node: ts.Decorator): string | undefined;
|
|
75
75
|
/** The decorators declaring a field: `@Field`, and `@Id` for the key the class names. */
|
|
76
76
|
export declare const FIELD_DECORATORS: ReadonlySet<string | undefined>;
|
|
77
|
+
export declare const RELATION_DECORATORS: ReadonlySet<string | undefined>;
|
|
77
78
|
/** Where the line holding offset `at` of `text` starts. */
|
|
78
79
|
export declare function lineStartOf(text: string, at: number): number;
|
|
79
80
|
/** The whitespace the line holding `node` starts with. */
|
package/dist/syntax.js
CHANGED
|
@@ -183,6 +183,12 @@ export function decoratorName(node) {
|
|
|
183
183
|
}
|
|
184
184
|
/** The decorators declaring a field: `@Field`, and `@Id` for the key the class names. */
|
|
185
185
|
export const FIELD_DECORATORS = new Set(['Field', 'Id']);
|
|
186
|
+
export const RELATION_DECORATORS = new Set([
|
|
187
|
+
'OneToOne',
|
|
188
|
+
'ManyToOne',
|
|
189
|
+
'OneToMany',
|
|
190
|
+
'ManyToMany',
|
|
191
|
+
]);
|
|
186
192
|
/** Where the line holding offset `at` of `text` starts. */
|
|
187
193
|
export function lineStartOf(text, at) {
|
|
188
194
|
return text.lastIndexOf('\n', at - 1) + 1;
|
package/dist/transform.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import ts from 'typescript';
|
|
2
2
|
import { BUILDER_NAMES, isBuilder, toBuilders } from './builders.js';
|
|
3
3
|
import { foldClassDecorators } from './classOptions.js';
|
|
4
|
+
import { rewriteClientAwait } from './clientCalls.js';
|
|
4
5
|
import { rewriteColumnRefs } from './columnRefs.js';
|
|
5
6
|
import { createContext, instanceTypeOf, locationAt, memberNames, ownerOf, } from './context.js';
|
|
6
7
|
import { toDefinedEntities } from './definedEntity.js';
|
|
@@ -14,9 +15,9 @@ import { rewriteBuilderIndexLengths, rewriteJsonIndexEntries } from './jsonIndex
|
|
|
14
15
|
import { entityGetterTarget, fieldKeysEdits, isCallback, keyListEdits, mappedByEdits, memberAccess, paramFor, quoted, referencesEdits, } from './keyMaps.js';
|
|
15
16
|
import { toMigrationBuilders } from './migrationBuilders.js';
|
|
16
17
|
import { relationTargetFor } from './relationTarget.js';
|
|
18
|
+
import { toRelationTargets } from './relationTargets.js';
|
|
17
19
|
import { statementTemplate } from './statementSql.js';
|
|
18
|
-
import { arrayElements, decoratorName, decoratorsOf, FIELD_DECORATORS, identifierText, indentOf, namedProperty, namedValue, objectLiteral, objectProperties, optionsOf, propertyKey, propertyValue, } from './syntax.js';
|
|
19
|
-
const RELATION_DECORATORS = new Set(['OneToOne', 'ManyToOne', 'OneToMany', 'ManyToMany']);
|
|
20
|
+
import { arrayElements, decoratorName, decoratorsOf, FIELD_DECORATORS, identifierText, indentOf, namedProperty, namedValue, objectLiteral, objectProperties, optionsOf, propertyKey, propertyValue, RELATION_DECORATORS, } from './syntax.js';
|
|
20
21
|
const TO_ONE_DECORATORS = new Set(['OneToOne', 'ManyToOne']);
|
|
21
22
|
const TO_ONE_CARDINALITIES = new Set(['11', 'm1']);
|
|
22
23
|
/**
|
|
@@ -208,6 +209,18 @@ function rewriteClassDecorators(node, ctx) {
|
|
|
208
209
|
}
|
|
209
210
|
}
|
|
210
211
|
}
|
|
212
|
+
/** `UqlModule.forRoot({ getContext })`, and its async form, as `{ contextOf }`, which the NestJS module names it now. */
|
|
213
|
+
function rewriteModuleCall(call, ctx) {
|
|
214
|
+
const callee = call.expression;
|
|
215
|
+
const [options] = call.arguments;
|
|
216
|
+
if (!options ||
|
|
217
|
+
!ts.isPropertyAccessExpression(callee) ||
|
|
218
|
+
!['forRoot', 'forRootAsync'].includes(callee.name.text) ||
|
|
219
|
+
uqlExport(callee.expression, ctx.checker) !== 'UqlModule') {
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
renameOption(optionsOf(options), 'getContext', 'contextOf', call, ctx);
|
|
223
|
+
}
|
|
211
224
|
/**
|
|
212
225
|
* Rewrites the imperative API the same way: `defineEntity(Post, { ... })`, `defineIndex(Post, { columns })`,
|
|
213
226
|
* `defineRelation(Post, 'tag', { mappedBy, references })` and `defineFilter(Post, 'live', { condition })`.
|
|
@@ -634,24 +647,34 @@ function rewriteProperty(node, ctx) {
|
|
|
634
647
|
renameSqlOption(options, 'virtual', 'computed', node, owner, ctx);
|
|
635
648
|
}
|
|
636
649
|
if (RELATION_DECORATORS.has(name)) {
|
|
637
|
-
|
|
638
|
-
option: 'entity',
|
|
639
|
-
satisfiedBy: ['entity'],
|
|
640
|
-
advice: 'name its target, `entity: () => Target`',
|
|
641
|
-
});
|
|
642
|
-
if (options.kind === 'literal') {
|
|
643
|
-
const target = relationTargetFor(ctx.checker.getTypeAtLocation(node), ctx.checker);
|
|
644
|
-
rewriteRelationOptions(options.node, owner.param, ctx, paramFor(target));
|
|
645
|
-
}
|
|
646
|
-
if (options.kind === 'literal' && TO_ONE_DECORATORS.has(name)) {
|
|
647
|
-
addForeignKeyReference(options.node, propertyKey(node.name), owner, ctx, node);
|
|
648
|
-
}
|
|
650
|
+
rewriteRelation(decorator, name, node, owner, ctx);
|
|
649
651
|
}
|
|
650
652
|
}
|
|
651
653
|
if (decorators.length) {
|
|
652
654
|
dropDeclare(node, ctx);
|
|
653
655
|
}
|
|
654
656
|
}
|
|
657
|
+
/** A relation decorator holding its target as `entity`, which a later pass moves first; one passing it first is current. */
|
|
658
|
+
function rewriteRelation(decorator, name, node, owner, ctx) {
|
|
659
|
+
const [first] = ts.isCallExpression(decorator.expression) ? decorator.expression.arguments : [];
|
|
660
|
+
if (first && isCallback(first)) {
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
reportMissingOption(decorator, node, ctx, {
|
|
664
|
+
option: 'entity',
|
|
665
|
+
satisfiedBy: ['entity'],
|
|
666
|
+
advice: 'pass its target first, `@ManyToOne(() => Target)`',
|
|
667
|
+
});
|
|
668
|
+
const options = decoratorOptions(decorator);
|
|
669
|
+
if (options.kind !== 'literal') {
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
const target = relationTargetFor(ctx.checker.getTypeAtLocation(node), ctx.checker);
|
|
673
|
+
rewriteRelationOptions(options.node, owner.param, ctx, paramFor(target));
|
|
674
|
+
if (TO_ONE_DECORATORS.has(name)) {
|
|
675
|
+
addForeignKeyReference(options.node, propertyKey(node.name), owner, ctx, node);
|
|
676
|
+
}
|
|
677
|
+
}
|
|
655
678
|
/** Whether a field decorator already declares its column with a builder, which states everything the rewrites add. */
|
|
656
679
|
function writesBuilder(decorator) {
|
|
657
680
|
const [first] = ts.isCallExpression(decorator.expression) ? decorator.expression.arguments : [];
|
|
@@ -734,7 +757,7 @@ export function transformFile(source, checker, options = { strictNullChecks: tru
|
|
|
734
757
|
const builders = toBuilders(source.fileName, legacy.text, { locate: located(legacy), taken });
|
|
735
758
|
const migrated = toMigrationBuilders(source.fileName, builders.text, located(followed(legacy, builders)));
|
|
736
759
|
const { unresolved } = migrated;
|
|
737
|
-
const text = toGeneratedKeys(source.fileName, migrated.text);
|
|
760
|
+
const text = toRelationTargets(source.fileName, toGeneratedKeys(source.fileName, migrated.text));
|
|
738
761
|
return {
|
|
739
762
|
fileName: source.fileName,
|
|
740
763
|
text,
|
|
@@ -768,6 +791,7 @@ export function rewriteLegacy(source, checker, options, taken = foreignNames(sou
|
|
|
768
791
|
}
|
|
769
792
|
if (ts.isCallExpression(node)) {
|
|
770
793
|
rewriteDefineCall(node, ctx);
|
|
794
|
+
rewriteModuleCall(node, ctx);
|
|
771
795
|
rewriteUpsertCall(node, ctx);
|
|
772
796
|
if (importsUql) {
|
|
773
797
|
rewriteBuilderCall(node, ctx);
|
|
@@ -780,6 +804,9 @@ export function rewriteLegacy(source, checker, options, taken = foreignNames(sou
|
|
|
780
804
|
if (ts.isPropertyAssignment(node)) {
|
|
781
805
|
rewriteStatementKeys(node, ctx);
|
|
782
806
|
}
|
|
807
|
+
if (ts.isAwaitExpression(node)) {
|
|
808
|
+
rewriteClientAwait(node, ctx);
|
|
809
|
+
}
|
|
783
810
|
if (importsUql && ts.isVariableDeclaration(node)) {
|
|
784
811
|
rewriteUpsertResult(node, ctx);
|
|
785
812
|
}
|