Project

jscontact

0.0
The project is in a healthy, maintained state
JSContact 1.0 and 2.0 models, validation, localization patches, and optional vCard 4.0 conversion.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Runtime

>= 2.19.4, < 4
>= 2.0, < 3
 Project Readme

JSContact

JSON contact cards with validation and vCard conversion.

Gem version CI Ruby 3.3 or later MIT License

Website · Installation · Quick start · Supported scope · Development · License

Parse, validate, build, and convert JSContact contact cards in Ruby. Supports RFC 9553, RFC 9555, and RFC 9982.

Installation

Requires Ruby 3.3 or later. Supports CRuby, JRuby, and TruffleRuby.

Add the gem to your Gemfile:

gem "jscontact"
# Add only when using the optional vCard converter:
gem "jcard_jcal", "~> 0.1.0"

Then run bundle install.

The JSON API depends on json and tzinfo. On systems without a zoneinfo database (such as Windows), also install tzinfo-data for time zone and country validation.

Quick start

require "jscontact"

card = JSContact::Card.build do |contact|
  contact.name = { full: "Mina Sample" }
  contact.add_email(address: "mina@example.test", contexts: { work: true })
  contact["example.test:customer"] = { "number" => 42 }
end

card.name.full                    # => "Mina Sample"
card.emails["e1"].address         # => "mina@example.test"
card.emails["e1"].label = "Desk" # updates the parent card
card.to_h                        # independent, deep copy
json = card.to_json              # validates before serializing
copy = JSContact.parse(json)

JSContact and Jscontact refer to the same module. The schema defines typed classes such as Name, Address, and EmailAddress; nested accessors return typed views. [] and []= also accept unknown property names. Camel-case property accessors have snake-case aliases, for example preferred_languages.

Card.new(hash) copies the input and permits incomplete data while building a card. Use strict: true to validate immediately. Constructors accept symbol keys and normalize them to strings; duplicate normalized keys are rejected.

to_h preserves absent default properties; accessors expose their defaults. Card.build(explicit_types: true) includes optional nested @type members when exporting. Nested objects serialized on their own include their required @type. Instances are mutable; give each concurrent worker its own card.

Validation and versions

card = JSContact.parse(json, strict: false)
card.valid?
card.warnings.each { |violation| puts "#{violation.pointer}: #{violation.message}" }
card.validate! # raises JSContact::ValidationError if invalid

upgraded = JSContact.upgrade(card) # validates, copies, and sets version to "2.0"

parse is strict by default. Lenient parsing retains schema violations in errors (also available as warnings); malformed JSON, duplicate keys, unsupported Ruby values, and resource-limit violations still raise. Serialization is always strict. ValidationError#errors contains every collected Violation, with a JSON Pointer and message; the empty pointer identifies the document root.

New cards use version 2.0; parsed 1.0 cards retain their version until upgraded. Version 1.0 requires uid; version 2.0 permits it to be absent. Upgrading changes only the version, without inventing a UID or renumbering map identifiers. Unknown properties with valid names are preserved. Unknown enum values are reported as violations unless they use the vendor extension syntax.

Patches and localizations

card.localizations = { "ja" => { "name/full" => "サンプル ミナ" } }
japanese = card.localized("ja")

patched = JSContact::PatchObject.new({ "name/full" => "Mina Updated" }).apply(card.to_h)

Patch keys are JSON Pointers without the leading slash. nil deletes an object member; array entries can be replaced but cannot be inserted or removed. Escapes, parent paths, overlapping paths, resulting types, and required properties are checked before returning a result. Neither the patch nor its target is modified. Schema validation applies when the target has a recognized @type; untyped objects receive JSON structure validation.

localized matches language tags without case sensitivity, applies the selected patch to a copy, removes its localization map, and sets its language. If no patch matches, it returns an unchanged copy. Patches cannot modify localizations itself.

vCard conversion

require "jscontact/vcard"

text = JSContact::VCard.from_jscontact(card)
restored = JSContact::VCard.to_jscontact(text) # JSContact 2.0

Only the optional entrypoint loads jcard_jcal. Conversion accepts exactly one vCard 4.0. A missing UID stays absent when converting to JSContact 2.0. Requesting version: "1.0" emits a deprecation warning and supplies a stable UID if necessary.

Conversion follows RFC 9555 in both directions, including phonetic values, PROP-ID, ALTID, LANGUAGE, and JSCOMPS. Unmatched properties and parameters use vCardProps, vCardParams, and vCardName; JSContact values without a native vCard form use JSPROP/JSPTR.

Conversion preserves data, rather than the original text's property order, folding, or choice of equivalent representation. Date forms without a JSContact equivalent and unmatched birth/death place properties are retained in vCardProps. Timestamp conversion preserves leap seconds. Timestamps without a UTC offset remain in vCardProps or vCardParams, since no UTC instant can be inferred.

JSContact date fields use the Gregorian calendar even when calendarScale names another calendar. The converter preserves non-Gregorian vCard CALSCALE properties in vCardProps; it does not perform calendar arithmetic. In the other direction, it emits a Gregorian native date and retains non-Gregorian metadata through JSPROP. The underlying vCard parser checks Gregorian date validity, so dates from an unsupported calendar that fail those checks raise ConversionError.

A top-level unknown property whose value is JSON null cannot be represented by JSPROP: its PatchObject semantics mean deletion. Conversion raises ConversionError with the property pointer instead of dropping it. Nested nulls inside a retained object or array are supported. Ordinary JSON round trips retain all null values.

Supported scope

Feature Status
RFC 9553 object models, validation, JSON generation Supported
RFC 9982 JSContact 2.0 and optional UID Supported; 1.0 is retained when read
PatchObject and localizations Supported
RFC 9555 and RFC 9554 vCard 4.0 conversion Supported as described above
Unknown properties and vendor JSON Preserved, subject to valid names and I-JSON constraints
JMAP for Contacts Card data supported; protocol operations are outside scope
vCard 2.1/3.0, CardDAV sync, RDAP profiles, locale-specific display formatting Outside scope

Resource limits

These options apply to parse and model constructors. Exceeding a limit raises LimitError, including in lenient mode.

Option Default Applies to
max_input_size 16 MiB JSON input bytes in parse
max_depth 32 Nested JSON objects and arrays, including vendor values
max_map_size 10,000 Schema-defined maps and arrays
max_data_uri_size 1 MiB Estimated decoded data URI size
max_patches 1,000 Total localization patches, or entries in a PatchObject
JSContact.parse(json, max_input_size: 1_048_576, max_depth: 16, max_map_size: 500)

The gem never fetches resource URIs or resolves linked contacts. vCard text parsing also uses jcard_jcal's own parser limits.

Development

bundle install
bundle exec rake
COVERAGE=1 bundle exec rake
bundle exec rbs -I sig validate
bundle exec ruby script/check_syntax.rb
bundle exec ruby script/check_licenses.rb
bundle exec ruby script/benchmark.rb
bundle exec ruby script/update_registry.rb
bundle exec ruby script/update_registry.rb --refresh

The first test run downloads RFC fixtures into tmp/; later runs reuse the cache. See conformance notes for fixture and registry maintenance, and boundary measurements for the default resource limits.

Contributing

Bug reports and pull requests are welcome on GitHub. See Development for the checks to run before submitting a change. Report security vulnerabilities privately as described in SECURITY.md.

License

Released under the MIT License.