sdc

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

README

haistack-sdc (pkg/sdc)

FHIR R4 Structured Data Capture (SDC 3.0.0) behavior services for questionnaire-driven workflows.

pkg/sdc is deliberately renderer- and transport-neutral. It does not own HTTP handlers, UI widgets, database tables, or a second FHIR persistence model.

Boundaries

Canonical FHIR resources are represented by *types.ResourceEnvelope, just as they are in pkg/core, pkg/store, pkg/http, and pkg/runtime.

q, err := svc.Read(ctx, "Questionnaire", "intake")
if err != nil {
    // handle core.ResourceService error
}

outcome := sdc.ValidateQuestionnaireResource(ctx, q, sdc.ValidationOptions{})
if len(outcome.Issue) != 0 {
    // render or return the OperationOutcome-compatible diagnostics
}

The generated R4 protobuf types remain available through pkg/proto/r4. Use sdc.ParseR4 or the existing pkg/proto codec when typed protobuf access is needed; canonical JSON and ResourceEnvelope remain the interchange and storage boundary.

The compatibility projections encode polymorphic FHIR values with their correct value[x]/answer[x] keys and encode SDC behavior fields as FHIR extensions. Projection envelopes are therefore hash-stable across a decode/encode round trip.

The small questionnaire projection structs retained in the package are compatibility views for behavior evaluation. They are not replacements for pkg/proto/r4 resources and should not be persisted directly.

Core operations

Validation

ValidateQuestionnaireResource checks questionnaire structure, duplicate linkIds, item types, enablement declarations, generic item constraints (maxLength, regex, questionnaire-constraint), and required SDC fields. ValidateQuestionnaireResponseResource checks response identity, required and disabled items, repeats/cardinality, answer types, answer options, terminology, value constraints (maxLength, regex), questionnaire-constraint invariants, and calculated/enablement constraints.

Diagnostics are OperationOutcome-compatible and retain renderer field paths.

Generic FHIR item constraints (maxLength, minLength, regex, questionnaire-constraint, questionnaire-minValue, questionnaire-maxValue, questionnaire-minOccurs, questionnaire-maxOccurs) are preserved on the questionnaire model and enforced during response validation.

SDC and FHIR presentation extensions (questionnaire-itemControl, questionnaire-entryFormat, questionnaire-choiceOrientation, questionnaire-optionExclusive, questionnaire-usageMode, questionnaire-displayCategory, questionnaire-supportLink, reference and unit extensions, questionnaire-level launch context/variables, and QuestionnaireResponse workflow extensions) are modeled on the projection and exposed on FieldState for renderers.

answerValueSet validation uses the configured terminology service (including expansion for open-choice string answers). Reference answers honor referenceProfile and referenceFilter when a ReferenceResolver is supplied. Validation accepts launch context, subject, and evaluates questionnaire variables in FHIRPath expressions. usageMode is tied to response status (capture for in-progress, display for completed/amended) in validation and Render. Tier-5 extraction metadata drives QuestionnaireExtractor (sourceStructureMap, item definitions, observationExtract). HTTP $populate and $validate parse Parameters for subject and launch context; the default runtime wires ReferenceResolver and QuestionnaireExtractor. phone-number standards, email rules, or country-specific postal-code formats remain application-owned.

Response builder

NewResponse constructs a QuestionnaireResponse from rendered form values. The builder sets QuestionnaireResponse.questionnaire to Canonical(q), emits the correct FHIR value[x] field for each item type, resolves choice codes to declared answerOption codings, and preserves nested and repeated items. Unknown linkIds and invalid values are reported as structured issues through ValidationError.

builder, err := sdc.NewResponse(questionnaire)
if err != nil {
    // invalid questionnaire structure
}

response, err := builder.
    Set("name", "Ada").
    SetCoding("color", "red").
    InGroup("group", 1).
    Set("nested", true).
    SetAtAnswer(sdc.ItemPath{{LinkID: "trigger"}}, 0, "detail", "extra").
    AppendAnswer("tags", "alpha").
    Build(sdc.ValidationOptions{})
if err != nil {
    if outcome, ok := sdc.OutcomeFromError(err); ok {
        // render outcome.Issue
    }
}

Use SetAt / AppendAnswerAt when a linkId appears at multiple nesting levels, InGroup to target a repeating-group instance during auto-placement, and SetAtAnswer / AppendAnswerAtAnswer for item-controlled nesting under answer[n].item. Use SetCodingWithSystem when answer options share the same code in different code systems. Already-formed FHIR answer values (for example a Coding struct) are stored without modification; SDC validation still enforces answer options.

Population

PopulateResource returns a new QuestionnaireResponse envelope without saving it. Population accepts subject and launch context through PopulationContext, supports initial values/expressions, answer expressions, and injectable population providers.

FHIRPath is the built-in expression path. CQL is provided by pkg/cql and wired by the default runtime:

engine, _ := fhirpath.NewEngine(fhirpath.Config{})
response, outcome := sdc.PopulateResource(ctx, questionnaire,
    sdc.PopulationContext{
        Subject:  patientEnvelope,
        Provider: sdc.FHIRPathExpressions{Engine: engine},
    },
)

cqlEngine, _ := cql.NewEngine(cql.Config{FHIRPath: engine})
response, outcome = sdc.PopulateResource(ctx, questionnaire,
    sdc.PopulationContext{
        Subject: patientEnvelope,
        Provider: sdc.ComposeExpressions(
            sdc.FHIRPathExpressions{Engine: engine},
            nil,
            cql.NewProvider(cqlEngine, nil),
        ),
    },
)

The built-in FHIRPath provider adapts Questionnaire and QuestionnaireResponse projections and resource-shaped JSON maps. A subject should normally be a *types.ResourceEnvelope or supported R4 proto resource.

CQL expressions use text/cql, text/cql.identifier, application/cql, or application/x-cql. Named defines are resolved from cqf-library canonicals, contained Library resources, or a cql.LibraryResolver. Missing Patient context or a missing library is reported as an unavailable-expression diagnostic. FHIR Query remains an injectable adapter; if no provider is installed, the operation reports an unavailable-expression diagnostic.

SearchFHIRQueryProvider executes application/x-fhir-query expressions against pkg/search. ComposeExpressions combines FHIRPath, FHIR Query, and CQL providers for populate, validate, and render. RenderWithOptions evaluates contextExpression extensions and attaches results to FieldState.ContextResources. FHIR Query substitution supports %subject, %patient (alias), launch context, questionnaire variables, and %qitem (current item linkId). When no FHIR Query provider is configured, context expressions remain metadata-only and render a field-level diagnostic. The default runtime only wires FHIR Query when search is enabled.

Calculated expressions and rendering

EvaluateCalculated iterates calculated expressions with a convergence limit, dependency inspection, and explicit cycle diagnostics. Render produces a renderer-neutral FormModel containing field visibility, enabled/read-only state, answers, options, media, item-control metadata, issues, and navigation hints. Use RenderWithOptions when expression-based enablement or validation issues should be evaluated during rendering.

Modular assembly

Assembler resolves questionnaire references through a caller-supplied QuestionnaireResolver. It does not perform network access itself. A store-backed resolver, StoreQuestionnaireResolver, uses the existing store.ResourceStore and canonical JSON resources.

Envelope-first callers can use AssembleQuestionnaireResource to perform the same operation without manually decoding the projection.

Extraction

Definition, template, and StructureMap extractor contracts produce a canonical transaction Bundle envelope:

bundle, diagnostics, err := sdc.ExtractResource(ctx, questionnaire,
    questionnaireResponse, extractor)
if err != nil {
    // no resource was persisted or applied
}

// Applying it is an explicit caller decision:
result, err := coreService.ProcessTransactionBundle(ctx, bundle)

Definition extraction supports deterministic mappings, repeated answers, resource identities, POST-versus-PUT request generation, and extraction diagnostics. StructureMap execution is provided by pkg/structuremap and wired into the default runtime when sourceStructureMap is configured.

HTTP and runtime

pkg/http provides the transport adapter when Config.SDCService is set. The runtime wires http.CoreSDCService by default using the existing core resource service, store-backed questionnaire resolution, runtime FHIRPath engine, and pkg/cql CQL provider.

Supported operation routes include:

