uql-codemod 0.56.0 → 0.56.2

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 CHANGED
@@ -42,6 +42,8 @@ Only `--flag=value` is read, and anything unrecognised is an error. It exits `0`
42
42
  - Imports off `uql-orm/maria`, `uql-orm/mongo` and `uql-orm/bunSql` to `uql-orm/mariadb`, `uql-orm/mongodb` and `uql-orm/bun-sql`, and off `uql-orm/type`, `uql-orm/dialect`, `uql-orm/entity`, `uql-orm/querier` and `uql-orm/namingStrategy` to `uql-orm`.
43
43
  - A sole numeric key to the generated one it was: `f.number().id()` to `f.number().autoIncrement()`, `f.bigint().id()` to `f.bigint().autoIncrement()`, and `.autoIncrement()` on `f.column('int').id()`. `.autoIncrement(false)` is dropped, a key no longer needing it, and a key a relation shares stays as it is. A class's `id!` stays too, which an insert then has to name until it is `id?` or listed in `[filledKey]`. On MongoDB, take `.autoIncrement()` off a numeric key: nothing generates one there. A subclass's `.autoIncrement()` on a column that is no key, its key inherited, stays and has to go by hand.
44
44
  - The `[idKey]?: '...'` brand, and its import, on a key not called `id`, `_id` or `uuid` and on every composite.
45
+ - A `security: true` filter to the policy replacing it, where it reads the context as data: `tenant: { where: (ctx) => (ctx?.tenantId != null ? { companyId: ctx.tenantId } : undefined), security: true }` in `@Entity`'s or `defineEntity`'s `filters` to `policies: [{ must: { companyId: $context.tenantId } }]`, keeping its `ops`, a `.filters({ ... })` section to `.policies([...])`, and one a `@Filter` declares once it is folded into `@Entity`.
46
+ - A policy's `check` to the `$new` side of its predicate: `{ allow: W, check: C }` to `{ allow: { $old: W, $new: C } }` (`{ $new: C }` where `W` is `{}`), wherever the policy literal is written, and `explainPolicies(...).where` and `.check` to `.$old` and `.$new`.
45
47
 
46
48
  ## What it leaves to you
47
49
 
@@ -67,6 +69,8 @@ Reported with what to do, never guessed:
67
69
  - 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.
68
70
  - 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.
69
71
  - `Relation<T>` imported from `uql-orm`, which no longer exports it: write the property's type without it, and drop the import.
72
+ - A security filter it cannot read as data (a guard on another key, any other logic): declare it as a policy. A filter's `onMissing`, which no filter takes now: remove it.
73
+ - A destructuring of `explainPolicies`' answer, which names `$old` and `$new` now: rename what it reads.
70
74
 
71
75
  ## After it runs
