LakeQL
  • Overview
Server Setup
  • Create Server
  • Define Config
  • Yoga Configuration
  • createLakeQLApp
Authentication
  • Authorization Model
  • JWT Authentication
  • Permissions
  • Scope Authorization
  • Trino User Impersonation
  • Debugging Identity
Schema Builder
  • Builder Configuration
  • Scalar Types
  • Comparison Types
  • Pagination
  • Input Validation
Customization
  • Custom Queries & Mutations
  • Extending Core
  • CORS Configuration
  • Error Handling
  • API Reference
GitHub
LakeQL
  1. API
  2. API Reference

On this page

  1. API Reference
    1. Vbuilder
    2. FcreateLakeQLApp
    3. VEMPTY_PERMISSIONS_WARNING
    4. ICreateLakeQLAppOptions
    5. ILakeQLApp
    6. FdefineApiConfig
    7. IApiRuntimeConfig
    8. IDefinedApiConfig
    9. TDefineConfigOptions
    10. FcreateApiResolveAuth
    11. IApiAuthContext
    12. ICreateApiResolveAuthOptions
    13. IResolveAuthSourceInfo
    14. FtrinoUserImpersonation
    15. ITrinoUserImpersonationOptions
    16. FtokenResolver
    17. FhasReadPermission
    18. FhasWritePermission
    19. FentraIdIdentityResolver
    20. FhandleErrorResponse
    21. FthrowFirstError
    22. FcreatePermission
    23. IPermissionFields
    24. FcreateApiServer
    25. FstartApiServer
    26. FcreateYogaServer
    27. FserveYoga
    28. FcreateErrorLoggingPlugin
    29. IApiErrorContext
    30. TApiErrorHook
    31. FloadSchema
    32. CSchemaFilesNotFoundError
    33. ISchemaLoadOptions
    34. IContext
    35. TReadPermissionResolver
    36. TWritePermissionResolver
    37. TYogaConfigOverrides
    38. IPageInfoInterface
    39. IConnectionInterface
    40. IUserScalars
    41. TBuilderScalar

API Reference

Complete reference for the @lakeql/api public API.

The complete public API of @lakeql/api, generated from the package's TypeScript source.

The near plug-and-play entry point is createLakeQLApp. The lower-level server entry points are defineApiConfig, createApiServer, and startApiServer. Compose authentication with createApiResolveAuth and trinoUserImpersonation, and permissions with createPermission. The rest of the surface covers the schema builder, error handling, the Yoga integration, and the supporting types.

The package is published with subpath exports (for example, @lakeql/api/config, @lakeql/api/resolve-auth). Each export below lives under the subpath matching its source module.

Definition

new SchemaBuilder<{
  Context: Context
  Scalars: Partial<UserScalars["Scalars"]>
  AuthScopes: {
    authorized: boolean
    readPermission: PermissionFields
    writePermission: PermissionFields
  }
}>({
  plugins: [ScopeAuthPlugin, ValidationPlugin],
  scopeAuth: {
    authScopes: (context) => ({
      authorized: !!context.currentUser,
      readPermission: ({ dataSource, tableName, catalog, schema }) =>
        (context.hasReadPermission ?? hasReadPermission)({
          catalog,
          context,
          dataSource,
          schema,
          tableName,
        }),
      writePermission: ({ dataSource, tableName, catalog, schema }) =>
        (context.hasWritePermission ?? hasWritePermission)({
          catalog,
          context,
          dataSource,
          schema,
          tableName,
        }),
    }),
    defaultStrategy: "any",
    treatErrorsAsUnauthorized: true,
    unauthorizedError: (_parent, _context, _info, result) => {
      // throw an error if it's found
      // this handles also 403 errors ( aka Permission denied)
      throwFirstError(result.failure)
      // throw a fallback error if no error was found
      return new Error(`Not authorized`)
    },
  },

  validation: {
    validationError: (validationResult) =>
      handleErrorResponse(
        new Error(
          validationResult.issues.map((i) => i.message).join("; ") ||
            "Validation failed"
        )
      ),
  },
})

Builds a ready-to-start LakeQL API server from a loaded project config.

Encapsulates the full wiring the generated src/index.ts would otherwise hand-write: it loads the config (unless project is supplied), derives the per-source sources map and the global impersonation resolver, builds the ResolveAuth via createApiResolveAuth, composes the runtime via createLakeQLRuntime, and defines the server via defineApiConfig. Every remaining option is forwarded to defineApiConfig unchanged.

Permissions default to project.config.auth?.permissions ?? [] and can be overridden via CreateLakeQLAppOptions.permissions. When the effective rule set is empty, EMPTY_PERMISSIONS_WARNING is printed so the default behavior is a deliberate choice, not a silent gap.