POST /fhir/Questionnaire/{id}/$populate
POST /fhir/Questionnaire/$populate?questionnaire={canonical}
POST /fhir/QuestionnaireResponse/$validate
POST /fhir/QuestionnaireResponse/{id}/$validate
POST /fhir/Questionnaire/{id}/$assemble
POST /fhir/QuestionnaireResponse/$extract
POST /fhir/Questionnaire/$next-question
POST /fhir/Questionnaire/$next
POST /fhir/Questionnaire/$answer

Populate, validate, and assemble work with the default adapter. Extraction requires application mappings/templates. Package-level adaptive callers can use the bundled SequentialAdaptiveEngine for deterministic questionnaire-order flow or inject a session policy for branching/scoring behavior. The HTTP adapter still requires an application session adapter. Unavailable capabilities return FHIR OperationOutcome errors.

Applications can replace or extend the adapter through the runtime builder:

rt, err := runtime.New().
    WithSQLite("health.db").
    WithSDC(mySDCService).
    WithHTTP(":8080").
    Build(ctx)

Module bundle

modules/sdc is an installable module containing SDC-specific profiles, extensions, operation/capability definitions, terminology artifacts, and examples. Base FHIR R4 definitions such as Questionnaire, QuestionnaireResponse, and Bundle come from the embedded registry bundle; the SDC module does not duplicate them.

Install it through the normal module manager or runtime WithModules path.

Scope and adapters

Included:

  • FHIR R4 / SDC 3.0.0 questionnaire behavior
  • FHIRPath expression integration via pkg/fhirpath
  • CQL expression integration via pkg/cql (CQL 1.5 libraries; CQF Measure evaluation is in pkg/cql / Measure/$evaluate-measure)
  • population, validation, assembly, rendering state, and extraction contracts
  • canonical transaction Bundle generation without persistence side effects
  • adaptive protocol interfaces

Injected by applications:

  • FHIR Query runtime (default runtime wires SearchFHIRQueryProvider when search is enabled)
  • terminology service and value-set expansion
  • StructureMap runtime (default runtime wires pkg/structuremap when sourceStructureMap is set)
  • extraction mappings/templates
  • adaptive questionnaire selection and session policy

CQL evaluation lives in pkg/cql and is wired by the default runtime when a CQLProvider can load libraries from the store, contained resources, or cqf-library canonicals. Applications may still replace the provider.

See doc.go for the package-level API boundary and the tests in this directory for executable behavior examples. Example CQL questionnaires and libraries live in modules/sdc/examples/cql-questionnaire.json and cql-library.json.

Documentation

Overview

Package sdc provides FHIR R4 Structured Data Capture (SDC 3.0.0) behavior services without coupling them to HTTP, a frontend, or a database schema.

Canonical resource boundary

FHIR resources enter and leave this package as *types.ResourceEnvelope values. JSON remains the stored source of truth, and callers can obtain the existing generated R4 representation with ParseR4 when typed protobuf access is needed. SDC does not define replacement FHIR resource or Bundle models.

The package's questionnaire projection structs are compatibility views used internally by the behavior engine. Their JSON methods preserve FHIR polymorphic value keys and encode SDC behavior fields as extensions. New integrations should use the ResourceEnvelope APIs: ValidateQuestionnaireResource, ValidateQuestionnaireResponseResource, PopulateResource, ExtractResource, AssembleQuestionnaireResource, SaveQuestionnaireResource, and SaveQuestionnaireResponseResource.

Behavior services

The package supports questionnaire normalization, linkId indexing, repeats, enableWhen rules, calculated expressions, generic item constraints, FHIR/SDC questionnaire extensions (tiers 1-6), population, response building, modular assembly, renderer-neutral form state, validation diagnostics, and transaction Bundle extraction. FHIRPath is supported through the existing pkg/fhirpath.Engine. CQL is provided by pkg/cql and wired through sdc.CQLProvider (default runtime installs it). FHIR Query, StructureMap, terminology, and adaptive behavior are explicit adapter contracts; unavailable adapters fail with diagnostics. StructureMap extraction is provided by pkg/structuremap and wired into the default runtime. FHIR Query context expressions are evaluated during Render when a SearchFHIRQueryProvider is configured.

Extraction returns a transaction Bundle as a *types.ResourceEnvelope. It does not persist or apply that Bundle. Callers may explicitly pass it to core.ResourceService.ProcessTransactionBundle or another transaction processor.

HTTP and runtime integration lives in pkg/http and pkg/runtime. The HTTP adapter exposes SDC operations when an SDCService is configured, while the runtime supplies a default core/FHIRPath adapter and permits application policy injection through runtime.Builder.WithSDC.

Index

Constants