72
76
 
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Each policy stating `check`, as the predicate it means: `{ allow: W, check: C }` reads the found row by `W` and the
3
+ * written one by `C`, so it is `{ allow: { $old: W, $new: C } }`, wherever the policy literal is written. Reads of
4
+ * `explainPolicies` go to their new sides; a destructuring of them is reported.
5
+ */
6
+ export declare function toSidedPolicies(fileName: string, text: string, locate: (at: number) => string): {
7
+ readonly text: string;
8
+ readonly unresolved: readonly string[];
9
+ };
@@ -0,0 +1,61 @@
1
+ import ts from 'typescript';
2
+ import { formatFindings } from './context.js';
3
+ import { applyEdits, original, removeFromList, replaced } from './edits.js';
4
+ import { identifierText, propertyAssignment, propertyValue } from './syntax.js';
5
+ /** What `explainPolicies` answered each side as, and what it answers it as now. */
6
+ const EXPLAINED = { where: '$old', check: '$new' };
7
+ /**
8
+ * Each policy stating `check`, as the predicate it means: `{ allow: W, check: C }` reads the found row by `W` and the
9
+ * written one by `C`, so it is `{ allow: { $old: W, $new: C } }`, wherever the policy literal is written. Reads of
10
+ * `explainPolicies` go to their new sides; a destructuring of them is reported.
11
+ */
12
+ export function toSidedPolicies(fileName, text, locate) {
13
+ if (!text.includes('uql-orm') || (!text.includes('check') && !text.includes('explainPolicies'))) {
14
+ return { text, unresolved: [] };
15
+ }
16
+ const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true);
17
+ const edits = [];
18
+ const findings = [];
19
+ const visit = (node) => {
20
+ const sided = ts.isObjectLiteralExpression(node) ? sidedPolicy(node, source) : undefined;
21
+ if (sided) {
22
+ edits.push(...sided);
23
+ return;
24
+ }
25
+ const renamed = ts.isPropertyAccessExpression(node) && explains(node.expression) && EXPLAINED[node.name.text];
26
+ if (renamed) {
27
+ edits.push(replaced(node.name, renamed));
28
+ }
29
+ if (ts.isVariableDeclaration(node) &&
30
+ ts.isObjectBindingPattern(node.name) &&
31
+ node.initializer &&
32
+ explains(node.initializer)) {
33
+ findings.push({
34
+ node,
35
+ message: "explainPolicies answers '$old' and '$new' now, where it answered 'where' and 'check': rename what you read",
36
+ });
37
+ }
38
+ ts.forEachChild(node, visit);
39
+ };
40
+ visit(source);
41
+ return { text: edits.length ? applyEdits(text, edits) : text, unresolved: formatFindings(findings, locate) };
42
+ }
43
+ /**
44
+ * The edits folding `policy`'s `check` into its predicate, the rest of it kept as written, or `undefined` for one
45
+ * stating none.
46
+ */
47
+ function sidedPolicy(policy, source) {
48
+ const check = propertyAssignment(policy, 'check');
49
+ const found = propertyValue(policy, 'allow') ?? propertyValue(policy, 'must');
50
+ if (!check || !found) {
51
+ return undefined;
52
+ }
53
+ const every = ts.isObjectLiteralExpression(found) && !found.properties.length;
54
+ const written = ['$new: ', original(check.initializer)];
55
+ const predicate = every ? ['{ ', ...written, ' }'] : ['{ $old: ', original(found), ', ', ...written, ' }'];
56
+ return [replaced(found, predicate), ...removeFromList(policy.properties, [check], source)];
57
+ }
58
+ /** Whether `node` calls `explainPolicies`. */
59
+ function explains(node) {
60
+ return ts.isCallExpression(node) && identifierText(node.expression) === 'explainPolicies';
61
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Each `security: true` filter that reads the context as data, as the `must` policy replacing it: in `@Entity`'s and
3
+ * `defineEntity`'s `filters`, a `.filters()` section becoming `.policies()`. Off the text the earlier passes wrote,
4
+ * so `@Filter` and `defineFilter` are folded in and every filter says `where`. Reports the rest, and an `onMissing`
5
+ * no filter takes now.
6
+ */
7
+ export declare function toPolicies(fileName: string, text: string, locate: (at: number) => string): {
8
+ readonly text: string;
9
+ readonly unresolved: readonly string[];
10
+ };
@@ -0,0 +1,192 @@
1
+ import ts from 'typescript';
2
+ import { formatFindings } from './context.js';
3
+ import { editedText, original, reparsedAgain } from './edits.js';
4
+ import { importEdits } from './imports.js';
5
+ import { isCallback, memberAccess } from './keyMaps.js';
6
+ import { chainOf, identifierText, isUndefined, namedProperty, objectLiteral, propertyKey, propertyValue, unwrapped, } from './syntax.js';
7
+ /** What a security filter states that its policy keeps (`where`, `ops`) or drops: any other leaves it to a human. */
8
+ const SECURITY_OPTIONS = new Set(['where', 'security', 'ops', 'onMissing', 'default']);
9
+ /**
10
+ * Each `security: true` filter that reads the context as data, as the `must` policy replacing it: in `@Entity`'s and
11
+ * `defineEntity`'s `filters`, a `.filters()` section becoming `.policies()`. Off the text the earlier passes wrote,
12
+ * so `@Filter` and `defineFilter` are folded in and every filter says `where`. Reports the rest, and an `onMissing`
13
+ * no filter takes now.
14
+ */
15
+ export function toPolicies(fileName, text, locate) {
16
+ if (!text.includes('security') && !text.includes('onMissing')) {
17
+ return { text, unresolved: [] };
18
+ }
19
+ const source = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true);
20
+ const edits = [];
21
+ const findings = [];
22
+ const report = (node, message) => findings.push({ node, message });
23
+ const visit = (node) => {
24
+ const filters = filtersOf(node);
25
+ const split = filters && splitFilters(filters.literal, report);
26
+ if (filters && split && filters.policiesStated) {
27
+ report(node, 'move its security filters into the policies it states by hand');
28
+ }
29
+ else if (filters && split) {
30
+ edits.push(filters.write(split.kept, `[${split.policies.join(', ')}]`));
31
+ }
32
+ if (!filters) {
33
+ ts.forEachChild(node, visit);
34
+ }
35
+ };
36
+ visit(source);
37
+ const written = edits.length
38
+ ? reparsedAgain(fileName, editedText(text, edits), (edited) => importEdits(edited, new Set(['$context']), new Set())).text
39
+ : text;
40
+ return { text: written, unresolved: formatFindings(findings, locate) };
41
+ }
42
+ /** The filters `node` declares: an entity's `filters` option, or a `defineEntity(...).filters({ ... })` section. */
43
+ function filtersOf(node) {
44
+ if (ts.isPropertyAssignment(node) &&
45
+ ts.isObjectLiteralExpression(node.parent) &&
46
+ propertyKey(node.name) === 'filters') {
47
+ const literal = objectLiteral(node.initializer);
48
+ return (literal && {
49
+ literal,
50
+ policiesStated: namedProperty(node.parent, 'policies') !== undefined,
51
+ write: (kept, policies) => ({
52
+ start: node.getStart(),
53
+ end: node.getEnd(),
54
+ text: [...(kept.length ? ['filters: ', ...braced(kept), ', '] : []), `policies: ${policies}`],
55
+ }),
56
+ });
57
+ }
58
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression)) {
59
+ return undefined;
60
+ }
61
+ const { name } = node.expression;
62
+ const literal = name.text === 'filters' ? objectLiteral(node.arguments[0]) : undefined;
63
+ if (!literal) {
64
+ return undefined;
65
+ }
66
+ const { root, methods } = chainOf(node);
67
+ if (!ts.isCallExpression(root) || identifierText(root.expression) !== 'defineEntity') {
68
+ return undefined;
69
+ }
70
+ return {
71
+ literal,
72
+ policiesStated: methods.some((method) => method.name === 'policies'),
73
+ write: (kept, policies) => ({
74
+ start: name.getStart(),
75
+ end: node.getEnd(),
76
+ text: [...(kept.length ? ['filters(', ...braced(kept), ').'] : []), `policies(${policies})`],
77
+ }),
78
+ };
79
+ }
80
+ /**
81
+ * The filters `literal` keeps, and the policies its security filters become; `undefined` where none becomes one.
82
+ * Reports a security filter it cannot read as data, and an `onMissing` no filter takes now.
83
+ */
84
+ function splitFilters(literal, report) {
85
+ const kept = [];
86
+ const policies = [];
87
+ for (const prop of literal.properties) {
88
+ const options = ts.isPropertyAssignment(prop) ? objectLiteral(prop.initializer) : undefined;
89
+ const name = ts.isPropertyAssignment(prop) ? propertyKey(prop.name) : undefined;
90
+ const security = options && namedProperty(options, 'security') !== undefined;
91
+ const policy = security ? policyOf(options) : undefined;
92
+ if (policy) {
93
+ policies.push(policy);
94
+ continue;
95
+ }
96
+ if (security) {
97
+ report(prop, `security filter '${name}' is a policy now: declare it in the entity's 'policies', see https://uql-orm.dev/upgrade-guide`);
98
+ }
99
+ else if (options && namedProperty(options, 'onMissing')) {
100
+ report(prop, `filter '${name}' gives 'onMissing', which no filter takes now: one is skipped where the context lacks a key it reads, so remove it`);
101
+ }
102
+ kept.push(prop);
103
+ }
104
+ return policies.length ? { kept, policies } : undefined;
105
+ }
106
+ /** The `must` policy a security filter's options become, keeping their `ops`, where they read the context as data. */
107
+ function policyOf(filter) {
108
+ const where = propertyValue(filter, 'where');
109
+ const known = filter.properties.every((prop) => ts.isPropertyAssignment(prop) && SECURITY_OPTIONS.has(propertyKey(prop.name)));
110
+ const must = propertyValue(filter, 'security')?.kind === ts.SyntaxKind.TrueKeyword && known && where ? mustOf(where) : undefined;
111
+ const ops = propertyValue(filter, 'ops');
112
+ return must && `{ must: ${must}${ops ? `, ops: ${ops.getText()}` : ''} }`;
113
+ }
114
+ /**
115
+ * A security filter's `where` as a policy's: a literal as it is, and a callback each of whose fields reads a context
116
+ * key, `(ctx) => ({ companyId: ctx?.tenantId })`, where it tests only that those keys are there, as data.
117
+ */
118
+ function mustOf(where) {
119
+ if (ts.isObjectLiteralExpression(where)) {
120
+ return where.getText();
121
+ }
122
+ if (!isCallback(where) || where.parameters.length !== 1) {
123
+ return undefined;
124
+ }
125
+ const context = identifierText(where.parameters[0].name);
126
+ const body = returned(where.body);
127
+ if (!context || !body) {
128
+ return undefined;
129
+ }
130
+ const guarded = ts.isConditionalExpression(body) && isUndefined(body.whenFalse);
131
+ const scope = unwrapped(guarded ? body.whenTrue : body);
132
+ if (!ts.isObjectLiteralExpression(scope) || !scope.properties.length) {
133
+ return undefined;
134
+ }
135
+ const entries = scope.properties.map((prop) => {
136
+ if (!ts.isPropertyAssignment(prop)) {
137
+ return undefined;
138
+ }
139
+ const key = contextKey(prop.initializer, context);
140
+ return key && [prop.name.getText(), key];
141
+ });
142
+ if (!entries.every((entry) => entry !== undefined)) {
143
+ return undefined;
144
+ }
145
+ const keys = new Set(entries.map(([, key]) => key));
146
+ const tested = guarded ? presenceKeys(body.condition, context) : [];
147
+ if (!tested || !tested.every((key) => keys.has(key))) {
148
+ return undefined;
149
+ }
150
+ return `{ ${entries.map(([field, key]) => `${field}: ${memberAccess('$context', key)}`).join(', ')} }`;
151
+ }
152
+ /** What a function body returns: its expression, or a block's one `return`. */
153
+ function returned(body) {
154
+ if (!ts.isBlock(body)) {
155
+ return unwrapped(body);
156
+ }
157
+ const [statement, ...rest] = body.statements;
158
+ return statement && !rest.length && ts.isReturnStatement(statement) && statement.expression
159
+ ? unwrapped(statement.expression)
160
+ : undefined;
161
+ }
162
+ /** The context key `value` reads off `context`, `ctx.tenantId`, `ctx?.tenantId` or `ctx!.tenantId`. */
163
+ function contextKey(value, context) {
164
+ const access = unwrapped(value);
165
+ return ts.isPropertyAccessExpression(access) && identifierText(unwrapped(access.expression)) === context
166
+ ? access.name.text
167
+ : undefined;
168
+ }
169
+ /**
170
+ * The keys a condition tests are there, as `ctx?.tenantId`, `ctx?.tenantId != null` or `!== undefined`, joined by
171
+ * `&&`; `undefined` for a condition testing anything else.
172
+ */
173
+ function presenceKeys(condition, context) {
174
+ const test = unwrapped(condition);
175
+ if (!ts.isBinaryExpression(test)) {
176
+ const key = contextKey(test, context);
177
+ return key ? [key] : undefined;
178
+ }
179
+ const { operatorToken: op, left, right } = test;
180
+ if (op.kind === ts.SyntaxKind.AmpersandAmpersandToken) {
181
+ const [a, b] = [presenceKeys(left, context), presenceKeys(right, context)];
182
+ return a && b && [...a, ...b];
183
+ }
184
+ const absent = isUndefined(right) || right.kind === ts.SyntaxKind.NullKeyword;
185
+ const unequal = op.kind === ts.SyntaxKind.ExclamationEqualsToken || op.kind === ts.SyntaxKind.ExclamationEqualsEqualsToken;
186
+ const key = absent && unequal ? contextKey(left, context) : undefined;
187
+ return key ? [key] : undefined;
188
+ }
189
+ /** `{ a, b }`, each property as it was written. */
190
+ function braced(props) {
191
+ return ['{ ', ...props.flatMap((prop, index) => [...(index ? [', '] : []), original(prop)]), ' }'];
192
+ }
package/dist/syntax.d.ts CHANGED
@@ -79,3 +79,7 @@ export declare const RELATION_DECORATORS: ReadonlySet<string | undefined>;
79
79
  export declare function lineStartOf(text: string, at: number): number;