Parameters

NameType
options?CreateLakeQLAppOptions

Project source and server-shaping options. All optional.

Default: {}

Returns

Promise<LakeQLApp>

The composed LakeQLApp with runtime, start, and close. *

The warning printed on startup when no permission rules are configured.

Exported so tests and the docs can assert the exact wording the wrapper emits. Empty auth.permissions is a valid state, but it applies the defaults, so surface it instead of leaving a silent gap.

Definition

"No LakeQL permission rules configured. Defaults apply: human reads are delegated to each data source's own access control (e.g. Trino rules via impersonation, Fabric OBO), service-principal reads are denied, and all writes are denied until a matching Mutation rule is added. Ensure impersonation is configured — otherwise human queries run with the data source's service credentials."

Options accepted by createLakeQLApp.

Every server-shaping option is inherited structurally from ApiRuntimeConfig (minus runtime, which the wrapper builds), so a new defineApiConfig option is forwarded automatically without touching this type. Two wrapper-only options are added: project selects an already-loaded config, and handleSignals controls graceful shutdown.

Properties

NameType
project?LoadedLakeQLProject

An already-loaded project (from loadConfig()). When omitted, the wrapper calls loadConfig() itself with no arguments, matching the generated entry file’s default.

permissions?ApiRuntimeConfig["permissions"]

Permission rules for technical users.

Default: project.config.auth?.permissions ?? []
handleSignals?boolean

Register SIGTERM/SIGINT handlers that close the runtime and exit.

When true (the default) the wrapper owns graceful shutdown, reproducing the generated entry file. Set to false to own the lifecycle yourself via the returned close()/runtime.

Default: true

The composed application returned by createLakeQLApp.

Exposes the underlying runtime for advanced control plus start/close lifecycle helpers.

Properties

NameType
runtimeRequiredLakeQLRuntime

The composed runtime that owns data sources and read/write strategies. Advanced callers can drive it directly.

startRequired() => Promise<void>

Starts the HTTP server. Reproduces the generated entry file’s startup error handling: configuration-state errors (e.g. no schema files yet) are printed without a stack trace and the process exits non-zero.

closeRequired() => Promise<void>

Closes the runtime, releasing all data-source connections. Note this does not stop the HTTP listener — the socket is released on process exit. Call it when handleSignals is false and you own shutdown.

Defines the API server configuration with convenience methods for creating a Yoga server or starting the full HTTP server.

Parameters

NameType
inputRequiredDefineConfigOptions

API runtime configuration options.

Returns

DefinedApiConfig

A resolved configuration with createYogaServer and startServer helpers.

Runtime configuration options for the LakeQL API server.

Properties

NameType
tokenResolver?TokenResolver

Custom JWT token resolver.

Default: built-in mock auth
identityResolver?IdentityResolver

Maps a JWT payload to a ResolvedIdentity.

Default: entraIdIdentityResolver
hasReadPermission?ReadPermissionResolver

Custom read permission resolver.

Default: built-in read permission check
hasWritePermission?WritePermissionResolver

Custom write permission resolver.

Default: built-in write permission check
yogaConfig?YogaConfigOverrides

Override GraphQL Yoga options.

GraphQL Yoga Docs↗
cors?CorsOptions

CORS options for the GraphQL route, applied by the Hono layer that wraps Yoga. When omitted, CORS is not enabled (same-origin only). Set origin to the front-ends allowed to call the API.

A wildcard origin ("*") cannot be combined with credentials: true — the browser rejects that pairing — so there is no permissive default.

Hono CORS↗
permissions?Permission[]

Permission rules for technical users.

Default: []
runtime?LakeQLRuntime

The LakeQL runtime that owns data sources and read/write strategies.

Built by the application (via createLakeQLRuntime) and passed in so resolvers can resolve read strategies through the GraphQL context. The API does not construct or own the runtime lifecycle.

baseDir?string

Base directory for resolving relative paths.

Default: process.cwd()
schemaPath?string

Path to query schema files (relative to baseDir).

graphqlPath?string

GraphQL endpoint path.

Default: "/graphql"
healthCheckEndpoint?string

Health check endpoint path.

Default: "/live"
port?number

Server port.

Default: 4000
onError?ApiErrorHook

Hook invoked for every GraphQL execution error after it is logged. Use it to forward errors to external telemetry (OpenTelemetry, Sentry, metrics) without this package depending on any of them. Thrown errors from the hook are swallowed so telemetry never breaks a response.

The resolved API configuration returned by defineApiConfig. Carries every ApiRuntimeConfig field through unchanged and adds the server helpers.

Properties

NameType
createYogaServerRequired( logger: ReturnType<typeof createLogger> ) => ReturnType<typeof createYogaServer>
startServerRequired() => ReturnType<typeof startApiServer>