View Source
const (
	FHIRBaseURL = "http://hl7.org/fhir/StructureDefinition/"

	MinLengthExtension                 = FHIRBaseURL + "minLength"
	QuestionnaireMinValueExtension     = FHIRBaseURL + "questionnaire-minValue"
	QuestionnaireMaxValueExtension     = FHIRBaseURL + "questionnaire-maxValue"
	QuestionnaireMinOccursExtension    = FHIRBaseURL + "questionnaire-minOccurs"
	QuestionnaireMaxOccursExtension    = FHIRBaseURL + "questionnaire-maxOccurs"
	QuestionnaireReferenceResourceExt  = FHIRBaseURL + "questionnaire-referenceResource"
	QuestionnaireReferenceProfileExt   = FHIRBaseURL + "questionnaire-referenceProfile"
	QuestionnaireReferenceFilterExt    = FHIRBaseURL + "questionnaire-referenceFilter"
	QuestionnaireUnitExtension         = FHIRBaseURL + "questionnaire-unit"
	QuestionnaireUnitOptionExtension   = FHIRBaseURL + "questionnaire-unitOption"
	QuestionnaireUnitValueSetExtension = FHIRBaseURL + "questionnaire-unitValueSet"
	QuestionnaireChoiceOrientationExt  = FHIRBaseURL + "questionnaire-choiceOrientation"
	QuestionnaireOptionExclusiveExt    = FHIRBaseURL + "questionnaire-optionExclusive"
	QuestionnaireSliderStepValueExt    = FHIRBaseURL + "questionnaire-sliderStepValue"
	QuestionnaireUsageModeExtension    = FHIRBaseURL + "questionnaire-usageMode"
	QuestionnaireDisplayCategoryExt    = FHIRBaseURL + "questionnaire-displayCategory"
	QuestionnaireSupportLinkExtension  = FHIRBaseURL + "questionnaire-supportLink"
	QuestionnaireFHIRTypeExtension     = FHIRBaseURL + "questionnaire-fhirType"
	QuestionnaireBaseTypeExtension     = FHIRBaseURL + "questionnaire-baseType"
	QuestionnaireOptionPrefixExtension = FHIRBaseURL + "questionnaire-optionPrefix"
	QuestionnaireRegexExtension        = FHIRBaseURL + "regex"
	QuestionnaireConstraintExtension   = FHIRBaseURL + "questionnaire-constraint"
	CQFLibraryExtension                = FHIRBaseURL + "cqf-library"

	SDCLaunchContextExtension      = SDCBaseURL + "sdc-questionnaire-launchContext"
	SDCVariableExtension           = SDCBaseURL + "sdc-questionnaire-variable"
	SDCRequiredExtension           = SDCBaseURL + "sdc-questionnaire-required"
	SDCSourceStructureMapExtension = SDCBaseURL + "sdc-questionnaire-sourceStructureMap"
	SDCObservationExtractExtension = SDCBaseURL + "sdc-questionnaire-observationExtract"
	SDCObservationLinkPeriodExt    = SDCBaseURL + "sdc-questionnaire-observationLinkPeriod"
	SDCAdditionalDefExtension      = SDCBaseURL + "sdc-questionnaire-additionalDef"
	SDCAssembledFromExtension      = SDCBaseURL + "sdc-questionnaire-assembledFrom"
	SDCCanonicalExtension          = SDCBaseURL + "sdc-questionnaire-canonical"
	SDCSignatureRequiredExtension  = SDCBaseURL + "sdc-questionnaire-signatureRequired"

	QuestionnaireResponseAuthorExtension    = FHIRBaseURL + "questionnaire-responseAuthor"
	QuestionnaireResponseReviewerExtension  = FHIRBaseURL + "questionnaire-responseReviewer"
	QuestionnaireResponseSignatureExtension = FHIRBaseURL + "questionnaire-responseSignature"
	QuestionnaireCompletionModeExtension    = FHIRBaseURL + "questionnaire-completionMode"
	QuestionnaireResponseReasonExtension    = FHIRBaseURL + "questionnaireresponse-reason"

	SDCIsSubjectExtension         = SDCBaseURL + "sdc-questionnaire-isSubject"
	SDCResponseIsSubjectExtension = SDCBaseURL + "sdc-questionnaireresponse-isSubject"
	SDCKeyboardExtension          = SDCBaseURL + "sdc-questionnaire-keyboard"
	SDCCandidateExpressionExt     = SDCBaseURL + "sdc-questionnaire-candidateExpression"
	SDCEntryModeExtension         = SDCBaseURL + "sdc-questionnaire-entryMode"
	SDCEndpointExtension          = SDCBaseURL + "sdc-questionnaire-endpoint"
	SDCMinQuantityExtension       = SDCBaseURL + "sdc-questionnaire-minQuantity"
	SDCMaxQuantityExtension       = SDCBaseURL + "sdc-questionnaire-maxQuantity"
	SDCUnitOpenExtension          = SDCBaseURL + "sdc-questionnaire-unitOpen"
	SDCSubQuestionnaireExtension  = SDCBaseURL + "sdc-questionnaire-subQuestionnaire"
	SDCAnswerOptionToggleExprExt  = SDCBaseURL + "sdc-questionnaire-answerOptionToggleExpression"
	SDCDefinitionExtractExtension = SDCBaseURL + "sdc-questionnaire-definitionExtract"
	SDCDefinitionExtractValueExt  = SDCBaseURL + "sdc-questionnaire-definitionExtractValue"

	TargetConstraintExtension           = FHIRBaseURL + "targetConstraint"
	QuestionnaireLookupQuestionnaireExt = FHIRBaseURL + "questionnaire-lookupQuestionnaire"
	ItemWeightExtension                 = FHIRBaseURL + "itemWeight"
)
View Source
const (
	SDCExtractAllocateIDExt      = SDCBaseURL + "sdc-questionnaire-extractAllocateId"
	SDCTemplateExtractExt        = SDCBaseURL + "sdc-questionnaire-templateExtract"
	SDCTemplateExtractValueExt   = SDCBaseURL + "sdc-questionnaire-templateExtractValue"
	SDCTemplateExtractContextExt = SDCBaseURL + "sdc-questionnaire-templateExtractContext"
	SDCTemplateExtractBundleExt  = SDCBaseURL + "sdc-questionnaire-templateExtractBundle"
	SDCAssembleContextExt        = SDCBaseURL + "sdc-questionnaire-assembleContext"
	SDCAssembleExpectationExt    = SDCBaseURL + "sdc-questionnaire-assemble-expectation"
	SDCContextExpressionExt      = SDCBaseURL + "sdc-questionnaire-contextExpression"
	SDCPerformerTypeExt          = SDCBaseURL + "sdc-questionnaire-performerType"
	SDCChoiceColumnExt           = SDCBaseURL + "sdc-questionnaire-choiceColumn"
	SDCItemOptionalDisplayExt    = SDCBaseURL + "sdc-questionnaire-itemOptionalDisplay"
	SDCCQFLibraryExt             = SDCBaseURL + "sdc-questionnaire-cqf-library"
)
View Source
const (
	SDCEnableWhenExpressionExtension  = SDCBaseURL + "sdc-questionnaire-enableWhenExpression"
	SDCInitialExpressionExtension     = SDCBaseURL + "sdc-questionnaire-initialExpression"
	SDCAnswerExpressionExtension      = SDCBaseURL + "sdc-questionnaire-answerExpression"
	SDCCalculatedExpressionExtension  = SDCBaseURL + "sdc-questionnaire-calculatedExpression"
	SDCItemPopulationContextExtension = SDCBaseURL + "sdc-questionnaire-itemPopulationContext"
	SDCItemMediaExtension             = SDCBaseURL + "sdc-questionnaire-itemMedia"
	SDCTextReferenceExtension         = SDCBaseURL + "sdc-questionnaire-textReference"
	QuestionnaireHiddenExtension      = "http://hl7.org/fhir/StructureDefinition/questionnaire-hidden"
	QuestionnaireItemControlExtension = "http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl"
	QuestionnaireEntryFormatExtension = "http://hl7.org/fhir/StructureDefinition/questionnaire-entryFormat"
)

SDC expression extensions are FHIR extensions, not additional JSON fields on Questionnaire.item. These URLs are also used by Render to interpret common UI extensions without coupling the package to a widget framework.

View Source
const (
	CQLLanguage           = "text/cql"
	CQLIdentifierLanguage = "text/cql.identifier"
	CQLApplicationLang    = "application/cql"
	CQLApplicationXLang   = "application/x-cql"
)
View Source
const FHIRQueryLanguage = "application/x-fhir-query"
View Source
const SDCBaseURL = "http://hl7.org/fhir/uv/sdc/StructureDefinition/"
View Source
const SDCPackageVersion = "3.0.0"

Variables

This section is empty.

Functions

func Canonical

func Canonical(q Questionnaire) string

func CanonicalOutcomeJSON

func CanonicalOutcomeJSON(o Outcome) ([]byte, error)

CanonicalOutcomeJSON returns stable JSON for an SDC Outcome.

func DependencyCycles

func DependencyCycles(q Questionnaire) [][]string

func Enabled

func Enabled(item Item, r QuestionnaireResponse) bool

func Envelope

func Envelope(resourceType, id string, v any) (*types.ResourceEnvelope, error)

func Equal

func Equal(a, b any) bool

func ErrFromOutcome

func ErrFromOutcome(o Outcome) error

ErrFromOutcome returns ValidationError when outcome contains error issues.

func ExpressionDependencies

func ExpressionDependencies(q Questionnaire) map[string][]string

ExpressionDependencies returns the questionnaire linkIds referenced by calculated expressions. It is intentionally conservative: unknown tokens are ignored, while known linkIds are edges in the dependency graph.

func HasErrors

func HasErrors(o Outcome) bool

HasErrors reports whether outcome contains error or fatal issues.

func IsCQLLanguage

func IsCQLLanguage(lang string) bool

IsCQLLanguage reports whether lang is a CQL expression language used by SDC.

func MarshalOutcome

func MarshalOutcome(o Outcome) ([]byte, error)

MarshalOutcome returns canonical JSON for an SDC Outcome (issues sorted for stability).

func NewSDCFHIRPathEngine

func NewSDCFHIRPathEngine(cfg fhirpath.Config) (fhirpath.Engine, error)

NewSDCFHIRPathEngine returns a FHIRPath engine with SDC custom functions such as weight().

func OutcomeSummary

func OutcomeSummary(o Outcome) string

OutcomeSummary joins all error and fatal diagnostics into a single human-readable summary.

func ParseR4

func ParseR4(env *types.ResourceEnvelope) (any, error)

ParseR4 returns the generated Google R4 representation through the existing proto adapter. Callers should generally retain the envelope as the canonical value and use this only when typed protobuf access is required.

func ProjectionEnvelope

func ProjectionEnvelope(q Questionnaire) (*types.ResourceEnvelope, error)

ProjectionEnvelope is a compatibility helper for JSON behavior projections. New code should construct envelopes through types.JSONCodec or proto.ToEnvelope.

func QuestionnaireResource

func QuestionnaireResource(env *types.ResourceEnvelope) (*types.ResourceEnvelope, error)

QuestionnaireResource validates and returns an existing canonical Questionnaire envelope.

func QuestionnaireResponseResource

func QuestionnaireResponseResource(env *types.ResourceEnvelope) (*types.ResourceEnvelope, error)

QuestionnaireResponseResource validates and returns an existing canonical QuestionnaireResponse envelope.

func ResponseProjectionEnvelope

func ResponseProjectionEnvelope(r QuestionnaireResponse) (*types.ResourceEnvelope, error)

func SaveQuestionnaireResource

func SaveQuestionnaireResource(ctx context.Context, s ResourceService, env *types.ResourceEnvelope) (*types.ResourceEnvelope, error)

SaveQuestionnaireResource persists an already-canonical Questionnaire using the existing core resource service lifecycle.

func SaveQuestionnaireResponseResourceWithOptions

func SaveQuestionnaireResponseResourceWithOptions(ctx context.Context, s ResourceService, env *types.ResourceEnvelope, opts SaveResponseOptions) (*types.ResourceEnvelope, error)

