KScript docs
EN

KScript.Core

The language itself: variables, branches, loops, functions, errors, imports and echo. Always imported.

KScript.Core is the language itself. Every script and page has it, so there is nothing to import.

ElementsStatements

#<break>break

Leaves the innermost loop.
Exits the enclosing loop. Write break.

Self-closing.A statement on its own.

Example
<for each="n" in="1..100">
  <if $n gt 3>
    <break />
  </if>
  <echo>$n</echo>
</for>
for n in 1..100 {
  if $n > 3 {
    break
  }
  echo $n
}

#<call>call

Calls a function for its effect, optionally keeping the result.

Self-closing.A statement on its own.

AttributeOptionValueDescription
fn requireda function: @nameThe function (or command) to call: @greet (in XML, fn="greet").
argsexpressions, comma separatedArguments, comma separated.
intoa new variable's nameA variable for the result.
Example
<fn name="greet" params="who: string"><echo>Hello, $who!</echo></fn>
<call fn="greet" args="'World'" />
fn greet(who: string) {
  echo "Hello, { $who }!"
}
@greet('World')

#<case>value => …

A branch of <match>: runs when the value equals one of is, or when when is true (with both, the value must match and when must be true). In a .kscript file a branch is an arm: 1, 2 => ..., _ when $n > 9 => ....A branch of match: runs when the value equals one of is, or when when is true (with both, the value must match and when must be true). In a .kscript file a branch is an arm: 1, 2 => ..., _ when $n > 9 => ....
Use a match arm such as 0 => 'zero', or _ => 'other' for the fallback.

Holds statements.Holds statements in { }. Goes inside <match>match.

AttributeValueDescription
isexpressions, comma separatedValues to compare with, comma separated.
whenexpressionA condition.
Example
<let name="n" value="12" />
<match $n>
  <case is="1, 2"><echo>a couple</echo></case>
  <case when="$n gt 9"><echo>lots</echo></case>
  <default><echo>a few</echo></default>
</match>
$n = 12
match $n {
  1, 2 => echo 'a couple'
  _ when $n > 9 => echo 'lots'
  _ => echo 'a few'
}

#<catch>catch err

Handles matching errors in a try block, a function call, or calls to methods of a type or model. The nearest matching handler runs first. The bound error exposes its type, message, location, status, cause and custom fields. A bare throw passes it to the next enclosing handler.
Recovers from errors. Use @load() catch Validation => $err.message for a fallback value or append catch Validation { return $err.message } to a declaration. Omit the type to catch any error.

Holds statements.Holds statements in { }. Goes inside <try>try or <fn>fn or <type>type or <model>model.

AttributeValueDescription
asa new variable's nameA variable for the error. Defaults to err.
whenexpressionOnly handle errors for which this is true, such as $err.status == 404.
typean error typeOnly handle errors of these types, or types that extend them: NotFound, [IO, Network]. Error catches everything.
Example
<try>
  <throw type="NotFound" message="No such order" />
  <catch type="NotFound" as="e">
    <echo>{ $e.type } ({ $e.status }): { $e.message }</echo>
  </catch>
</try>
try {
  throw NotFound "No such order"
} catch NotFound as e {
  echo "{ $e.type } ({ $e.status }): { $e.message }"
}

#<collection>collection

Builds a list or map from nested <item> elements, for data that reads better as markup than as a literal.Builds a list or map from nested item elements, for data that reads better as markup than as a literal.

Holds statements.Holds statements in { }. Holds only <item>item.

AttributeOptionValueDescription
name requireda new variable's nameThe variable to declare.
consttrue or falsetrue makes a later <set> an error.true makes a later $name += value an error.
Example
<collection name="person">
  <item key="name">Joan</item>
  <item key="age">82</item>
</collection>
collection(name: person) {
  item(key: 'name') "Joan"
  item(key: 'age') "82"
}

#<config>config

Reads the script's settings with other options: an environment, other files, a prefix for environment variables, defaults and required settings. Without into, it changes $config.

Self-closing.A statement on its own. Scripts only.

AttributeOptionValueDescription
enva string with { }The environment, such as staging or production. Its files (kscript.staging.json, .env.staging) are layered over the base files. Default: kscript --env, or KSCRIPT_ENV.
filesa string with { }Other files to read, as a list: ['settings.json', 'secrets.kscript?', '.env?'] (in XML, settings.json, secrets.kscript?, .env?). JSON files hold settings, a .kscript file defines configure(environment), and .env files feed @env(). A name without an extension means its .json file. End a name with ? if it may be missing.
prefixa stringEnvironment variables with this prefix override the files: with prefix="APP_", APP_DATABASE__HOST sets database.host.
roota file pathThe folder the files are in. Default: the script's folder.
defaultsexpressionA map of settings used when no file sets them.
requirea list of names: [a, b]Settings that must be set, as a list: ['database.host', 'api.key'] (in XML, database.host, api.key).
usertrue or falsetrue also reads the person's own settings: config.json in the app's config folder (see KScript.Storage), layered over the other files.
export_envtrue or falseno stops values in .env files becoming environment variables (they always do for @env() unless this is no).
intoa new variable's nameStore the settings in this variable instead of changing $config.
Example
<config env="staging" prefix="APP_" require="database.host" defaults="{ server: { port: 8080 }, database: { host: 'localhost' } }" />
<echo>{$config.database.host}:{$config.server.port}</echo>
config(env: 'staging', prefix: 'APP_', require: 'database.host', defaults: { server: { port: 8080 }, database: { host: 'localhost' } })
echo "{$config.database.host}:{$config.server.port}"

#<const>const $name = value

Declares a value that can't change: the same as <let const="true">. Top-level consts are exported to scripts that import this one.
Defines a constant. Write const limit = 10.

Its text is one expression.

AttributeValueDescription
name requireda new variable's nameThe constant to declare.
valueexpressionIts value. Can be written as the element's text instead.
typestring | int | float | number | bool | list | set | map | fn | date | markdown | latex | formatted_file | document | email | password | handle | uuid | regex | url | domain | ip | cidr | mac | port | slug | slash_path | file_path | semver | mime | hex | base64 | jwt | json | csv | phone | country | currency | locale | timezone | duration | date_format | cron | color | iban | card | money | anyConvert the value to this type, or fail early: a built-in such as int, an <enum>, a <type>, T[] for a list, T? to allow null.Convert the value to this type, or fail early: a built-in such as int, an enum, a type, T[] for a list, T? to allow null.
descriptiona stringWhat the constant is for, shown on hover.
Example
<const name="max_size" value="10 * 1024" />
const $max_size = 10 * 1024

#<construct>construct

A type's constructor. Its fields are what a caller may pass, as Point(x: 1) or as a component's attributes, and every other field of the type is the value's own state. The statements run once when a value is made, with the fields as variables they can set. In a .kscript file: construct({ x: number, y: number = 0 }) { ... }.

Holds statements.Holds statements in { }. Goes inside <type>type.

AttributeOptionValueDescription
descriptiona stringWhat the constructor does, shown on hover.
Example
<type name="Point">
  <construct>
    <field name="x" type="number" />
    <field name="y" type="number" default="0" />
    <set name="sum" value="$x + $y" />
  </construct>
  <field name="sum" type="number" />
</type>
<echo>{ Point(x: 3, y: 4).sum }</echo>
type Point {
  construct({ x: number, y: number = 0 }) {
    .sum = .x + .y
  }
  sum: number
}
echo Point(x: 3, y: 4).sum

#<continue>continue

Skips to the next turn of the innermost loop.
Starts the next iteration of the enclosing loop. Write continue.

Self-closing.A statement on its own.

Example
<for each="n" in="1..6">
  <if $n % 2 eq 0>
    <continue />
  </if>
  <echo>$n</echo>
</for>
for n in 1..6 {
  if $n % 2 == 0 {
    continue
  }
  echo $n
}

#<default>_ => …

The branch of <match> that runs when no case matched. In a .kscript file it is the arm _ => ....The branch of match that runs when no case matched. In a .kscript file it is the arm _ => ....
Use a match arm such as 0 => 'zero', or _ => 'other' for the fallback.

