uql-codemod 0.55.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.
@@ -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/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', "construct the `HttpQuerier` where it is used, `new HttpQuerier('/api')`"],
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#Hook', { to: 'RequestHook' }],
120
- ['uql-orm/http#HookContext', { to: 'RequestHookContext' }],
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. */
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';
@@ -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 })`.
@@ -778,6 +791,7 @@ export function rewriteLegacy(source, checker, options, taken = foreignNames(sou
778
791
  }
779
792
  if (ts.isCallExpression(node)) {
780
793
  rewriteDefineCall(node, ctx);
794
+ rewriteModuleCall(node, ctx);
781
795
  rewriteUpsertCall(node, ctx);
782
796
  if (importsUql) {
783
797
  rewriteBuilderCall(node, ctx);
@@ -790,6 +804,9 @@ export function rewriteLegacy(source, checker, options, taken = foreignNames(sou
790
804
  if (ts.isPropertyAssignment(node)) {
791
805
  rewriteStatementKeys(node, ctx);
792
806
  }
807
+ if (ts.isAwaitExpression(node)) {
808
+ rewriteClientAwait(node, ctx);
809
+ }
793
810
  if (importsUql && ts.isVariableDeclaration(node)) {
794
811
  rewriteUpsertResult(node, ctx);
795
812
  }
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "uql-codemod",
3
3
  "description": "Upgrade uql-orm across versions that introduce breaking changes",
4
4
  "license": "MIT",
5
- "version": "0.55.0",
5
+ "version": "0.56.0",
6
6
  "type": "module",
7
7
  "engines": {
8
8
  "node": ">=22.18"