SaveQuestionnaireResponseResourceWithOptions persists a QuestionnaireResponse envelope. When a questionnaire envelope or resolver is provided, SDC validation runs before save.

func ToOperationOutcome

func ToOperationOutcome(o Outcome) types.OperationOutcome

ToOperationOutcome maps an SDC Outcome into a FHIR OperationOutcome. Field paths are preserved in Expression for renderer and API consumers.

Types

type AdaptiveEngine

type AdaptiveEngine interface {
	Search(context.Context, AdaptiveSearchRequest) ([]Questionnaire, error)
	NextQuestion(context.Context, *AdaptiveSession) (*Item, error)
	SubmitAnswer(context.Context, *AdaptiveSession, ResponseItem) (*Item, error)
}

type AdaptiveSearchRequest

type AdaptiveSearchRequest struct {
	Query   string
	Subject any
}

type AdaptiveService

type AdaptiveService struct{ Engine AdaptiveEngine }

func (AdaptiveService) Next

func (AdaptiveService) Search

func (AdaptiveService) Submit

type AdaptiveSession

type AdaptiveSession struct {
	ID            string
	Questionnaire string
	Response      QuestionnaireResponse
	State         map[string]any
}

type Answer

type Answer struct {
	Value any `json:"-"`
	// ValueType optionally names the FHIR primitive suffix (for example Date
	// or Uri) when Go's underlying value is otherwise ambiguous.
	ValueType string         `json:"-"`
	Item      []ResponseItem `json:"item,omitempty"`
	// contains filtered or unexported fields
}

func (Answer) MarshalJSON

func (a Answer) MarshalJSON() ([]byte, error)

MarshalJSON preserves FHIR's polymorphic value[x] fields.

func (*Answer) UnmarshalJSON

func (a *Answer) UnmarshalJSON(b []byte) error

type AnswerOption

type AnswerOption struct {
	InitialSelected  bool           `json:"initialSelected,omitempty"`
	Value            any            `json:"-"`
	ValueType        string         `json:"-"`
	OptionPrefix     string         `json:"-"`
	OptionWeight     *float64       `json:"-"`
	ToggleExpression *Expression    `json:"-"`
	Disabled         bool           `json:"-"`
	OptionalDisplay  bool           `json:"-"`
	ChoiceColumns    []ChoiceColumn `json:"-"`
	Extension        []Extension    `json:"extension,omitempty"`
	// contains filtered or unexported fields
}

func CodingOption

func CodingOption(code, display string, system ...string) (AnswerOption, error)

CodingOption constructs an answer option with a FHIR Coding value.

func StringOption

func StringOption(s string) (AnswerOption, error)

StringOption constructs an answer option with a FHIR string value.

func (AnswerOption) MarshalJSON

func (a AnswerOption) MarshalJSON() ([]byte, error)

func (*AnswerOption) UnmarshalJSON

func (a *AnswerOption) UnmarshalJSON(b []byte) error

type AnswerOptionValueError

type AnswerOptionValueError struct {
	LinkID    string
	ItemType  string
	ValueType string
	Reason    string
}

AnswerOptionValueError is returned when an answer option's Go value does not match the FHIR value[x] type expected for its parent question item.

func (AnswerOptionValueError) Error

func (e AnswerOptionValueError) Error() string

type Assembler

type Assembler struct {
	Resolver QuestionnaireResolver
	Context  map[string]any
	Elements DefinitionElementResolver
}

func AssemblerFromParameters

func AssemblerFromParameters(params OperationParameters, resolver QuestionnaireResolver, elements DefinitionElementResolver) Assembler

AssemblerFromParameters builds an assembler using named parameters as assemble context.

func (Assembler) Assemble

func (Assembler) AssembleResource

func (a Assembler) AssembleResource(ctx context.Context, env *types.ResourceEnvelope) (*types.ResourceEnvelope, Outcome)

AssembleResource performs modular assembly for a canonical Questionnaire envelope using this assembler's resolver.

type Attachment

type Attachment struct {
	ContentType string `json:"contentType,omitempty"`
	URL         string `json:"url,omitempty"`
	Title       string `json:"title,omitempty"`
}

type BoundValue

type BoundValue struct {
	Value     any    `json:"-"`
	ValueType string `json:"-"`
}

type CQFLibraryRef

type CQFLibraryRef struct {
	LibraryCanonical string
	Name             string
}

CQFLibraryRef associates a CQL library with the questionnaire.

type CQLEvalInput

type CQLEvalInput struct {
	Language string
	Name     string
	Input    any
}

CQLEvalInput wraps an SDC expression evaluation so a CQLProvider receives language and nested input (typically ExpressionEnvironment or a Patient).

type CQLExpressions

type CQLExpressions struct{ Provider CQLProvider }

func (CQLExpressions) Evaluate

func (p CQLExpressions) Evaluate(ctx context.Context, e Expression, r any) ([]any, error)

type CQLProvider

type CQLProvider interface {
	EvaluateCQL(context.Context, string, any) ([]any, error)
}

type CalculatedOptions

type CalculatedOptions struct{ MaxIterations int }

type CalculationResult

type CalculationResult struct {
	Response    QuestionnaireResponse
	Diagnostics []Diagnostic
	Converged   bool
}

type CanonicalResolver

type CanonicalResolver struct {
	Resources ResourceService
	Finder    QuestionnaireFinder
}

func (CanonicalResolver) Resolve

func (c CanonicalResolver) Resolve(ctx context.Context, canonical string) (Questionnaire, error)

type ChoiceColumn

type ChoiceColumn struct {
	Path       string
	Label      string
	ForDisplay bool
}

ChoiceColumn guides multi-column rendering for choice/reference items.

type CodeableConcept

type CodeableConcept struct {
	Coding []Coding `json:"coding,omitempty"`
	Text   string   `json:"text,omitempty"`
}

CodeableConcept is a lightweight FHIR CodeableConcept projection.

type Coding

type Coding struct {
	System  string `json:"system,omitempty"`
	Code    string `json:"code,omitempty"`
	Display string `json:"display,omitempty"`
}

type ContextExpression

type ContextExpression struct {
	Expression Expression
	Label      string
}

ContextExpression provides contextual resources to help answer a question.

type ContextResourceResult

type ContextResourceResult struct {
	Label     string
	Resources []any
}

ContextResourceResult holds evaluated resources for one contextExpression. An entry with only Label set means the query succeeded but returned no matches.

type DefinitionElementResolver

type DefinitionElementResolver interface {
	ResolveElement(ctx context.Context, definition string) (ResolvedElement, error)
}

DefinitionElementResolver resolves item.definition element metadata during assembly.

type DefinitionExtractContext

type DefinitionExtractContext struct {
	Definition string
	FullURL    string
}

DefinitionExtractContext declares a resource to create during definition-based extraction.

type DefinitionExtractValue

type DefinitionExtractValue struct {
	Definition string
	Expression *Expression
	Value      any
	ValueType  string
}

DefinitionExtractValue maps a fixed value or expression into an extracted resource element.

type DefinitionExtractor

type DefinitionExtractor struct {
	Mappings []DefinitionMap
	Existing func(context.Context, string, string) (bool, error)
}

func (DefinitionExtractor) Extract

type DefinitionMap

type DefinitionMap struct {
	LinkID       string
	ResourceType string
	Path         string
	ValuePath    string
	Identity     string
}

type Diagnostic

type Diagnostic struct {
	LinkID     string
	Expression string
	Message    string
	Severity   string
}

type EnableWhen

type EnableWhen struct {
	Question string `json:"question"`
	Operator string `json:"operator"`
	Answer   any    `json:"-"`
	// AnswerType optionally names the FHIR answer[x] suffix.
	AnswerType string `json:"-"`
	// contains filtered or unexported fields
}

func (EnableWhen) MarshalJSON

func (e EnableWhen) MarshalJSON() ([]byte, error)

func (*EnableWhen) UnmarshalJSON

func (e *EnableWhen) UnmarshalJSON(b []byte) error

type Expression

type Expression struct {
	Language   string `json:"language"`
	Expression string `json:"expression,omitempty"`
	Name       string `json:"name,omitempty"`
}

type ExpressionEnvironment

type ExpressionEnvironment struct {
	Resource      any
	Questionnaire any
	Context       any
	QItem         any
	Constants     map[string]any
}

