KScript docs
EN

Types and validation

Refinement types

A type built on one built-in type, or on another refinement type, adds rules to it. It has no fields: its values are the base type's values that pass the rules.

<type name="Age" with="int" min="0" max="150" />

<type name="Slug" with="string" pattern="/^[a-z0-9]+(-[a-z0-9]+)*$/">
  <normalize value="$value->trim()->lower()" />
</type>

<type name="Username" with="handle" max="16" not="[@admin, @root]" />

<let name="age" type="Age" value="42" />
<let name="slug" type="Slug" value="' Hello-World '" />
<echo>{ $age } { $slug }</echo>
<try>
  <let name="too_old" type="Age" value="200" />
  <catch as="err">
    <echo value="$err.message" />
  </catch>
</try>
type Age with [int] { min: 0; max: 150 }

type Slug with [string] {
  pattern: /^[a-z0-9]+(-[a-z0-9]+)*$/
  normalize: $value->trim()->lower()
}

type Username with [handle] {
  max: 16
  not: [@admin, @root]
}

$age: Age = 42
$slug: Slug = ' Hello-World '
echo "{ $age } { $slug }"
try {
  $too_old: Age = 200
} catch err {
  echo $err.message
}

Write each rule on its own line, or separate rules on one line with a semicolon. A comma after a rule value, such as min: 8,, is a syntax error. A validate rule accepts a comma between its test and its message.

Rule What it checks
min, max A number's value, or the length of text or a list.
pattern Text must match. It is a regex literal such as /^[a-z]+$/i, or quoted text.
one_of The value must be one of these.
not The value must not be one of these.
validate: test, 'message' Any expression, with the value as $value. Several can be given; each one that fails adds its message.
normalize: expression Evaluates an expression with the base value in $value. If the expression supplies a function, KScript passes the base value to that function. The rules check the returned value.

A value is converted to the base type first, then normalized, then checked against the rules. One that fails reports every rule it broke. Rules on a field work the same way: title: string(min: 1).

Calling a type makes a value of it, checked the same way: Age(42), Slug(' Hello-World '). Every declared type works like this (Repo($data), Size('small')), and its name is always written bare, without $.

Checked conversions with as

Use expression as Type when you need a typed value inside an expression. KScript evaluates the expression once, then applies the same conversion, normalization and validation as a typed assignment. A failed check raises an error at the cast.

<type name="PasskeySessionKey" with="string" min="8" pattern="/^passkey_[a-zA-Z]+$/">
  <normalize value="fn(c) => $c->trim()" />
  <fn name="length">
    <return value="$value->count()" />
  </fn>
</type>

<fn name="key_length" params="key: PasskeySessionKey" value="$key->count()" />

<let name="kind" value="'login'" />
<let name="session_key" value="&quot;passkey_{$kind}&quot; as PasskeySessionKey" />
<echo value="$session_key" /> <!-- passkey_login -->
<echo value="$session_key->count()" /> <!-- 13 -->
<echo value="$session_key->length()" /> <!-- 13 -->
<echo value="@key_length($session_key)" /> <!-- 13 -->
type PasskeySessionKey with [string] {
  min: 8
  normalize: fn(c) => $c->trim()
  pattern: /^passkey_[a-zA-Z]+$/
  fn length() {
    return $value->count()
  }
}

fn key_length(key: PasskeySessionKey) => $key->count()

$kind = 'login'
$session_key = "passkey_{$kind}" as PasskeySessionKey
echo $session_key  // passkey_login
echo $session_key->count()  // 13
echo $session_key->length()  // 13
echo @key_length($session_key)  // 13

The opening slash comes before the ^ anchor in a regex literal. Here the normalizer receives the string before the pattern runs. You can also write normalize: $value->trim() directly.

A helper can live on the type itself. The normalizer can call it with @trim_key($value) or pass the function as normalize: @trim_key. Both forms use the input string. KScript finds helpers declared later in the block, inherited methods, and functions declared in the surrounding module. A method on the type takes precedence over a module function of the same name.

<type name="KeyText" with="string">
  <normalize value="@trim_key($value)" />
  <fn name="trim_key" params="key: string" value="$key->trim()" />
</type>
<echo value="KeyText('  passkey_Login  ')" /> <!-- passkey_Login -->
type KeyText with [string] {
  normalize: @trim_key($value)
  fn trim_key(key: string) => $key->trim()
}
echo KeyText('  passkey_Login  ')  // passkey_Login

A PasskeySessionKey supports the methods of string and its own methods. Inside a refinement method, $value is the underlying value and $this is the refined receiver, so $this->length() can call another method on the type. A refinement inherits methods from its base and can replace one by declaring the same name. Use $value to call the underlying built-in method. You can also pass the key to a typed function such as key_length. In a record method, $this.field reads a field of the record.