Configuration options for defineApiConfig.

Definition

ApiRuntimeConfig
See:ApiRuntimeConfig

Creates the ResolveAuth function for the API runtime.

The returned function resolves the effective impersonation resolver for a data source (per-source, then global), invokes it with the current user from the request context, and returns neutral { requestAuth, options } for the read strategy. When no resolver applies or there is no authenticated user, it returns an empty result (system user).

Parameters

NameType
optionsRequiredCreateApiResolveAuthOptions

Per-source metadata and the global impersonation resolver.

Returns

ResolveAuth

A ResolveAuth suitable for createLakeQLRuntime.

Per-request auth context expected in the opaque context passed to the read strategy. The API builds this as the GraphQL context.

Properties

NameType
currentUserRequiredJWTPayload | null

Decoded JWT payload, or null when unauthenticated.

identityRequiredResolvedIdentity | null

Resolved identity, or null when unauthenticated.

Configuration for createApiResolveAuth.

Properties

NameType
sourcesRequiredReadonly<Record<string, ResolveAuthSourceInfo>>

Per-data-source metadata keyed by configured source name. Typically derived from project.config.dataSources (adapter + optional per-source impersonationResolver).

globalImpersonationResolver?ImpersonationResolver

Global fallback impersonation resolver (from auth.impersonationResolver).

Per-data-source metadata needed to resolve impersonation: the adapter name and an optional per-source impersonation resolver.

Properties

NameType
adapterRequiredstring

Open adapter name owning this data source.

impersonationResolver?ImpersonationResolver

Optional per-data-source impersonation resolver.

Creates an ImpersonationResolver that impersonates the current user by their JWT nameField via Trino’s impersonateAs option (X-Trino-User).

Returns null when the field is missing or not a non-empty string, so the caller falls back to the system user.

Parameters

NameType
options?TrinoUserImpersonationOptions

Optional field selection.

Default: {}

Returns

ImpersonationResolver

An ImpersonationResolver producing { options: { impersonateAs } }.

Options for trinoUserImpersonation.

Properties

NameType
nameField?string

Name of the JWT payload field to impersonate as.

Default: "userName"
transform?TrinoUsernameTransform

Maps the claim value to the Trino username before it is sent as X-Trino-User. Use this when the IdP claim does not match the Trino username verbatim: "lower" / "upper" for case normalization, or a function for anything else.

Applied only to a present, non-empty string claim. When the result is an empty string, the resolver returns null (no impersonation).

Default: the claim value is used unchanged

Default token resolver — mock auth for development.

In production, callers should supply their own TokenResolver through ApiRuntimeConfig.tokenResolver.

Parameters

NameType
reqRequiredRequest

Returns

Promise<JWTPayload | null | undefined>

Checks whether the current user may read from a data source table.

Authorization model:

  • Unauthenticated users are denied.
  • Service principals without an explicit permission entry are denied.
  • Human users without a permission entry are allowed (Trino/adapter enforces).
  • If rules exist, at least one Query rule for the data source must match.

Parameters

NameType
{ context: Context } & PermissionFieldsRequired{ context: Context } & PermissionFields

Returns

boolean

true if read access is allowed, otherwise false.

Checks whether the current user may perform write operations on a data source table.

Authorization model:

  • Unauthenticated users are denied.
  • If no user-specific Mutation rules exist, write access is denied.
  • If rules exist, at least one rule for the data source must match.

Parameters

NameType
{ context: Context } & PermissionFieldsRequired{ context: Context } & PermissionFields

Returns

boolean

true if write access is allowed, otherwise false.

Default identity resolver for Microsoft Entra ID (Azure AD) tokens.

Extracts userName from the token using a fallback chain:

  1. onpremsamaccountname — synced on-prem AD account
  2. preferred_username — Entra ID UPN
  3. azp — authorized party (client ID for app-only tokens)
  4. "unknown" — fallback when none of the above are present

Determines service principal status when:

  • idtyp claim is "app" (explicit app-only token), or
  • no idtyp claim is present AND no onpremsamaccountname claim exists (heuristic: app-only tokens typically lack user-linked claims)

Parameters

NameType
tokenRequiredJWTPayload

Decoded JWT payload from the token resolver.

Returns

ResolvedIdentity

Translates a DataSourceError into a GraphQLError.

If the error is not a DataSourceError, it is re-thrown as a generic 500 GraphQLError.

Parameters

NameType
errorRequiredunknown

The error to handle.

Returns

never

Parameters

NameType
failureRequiredAuthFailure

Builds a permission entry for a single data source.

Parameters

NameType
dataSourceRequiredstring

Runtime name of the data source.