ExpressionEnvironment carries SDC FHIRPath % constants.

type ExpressionProvider

type ExpressionProvider interface {
	Evaluate(context.Context, Expression, any) ([]any, error)
}

func ComposeExpressions

func ComposeExpressions(fhirpath ExpressionProvider, fhirQuery FHIRQueryProvider, cql CQLProvider) ExpressionProvider

ComposeExpressions builds a multi-language expression provider.

type Extension

type Extension struct {
	URL   string `json:"url"`
	Value any    `json:"-"`
	// ValueType optionally names the FHIR value[x] suffix for generic values.
	ValueType string      `json:"-"`
	Extension []Extension `json:"extension,omitempty"`
	// contains filtered or unexported fields
}

func (Extension) MarshalJSON

func (e Extension) MarshalJSON() ([]byte, error)

func (*Extension) UnmarshalJSON

func (e *Extension) UnmarshalJSON(b []byte) error

type ExtractionDiagnostic

type ExtractionDiagnostic struct {
	Severity string
	Message  string
	LinkID   string
}

func ExtractResource

ExtractResource converts an extraction result into the canonical Bundle envelope used by core transaction processing. It has no persistence side effects.

type ExtractionResult

type ExtractionResult struct {
	// Bundle is the canonical FHIR transaction Bundle envelope.
	Bundle      *types.ResourceEnvelope
	Diagnostics []ExtractionDiagnostic
}

type Extractor

type Extractor interface {
	Extract(context.Context, Questionnaire, QuestionnaireResponse) (ExtractionResult, error)
}

type FHIRPathExpressions

type FHIRPathExpressions struct{ Engine fhirpath.Engine }

func (FHIRPathExpressions) Evaluate

func (p FHIRPathExpressions) Evaluate(ctx context.Context, e Expression, r any) ([]any, error)

type FHIRPathProvider

type FHIRPathProvider interface {
	Evaluate(context.Context, string, any) ([]any, error)
}

type FHIRQueryExpressions

type FHIRQueryExpressions struct{ Provider FHIRQueryProvider }

func (FHIRQueryExpressions) Evaluate

func (p FHIRQueryExpressions) Evaluate(ctx context.Context, e Expression, r any) ([]any, error)

type FHIRQueryProvider

type FHIRQueryProvider interface {
	ExecuteFHIRQuery(context.Context, string, any) ([]any, error)
}

type FHIRQuerySearch

type FHIRQuerySearch interface {
	Search(ctx context.Context, resourceType string, params url.Values) ([]*types.ResourceEnvelope, error)
}

FHIRQuerySearch executes FHIR search for the SDC FHIR Query adapter.

type FieldState

type FieldState struct {
	LinkID              string
	Text                string
	Type                string
	Visible             bool
	Enabled             bool
	Required            bool
	ReadOnly            bool
	Repeats             bool
	MaxLength           *int
	MinLength           *int
	MinValue            *BoundValue
	MaxValue            *BoundValue
	MinOccurs           *int
	MaxOccurs           *int
	Regex               string
	Constraints         []ItemConstraint
	ReferenceResources  []string
	ReferenceProfiles   []string
	ReferenceFilter     string
	Unit                *Coding
	UnitOptions         []Coding
	UnitValueSet        string
	ChoiceOrientation   string
	OptionExclusive     bool
	SliderStepValue     *float64
	UsageMode           string
	IsSubject           bool
	InputKeyboard       string
	LookupQuestionnaire string
	DisplayCategory     string
	SupportLinks        []SupportLink
	FHIRType            string
	BaseType            string
	RequiredExpression  *Expression
	Answers             []Answer
	Options             []AnswerOption
	Candidates          []any
	ContextResources    []ContextResourceResult
	Issues              []Issue
	Media               []Attachment
	ItemControl         string
	EntryFormat         string
	NavigationHint      string
	ContextExpressions  []ContextExpression
	ChoiceColumns       []ChoiceColumn
	OptionalDisplay     bool
	PerformerTypes      []string
}

type FormMode

type FormMode string

FormMode distinguishes capture-time from display-time questionnaire rendering.

const (
	FormModeCapture FormMode = "capture"
	FormModeDisplay FormMode = "display"
)

type FormModel

type FormModel struct {
	Questionnaire Questionnaire
	Response      QuestionnaireResponse
	EntryMode     string
	Fields        []FieldState
	Issues        []Issue
}

func RenderWithOptions

func RenderWithOptions(q Questionnaire, r QuestionnaireResponse, opts ValidationOptions) FormModel

RenderWithOptions evaluates expression-based enablement and attaches response-validation issues to the corresponding fields.

type Issue

type Issue struct {
	Severity    string   `json:"severity"`
	Code        string   `json:"code"`
	Diagnostics string   `json:"diagnostics,omitempty"`
	Expression  []string `json:"expression,omitempty"`
	FieldPath   string   `json:"fieldPath,omitempty"`
}

type Item

type Item struct {
	LinkID                  string                    `json:"linkId"`
	Definition              string                    `json:"definition,omitempty"`
	Code                    []Coding                  `json:"code,omitempty"`
	Prefix                  string                    `json:"prefix,omitempty"`
	Text                    string                    `json:"text,omitempty"`
	Type                    string                    `json:"type"`
	EnableWhen              []EnableWhen              `json:"enableWhen,omitempty"`
	EnableBehavior          string                    `json:"enableBehavior,omitempty"`
	EnableWhenExpression    *Expression               `json:"enableWhenExpression,omitempty"`
	Required                bool                      `json:"required,omitempty"`
	Repeats                 bool                      `json:"repeats,omitempty"`
	ReadOnly                bool                      `json:"readOnly,omitempty"`
	MaxLength               *int                      `json:"maxLength,omitempty"`
	Regex                   string                    `json:"-"`
	Constraints             []ItemConstraint          `json:"-"`
	MinLength               *int                      `json:"-"`
	MinValue                *BoundValue               `json:"-"`
	MaxValue                *BoundValue               `json:"-"`
	MinOccurs               *int                      `json:"-"`
	MaxOccurs               *int                      `json:"-"`
	ReferenceResources      []string                  `json:"-"`
	ReferenceProfiles       []string                  `json:"-"`
	ReferenceFilter         string                    `json:"-"`
	Unit                    *Coding                   `json:"-"`
	UnitOptions             []Coding                  `json:"-"`
	UnitValueSet            string                    `json:"-"`
	ChoiceOrientation       string                    `json:"-"`
	OptionExclusive         bool                      `json:"-"`
	SliderStepValue         *float64                  `json:"-"`
	UsageMode               string                    `json:"-"`
	IsSubject               bool                      `json:"-"`
	InputKeyboard           string                    `json:"-"`
	DisplayCategory         string                    `json:"-"`
	CandidateExpression     *Expression               `json:"-"`
	Variables               []QuestionnaireVariable   `json:"-"`
	DefinitionExtract       *DefinitionExtractContext `json:"-"`
	DefinitionExtractValues []DefinitionExtractValue  `json:"-"`
	ExtractAllocateID       string                    `json:"-"`
	TemplateExtract         *TemplateExtractContext   `json:"-"`
	TemplateExtractValues   []TemplateExtractValue    `json:"-"`
	AssembleContexts        []string                  `json:"-"`
	SubQuestionnaire        string                    `json:"-"`
	ContextExpressions      []ContextExpression       `json:"-"`
	ChoiceColumns           []ChoiceColumn            `json:"-"`
	OptionalDisplay         bool                      `json:"-"`
	LookupQuestionnaire     string                    `json:"-"`
	MinQuantity             *BoundValue               `json:"-"`
	MaxQuantity             *BoundValue               `json:"-"`
	UnitOpen                string                    `json:"-"`
	TargetConstraints       []ItemConstraint          `json:"-"`
	SupportLinks            []SupportLink             `json:"-"`
	FHIRType                string                    `json:"-"`
	BaseType                string                    `json:"-"`
	RequiredExpression      *Expression               `json:"requiredExpression,omitempty"`
	AnswerOption            []AnswerOption            `json:"answerOption,omitempty"`
	AnswerValueSet          string                    `json:"answerValueSet,omitempty"`
	Initial                 []Answer                  `json:"initial,omitempty"`
	Item                    []Item                    `json:"item,omitempty"`
	Extension               []Extension               `json:"extension,omitempty"`
	AnswerExpression        *Expression               `json:"answerExpression,omitempty"`
	InitialExpression       *Expression               `json:"initialExpression,omitempty"`
	CalculatedExpression    *Expression               `json:"calculatedExpression,omitempty"`
	ItemPopulationContext   *Expression               `json:"itemPopulationContext,omitempty"`
	TextRef                 string                    `json:"textReference,omitempty"`
	Media                   []Attachment              `json:"media,omitempty"`
}