The target can also be a built-in type ($text as int), a type with local rules ($name as string(min: 2)), or a list ($rows as Repo[]). An optional target such as PasskeySessionKey? accepts null and validates every non-null value. Parenthesize an arithmetic expression to convert its result, as in ($a + $b) as int.

Converting one number with as int, a typed variable ($n: int = 3.9) or an int parameter drops the fraction and gives 3. Data checked against a type is stricter: an int field, an int[] item or a refinement of int reports a number that isn't whole (needs a whole number, but got a number (12.9)) instead of cutting it down. Text such as 'NaN' or 'Infinity' is not a number, and a plain number such as '1.5' is not a date.

Your own native types

kscript make native writes a refinement type to natives/ that works like a built-in one. Every script in the project can use it without an import, the same way the extensions/ folder works. Values of it are written without quotes where the type reads text, they are checked wherever the type is used (assignments, arguments, a call of the type and request bodies), and the editor checks the values written in code:

CommandWhat it does
kscript make native Sku --pattern '/^[A-Z]{3}-\d{4}$/' --normalize '$value->trim()->upper()'Text in a pattern, tidied first.
kscript make native Percent --base int --min 0 --max 100A whole number from 0 to 100.
kscript make native Username --base handle --max 16 --not @admin,@rootA handle, with names that aren't allowed.
kscript make native CompanySite --base url --validate '$value.host->ends_with("example.com"), "Use a company site"'A URL with a rule of its own.

The first one writes natives/sku.kscript:

<type name="Sku" with="string" description="Sku: a native type built on string. A value that breaks a rule fails where it is made, and the editor checks the values written in code." pattern="/^[A-Z]{3}-\d{4}$/">
  <normalize value="$value->trim()->upper()" />
  <!-- Rules: normalize, pattern, min, max, one_of, not and validate. Add methods with fn. -->
</type>
/// Sku: a native type built on string. A value that breaks a rule fails where it is made, and the editor checks the values written in code.
type Sku with [string] {
  normalize: $value->trim()->upper()
  pattern: /^[A-Z]{3}-\d{4}$/
  // Rules: normalize, pattern, min, max, one_of, not and validate. Add methods with fn.
}

Then, in any script in the project:

<let name="sku" type="Sku" value="abc-1234" /> <!-- ABC-1234 -->
<fn name="price" params="of: Sku" value="10" />
$sku: Sku = abc-1234   // ABC-1234
fn price(of: Sku) => 10

--base selects the base type, which defaults to string. It accepts native types such as url, domain and country, or another refinement. The rules are --pattern, --min, --max, --one-of a,b, --not a,b, --normalize and --validate "test, 'message'". Declare methods with fn in the type body and call them with ->.

The block holds only the rules and the fn methods, never statements. Code such as echo or if goes inside a method, and the editor reports it as an error anywhere else in the block, saying what the block holds:

<type name="Percent" with="int" min="0" max="100">
  <!-- A method: code goes in here. echo or if on its own line in the block is an error. -->
  <fn name="is_full" value="$value == 100" />
</type>
type Percent with [int] {
  min: 0
  max: 100

  // A method: code goes in here. echo or if on its own line in the block is an error.
  fn is_full() => $value == 100
}

The same goes for every declaration's block: a record type holds its fields, rules, construct and methods; a model its fields, validate: rules and methods; a job its fields and its handle, failed and middleware functions; an error its fields; an extend block its methods; and an enum its values. Completion in a block suggests only what it can hold. In an XML project, the file is a <type> element in natives/sku.ks.xml.

The types and enums in every file under natives/ (subfolders too) are the project's own native types. "natives" in kscript.json names other folders or globs, and kscript make native writes to the first folder it lists:

JSON
{ "natives": ["src/types", "shared/**/*.kscript"] }

A type a script declares itself wins over a project type of the same name.

Native types from packages

A package adds a native type with p.NativeType(new IsbnType()), where IsbnType is a subclass of NativeType (KScript.Core). The base class makes a type say everything the language does with its values, so none can be left out: its name, description and example, how text becomes a value (Parse), how it is written without quotes, what == means (Equality), whether < and sorting work (Ordering), whether a for loop can walk it (Iteration), its operators (DeclareOperators), its fields and methods (DeclareMembers), the filters and methods of a list of it (DeclareListMembers), the string methods it keeps and the values the editor offers. "None" is a fine answer to any of them, written as an empty body or Ordering.None. DurationType is the one to copy. Once the package is imported, the type works like a built-in one: values without quotes, checks in the editor, ->type() and OpenAPI schemas. Native type names are lowercase, and a name that is taken can't be reused.