Millwork
    Preparing search index...

    Module @millwork-ts/core

    @millwork-ts/core

    Codecs, shapes and values: turn wire data into real objects and back. Core has no framework and no peer dependency.

    Docs: joegaudet.com/millwork · Guide · API

    pnpm add @millwork-ts/core
    

    For WarpDrive and ember-data, also add @millwork-ts/warp-drive.

    • A codec turns one raw wire value into a value and back.
    • A value is immutable. To change it, set a new one. Two values are equal when the codec equals says so.
    • A shape is a nested object that you edit in place. It tracks its changes by path.

    A codec has name, hydrate, serialize, equals and isValue.

    • hydrate is forgiving. Bad wire data gives undefined and a report to onInvalid. It never throws.
    • serialize is strict. A value of the wrong type throws a TypeError.
    • null and a missing value give undefined. nullable(codec) keeps null.
    import { money, onInvalid } from '@millwork-ts/core'

    const total = money.hydrate({ amount: '19.99', currency: 'USD' }, { wire: 'decimal' })
    total?.toDecimalString() // "19.99"
    money.serialize(total, { wire: 'minor' }) // { amount: 1999, currency: 'USD' }

    onInvalid(({ codec, raw, error }) => console.error(codec, raw, error))

    The core codecs are money, decimal, bigint, number-string, percent, ratio, boolean-ish, url, email, uuid, ulid, snowflake, country, currency-code, language, locale, time-zone, latlng, geojson, bytes, byte-size, bitflags, mime-type and i18n-text. The codecs record has all of them by name. arrayOf, nullable, setOf, mapOf and rangeOf make a codec from another codec.

    Core has no date type. Use one of the date packages: @millwork-ts/temporal, @millwork-ts/luxon, @millwork-ts/date-fns or @millwork-ts/dayjs.

    The wire forms and options of each codec are in the guide.

    The url codec accepts only http:, https:, mailto: and tel: URLs by default. A javascript: or data: URL is bad input, so it is not safe to put a hydrated URL in a link without this check. Set the protocols option to change the list, or to '*' to accept all protocols. With the base option, the codec resolves a relative URL first, and then checks its protocol.

    url.hydrate('javascript:alert(1)') // undefined, and a report to onInvalid
    url.hydrate('ftp://example.com/a', { protocols: ['ftp:'] }) // a FrozenURL
    url.hydrate('/a', { base: 'https://example.com' }) // https://example.com/a

    Use defineCodec. Do not write the Codec object by hand: defineCodec gives the rules for null, errors and freezing.

    import { defineCodec, registerCodecs } from '@millwork-ts/core'

    export const upper = defineCodec<string, string>({
    name: 'upper',
    parse(raw) {
    if (typeof raw !== 'string') throw new TypeError('not a string')
    return raw.toUpperCase()
    },
    format: value => value.toLowerCase(),
    isValue: (input): input is string => typeof input === 'string',
    })

    registerCodecs({ upper }) // now a field can name it: 'upper'
    import { Shape, Value, field, type Money, type ShapeArray } from '@millwork-ts/core'

    export class Address extends Shape {
    static override type = 'address'

    @field accessor city!: string
    @field accessor zip!: string
    }

    export class LineItem extends Shape {
    static override type = 'line-item'

    @field accessor sku!: string
    @field accessor qty!: number
    }

    export class Price extends Value {
    static override type = 'price'

    @field('money', { wire: 'decimal' }) accessor amount!: Money
    @field accessor label!: string
    }
    • Each class has a unique static type. Minifiers rename classes, so the name does not come from the class. A second class with the same type throws.
    • Ember compiles legacy decorators. There, write @field declare city: string.
    • shape({ type, fields }) and value({ type, fields }) make a class from JSON, with the same power.
    • @field(LineItem, { array: true, key: 'sku' }) gives a ShapeArray. Change it with add, remove and move.
    • @field({ card: Card, bank: Bank }) is polymorphic. The $type key of the raw value picks the class. The discriminator option changes the key.

    A shape and a shape array have the Tracked API:

    address.city = 'Montreal'
    address.isDirty // true
    address.changes() // [{ kind: 'set', path: ['city'], from: 'Toronto', to: 'Montreal' }]
    address.rollback(['city'])

    A value is immutable. A write throws a TypeError. price.with({ label: 'Sale' }) gives a copy. Price.codec is the codec of the class.

    toStandardSchema gives a Standard Schema for a codec, or for a shape or value class. It reads the raw wire form. No validation runs when a field is read.

    import { money, toStandardSchema } from '@millwork-ts/core'

    const total = toStandardSchema(money, { wire: 'decimal' })
    total['~standard'].validate({ amount: 'x', currency: 'USD' })
    // { issues: [{ message: '[millwork] money: not a decimal: "x"' }] }

    const address = toStandardSchema(Address)
    address['~standard'].validate({ city: 'Toronto' })
    // { issues: [{ message: '[millwork] zip: required', path: ['zip'] }] }

    MIT

    Decimal
    FrozenURL
    I18nText
    Money
    Percent
    RawWrite
    Shape
    ShapeArray
    Slot
    Value
    Binding
    BitflagsOptions
    BooleanIshOptions
    BytesOptions
    Change
    Codec
    CodecSpec
    DateCodecFamily
    DateRecord
    DateTypes
    DecimalOptions
    DurationRecord
    EpochRecord
    Feature
    FeatureCollection
    FieldDecorator
    FieldDefinition
    FieldInput
    FieldOptions
    IntervalOptions
    IntervalParts
    IntervalWire
    InvalidReport
    Issue
    LatLng
    LatLngOptions
    MapOptions
    MimeType
    MoneyOptions
    NamedClass
    OffsetDateTimeRecord
    PercentOptions
    Range
    RangeOptions
    Ratio
    RatioOptions
    RegisterShapesOptions
    ShapeDefinition
    StructuredClass
    StructureInput
    TimeRecord
    Tracked
    UrlOptions
    YearMonthRecord
    ZonedDateTimeRecord
    ZonedOptions
    AnyCodec
    Bounds
    DurationFields
    EpochUnit
    FieldRef
    GeoJson
    Geometry
    InvalidHandler
    LatLngRaw
    LocalDateTimeRecord
    MapRaw
    MoneyRaw
    MoneyWire
    OptionsOf
    PercentUnit
    PolymorphicMap
    Position
    RangeRaw
    RawObject
    RawOf
    ShapeRef
    Structured
    ValueOf
    bigint
    bitflags
    booleanIsh
    bytes
    byteSize
    codecFactories
    codecs
    country
    currencyCode
    decimal
    DEFAULT_URL_PROTOCOLS
    DISCORD_EPOCH
    email
    geojson
    i18nText
    language
    latlng
    locale
    mimeType
    money
    numberString
    percent
    ratio
    snowflake
    timeZone
    TWITTER_EPOCH
    ulid
    url
    uuid
    arrayOf
    codecNamed
    currencyExponent
    defineCodec
    definitionOf
    durationMilliseconds
    field
    formatDuration
    formatEpoch
    formatOffset
    fraction
    mapOf
    nullable
    onInvalid
    parseEpoch
    parseIsoDate
    parseIsoDuration
    parseIsoTime
    parseLocalDateTime
    parseRfc3339
    parseRfc9557
    parseWith
    parseYearMonth
    rangeOf
    rawOf
    readDuration
    readInterval
    registerCodecs
    registeredCodecs
    registerShapes
    reportInvalid
    sameDuration
    setOf
    shape
    shapeNamed
    shapeSchema
    snowflakeTime
    splitIsoInterval
    toStandardSchema
    ulidTime
    value
    valueCodec
    writeDuration