func (Item) MarshalJSON

func (it Item) MarshalJSON() ([]byte, error)

func (*Item) UnmarshalJSON

func (it *Item) UnmarshalJSON(b []byte) error

type ItemConstraint

type ItemConstraint struct {
	Key          string `json:"key,omitempty"`
	Requirements string `json:"requirements,omitempty"`
	Severity     string `json:"severity,omitempty"`
	Expression   string `json:"expression,omitempty"`
}

ItemConstraint is a FHIR questionnaire-constraint extension on Questionnaire.item.

type ItemPath

type ItemPath []PathSegment

ItemPath identifies a location in the response tree. Each segment names a parent item by linkId and, for repeating parents, the zero-based instance index at that level.

type LaunchContextDef

type LaunchContextDef struct {
	Name string   `json:"name,omitempty"`
	Type []string `json:"type,omitempty"`
}

LaunchContextDef declares a named launch context on a Questionnaire.

type MultiExpressionProvider

type MultiExpressionProvider struct {
	FHIRPath  ExpressionProvider
	FHIRQuery ExpressionProvider
	CQL       ExpressionProvider
}

MultiExpressionProvider routes expressions to language-specific providers.

func (MultiExpressionProvider) Evaluate

func (p MultiExpressionProvider) Evaluate(ctx context.Context, e Expression, input any) ([]any, error)

type OperationParameters

type OperationParameters struct {
	Subject       any
	LaunchContext map[string]any
}

OperationParameters carries subject and launch context for SDC operations.

func ParseOperationParameters

func ParseOperationParameters(env *types.ResourceEnvelope) OperationParameters

ParseOperationParameters extracts SDC populate/validate parameters from a FHIR Parameters resource.

type Outcome

type Outcome struct {
	ResourceType string  `json:"resourceType"`
	Issue        []Issue `json:"issue,omitempty"`
}

func AssembleQuestionnaireResource

func AssembleQuestionnaireResource(ctx context.Context, env *types.ResourceEnvelope, assembler Assembler) (*types.ResourceEnvelope, Outcome)

AssembleQuestionnaireResource resolves modular Questionnaire references and returns the assembled resource as a canonical envelope.

func AssembleResource

func AssembleResource(ctx context.Context, env *types.ResourceEnvelope, assembler Assembler) (*types.ResourceEnvelope, Outcome)

AssembleResource is the concise envelope-first alias for AssembleQuestionnaireResource.

func OutcomeFromError

func OutcomeFromError(err error) (Outcome, bool)

OutcomeFromError returns the SDC Outcome when err is or wraps ValidationError.

func PopulateResource

PopulateResource executes SDC population and returns a canonical response envelope without persisting it.

func ValidateQuestionnaire

func ValidateQuestionnaire(q Questionnaire, opts ValidationOptions) Outcome

func ValidateQuestionnaireResource

func ValidateQuestionnaireResource(_ context.Context, env *types.ResourceEnvelope, opts ValidationOptions) Outcome

func ValidateQuestionnaireResponseResource

func ValidateQuestionnaireResponseResource(_ context.Context, qenv, renv *types.ResourceEnvelope, opts ValidationOptions) Outcome

func (Outcome) Error

func (o Outcome) Error() string

type PathSegment

type PathSegment struct {
	LinkID string
	Index  int
}

PathSegment is one level in an ItemPath.

type Period

type Period struct {
	Start string `json:"start,omitempty"`
	End   string `json:"end,omitempty"`
}

Period is a FHIR Period projection.

type PopulationContext

type PopulationContext struct {
	Subject            any
	LaunchContext      map[string]any
	InitialResponse    *QuestionnaireResponse
	Provider           ExpressionProvider
	PopulationProvider PopulationProvider
}

func PopulationContextFromParameters

func PopulationContextFromParameters(params OperationParameters, base PopulationContext) PopulationContext

type PopulationProvider

type PopulationProvider interface {
	Populate(context.Context, Questionnaire, PopulationContext) (*QuestionnaireResponse, error)
}

type Questionnaire

type Questionnaire struct {
	ResourceType          string                  `json:"resourceType"`
	ID                    string                  `json:"id,omitempty"`
	URL                   string                  `json:"url,omitempty"`
	Version               string                  `json:"version,omitempty"`
	Status                string                  `json:"status,omitempty"`
	SubjectType           []string                `json:"subjectType,omitempty"`
	Item                  []Item                  `json:"item,omitempty"`
	Extension             []Extension             `json:"extension,omitempty"`
	Contained             []map[string]any        `json:"contained,omitempty"`
	Meta                  map[string]any          `json:"meta,omitempty"`
	LaunchContexts        []LaunchContextDef      `json:"-"`
	Variables             []QuestionnaireVariable `json:"-"`
	CanonicalOverride     string                  `json:"-"`
	AssembledFrom         []string                `json:"-"`
	SourceStructureMap    string                  `json:"-"`
	AdditionalDefinitions []string                `json:"-"`
	ObservationExtract    bool                    `json:"-"`
	ObservationLinkPeriod *Period                 `json:"-"`
	SignatureRequired     bool                    `json:"-"`
	EntryMode             string                  `json:"-"`
	Endpoint              string                  `json:"-"`
	TemplateExtractBundle *TemplateExtractContext `json:"-"`
	TargetConstraints     []ItemConstraint        `json:"-"`
	AssembleExpectation   string                  `json:"-"`
	PerformerTypes        []string                `json:"-"`
	CQFLibraries          []CQFLibraryRef         `json:"-"`
}

Questionnaire is a JSON behavior projection only. It is not a persisted FHIR model; use DecodeQuestionnaireResource and ResourceEnvelope-based APIs at package boundaries. It remains exported temporarily for compatibility with the first SDC API revision.

func DecodeQuestionnaire

func DecodeQuestionnaire(raw []byte) (Questionnaire, error)

func DecodeQuestionnaireResource

func DecodeQuestionnaireResource(env *types.ResourceEnvelope) (Questionnaire, error)

DecodeQuestionnaireResource validates and decodes an envelope's canonical JSON into the package's internal behavior projection.

func NewDraft

func NewDraft(url string, items []Item) Questionnaire

func Publish

func Publish(q Questionnaire) Questionnaire

func Version

func Version(q Questionnaire, v string) Questionnaire

func (Questionnaire) MarshalJSON

func (q Questionnaire) MarshalJSON() ([]byte, error)

func (*Questionnaire) UnmarshalJSON

func (q *Questionnaire) UnmarshalJSON(b []byte) error

type QuestionnaireExtractor

type QuestionnaireExtractor struct {
	Definition   DefinitionExtractor
	StructureMap StructureMapExtractor
	Expressions  ExpressionProvider
}

QuestionnaireExtractor routes extraction using questionnaire tier-5 metadata. SourceStructureMap selects the StructureMap runtime; item definitions and ObservationExtract drive definition-based extraction when no map is configured.

func (QuestionnaireExtractor) Extract

type QuestionnaireFinder

type QuestionnaireFinder interface {
	FindQuestionnaire(context.Context, string) (Questionnaire, error)
}

type QuestionnaireFinderFunc

type QuestionnaireFinderFunc func(context.Context, string) (Questionnaire, error)

func (QuestionnaireFinderFunc) FindQuestionnaire

func (f QuestionnaireFinderFunc) FindQuestionnaire(ctx context.Context, c string) (Questionnaire, error)

type QuestionnaireResolver

type QuestionnaireResolver interface {
	Resolve(context.Context, string) (Questionnaire, error)
}

type QuestionnaireResponse

