JavaScript built-in classes wrapped for use in @ps.javascript decorated functions. These classes transpile to their JavaScript equivalents with new constructors and static methods.
from pulse.js import (
AbortController,
AbortSignal,
Animation,
Array,
ArrayBuffer,
BigInt64Array,
BigUint64Array,
Blob,
CustomEvent,
DataView,
Date,
DOMParser,
DocumentTimeline,
Error,
File,
FileReader,
Float32Array,
Float64Array,
FormData,
Headers,
Int16Array,
Int32Array,
Int8Array,
IntersectionObserver,
KeyframeEffect,
Map,
MutationObserver,
Number,
Object,
PerformanceObserver,
Promise,
RegExp,
Request,
ResizeObserver,
Response,
Set,
String,
TextDecoder,
TextEncoder,
Uint16Array,
Uint32Array,
Uint8Array,
Uint8ClampedArray,
URL ,
URLSearchParams,
WeakMap,
WeakSet,
XMLSerializer,
)
JavaScript Array - a generic indexed collection.
from pulse.js import Array
@ps.javascript
def example ():
arr = Array( 10 ) # -> new Array(10)
arr = Array( 1 , 2 , 3 ) # -> new Array(1, 2, 3)
Method Description Array.isArray(value)Check if value is an array Array.from_(iterable)Create array from iterable (note the underscore) Array.from_(iterable, mapFn)Create array with mapping function Array.of(*elements)Create array from arguments
Property Description lengthNumber of elements
These modify the array in place:
Method Description push(*items)Add items to end, return new length pop()Remove and return last item shift()Remove and return first item unshift(*items)Add items to start, return new length splice(start, deleteCount, *items)Remove/replace elements reverse()Reverse in place sort(compareFn=None)Sort in place fill(value, start=0, end=None)Fill with value copyWithin(target, start=0, end=None)Copy within array
These return new arrays or values:
Method Description concat(*items)Merge arrays/values slice(start=0, end=None)Return portion join(separator=",")Join to string indexOf(element, fromIndex=0)First index of element lastIndexOf(element, fromIndex=None)Last index of element includes(element, fromIndex=0)Check if contains at(index)Get at index (supports negative) flat(depth=1)Flatten nested arrays flatMap(callback)Map then flatten by one level toReversed()Return new reversed array (ES2023) toSorted(compareFn=None)Return new sorted array (ES2023) toSpliced(start, deleteCount, *items)Return new spliced array (ES2023) with_(index, value)Return new array with element replaced (ES2023)
Method Description forEach(callback)Execute for each element map(callback)Create array with mapped values filter(callback)Create array with passing elements reduce(callback, initialValue=None)Reduce to single value (left to right) reduceRight(callback, initialValue=None)Reduce right to left find(callback)First element passing test findIndex(callback)Index of first passing element findLast(callback)Last element passing test (ES2023) findLastIndex(callback)Index of last passing element (ES2023) every(callback)Test if all pass some(callback)Test if any pass keys()Iterator of indices values()Iterator of values entries()Iterator of [index, value] pairs
from pulse.js import Array
@ps.javascript
def process_items (items):
# Filter and map
result = Array.from_(items).filter(
lambda x, i, arr: x > 0
).map(
lambda x, i, arr: x * 2
)
# Reduce
total = result.reduce( lambda acc, x, i, arr: acc + x, 0 )
return total
JavaScript Date - date and time handling.
from pulse.js import Date
@ps.javascript
def example ():
now = Date() # -> new Date()
specific = Date( "2024-01-15" ) # -> new Date("2024-01-15")
timestamp = Date.now() # -> Date.now()
Method Description Date.now()Current timestamp in milliseconds Date.parse(dateString)Parse date string to timestamp Date.UTC(year, month, ...)Create UTC timestamp
Method Description getDate()Day of month (1-31) getDay()Day of week (0-6) getFullYear()Four-digit year getHours()Hours (0-23) getMilliseconds()Milliseconds (0-999) getMinutes()Minutes (0-59) getMonth()Month (0-11) getSeconds()Seconds (0-59) getTime()Timestamp in milliseconds getTimezoneOffset()UTC offset in minutes
UTC variants: getUTCDate(), getUTCDay(), getUTCFullYear(), etc.
Method Description setDate(date)Set day of month setFullYear(year, month?, date?)Set year setHours(hours, min?, sec?, ms?)Set hours setMilliseconds(ms)Set milliseconds setMinutes(min, sec?, ms?)Set minutes setMonth(month, date?)Set month setSeconds(sec, ms?)Set seconds setTime(time)Set timestamp
UTC variants: setUTCDate(), setUTCFullYear(), etc.
Method Description toDateString()Date portion as string toISOString()ISO 8601 format toJSON()JSON representation toLocaleDateString(locales?, options?)Locale date string toLocaleString(locales?, options?)Locale date/time string toLocaleTimeString(locales?, options?)Locale time string toString()Full string representation toTimeString()Time portion as string toUTCString()UTC string valueOf()Primitive value (timestamp)
JavaScript Error types for error handling.
from pulse.js import Error, throw
from pulse.js.error import TypeError , RangeError, ReferenceError
@ps.javascript
def example ():
throw(Error( "Something went wrong" ))
throw( TypeError ( "Expected a string" ))
Property/Method Description messageError message nameError type name stackStack trace (if available) toString()String representation
All error types have the same interface as Error:
Error - Base error
TypeError - Type mismatch
RangeError - Value out of range
ReferenceError - Invalid reference
SyntaxError - Syntax error
EvalError - Eval error
URIError - URI handling error
The throw function converts to a JavaScript throw statement:
from pulse.js import Error, throw
@ps.javascript
def validate (value):
if value < 0 :
throw(RangeError( "Value must be non-negative" ))
return value
JavaScript Map - a key-value collection that preserves insertion order.
from pulse.js import Map
@ps.javascript
def example ():
m = Map() # -> new Map()
m = Map([[ "a" , 1 ], [ "b" , 2 ]]) # -> new Map([["a", 1], ["b", 2]])
Property Description sizeNumber of entries
Method Description clear()Remove all entries delete(key)Remove entry, return True if existed get(key)Get value for key has(key)Check if key exists set(key, value)Set entry, return Map for chaining forEach(callback)Execute for each entry keys()Iterator of keys values()Iterator of values entries()Iterator of [key, value] pairs
from pulse.js import Map
@ps.javascript
def build_lookup (items):
lookup = Map()
for item in items:
lookup.set(item.id, item)
if lookup.has( "abc" ):
return lookup.get( "abc" )
return None
JavaScript Number - numeric utilities.
from pulse.js import Number
@ps.javascript
def example ():
Number.isFinite( 42 ) # -> Number.isFinite(42)
Number. MAX_SAFE_INTEGER # -> Number.MAX_SAFE_INTEGER
Constant Description EPSILONSmallest difference between numbers MAX_SAFE_INTEGERMaximum safe integer (2^53 - 1) MIN_SAFE_INTEGERMinimum safe integer MAX_VALUEMaximum representable number MIN_VALUEMinimum positive number NaNNot-a-Number NEGATIVE_INFINITYNegative infinity POSITIVE_INFINITYPositive infinity
Method Description isFinite(value)Check if finite number isInteger(value)Check if integer isNaN(value)Check if NaN isSafeInteger(value)Check if safe integer parseFloat(string)Parse float from string parseInt(string, radix=10)Parse integer from string
JavaScript Object utilities - static methods for object manipulation.
from pulse.js import Object
@ps.javascript
def example ():
keys = Object.keys(data) # -> Object.keys(data)
merged = Object.assign({}, a, b) # -> Object.assign({}, a, b)
Method Description assign(target, *sources)Copy properties to target create(proto, properties?)Create with prototype defineProperty(obj, prop, descriptor)Define property defineProperties(obj, props)Define multiple properties entries(obj)Array of [key, value] pairs freeze(obj)Prevent modifications fromEntries(entries)Create from [key, value] pairs getOwnPropertyDescriptor(obj, prop)Get property descriptor getOwnPropertyDescriptors(obj)Get all descriptors getOwnPropertyNames(obj)All own property names getOwnPropertySymbols(obj)All own Symbol properties getPrototypeOf(obj)Get prototype hasOwn(obj, prop)Check own property is_(value1, value2)SameValue comparison (note underscore) isExtensible(obj)Check if extensible isFrozen(obj)Check if frozen isSealed(obj)Check if sealed keys(obj)Array of enumerable keys preventExtensions(obj)Prevent adding properties seal(obj)Prevent adding/removing properties setPrototypeOf(obj, prototype)Set prototype values(obj)Array of enumerable values groupBy(items, keyFn)Group items by key (ES2024)
JavaScript Promise - async operation handling.
from pulse.js import Promise
@ps.javascript
async def example ():
result = await Promise.resolve( 42 )
data = await fetch( "/api/data" )
Promise( lambda resolve, reject: ... )
Method Description resolve(value?)Create resolved promise reject(reason)Create rejected promise all(iterable)Wait for all to resolve allSettled(iterable)Wait for all to settle any(iterable)First to fulfill race(iterable)First to settle withResolvers()Create with exposed resolve/reject (ES2024)
Method Description then(onFulfilled?, onRejected?)Attach handlers catch(onRejected)Attach rejection handler finally_(onFinally)Attach settlement handler (note underscore)
Promise supports Python's await syntax:
@ps.javascript
async def fetch_data ():
response = await fetch( "/api/data" )
data = await response.json()
return data
URL parser and serializer.
from pulse.js import URL
@ps.javascript
def example ():
url = URL( "https://example.com?foo=1#section" )
return url.href, url.searchParams.toString()
Property Description hrefFull URL string originScheme + host + port protocolScheme (e.g. "https:") usernameUsername passwordPassword hostHost + port hostnameHost without port portPort pathnamePath searchQuery string with leading ? hashFragment with leading # searchParamsURLSearchParams instance
Method Description toString()Serialize to string (same as href) toJSON()JSON serialization
Query string utility.
from pulse.js import URLSearchParams
@ps.javascript
def example ():
params = URLSearchParams( "foo=1&bar=2" )
params.append( "bar" , "3" )
return params.toString()
Property Description sizeTotal number of params
Method Description append(name, value)Add a parameter delete(name, value=None)Remove parameter(s) get(name)First value getAll(name)All values has(name, value=None)Check for param set(name, value)Set and replace sort()Sort by key toString()Serialize entries()Iterator of pairs keys()Iterator of keys values()Iterator of values
Abort async operations via signals.
from pulse.js import AbortController
@ps.javascript
def example ():
controller = AbortController()
controller.abort()
return controller.signal.aborted
Property Description signalAbortSignal instance
Method Description abort()Trigger abort
Property/Method Description abortedTrue if aborted onabortEvent handler throwIfAborted()Throw if aborted
Headers, Request, Response, and fetch().
from pulse.js import Headers, Request, fetch, obj
@ps.javascript
def example ():
headers = Headers()
headers.set( "Content-Type" , "application/json" )
req = Request( "/api" , obj( method = "POST" , headers = headers, body = " {} " ))
return fetch(req)
Method Description append(name, value)Add header value delete(name)Remove header get(name)Get first value has(name)Check header set(name, value)Set header forEach(cb, thisArg=None)Iterate
Property Description urlRequest URL methodHTTP method headersHeaders bodyRequest body
Property/Method Description okStatus 2xx statusStatus code headersHeaders bodyBody stream json()Parse JSON text()Read text blob()Read Blob formData()Read FormData arrayBuffer()Read ArrayBuffer
Form-like key/value collection for multipart requests.
from pulse.js import FormData
@ps.javascript
def example ():
data = FormData()
data.append( "name" , "Ada" )
return data.get( "name" )
Method Description append(name, value, filename=None)Append value set(name, value, filename=None)Set value delete(name)Remove key get(name)First value getAll(name)All values has(name)Check key entries()Iterator of pairs keys()Iterator of keys values()Iterator of values forEach(cb, thisArg=None)Iterate
Binary data container.
from pulse.js import Blob, obj
@ps.javascript
def example ():
blob = Blob([ "hello" ], obj( type = "text/plain" ))
return blob.size
Property Description sizeSize in bytes typeMIME type
Method Description arrayBuffer()Read as ArrayBuffer bytes()Read as Uint8Array slice(start=None, end=None, contentType=None)Slice stream()ReadableStream text()Read as text
Blob with name/metadata.
from pulse.js import File, obj
@ps.javascript
def example ():
f = File([ "hello" ], "note.txt" , obj( type = "text/plain" ))
return f.name
Property Description nameFile name lastModifiedLast modified timestamp webkitRelativePathRelative path (if any)
Reads File/Blob contents.
from pulse.js import FileReader
@ps.javascript
def example (blob):
reader = FileReader()
reader.readAsText(blob)
return reader.result
Method Description readAsText(blob, encoding=None)Read as text readAsArrayBuffer(blob)Read as ArrayBuffer
UTF-8 encode/decode helpers.
from pulse.js import TextEncoder, TextDecoder
@ps.javascript
def example (text: str ):
enc = TextEncoder()
data = enc.encode(text)
dec = TextDecoder( "utf-8" )
return dec.decode(data)
Property/Method Description encodingAlways "utf-8" encode(string="")Encode to Uint8Array encodeInto(string, destination)Encode into buffer
Property/Method Description encodingDecoder encoding fatalFatal mode ignoreBOMIgnore BOM decode(input=None, options=None)Decode bytes
Binary buffers and views.
from pulse.js import ArrayBuffer, Uint8Array
@ps.javascript
def example ():
buf = ArrayBuffer( 8 )
view = Uint8Array(buf)
return buf.byteLength, view.byteLength
Property/Method Description byteLengthSize in bytes slice(begin=0, end=None)Copy range isView(value)Check view
Property Description bufferBacking buffer byteLengthView length byteOffsetView offset
Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,
Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array,
BigUint64Array.
Observe element visibility changes.
from pulse.js import IntersectionObserver, obj
@ps.javascript
def example (target):
observer = IntersectionObserver( lambda entries, obs: None , obj( threshold = 0.5 ))
observer.observe(target)
Method Description observe(target)Start observing unobserve(target)Stop observing target disconnect()Stop all observations takeRecords()Pending entries
Observe element size changes.
from pulse.js import ResizeObserver, obj
@ps.javascript
def example (target):
observer = ResizeObserver( lambda entries, obs: None )
observer.observe(target, obj( box = "border-box" ))
Method Description observe(target, options=None)Start observing unobserve(target)Stop observing target disconnect()Stop all observations
Observe performance entry events.
from pulse.js import PerformanceObserver, obj
@ps.javascript
def example ():
observer = PerformanceObserver( lambda list_, obs: None )
observer.observe(obj( entryTypes = [ "mark" , "measure" ]))
Method Description observe(options)Start observing disconnect()Stop observing takeRecords()Pending entries
The Web Animations API lets you create smooth, performant animations from Python code. Unlike CSS animations, you get programmatic control—pause, reverse, seek to any point, or chain animations with promises.
from pulse.js import Animation, KeyframeEffect, document, obj
@ps.javascript
def fade_in (element):
# Define what animates: target element, keyframes, and timing
effect = KeyframeEffect(
element,
[obj( opacity = 0 ), obj( opacity = 1 )], # From invisible to visible
obj( duration = 300 , easing = "ease-out" , fill = "forwards" ),
)
# Create and start the animation
animation = Animation(effect, document.timeline)
animation.play()
return animation
Use it when you need to:
Control animations from code (pause, reverse, speed up)
Wait for an animation to finish before doing something else
Animate based on runtime values (user input, scroll position)
Coordinate multiple animations
For simple hover effects or static transitions, CSS is usually simpler.
Defines what gets animated. Pass a target element, keyframes, and timing options.
effect = KeyframeEffect(
target, # Element to animate
[obj( opacity = 0 ), obj( opacity = 1 )], # Keyframes (array of states)
obj( duration = 300 , easing = "ease-in-out" ), # Timing options
)
Keyframes are an array of style states. The animation interpolates between them:
# Slide and fade in
[
obj( opacity = 0 , transform = "translateY(-20px)" ),
obj( opacity = 1 , transform = "translateY(0)" ),
]
# Bounce effect (multiple keyframes)
[
obj( transform = "scale(1)" ),
obj( transform = "scale(1.2)" ),
obj( transform = "scale(1)" ),
]
Timing options control how the animation plays:
Option Description durationLength in milliseconds (e.g., 300) easingTiming function: "linear", "ease", "ease-in", "ease-out", "ease-in-out", or a cubic-bezier fillWhat happens when animation ends: "none", "forwards" (keep end state), "backwards", "both" iterationsHow many times to repeat (use Infinity for forever) direction"normal", "reverse", "alternate", "alternate-reverse"delayWait before starting (milliseconds) endDelayWait after ending (milliseconds) iterationStartOffset into the iteration to start at (0-1)
Property Description targetThe element being animated compositeHow values combine with underlying styles iterationCompositeHow values accumulate across iterations pseudoElementTarget pseudo-element (e.g., "::before")
Method Description getTiming()Get current timing options getComputedTiming()Get computed values including progress getKeyframes()Get the computed keyframes setKeyframes(keyframes)Replace keyframes mid-animation updateTiming(timing)Update timing options mid-animation
Controls playback of a KeyframeEffect. Think of it like a video player for your effect.
animation = Animation(effect, document.timeline)
animation.play() # Start it
Property Description currentTimeCurrent position in milliseconds (read/write) playState"idle", "running", "paused", "finished"playbackRateSpeed multiplier (1 = normal, 2 = double speed, -1 = reverse) finishedPromise that resolves when animation completes readyPromise that resolves when animation is ready to play pendingTrue if play/pause is pending startTimeWhen animation started on the timeline effectThe KeyframeEffect being played (read/write) timelineThe timeline this animation is attached to (read/write) idAnimation identifier string (read/write) replaceState"active", "removed", or "persisted"overallProgressProgress across all iterations (0-1)
Method Description play()Start or resume playback pause()Pause at current position reverse()Play backwards from current position finish()Jump to end (or start if reversed) cancel()Stop and reset to initial state commitStyles()Write current animated values to element's style persist()Prevent automatic removal when finished updatePlaybackRate(rate)Smoothly change speed without jumping
The finished promise lets you chain actions:
@ps.javascript
async def animate_then_remove (element):
effect = KeyframeEffect(
element,
[obj( opacity = 1 ), obj( opacity = 0 )],
obj( duration = 200 , fill = "forwards" ),
)
animation = Animation(effect, document.timeline)
animation.play()
# Wait for fade out to complete
await animation.finished
# Now safe to remove
element.remove()
The default timeline tied to document.timeline. You rarely need to create one yourself, but you can for custom timing:
from pulse.js import DocumentTimeline
# Custom timeline with offset origin
timeline = DocumentTimeline(obj( originTime = 1000 ))
animation = Animation(effect, timeline)
Property Description currentTimeCurrent time on this timeline (milliseconds since origin)
Learn more: Animation (MDN) , KeyframeEffect (MDN)
Parse and serialize DOM.
from pulse.js import DOMParser, XMLSerializer
@ps.javascript
def example (source: str ):
parser = DOMParser()
doc = parser.parseFromString(source, "text/html" )
serializer = XMLSerializer()
return serializer.serializeToString(doc)
Method Description parseFromString(string, mimeType)Parse DOM
Method Description serializeToString(root)Serialize DOM
Custom event with detail.
from pulse.js import CustomEvent, obj
@ps.javascript
def example ():
event = CustomEvent( "ping" , obj( detail = obj( ok = True )))
return event.detail
Property Description detailCustom payload
Observe DOM changes in the browser.
from pulse.js import MutationObserver, obj
@ps.javascript
def example (target):
observer = MutationObserver( lambda records, obs: None )
observer.observe(target, obj( childList = True , subtree = True ))
Method Description observe(target, options)Start observing DOM mutations disconnect()Stop observing takeRecords()Return pending mutation records
Option Description childListWatch for child node additions/removals attributesWatch for attribute changes characterDataWatch for text changes subtreeInclude all descendants attributeOldValueRecord previous attribute value characterDataOldValueRecord previous text value attributeFilterList of attribute names to watch
JavaScript RegExp - regular expressions.
from pulse.js import RegExp
@ps.javascript
def example ():
pattern = RegExp( r " \d + " , "g" ) # -> new RegExp("\\d+", "g")
if pattern.test( "abc123" ):
matches = pattern.exec( "abc123" )
Method Description exec(string)Execute search, return matches or None test(string)Test if pattern matches toString()String representation
Property Description sourcePattern string flagsFlag string globGlobal flag (g) ignoreCaseCase-insensitive flag (i) multilineMultiline flag (m) dotAllDot-all flag (s) unicodeUnicode flag (u) stickySticky flag (y) lastIndexNext search start index
JavaScript Set - a collection of unique values.
from pulse.js import Set
@ps.javascript
def example ():
s = Set() # -> new Set()
s = Set([ 1 , 2 , 3 ]) # -> new Set([1, 2, 3])
Property Description sizeNumber of values
Method Description add(value)Add value, return Set for chaining clear()Remove all values delete(value)Remove value, return True if existed has(value)Check if value exists forEach(callback)Execute for each value keys()Iterator of values (same as values) values()Iterator of values entries()Iterator of [value, value] pairs
Method Description union(other)Values in either set intersection(other)Values in both sets difference(other)Values in this but not other symmetricDifference(other)Values in either but not both isSubsetOf(other)Check if subset isSupersetOf(other)Check if superset isDisjointFrom(other)Check if no overlap
JavaScript String constructor and static methods.
from pulse.js import String
@ps.javascript
def example ():
String.fromCharCode( 65 ) # -> String.fromCharCode(65) -> "A"
String.fromCodePoint( 0x 1F600 ) # -> String.fromCodePoint(0x1F600) -> emoji
Method Description fromCharCode(*codes)Create from char codes fromCodePoint(*codePoints)Create from code points raw(template, *substitutions)Raw template literal
JavaScript WeakMap - key-value collection with weak key references.
from pulse.js import WeakMap
@ps.javascript
def example ():
cache = WeakMap()
cache.set(obj, "value" )
Keys must be objects. Entries are garbage collected when keys are no longer referenced.
Method Description delete(key)Remove entry, return True if existed get(key)Get value for key has(key)Check if key exists set(key, value)Set entry, return WeakMap for chaining
JavaScript WeakSet - collection with weak value references.
from pulse.js import WeakSet
@ps.javascript
def example ():
seen = WeakSet()
seen.add(obj)
Values must be objects. Entries are garbage collected when values are no longer referenced.
Method Description add(value)Add value, return WeakSet for chaining delete(value)Remove value, return True if existed has(value)Check if value exists
Create plain JavaScript object literals (not Maps):
from pulse.js import obj
@ps.javascript
def example ():
style = obj( color = "red" , fontSize = "14px" ) # -> { color: "red", fontSize: "14px" }
# With spread
merged = obj( ** base, newKey = "value" ) # -> { ...base, newKey: "value" }
Use obj() when you need a plain JS object, like for React props or style objects. Python dict() transpiles to new Map().
The JavaScript undefined value:
from pulse.js import undefined
@ps.javascript
def example ():
if value is undefined:
return "missing"
Throw JavaScript errors:
from pulse.js import throw, Error
@ps.javascript
def validate (x):
if x < 0 :
throw(Error( "Must be positive" ))