Package {form.model}


Title: Versioned Form Definitions and Reference Catalogues
Version: 0.7.0
Description: Loads explicit YAML resources describing versioned forms, fields, declarative constraints, reference requirements, and workbook layouts. Checks model definitions and prepares the reference lookups they require. Retrieves and verifies reference catalogues from local or authenticated sources, caches tables for offline use, and matches text values with aliases and configurable matching. Resolves correspondences between independently configured catalogues.
License: LGPL-2.1
URL: https://ultreia-io.github.io/form.model/, https://github.com/ultreia-io/form.model
BugReports: https://github.com/ultreia-io/form.model/issues
Encoding: UTF-8
Depends: R (≥ 4.1.0)
Imports: base64enc, curl, digest, stats, utils, yaml (≥ 2.3.10)
Suggests: askpass, knitr, rmarkdown, testthat (≥ 3.0.0), withr
VignetteBuilder: knitr
Config/testthat/edition: 3
Config/Needs/coverage: covr, xml2
Config/Needs/website: pkgdown, zip
Config/roxygen2/version: 8.1.1
NeedsCompilation: no
Packaged: 2026-11-29 17:17:43 UTC; root
Author: Tony Chemit ORCID iD [aut, cre, cph] (URL: https://ultreia.io)
Maintainer: Tony Chemit <dev@tchemit.fr>
Repository: CRAN
Date/Publication: 2026-11-30 15:50:50 UTC

Versioned form models and reference catalogues

Description

Load and check YAML form models. Retrieve catalogue tables and prepare text lookups, including aliases. Map reference values between catalogues.

Author(s)

Maintainer: Tony Chemit dev@tchemit.fr (ORCID) (URL: https://ultreia.io) [copyright holder]

Authors:

See Also

Useful links:


Signal a model error

Description

Signal a model error

Usage

abort_model(resource, path, message, diagnostics = NULL)

Arguments

resource

Source label.

path

Location within the source.

message

Error message.

diagnostics

Optional definition diagnostics.

Value

Raises model_form_error carrying the supplied context.


Apply source overrides to a reference configuration

Description

Apply source overrides to a reference configuration

Usage

apply_reference_sources(configuration, overrides)

Arguments

configuration

Parsed reference configuration.

overrides

Source settings grouped by catalogue name.

Value

The configuration with the source overrides applied.


Construct a checked model

Description

Construct a checked model

Usage

as_form_model(definition, resource = "<list>")

Arguments

definition

Named list following form_schema(); sequences are unnamed lists.

resource

Source label for diagnostics.

Value

The definition as a form_model list, without the source label. Invalid definitions raise model_form_error with diagnostics.

Examples

# Load the bundled survey model.
model_definition <- read_form_model("examples/survey/form.yaml", "form.model")
# Construct a checked model from the definition.
as_form_model(form_definition(model_definition))

Resolve a verified cached CSV named by reference ID and checksum

Description

Resolve a verified cached CSV named by reference ID and checksum

Usage

cached_reference_file(source, path, checksum, directory, offline, id)

Arguments

source

Reference source configuration.

path

Relative source path.

checksum

Expected SHA-256.

directory

Source-specific cache directory.

offline

Whether network and source reads are forbidden.

id

Catalogue ID, or the catalogue name for its own CSV.

Value

Verified local CSV path.


Resolve several reference CSVs, downloading missing ones concurrently

Description

Resolve several reference CSVs, downloading missing ones concurrently

Usage

cached_reference_files(source, selected, directory, offline)

Arguments

source

Reference source configuration.

selected

Catalogue rows in requested order.

directory

Source-specific cache directory.

offline

Whether source requests are forbidden.

Value

Verified cached CSV paths in the same order as selected.


Decode a checked cell location

Description

Decode a checked cell location

Usage

cell_coordinates(location)

Arguments

location

Uppercase A1-style address already checked by the schema.

Value

List with one-based numeric row and column coordinates.


Check a form definition

Description

Check a form definition

Usage

check_form_model(definition, resource = "<list>")

Arguments

definition

Named list following form_schema(); sequences are unnamed lists.

resource

Source label for diagnostics.

Details

Checks schema structure, then model consistency if structure passes. Invalid definitions return diagnostics; invalid arguments raise model_form_error. Submitted data is not checked.

Value

A form_model_check with valid and a diagnostics data frame containing resource, path and message columns.

Examples

# Load the bundled survey model.
model_definition <- read_form_model("examples/survey/form.yaml", "form.model")
# Check the structure and consistency of the definition.
check_form_model(form_definition(model_definition))

Check a configuration against its packaged YAML schema

Description

Check a configuration against its packaged YAML schema

Usage

check_reference_configuration(configuration)

Arguments

configuration

Parsed YAML configuration.

Details

Uses the package's form.references/schema/1 dialect, not JSON Schema. Diagnostics never include configuration values or resolved credentials.

Value

NULL, invisibly; invalid configurations raise path-specific errors.


Download one reference file with a configured HTTP handle

Description

Download one reference file with a configured HTTP handle

Usage

download_reference_http_file(handle, destination)

Arguments

handle

Configured curl handle.

destination

Path for the response body.

Value

The curl response metadata.


Download a batch of reference files

Description

Download a batch of reference files

Usage

download_reference_http_files(handles, destinations)

Arguments

handles

Configured curl handles.

destinations

Paths for the response bodies.

Value

The curl transfer results in input order.


Download a source resource to a temporary destination

Description

Download a source resource to a temporary destination

Usage

fetch_reference_file(source, path, destination)

Arguments

source

Reference source configuration.

path

Validated relative resource path.

destination

Local file to write.

Value

Destination path, invisibly.


Get the complete definition

Description

Get the complete definition

Usage

form_definition(model)

Arguments

model

A checked form_model from read_form_model() or as_form_model().

Details

Accessors preserve declaration order and do not revalidate models. Treat checked models as read-only. Invalid model arguments raise model_form_error.

Value

An ordinary model definition with form, sheets, and references containing named catalogues and their declared tables.

Examples

# Load the bundled survey model.
model_definition <- read_form_model("examples/survey/form.yaml", "form.model")
# Inspect the declared form identity.
form_definition(model_definition)$form

Get one field

Description

Get one field

Usage

form_field(model, id)

Arguments

model

A checked form_model from read_form_model() or as_form_model().

id

Exact ⁠<sheet>.<field>⁠ identifier.

Value

One definition as returned by form_fields(). Unknown IDs raise model_form_error.

Examples

# Load the bundled survey model.
model_definition <- read_form_model("examples/survey/form.yaml", "form.model")
# Inspect the allowed values for the observation unit.
form_field(model_definition, "Observations.unit")$enum

Get fields in declaration order

Description

Get fields in declaration order

Usage

form_fields(model, sheet = NULL)

Arguments

model

A checked form_model from read_form_model() or as_form_model().

sheet

Exact worksheet name, or NULL for all sheets.

Details

Adds field IDs, names, sheet names and numeric coordinates. Omitted mandatory becomes FALSE; reference severity defaults to "error". Use form_definition() for the original declarations.

Value

Field definitions named ⁠<sheet>.<field>⁠. Unknown sheets raise model_form_error.

Examples

# Load the bundled survey model.
model_definition <- read_form_model("examples/survey/form.yaml", "form.model")
# Inspect the observation fields in workbook column order.
form_fields(model_definition, sheet = "Observations")

Get a sheet layout

Description

Get a sheet layout

Usage

form_layout(model, id)

Arguments

model

A checked form_model from read_form_model() or as_form_model().

id

Exact worksheet name.

Value

The effective layout (cells or table), with table column_count derived from the fields. Unknown sheets raise model_form_error.

Examples

# Load the bundled survey model.
model_definition <- read_form_model("examples/survey/form.yaml", "form.model")
# Inspect the observation table layout.
form_layout(model_definition, "Observations")

Get form identity and versions

Description

Get form identity and versions

Usage

form_metadata(model)

Arguments

model

A checked form_model from read_form_model() or as_form_model().

Value

A list with form and schema_version.

Examples

# Load the bundled survey model.
model_definition <- read_form_model("examples/survey/form.yaml", "form.model")
# Inspect the model identity and declared reference catalogues.
form_metadata(model_definition)

Get declared reference catalogues and tables

Description

Get declared reference catalogues and tables

Usage

form_references(model)

Arguments

model

A checked form_model from read_form_model() or as_form_model().

Value

A named list of catalogue names and their declared table identifiers. Reference data is not loaded.

Examples

# Load the bundled survey model.
model_definition <- read_form_model("examples/survey/form.yaml", "form.model")
# Inspect the catalogue and table requirements.
form_references(model_definition)

Locate an installed resource

Description

Locate an installed resource

Usage

form_resource(path, package)

Arguments

path

File path relative to the package directory.

package

Installed package name.

Value

Absolute file path. Missing files and paths escaping the package raise model_form_error.

Examples

# Locate the installed survey definition.
form_resource("examples/survey/form.yaml", "form.model")

Read the model-definition schema

Description

Read the model-definition schema

Usage

form_schema(version = "1.0.0")

Arguments

version

Schema version; currently "1.0.0".

Details

Uses the package's form.model/schema/1 dialect, not JSON Schema.

Value

The schema as a nested list. Unsupported versions raise model_form_error.

Examples

# Inspect the supported schema contract version.
form_schema()$contract_version

Get sheet definitions

Description

Get sheet definitions

Usage

form_sheets(model)

Arguments

model

A checked form_model from read_form_model() or as_form_model().

Details

Table layouts include column_count derived from the ordered fields. An optional primary_key preserves the declared sequence of local field names. Key components must be filled and their combination must identify one row; this package checks the declaration, not submitted values. unique_key preserves an ordered key whose complete values must be unique. at_least_one preserves selected fields and optional severity (default error); populated rows must supply at least one selected value. Use form_definition() for the original declarations.

Value

Sheets in declaration order, named by worksheet, each with fields and layout.

Examples

# Load the bundled survey model.
model_definition <- read_form_model("examples/survey/form.yaml", "form.model")
# List the worksheet names in workbook order.
names(form_sheets(model_definition))

Check a scalar against a form field type

Description

Share field-type checks between model definitions and validation consumers. Requiredness and other field constraints are handled by the caller.

Usage

form_value_matches_type(x, type)

Arguments

x

Scalar value to check, without coercion.

type

One of string, email, integer, number, boolean, latitude, longitude, date, or datetime.

Details

Dates require YYYY-MM-DD; datetimes require YYYY-MM-DDTHH:MM:SSZ. Both must parse and format back to the identical string, using UTC for datetimes. Emails require nonempty local and domain parts, a domain dot, and no whitespace or additional at signs. Mailbox existence is not checked. Numeric values must be finite; integers must have no fractional part. Coordinates are decimal degrees: latitude is in ⁠[-90, 90]⁠ and longitude in ⁠[-180, 180]⁠, including both endpoints. Numeric text is not coerced.

Value

One logical value; FALSE for missing or incompatible values, unsupported types, or classed values such as factors, Date, and POSIXct.

Examples

# Check whether the value matches the email type.
form_value_matches_type("contact@example.org", "email")
# Check whether the value matches the datetime type.
form_value_matches_type("2026-10-18T12:00:00Z", "datetime")

Retrieve selected tables from the configured catalogue

Description

Retrieve selected tables from the configured catalogue

Usage

get_reference_tables(ids, source, offline = FALSE)

Arguments

ids

Exact catalogue IDs.

source

Source configuration.

offline

Use verified cache only.

Details

CSV values remain text, including leading zeros. The source selects the catalogue; the caller supplies its table IDs. No model interpretation occurs. When present, the reserved aliases table (domain catalogue) is retrieved too, through the same source and verified cache. Its columns are table, column, alias and canonical. Alias targets are checked for the retrieved tables. Aliases are grouped once by table and column and attached to the retrieved tables. reference_index() applies them automatically for the selected column. The reserved alias table is not returned in data and cannot be requested directly.

Value

Verified tables, paths, catalogue rows and publication metadata.

Examples

# Choose a temporary location for this example.
reference_cache_directory <- tempfile("references-")
# Configure the reference catalogue sources.
reference_source_configuration <- reference_source(
  system.file("examples", "survey", "catalogue", "code_lists", package = "form.model"),
  reference_cache_directory)
# Retrieve the selected tables and verify their checksums.
reference_tables <- get_reference_tables(c("stations", "observers"), reference_source_configuration)
# Display the selected reference rows or values.
reference_tables$data$stations$code
# Remove the temporary files created by this example.
unlink(reference_cache_directory, recursive = TRUE)

Check whether secure password prompting is available

Description

Check whether secure password prompting is available

Usage

has_reference_password_prompt()

Value

TRUE when askpass can be loaded.


Load a model by filename prefix

Description

Load a model by filename prefix

Usage

load_form_model(name, directory)

Arguments

name

Prefix of ⁠<name>-form.yaml⁠, starting with a letter and containing only letters, digits, underscores, dots or hyphens.

directory

Directory containing the file.

Value

A checked form_model; see read_form_model() for errors.

Examples

# Choose a temporary directory for the named model example.
model_directory <- tempfile("named-model-")
# Create the temporary model directory.
dir.create(model_directory)
# Copy the survey definition using the named-loader convention.
file.copy(form_resource("examples/survey/form.yaml", "form.model"),
  file.path(model_directory, "survey-form.yaml"))
# Load the definition using its filename prefix.
load_form_model("survey", model_directory)
# Remove the temporary model directory.
unlink(model_directory, recursive = TRUE)

Resolve encountered source values to target reference values

Description

Resolve encountered source values to target reference values

Usage

map_reference_values(
  prepared,
  target,
  values,
  source_table = NULL,
  source_lookup = NULL,
  target_lookup = NULL,
  property = NULL
)

Arguments

prepared

A result from prepare_mapping_references().

target

One prepared target table ID.

values

Character vector or list of scalar text values. NULL elements, NA and empty text indicate missing input; other types are rejected.

source_table

Optional source table selector.

source_lookup

Optional effective source lookup selector.

target_lookup

Optional effective target lookup selector.

property

Optional returned target property selector.

Details

Selectors must identify exactly one mapping; alternatives are never fallbacks. Status is resolved, missing_input, missing_source_record, missing_property, no_match or ambiguous. Stage is input, source, correspondence or target. Only resolved results receive a target value. Source and target ambiguities retain all matching rows even if their requested properties agree. Conflicting CSV targets remain ambiguous even if target aliases would converge. Repeated inputs and reusable target lookups are evaluated together. The caller decides whether unresolved results block a field, row or export.

Value

A data frame with one row per input in original order. Scalar columns are source_value, target_value, status and stage. List columns retain source_rows, target_rows, target_candidates and correspondence_values. Row indexes address the corresponding prepared reference index's data. The provenance attribute contains the selected mapping, configuration checksum, catalogue revisions and any correspondence-file checksum.


Mapping configuration objects

Description

An S3 mapping_configuration is a named list of correspondences between two reference catalogues.

Construction

Use read_mapping_configuration() to read and validate mapping.yaml.

Lookup defaults and returned properties are made explicit, and correspondence-file paths become absolute.

Reading does not load catalogue rows or open correspondence files.

Structure

Alternatives are always stored as lists, including when the YAML uses the compact single-alternative form.

Catalogue definitions and their data are not embedded in this object.

Attributes

Use

Pass the object and named reference_configuration objects to prepare_mapping_references().

Mapping alternatives require an explicit, unambiguous selection; they are not fallbacks.

There are no class-specific S3 methods.

See Also

read_mapping_configuration(), resolve_mapping_lookups(), mapping_references


Prepared mapping reference objects

Description

An S3 mapping_references is a list holding the catalogue indexes and correspondences needed for value resolution.

Construction

Use prepare_mapping_references() with a mapping_configuration and named reference configurations.

Preparation loads the selected target mappings and their required data, checks columns and reads correspondence files.

Only rebound mappings require source catalogue rows.

Structure

Each alternative contains its mapping, source_index and target_index.

source_index is NULL for CSV and unchanged-input correspondences.

Keys linking alternatives, reference indexes and provenance are internal identifiers.

Use

Pass the object to map_reference_values() for each selected target and its encountered source values.

Prepare it once and reuse it for successive calls; prepare it again when configuration or reference data changes.

Inspect the returned result rows and their provenance for resolution diagnostics.

Mapping results are ordinary data frames, not another custom S3 class.

There are no class-specific S3 methods.

See Also

prepare_mapping_references(), map_reference_values(), mapping_configuration


Read the catalogue-mapping schema

Description

Read the catalogue-mapping schema

Usage

mapping_schema(version = "1.0.0")

Arguments

version

Schema version; currently "1.0.0".

Details

Uses the package-specific form.references/mapping-schema/1 dialect.

Value

The packaged schema as a nested list. Unsupported versions raise an error.

Examples

mapping_schema()$contract_version

Check a model argument's shape

Description

Check a model argument's shape

Usage

model_arg(model)

Arguments

model

Object passed to an accessor.

Value

Returns silently for a form_model with required top-level properties; otherwise raises model_form_error. Does not recheck the definition.


Build order-independent comparison keys for names

Description

Build order-independent comparison keys for names

Usage

normalized_name_key(x, ignore_case = TRUE)

Arguments

x

Character vector of names.

ignore_case

Ignore letter case? Defaults to TRUE.

Details

Removes commas, squishes whitespace, optionally uppercases and transliterates accents to ASCII, replaces apostrophes, hyphens, dots and parentheses with spaces, then sorts and concatenates words. This is not fuzzy matching or a cryptographic hash. Different names can share a key; retain duplicate rows.

Value

Character keys; missing or empty normalized names return NA.


Check value attributes

Description

Check value attributes

Usage

plain(x)

Arguments

x

Any R object.

Value

Whether attributes are absent or limited to names.


Prepare catalogue tables and explicit correspondences for mappings

Description

Prepare catalogue tables and explicit correspondences for mappings

Usage

prepare_mapping_references(
  mapping,
  configurations,
  targets = NULL,
  offline = FALSE,
  catalogues = NULL
)

Arguments

mapping

A configuration from read_mapping_configuration().

configurations

Named list of reference configurations from read_reference_configuration(), keyed by the mapping's configuration names.

targets

Target table IDs to prepare; NULL selects every configured target.

offline

Use verified reference caches only. Correspondence CSVs are local files.

catalogues

Optional results from get_reference_tables(), grouped first by configuration name and then by catalogue name. These supply tables already in memory.

Details

Retrieves each required table once per configuration and catalogue. Source rows are required only for property-based correspondences. File-based and unchanged-input mappings check source declarations but load target data only. Different lookups share table retrieval; repeated identical lookups share indexes.

Checks actual lookup and property columns, CSV headers and nonempty text values. Identical CSV pairs are deduplicated; conflicting targets remain candidates. Preparation does not require every source value to have a correspondence.

Value

A mapping_references object retaining the selected alternatives, shared reference indexes, correspondence tables and provenance.

Examples

local({
  directory <- system.file("examples", "survey", package = "form.model")
  mapping <- read_mapping_configuration(file.path(directory, "mapping.yaml"))
  source <- read_reference_configuration(file.path(directory, "references-source.yaml"))
  target <- read_reference_configuration(file.path(directory, "references.yaml"))
  configurations <- list(source = source, target = target)
  on.exit({
    for (configuration in configurations) {
      for (catalogue in configuration$catalogues) unlink(catalogue$source$cache, recursive = TRUE)
    }
  })
  prepared <- prepare_mapping_references(mapping, configurations)
  map_reference_values(prepared, "stations", c("station-north", "station-unmapped"))[, 1:4]
})

Prepare reference values selected by a model

Description

Prepare reference values selected by a model

Usage

prepare_model_references(
  model,
  configuration,
  offline = FALSE,
  catalogues = NULL
)

Arguments

model

An unresolved form model with named lookup bindings.

configuration

Combined configuration from read_reference_configuration().

offline

Use verified cached files only; defaults to FALSE.

catalogues

Optional results from get_reference_tables(), named by catalogue. Supply these to build lookups from tables already in memory.

Details

Table IDs and lookup columns come exclusively from the model's resolved bindings. Each required table is retrieved once per catalogue. Empty lookup values are excluded; duplicate rows and canonical spelling are retained. Catalogue aliases are grouped once by table and column. Each required lookup is indexed with only its own aliases and can be passed to reference_match_rows(). Alias file paths and checksums are recorded in provenance. Missing sources, tables or columns raise errors. No validation rules are run.

Value

A list containing model (the resolved model) and references (named indexes with values, complete rows, lookup settings and provenance). The supplied model is unchanged.

Examples

# Load the requested form model.
form_model_definition <- form.model::read_form_model("examples/survey/form.yaml", "form.model")
# Read the catalogue sources and lookup definitions.
reference_configuration <- read_reference_configuration(
  system.file("examples", "survey", "references.yaml", package = "form.model"))
# Use a temporary cache for this example.
reference_cache_directory <- tempfile("model-references-")
# Assign the temporary cache to each catalogue source.
for (catalogue in names(reference_configuration$catalogues))
  reference_configuration$catalogues[[catalogue]]$source$cache <- reference_cache_directory
# Prepare the reference tables required by the form model.
reference_preparation <- prepare_model_references(form_model_definition, reference_configuration)
# Display the returned values.
names(reference_preparation$references)
# Display the selected reference rows or values.
reference_preparation$references[["registries/contacts/email"]]$data
# Remove the temporary files created by this example.
unlink(reference_cache_directory, recursive = TRUE)

Print a model summary

Description

Print a model summary

Usage

## S3 method for class 'form_model'
print(x, ...)

Arguments

x

A checked form_model.

...

Unused.

Value

x, invisibly; prints identity, versions, and field and sheet counts.


Print definition check results

Description

Print definition check results

Usage

## S3 method for class 'form_model_check'
print(x, ...)

Arguments

x

A form_model_check from check_form_model().

...

Unused.

Value

x, invisibly; prints validity and any diagnostics.


Print a reference source without authentication details

Description

Print a reference source without authentication details

Usage

## S3 method for class 'reference_source'
print(x, ...)

Arguments

x

A reference_source object.

...

Unused arguments.

Value

x, invisibly.


Prompt for a missing catalogue password

Description

Prompt for a missing catalogue password

Usage

prompt_reference_password(variable)

Arguments

variable

Name of the environment variable for the password.

Value

The user's reply from askpass.


Read catalogue publication metadata without evaluating YAML expressions

Description

Read catalogue publication metadata without evaluating YAML expressions

Usage

read_catalogue_metadata(path)

Arguments

path

Local YAML path.

Value

A list containing published_at and sha256 strings.


Read and check a YAML form model

Description

Read and check a YAML form model

Usage

read_form_model(path, package = NULL)

Arguments

path

File path, or package-relative path when package is supplied.

package

Optional installed package name.

Details

Uses YAML 1.1 types: quote versions and codes; use true/false for booleans. Tags, anchors, aliases, merges, directives and document markers are unsupported. The source path is not stored in the model.

Value

A checked form_model list. Invalid YAML or definitions raise model_form_error with source context and available diagnostics.

Examples

# Load the bundled survey model.
model_definition <- read_form_model("examples/survey/form.yaml", "form.model")
# Inspect the model identity and declared reference catalogues.
form_metadata(model_definition)

Read catalogue correspondences without loading data

Description

Read catalogue correspondences without loading data

Usage

read_mapping_configuration(path)

Arguments

path

Local mapping YAML path.

Details

Validates the versioned mapping schema, lookup inheritance and alternative uniqueness. A selection is identified by its source table, source lookup, target lookup and returned property. YAML expressions are never evaluated. Reading does not load reference configurations, open CSV correspondence files or retrieve catalogue data.

Relative correspondence paths resolve from the YAML directory. File existence, contents and table columns are checked during preparation.

Value

A mapping_configuration object. Each target table contains a list of alternatives, including when YAML uses the compact single-mapping form. Effective source and target lookups and the returned property are explicit. Correspondence file paths are absolute. The provenance attribute records the configuration path and SHA-256 checksum.

Examples

mapping <- read_mapping_configuration(system.file(
  "examples", "survey", "mapping.yaml", package = "form.model"))
names(mapping$mappings)

Read the catalogue selected by a source

Description

Read the catalogue selected by a source

Usage

read_reference_catalogue(source, offline = FALSE)

Arguments

source

Source configuration.

offline

Use the verified cache only.

Details

Catalogue and CSV checksums are verified before cached files are replaced.

Value

Catalogue rows with publication metadata.

Examples

# Choose a temporary location for this example.
reference_cache_directory <- tempfile("references-")
# Configure the reference catalogue sources.
reference_source_configuration <- reference_source(
  system.file("examples", "survey", "catalogue", "code_lists", package = "form.model"),
  reference_cache_directory)
# Read the catalogue and display its table IDs and versions.
read_reference_catalogue(reference_source_configuration)[, c("id", "version")]
# Remove the temporary files created by this example.
unlink(reference_cache_directory, recursive = TRUE)

Read catalogue sources and lookup definitions

Description

Read catalogue sources and lookup definitions

Usage

read_reference_configuration(path, prompt = FALSE, sources_path = NULL)

Arguments

path

YAML configuration path.

prompt

Securely prompt for missing passwords; defaults to FALSE.

sources_path

Optional YAML mapping catalogue names to source overrides. Relative override paths resolve from this file.

Details

The packaged schema/references-1.0.0.yaml schema checks the required schema_version. Each catalogue declares source and tables; each source directory contains catalogue.yaml and catalogue.csv; lookup names are column names. Relative source and cache paths resolve from the YAML directory. The schema uses form.references/schema/1, not JSON Schema.

Sources accept url, cache, timeout and max_connections, plus user and password for HTTPS Basic authentication. If cache is omitted, each source uses a temporary directory for the current R session. Set cache explicitly to retain downloaded files across sessions. Use password: !env VARIABLE to read a secret from the environment. With prompt = TRUE, missing passwords are requested through askpass. Credentials remain in memory; do not serialize the result.

Value

A reference_configuration object containing named catalogues, each with a reference_source object and table lookup definitions. No data is downloaded.

Examples

# Read the catalogue sources and lookup settings.
reference_configuration <- read_reference_configuration(
  system.file("examples", "survey", "references.yaml", package = "form.model"))
# Inspect the configured catalogue names.
names(reference_configuration$catalogues)

Read a reference CSV without value conversion

Description

Read a reference CSV without value conversion

Usage

read_reference_csv(path)

Arguments

path

CSV path.

Value

A data.frame with character columns and original column names.


Read restricted YAML as data

Description

Read restricted YAML as data

Usage

read_yaml_data(path)

Arguments

path

UTF-8 YAML file.

Details

Uses YAML 1.1 types without expression evaluation. Invalid syntax, non-string keys and parser warnings raise model_form_error.

Value

Parsed data: named lists for mappings and unnamed lists for sequences.


Resolve the source-specific cache directory

Description

Resolve the source-specific cache directory

Usage

reference_cache(source)

Arguments

source

Reference source configuration.

Value

Source-specific directory path.


Name cached CSVs by catalogue ID and content revision

Description

Name cached CSVs by catalogue ID and content revision

Usage

reference_cache_paths(directory, ids, checksums)

Arguments

directory

Source-specific cache directory.

ids

Validated catalogue IDs or catalogue name.

checksums

Expected SHA-256 checksums.

Value

Readable cache paths. Full checksums still verify every file.


Reference configuration objects

Description

An S3 reference_configuration is a named list describing reference catalogues and their lookup policies.

Construction

Use read_reference_configuration() to read and validate a reference YAML file.

Relative paths and environment variables are resolved before the object is returned.

No catalogue data is downloaded at this stage.

Structure

Use

Pass the object to resolve_reference_lookups() or prepare_model_references() for form-model references.

Named lists of these objects supply the catalogues used by prepare_mapping_references().

Sources can contain authentication headers in memory; do not serialize a configuration containing credentials.

There are no class-specific S3 methods.

See Also

read_reference_configuration(), reference_source, mapping_configuration


Internal environment-variable reference objects

Description

The internal S3 class reference_env marks an environment-variable name parsed from a YAML !env tag.

Construction and structure

The YAML handler inside read_reference_configuration() creates this temporary object.

It contains the tagged variable name, represented as a character scalar, with class reference_env.

For example, ⁠password: !env REGISTRY_PASSWORD⁠ marks the name REGISTRY_PASSWORD, not its secret value.

Lifecycle

This class has no public constructor or class-specific S3 methods.

Configure environment references through YAML rather than constructing this internal marker directly.

See Also

read_reference_configuration(), reference_configuration


Resolve a YAML environment-variable reference

Description

Resolve a YAML environment-variable reference

Usage

reference_environment_value(variable, prompt = FALSE)

Arguments

variable

Environment-variable name supplied through the YAML !env tag.

prompt

Whether to request a missing secret using askpass.

Value

The nonempty environment-variable value or prompted secret.


Compare a file's bytes with an expected checksum

Description

Compare a file's bytes with an expected checksum

Usage

reference_hash_matches(path, checksum)

Arguments

path

Local path.

checksum

Expected SHA-256.

Value

TRUE only for an existing file with the expected checksum.


Resolve HTTP headers without persisting credentials

Description

Resolve HTTP headers without persisting credentials

Usage

reference_headers(headers)

Arguments

headers

Named strings or a function returning them.

Value

A named character vector, possibly empty.


Build a shared lookup over reference rows

Description

Build a shared lookup over reference rows

Usage

reference_index(data, column = NULL, matching = "exact", ignore_case = TRUE)

Arguments

data

Reference table, character vector or list of text values. Rows are retained in order.

column

Lookup column when data is a data frame; otherwise NULL.

matching

"exact" or "name" for optional normalized-name fallback.

ignore_case

Ignore case in keys, aliases and name fallback? Defaults to TRUE.

Details

Lookup keys are plain text. Values are never converted to text implicitly. Reference matching supports text fields only. Catalogue aliases attached to the selected column are applied automatically. Inspect index$aliases for that lookup's alias-to-canonical mappings. Exact matches take precedence over aliases, then name fallback. Duplicate rows remain separate matches. No catalogue-specific validity policy is applied: callers decide whether any match or exactly one match is required. Submitted and reference values are unchanged.

Value

A reference_index object retaining the original data, values and row indexes.

Examples

# Prepare species.
reference_species_table <- data.frame(code = c("001", "002"), label = c("First", "Second"))
# Prepare reference index.
reference_index <- reference_index(reference_species_table, "code")
# Prepare reference rows.
reference_rows <- reference_match_rows(reference_index, c("001", "unknown"))
# Display the selected reference rows or values.
reference_index$data[reference_rows[[1]], , drop = FALSE]
# Display the number of matching rows for each submitted value.
lengths(reference_rows)

Reference lookup index objects

Description

An S3 reference_index is a list retaining reference values, their rows and reusable matching indexes.

Construction

Use reference_index() to index a reference table, character vector or list of text values.

prepare_model_references() and prepare_mapping_references() also create these objects internally.

Catalogue aliases attached to the selected lookup column are incorporated automatically.

Structure

Preparation may add a lookup specification.

Model-based preparation also adds version, containing the reference table's SHA-256 checksum.

Use

Pass the object to reference_match_rows() to obtain matching row indexes for each supplied value.

Those indexes address this object's data; they are not necessarily row numbers in the original CSV.

Exact matches take precedence over aliases, followed by configured normalized-name matching.

Duplicate matches remain separate candidates. Rebuild the index after changing its data or lookup policy.

There are no class-specific S3 methods; use the lookup function rather than editing the internal indexes.

See Also

reference_index(), reference_match_rows(), mapping_references


Encode a text comparison key

Description

Encode a text comparison key

Usage

reference_key(x, ignore_case = FALSE)

Arguments

x

One nonmissing text value.

ignore_case

Ignore letter case? Defaults to FALSE.

Value

A UTF-8 comparison key, prefixed so empty text has a nonempty key.


Find matching reference rows

Description

Find matching reference rows

Usage

reference_match_rows(index, values)

Arguments

index

Lookup from reference_index() or prepare_model_references().

values

Character vector or list of text values; NULL and NA indicate missing values.

Details

Repeated values share a lookup. Use lengths() for match counts and the returned positions to retrieve canonical codes or complete entity rows.

Value

One integer vector per input value, containing matching positions in index$data and index$values. Unknown or missing values return integer(0). Multiple positions are preserved; no arbitrary canonical row is selected.


Identify missing lookup values

Description

Identify missing lookup values

Usage

reference_null_value(x)

Arguments

x

One lookup value.

Value

TRUE for NULL, NA or NA_character_.


Configure one restricted HTTP reference request

Description

Configure one restricted HTTP reference request

Usage

reference_request_handle(source, path)

Arguments

source

Reference source configuration.

path

Validated relative resource path.

Value

A curl handle with the URL and request policy applied.


Read the reference-configuration schema

Description

Read the reference-configuration schema

Usage

reference_schema(version = "1.0.0")

Arguments

version

Schema version; currently "1.0.0".

Details

Uses the package's form.references/schema/1 dialect, not JSON Schema.

Value

The schema as a nested list. Unsupported versions raise an error.

Examples

# Inspect the supported schema contract version.
reference_schema()$contract_version

Configure a reference source

Description

Configure a reference source

Usage

reference_source(
  url,
  cache = tempfile("form.model-"),
  headers = NULL,
  timeout = 60,
  max_connections = 4L
)

Arguments

url

HTTP(S) base URL or local directory containing the selected catalogue.yaml and catalogue.csv files. URLs must not contain credentials, query strings or fragments.

cache

Local cache directory. Defaults to a new temporary directory for this source in the current R session. Supply an explicit path to retain files across sessions. Different sources receive separate subdirectories. Use separate caches for separate authenticated identities.

headers

Named HTTP header values, or a function returning them at request time. NULL sends no authentication headers.

timeout

Positive request timeout in seconds.

max_connections

Maximum simultaneous CSV downloads. The default is four.

Details

Credentials stay in memory and are never written into the cache. Authenticated requests do not follow redirects; supply the final base URL.

Value

A reference_source object. No files are downloaded.

Examples

# Configure the reference catalogue sources.
reference_source_configuration <- reference_source(
  system.file("examples", "survey", "catalogue", "code_lists", package = "form.model"),
                           cache = tempfile("references-"))
# Configure the reference catalogue sources.
reference_source_configuration

Reference source objects

Description

An S3 reference_source is a list describing how to retrieve and cache one reference catalogue.

Construction

Use reference_source() directly, or read a source declaration with read_reference_configuration().

Construction validates the settings but does not download files or create the cache directory.

Structure

Cache lifetime

The default cache is a new path in the current R session's temporary directory.

An explicitly configured cache path can be reused across sessions.

Authentication headers remain in memory and are not written to the cache.

Use and methods

Pass the object to read_reference_catalogue() or get_reference_tables().

The registered print.reference_source() method displays the source URL and cache path without printing headers.

This is the only package-defined S3 method for this class.

See Also

reference_source(), print.reference_source(), reference_configuration


Select catalogue aliases for one lookup

Description

Select catalogue aliases for one lookup

Usage

reference_table_aliases(aliases, table, column, values, ignore_case = FALSE)

Arguments

aliases

Alias rows already selected for one table and column, or NULL.

table

Reference table identifier.

column

Lookup column.

values

Canonical values from the reference table.

ignore_case

Whether comparison ignores case.

Value

A named character vector mapping aliases to canonical values.


Check whether a value is plain text

Description

Check whether a value is plain text

Usage

reference_text(x)

Arguments

x

One lookup value.

Value

TRUE for one unclassed, nonmissing character value.


Rename a reference cache file

Description

Rename a reference cache file

Usage

rename_reference_cache_file(from, to)

Arguments

from

Source file path.

to

Destination file path.

Value

TRUE if the rename succeeds.


Replace a cache file while retaining the previous file on failure

Description

Replace a cache file while retaining the previous file on failure

Usage

replace_cache_file(staged, target)

Arguments

staged

Complete temporary file on the same filesystem.

target

Final path.

Value

Target path, invisibly.


Require the selected tables in an already retrieved catalogue

Description

Require the selected tables in an already retrieved catalogue

Usage

require_reference_tables(ids, catalogue, label)

Arguments

ids

Required table IDs.

catalogue

Result from get_reference_tables().

label

Catalogue name for diagnostics.

Value

The supplied catalogue.


Resolve the lookup declarations of a catalogue mapping

Description

Resolve the lookup declarations of a catalogue mapping

Usage

resolve_mapping_lookups(mapping, configurations)

Arguments

mapping

A configuration from read_mapping_configuration().

configurations

Named list of reference configurations from read_reference_configuration(), keyed by the mapping's configuration names.

Details

Checks both catalogue declarations without loading catalogue rows or correspondence files. Actual property columns are checked during preparation.

Value

The mapping with a mapping_lookups attribute containing the resolved lookup policies for every alternative. The input is unchanged.


Resolve a model's named reference lookups

Description

Resolve a model's named reference lookups

Usage

resolve_reference_lookups(model, configuration = NULL)

Arguments

model

A form model with named reference bindings.

configuration

Catalogue definitions from read_reference_configuration(). May be NULL only when the model is already resolved.

Details

Already resolved models retain their frozen definitions. Supplying a new configuration for such a model is rejected; resolve the original model instead. No catalogue rows are loaded. Unknown table or lookup names fail immediately.

Value

A checked form model with explicit lookup settings and a reference_lookups attribute freezing the resolved definitions.

Examples

# Load the requested form model.
form_model_definition <- form.model::read_form_model("examples/survey/form.yaml", "form.model")
# Read the named reference lookup settings.
reference_configuration <- read_reference_configuration(
  system.file("examples", "survey", "references.yaml", package = "form.model"))
# Resolve reference lookups without changing the original form model.
reference_resolved_form_model <- resolve_reference_lookups(
  form_model_definition, reference_configuration)
# Display the returned values.
names(attr(reference_resolved_form_model, "reference_lookups"))

Require one nonempty text value

Description

Require one nonempty text value

Usage

scalar_text(value, label)

Arguments

value

Value to check.

label

Argument name used in errors.

Value

NULL, invisibly.


Check a schema scalar type

Description

Check a schema scalar type

Usage

scalar_type(x, type)

Arguments

x

Value to check without coercion.

type

string, boolean, number, integer, or scalar.

Value

Whether x is one nonmissing, unclassed value of the requested type. Numbers must be finite; scalar accepts text, logicals and numbers.


Collect schema diagnostics

Description

Collect schema diagnostics

Usage

schema_check(x, node, definitions, path, add)

Arguments

x

Definition value.

node

Schema node.

definitions

Schema definitions for resolving references.

path

Diagnostic location.

add

Callback receiving ⁠(path, message)⁠.

Value

Invisible NULL; diagnostics are passed to add.


Select an exact model version

Description

Select an exact model version

Usage

select_form_model(paths, id, version, package = NULL)

Arguments

paths

Nonempty character vector of YAML file paths.

id

Exact form identifier.

version

Exact form version.

package

Optional installed package containing the relative paths.

Value

The matching form_model. All files are checked; invalid files or anything other than one match raise model_form_error.

Examples

# Select the survey definition with the exact requested version.
select_form_model("examples/survey/form.yaml", "survey", "2026.2",
                  package = "form.model")

Collect model consistency diagnostics

Description

Collect model consistency diagnostics

Usage

semantic_check(d, add)

Arguments

d

Definition that has passed schema checking.

add

Callback receiving ⁠(path, message)⁠.

Value

Diagnostics for references, constraints, dependencies and layouts, passed to add.


Apply headers to a reference request

Description

Apply headers to a reference request

Usage

set_reference_request_headers(handle, headers)

Arguments

handle

Configured curl handle.

headers

Named list of HTTP headers.

Value

The updated curl handle, invisibly.


Require a nonempty string

Description

Require a nonempty string

Usage

text_arg(x, name)

Arguments

x

Value to check; whitespace is not trimmed.

name

Argument name for errors.

Value

Returns silently on success; raises model_form_error otherwise.


Require relative resource paths confined to the source

Description

Require relative resource paths confined to the source

Usage

valid_reference_paths(paths)

Arguments

paths

Character vector of slash-separated paths.

Value

NULL, invisibly.


Check catalogue-owned alias rows

Description

Check catalogue-owned alias rows

Usage

validate_reference_aliases(aliases, catalogue, tables)

Arguments

aliases

Downloaded aliases table.

catalogue

Complete catalogue inventory.

tables

Retrieved reference tables.

Value

Alias mappings grouped by retrieved table and column.


Validate the downloadable catalogue contract

Description

Validate the downloadable catalogue contract

Usage

validate_reference_catalogue(catalogue)

Arguments

catalogue

Parsed CSV table.

Value

NULL, invisibly; invalid catalogues raise an error.


Check restricted YAML syntax

Description

Check restricted YAML syntax

Usage

yaml_profile(text, resource)

Arguments

text

YAML source text.

resource

Source label for errors.

Details

Rejects tags, anchors, aliases, merges, directives and document markers outside quoted strings, comments and block scalars. Parsing happens separately.

Value

Returns silently on success; raises model_form_error otherwise.