type QuestionnaireResponse struct {
	ResourceType    string            `json:"resourceType"`
	ID              string            `json:"id,omitempty"`
	Questionnaire   string            `json:"questionnaire,omitempty"`
	Status          string            `json:"status,omitempty"`
	Subject         map[string]any    `json:"subject,omitempty"`
	Authored        string            `json:"authored,omitempty"`
	Item            []ResponseItem    `json:"item,omitempty"`
	Extension       []Extension       `json:"extension,omitempty"`
	Author          []Reference       `json:"-"`
	Reviewer        []Reference       `json:"-"`
	Signatures      []Signature       `json:"-"`
	CompletionMode  string            `json:"-"`
	ResponseReasons []CodeableConcept `json:"-"`
}

QuestionnaireResponse is a JSON behavior projection, not a replacement for pkg/proto/r4.QuestionnaireResponse or types.ResourceEnvelope. It remains exported temporarily for compatibility with the first SDC API revision.

func DecodeQuestionnaireResponseResource

func DecodeQuestionnaireResponseResource(env *types.ResourceEnvelope) (QuestionnaireResponse, error)

func DecodeResponse

func DecodeResponse(raw []byte) (QuestionnaireResponse, error)

func (QuestionnaireResponse) MarshalJSON

func (r QuestionnaireResponse) MarshalJSON() ([]byte, error)

func (*QuestionnaireResponse) UnmarshalJSON

func (r *QuestionnaireResponse) UnmarshalJSON(b []byte) error

type QuestionnaireVariable

type QuestionnaireVariable struct {
	Name       string     `json:"name,omitempty"`
	Expression Expression `json:"expression,omitempty"`
}

QuestionnaireVariable is an sdc-questionnaire-variable extension.

type Reference

type Reference struct {
	Reference string `json:"reference,omitempty"`
	Type      string `json:"type,omitempty"`
	Display   string `json:"display,omitempty"`
}

Reference is a lightweight FHIR Reference projection.

type ReferenceResolver

type ReferenceResolver interface {
	ResolveReference(context.Context, Reference) (map[string]any, error)
}

ReferenceResolver resolves a reference answer for profile validation.

type ResolvedElement

type ResolvedElement struct {
	Text      string
	Short     string
	Min       *int
	MaxLength *int
}

ResolvedElement carries StructureDefinition element metadata for assembly.

type ResourceService

ResourceService is the persistence surface needed by SDC. core.ResourceService satisfies it.

type ResourceServiceReferenceResolver

type ResourceServiceReferenceResolver struct {
	Service ResourceService
}

ResourceServiceReferenceResolver resolves references through a ResourceService.

func (ResourceServiceReferenceResolver) ResolveReference

func (r ResourceServiceReferenceResolver) ResolveReference(ctx context.Context, ref Reference) (map[string]any, error)

type ResourceStoreProvider

type ResourceStoreProvider interface {
	ResourceStore() store.ResourceStore
}

ResourceStoreProvider exposes the backing resource store for questionnaire resolution.

type ResponseBuilder

type ResponseBuilder struct {
	// contains filtered or unexported fields
}

ResponseBuilder constructs a QuestionnaireResponse from rendered form values while applying SDC answer typing rules. Use NewResponse to create a builder, set answers with Set or the typed helpers, then call Build to validate and obtain the response.

func NewResponse

func NewResponse(q Questionnaire) (*ResponseBuilder, error)

NewResponse creates a builder for the given questionnaire. The builder sets QuestionnaireResponse.questionnaire to Canonical(q) and defaults status to in-progress.

func (*ResponseBuilder) AppendAnswer

func (b *ResponseBuilder) AppendAnswer(linkID string, value any) *ResponseBuilder

AppendAnswer adds another answer for a repeating question identified by linkID. When linkID is unique the nesting level is resolved automatically.

func (*ResponseBuilder) AppendAnswerAt

func (b *ResponseBuilder) AppendAnswerAt(path ItemPath, linkID string, value any) *ResponseBuilder

AppendAnswerAt adds another answer for a repeating question at the given path.

func (*ResponseBuilder) AppendAnswerAtAnswer

func (b *ResponseBuilder) AppendAnswerAtAnswer(path ItemPath, answerIndex int, linkID string, value any) *ResponseBuilder

AppendAnswerAtAnswer adds another answer for a repeating question nested under answer[answerIndex] of the controlling item identified by path.

func (*ResponseBuilder) Build

Build assembles and validates the QuestionnaireResponse. It returns ValidationError when builder or SDC validation reports error issues.

func (*ResponseBuilder) BuildResource

func (b *ResponseBuilder) BuildResource(opts ValidationOptions) (*types.ResourceEnvelope, error)

BuildResource is like Build but returns a canonical ResourceEnvelope.

func (*ResponseBuilder) BuilderOutcome

func (b *ResponseBuilder) BuilderOutcome() Outcome

BuilderOutcome returns issues recorded during Set operations before Build validation. Most callers should use Build and handle ValidationError instead.

func (*ResponseBuilder) InGroup

func (b *ResponseBuilder) InGroup(linkID string, index int) *ResponseBuilder

InGroup selects the repeating-group instance used by subsequent auto-placed Set, AppendAnswer, and SetCoding calls for nested linkIds.

func (*ResponseBuilder) Preview

Preview returns the in-progress response without running validation.

func (*ResponseBuilder) Set

func (b *ResponseBuilder) Set(linkID string, value any) *ResponseBuilder

Set assigns an answer for linkID. When linkID is unique in the questionnaire the answer is placed at the correct nesting level automatically. When linkID appears at multiple levels, use SetAt or SetAtAnswer with an explicit path.

func (*ResponseBuilder) SetAt

func (b *ResponseBuilder) SetAt(path ItemPath, linkID string, value any) *ResponseBuilder

SetAt assigns an answer for linkID under the given parent path.

func (*ResponseBuilder) SetAtAnswer

func (b *ResponseBuilder) SetAtAnswer(path ItemPath, answerIndex int, linkID string, value any) *ResponseBuilder

SetAtAnswer assigns an answer for linkID nested under answer[answerIndex] of the controlling item identified by path. path must include the controlling question as its final segment.

func (*ResponseBuilder) SetAuthored

func (b *ResponseBuilder) SetAuthored(authored string) *ResponseBuilder

SetAuthored sets QuestionnaireResponse.authored.

func (*ResponseBuilder) SetCoding

func (b *ResponseBuilder) SetCoding(linkID, code string) *ResponseBuilder

SetCoding assigns a choice or open-choice answer by option code. The code is resolved to the declared answerOption Coding when present; otherwise an issue is recorded for closed choice items.

func (*ResponseBuilder) SetCodingAt

func (b *ResponseBuilder) SetCodingAt(path ItemPath, linkID, code string) *ResponseBuilder

SetCodingAt assigns a choice answer by option code at the given path.

func (*ResponseBuilder) SetCodingAtAnswer

func (b *ResponseBuilder) SetCodingAtAnswer(path ItemPath, answerIndex int, linkID, code string) *ResponseBuilder

SetCodingAtAnswer assigns a choice answer nested under answer[answerIndex].

func (*ResponseBuilder) SetCodingAtAnswerWithSystem

func (b *ResponseBuilder) SetCodingAtAnswerWithSystem(path ItemPath, answerIndex int, linkID, system, code string) *ResponseBuilder

SetCodingAtAnswerWithSystem assigns a choice answer nested under answer[answerIndex] with optional system matching.

func (*ResponseBuilder) SetCodingAtWithSystem

func (b *ResponseBuilder) SetCodingAtWithSystem(path ItemPath, linkID, system, code string) *ResponseBuilder

SetCodingAtWithSystem assigns a choice answer by code and optional system at the given path.

func (*ResponseBuilder) SetCodingWithSystem

func (b *ResponseBuilder) SetCodingWithSystem(linkID, system, code string) *ResponseBuilder

SetCodingWithSystem assigns a choice answer by code and, when system is non-empty, requires the matching answerOption system.

func (*ResponseBuilder) SetStatus

func (b *ResponseBuilder) SetStatus(status string) *ResponseBuilder

SetStatus sets QuestionnaireResponse.status.

func (*ResponseBuilder) SetSubject

func (b *ResponseBuilder) SetSubject(subject map[string]any) *ResponseBuilder

SetSubject sets QuestionnaireResponse.subject.

type ResponseItem

type ResponseItem struct {
	LinkID    string         `json:"linkId"`
	Text      string         `json:"text,omitempty"`
	Answer    []Answer       `json:"answer,omitempty"`
	Item      []ResponseItem `json:"item,omitempty"`
	Extension []Extension    `json:"extension,omitempty"`
	IsSubject bool           `json:"-"`
}