Holds statements.Holds statements in { }. Goes inside <match>match.

Example
<let name="day" value="'Tuesday'" />
<match $day>
  <case is="'Saturday', 'Sunday'"><echo>Weekend</echo></case>
  <default><echo>Weekday</echo></default>
</match>
$day = 'Tuesday'
match $day {
  'Saturday', 'Sunday' => echo 'Weekend'
  _ => echo 'Weekday'
}

#<do>$name = value; …

Runs assignment statements and calls, separated by ;. A call that names a statement, such as locale(set: 'fr'), runs that statement, as the same line does in a .kscript file.
Write an assignment like $total = 10 or a standalone call such as @save($total).

Its text is assignments separated by ;.

Example
<let name="total" value="10" />
<do>$total += 5; $total *= 2</do>
<echo>$total</echo>
$total = 10
$total += 5
$total *= 2
echo $total

#<echo>echo

Prints its text. { expr } inserts a value; $name and $name->method() work directly.

Holds text with { } values.

AttributeOptionValueDescription
valueexpressionPrint this value instead of the text.
formattext|'json'|'markdown'How to print: text (the default), json (indented and, in a terminal, coloured), or markdown (with KScript.Terminal). A map or nested list on its own is printed as json.
newlinetrue or falseno leaves the cursor at the end of the line.
Example
<let name="name" value="'Joan'" />
<let name="items" value="['tea', 'cake']" />
<echo>Hello, $name! You have { $items->count() } items.</echo>
$name = 'Joan'
$items = ['tea', 'cake']
echo "Hello, { $name }! You have { $items->count() } items."

#<elif>elif

Runs when the earlier <if>/<elif> tests were false and this test is true.Runs when the earlier if/elif tests were false and this test is true.
Tests another condition after an if or elif branch. Write elif $ready { ... }, or elif $ready => @start() for one statement.

Holds statements.Holds statements in { }. Follows <if>if or <elif>elif.

AttributeValueDescription
test requiredexpressionThe condition, for example $n < 10 and $name != '' (in an XML attribute, $n lt 10 and $name ne '').
Example
<let name="n" value="7" />
<if $n lt 5>
  <echo>small</echo>
</if>
<elif $n lt 10>
  <echo>medium</echo>
</elif>
<else>
  <echo>large</echo>
</else>
$n = 7
if $n < 5 {
  echo 'small'
} elif $n < 10 {
  echo 'medium'
} else {
  echo 'large'
}

#<else>else

Runs when the earlier <if>/<elif> tests were all false, or after a <for> that had nothing to loop over.Runs when the earlier if/elif tests were all false, or after a for item in list that had nothing to loop over.
Runs the fallback branch. Write else { ... } after an if, elif, or for block, or else => @stop() for one statement.

Holds statements.Holds statements in { }. Follows <if>if or <elif>elif or <for>for item in list.

Example
<let name="names" value="[]" />
<for each="name" in="$names">
  <echo>$name</echo>
</for>
<else>
  <echo>Nobody here</echo>
</else>
$names = []
for name in $names {
  echo $name
} else {
  echo 'Nobody here'
}

#<enum>enum

Declares a set of named values. Size.small is 'small', and a parameter typed with it (params="size: Size") only takes those values, which calls can write bare: @pack(large).
Declares a set of named values. Write enum Size { small, large }.

Self-closing.A statement on its own.

AttributeValueDescription
name requireda new variable's nameThe enum's name, used as a parameter type and as Name (Size.small).
values requireda list of names: [a, b]The values, as a list: [small, medium, large] (in XML, small, medium, large).
descriptiona stringWhat the enum is for, shown on hover.
Example
<enum name="Size" values="small, medium, large" />
<fn name="pack" params="size: Size" value="'Packing ' + $size" />
<echo>{ @pack(large) }</echo>
enum Size { small, medium, large }
fn pack(size: Size) => 'Packing ' + $size
echo @pack(large)

#<error>error