80
80
  /** The whitespace the line holding `node` starts with. */
81
81
  export declare function indentOf(node: ts.Node): string;
82
+ /** `node` without the parentheses and `!` around it. */
83
+ export declare function unwrapped(node: ts.Expression): ts.Expression;
84
+ /** Whether `node` is `undefined`, as written or as `void 0`. */
85
+ export declare function isUndefined(node: ts.Expression): boolean;
package/dist/syntax.js CHANGED
@@ -199,3 +199,12 @@ export function indentOf(node) {
199
199
  const line = text.slice(lineStartOf(text, node.getStart()), node.getStart());
200
200
  return line.slice(0, line.length - line.trimStart().length);
201
201
  }
202
+ /** `node` without the parentheses and `!` around it. */
203
+ export function unwrapped(node) {
204
+ return ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node) ? unwrapped(node.expression) : node;
205
+ }
206
+ /** Whether `node` is `undefined`, as written or as `void 0`. */
207
+ export function isUndefined(node) {
208
+ const value = unwrapped(node);
209
+ return identifierText(value) === 'undefined' || ts.isVoidExpression(value);
210
+ }
package/dist/transform.js CHANGED
@@ -14,10 +14,12 @@ import { clashingName, deadImportNames, foreignNames, LEGACY_SQL_TAG, reportRemo
14
14
  import { rewriteBuilderIndexLengths, rewriteJsonIndexEntries } from './jsonIndex.js';
15
15
  import { entityGetterTarget, fieldKeysEdits, isCallback, keyListEdits, mappedByEdits, memberAccess, paramFor, quoted, referencesEdits, } from './keyMaps.js';
16
16
  import { toMigrationBuilders } from './migrationBuilders.js';
17
+ import { toSidedPolicies } from './policyChecks.js';
17
18
  import { relationTargetFor } from './relationTarget.js';
18
19
  import { toRelationTargets } from './relationTargets.js';
20
+ import { toPolicies } from './securityFilters.js';
19
21
  import { statementTemplate } from './statementSql.js';
20
- import { arrayElements, decoratorName, decoratorsOf, FIELD_DECORATORS, identifierText, indentOf, namedProperty, namedValue, objectLiteral, objectProperties, optionsOf, propertyKey, propertyValue, RELATION_DECORATORS, } from './syntax.js';
22
+ import { arrayElements, decoratorName, decoratorsOf, FIELD_DECORATORS, identifierText, indentOf, namedProperty, namedValue, objectLiteral, objectProperties, optionsOf, propertyKey, propertyValue, RELATION_DECORATORS, isUndefined, } from './syntax.js';
21
23
  const TO_ONE_DECORATORS = new Set(['OneToOne', 'ManyToOne']);
22
24
  const TO_ONE_CARDINALITIES = new Set(['11', 'm1']);
23
25
  /**
@@ -493,9 +495,6 @@ function isWriteOptions(node, ctx) {
493
495
  .map((property) => property.name);
494
496
  return names.length > 0 && names.every((name) => name === 'returning');
495
497
  }
496
- function isUndefined(node) {
497
- return identifierText(node) === 'undefined';
498
- }
499
498
  /** The value of options holding `update` alone, `{ update: value }` or `{ update }`. */
500
499
  function upsertUpdate(options) {
501
500
  const literal = objectLiteral(options);
@@ -755,14 +754,22 @@ export function transformFile(source, checker, options = { strictNullChecks: tru
755
754
  const legacy = rewriteLegacy(source, checker, options, taken);
756
755
  const located = (pass) => (at) => locationAt(source, pass.sourceOffset(at));
757
756
  const builders = toBuilders(source.fileName, legacy.text, { locate: located(legacy), taken });
758
- const migrated = toMigrationBuilders(source.fileName, builders.text, located(followed(legacy, builders)));
759
- const { unresolved } = migrated;
760
- const text = toRelationTargets(source.fileName, toGeneratedKeys(source.fileName, migrated.text));
757
+ const locate = located(followed(legacy, builders));
758
+ const migrated = toMigrationBuilders(source.fileName, builders.text, locate);
759
+ const policies = toPolicies(source.fileName, migrated.text, locate);
760
+ const sided = toSidedPolicies(source.fileName, policies.text, locate);
761
+ const text = toRelationTargets(source.fileName, toGeneratedKeys(source.fileName, sided.text));
761
762
  return {
762
763
  fileName: source.fileName,
763
764
  text,
764
765
  changed: text !== source.getFullText(),
765
- unresolved: [...legacy.unresolved, ...builders.unresolved, ...unresolved],
766
+ unresolved: [
767
+ ...legacy.unresolved,
768
+ ...builders.unresolved,
769
+ ...migrated.unresolved,
770
+ ...policies.unresolved,
771
+ ...sided.unresolved,
772
+ ],
766
773
  notes: legacy.notes,
767
774
  };
768
775
  }
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.56.0",
5
+ "version": "0.56.2",
6
6
  "type": "module",
7
7
  "engines": {
8
8
  "node": ">=22.18"