func (ResponseItem) MarshalJSON

func (ri ResponseItem) MarshalJSON() ([]byte, error)

func (*ResponseItem) UnmarshalJSON

func (ri *ResponseItem) UnmarshalJSON(b []byte) error

type ResponseValidator

type ResponseValidator struct {
	Base     validate.Validator
	Resolver QuestionnaireResolver
	Options  ValidationOptions
}

ResponseValidator validates QuestionnaireResponse envelopes with SDC rules. An optional base validator runs first for structural FHIR validation.

func (*ResponseValidator) ValidateResource

func (v *ResponseValidator) ValidateResource(ctx context.Context, resource *types.ResourceEnvelope) error

ValidateResource runs base validation when configured, then SDC response validation.

type SaveResponseOptions

type SaveResponseOptions struct {
	Questionnaire *types.ResourceEnvelope
	Resolver      QuestionnaireResolver
	Validation    ValidationOptions
}

SaveResponseOptions configures SDC validation before persisting a response.

func DefaultSaveResponseOptions

func DefaultSaveResponseOptions(s ResourceService) SaveResponseOptions

DefaultSaveResponseOptions builds save options that resolve questionnaires from the resource store when the service implements ResourceStoreProvider.

type SearchFHIRQueryProvider

type SearchFHIRQueryProvider struct {
	Search FHIRQuerySearch
}

SearchFHIRQueryProvider executes FHIR Query expressions against a local search service.

func NewSearchFHIRQueryProvider

func NewSearchFHIRQueryProvider(svc *search.Service) SearchFHIRQueryProvider

NewSearchFHIRQueryProvider constructs a provider backed by pkg/search.Service.

func (SearchFHIRQueryProvider) ExecuteFHIRQuery

func (p SearchFHIRQueryProvider) ExecuteFHIRQuery(ctx context.Context, query string, input any) ([]any, error)

ExecuteFHIRQuery parses a FHIR REST query and returns matching resources. Callers that need SDC %variable substitution should use executeFHIRQueryWithConstants or evaluate through a contextual expression provider.

func (SearchFHIRQueryProvider) ExecuteFHIRQueryWithConstants

func (p SearchFHIRQueryProvider) ExecuteFHIRQueryWithConstants(ctx context.Context, query string, constants map[string]any) ([]any, error)

ExecuteFHIRQueryWithConstants substitutes %variables from constants before executing the query.

type SequentialAdaptiveEngine

type SequentialAdaptiveEngine struct {
	Questionnaires []Questionnaire
	Resolver       QuestionnaireResolver
}

SequentialAdaptiveEngine is a small deterministic adaptive engine for applications that do not need a policy-specific next-question service. It searches a supplied catalog, walks enabled question items in questionnaire order, and stores submitted answers in the session. Applications with branching, scoring, or remote policy can continue to inject their own AdaptiveEngine.

func (SequentialAdaptiveEngine) NextQuestion

func (e SequentialAdaptiveEngine) NextQuestion(ctx context.Context, session *AdaptiveSession) (*Item, error)

func (SequentialAdaptiveEngine) Search

func (SequentialAdaptiveEngine) SubmitAnswer

func (e SequentialAdaptiveEngine) SubmitAnswer(ctx context.Context, session *AdaptiveSession, answer ResponseItem) (*Item, error)

type Signature

type Signature struct {
	Type []Coding  `json:"type,omitempty"`
	When string    `json:"when,omitempty"`
	Who  Reference `json:"who,omitempty"`
}

Signature is a questionnaire-responseSignature extension value.

type StaticTerminology

type StaticTerminology struct{ Codes map[string]map[string]string }

func (StaticTerminology) Display

func (s StaticTerminology) Display(_ context.Context, c Coding) (string, error)

func (StaticTerminology) Expand

func (s StaticTerminology) Expand(_ context.Context, url string) ([]Coding, error)

func (StaticTerminology) ValidateCode

func (s StaticTerminology) ValidateCode(_ context.Context, c Coding, _ string) error

type StoreDefinitionElementResolver

type StoreDefinitionElementResolver struct {
	Store DefinitionStore
}

StoreDefinitionElementResolver resolves elements from store.DefinitionStore StructureDefinitions.

func (StoreDefinitionElementResolver) ResolveElement

func (r StoreDefinitionElementResolver) ResolveElement(ctx context.Context, definition string) (ResolvedElement, error)

type StoreQuestionnaireResolver

type StoreQuestionnaireResolver struct{ Resources store.ResourceStore }

StoreQuestionnaireResolver resolves canonical questionnaires from the repository's existing ResourceStore without introducing SDC-specific tables.

func (StoreQuestionnaireResolver) FindQuestionnaire

func (s StoreQuestionnaireResolver) FindQuestionnaire(ctx context.Context, canonical string) (Questionnaire, error)

func (StoreQuestionnaireResolver) Resolve

func (s StoreQuestionnaireResolver) Resolve(ctx context.Context, canonical string) (Questionnaire, error)

type StructureMapExtractor

type StructureMapExtractor struct {
	Run func(context.Context, Questionnaire, QuestionnaireResponse) ([]json.RawMessage, error)
}

func (StructureMapExtractor) Extract

type SupportLink struct {
	URL   string `json:"url,omitempty"`
	Label string `json:"label,omitempty"`
}

SupportLink is a questionnaire-supportLink extension value.

type TemplateExtractContext

type TemplateExtractContext struct {
	TemplateReference string
	FullURL           string
	ResourceID        string
}

TemplateExtractContext references a contained resource template for extraction.

type TemplateExtractValue

type TemplateExtractValue struct {
	Path       string
	Expression *Expression
	Value      any
	ValueType  string
}

TemplateExtractValue maps a FHIRPath expression or fixed value into a template path.

type TemplateExtractor

type TemplateExtractor struct {
	Template func(context.Context, QuestionnaireResponse) ([]json.RawMessage, error)
}

func (TemplateExtractor) Extract

type TerminologyAdapter

type TerminologyAdapter struct {
	Service terminology.Provider
	ScopeID string
}

TerminologyAdapter adapts the terminology service to SDC validation.

func (TerminologyAdapter) Display

func (a TerminologyAdapter) Display(_ context.Context, c Coding) (string, error)

func (TerminologyAdapter) Expand

func (a TerminologyAdapter) Expand(ctx context.Context, url string) ([]Coding, error)

func (TerminologyAdapter) ValidateCode

func (a TerminologyAdapter) ValidateCode(ctx context.Context, c Coding, valueSet string) error

type TerminologyResolver

type TerminologyResolver interface {
	ValidateCode(context.Context, Coding, string) error
	Display(context.Context, Coding) (string, error)
	Expand(context.Context, string) ([]Coding, error)
}

type Tree

type Tree struct {
	Root     []Item
	ByLinkID map[string][]*Item
}

func Normalize

func Normalize(q Questionnaire) (Tree, error)

func (Tree) LinkIDs

func (t Tree) LinkIDs() []string

func (Tree) Resolve

func (t Tree) Resolve(linkID string) []*Item

type UnsupportedProvider

type UnsupportedProvider struct{ Language string }

func (UnsupportedProvider) Evaluate

type ValidationError

type ValidationError struct {
	Outcome Outcome
	// contains filtered or unexported fields
}

ValidationError carries a complete SDC OperationOutcome without collapsing diagnostics. It implements error while preserving every issue for structured callers.

func NewValidationError

func NewValidationError(o Outcome, cause error) ValidationError

NewValidationError wraps outcome and an optional underlying cause.

func (ValidationError) Error

func (e ValidationError) Error() string

func (ValidationError) OperationOutcome

func (e ValidationError) OperationOutcome() types.OperationOutcome

OperationOutcome returns the FHIR OperationOutcome representation of the validation failure.

func (ValidationError) Unwrap

func (e ValidationError) Unwrap() error

type ValidationOptions

type ValidationOptions struct {
	// Ctx carries request tenant terminology scope and opt-in when set.
	Ctx             context.Context
	Terminology     TerminologyResolver
	AllowIncomplete bool
	Expressions     ExpressionProvider
	LaunchContext   map[string]any
	Subject         any
	References      ReferenceResolver
}

func ValidationOptionsFromParameters

func ValidationOptionsFromParameters(params OperationParameters, base ValidationOptions) ValidationOptions

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL