@kronor/dtv 13.0.2 → 13.0.3

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,65 @@
1
+ import { getNamedType, isObjectType } from 'graphql';
2
+ import { loadDefinitionsConfig } from '../config/loadConfig.js';
3
+ import { loadProject } from '../definitions/loadProject.js';
4
+ /*
5
+ * A column whose data is a single scalar field is sorted by that field unless it says
6
+ * otherwise, and a column can name any field it selects. GraphQL orders by a JSON field
7
+ * as readily as by any other, but the order means nothing to a user, and an export that
8
+ * pages through the rows by the sorted field cannot page by a JSON value. So the typegen,
9
+ * which has the schema, fails on every column sorted by one. The fix is
10
+ * `orderBy: Orderable.notOrderable`, or sorting by a scalar field.
11
+ */
12
+ /** The scalars a column cannot be sorted by. */
13
+ export const UNORDERABLE_SCALARS = new Set(['json', 'jsonb']);
14
+ /**
15
+ * The type a dotted path through the row ends in, or null when the schema has no such
16
+ * path: a field the row does not have is not this check's to report.
17
+ */
18
+ export function orderByTypeOf(schema, rowTypeName, orderBy) {
19
+ let type = schema.getType(rowTypeName) ?? undefined;
20
+ for (const field of orderBy.split('.')) {
21
+ if (!type || !isObjectType(type))
22
+ return null;
23
+ const definition = type.getFields()[field];
24
+ if (!definition)
25
+ return null;
26
+ type = getNamedType(definition.type);
27
+ }
28
+ return type ?? null;
29
+ }
30
+ export function findUnorderableColumns(schema, views) {
31
+ return views.flatMap(({ viewId, rowTypeName, columns }) => Object.entries(columns).flatMap(([columnId, { orderBy }]) => {
32
+ if (orderBy === null)
33
+ return [];
34
+ const type = orderByTypeOf(schema, rowTypeName, orderBy);
35
+ return type !== null && UNORDERABLE_SCALARS.has(type.name)
36
+ ? [{ viewId, columnId, orderBy, scalar: type.name }]
37
+ : [];
38
+ }));
39
+ }
40
+ export function describeUnorderableColumns(columns) {
41
+ return [
42
+ 'Columns sorted by a JSON field:',
43
+ ...columns.map(c => `- ${c.viewId}: column ${JSON.stringify(c.columnId)} sorts by ${JSON.stringify(c.orderBy)} (${c.scalar})`),
44
+ 'A JSON field has no meaningful order, and an export cannot page through the rows by it. '
45
+ + 'Set `orderBy: Orderable.notOrderable` on the column, or sort it by a scalar field.'
46
+ ].join('\n');
47
+ }
48
+ /** The views as `dtv definitions` builds them: through the project's own Vite. */
49
+ export async function loadColumnOrdering(configPath) {
50
+ const config = await loadDefinitionsConfig(configPath);
51
+ const project = await loadProject({ cwd: process.cwd(), config });
52
+ return {
53
+ columnsOf: viewId => {
54
+ if (project.definitions[viewId] === undefined)
55
+ return undefined;
56
+ try {
57
+ return project.projectDefinition(viewId, 1).columns;
58
+ }
59
+ catch {
60
+ return undefined;
61
+ }
62
+ },
63
+ close: () => project.close()
64
+ };
65
+ }
@@ -4,6 +4,7 @@ import fg from 'fast-glob';
4
4
  import ts from 'typescript';
5
5
  import { loadConfig, resolveSchema } from '../config/loadConfig.js';
6
6
  import { collectReachableTypes, fetchSchema, renderTsFromSchema, singleQuoteStringLiteral, toIdentifier, toPascalCase, unwrapCollectionElementType, } from '@kronor/hasura-graphql/typegen';
7
+ import { describeUnorderableColumns, findUnorderableColumns, loadColumnOrdering, } from './orderingCheck.js';
7
8
  async function writeFileEnsuringDir(filePath, content) {
8
9
  await fs.mkdir(path.dirname(filePath), { recursive: true });
9
10
  await fs.writeFile(filePath, content, 'utf8');
@@ -710,11 +711,38 @@ export async function runTypegen(args) {
710
711
  else {
711
712
  console.log(`Generated types for ${written.length} of ${viewRows.length} view(s).`);
712
713
  }
714
+ // After the types are written: the view modules import them.
715
+ const ordering = await (args.loadColumnOrdering ?? loadColumnOrdering)(args.configPath);
716
+ const checked = [];
717
+ const unchecked = [];
718
+ try {
719
+ for (const v of viewRows) {
720
+ const columns = ordering.columnsOf(v.viewId);
721
+ if (columns === undefined)
722
+ unchecked.push(v.viewId);
723
+ else
724
+ checked.push({ viewId: v.viewId, rowTypeName: v.rowTypeName, columns });
725
+ }
726
+ }
727
+ finally {
728
+ await ordering.close();
729
+ }
730
+ if (unchecked.length) {
731
+ console.warn(`Warning: did not check what the columns of ${unchecked.map(id => JSON.stringify(id)).join(', ')} are sorted by — \`dtv definitions check\` says why they cannot be built.`);
732
+ }
733
+ const unorderable = findUnorderableColumns(schema, checked);
734
+ const errors = [];
713
735
  if (failed.length) {
714
736
  const lines = ['Type generation failed for:'];
715
737
  for (const f of failed)
716
738
  lines.push(`- ${f.viewId}: ${f.message}`);
717
739
  lines.push('Their committed generated types are unchanged and may now be stale.');
718
- throw new Error(lines.join('\n'));
740
+ errors.push(lines.join('\n'));
741
+ }
742
+ if (unorderable.length) {
743
+ errors.push(describeUnorderableColumns(unorderable));
744
+ }
745
+ if (errors.length) {
746
+ throw new Error(errors.join('\n\n'));
719
747
  }
720
748
  }