Skip to content

Starlang function reference

The complete catalogue of the 373 functions across 29 modules built into Starlang. For syntax, imports and idioms see the Starlang guide.

Generated from the Starlang manifest (lsp/manifest.json, produced from the stdlib/ builtins), enriched with the module reference pages — so this list stays in lock-step with the language. Regenerate with python3 docs/reference/starlang/generate.py.

Imports

  • Auto-imported modules are in scope in every transform — call their functions directly.
  • Other modules need an import. Three forms: import * from sl::core::Dates (all, bare), import addDays, formatTime from sl::core::Dates (specific), or import sl::core::Dates (namespaced — call as Dates::addDays(...)).

sl::Runtime · auto-imported

Function Signature Description
dataFormatsDescriptor () Array of supported formats
eval (str) Look up variable by name in env
evalUrl (url) Stub, returns null
fail (msg) Throw RuntimeError with message
failIf (cond, msg) Throw if condition is truthy
findDataFormatDescriptorByMime (mime) Format descriptor or null
location () {file, line, column}
locationString () Location as string
orElse (val, fallback) Return val if not null/error, else fallback
orElseTry (fn1, fn2) Try fn1; if error, return fn2()
prop (key) Get environment variable or null
props () All env vars as Object
run (url, props, body) Stub, returns null
runUrl (url, props, body) Stub, returns null
try (fn) Execute fn, return {success, result\|error}
version () Returns "starlang/2.0"
wait (ms) Sleep for ms milliseconds

sl::ai::Extract · auto-imported

Function Signature Description
cleanOCR (text, options?): String Clean and normalize OCR-extracted text
extractAddresses (text): Array Extract US-style street addresses
extractDates (text): Array Extract date strings in common formats
extractKeyValuePairs (text, options?): Array Extract key-value pairs from structured text
extractListItems (text): Array Extract bulleted and numbered list items
extractNumbers (text): Array Extract numeric values including currencies and suffixed numbers
extractPhoneNumbers (text): Array Extract phone numbers in various formats
extractSections (text, options?): Array Extract document sections by headers
extractTables (text): Array Extract tables from text (pipe-delimited and whitespace-aligned)

sl::ai::Schema · auto-imported

Function Signature Description
aggregateUsage (usages): Object Sum multiple usage objects
assistantMessage (content): Object Create assistant message
buildContext (messages, options?): String Build conversation context for prompts
coerceToSchema (obj, schema): Object Coerce object to match schema types
contentFilter (content, rules): Object Filter content against rules
conversationWindow (messages, maxTokens): Array Keep recent messages in budget
estimateCost (usage, model?): Object Estimate token cost
extractCodeBlocks (text): Array Extract code blocks with language tags
extractJson (text): Array Extract and parse JSON from text
extractModel (response): String Extract model name
extractPlainText (response): String Extract plain text, removing markup
extractStopReason (response): String Extract stop reason
extractStructured (text, format?): Array Extract structured data (json/xml/csv)
extractText (response): String Extract plain text content
extractToolCalls (response): Array Extract tool calls from LLM response
extractUsage (response): Object Extract token usage {input, output, total}
extractXml (text): Array Extract XML elements from text
hasToolUse (response): Boolean Check if response contains tool use
isValid (obj, schema): Boolean Check validity (boolean)
jsonSchema (obj): Object Generate JSON schema from object
mapSchema (schema, mapping): Object Transform schema fields
mergeSchemas (schemas): Object Merge multiple schemas
messageOf (role, content): Object Create chat message
normalizeResponse (response): Object Normalize across LLM providers
parseJsonOrFix (text): Any Parse JSON or attempt to fix invalid JSON
parseResponse (response): Object Parse into normalized format
promptTemplate (template, vars): String Render prompt template
splitResponse (response): Object Split into text and tool calls
systemMessage (content): Object Create system message
toolDef (name, description, schema): Object Define AI tool with input schema
toolResult (toolUseId, result): Object Create tool result response
userMessage (content): Object Create user message
validate (obj, schema): Object Validate object against JSON schema

sl::ai::Text · auto-imported