Declares an error type. throw NotFound(id: 42) raises one, catch NotFound as e catches it and the error types that extend it, and $e.id reads its fields. A status (its own or a parent's) is the HTTP status a KScript.Http route answers with when nothing catches it.
Declares an error type. Write error InvalidAge extends Validation { age: int }, then throw InvalidAge(age: $age).

Holds statements.Holds statements in { }.

AttributeValueDescription
name requireda new variable's nameThe error type's name, starting with a capital letter: NotFound, PaymentFailed.
extendsan error typeThe error type it is a kind of, such as Validation or another <error>. catch of that type catches this one too, and it inherits its fields, message and status. Defaults to Error.The error type it is a kind of, such as Validation or another error. catch of that type catches this one too, and it inherits its fields, message and status. Defaults to Error.
messagea string with { }The message, with the fields as variables: No {$kind} with id {$id}. throw NotFound(id: 1, message: '...') gives one instead.
statusa stringThe HTTP status a KScript.Http route answers with, such as 404. Inherited from the type it extends.
fieldsfieldsThe fields on one line, like fn params: id: int, kind: string = 'item'.
descriptiona stringWhat the error means, shown on hover.
OptionValueDescription
messagea string with { }The message, with the fields as variables: No {$kind} with id {$id}. throw NotFound(id: 1, message: '...') gives one instead.
statusa stringThe HTTP status a KScript.Http route answers with, such as 404. Inherited from the type it extends.
descriptiona stringWhat the error means, shown on hover.
Example
<error name="PersonNotFound" extends="NotFound" fields="id: int" message="No person with id {$id}" />
<try>
  <throw value="PersonNotFound(id: 42)" />
  <catch type="NotFound" as="e">
    <echo>{ $e.message } ({ $e.status })</echo>
  </catch>
</try>
error PersonNotFound(fields: id: int, message: "No person with id {$id}") extends NotFound
try {
  throw PersonNotFound(id: 42)
} catch NotFound as e {
  echo "{ $e.message } ({ $e.status })"
}

#<exit>exit

Ends the script, with an exit code for the shell (0 means success).
Stops the script. Write exit 3 to set the process exit status or exit for status zero.

Self-closing.A statement on its own.

AttributeValueDescription
codeexpressionThe exit code. Defaults to 0.
Example
<exit code="1" />
exit 1

#<extend>extend

Adds methods to a type: a built-in one such as date, string or list, a package's (file, response), or a <type>. Each <fn> inside becomes a method, with the value it is called on as $this: extend date { fn api_date() => $this->format('yyyy-MM-dd') } makes @today()->api_date() work. Scripts that import the file get the methods too, and in a project every file in the extensions folder applies everywhere.Adds methods to a type: a built-in one such as date, string or list, a package's (file, response), or a type. Each fn inside becomes a method, with the value it is called on as $this: extend date { fn api_date() => $this->format('yyyy-MM-dd') } makes @today()->api_date() work. Scripts that import the file get the methods too, and in a project every file in the extensions folder applies everywhere.
Adds methods to a type. Write extend string { fn example() => $this }.

Holds statements.Holds statements in { }.

AttributeValueDescription
type requireda stringThe type to add methods to: date, string, number, bool, list, map, fn, email, handle, uuid, regex, password, a package's type such as file or response, or a <type>'s name.The type to add methods to: date, string, number, bool, list, map, fn, email, handle, uuid, regex, password, a package's type such as file or response, or a type's name.
descriptiona stringWhat the methods are for, shown on hover.
Example
<extend type="date">
  <fn name="is_payday" value="$this.day == 25" />
</extend>
<echo>{ @today()->is_payday() }</echo>
extend date {
  fn is_payday() => $this.day == 25
}
echo @today()->is_payday()

#<field>name: type

One field of a <type>, <error>, <model> or <job>: in a .kscript file, one line of the block, stars: int from stargazers_count.One field of a type, error, model or job: in a .kscript file, one line of the block, stars: int from stargazers_count.
Write a field inside the type or model body, such as name: string or due?: date.

Self-closing.A statement on its own. Goes inside <type>type or <error>error or <model>model or <job>job or <event>event or <construct>construct.

AttributeValueDescription
name requireda stringThe field's name. End it with ? to make it optional.
typestring | int | float | number | bool | list | set | map | fn | date | markdown | latex | formatted_file | document | email | password | handle | uuid | regex | url | domain | ip | cidr | mac | port | slug | slash_path | file_path | semver | mime | hex | base64 | jwt | json | csv | phone | country | currency | locale | timezone | duration | date_format | cron | color | iban | card | money | anyThe field's type: a built-in such as string or int, an <enum>, another <type>, T[] for a list, T? to allow null. Defaults to any.The field's type: a built-in such as string or int, an enum, another type, T[] for a list, T? to allow null. Defaults to any.
froma stringWhere to read the value, when it isn't the field's name: stargazers_count, owner.login, items[0].name.
defaultexpressionThe value when the data has none (makes the field optional).
optionaltrue or falsetrue lets the value be missing or null.
valueexpressionWorks the field out from the others (they are $name) instead of reading it: $first + ' ' + $last.
mina stringThe smallest value allowed: a number, a date, or the length of text or a list.
maxa stringThe largest value allowed: a number, a date, or the length of text or a list.
patterna stringA regular expression the value's text must match.
one_ofa stringThe only values allowed: gb, ie or ['gb', 'ie'].
nota stringValues that aren't allowed, such as reserved names.
descriptiona stringWhat the field holds, shown on hover and completion.
privatetrue or falsetrue keeps the field to the type's own methods: other code can't read, set or pass it. In a .kscript file, private count: int.
Example
<type name="Repo">
  <field name="name" type="string" />
  <field name="stars" type="int(min: 0)" from="stargazers_count" />
  <field name="topics" type="string[]" default="[]" />
</type>
<let name="repo" value="Repo({ name: 'kscript', stargazers_count: 42 })" />
<echo>{ $repo.name } has { $repo.stars } stars and { $repo.topics->count() } topics</echo>
type Repo {
  name: string
  stars: int(min: 0) from stargazers_count
  topics: string[] = []
}
$repo = Repo({ name: 'kscript', stargazers_count: 42 })
echo "{ $repo.name } has { $repo.stars } stars and { $repo.topics->count() } topics"

#<finally>finally

Runs after the <try> body and any <catch>, whether or not there was an error.Runs after the try body and any catch err, whether or not there was an error.
Runs cleanup after the try body and any catch. Append finally { ... } after the preceding block.

Holds statements.Holds statements in { }. Goes inside <try>try.

Example
<try>
  <echo>working</echo>
  <throw message="Oops" />
  <catch as="err"><echo>caught: { $err.message }</echo></catch>
  <finally><echo>cleaned up</echo></finally>
</try>
try {
  echo 'working'
  throw "Oops"
} catch err {
  echo "caught: { $err.message }"
} finally {
  echo 'cleaned up'
}

#<fn>fn

Declares a function, called like a command: @name(args), or piped: $x |> @name(). Functions can be called before the line that declares them.
Declares a function. Write fn greet(name: string) => "Hi {$name}" or give it a statement body with braces. Call it with @greet('Joan').

Holds statements.Holds statements in { }.

AttributeValueDescription
name requireda function nameThe function's name.
genericsa stringType parameters a call fills in, used in the parameter and return types: T for fn first<T>(items: T[]): T.
paramsparametersParameters, with optional types and defaults: who, greeting = 'Hello' or count: int = 1.
valueexpressionFor one-line functions: the result, instead of a body.
returnsa stringThe declared return type.
signaturea stringDeclares a method signature without an implementation.
optionala stringThe method may be omitted by a type implementing this signature.
surfacepage|window|terminal|'document'For a component's render: where it draws, when its content doesn't show it.
privatetrue or falseInside a <type> or <model>: true keeps the method to the type's own methods. In a .kscript file, private fn tally().Inside a type or model: true keeps the method to the type's own methods. In a .kscript file, private fn tally().
overridetrue or falseInside <extend>: true replaces the type's built-in method of the same name. Without it, reusing a built-in method's name is an error.Inside extend: true replaces the type's built-in method of the same name. Without it, reusing a built-in method's name is an error.
descriptiona stringWhat the function does. Shown in hover, and to a model when used as an <llm> tool.What the function does. Shown in hover, and to a model when used as an llm tool.
Example
<fn name="greet" params="who: string, greeting = 'Hello'">
  <return value="$greeting + ', ' + $who + '!'" />
</fn>
<echo>@greet('World')</echo>
fn greet(who: string, greeting = 'Hello') {
  return $greeting + ', ' + $who + '!'
}
echo @greet('World')

#<for>for item in list

Loops over a list, a map or a range such as 0..10 (end exclusive) or 0..100 step 5. $loop holds index, first, last and count.
Loops over values. Write for item in $items { ... }.

Holds statements.Holds statements in { }. A loop: <break /> and <continue /> work inside.A loop: break and continue work inside.

AttributeValueDescription
each requirednew variable namesThe loop variable, or key, value for a map.
in requiredexpressionWhat to loop over: a list, a map, a range, a number (0 up to it) or text (its characters).
ata new variable's nameA variable for the position, from 0.
Example
<let name="people" value="[{ name: 'Joan' }, { name: 'Sam' }]" />
<for each="p" in="$people">
  <echo>{$p.name}</echo>
</for>
<for each="i" in="0..10"><echo>$i</echo></for>
<let name="settings" value="{ host: 'localhost', port: 8080 }" />
<for each="key, value" in="$settings"><echo>$key = $value</echo></for>
$people = [{ name: 'Joan' }, { name: 'Sam' }]
for p in $people {
  echo $p.name
}
for i in 0..10 {
  echo $i
}
$settings = { host: 'localhost', port: 8080 }
for key, value in $settings {
  echo "{ $key } = { $value }"
}

#<guard>guard

Checks a precondition. When the test is false, its body must leave the current flow.
Checks a precondition. Write guard $ready else { return }. The failure block leaves with return, throw, break, continue or exit.

Holds statements.Holds statements in { }.

AttributeValueDescription
test requiredexpressionThe condition, for example $n < 10 and $name != '' (in an XML attribute, $n lt 10 and $name ne '').
Example
<fn name="half" params="n: number">
  <guard test="$n ge 0">
    <return value="0" />
  </guard>
  <return value="$n / 2" />
</fn>
<echo>{ @half(10) } { @half(-4) }</echo>
fn half(n: number) {
  guard $n >= 0 else {
    return 0
  }
  return $n / 2
}
echo "{ @half(10) } { @half(-4) }"

#<if>if

Runs its body when the test is true. Follow it with <elif> and <else> for other cases.Runs its body when the test is true. Follow it with elif and else for other cases.
Runs a block when its condition is true. Write if $ready { ... }, or if $ready => @start() for one statement on the same line, followed by optional elif condition { ... } and else { ... } branches.

Holds statements.Holds statements in { }.

AttributeValueDescription
test requiredexpressionThe condition, for example $n < 10 and $name != '' (in an XML attribute, $n lt 10 and $name ne '').
Example
<let name="score" value="80" />
<if $score ge 90>
  <echo>A</echo>
</if>
<elif $score ge 75>
  <echo>B</echo>
</elif>
<else>
  <echo>C</echo>
</else>
$score = 80
if $score >= 90 {
  echo 'A'
} elif $score >= 75 {
  echo 'B'
} else {
  echo 'C'
}

#<import>import

Imports a package (package="KScript.Terminal"), or the top-level <fn> functions and <let const> values of another script (path). Goes at the top of the script.Imports a package (package="KScript.Terminal"), or the top-level fn functions and <let const> values of another script (path). Goes at the top of the script.
Imports a package with import KScript.IO, or another script with import "./helpers.kscript".

Self-closing.A statement on its own.

AttributeValueDescription
packagea stringA package such as KScript.Terminal, KScript.Math, KScript.IO or KScript.Net.
patha file pathA script to import, relative to this file.
asa new variable's nameUse the import under a prefix: @math.sqrt(2), str.slugify().
namesa list of functions: [a, b]Import only these names from a script, callable directly: @slugify().
Example
<import package="KScript.Terminal" />
<import package="KScript.Math" as="math" />
<import path="lib/strings.ks.xml" as="str" />
import KScript.Terminal
import KScript.Math as math
import "lib/strings.ks.xml" as str

#<item>item

An entry of <collection>. With key it is a map entry, without it a list item. Its text is the value (numbers become numbers); nested items make a list or map.An entry of collection. With key it is a map entry, without it a list item. Its text is the value (numbers become numbers); nested items make a list or map.

Holds text with { } values. Goes inside <collection>collection or <item>item.

AttributeOptionValueDescription
keya stringThe key in the enclosing map.
valueexpressionThe value as an expression, instead of text.
Example
<collection name="order">
  <item key="id">42</item>
  <item key="lines">
    <item>Tea</item>
    <item>Cake</item>
  </item>
</collection>
<echo>{ $order.id }: { $order.lines }</echo>
collection(name: order) {
  item(key: 'id') "42"
  item(key: 'lines') {
    item "Tea"
    item "Cake"
  }
}
echo "{ $order.id }: { $order.lines }"

#<kscript>a .kscript file

The root of a script. Everything the script does goes inside.

Holds statements.Holds statements in { }. Scripts only.

Example
<kscript>
  <echo>Hello!</echo>
</kscript>
echo 'Hello!'

#<let>$name = value

Declares a variable in the current scope. The value goes in value, or in the element text for longer values. Without name, the text is assignment statements such as $x = 3.
Write an assignment like $total = 10 or a standalone call such as @save($total).

Its text is one expression.

AttributeValueDescription
namea new variable's nameThe variable to declare.
valueexpressionThe initial value. Can be written as the element's text instead.
typestring | int | float | number | bool | list | set | map | fn | date | markdown | latex | formatted_file | document | email | password | handle | uuid | regex | url | domain | ip | cidr | mac | port | slug | slash_path | file_path | semver | mime | hex | base64 | jwt | json | csv | phone | country | currency | locale | timezone | duration | date_format | cron | color | iban | card | money | anyConvert the value to this type, or fail early: a built-in such as int, an <enum>, a <type>, T[] for a list, T? to allow null.Convert the value to this type, or fail early: a built-in such as int, an enum, a type, T[] for a list, T? to allow null.
consttrue or falsetrue makes a later <set> an error.true makes a later $name += value an error.
Example
<let name="count" value="0" />
<let name="people">[{ name: 'Joan', age: 82 }]</let>
<let>$x = 3</let>
$count = 0
$people = [{ name: 'Joan', age: 82 }]
$x = 3

#<locale>locale

Changes the current locale, which @t() and the @format_ commands use. Without set, picks the best available locale from from (a list of wishes, such as an Accept-Language header).

Self-closing.A statement on its own.

AttributeOptionValueDescription
seta string with { }The locale, such as fr or en-GB.
fromexpressionWishes in order, as a list or an Accept-Language header: the best available locale is used.
Example
<locale set="fr" />
<locale from="['fr-CA', 'en']" />
locale(set: 'fr')
locale(from: ['fr-CA', 'en'])

#<log>log

Logs its text through $log's providers, at a level. Fields add values such as { user: $id }.

Holds text with { } values.

AttributeOptionValueDescription
leveltrace|debug|info|warn|error|fatalHow serious it is (default info).
messagea string with { }The message, instead of the element's text.
categorya string with { }Where it comes from, such as db or payments.
fieldsexpressionA map of extra values, such as { order: $order.id, total: $total }.
Example
<let name="id" value="42" />
<let name="customer" value="{ name: 'Joan' }" />
<log level="warn" category="payments" fields="{ order: $id }">Card declined for {$customer.name}</log>
$id = 42
$customer = { name: 'Joan' }
log(level: warn, category: 'payments', fields: { order: $id }) "Card declined for {$customer.name}"

#<log_provider>log_provider

Adds somewhere for log entries to go: the console, a file, memory (for tests), a function, or a type a package adds (KScript.Net adds http). Usually set in config under logging.providers instead.

Self-closing.A statement on its own. Scripts only.

AttributeOptionValueDescription
typea stringconsole, file, memory, or a type from an imported package such as http. Leave it out when using fn.
fna function: @nameA function called with each entry (a map of time, level, category, message, fields, script and line): @alert (in XML, fn="alert").
leveltrace|debug|info|warn|error|fatal|offThe lowest level this provider writes (default: all that logging lets through).
formattext|'json'text or json (console and file).
patha string with { }The file to append to (file).
rollnever|dailydaily starts a new file each day: app-2026-11-20.log (file).
streamstderr|stdoutWhere console entries go (default stderr).
colortrue or falseColour console entries by level (default: when at a terminal).
timea stringThe console's time format, such as HH:mm:ss.fff (default HH:mm:ss). Empty leaves the time out.
urla string with { }Where entries are sent (http, from KScript.Net).
headersexpressionA map of request headers (http).
batchexpressionHow many entries to send at once (http, default 20).
namea stringA name for the provider, used in error messages.
replacetrue or falsetrue removes the providers already set up, including the default console one.
Example
<log_provider type="file" path="logs/app.log" format="json" level="debug" />
<fn name="alert" params="entry: map"><echo>ALERT: {$entry.message}</echo></fn>
<log_provider fn="alert" level="error" />
log_provider(type: 'file', path: 'logs/app.log', format: json, level: debug)
fn alert(entry: map) {
  echo "ALERT: {$entry.message}"
}
log_provider(fn: @alert, level: error)

#<match>match

Compares one value against several cases. Inside, $it is the value.
Selects the first matching arm. Write match $n { 0 => 'zero', _ => 'other' }.

Holds statements.Holds statements in { }.

AttributeValueDescription
value requiredexpressionThe value to compare.
Example
<let name="choice" value="'other'" />
<match $choice>
  <case is="1"><echo>One</echo></case>
  <case is="2, 3"><echo>Two or three</echo></case>
  <case when="$choice gt 9"><echo>Big</echo></case>
  <default><echo>Unknown</echo></default>
</match>
$choice = 'other'
match $choice {
  1 => echo 'One'
  2, 3 => echo 'Two or three'
  _ when $choice > 9 => echo 'Big'
  _ => echo 'Unknown'
}

#<normalize>normalize

Cleans up a value before a <type>'s rules check it, such as trimming or lower-casing. The value is $value; the result is converted to the type again.Cleans up a value before a type's rules check it, such as trimming or lower-casing. The value is $value; the result is converted to the type again.

Self-closing.A statement on its own. Goes inside <type>type.

AttributeOptionValueDescription
value requiredexpressionThe cleaned-up value: $value->trim()->lower().
Example
<type name="Slug" with="string" pattern="^[a-z0-9-]+$">
  <normalize value="$value->trim()->lower()" />
</type>
<echo>{ Slug(' Hello-World ') }</echo>
type Slug with [string] {
  pattern: "^[a-z0-9-]+$"
  normalize: $value->trim()->lower()
}
echo Slug(' Hello-World ')

#<return>return

Ends the function with a value.
Leaves the current function. Write return $result to send a value to the caller, or return to return null.

Self-closing.A statement on its own. Goes inside <fn>fn.

AttributeValueDescription
valueexpressionThe result. Without it the function returns null.
Example
<fn name="area" params="w: number, h: number">
  <return value="$w * $h" />
</fn>
<echo>{ @area(3, 4) }</echo>
fn area(w: number, h: number) {
  return $w * $h
}
echo @area(3, 4)

#<set>$name += value

Changes an existing variable. Fails if the variable was never declared (a typo guard) or is const. Without name, the text is assignment statements.
Write an assignment like $total = 10 or a standalone call such as @save($total).

Its text is one expression.

AttributeValueDescription
namea variable's nameThe variable to change.
valueexpressionThe new value. Can be written as the element's text instead.
op'='|'+='|'-='|'*='|'/='|'??='Update instead of replace: op="+=" value="1".
typestring | int | float | number | bool | list | set | map | fn | date | markdown | latex | formatted_file | document | email | password | handle | uuid | regex | url | domain | ip | cidr | mac | port | slug | slash_path | file_path | semver | mime | hex | base64 | jwt | json | csv | phone | country | currency | locale | timezone | duration | date_format | cron | color | iban | card | money | anyConvert the value to this type, or fail: a built-in such as int, an <enum>, a <type>, T[] for a list, T? to allow null.Convert the value to this type, or fail: a built-in such as int, an enum, a type, T[] for a list, T? to allow null.
Example
<let name="total" value="0" />
<let name="count" value="0" />
<set name="total" value="$total + 2.50 * 3" />
<set>$count += 1</set>
<echo>$count item, $total</echo>
$total = 0
$count = 0
$total = $total + 2.50 * 3
$count += 1
echo "{ $count } item, { $total }"

#<slot>slot

In a layout or component: where the page's (or caller's) content goes. In a component's render for a window, a document or the terminal, it draws what was written inside the component where it is used.

Self-closing.A statement on its own.

AttributeOptionValueDescription
namea stringA named slot, in a page's layout or component.
Example
<type name="Panel" extends="Component">
  <field name="title" type="string" />
  <fn name="render">
    <echo>{$title}</echo>
    <slot />
  </fn>
</type>
<Panel title="Notes">
  <echo>Buy milk</echo>
</Panel>
type Panel extends Component {
  title: string
  fn render() {
    echo .title
    slot
  }
}
Panel(title: 'Notes') {
  echo 'Buy milk'
}

#<spawn>spawn

Runs a function in the background. The script waits for it before it ends.

Self-closing.A statement on its own.

AttributeOptionValueDescription
fn requireda function: @nameThe function to run: @count_to (in XML, fn="count_to").
argsexpressions, comma separatedArguments, comma separated.
Example
<fn name="count_to" params="n: int"><echo>Counted to { @range(1, $n + 1)->last() }</echo></fn>
<spawn fn="count_to" args="1000" />
<echo>Started counting</echo>
fn count_to(n: int) {
  echo "Counted to { @range(1, $n + 1)->last() }"
}
spawn(fn: @count_to, args: 1000)
echo 'Started counting'

#<strict>strict

Turns on strict types for the script: every value needs a type the checker can prove, and a type mistake is an error that stops the script before it runs. Goes at the top of the script, before anything but imports. "strict": true in kscript.json does the same for every script in a project.
Turns on strict types: every value needs a type the checker can prove, and a type mistake stops the script before it runs. Write strict at the top of the file, before anything but imports.

Self-closing.A statement on its own.

Example
<strict />
<fn name="area" params="width: number, height: number" returns="number" value="$width * $height" />
<echo value="@area(3, 4)" />
strict
fn area(width: number, height: number): number => $width * $height
echo @area(3, 4)

#<throw>throw

Raises an error, which a <catch> can handle. Without a <try>, the script stops with the message. value throws an error made from a type (NotFound(id: 42)) or a caught one again; a bare <throw /> inside a <catch> rethrows the error it is handling.Raises an error, which a catch err can handle. Without a try, the script stops with the message. value throws an error made from a type (NotFound(id: 42)) or a caught one again; a bare throw inside a catch err rethrows the error it is handling.
Raises an error when the statement runs. Use throw Validation "Invalid age" for a message, or throw Error(message: 'Oops', value: $age, cause: $original) for named fields. To throw a payload map, write throw $payload. Inside a catch, bare throw rethrows the current error. Use throw if condition { ... } for a conditional throw.

Holds text with { } values.

AttributeValueDescription
typean error typeThe error type, such as Validation or an <error>. Defaults to Error.The error type, such as Validation or an error. Defaults to Error.
messagea string with { }What went wrong. Can be written as the element's text instead.
valueexpressionThe error to throw: NotFound(id: 42), Validation('Too short'), or a caught $err.
causeexpressionThe error that led to this one, such as the $err of the <catch> around it. It is $e.cause on the new error.The error that led to this one, such as the $err of the catch err around it. It is $e.cause on the new error.
Example
<let name="age" value="-1" />
<try>
  <throw type="Validation" message="Age must be positive, got {$age}" />
  <catch as="err"><echo>{ $err.type }: { $err.message }</echo></catch>
</try>
$age = -1
try {
  throw Validation "Age must be positive, got {$age}"
} catch err {
  echo "{ $err.type }: { $err.message }"
}

#<translations>translations

Says where translation files are and which locale to fall back to. Usually set in config under i18n instead.

Self-closing.A statement on its own.

AttributeOptionValueDescription
foldera string with { }The folder of translation files (default locales): locales/en.json, locales/fr.yaml, or locales/fr/*.json.
defaulta string with { }The locale used when a translation is missing (default en).
Example
<translations folder="lang" default="en-GB" />
translations(folder: 'lang', default: 'en-GB')

#<try>try

Runs its body, handing errors to its <catch> elements. <finally> always runs.Runs its body, handing errors to its catch err elements. finally always runs.
Runs statements with one or more error handlers and optional cleanup. Write try { ... } catch Validation as err { ... }.

Holds statements.Holds statements in { }.

Example
<let name="text" value="'not json'" />
<try>
  <let name="data" value="$text->convert(from: json)" />
  <catch as="err" when="$err.type eq 'Json'">
    <echo>That isn't JSON: {$err.message}</echo>
  </catch>
  <finally><echo>done</echo></finally>
</try>
$text = 'not json'
try {
  $data = $text->convert(from: json)
} catch err when $err.type == 'Json' {
  echo "That isn't JSON: {$err.message}"
} finally {
  echo 'done'
}

#<type>type

Declares the shape of some data, such as an API response. ->convert(from: json, as: Repo), Repo($data), <let type="Repo"> and repo: Repo parameters check data against it and turn it into a record: a map whose fields the editor knows. Every problem is reported at once, with its JSON path.
Declares a type. Write type Person { name: string } for a record, or type Key with [string] { min: 3 } for a refinement.

Holds statements.Holds statements in { }.

AttributeValueForDescription
name requireda new variable's nameany typeThe type's name, used as type="Repo", as: Repo and Repo.
fieldsfieldstypes with fieldsA short type's fields on one line, like fn params: login: string, id: int, avatar_url?: string. Bigger types list their fields one per line instead (<field> elements).A short type's fields on one line, like fn params: login: string, id: int, avatar_url?: string. Bigger types list their fields one per line instead (name: type elements).
patha file pathtypes with fieldsA JSON file holding a sample of the data. Its keys become fields; <field> elements and fields replace the ones they name.A JSON file holding a sample of the data. Its keys become fields; name: type elements and fields replace the ones they name.
extradrop|keep|errortypes with fieldsKeys in the data that the type doesn't list: drop them (the default), keep them, or make them an error. Written in brackets after the type's name: type Repo(extra: error) { name: string }.
extendsa stringtypes with fieldsA type whose required method signatures this type implements.
withstring | int | float | number | bool | list | set | map | fn | date | markdown | latex | formatted_file | document | email | password | handle | uuid | regex | url | domain | ip | cidr | mac | port | slug | slash_path | file_path | semver | mime | hex | base64 | jwt | json | csv | phone | country | currency | locale | timezone | duration | date_format | cron | color | iban | card | money | anyany typeOther types this one is made from. Types with fields are joined: with="User, Auditable" has all their fields and rules, and fits wherever they do. One built-in type, such as with="int" or with="handle", makes a type with rules instead of fields: min, max, pattern, one_of, not, <validate>, <normalize> and <value>.Other types this one is made from. Types with fields are joined: with="User, Auditable" has all their fields and rules, and fits wherever they do. One built-in type, such as with="int" or with="handle", makes a type with rules instead of fields: min, max, pattern, one_of, not, validate, normalize and value.
mina number, a date, a length or a counttypes made from one built-in typeThe smallest value allowed, read by the base type: a number for int and float, a date for date, a length for text (a handle's name without its @), and a count for lists. type Age with [int] { min: 0 }.
maxa number, a date, a length or a counttypes made from one built-in typeThe largest value allowed, read by the base type: a number for int and float, a date for date, a length for text, and a count for lists. type Age with [int] { max: 150 }.
patterna regular expression: /^[a-z]+$/any typeA regular expression the value's text must match: /^[a-z0-9-]+$/. On a type made from a number, the text is its digits, so a pattern of letters is an error. On a type with fields, its named groups fill the fields of the same name, so the type can be made from text.
parseexpressiontypes with fieldsOn a type with fields: an expression that turns text into a map of the fields, with the text as $value and the pattern's match (if any) as $match.
one_ofa list of values of the base type: [a, b]types made from one built-in typeThe only values allowed, each a value of the base type: [gb, ie] for a country, [1, 2, 3] for an int. Compared after converting and normalising.
nota list of values of the base type: [a, b]types made from one built-in typeValues that aren't allowed, each a value of the base type, such as reserved names: [@admin, @root] for a handle.
factoryan expression of $value: try each $value |> NumberEntry, MultiplierEntrytypes made from one built-in typeWhat a value of this type is made into, once it passes the type's own rules: factory(label) => try each $label |> NumberEntry, MultiplierEntry, or factory: ... with the value as $value. It gives back a value of the type or of a type made from it, which keeps that type wherever it goes. MicrowaveButton('[*11]') runs it; MultiplierEntry('[*11]') doesn't.
descriptiona stringany typeWhat the type is, shown on hover.
OptionValueForDescription
patha file pathtypes with fieldsA JSON file holding a sample of the data. Its keys become fields; <field> elements and fields replace the ones they name.A JSON file holding a sample of the data. Its keys become fields; name: type elements and fields replace the ones they name.
extradrop|keep|errortypes with fieldsKeys in the data that the type doesn't list: drop them (the default), keep them, or make them an error. Written in brackets after the type's name: type Repo(extra: error) { name: string }.
mina number, a date, a length or a counttypes made from one built-in typeThe smallest value allowed, read by the base type: a number for int and float, a date for date, a length for text (a handle's name without its @), and a count for lists. type Age with [int] { min: 0 }.
maxa number, a date, a length or a counttypes made from one built-in typeThe largest value allowed, read by the base type: a number for int and float, a date for date, a length for text, and a count for lists. type Age with [int] { max: 150 }.
patterna regular expression: /^[a-z]+$/any typeA regular expression the value's text must match: /^[a-z0-9-]+$/. On a type made from a number, the text is its digits, so a pattern of letters is an error. On a type with fields, its named groups fill the fields of the same name, so the type can be made from text.
parseexpressiontypes with fieldsOn a type with fields: an expression that turns text into a map of the fields, with the text as $value and the pattern's match (if any) as $match.
one_ofa list of values of the base type: [a, b]types made from one built-in typeThe only values allowed, each a value of the base type: [gb, ie] for a country, [1, 2, 3] for an int. Compared after converting and normalising.
nota list of values of the base type: [a, b]types made from one built-in typeValues that aren't allowed, each a value of the base type, such as reserved names: [@admin, @root] for a handle.
factoryan expression of $value: try each $value |> NumberEntry, MultiplierEntrytypes made from one built-in typeWhat a value of this type is made into, once it passes the type's own rules: factory(label) => try each $label |> NumberEntry, MultiplierEntry, or factory: ... with the value as $value. It gives back a value of the type or of a type made from it, which keeps that type wherever it goes. MicrowaveButton('[*11]') runs it; MultiplierEntry('[*11]') doesn't.
descriptiona stringany typeWhat the type is, shown on hover.
Example
<type name="User">
  <field name="login" type="string" />
  <field name="id" type="int" />
</type>
<type name="Repo">
  <field name="name" type="string" />
  <field name="stars" type="int" from="stargazers_count" />
  <field name="owner" type="User" />
</type>
<let name="repo" value="Repo({ name: 'kscript', stargazers_count: 12, owner: { login: 'kyle', id: 1 } })" />
<echo>$repo.name has $repo.stars stars</echo>
type User {
  login: string
  id: int
}
type Repo {
  name: string
  stars: int from stargazers_count
  owner: User
}
$repo = Repo({ name: 'kscript', stargazers_count: 12, owner: { login: 'kyle', id: 1 } })
echo "{ $repo.name } has { $repo.stars } stars"

#<validate>validate

A rule a <type> checks: the test must be true. In a type made from one other type, the value is $value. In a type with fields, each field is a variable ($end > $start). Every rule that fails is reported, with its message.A rule a type checks: the test must be true. In a type made from one other type, the value is $value. In a type with fields, each field is a variable ($end > $start). Every rule that fails is reported, with its message.

Self-closing.A statement on its own. Goes inside <type>type or <model>model.

AttributeOptionValueDescription
test requiredexpressionWhat must be true: $value % 5 == 0, $end > $start.
messagea stringWhat to say when it isn't, such as must end after it starts.
Example
<type name="Even" with="int">
  <validate test="$value % 2 == 0" message="must be even" />
</type>
<echo>{ Even(4) }</echo>
type Even with [int] {
  validate: $value % 2 == 0, 'must be even'
}
echo Even(4)

#<value>value

What a value of a <type> made from one other type reads as wherever it is used, worked out once its rules have passed. $value is the checked value (after normalize), and .group(1) reads what the pattern captured. The result can be of another type: value: .group(1)->to_int() makes the value read as a number.What a value of a type made from one other type reads as wherever it is used, worked out once its rules have passed. $value is the checked value (after normalize), and .group(1) reads what the pattern captured. The result can be of another type: value: .group(1)->to_int() makes the value read as a number.

Self-closing.A statement on its own. Goes inside <type>type.

AttributeOptionValueDescription
value requiredexpressionWhat the value reads as: .group(1)->to_int(), $value->split(',').
Example
<type name="Multiplier" with="string" pattern="^x(\d+)$">
  <value value=".group(1)->to_int()" />
</type>
<echo>{ Multiplier('x11') + 1 }</echo>
type Multiplier with [string] {
  pattern: "^x(\d+)$"
  value: .group(1)->to_int()
}
echo Multiplier('x11') + 1

#<wait>wait

Pauses the script.

Self-closing.A statement on its own.

AttributeOptionValueDescription
duration requiredexpressionHow long to wait: 500ms, 2s, 1m30s. A plain number is seconds.
Example
<wait duration="1.5s" />
wait(duration: 1.5s)

#<while>while

Loops while the test is true. test="true" loops until <break/>.Loops while the test is true. test="true" loops until break.
Repeats while its condition is true. Write while $remaining > 0 { ... }.

Holds statements.Holds statements in { }. A loop: <break /> and <continue /> work inside.A loop: break and continue work inside.

AttributeValueDescription
test requiredexpressionThe condition, for example $n < 10 and $name != '' (in an XML attribute, $n lt 10 and $name ne '').
Example
<let name="n" value="0" />
<while $n lt 3>
  <set name="n" value="$n + 1" />
</while>
<echo>$n</echo>
$n = 0
while $n < 3 {
  $n = $n + 1
}
echo $n

Commands

Commands are called with @, in any expression: @name(arguments).

#@char_of(code: number) → string

The character with this character code: @char_of(65) is A.
ParameterTakes
code requirednumber
Example
<echo>{ @char_of(75) + @char_of(83) }</echo>
echo @char_of(75) + @char_of(83)

#@decrypt(text) → any

The value @encrypt() was given. Text that was changed, or encrypted with another KSCRIPT_SECRET, is a Format error.
Example
<echo>{ @decrypt(@encrypt('hello')) }</echo>
echo @decrypt(@encrypt('hello'))

#@encrypt(value) → string

Encrypts a value (text, a number, a map or a list) with the app's secret, KSCRIPT_SECRET, so only the app can read it: a third party's token kept in the database, say. The text is URL-safe. @decrypt() gives the value back.
Example
<let name="secret" value="@encrypt({ token: 'abc' })" />
<echo>{ @decrypt($secret).token }</echo>
$secret = @encrypt({ token: 'abc' })
echo @decrypt($secret).token

#@env(name, default?) → string

An environment variable, or default when it isn't set.

Arguments can be named: @env(…, default: …).

Example
<echo>{ @env('KSCRIPT_DOCS_EXAMPLE', 'not set') }</echo>
echo @env('KSCRIPT_DOCS_EXAMPLE', 'not set')

#@escape_regex(text: string) → string

Text with every character that means something in a regular expression escaped, so it matches only itself: build a pattern from what a user typed.
ParameterTakes
text requiredstring
Example
<echo>{ 'Price: $5 (each)'->matches(@escape_regex('$5 (')) }</echo>
echo 'Price: $5 (each)'->matches(@escape_regex('$5 ('))

#@format_bytes(bytes: number, binary?: bool, locale?) → string

A number of bytes for people: 1.4 MB, in powers of 1000. With binary: true, powers of 1024 (1.3 MiB).
ParameterTakes
bytes requirednumber
binary optionala flag: binary or not binary
locale optionalany value

Arguments can be named: @format_bytes(…, binary: …, locale: …).

Example
<echo>{ @format_bytes(1400000) }</echo>
echo @format_bytes(1400000)

#@format_currency(amount, currency, locale?) → string

An amount of money for the locale: @format_currency(9.5, 'EUR') is €9.50 in en and 9,50 € in fr.

Arguments can be named: @format_currency(…, currency: …, locale: …).

Example
<echo>{ @format_currency(19.99, currency: 'EUR', locale: 'fr') }</echo>
echo @format_currency(19.99, currency: 'EUR', locale: 'fr')

#@format_date(date: date, style?, locale?) → string

A date for the locale. style: short, medium (the default), long, full, time, datetime, or a pattern such as 'd MMMM yyyy'.
ParameterTakes
date requireddate
style optionalany value
locale optionalany value

Arguments can be named: @format_date(…, style: …, locale: …).

Example
<echo>{ @format_date('2026-11-19'->to_date(), style: 'long') }</echo>
echo @format_date('2026-11-19'->to_date(), style: 'long')

#@format_duration(duration: duration, locale?) → string

A length of time in words for the locale: 1h30m is 1 hour 30 minutes, 1 heure 30 minutes in fr.
ParameterTakes
duration requiredduration
locale optionalany value

Arguments can be named: @format_duration(…, locale: …).

Example
<echo>{ @format_duration(1h30m) }</echo>
echo @format_duration(1h30m)

#@format_list(items: list, style?: and|or, locale?) → string

Items joined for the locale: a, b and c (or a, b or c with style: or).
ParameterTakes
items requiredlist
style optionalone of these words: and|or
locale optionalany value

Arguments can be named: @format_list(…, style: …, locale: …).

Example
<echo>{ @format_list(['tea', 'coffee', 'milk']) }</echo>
echo @format_list(['tea', 'coffee', 'milk'])

#@format_number(number, decimals?, locale?) → string

A number written for the locale: 1,234.5 in en, 1 234,5 in fr.

Arguments can be named: @format_number(…, decimals: …, locale: …).

Example
<echo>{ @format_number(1234567.891, decimals: 2) }</echo>
echo @format_number(1234567.891, decimals: 2)

#@format_ordinal(number: number, locale?) → string

A whole number as an ordinal for the locale: 1st, 2nd, 23rd in en, 1er and 2e in fr.
ParameterTakes
number requirednumber
locale optionalany value

Arguments can be named: @format_ordinal(…, locale: …).

Example
<echo>{ @format_ordinal(23) }</echo>
echo @format_ordinal(23)

#@format_percent(fraction, decimals?, locale?) → string

A fraction as a percentage for the locale: 0.25 is 25%.

Arguments can be named: @format_percent(…, decimals: …, locale: …).

Example
<echo>{ @format_percent(0.256, decimals: 1) }</echo>
echo @format_percent(0.256, decimals: 1)

#@format_relative(date: date, from?: date, locale?) → string

How long ago or ahead a date is, in words for the locale: 3 hours ago, in 2 days, il y a 3 jours. Measured from now (which @with_clock() fixes in tests) or from another date.
ParameterTakes
date requireddate
from optionaldate
locale optionalany value

Arguments can be named: @format_relative(…, from: …, locale: …).

Example
<echo>{ @format_relative('2026-11-19 09:00'->to_date(), from: '2026-11-19 12:00'->to_date()) }</echo>
echo @format_relative('2026-11-19 09:00'->to_date(), from: '2026-11-19 12:00'->to_date())

#@has_t(key, locale?) → bool

True when a key has a translation in the current locale (or its fallbacks).

Arguments can be named: @has_t(…, locale: …).

Example
<echo>{ @has_t('cart.items') }</echo>
echo @has_t('cart.items')

#@inject(model?, from?, can?) → any

The record of a model that the route being answered holds. As the default of an input, post: Post = @inject(), it reads the model from the input's type and takes the route's {post}; from: names another route parameter. On its own it is given the model: @inject(Post). can: names an ability the model's policy must allow, @inject(can: read), and answers 403 when it doesn't. What a caller passes always wins over the default.

Arguments can be named: @inject(…, from: …, can: …).

Example
<import package="KScript.Data" /><model name="Post"><field name="title" type="string" /></model><type name="PostCard"><construct><field name="post" type="Post" default="@inject()" /></construct></type>
import KScript.Data
model Post {
  title: string
}
type PostCard {
  construct({ post: Post = @inject() })
}

#@locale() → string

The current locale, such as fr or en-GB.
Example
<echo>{ @locale() }</echo>
echo @locale()

#@locales() → list

The locales there are translation files for.
Example
<echo>{ @locales() }</echo>
echo @locales()

#@locale_path(path, locale?) → string

A site path for a locale, for language links: @locale_path('/about', 'fr') is /fr/about. The default locale has no prefix, and a locale prefix already on the path is replaced.

Arguments can be named: @locale_path(…, locale: …).

Example
<a href="{ @locale_path($request.path, 'fr') }">Français</a>
a(href: @locale_path($request.path, 'fr')) "Français"

#@max(values...) → any

The largest of the arguments (or of one list).
Example
<echo>{ @max(4, 9, 2) }</echo>
echo @max(4, 9, 2)

#@min(values...) → any

The smallest of the arguments (or of one list).
Example
<echo>{ @min(4, 9, 2) }</echo>
echo @min(4, 9, 2)

#@now() → date

The current date and time.
Example
<echo>{ @now()->format('d MMMM yyyy') }</echo>
echo @now()->format('d MMMM yyyy')

#@parse_env(text) → map

Parses .env text (NAME=value lines) into a map. ${NAME} uses earlier lines or the environment.
Example
<echo>{ @parse_env('PORT=8080').PORT }</echo>
echo @parse_env('PORT=8080').PORT

#@plural(count, locale?) → string

The plural category of a number in a language: zero, one, two, few, many or other.

Arguments can be named: @plural(…, locale: …).

Example
<echo>{ [0, 1, 5]->map(fn(n) => @plural($n)) }</echo>
echo [0, 1, 5]->map(fn(n) => @plural($n))

#@range(start, end?, step?) → list

Numbers from start up to (not including) end; with one argument, from 0. start..end is the short form when the step is 1.

Arguments can be named: @range(…, end: …, step: …).

Example
<echo>{ @range(1, 10, step: 3) }</echo>
echo @range(1, 10, step: 3)

#@retry(times: number, work: fn, backoff?: duration, when?: fn) → any

Calls work, and calls it again when it throws, up to times calls in all; returns what it returns, or throws the last error. backoff waits between calls; when, given the error, says whether to try again: @retry(3, fn() => @api($url), backoff: 1s, when: fn(err) => $err.type == 'Timeout'). Work is given the attempt, 1 for the first.
ParameterTakes
times requirednumber
work requiredfn
backoff optionalduration
when optionalfn

Arguments can be named: @retry(…, work: …, backoff: …).

Example
<fn name="flaky" params="attempt: int">
  <if test="$attempt lt 3"><throw message="busy" type="Timeout" /></if>
  <return value="'worked on try ' + $attempt" />
</fn>
<echo>{ @retry(3, @flaky) }</echo>
fn flaky(attempt: int) {
  if $attempt < 3 {
    throw Timeout "busy"
  }
  return 'worked on try ' + $attempt
}
echo @retry(3, @flaky)

#@secure_equals(a: string, b: string) → bool

True when two secrets, such as a webhook signature and the one you worked out, are the same. Takes the same time however much of them matches, so it gives nothing away.
ParameterTakes
a requiredstring
b requiredstring

Arguments can be named: @secure_equals(…, b: …).

Example
<echo>{ @secure_equals('payload'->hmac('secret'), 'payload'->hmac('secret')) }</echo>
echo @secure_equals('payload'->hmac('secret'), 'payload'->hmac('secret'))

#@set_exchange_rate(from: currency, to: currency, rate: number)

Sets a rate for this run. One unit of from buys rate units of to. Overrides the project's money.exchange_rates entry for this direction.
ParameterTakes
from requiredcurrency
to requiredcurrency
rate requirednumber

Arguments can be named: @set_exchange_rate(…, to: …, rate: …).

Example
<echo>{ @set_exchange_rate(from: 'EUR', to: 'GBP', rate: 0.80) }</echo>
echo @set_exchange_rate(from: 'EUR', to: 'GBP', rate: 0.80)

#@slugify(text: string) → slug

Turns text into a slug: 'Hello, World!' gives hello-world. Accents are dropped.
ParameterTakes
text requiredstring
Example
<echo>{ @slugify('Crème Brûlée recipes!') }</echo>
echo @slugify('Crème Brûlée recipes!')

#@t(key, values?, locale?) → string

The translation of a key in the current locale (from locales/fr.json and so on), with {name} filled in from values. With values.count, plural forms (one, other, few...) are picked for the language.

Arguments can be named: @t(…, values: …, locale: …).

Example
<let name="items" value="[1, 2, 3]" />
<echo>{ @t('cart.items', { count: $items->count() }) }</echo>
$items = [1, 2, 3]
echo @t('cart.items', { count: $items->count() })

#@today() → date

Today's date, at midnight.
Example
<echo>{ @today()->format('yyyy-MM-dd HH:mm') }</echo>
echo @today()->format('yyyy-MM-dd HH:mm')

#@uuid(v?: int, name?: string, namespace?: string) → uuid

A new UUID. Version 4 (the default) is random. Version 7 starts with the time, so newer ones sort later and sit together in a database index; its .timestamp gives the time back. Version 8 is custom: with a name it is a SHA-256 hash of the namespace and the name, so the same name always gives the same UUID; without one it starts with the time, so newer ones sort later.
ParameterTakes
v optionalint
name optionalstring
namespace optionalstring

Arguments can be named: @uuid(…, name: …, namespace: …).

Example
<echo>{ @uuid().version }</echo>
echo @uuid().version

Methods

On string values: ->upper(), ->lower(), ->trim(), ->count(), ->count_of(), ->is_empty(), ->is_blank(), ->contains(), ->starts_with(), ->ends_with(), ->strip(), ->normalize_unicode(), ->replace(), ->split(), ->lines(), ->chars(), ->index_of(), ->repeat(), ->reverse(), ->first(), ->last(), ->slice(), ->truncate(), ->pad(), ->capitalize(), ->title(), ->escape(), ->url_encode(), ->url_decode(), ->to_number(), ->to_int(), ->to_bool(), ->to_date(), ->to_base64(), ->from_base64(), ->md5(), ->sha256(), ->sha1(), ->sha512(), ->hmac(), ->case(), ->before(), ->after(), ->squish(), ->words(), ->wrap(), ->mask(), ->is_numeric(), ->matches(), ->find_all(), ->numbers(), ->blocks(), ->grid(), ->shapes()

On number values: ->round(), ->floor(), ->ceil(), ->abs(), ->min(), ->max(), ->bits(), ->clamp(), ->to_date(), ->to_number(), ->to_int(), ->format(), ->increment(), ->decrement(), ->is_even(), ->is_odd(), ->times()

On bool values: ->not()

On list values: ->count(), ->count_of(), ->is_empty(), ->first(), ->last(), ->at(), ->filter(), ->reject(), ->map(), ->flat_map(), ->partition(), ->pluck(), ->find(), ->any(), ->all(), ->each(), ->reduce(), ->sort(), ->max(), ->min(), ->sum(), ->average(), ->group_by(), ->reverse(), ->join(), ->contains(), ->index_of(), ->slice(), ->take(), ->skip(), ->unique(), ->push(), ->prepend(), ->insert(), ->pop(), ->remove(), ->remove_at(), ->flatten(), ->chunk(), ->zip(), ->to_map(), ->difference(), ->intersect(), ->union(), ->count_by(), ->common(), ->take_while(), ->skip_while(), ->window(), ->split(), ->replace_at(), ->only(), ->without(), ->numbers(), ->product(), ->combinations(), ->permutations(), ->scan(), ->cells(), ->positions_of(), ->rotate(), ->shapes()

On map values: ->keys(), ->values(), ->entries(), ->has(), ->get(), ->set(), ->remove(), ->merge(), ->pick(), ->omit(), ->deep_merge(), ->count(), ->is_empty(), ->map(), ->filter(), ->reject(), ->any(), ->all(), ->find(), ->reduce(), ->map_keys(), ->sort()

On date values: ->format(), ->add(), ->subtract(), ->date(), ->iso(), ->timestamp(), ->start_of(), ->end_of(), ->since(), ->is_same()

On fn values: ->call()

On any values: ->convert(), ->from(), ->to(), ->type(), ->to_string(), ->is_null(), ->or(), ->is_a()

On type values: ->check(), ->is(), ->schema()

On config values: ->get(), ->has(), ->require(), ->environment(), ->all(), ->sources(), ->reload()

On logger values: ->trace(), ->debug(), ->info(), ->warn(), ->error(), ->fatal(), ->log(), ->with(), ->named(), ->is_enabled(), ->entries(), ->flush()

On error values: ->is(), ->chain()

On password values: ->hash(), ->verify(), ->needs_rehash(), ->strength(), ->is_strong(), ->reveal()

On regex values: ->test(), ->match(), ->match_all(), ->replace(), ->split()

On url values: ->with(), ->without(), ->join()

On domain values: ->is_subdomain_of(), ->ascii()

On ip values: ->in()

On cidr values: ->contains()

On slash_path values: ->join(), ->is_within()

On semver values: ->compare(), ->satisfies(), ->bump()

On semver[] values: ->latest()

On mime values: ->is()

On hex values: ->to_number()

On base64 values: ->decode()

On csv values: ->cells(), ->save()

On phone values: ->tel()

On currency values: ->format()

On locale values: ->format()

On timezone values: ->offset(), ->now(), ->convert(), ->is_dst()

On duration values: ->iso(), ->after(), ->before(), ->add(), ->subtract()

On date_format values: ->format(), ->parse()

On cron values: ->next(), ->next_times()

On color values: ->rgb(), ->hex(), ->css(), ->mix(), ->lighten(), ->darken(), ->contrast_ratio()

On iban values: ->formatted()

On card values: ->reveal()

On money values: ->add(), ->subtract(), ->format(), ->split(), ->allocate()

On money[] values: ->total()

On set values: ->count(), ->is_empty(), ->contains(), ->add(), ->remove(), ->union(), ->intersect(), ->difference(), ->is_subset(), ->overlaps(), ->all(), ->any(), ->average(), ->count_by(), ->each(), ->filter(), ->find(), ->group_by(), ->join(), ->map(), ->max(), ->min(), ->reduce(), ->reject(), ->sort(), ->sum()

On formatted_file values: ->find(), ->replace(), ->insert(), ->save()

Variables

VariableTypeDescription
$argslistThe command line arguments after the script path.
$configconfigThe project's settings: the "config" section of kscript.json, with kscript.<env>.json and config.kscript laid over it: $config.database.host.
$envmapEnvironment variables: $env.HOME, $env['PATH'].
$eventmapThe event a handler runs for, in on-* attributes and <on> blocks: $event.value, $event.key, $event.data... Its fields depend on the handler.
$logloggerThe script's logger: $log->info('Saved', { id: $id }), $log->named('db')->debug(...). Providers and levels come from $config.logging.
$osmapThe computer: $os.name (windows, macos or linux), $os.user, $os.machine, $os.home, $os.temp, $os.separator, $os.newline.
$scriptmapThis script: $script.path, $script.dir, $script.name.