@stonecrop/schema 0.16.3 → 0.16.5

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/dist/schema.d.ts CHANGED
@@ -23,6 +23,15 @@ export declare const ActionDefinition: z.ZodObject<{
23
23
  */
24
24
  export declare type ActionDefinition = z.infer<typeof ActionDefinition>;
25
25
 
26
+ /**
27
+ * A doctype as it exists on disk: a plain object that may carry keys this package does not model
28
+ * (`handler` on an action, `filterFunction` on a field, whatever an app has added). Typing it
29
+ * loosely is what lets the merge round-trip those keys untouched instead of dropping them.
30
+ *
31
+ * @public
32
+ */
33
+ export declare type AuthoredDoctype = Record<string, unknown>;
34
+
26
35
  /**
27
36
  * Build a merged scalar map from the built-in maps and user-provided custom scalars.
28
37
  * Precedence (highest to lowest): customScalars → GQL_SCALAR_MAP → WELL_KNOWN_SCALARS
@@ -295,7 +304,7 @@ export declare const COMPONENT_LINK_EXPANSION: Record<string, LinkExpansion>;
295
304
  *
296
305
  * @public
297
306
  */
298
- export declare type ComponentCategory = 'text' | 'number' | 'boolean' | 'date' | 'datetime' | 'select' | 'code' | 'link' | 'attach' | 'quantity';
307
+ export declare type ComponentCategory = 'text' | 'number' | 'boolean' | 'date' | 'datetime' | 'select' | 'code' | 'link' | 'attach' | 'quantity' | 'currency';
299
308
 
300
309
  /**
301
310
  * Resolve a component's semantic category, or `undefined` for an unknown (custom) component —
@@ -464,6 +473,36 @@ export declare interface DoctypeContext {
464
473
  [key: string]: unknown;
465
474
  }
466
475
 
476
+ /**
477
+ * What generation found that the authored doctype does not agree with. Every bucket is advisory —
478
+ * nothing here is applied automatically.
479
+ *
480
+ * @public
481
+ */
482
+ export declare interface DoctypeDrift {
483
+ /** The authored doctype's name. */
484
+ doctype: string;
485
+ /**
486
+ * `clean` — the authored primary key is the one generation would derive.
487
+ * `partial` — the doctype declares an identity generation cannot derive, so identity was left alone.
488
+ */
489
+ mode: 'clean' | 'partial';
490
+ /** Why the mode is `partial`, when it is. */
491
+ reason?: string;
492
+ /** Fieldnames confirmed against the schema and stamped. */
493
+ tagged: string[];
494
+ /** Authored fields with no matching schema field — app components, fieldsets, or stale entries. */
495
+ orphan: string[];
496
+ /** Schema fields absent from the doctype. Usually deliberate curation, occasionally an oversight. */
497
+ omitted: string[];
498
+ /** `fieldname: authored=… schema=…` where the chosen component differs from the scalar mapping. */
499
+ componentDrift: string[];
500
+ /** `fieldname: authored=… schema=…` where nullability disagrees. */
501
+ requiredDrift: string[];
502
+ /** Identity properties that differ. These are the ones a human must adjudicate. */
503
+ identityDrift: string[];
504
+ }
505
+
467
506
  /**
468
507
  * Union of all authoring-time field variants.
469
508
  * Use `kind` to discriminate: `'field'` | `'fieldset'` | `'table'`.
@@ -676,6 +715,52 @@ export declare const FieldValidation: z.ZodObject<{
676
715
  */
677
716
  export declare type FieldValidation = z.infer<typeof FieldValidation>;
678
717
 
718
+ /**
719
+ * Render a drift report as human-readable lines. Empty when generation agrees with the doctype.
720
+ *
721
+ * @param drift - a report from {@link mergeIntrospectedDoctype}
722
+ * @returns one line per finding, ready to print
723
+ *
724
+ * @public
725
+ */
726
+ export declare function formatDoctypeDrift(drift: DoctypeDrift): string[];
727
+
728
+ /**
729
+ * Find the field a doctype marks as its primary key, or `undefined` when none is marked.
730
+ *
731
+ * This is the single definition of "which field identifies a record". Both sides depend on it:
732
+ * the middleware builds the SQL identity predicate from it, and the client resolves a record's
733
+ * route/store key from it. Call this; never re-derive the rule at the call site, or the two will
734
+ * drift and the client will key records by a column the server never queried.
735
+ *
736
+ * Two deliberate limits, both matching the shape `primaryKey` actually has:
737
+ * - Only **top-level** fields are scanned. `primaryKey` is a `ValueField` flag and a fieldset's
738
+ * children are not identity columns, so a nested match would be an authoring error, not a PK.
739
+ * - The **first** match wins. Nothing in the schema enforces exactly one `primaryKey: true`, and
740
+ * there is no composite-key representation — a doctype with several is already malformed, and
741
+ * picking the first is what the middleware has always done.
742
+ *
743
+ * @param fields - the doctype's top-level fields
744
+ * @returns the primary-key field, or `undefined` for a PK-less doctype
745
+ * @public
746
+ */
747
+ export declare function getPrimaryKeyField(fields: readonly DoctypeField[]): ValueField | undefined;
748
+
749
+ /**
750
+ * Resolve a record's identity value using the doctype's declared primary key.
751
+ *
752
+ * Falls back to `record.id` when the doctype declares no `primaryKey`. That fallback is
753
+ * load-bearing, not defensive: surrogate-key doctypes carry an `id` column and never mark a
754
+ * primary key, and PostGraphile renames a single-column `id` PK to `rowId` — so the declared
755
+ * field and `id` are both real sources, in that order.
756
+ *
757
+ * @param fields - the doctype's top-level fields
758
+ * @param record - the record to read the identity from
759
+ * @returns the identity as a string, or `undefined` when neither source yields a usable value
760
+ * @public
761
+ */
762
+ export declare function getRecordIdentity(fields: readonly DoctypeField[], record: Record<string, unknown>): string | undefined;
763
+
679
764
  /**
680
765
  * Options for fetching a single record
681
766
  * @public
@@ -760,19 +845,28 @@ export declare interface GraphQLConversionOptions {
760
845
  */
761
846
  include?: string[];
762
847
  /**
763
- * Per-type, per-field overrides for the converted field definitions.
764
- * Outer key is the GraphQL type name, inner key is the field name.
848
+ * Emit a doctype under a different name than its GraphQL type. Key is the GraphQL type name,
849
+ * value is the doctype `name`; `slug` is derived from the value.
850
+ *
851
+ * This exists for the case where a doctype is not one-to-one with a table — a second view over
852
+ * an existing type, say, distinguished only by presentation. Without it the converter can only
853
+ * ever name a doctype after its type.
854
+ *
855
+ * Keep it consistent with the middleware's `tables` option, which maps the resulting doctype
856
+ * name to its SQL target.
765
857
  *
766
858
  * @example
767
859
  * ```typescript
768
- * {
769
- * SalesOrder: {
770
- * totalAmount: { component: 'ANumericInput', align: 'right' }
771
- * }
772
- * }
860
+ * { Plan: 'Planner' } // emits a doctype named Planner, slug 'planner', from type Plan
773
861
  * ```
774
862
  */
775
- typeOverrides?: Record<string, Record<string, Omit<Partial<ValueField>, 'kind'>>>;
863
+ doctypeNames?: Record<string, string>;
864
+ /**
865
+ * Called with any advisory message raised during conversion — currently only the
866
+ * un-normalized-PostGraphile warning. Left to the caller so the library never writes to the
867
+ * console itself.
868
+ */
869
+ onWarning?: (message: string) => void;
776
870
  /**
777
871
  * Map custom or non-standard GraphQL scalar types to the component that renders them.
778
872
  * Merged with the built-in scalar maps (GQL_SCALAR_MAP + WELL_KNOWN_SCALARS).
@@ -853,6 +947,20 @@ export declare type InteractionMode = 'edit' | 'read' | 'display';
853
947
  */
854
948
  export declare const INTERNAL_SCALARS: Set<string>;
855
949
 
950
+ /**
951
+ * The field properties a `source: 'introspected'` marker freezes — the ones the database owns.
952
+ *
953
+ * This is the single definition of the identity set. The docbuilder greys these inputs on an
954
+ * introspected field, and the converter's merge refuses to rewrite them. Stating it twice is how
955
+ * the two drift, so both read this constant.
956
+ *
957
+ * Everything absent from this list is author-owned, `component` most importantly: it chooses the
958
+ * widget, which is an authoring decision the database has no opinion about.
959
+ *
960
+ * @public
961
+ */
962
+ export declare const INTROSPECTED_IDENTITY_PROPS: readonly ["fieldname", "primaryKey", "required", "options", "cardinality", "doctype"];
963
+
856
964
  /**
857
965
  * Input source for the GraphQL schema converter.
858
966
  * Accepts either a standard GraphQL introspection result or an SDL string.
@@ -956,6 +1064,32 @@ export declare type LinkExpansion = 'inline' | 'expand';
956
1064
  */
957
1065
  export declare type LinkRenderMode = 'inline' | 'record' | 'table';
958
1066
 
1067
+ /**
1068
+ * Verify an authored doctype against freshly generated output and stamp provenance.
1069
+ *
1070
+ * @param authored - the doctype as it exists on disk; every key not named below is preserved verbatim
1071
+ * @param generated - `convertGraphQLSchema` output for the corresponding GraphQL type
1072
+ * @returns the doctype to write, plus a drift report
1073
+ *
1074
+ * @example
1075
+ * ```ts
1076
+ * const [generated] = convertGraphQLSchema(introspection, { include: ['Uom'] })
1077
+ * const { doctype, drift } = mergeIntrospectedDoctype(JSON.parse(onDisk), generated)
1078
+ * if (drift.identityDrift.length) console.warn(drift.identityDrift.join('\n'))
1079
+ * ```
1080
+ *
1081
+ * @public
1082
+ */
1083
+ export declare function mergeIntrospectedDoctype(authored: AuthoredDoctype, generated: ConvertedGraphQLDoctype): MergeResult;
1084
+
1085
+ /** Outcome of a merge: the doctype to write, plus what generation disagreed with. @public */
1086
+ export declare interface MergeResult {
1087
+ /** The authored doctype with `source` markers added and nothing else changed. */
1088
+ doctype: AuthoredDoctype;
1089
+ /** Advisory report. Never applied. */
1090
+ drift: DoctypeDrift;
1091
+ }
1092
+
959
1093
  /**
960
1094
  * Recursively injects the `kind` discriminant into a raw field object and, for fieldsets,
961
1095
  * into each of its nested `schema` children — mirroring exactly what Zod's `preprocess`
package/dist/src/cli.js CHANGED
@@ -16,7 +16,7 @@ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
16
16
  import { resolve, join } from 'node:path';
17
17
  import { parseArgs } from 'node:util';
18
18
  import { getIntrospectionQuery } from 'graphql';
19
- import { convertGraphQLSchema } from './converter/index';
19
+ import { convertGraphQLSchema, formatDoctypeDrift, mergeIntrospectedDoctype } from './converter/index';
20
20
  import { validateDoctype } from './validation';
21
21
  /**
22
22
  * Fetch an introspection result from a live GraphQL endpoint.
@@ -58,9 +58,10 @@ async function main() {
58
58
  output: { type: 'string', short: 'o' },
59
59
  include: { type: 'string' },
60
60
  exclude: { type: 'string' },
61
- overrides: { type: 'string' },
61
+ names: { type: 'string' },
62
62
  'custom-scalars': { type: 'string' },
63
63
  'include-unmapped': { type: 'boolean', default: false },
64
+ check: { type: 'boolean', default: false },
64
65
  help: { type: 'boolean', short: 'h' },
65
66
  },
66
67
  });
@@ -95,11 +96,11 @@ async function main() {
95
96
  if (values.exclude) {
96
97
  options.exclude = values.exclude.split(',').map(s => s.trim());
97
98
  }
98
- if (values.overrides) {
99
- const overridesPath = resolve(values.overrides);
100
- const overridesContent = readFileSync(overridesPath, 'utf-8');
101
- options.typeOverrides = JSON.parse(overridesContent);
99
+ if (values.names) {
100
+ const namesPath = resolve(values.names);
101
+ options.doctypeNames = JSON.parse(readFileSync(namesPath, 'utf-8'));
102
102
  }
103
+ options.onWarning = message => console.warn(` WARN: ${message}`);
103
104
  if (values['custom-scalars']) {
104
105
  const scalarsPath = resolve(values['custom-scalars']);
105
106
  const scalarsContent = readFileSync(scalarsPath, 'utf-8');
@@ -134,13 +135,35 @@ async function main() {
134
135
  }
135
136
  let warnings = 0;
136
137
  let errors = 0;
137
- for (const doctype of doctypes) {
138
- const fileName = `${doctype.slug}.json`;
138
+ let changed = 0;
139
+ const driftLines = [];
140
+ for (const generated of doctypes) {
141
+ const fileName = `${generated.slug}.json`;
139
142
  const filePath = join(outputDir, fileName);
140
- const json = JSON.stringify(doctype, null, '\t');
141
- writeFileSync(filePath, json + '\n', 'utf-8');
143
+ // When a doctype already exists it is the source of truth: generation confirms it and adds
144
+ // provenance markers, and reports anything it disagrees with rather than applying it. A
145
+ // doctype legitimately declares identity the schema cannot express — most often a natural
146
+ // key that is a UNIQUE constraint, not the table's PRIMARY KEY — and overwriting that would
147
+ // silently re-key the doctype on every run. A first generation has nothing to merge into,
148
+ // so converter output is written verbatim.
149
+ let output = generated;
150
+ if (existsSync(filePath)) {
151
+ const { doctype: merged, drift } = mergeIntrospectedDoctype(JSON.parse(readFileSync(filePath, 'utf-8')), generated);
152
+ output = merged;
153
+ driftLines.push(...formatDoctypeDrift(drift));
154
+ }
155
+ // Serialize the merged object directly. Never round-trip it through the Zod parser first:
156
+ // that runs in strip mode and would silently drop every key this package does not model,
157
+ // `handler` on an action being the one consumers actually rely on.
158
+ const json = JSON.stringify(output, null, '\t') + '\n';
159
+ const unchanged = existsSync(filePath) && readFileSync(filePath, 'utf-8') === json;
160
+ if (!unchanged)
161
+ changed++;
162
+ if (!values.check && !unchanged) {
163
+ writeFileSync(filePath, json, 'utf-8');
164
+ }
142
165
  // Validate the output
143
- const validation = validateDoctype(doctype);
166
+ const validation = validateDoctype(output);
144
167
  if (!validation.success) {
145
168
  errors++;
146
169
  console.error(` ERROR: ${fileName} failed validation:`);
@@ -150,7 +173,7 @@ async function main() {
150
173
  }
151
174
  else {
152
175
  // Check for unmapped fields
153
- const unmappedFields = doctype.fields.filter((f) => f._unmapped);
176
+ const unmappedFields = generated.fields.filter((f) => f._unmapped);
154
177
  if (unmappedFields.length > 0) {
155
178
  warnings++;
156
179
  console.warn(` WARN: ${fileName} has ${unmappedFields.length} unmapped field(s): ${unmappedFields
@@ -159,10 +182,16 @@ async function main() {
159
182
  }
160
183
  }
161
184
  }
162
- console.log(`\nGenerated ${doctypes.length} doctype(s) in ${outputDir}` +
185
+ if (driftLines.length > 0) {
186
+ console.log('\nDrift between the authored doctypes and the schema (reported, not applied):');
187
+ for (const line of driftLines)
188
+ console.log(line);
189
+ }
190
+ console.log(`\n${values.check ? 'Checked' : 'Generated'} ${doctypes.length} doctype(s) in ${outputDir}` +
191
+ (changed ? ` (${changed} ${values.check ? 'would change' : 'written'})` : ' (all up to date)') +
163
192
  (warnings ? ` (${warnings} with warnings)` : '') +
164
193
  (errors ? ` (${errors} with errors)` : ''));
165
- if (errors > 0) {
194
+ if (errors > 0 || (values.check && changed > 0)) {
166
195
  process.exit(1);
167
196
  }
168
197
  }
@@ -184,11 +213,16 @@ OUTPUT:
184
213
  OPTIONS:
185
214
  --include <types> Comma-separated list of type names to include
186
215
  --exclude <types> Comma-separated list of type names to exclude
187
- --overrides <file> JSON file with per-type field overrides
216
+ --names <file> JSON file mapping GraphQL type name to doctype name
188
217
  --custom-scalars <file> JSON file mapping custom scalar names to field templates
189
218
  --include-unmapped Include _graphqlType metadata on unmapped fields
219
+ --check Report drift and exit non-zero if anything would change; write nothing
190
220
  --help, -h Show this help message
191
221
 
222
+ NOTE: an existing doctype file is the source of truth. Regeneration verifies it against the
223
+ schema and adds 'source: introspected' markers; it reports disagreements rather than
224
+ overwriting them, so hand-curation survives. Use --check in CI.
225
+
192
226
  EXAMPLES:
193
227
  # From a live PostGraphile server
194
228
  stonecrop-schema generate -e http://localhost:5000/graphql -o ./schemas
@@ -9,7 +9,7 @@
9
9
  *
10
10
  * @public
11
11
  */
12
- export type ComponentCategory = 'text' | 'number' | 'boolean' | 'date' | 'datetime' | 'select' | 'code' | 'link' | 'attach' | 'quantity';
12
+ export type ComponentCategory = 'text' | 'number' | 'boolean' | 'date' | 'datetime' | 'select' | 'code' | 'link' | 'attach' | 'quantity' | 'currency';
13
13
  /**
14
14
  * Canonical component → semantic category. Only the components Stonecrop ships with appear here;
15
15
  * custom/unknown component names have no category and consumers fall back to their default.
@@ -1 +1 @@
1
- {"version":3,"file":"component-meta.d.ts","sourceRoot":"","sources":["../../src/component-meta.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,MAAM,iBAAiB,GAC5B,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,MAAM,GAAG,UAAU,GAAG,QAAQ,GAAG,MAAM,GAAG,MAAM,GAAG,QAAQ,GAAG,UAAU,CAAA;AAEzG;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAgBhE,CAAA;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,iBAAiB,GAAG,SAAS,CAEnF;AAED;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,aAAa,GAAG,QAAQ,GAAG,QAAQ,CAAA;AAE/C;;;;;GAKG;AACH,eAAO,MAAM,wBAAwB,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAIlE,CAAA;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,aAAa,GAAG,SAAS,CAEpF;AAED;;;;;;;;;GASG;AACH,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,QAAQ,GAAG,OAAO,CAAA;AAE1D;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,qBAAqB,CACpC,IAAI,EAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,EAClD,cAAc,CAAC,EAAE,MAAM,GACrB,cAAc,CAGhB;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,oBAAoB,EAAE,SAAS,MAAM,EAEtC,CAAA"}
1
+ {"version":3,"file":"component-meta.d.ts","sourceRoot":"","sources":["../../src/component-meta.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,MAAM,iBAAiB,GAC5B,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,MAAM,GAAG,UAAU,GAAG,QAAQ,GAAG,MAAM,GAAG,MAAM,GAAG,QAAQ,GAAG,UAAU,GAAG,UAAU,CAAA;AAEtH;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAiBhE,CAAA;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,iBAAiB,GAAG,SAAS,CAEnF;AAED;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,aAAa,GAAG,QAAQ,GAAG,QAAQ,CAAA;AAE/C;;;;;GAKG;AACH,eAAO,MAAM,wBAAwB,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAIlE,CAAA;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,aAAa,GAAG,SAAS,CAEpF;AAED;;;;;;;;;GASG;AACH,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,QAAQ,GAAG,OAAO,CAAA;AAE1D;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,qBAAqB,CACpC,IAAI,EAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,EAClD,cAAc,CAAC,EAAE,MAAM,GACrB,cAAc,CAGhB;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,oBAAoB,EAAE,SAAS,MAAM,EAEtC,CAAA"}
@@ -19,6 +19,7 @@ export const COMPONENT_CATEGORY = {
19
19
  AFormLink: 'link',
20
20
  AFileAttach: 'attach',
21
21
  AQuantityInput: 'quantity',
22
+ ACurrencyInput: 'currency',
22
23
  };
23
24
  /**
24
25
  * Resolve a component's semantic category, or `undefined` for an unknown (custom) component —
@@ -43,5 +43,7 @@ export { convertGraphQLSchema as default };
43
43
  export type { IntrospectionSource, GraphQLConversionOptions, GraphQLConversionFieldMeta, ConvertedGraphQLDoctype, } from './types';
44
44
  export { GQL_SCALAR_MAP, WELL_KNOWN_SCALARS, INTERNAL_SCALARS, buildScalarMap } from './scalars';
45
45
  export { defaultIsEntityType, defaultIsEntityField, classifyFieldType } from './heuristics';
46
+ export { mergeIntrospectedDoctype, formatDoctypeDrift } from './merge';
47
+ export type { AuthoredDoctype, DoctypeDrift, MergeResult } from './merge';
46
48
  export { toSlug, toPascalCase, pascalToSnake, snakeToCamel, camelToSnake, snakeToLabel, camelToLabel } from '../naming';
47
49
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/converter/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAMH,OAAO,KAAK,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAA;AAIrG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,oBAAoB,CACnC,MAAM,EAAE,mBAAmB,EAC3B,OAAO,GAAE,wBAA6B,GACpC,uBAAuB,EAAE,CA+H3B;AAwBD,OAAO,EAAE,oBAAoB,IAAI,OAAO,EAAE,CAAA;AAG1C,YAAY,EACX,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAC1B,uBAAuB,GACvB,MAAM,SAAS,CAAA;AAGhB,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAGhG,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAG3F,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/converter/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAMH,OAAO,KAAK,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAA;AAIrG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,oBAAoB,CACnC,MAAM,EAAE,mBAAmB,EAC3B,OAAO,GAAE,wBAA6B,GACpC,uBAAuB,EAAE,CAkJ3B;AAwBD,OAAO,EAAE,oBAAoB,IAAI,OAAO,EAAE,CAAA;AAG1C,YAAY,EACX,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAC1B,uBAAuB,GACvB,MAAM,SAAS,CAAA;AAGhB,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAGhG,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAG3F,OAAO,EAAE,wBAAwB,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAA;AACtE,YAAY,EAAE,eAAe,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAGzE,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA"}
@@ -86,8 +86,18 @@ export function convertGraphQLSchema(source, options = {}) {
86
86
  if (!isObjectType(type))
87
87
  continue;
88
88
  const fields = type.getFields();
89
- const typeOverrides = options.typeOverrides?.[typeName];
90
- const entityFields = Object.entries(fields).filter(([fieldName, field]) => isEntityField(fieldName, field, type));
89
+ // A type carrying BOTH `id` and `rowId` is PostGraphile Amber with its default inflection:
90
+ // the Relay global identifier has taken `id`, displacing the real column to `rowId`. Neither
91
+ // name can be emitted as-is — `id` is an opaque node id, and `rowId` does not name a column.
92
+ // Refuse to guess: drop the Relay field and tell the caller to fix it at the inflector, where
93
+ // it belongs. Normalizing here would bake a database fact into the doctype.
94
+ const isUnnormalizedPostGraphile = 'id' in fields && 'rowId' in fields;
95
+ if (isUnnormalizedPostGraphile) {
96
+ options.onWarning?.(`${typeName}: schema exposes both 'id' (Relay identifier) and 'rowId' (the real column). ` +
97
+ `Skipping 'id' and emitting 'rowId' verbatim — no primary key can be derived. ` +
98
+ `Override the '_attributeName' and 'nodeIdFieldName' inflectors so the column keeps its own name.`);
99
+ }
100
+ const entityFields = Object.entries(fields).filter(([fieldName, field]) => isEntityField(fieldName, field, type) && !(isUnnormalizedPostGraphile && fieldName === 'id'));
91
101
  // oxlint-disable-next-line oxc/no-map-spread -- ...custom spread required; Object.assign cannot preserve the metadata-carrying inferred union type from classifyField
92
102
  const allClassifiedFields = entityFields.map(([fieldName, field]) => {
93
103
  // Check for full custom classification first
@@ -104,13 +114,14 @@ export function convertGraphQLSchema(source, options = {}) {
104
114
  }
105
115
  }
106
116
  // Default classification
107
- const classified = classifyFieldType(fieldName, field, entityTypes, options);
108
- // Apply per-field overrides
109
- if (typeOverrides?.[fieldName]) {
110
- return Object.assign(classified, typeOverrides[fieldName]);
111
- }
112
- return classified;
117
+ return classifyFieldType(fieldName, field, entityTypes, options);
113
118
  });
119
+ // Derive the primary key, but only for the one case SDL actually settles: a non-null `id`
120
+ // that is a plain scalar. A natural key is typically a UNIQUE constraint indistinguishable
121
+ // from any other column here, and a table may carry several — so anything else is left for
122
+ // the author to declare. Emitting a guess would be worse than emitting nothing, because the
123
+ // middleware builds its identity predicate from this and the client keys records by it.
124
+ const primaryKeyFieldname = allClassifiedFields.find(field => field.fieldname === 'id' && field.required && !field.doctype && !field._isLink)?.fieldname;
114
125
  // Separate scalar fields from link fields
115
126
  const links = {};
116
127
  const convertedFields = allClassifiedFields
@@ -124,21 +135,22 @@ export function convertGraphQLSchema(source, options = {}) {
124
135
  }
125
136
  return true;
126
137
  })
127
- // Clean up internal metadata unless requested, and stamp provenance.
128
- // Stamped last so every classification path (default, classifyField,
129
- // typeOverrides) carries the marker — the docbuilder's identity lock
130
- // keys off it, and an override must not be able to unset it.
138
+ // Clean up internal metadata unless requested, and stamp identity + provenance.
139
+ // Stamped last so every classification path (default, classifyField) carries the marker —
140
+ // the docbuilder's identity lock keys off it, and no classifier may unset it.
131
141
  .map(field => {
142
+ const identity = field.fieldname === primaryKeyFieldname ? { primaryKey: true } : {};
132
143
  if (!options.includeUnmappedMeta) {
133
144
  const { _graphqlType, _unmapped, _isLink, ...clean } = field;
134
- return Object.assign(clean, { source: 'introspected' });
145
+ return Object.assign(clean, identity, { source: 'introspected' });
135
146
  }
136
147
  const { _isLink, ...rest } = field;
137
- return Object.assign(rest, { source: 'introspected' });
148
+ return Object.assign(rest, identity, { source: 'introspected' });
138
149
  });
150
+ const doctypeName = options.doctypeNames?.[typeName] ?? typeName;
139
151
  const doctype = {
140
- name: typeName,
141
- slug: toSlug(typeName),
152
+ name: doctypeName,
153
+ slug: toSlug(doctypeName),
142
154
  fields: convertedFields,
143
155
  };
144
156
  if (Object.keys(links).length > 0) {
@@ -175,5 +187,7 @@ export { convertGraphQLSchema as default };
175
187
  export { GQL_SCALAR_MAP, WELL_KNOWN_SCALARS, INTERNAL_SCALARS, buildScalarMap } from './scalars';
176
188
  // Heuristics
177
189
  export { defaultIsEntityType, defaultIsEntityField, classifyFieldType } from './heuristics';
190
+ // Merge — verifies an authored doctype against the schema and stamps provenance
191
+ export { mergeIntrospectedDoctype, formatDoctypeDrift } from './merge';
178
192
  // Naming utilities
179
193
  export { toSlug, toPascalCase, pascalToSnake, snakeToCamel, camelToSnake, snakeToLabel, camelToLabel } from '../naming';
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Merge introspected schema facts into an already-authored doctype.
3
+ *
4
+ * The authored doctype is the source of truth. Generation **verifies** it and stamps provenance;
5
+ * it does not overwrite. That polarity is deliberate and load-bearing — a doctype legitimately
6
+ * declares a `primaryKey` the schema cannot express. A natural business key is very often a
7
+ * `UNIQUE` constraint rather than the table's `PRIMARY KEY`, and where a table carries several
8
+ * uniques no rule can pick between them. Overwriting identity from the schema would silently
9
+ * re-key such a doctype on every regeneration and break the handlers that key on the old value.
10
+ *
11
+ * So divergence is **reported, never applied** — a human decides. The only mutation this performs
12
+ * is adding `source: 'introspected'` to fields confirmed to exist in the GraphQL schema.
13
+ *
14
+ * @packageDocumentation
15
+ */
16
+ import type { ConvertedGraphQLDoctype } from './types';
17
+ /**
18
+ * A doctype as it exists on disk: a plain object that may carry keys this package does not model
19
+ * (`handler` on an action, `filterFunction` on a field, whatever an app has added). Typing it
20
+ * loosely is what lets the merge round-trip those keys untouched instead of dropping them.
21
+ *
22
+ * @public
23
+ */
24
+ export type AuthoredDoctype = Record<string, unknown>;
25
+ /**
26
+ * What generation found that the authored doctype does not agree with. Every bucket is advisory —
27
+ * nothing here is applied automatically.
28
+ *
29
+ * @public
30
+ */
31
+ export interface DoctypeDrift {
32
+ /** The authored doctype's name. */
33
+ doctype: string;
34
+ /**
35
+ * `clean` — the authored primary key is the one generation would derive.
36
+ * `partial` — the doctype declares an identity generation cannot derive, so identity was left alone.
37
+ */
38
+ mode: 'clean' | 'partial';
39
+ /** Why the mode is `partial`, when it is. */
40
+ reason?: string;
41
+ /** Fieldnames confirmed against the schema and stamped. */
42
+ tagged: string[];
43
+ /** Authored fields with no matching schema field — app components, fieldsets, or stale entries. */
44
+ orphan: string[];
45
+ /** Schema fields absent from the doctype. Usually deliberate curation, occasionally an oversight. */
46
+ omitted: string[];
47
+ /** `fieldname: authored=… schema=…` where the chosen component differs from the scalar mapping. */
48
+ componentDrift: string[];
49
+ /** `fieldname: authored=… schema=…` where nullability disagrees. */
50
+ requiredDrift: string[];
51
+ /** Identity properties that differ. These are the ones a human must adjudicate. */
52
+ identityDrift: string[];
53
+ }
54
+ /** Outcome of a merge: the doctype to write, plus what generation disagreed with. @public */
55
+ export interface MergeResult {
56
+ /** The authored doctype with `source` markers added and nothing else changed. */
57
+ doctype: AuthoredDoctype;
58
+ /** Advisory report. Never applied. */
59
+ drift: DoctypeDrift;
60
+ }
61
+ /**
62
+ * Verify an authored doctype against freshly generated output and stamp provenance.
63
+ *
64
+ * @param authored - the doctype as it exists on disk; every key not named below is preserved verbatim
65
+ * @param generated - `convertGraphQLSchema` output for the corresponding GraphQL type
66
+ * @returns the doctype to write, plus a drift report
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * const [generated] = convertGraphQLSchema(introspection, { include: ['Uom'] })
71
+ * const { doctype, drift } = mergeIntrospectedDoctype(JSON.parse(onDisk), generated)
72
+ * if (drift.identityDrift.length) console.warn(drift.identityDrift.join('\n'))
73
+ * ```
74
+ *
75
+ * @public
76
+ */
77
+ export declare function mergeIntrospectedDoctype(authored: AuthoredDoctype, generated: ConvertedGraphQLDoctype): MergeResult;
78
+ /**
79
+ * Render a drift report as human-readable lines. Empty when generation agrees with the doctype.
80
+ *
81
+ * @param drift - a report from {@link mergeIntrospectedDoctype}
82
+ * @returns one line per finding, ready to print
83
+ *
84
+ * @public
85
+ */
86
+ export declare function formatDoctypeDrift(drift: DoctypeDrift): string[];
87
+ //# sourceMappingURL=merge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"merge.d.ts","sourceRoot":"","sources":["../../../src/converter/merge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAA;AAEtD;;;;;;GAMG;AACH,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAErD;;;;;GAKG;AACH,MAAM,WAAW,YAAY;IAC5B,mCAAmC;IACnC,OAAO,EAAE,MAAM,CAAA;IACf;;;OAGG;IACH,IAAI,EAAE,OAAO,GAAG,SAAS,CAAA;IACzB,6CAA6C;IAC7C,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,2DAA2D;IAC3D,MAAM,EAAE,MAAM,EAAE,CAAA;IAChB,mGAAmG;IACnG,MAAM,EAAE,MAAM,EAAE,CAAA;IAChB,qGAAqG;IACrG,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB,mGAAmG;IACnG,cAAc,EAAE,MAAM,EAAE,CAAA;IACxB,oEAAoE;IACpE,aAAa,EAAE,MAAM,EAAE,CAAA;IACvB,mFAAmF;IACnF,aAAa,EAAE,MAAM,EAAE,CAAA;CACvB;AAED,6FAA6F;AAC7F,MAAM,WAAW,WAAW;IAC3B,iFAAiF;IACjF,OAAO,EAAE,eAAe,CAAA;IACxB,sCAAsC;IACtC,KAAK,EAAE,YAAY,CAAA;CACnB;AAuBD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,eAAe,EAAE,SAAS,EAAE,uBAAuB,GAAG,WAAW,CA4EnH;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,YAAY,GAAG,MAAM,EAAE,CAYhE"}