zense/strata

Typed, versioned schemas for Roblox player data: one declaration gives you the Luau type, defaults, DataStore-safe validation and migrations.

Strata

Typed, versioned schemas for Roblox player data.

Declare the shape of your data once. From that one declaration you get:

  • the Luau type: typeof(PlayerData.Type), with no separate type to keep in sync
  • defaults for new players and for fields you add later
  • validation that knows DataStores: it reports the path to the bad field (pets[2].level: must be at least 1, got 0) and refuses NaN, invalid UTF-8, mixed tables and cycles
  • versioned migrations that run in order, never change the original data, and refuse data saved by a newer server

Strata is plain Luau with no dependencies, and it never touches DataStores. Use it with ProfileStore, your own DataStore code, or anything else that hands you a table.

local Strata = require(ReplicatedStorage.Packages.Strata)

local PlayerData = Strata.versioned({
	version = 2,
	schema = Strata.struct({
		coins = Strata.integer({ min = 0 }),
		pets = Strata.array(Strata.struct({
			name = Strata.string({ maxLength = 20, default = "Pet" }),
			level = Strata.integer({ min = 1, max = 100, default = 1 }),
		}), { maxItems = 100 }),
		settings = Strata.struct({
			music = Strata.fallback(Strata.boolean({ default = true })),
		}),
	}),
	migrations = {
		[1] = function(data) -- version 1 stored coins as "Cash"
			data.coins = data.Cash
			data.Cash = nil
			return data
		end,
	},
})
export type PlayerData = typeof(PlayerData.Type)
-- { coins: number, pets: { { name: string, level: number } }, settings: { music: boolean } }

local data, err = PlayerData:load(profile.Data)
if data == nil then
	warn(err.code, err.message) -- e.g. "NewerVersion", "InvalidData"
end

Install

Wally

[dependencies]
Strata = "layfate/[email protected]"

pesde

pesde add zense/strata

Manually: download Strata.rbxm from the latest release and put it in ReplicatedStorage.

Requirements

  • Luau's new type solver, for the inferred types. Strata uses type functions, which the old solver doesn't support. At runtime it works either way.
  • Strata's modules use string requires (require("./Util")), which Roblox supports.

Schemas

Every builder returns a schema with:

MethodWhat it does
schema:check(value)true, or false and an error naming the path to the bad value
schema:assert(value)Returns value, or errors with the same message
schema:default()A fresh default value (a new table every call)
schema:reconcile(value)Fills in missing fields with their defaults, in place. Wrong values are left for check to report
schema.TypeType-only: typeof(schema.Type) is the value's type
BuilderTypeDefaultOptions
Strata.number(opts?)number0, or the nearest boundmin, max, default, validate
Strata.integer(opts?)number0, or the nearest boundmin, max, default, validate
Strata.string(opts?)string""minLength, maxLength (characters), pattern, default, validate
Strata.boolean(opts?)booleanfalsedefault
Strata.literal(value)the value's typevalue
Strata.enum(values, opts?)the values' typethe first valuedefault
Strata.optional(schema)T?nil
Strata.array(schema, opts?){ T }{}minItems, maxItems, default, validate
Strata.map(key, value, opts?){ [K]: V }{}maxEntries, default, validate
Strata.struct(fields, opts?)inferred from the fieldseach field's defaultextra, validate
Strata.fallback(schema)Tthe schema's
Strata.any()anynil
  • Defaults are checked when the schema is defined. Strata.integer({ min = 1, default = 0 }) errors right away, not when the first player joins.
  • validate runs after the built-in checks: function(value) return value % 2 == 0, "must be even" end.
  • struct extra controls fields the schema doesn't declare: "keep" (the default) allows them if they can be stored, "strip" removes them in reconcile, and "reject" fails the check.
  • fallback makes reconcile replace an invalid value with the default instead of failing the load. Use it for data you'd rather reset than lose a player over, such as settings.
  • map keys must be strings (a string, a string literal or a string enum), because DataStores only keep string keys.
  • any accepts any value a DataStore can store. Nothing about its shape is checked.

What "storable" means

DataStores save JSON. Strata refuses, with the path, anything that wouldn't survive the trip:

  • NaN and ±infinity
  • strings that aren't valid UTF-8
  • integers beyond 2^53, which lose precision
  • tables that mix array and dictionary keys, arrays with gaps, and non-string dictionary keys
  • cycles, functions and Roblox types such as Vector3 (store them as numbers)

Versioned data

local PlayerData = Strata.versioned({
	schema = Strata.struct({ ... }), -- the current shape; must be a struct
	version = 3,                     -- the current version
	migrations = {                   -- migrations[n] upgrades version n to n + 1
		[1] = function(data) ... end,
		[2] = function(data) ... end,
	},
	firstVersion = 1,     -- optional: the oldest version still accepted
	unversionedAs = nil,  -- optional: treat data with no version as this version
	versionKey = "_version", -- optional: where the version is stored
})

PlayerData:load(raw) returns data or nil, LoadError. It never changes raw: it works on a copy.

  1. nil or {} is a new player and gets PlayerData:new().
  2. It reads the version. Data from a newer version than this server knows is refused (NewerVersion), so an old server can't overwrite it during a rolling update.
  3. It runs each migration in order. A migration may change data in place or return a new table.
  4. It reconciles, filling in missing fields with their defaults.
  5. It checks the result against the schema.
  6. It stamps the current version and returns the data.
err.codeMeaning
NotATableThe saved value isn't a table
MissingVersionThe data has no version and unversionedAs isn't set
BadVersionThe version isn't an integer, or is older than firstVersion
NewerVersionThe data was saved by a newer version. Don't save over it
MigrationFailedA migration errored or returned something other than a table. The message includes the traceback
InvalidDataAfter migrating, the data doesn't fit the schema. The message names the field

The migration chain is checked when the server starts: a missing migrations[2] is an error at definition time, not when an old player finally rejoins.

PlayerData:check(data) verifies data before you save it: the current version and a valid shape.

Adding Strata to a game that already has saves? Set unversionedAs = 0 and write migrations[0] to turn the old format into version 1.

With ProfileStore

Give ProfileStore an empty template, so Strata owns the defaults:

local store = ProfileStore.New("PlayerData", {})

local profile = store:StartSessionAsync(tostring(player.UserId), { Cancel = ... })
local data, err = PlayerData:load(profile.Data)
if data == nil then
	-- profile.Data is untouched, so ending the session saves it exactly as it was.
	profile:EndSession()
	player:Kick("Your data couldn't be loaded. Please rejoin.")
	return
end
profile.Data = data

There's a complete script in examples/ProfileStore.server.luau.

Development

Install the toolchain with Rokit by running rokit install, then:

lune run tests/run                         # tests (or: luau tests/run.luau)
stylua --check src tests examples          # format
selene src tests examples                  # lint
scripts/check-types.sh globalTypes.d.luau  # types, including the tests that must fail
rojo serve dev.project.json                # the example in Studio

check-types.sh needs the Roblox type definitions from luau-lsp. CI runs all of these on every push and pull request.

Releasing: bump the version in src/init.luau, wally.toml and pesde.toml, add a CHANGELOG.md section, and push a vX.Y.Z tag. The release workflow builds Strata.rbxm, creates the GitHub release and publishes to Wally and pesde when the WALLY_TOKEN and PESDE_TOKEN secrets are set.

License

MIT