rulesFnRequired(rule: (r: PermissionRule) => PermissionRule) => PermissionRule[]

Builder callback receiving a rule helper that creates PermissionRule entries.

Returns

{ dataSource: string; rules: PermissionRule[] }

A permission entry with dataSource and rules.

Adapter-agnostic permission target fields.

dataSource and tableName are always required. catalog and schema are optional — some adapters expose flat namespaces without catalogs or schemas.

Properties

NameType
dataSourceRequiredstring
tableNameRequiredstring
catalog?string
schema?string

Parameters

NameType
options?ApiRuntimeConfig
Default: {}

Returns

Promise<ApiServer>

Parameters

NameType
options?ApiRuntimeConfig
Default: {}

Parameters

NameType
loggerRequiredReturnType<typeof createLogger>
options?ApiRuntimeConfig
Default: {}

Returns

Promise<ApiYoga>

Parameters

NameType
objectRequiredObject
PropertyType
yogaApiYoga

Returns

MiddlewareHandler

Create the error-logging plugin.

Parameters

NameType
loggerRequiredLogger

The configured logger.

onError?ApiErrorHook

Optional application hook for external telemetry.

Returns

Plugin

A Yoga plugin that logs execution errors.

Context passed to an ApiErrorHook for each logged GraphQL error.

Properties

NameType
errorRequiredGraphQLError

The GraphQL error as surfaced to the client.

dataSourceError?DataSourceError

The underlying DataSourceError, when the failure originated from one.

operationName?string

The GraphQL operation name, when available.

Application hook invoked for every logged GraphQL error. Use it to forward errors to external telemetry (OpenTelemetry, Sentry, metrics). Thrown errors from the hook are swallowed so telemetry never breaks a response.

Definition

(context: ApiErrorContext) => void | Promise<void>
See:ApiErrorContext

Parameters

NameType
options?SchemaLoadOptions
Default: {}

Returns

Promise<import("graphql").GraphQLSchema>

Thrown by loadSchema when no generated schema files are found under the resolved schema directory.

This is an expected configuration state (for example, a freshly scaffolded project before the first pull), not an internal failure. Consumers can catch it to print a concise message instead of a stack trace.

Constructor

NameType
schemaDirRequiredstring

The resolved absolute directory that was searched.

Properties

NameType
nameRequiredunknown
schemaDirRequiredstring

The resolved absolute directory that was searched.

Properties

NameType
baseDir?string
schemaPath?string

The GraphQL context object available in every resolver.

Properties

NameType
currentUserRequiredJWTPayload | null

Decoded JWT payload from token verification, or null for unauthenticated requests.

identityRequiredResolvedIdentity | null

Resolved identity information (user name, SP flag), or null when unauthenticated.

permissionsRequiredPermission[]

Configured permission rules for technical users.

hasReadPermission?ReadPermissionResolver

Custom resolver for read permission checks.

hasWritePermission?WritePermissionResolver

Custom resolver for write permission checks.

getReadStrategyRequired(name: string) => DataSourceReadStrategy

Resolves the read strategy for a configured data-source name.

Delegates to the runtime passed to defineApiConfig. Always present; when the API was configured without a runtime, calling it throws.

getWriteStrategy?(name: string) => DataSourceWriteStrategy

Resolves the write strategy for a configured data-source name.

Delegates to the runtime passed to defineApiConfig. Undefined when the API was configured without a runtime.

Definition

(
  args: {
    context: {
      currentUser: JWTPayload | null
      identity: ResolvedIdentity | null
      permissions: Permission[]
    }
  } & PermissionFields
) => boolean | Promise<boolean>
See:PermissionFields

Definition

(
  args: {
    context: {
      currentUser: JWTPayload | null
      identity: ResolvedIdentity | null
      permissions: Permission[]
    }
  } & PermissionFields
) => boolean | Promise<boolean>
See:PermissionFields

Subset of GraphQL Yoga’s createYoga options, excluding schema and context which are managed internally.

GraphQL Yoga Docs↗

Definition

Omit<
  NonNullable<Parameters<typeof createYoga>[0]>,
  "schema" | "context"
>

Properties

NameType
maxPagesRequirednumber
hasNextRequiredboolean
hasPreviousRequiredboolean
currentPageRequirednumber
nextPageRequirednumber | null
previousPageRequirednumber | null

Type Parameters

ParameterConstraintDefault
T——

Properties

NameType
totalCountRequirednumber
pageInfoRequiredPageInfoInterface
nodesRequiredT[]

Properties

NameType
ScalarsRequiredObject
PropertyType
IDObject
DateObject
DateTimeObject
FileObject

Definition

keyof MergedScalars<UserScalars>
See:UserScalars

Previous page

Overview

Next page

Server Setup