@omnicajs/graphql-precise-dts
v0.5.1
Published
GraphQL files type declaration generator
Maintainers
Readme
graphql-precise-dts
@omnicajs/graphql-precise-dts is a GraphQL Code Generator plugin that generates TypeScript declaration files for GraphQL documents.
The generated outputs:
- keep fragment and operation types scoped to the corresponding
.graphqlmodule; - generate
TypedDocumentNodedeclarations for operations; - emit schema support files with scalar mappings (
schema.d.ts) and enum declarations (enums.ts); - account for directives that can change the runtime response shape;
- process directives in two stages:
- structural policies change whether selections are included, conditional, or forced non-null;
- generation policies can override rendered field types or emit warnings;
- support documents that contain multiple fragments, multiple operations, or their combination in the same
.graphqlfile.
Repository status
Current repository layout keeps the plugin implementation and the test generation pipeline separate:
- the plugin implementation lives in
src/; - unit tests live in
tests/units; - type-level tests live in
tests/types; - fixture GraphQL documents live in
tests/fixtures/documents; - test-only generated declarations are written to
tests/fixtures/generated.
The repository test suite validates both:
- unit-level behavior of internal modules such as path resolution, renderers, directive handling, planning, and model builders;
- consumer-facing TypeScript behavior against declarations generated by the plugin from test fixtures.
Installation
Install the plugin together with its runtime type dependencies:
yarn add -D @graphql-codegen/cli @omnicajs/graphql-precise-dts
yarn add graphql @graphql-typed-document-node/core@graphql-typed-document-node/core is required because generated declarations import TypedDocumentNode from that package.
[!IMPORTANT] Generated declaration files are resolved by the TypeScript project that includes or publishes them, not necessarily by the workspace where GraphQL Code Generator is configured. Make sure
@graphql-typed-document-node/coreis available from the package or workspace that contains or consumes the generated declarations. In a monorepo, installing it only next to the codegen config may be insufficient if the declarations are emitted into another package.If generated schema support files are imported through an alias by consumer code, configure a matching plugin
pathsentry as well. Otherwise generated declarations can fall back to relative imports for the same files, which may make TypeScript see different module specifiers for the same generated types.
Usage
Example GraphQL Code Generator config:
import type { CodegenConfig } from '@graphql-codegen/cli'
import {
NAMING_STYLE,
defineString,
} from '@omnicajs/graphql-precise-dts'
const config: CodegenConfig = {
schema: 'src/schema.graphql',
documents: [ 'src/**/*.graphql' ],
generates: {
'types/graphql-documents.d.ts': {
plugins: [ '@omnicajs/graphql-precise-dts' ],
config: {
prefix: '~/',
scope: 'src/',
relativeToCwd: false,
schemaOutputDirectory: 'schema',
paths: {
'@app/generated/*': [ 'types/schema/*' ],
},
scalars: {
DateTime: defineString(),
},
namingConvention: NAMING_STYLE.PASCAL_CASE,
},
},
},
}
export default configFor this repository itself, fixture declarations used by type tests are generated with:
yarn generate:test-fixturesOutput
For a target like:
types/graphql-documents.d.tsthe plugin produces:
types/graphql-documents.d.tswithdeclare module '...'blocks for GraphQL documents;types/schema.d.tswith schema-level TypeScript declarations such asScalars, input object types, object/interface output types, unions, and field argument types;types/enums.tswith schema enum declarations when the schema contains enum types.
schema.d.ts imports enum types from the sibling enums.ts file when schema declarations reference those enums:
import type { Permission } from './enums'
export type Scalars = {
String: { input: string; output: string; };
}
export type User = {
permission: Permission;
}Enum declarations are rendered in enums.ts:
export enum Permission {
GroupCreate = 'GroupCreate',
GroupEdit = 'GroupEdit',
}The plugin does not write enums.ts when the schema does not contain enum declarations.
GraphQL document declarations import enum types directly from enums.ts; they do not import enums from schema.d.ts.
Schema JSDoc
Generated schema support files preserve GraphQL SDL descriptions and selected standard directives as JSDoc.
This includes schema descriptions, @deprecated(reason: "..."), scalar @specifiedBy(url: "..."), and scalar
replacement remarks such as Scalars['DateTime']['output'].
See Schema JSDoc for supported locations and examples.
By default, schema support files are written next to the generated declaration file. Configure
schemaOutputDirectory to write them elsewhere:
{
schemaOutputDirectory: 'schema',
}For the target above, this writes support files under types/schema/:
types/schema/schema.d.tstypes/schema/enums.ts
Relative schemaOutputDirectory values are resolved from the generated declaration file directory.
Absolute values are used as-is.
Operation declarations are emitted as typed document exports:
export type GetUserQuery = ...
export type GetUserQueryVariables = Exact<...>
export const getUserQuery: TypedDocumentNode<GetUserQuery, GetUserQueryVariables>
export default getUserQueryWhen repeated or recursive input/output object shapes appear in generated types, the plugin may lift them into
named type declarations and render their usage sites as references to those aliases. This keeps recursive
structures representable and reduces duplication in the emitted declarations.
Generated export names share the same declaration namespace inside each emitted declare module '...' block.
Before rendering a document bundle, the plugin validates that:
- imported enum and fragment type names do not collide with generated fragment exports, operation payload/variables types, or generated aliases;
- generated variable and output aliases are renamed with numeric suffixes such as
TreeInput2when their preferred names are already occupied; - operation document value exports such as
getUserQueryremain unique within the same document bundle.
If two different declarations still resolve to the same exported name after normalization, generation fails with a name-collision diagnostic that identifies both sources.
Collision checks are split by TypeScript namespace:
- type namespace:
- imported type names;
- fragment exports;
- generated variable aliases;
- generated output aliases;
- operation
...Variablesexports; - operation
...Payloadexports.
- value namespace:
- operation document exports such as
getUserQuery.
- operation document exports such as
Type exports are validated only against other type exports. Value exports are validated only against other value
exports. This matches TypeScript namespace rules for type and const declarations.
If a single .graphql file contains multiple definitions, the plugin emits all matching fragment and operation
declarations into the same declare module '...' block.
If the same fragment name is defined more than once inside a single .graphql file, the plugin emits a warning and
keeps the first definition from that file. Later definitions with the same fragment name are ignored for that module,
including definitions that target a different GraphQL type.
The same fragment type name may appear in different .graphql files. Each file still gets its own
declare module '...' block, so the duplicated fragment type name is scoped to the module declaration for that
document. Fragment spreads first resolve to a fragment declared in the same document module. External fragment spreads
must be backed by that file's #import declarations, and the import source is resolved from the imported document.
Missing #import declarations, multiple imported documents that define the same external fragment name, and #import
declarations that point outside the configured documents fail generation with an error instead of emitting an arbitrary
import.
If a configured document references a fragment that is missing from the plugin documents input, the plugin emits
a warning that names the missing fragment definition and the document that referenced it.
If a field selection, field argument, fragment type condition, or inline fragment type condition references something that is not present in the GraphQL schema, generation fails with a schema diagnostic instead of emitting declarations for an incomplete result shape.
If a selection set repeats the same field or fragment spread directly, the plugin emits a warning with source locations for the redundant selections, even when those selections can be merged safely.
These warnings are emitted only for direct repeats within the same selection set level. Repeats that become visible only after flattening inline fragments are still merged in the generated output, but they are not reported as redundant direct repeats.
These warnings are diagnostics only. They do not change the generated output or recover external fragment definitions automatically.
If the same selection set contains repeated selections with the same response name, the plugin tries
to merge them using GraphQL-compatible field merging rules. Compatible repeats such as id + id,
repeated fragment spreads, or id plus ... on User { id } are deduplicated.
Field selections are merged only when all of the following stay compatible:
- they resolve to the same target field name;
- they use the same field arguments;
- they keep the same nullability and list structure;
- they keep the same override type policy result;
- their nested result value shapes stay compatible.
Repeated fragment spreads are deduplicated only when they target the same fragment type information.
Incompatible repeats such as name: nickname + name: id, or the same response name with different field arguments,
still fail generation with a conflict diagnostic.
Development scripts
yarn lint
yarn lint:fix
yarn test:units
yarn test:types
yarn tests
yarn test:coverage
yarn generate:test-fixturesyarn tests is the main verification entry point in this repository. It regenerates test fixture declarations and
then runs the full Vitest suite with type checks.
__typename behavior
The plugin keeps explicit __typename selections and also synthesizes fallback __typename values when they are needed
to describe the response shape precisely.
- for object-like results, fallback
__typenameis usually optional; - for
Query,Mutation, andSubscriptionoperation results, fallback__typenameis optional unless it was selected explicitly; - for concrete object shapes, selecting
__typenamethrough an alias such askind: __typenamesuppresses the synthesized fallback__typename; the aliased field is rendered as a regular string-literal field; - for abstract fields that split into distinct concrete shapes, the plugin may synthesize required
discriminating
__typenamevalues when no explicit__typenameselection exists; - if
__typenameis selected only conditionally or only for part of the branches, the generated__typenameremains optional; - if multiple concrete branches collapse to the same rendered shape, the plugin merges them into a single object type
and renders
__typenameas a union of possible string literals.
Reserved name rule:
- aliasing a non-
__typenamefield to the response name__typenameis not supported and causes plugin generation to fail. - incompatible selections that resolve to the same response name cause plugin generation to fail with a conflict diagnostic.
Configuration
Supported plugin config:
type PluginConfig = {
prefix?: string
scope?: string
paths?: Record<string, string | string[]>
relativeToCwd?: boolean
schemaOutputDirectory?: string
scalars?: Record<string, TsType | { input?: TsType; output?: TsType }>
namingConvention?: NAMING_STYLE | NamingConventionConfig
directivePolicies?: Record<string, DirectivePolicy | DirectiveNodePolicies>
}
const NAMING_STYLE = {
KEEP: 'keep',
PASCAL_CASE: 'pascalCase',
CAMEL_CASE: 'camelCase',
SNAKE_CASE: 'snakeCase',
} as const
type NAMING_STYLE = typeof NAMING_STYLE[keyof typeof NAMING_STYLE]
type NamingConventionConfig = {
typeNames?: NAMING_STYLE
enumValues?: NAMING_STYLE
operationNames?: NAMING_STYLE
fragmentNames?: NAMING_STYLE
transformUnderscore?: boolean
}prefix
Prefix prepended to generated GraphQL module ids.
scope
Optional path prefix used to preserve only the scoped part of the document path in module ids.
relativeToCwd
When enabled, absolute document paths are normalized relative to process.cwd() before generating module ids.
schemaOutputDirectory
Optional directory for generated schema support files.
By default, schema.d.ts and enums.ts are written next to the generated declaration file. When configured,
relative paths are resolved from the generated declaration file directory, while absolute paths are used directly.
Example:
{
schemaOutputDirectory: 'schema',
}For a generated declaration target such as types/graphql-documents.d.ts, this writes support files to
types/schema/schema.d.ts and types/schema/enums.ts.
paths
Optional alias map for imports from generated declaration modules to generated schema support files. The format follows
tsconfig/jsconfig paths entries:
{
schemaOutputDirectory: '../packages/graphql/generated',
paths: {
'@example/graphql/generated/*': [ 'packages/graphql/generated/*' ],
},
}When a generated support file matches a configured target, document declarations import Exact and generated enums
through the alias, for example @example/graphql/generated/schema and @example/graphql/generated/enums. If no target
matches, the plugin keeps the existing relative import behavior.
[!WARNING] If consumers import generated schema support modules through an alias, configure a matching
pathsentry. Otherwise, generated declarations can fall back to relative imports for the same files, which may make TypeScript see different module specifiers for the same generated types.
scalars
Overrides scalar TypeScript types.
String-based type config is not supported. Scalar mappings must be declared with TsType helpers.
For object literals inside custom type expressions, use defineObject({...}) together with
defineObjectField(type, optional?).
Examples:
{
scalars: {
DateTime: defineString(),
},
}or:
{
scalars: {
DateTime: {
input: defineString(),
output: defineNamed('Date'),
},
},
}Nullable unions are declared structurally:
{
scalars: {
DateTime: {
output: unionOf(defineNamed('Date'), defineNull()),
},
},
}Object-shaped custom types are declared through keyed field maps:
{
scalars: {
JsonObject: defineObject({
id: defineObjectField(defineString()),
archived: defineObjectField(defineBoolean(), true),
}),
},
}namingConvention
Controls how generated TypeScript names are normalized.
By default, the plugin normalizes generated TypeScript identifiers that are not runtime GraphQL object keys.
Schema type names, enum member identifiers, operation declaration base names, and fragment export names use pascalCase.
Field names, input field names, field argument names, and operation variable names are preserved exactly as they appear
in GraphQL.
Default behavior:
{
namingConvention: {
typeNames: 'pascalCase',
enumValues: 'pascalCase',
operationNames: 'pascalCase',
fragmentNames: 'pascalCase',
transformUnderscore: true,
},
}You can pass a short style string:
{
namingConvention: 'pascalCase',
}or use the exported constants:
{
namingConvention: NAMING_STYLE.PASCAL_CASE,
}The short form applies to generated schema type names, enum values, operation names, and fragment names. Runtime GraphQL keys are not configurable and are always preserved.
Use object form when categories need different rules:
{
namingConvention: {
typeNames: 'pascalCase',
enumValues: NAMING_STYLE.KEEP,
operationNames: 'pascalCase',
fragmentNames: 'pascalCase',
},
}With the default transformUnderscore: true, GraphQL names such as user_profile, user_filter, and
IS_ACTIVE render as UserProfile, UserFilter, and IsActive for generated TypeScript identifiers.
Field names, input field names, field argument names, and operation variable names are intentionally not configurable
because they represent runtime GraphQL keys. If a schema field is named first_name, the response JSON contains
first_name, not firstName.
See Naming for the full mapping table and examples.
directivePolicies
Defines how custom directives affect the generated response shape.
At plugin config level, policies can be defined in two forms:
- flat, for all supported target kinds:
{
directivePolicies: {
required: { effect: 'nonnull' },
opaque: { effect: 'override-type', type: defineNamed('OpaqueId') },
},
}- or scoped per target kind:
field,fragmentSpread,inlineFragment:
{
directivePolicies: {
mask: {
field: { effect: 'conditional' },
inlineFragment: { effect: 'exclude' },
},
},
}Current pipeline behavior:
- structural effects are
ignore,exclude,conditional,nonnull; - generation effects are
ignore,override-type,warn; - flat policies apply wherever the directive is encountered;
- scoped policies apply only to the matching selection kind;
- if a scoped policy does not define the current selection kind, the directive has no effect for that selection.
Supported effects:
ignoreexcludeconditionalnonnulloverride-typewarn
Additional documentation
- Module path resolution - path resolution rules and examples
for generated
declare moduleids. - Schema JSDoc - generated JSDoc for schema descriptions, deprecations, specified scalars, and scalar reference remarks.
- Types - structural
TsTypemodel, available helpers, supported operations, and config examples. - Naming - naming convention defaults, per-category config, and runtime key caveats.
- Directives - built-in directive semantics, custom directive policies,
current policy staging, and
__typenamebehavior for conditional and excluded selections. - Diagnostics - warnings, errors, and automatic recovery behavior reported during generation.