Function Signature Description
charCount (text): Number Count UTF-8 characters
chunk (text, options?): Array Split text by strategy with size/overlap
chunkByMarkdownHeaders (text, options?): Array Chunk markdown by headers
chunkByTokens (text, maxTokens, overlap?): Array Chunk respecting token limits
detectPII (text): Array Detect PII patterns
extractEmails (text): Array Extract all email addresses
extractUrls (text): Array Extract all URLs
keywords (text, options?): Array Extract top keywords by frequency
ngrams (text, n?): Array Generate n-grams
normalize (text, options?): String Clean and normalize text
paragraphSplit (text): Array Split text by paragraph breaks
pruneMessages (messages, maxTokens): Array Keep first + recent messages within budget
redactPII (text, options?): String Redact PII from text
removeStopWords (text, lang?): String Remove common stop words
sentenceSplit (text): Array Split text into sentences
similarity (a, b): Number Jaccard similarity (0--1)
slidingWindow (text, windowSize, step?): Array Create sliding windows of text
slidingWindowMessages (messages, maxTokens): Array Sliding window of messages within budget
stripMarkdown (text): String Remove markdown formatting
template (tmpl, vars): String Render template with variables
tokenCount (text): Number Estimate token count
truncateTokens (text, maxTokens): String Truncate text to token limit
wordCount (text): Number Count words

sl::core::Arrays · auto-imported

Function Signature Description
countBy (arr, fn) Count elements matching predicate
divideBy (arr, n) Chunk into groups of n
drop (arr, n) Drop first n elements
dropWhile (arr, fn) Drop while predicate is true
every (arr, fn) All elements match?
firstWith (arr, fn) First matching element or null
indexOf (arr, val) Index of first occurrence or -1
indexWhere (arr, fn) Index of first match or -1
join (a, b, fnA, fnB) Inner join on key functions
leftJoin (a, b, fnA, fnB) Left join
outerJoin (a, b, fnA, fnB) Full outer join
partition (arr, fn) {pass: [...], fail: [...]}
slice (arr, from, until) Slice (exclusive end)
some (arr, fn) Any element matches?
splitAt (arr, n) {l: first n, r: rest}
splitWhere (arr, fn) Split at first truthy element
sumBy (arr, fn) Sum of fn results
take (arr, n) First n elements
takeWhile (arr, fn) Take while predicate is true

sl::core::Numbers · auto-imported

Function Signature Description
fromBinary (str) "1010" -> 10
fromHex (str) "0xFF" -> 255
fromRadixNumber (str, radix) Parse string in base 2-36
toBinary (n) 10 -> "1010"
toHex (n) 255 -> "ff"
toRadixNumber (n, radix) Convert to base 2-36

sl::core::Objects · auto-imported

Function Signature Description
divideBy (obj, n) Chunk fields into n-field sub-objects
entrySet (obj) Array of {key, value}
everyEntry (obj, fn) All entries match fn(val, key)?
keySet (obj) Array of Key objects
mergeWith (a, b, fn) Merge with conflict resolver fn(existing, incoming)
nameSet (obj) Array of string key names
someEntry (obj, fn) Any entry matches?
takeWhile (obj, fn) Keep entries while fn is true
valueSet (obj) Array of values

sl::core::Strings · auto-imported

Function Signature Description
appendIfMissing (str, suffix) Append suffix if not already present
camelize (str) "my-var" -> "myVar"
capitalize (str) "hello world" -> "Hello World"
charCode (str) Unicode codepoint of first char
charCodeAt (str, idx) Codepoint at position
collapse (str) Collapse whitespace runs to single space
countCharactersBy (str, fn) Count chars matching predicate
countMatches (str, sub) Count non-overlapping occurrences
dasherize (str) "myVar" -> "my-var"
everyCharacter (str, fn) All chars match predicate?
first (str, n) First n characters
fromCharCode (code) Character from codepoint
hammingDistance (s1, s2) Hamming distance (same-length strings)
isAlpha (str) All alphabetic?
isAlphanumeric (str) All alphanumeric?
isLowerCase (str) All lowercase?
isNumeric (str) All digits?
isUpperCase (str) All uppercase?
isWhitespace (str) All whitespace?
last (str, n) Last n characters
leftPad (str, size[, pad]) Left-pad to size
levenshteinDistance (s1, s2) Edit distance
lines (str) Split on newlines
mapString (str, fn) Map over characters ($=char, $$=idx)
ordinalize (n) 1 -> "1st", 2 -> "2nd"
pluralize (str) English plural
prependIfMissing (str, prefix) Prepend if not already present
remove (str, sub) Remove all occurrences
repeat (str, n) Repeat n times
replaceAll (str, regex, repl) Replace all regex matches
reverse (str) Reverse string
rightPad (str, size[, pad]) Right-pad to size
singularize (str) English singular
someCharacter (str, fn) Any char matches predicate?
substring (str, from[, to]) Substring extraction
substringAfter (str, sep) After first occurrence of sep
substringAfterLast (str, sep) After last occurrence
substringBefore (str, sep) Before first occurrence
substringBeforeLast (str, sep) Before last occurrence
substringBy (str, fn) Split where fn returns true
substringEvery (str, n) Chunk into n-char pieces
underscore (str) "myVar" -> "my_var"
unwrap (str, wrapper) Remove wrapper from both ends
withMaxSize (str, max) Truncate to max length
words (str) Split by whitespace
wrapIfMissing (str, wrapper) Wrap both ends if missing
wrapWith (str, prefix, suffix) Wrap with different prefix/suffix

sl::Crypto · import * from sl::Crypto

Function Signature Description
HMACBinary (content, secret, algo) HMAC digest as Binary
HMACWith (content, secret, algo) HMAC digest as hex String
MD5 (content) MD5 hex String
SHA1 (content) SHA-1 hex String
hashWith (content, algorithm) Hash with MD5/SHA1/SHA256/SHA384/SHA512; returns Binary

sl::DTD · import * from sl::DTD

Function Signature Description
docTypeAsString (root[, publicId[, systemId]]) Generate DOCTYPE declaration

sl::Mime · import * from sl::Mime

Function Signature Description
fromString (str) Parse MIME type string -> {type, subtype, parameters}
isHandledBy (mime, format) Check if MIME matches format name
toString (obj) MIME object -> string

sl::System · import * from sl::System

Function Signature Description
envVar (name) Get environment variable or null
envVars () All environment variables as Object

sl::Types · import * from sl::Types

Function Signature Description
arrayItem (type) Element type of an Array type
baseTypeOf (val) Returns Type descriptor for the value
functionParamTypes (type) Function parameter types — always empty (stub; no param type info)
functionReturnType (type) Function return type — always Any (stub)
intersectionItems (type) Members of an Intersection type — always empty (stub)
isAnyType () Always true
isArrayType () Array
isBinaryType () Binary
isBooleanType () Boolean
isDateTimeType () DateTime
isDateType () Date
isFunctionType () Function
isIntersectionType () Intersection type — always false (stub)
isKeyType () Key
isLiteralType () Literal type — always false (stub)
isLocalDateTimeType () LocalDateTime
isLocalTimeType () LocalTime
isNamespaceType () Namespace
isNothingType () Nothing type — always false (stub)
isNullType () Null
isNumberType () Number
isObjectType () Object
isPeriodType () Period
isRangeType () Range
isReferenceType () Reference type — always false (stub)
isRegexType () Regex
isStringType () String
isTimeType () Time
isTimeZoneType () TimeZone
isTypeType () Type
isURIType () URI
isUnionType () Union type — always false (stub; unions unsupported)
literalValueOf (type) Always null (stub)
metadataOf (val) Metadata object or null
nameOf (type) Type name as String
objectFields (type) Field descriptors of an Object type (else empty array)
unionItems (type) Members of a Union type — always empty (stub)

sl::Values · import * from sl::Values

Function Signature Description
attr (obj, key) Get XML attribute value
field (obj, key) Get field value by string key
index (arr, idx) Get element at index (null if OOB)
mask (obj, keys) Remove specified keys
update (obj, path, fn) Deep update by dot-path

sl::ai::DataOps · import * from sl::ai::DataOps

Function Signature Description
dataProfile (arr): Object Profile dataset with statistics per field
deltaDetect (oldData, newData, keyField): Object Detect added, removed, modified, and unchanged records
detectAnomalies (arr, field, options?): Array Detect outliers using z-score or IQR
fillMissing (arr, rules): Array Fill null values with configurable strategies
inferSchema (data): Object Infer schema from data (types, nullable, patterns, stats)
qualityScore (arr, schema?): Object Compute data quality scores
semanticJoin (left, right, leftVecField, rightVecField, options?): Array Join datasets by vector similarity
standardize (value, from, to): Number Convert between measurement units

sl::ai::Http · import * from sl::ai::Http

Function Signature Description
basicAuth (username, password): String Generate Basic auth header value
bearerToken (token): String Generate Bearer token auth header value
buildQueryString (params): String Encode object as URL query string
fetch (url, options?): Object Make HTTP request
fetchBinary (url, options?): Binary Fetch binary data from URL
fetchParallel (requests): Array Execute multiple HTTP requests in parallel
fetchStream (url, options?): Array Stream Server-Sent Events from URL
parseHeaders (headerString): Object Parse HTTP header string into object
parseSSE (text): Array Parse SSE text into event objects
retry (fn, options?): Any Retry a function with exponential backoff

sl::ai::Transform · import * from sl::ai::Transform

Function Signature Description
diffObjects (oldObj, newObj): Object Compute structural diff between two objects
mapBatch (arr, batchSize, fn): Array Process array in batches through a callback
mergeDedupBy (arr1, arr2, keyField): Array Merge two arrays, deduplicating by key field
normalizeFields (obj, mapping): Object Rename and restructure object fields
patchObject (obj, operations): Object Apply JSON Patch-like operations to an object
transposeTable (data): Object/Array Transpose rows to columns or matrix transposition

sl::ai::Vectors · import * from sl::ai::Vectors

Function Signature Description
centroid (vectors): Array Calculate mean centroid of vectors
cosineSimilarity (vecA, vecB): Number Cosine similarity between vectors
dedup (items, vectorField, threshold?): Array Deduplicate by vector similarity
dimension (vec): Number Get vector dimension
dotProduct (vecA, vecB): Number Dot product of vectors
euclideanDistance (vecA, vecB): Number Euclidean distance between vectors
magnitude (vec): Number Magnitude (L2 norm) of vector
manhattanDistance (vecA, vecB): Number Manhattan distance between vectors
ones (n): Array Create vector of ones of size n
randomVec (n): Array Create normalized random vector of size n
rerank (resultSets, options?): Array Reciprocal Rank Fusion reranking
topK (query, candidates, k, options?): Array Find top-K similar candidates
vecAdd (vecA, vecB): Array Add two vectors element-wise
vecChunks (vec, chunkSize): Array Split vector into chunks
vecNormalize (vec): Array Normalize vector to unit length
vecScale (vec, scalar): Array Multiply vector by scalar
vecSubtract (vecA, vecB): Array Subtract two vectors element-wise
zeros (n): Array Create zero vector of size n

sl::core::Binaries · import * from sl::core::Binaries

Function Signature Description
concatWith (b1, b2) Concatenate two Binary values
fromBase64 (str) Decode from base64 to Binary
fromHex (str) Decode from hex to Binary
readLinesWith (bin, charset) Split Binary into lines
toBase64 (binary) Encode to base64 string
toHex (binary) Encode to hex string
writeLinesWith (arr, charset) Join String array to Binary

sl::core::Dates · import * from sl::core::Dates

Function Signature Description
addDays (dt, n) Add n days — preserves the input temporal type; n may be negative
addHours (dt, n) Add n hours
addMinutes (dt, n) Add n minutes
addMonths (dt, n) Add n months
addSeconds (dt, n) Add n seconds
addYears (dt, n) Add n years
atBeginningOfDay (dt) Truncate to midnight
atBeginningOfHour (dt) Truncate to top of hour
atBeginningOfMonth (dt) First day of month
atBeginningOfWeek (dt) Monday of the week
atBeginningOfYear (dt) January 1st
date ({year, month, day}) Construct Date from object
dateTime ({year, month, day, hour, minutes, seconds, timezone?}) Construct DateTime
formatTime (dt, layout) Format any temporal value to a plain string (not pipe-wrapped); same layout options as parseTime
localDateTime ({year, month, day, hour, minutes, seconds}) Construct LocalDateTime
localTime ({hour, minutes, seconds}) Construct LocalTime
parseTime (str, layout) Parse a string to a DateTime. layout is a Go reference layout ("2006-01-02") or a friendly name: date, datetime, rfc3339, time, kitchen
time ({hour, minutes, seconds, timezone?}) Construct Time
today () Today's date
tomorrow () Tomorrow's date
yesterday () Yesterday's date

sl::core::Periods · import * from sl::core::Periods

Function Signature Description
between (d1, d2) Period between two dates
days (n) Period of n days
duration (n) Period of n seconds (decomposed to H:M:S)
hours (n) Period of n hours
minutes (n) Period of n minutes
months (n) Period of n months
period ({years, months, days, hours, minutes, seconds}) Construct from object
seconds (n) Period of n seconds
years (n) Period of n years

sl::core::URL · import * from sl::core::URL

Function Signature Description
compose (uri, params) Append query parameters
decodeURI (str) URL-decode (full URI)
decodeURIComponent (str) URL-decode component
encodeURI (str) URL-encode (full URI)
encodeURIComponent (str) URL-encode component
parseURI (str) Parse URL into component object

sl::gis · import * from sl::gis

Function Signature Description
area (geometry) Area of a polygon, in square meters (always non-negative)
bbox (geometry) Bounding box as [minLon, minLat, maxLon, maxLat]
bearing (pointA, pointB) Initial compass bearing from A to B, 0–360 degrees
centroid (geometry) Centroid point of the geometry
contains (geometry, point) True if the polygon/ring/bounds contains the point
destination (point, bearingDegrees, meters) Point reached from point heading bearing for meters
distance (pointA, pointB) Great-circle distance between two points, in meters
dwithin (pointA, pointB, meters) True if the two points are within meters of each other
geohashDecode (hash) Decode a geohash to its cell-center point
geohashEncode (point, precision) Encode a point to a geohash of the given character precision
geohashNeighbors (hash) The 8 neighbouring cells, ordered N, NE, E, SE, S, SW, W, NW
intersects (geomA, geomB) True if the two geometries' bounds intersect (exact point-in-polygon when one side is a point and the other areal)
length (geometry) Geodesic length of a line (or lines), in meters
parseWKT (text) Parse a WKT string into a GeoJSON-shaped geometry
point (lon, lat) Construct a GeoJSON Point {type, coordinates}
toWKT (geometry) Serialize a geometry to a WKT string
within (point, geometry) True if the point lies inside the geometry (inverse of contains)

sl::module::Multipart · import * from sl::module::Multipart

Function Signature Description
field (name, content) Create form field part
file (name, content[, mime[, filename]]) Create file upload part
form (parts) Assemble multipart form
generateBoundary () Random boundary string (32 chars)

sl::util::Coercions · import * from sl::util::Coercions

Function Signature Description
toArray (val) Value to Array
toBinary (val) Value to Binary
toBoolean (val) "true" / "yes" / "1" -> true
toDate (val) To Date (error on failure)
toDateOrNull (val) To Date or null
toDateTime (val) To DateTime (error on failure)
toDateTimeOrNull (val) To DateTime or null
toLocalDateTime (val) To LocalDateTime
toLocalDateTimeOrNull (val) To LocalDateTime or null
toLocalTime (val) To LocalTime
toLocalTimeOrNull (val) To LocalTime or null
toNumber (val) To Number (error on failure)
toNumberOrNull (val) To Number or null
toPeriod (val) ISO-8601 string to Period
toRegex (val) String to Regex
toString (val) Any to String
toTime (val) To Time
toTimeOrNull (val) To Time or null
toTimeZone (val) String to TimeZone
toURI (val) String to URI object

sl::util::Diff · import * from sl::util::Diff

Function Signature Description
diff (val1, val2) Recursive structural diff

sl::util::Math · import * from sl::util::Math

Function Signature Description
acos (n) Arc cosine
asin (n) Arc sine
atan (n) Arc tangent
cos (n) Cosine
decimalAdd (a, b, scale) Add with precision
decimalDivide (a, b, scale) Divide with precision
decimalMultiply (a, b, scale) Multiply with precision
decimalPow (a, b, scale) Power with precision
decimalRound (n, scale) Round to scale decimal places
decimalSqrt (n, scale) Square root with precision
decimalSubtract (a, b, scale) Subtract with precision
log10 (n) Log base 10
logn (n, base) Log base n
sin (n) Sine
tan (n) Tangent
toDegrees (rad) Radians to degrees
toRadians (deg) Degrees to radians

sl::util::Timer · import * from sl::util::Timer

Function Signature Description
currentMilliseconds () Unix time in milliseconds
duration (fn) Execute fn, return {result, time: ms}
time (fn) Execute fn, return elapsed ms
toMilliseconds (period) Convert Period to milliseconds

sl::util::Tree · import * from sl::util::Tree

Function Signature Description
asExpressionString (val) Value to inspect string
filterArrayLeafs (tree, fn) Filter leaf array elements
filterObjectLeafs (tree, fn) Filter leaf object fields
filterTree (tree, fn) Recursively filter nodes
isArrayType (1 arg) Array
isAttributeType (val) Always false (stub; XML attributes aren't modeled in the tree module)
isObjectType (1 arg) Object
mapLeafValues (tree, fn) Map fn over all leaf scalar values
nodeExists (tree, path) Check if dot-path exists