or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

ast.mdcli.mdcompilation.mdembedded.mdindex.mdlibraries.mdoutput.md

libraries.mddocs/

0

# Built-in Libraries

1

2

Python standard library implementations providing familiar APIs for JavaScript environments. RapydScript-NG includes 11 built-in library modules that replicate Python functionality with JavaScript performance.

3

4

## Capabilities

5

6

### Math Module

7

8

Mathematical functions and constants following Python's math module API.

9

10

```python { .api }

11

# Import in RapydScript source

12

from math import sin, cos, tan, pi, e

13

14

# Mathematical functions

15

def ceil(x: float) -> int:

16

"""Return the ceiling of x as an integer."""

17

18

def floor(x: float) -> int:

19

"""Return the floor of x as an integer."""

20

21

def trunc(x: float) -> int:

22

"""Truncate x to an integer."""

23

24

def fabs(x: float) -> float:

25

"""Return the absolute value of x."""

26

27

def factorial(n: int) -> int:

28

"""Return n factorial as an integer."""

29

30

def fmod(x: float, y: float) -> float:

31

"""Return fmod(x, y) as floating point remainder."""

32

33

def fsum(iterable) -> float:

34

"""Return accurate floating point sum of values."""

35

36

# Exponential and logarithmic functions

37

def exp(x: float) -> float:

38

"""Return e**x (e to the power of x)."""

39

40

def log(x: float, base: float = e) -> float:

41

"""Return the logarithm of x to the given base."""

42

43

def pow(x: float, y: float) -> float:

44

"""Return x**y (x to the power of y)."""

45

46

def sqrt(x: float) -> float:

47

"""Return the square root of x."""

48

49

# Trigonometric functions

50

def sin(x: float) -> float:

51

def cos(x: float) -> float:

52

def tan(x: float) -> float:

53

def asin(x: float) -> float:

54

def acos(x: float) -> float:

55

def atan(x: float) -> float:

56

57

# Angular conversion

58

def degrees(x: float) -> float:

59

"""Convert angle x from radians to degrees."""

60

61

def radians(x: float) -> float:

62

"""Convert angle x from degrees to radians."""

63

64

# Hyperbolic functions

65

def sinh(x: float) -> float:

66

def cosh(x: float) -> float:

67

def tanh(x: float) -> float:

68

69

# Mathematical constants

70

pi: float # The mathematical constant π

71

e: float # The mathematical constant e

72

```

73

74

**Usage Examples:**

75

76

```python

77

from math import sin, cos, pi, factorial, sqrt

78

79

# Trigonometry

80

angle = pi / 4

81

print(sin(angle)) # 0.7071067811865476

82

83

# Integer operations

84

print(factorial(5)) # 120

85

86

# Square root

87

print(sqrt(16)) # 4.0

88

```

89

90

### Random Module

91

92

Random number generation following Python's random module API.

93

94

```python { .api }

95

from random import random, randint, choice, shuffle

96

97

def seed(x: int) -> None:

98

"""Initialize the random number generator."""

99

100

def random() -> float:

101

"""Return a random floating point number in [0.0, 1.0)."""

102

103

def randrange(start: int, stop: int = None, step: int = 1) -> int:

104

"""Return a randomly selected element from range(start, stop, step)."""

105

106

def randint(a: int, b: int) -> int:

107

"""Return a random integer N such that a <= N <= b."""

108

109

def uniform(a: float, b: float) -> float:

110

"""Return a random floating point number N such that a <= N <= b."""

111

112

def choice(seq: list) -> any:

113

"""Return a random element from the non-empty sequence seq."""

114

115

def shuffle(seq: list) -> None:

116

"""Shuffle the sequence x in place."""

117

118

def sample(population: list, k: int) -> list:

119

"""Return a k length list of unique elements chosen from population."""

120

```

121

122

**Usage Examples:**

123

124

```python

125

from random import randint, choice, shuffle

126

127

# Random integer

128

dice_roll = randint(1, 6)

129

130

# Random choice

131

colors = ['red', 'green', 'blue']

132

selected = choice(colors)

133

134

# Shuffle list in place

135

deck = list(range(52))

136

shuffle(deck)

137

```

138

139

### Regular Expressions Module

140

141

Regular expression operations following Python's re module API.

142

143

```python { .api }

144

from re import match, search, findall, compile

145

146

# Compilation flags

147

IGNORECASE: int

148

MULTILINE: int

149

DOTALL: int

150

VERBOSE: int

151

152

def compile(pattern: str, flags: int = 0) -> RegexObject:

153

"""Compile a regular expression pattern into a regex object."""

154

155

def search(pattern: str, string: str, flags: int = 0) -> MatchObject | None:

156

"""Scan through string looking for the first location where pattern matches."""

157

158

def match(pattern: str, string: str, flags: int = 0) -> MatchObject | None:

159

"""If zero or more characters at the beginning of string match pattern."""

160

161

def split(pattern: str, string: str, maxsplit: int = 0, flags: int = 0) -> list:

162

"""Split string by the occurrences of pattern."""

163

164

def findall(pattern: str, string: str, flags: int = 0) -> list:

165

"""Return all non-overlapping matches of pattern in string."""

166

167

def finditer(pattern: str, string: str, flags: int = 0) -> iterator:

168

"""Return an iterator over all non-overlapping matches."""

169

170

def sub(pattern: str, repl: str, string: str, count: int = 0, flags: int = 0) -> str:

171

"""Return the string obtained by replacing leftmost non-overlapping occurrences."""

172

173

def subn(pattern: str, repl: str, string: str, count: int = 0, flags: int = 0) -> tuple:

174

"""Perform the same operation as sub(), but return a tuple (new_string, number_of_subs_made)."""

175

176

def escape(string: str) -> str:

177

"""Escape all the characters in pattern except ASCII letters and numbers."""

178

179

class MatchObject:

180

def group(self, *groups) -> str:

181

"""Return one or more subgroups of the match."""

182

183

def groups(self) -> tuple:

184

"""Return a tuple containing all the subgroups of the match."""

185

186

def start(self, group: int = 0) -> int:

187

"""Return the indices of the start of the substring matched by group."""

188

189

def end(self, group: int = 0) -> int:

190

"""Return the indices of the end of the substring matched by group."""

191

192

def span(self, group: int = 0) -> tuple:

193

"""Return a 2-tuple containing (start(), end()) for group."""

194

195

class RegexObject:

196

def search(self, string: str, pos: int = 0, endpos: int = -1) -> MatchObject | None:

197

def match(self, string: str, pos: int = 0, endpos: int = -1) -> MatchObject | None:

198

def split(self, string: str, maxsplit: int = 0) -> list:

199

def findall(self, string: str, pos: int = 0, endpos: int = -1) -> list:

200

def sub(self, repl: str, string: str, count: int = 0) -> str:

201

```

202

203

**Usage Examples:**

204

205

```python

206

import re

207

208

# Pattern matching

209

match = re.search(r'\d+', 'The answer is 42')

210

if match:

211

print(match.group()) # '42'

212

213

# Find all matches

214

numbers = re.findall(r'\d+', 'Numbers: 1, 2, 3')

215

print(numbers) # ['1', '2', '3']

216

217

# Substitution

218

text = re.sub(r'\d+', 'X', 'Replace 123 and 456')

219

print(text) # 'Replace X and X'

220

```

221

222

### Encodings Module

223

224

Text and binary encoding/decoding utilities.

225

226

```python { .api }

227

from encodings import base64encode, base64decode, hexlify, utf8_decode

228

229

# Base64 encoding

230

def base64encode(data: bytes) -> str:

231

"""Encode binary data using base64."""

232

233

def base64decode(data: str) -> bytes:

234

"""Decode base64 encoded string to binary data."""

235

236

def urlsafe_b64encode(data: bytes) -> str:

237

"""Encode binary data using URL-safe base64."""

238

239

def urlsafe_b64decode(data: str) -> bytes:

240

"""Decode URL-safe base64 encoded string."""

241

242

# Hexadecimal encoding

243

def hexlify(data: bytes) -> str:

244

"""Return the hexadecimal representation of binary data."""

245

246

def unhexlify(hex_string: str) -> bytes:

247

"""Return the binary data represented by the hexadecimal string."""

248

249

# UTF-8 encoding

250

def utf8_decode(bytes: list) -> str:

251

"""Decode UTF-8 byte array to string."""

252

253

def utf8_encode_js(string: str) -> list:

254

"""Encode string to UTF-8 as JavaScript array."""

255

256

def utf8_encode_native(string: str) -> Uint8Array:

257

"""Encode string to UTF-8 as native typed array."""

258

```

259

260

**Usage Examples:**

261

262

```python

263

from encodings import base64encode, base64decode, hexlify

264

265

# Base64 encoding

266

data = b'Hello, World!'

267

encoded = base64encode(data)

268

decoded = base64decode(encoded)

269

270

# Hex encoding

271

hex_str = hexlify(b'ABC')

272

print(hex_str) # '414243'

273

```

274

275

### AES Cryptography Module

276

277

Advanced Encryption Standard implementation with multiple modes.

278

279

```python { .api }

280

from aes import AES, generate_key, random_bytes_secure

281

282

def generate_key(length: int = 32) -> bytes:

283

"""Generate a random AES key of specified length."""

284

285

def random_bytes_secure(length: int) -> bytes:

286

"""Generate cryptographically secure random bytes."""

287

288

def random_bytes_insecure(length: int) -> bytes:

289

"""Generate fast pseudo-random bytes (not cryptographically secure)."""

290

291

class AES:

292

def __init__(self, key: bytes):

293

"""Initialize AES with the given key."""

294

295

def encrypt(self, data: bytes, mode: str = 'CBC', iv: bytes = None) -> dict:

296

"""Encrypt data using specified mode."""

297

298

def decrypt(self, encrypted_data: dict) -> bytes:

299

"""Decrypt data encrypted with encrypt()."""

300

301

class CBC:

302

"""Cipher Block Chaining mode."""

303

def __init__(self, key: bytes, iv: bytes = None):

304

def encrypt(self, data: bytes) -> bytes:

305

def decrypt(self, data: bytes) -> bytes:

306

307

class CTR:

308

"""Counter mode."""

309

def __init__(self, key: bytes, counter: bytes = None):

310

def encrypt(self, data: bytes) -> bytes:

311

def decrypt(self, data: bytes) -> bytes:

312

313

class GCM:

314

"""Galois/Counter Mode (authenticated encryption)."""

315

def __init__(self, key: bytes, iv: bytes = None):

316

def encrypt(self, data: bytes, additional_data: bytes = None) -> dict:

317

def decrypt(self, encrypted_data: dict, additional_data: bytes = None) -> bytes:

318

```

319

320

**Usage Examples:**

321

322

```python

323

from aes import AES, generate_key, CBC

324

325

# Generate key and encrypt data

326

key = generate_key(32) # 256-bit key

327

aes = AES(key)

328

329

plaintext = b'Secret message'

330

cbc = CBC(key)

331

ciphertext = cbc.encrypt(plaintext)

332

decrypted = cbc.decrypt(ciphertext)

333

```

334

335

### Internationalization Module

336

337

Translation and localization support following Python's gettext API.

338

339

```python { .api }

340

from gettext import gettext, ngettext, install

341

342

def gettext(message: str) -> str:

343

"""Return the localized translation of message."""

344

345

def ngettext(singular: str, plural: str, n: int) -> str:

346

"""Return the localized translation of message based on count."""

347

348

def install(translations: dict) -> None:

349

"""Install translation catalog for use by gettext functions."""

350

351

def register_callback(callback: callable) -> None:

352

"""Register callback function for translation lookups."""

353

354

# Convenience alias

355

_ = gettext

356

357

class Translations:

358

"""Translation catalog manager."""

359

def __init__(self, catalog: dict):

360

def gettext(self, message: str) -> str:

361

def ngettext(self, singular: str, plural: str, n: int) -> str:

362

```

363

364

**Usage Examples:**

365

366

```python

367

from gettext import gettext as _, ngettext, install

368

369

# Mark strings for translation

370

title = _('Welcome')

371

message = _('Hello, World!')

372

373

# Plural forms

374

count = 5

375

msg = ngettext('Found {} file', 'Found {} files', count).format(count)

376

377

# Install translations

378

translations = {'Hello': 'Hola', 'Welcome': 'Bienvenido'}

379

install(translations)

380

```

381

382

### UUID Module

383

384

Universally Unique Identifier generation.

385

386

```python { .api }

387

from uuid import uuid4, short_uuid

388

389

def uuid4() -> str:

390

"""Generate a random UUID (version 4) as a string."""

391

392

def uuid4_bytes() -> bytes:

393

"""Generate a random UUID (version 4) as byte array."""

394

395

def short_uuid() -> str:

396

"""Generate a shorter UUID string (base62 encoded)."""

397

398

def short_uuid4() -> str:

399

"""Generate a short random UUID string."""

400

401

def decode_short_uuid(short_uuid: str) -> str:

402

"""Decode short UUID format back to standard UUID."""

403

```

404

405

**Usage Examples:**

406

407

```python

408

from uuid import uuid4, short_uuid

409

410

# Standard UUID

411

id = uuid4()

412

print(id) # 'f47ac10b-58cc-4372-a567-0e02b2c3d479'

413

414

# Short UUID

415

short_id = short_uuid()

416

print(short_id) # 'kHGr7lBX9k2pqE'

417

```

418

419

### Traceback Module

420

421

Stack trace formatting and exception handling utilities.

422

423

```python { .api }

424

from traceback import format_exception, print_exc

425

426

def format_exception(exc_type: type, exc_value: Exception, exc_traceback: object) -> list:

427

"""Format exception information as a list of strings."""

428

429

def format_exc() -> str:

430

"""Format the current exception as a string."""

431

432

def print_exc(file: object = None) -> None:

433

"""Print current exception to file (default: stderr)."""

434

435

def format_stack(frame: object = None, limit: int = None) -> list:

436

"""Format current stack trace as a list of strings."""

437

438

def print_stack(frame: object = None, limit: int = None, file: object = None) -> None:

439

"""Print current stack trace to file."""

440

```

441

442

### Element Maker Module

443

444

DOM element creation utilities for web development.

445

446

```python { .api }

447

from elementmaker import E

448

449

def maker_for_document(document: object) -> ElementMaker:

450

"""Create element maker for specific document object."""

451

452

class ElementMaker:

453

"""Factory for creating DOM elements with Python syntax."""

454

455

def __call__(self, tag: str, *children, **attributes) -> Element:

456

"""Create element with specified tag, children, and attributes."""

457

458

def __getattr__(self, tag: str) -> callable:

459

"""Create element factory for specific tag."""

460

461

# Default element maker

462

E: ElementMaker

463

```

464

465

**Usage Examples:**

466

467

```python

468

from elementmaker import E

469

470

# Create DOM elements

471

div = E.div(

472

E.h1('Title', class_='header'),

473

E.p('Content with ', E.strong('bold'), ' text'),

474

id='container'

475

)

476

477

# Custom tags

478

custom = E('custom-element', 'content', data_value='123')

479

```

480

481

### Operator Module

482

483

Standard operators as functions following Python's operator module.

484

485

```python { .api }

486

from operator import add, sub, mul, div, eq, lt

487

488

# Arithmetic operators

489

def add(a, b): return a + b

490

def sub(a, b): return a - b

491

def mul(a, b): return a * b

492

def div(a, b): return a / b

493

def mod(a, b): return a % b

494

def pow(a, b): return a ** b

495

def abs(a): return abs(a)

496

def neg(a): return -a

497

498

# Comparison operators

499

def eq(a, b): return a == b

500

def ne(a, b): return a != b

501

def lt(a, b): return a < b

502

def le(a, b): return a <= b

503

def gt(a, b): return a > b

504

def ge(a, b): return a >= b

505

506

# Logical operators

507

def and_(a, b): return a and b

508

def or_(a, b): return a or b

509

def not_(a): return not a

510

```

511

512

### Pythonize Module

513

514

Utilities for making JavaScript more Python-like.

515

516

```python { .api }

517

from pythonize import strings

518

519

def strings(*excluded_methods) -> None:

520

"""Add Python string methods to JavaScript String prototype.

521

522

Args:

523

*excluded_methods: Method names to exclude from copying

524

"""

525

```

526

527

**Usage Examples:**

528

529

```python

530

from pythonize import strings

531

532

# Enable Python string methods on JavaScript strings

533

strings()

534

535

# Now JavaScript strings have Python methods

536

text = "hello world"

537

print(text.capitalize()) # "Hello world"

538

print(text.count('l')) # 3

539

540

# Exclude specific methods

541

strings('split', 'replace') # Keep JavaScript versions of these

542

```

543

544

### Regular Expressions Module

545

546

Python-compatible regular expression operations using JavaScript's RegExp engine with Python syntax.

547

548

```python { .api }

549

from re import compile, match, search, findall, finditer, sub, split

550

551

# Flag constants

552

I = IGNORECASE = 2

553

L = LOCALE = 4

554

M = MULTILINE = 8

555

D = DOTALL = 16

556

U = UNICODE = 32

557

X = VERBOSE = 64

558

DEBUG = 128

559

A = ASCII = 256

560

561

def compile(pattern: str, flags: int = 0) -> Pattern:

562

"""Compile a regular expression pattern into a pattern object."""

563

564

def match(pattern: str, string: str, flags: int = 0) -> Match | None:

565

"""Check for a match only at the beginning of the string."""

566

567

def search(pattern: str, string: str, flags: int = 0) -> Match | None:

568

"""Scan through string looking for the first location where pattern matches."""

569

570

def findall(pattern: str, string: str, flags: int = 0) -> list:

571

"""Return all non-overlapping matches of pattern in string."""

572

573

def finditer(pattern: str, string: str, flags: int = 0) -> Iterator:

574

"""Return an iterator over all non-overlapping matches."""

575

576

def sub(pattern: str, repl: str | callable, string: str, count: int = 0, flags: int = 0) -> str:

577

"""Replace occurrences of pattern in string with repl."""

578

579

def subn(pattern: str, repl: str | callable, string: str, count: int = 0, flags: int = 0) -> tuple:

580

"""Same as sub, but returns tuple (new_string, number_of_subs_made)."""

581

582

def split(pattern: str, string: str, maxsplit: int = 0, flags: int = 0) -> list:

583

"""Split string by occurrences of pattern."""

584

585

def escape(pattern: str) -> str:

586

"""Escape special characters in pattern for literal matching."""

587

588

def purge() -> None:

589

"""Clear the regular expression cache."""

590

591

class Pattern:

592

"""Compiled regular expression pattern."""

593

pattern: str

594

flags: int

595

groups: int

596

groupindex: dict

597

598

def match(self, string: str, pos: int = 0, endpos: int = None) -> Match | None:

599

"""Match at start of string."""

600

601

def search(self, string: str, pos: int = 0, endpos: int = None) -> Match | None:

602

"""Search for pattern in string."""

603

604

def findall(self, string: str, pos: int = 0, endpos: int = None) -> list:

605

"""Find all matches in string."""

606

607

def finditer(self, string: str, pos: int = 0, endpos: int = None) -> Iterator:

608

"""Return iterator of all matches."""

609

610

def sub(self, repl: str | callable, string: str, count: int = 0) -> str:

611

"""Replace matches with repl."""

612

613

def subn(self, repl: str | callable, string: str, count: int = 0) -> tuple:

614

"""Replace matches with repl, return (result, count)."""

615

616

def split(self, string: str, maxsplit: int = 0) -> list:

617

"""Split string by pattern."""

618

619

class Match:

620

"""Result of a regular expression match."""

621

string: str

622

re: Pattern

623

pos: int

624

endpos: int

625

lastindex: int | None

626

lastgroup: str | None

627

628

def group(self, *groups) -> str | tuple:

629

"""Return one or more subgroups of the match."""

630

631

def groups(self, default: str = None) -> tuple:

632

"""Return tuple of all subgroups."""

633

634

def groupdict(self, default: str = None) -> dict:

635

"""Return dict of named subgroups."""

636

637

def start(self, group: int | str = 0) -> int:

638

"""Return start index of group."""

639

640

def end(self, group: int | str = 0) -> int:

641

"""Return end index of group."""

642

643

def span(self, group: int | str = 0) -> tuple:

644

"""Return (start, end) indices of group."""

645

646

def expand(self, template: str) -> str:

647

"""Expand template using match groups."""

648

```

649

650

**Usage Examples:**

651

652

```python

653

import re

654

655

# Basic pattern matching

656

pattern = re.compile(r'\d+')

657

match = pattern.search('Number: 42')

658

if match:

659

print(match.group()) # '42'

660

661

# Flags usage

662

text = 'Hello\nWorld'

663

matches = re.findall(r'hello.*world', text, re.IGNORECASE | re.DOTALL)

664

665

# Substitution with groups

666

def replace_func(match):

667

return match.group(1).upper()

668

669

result = re.sub(r'(\w+)', replace_func, 'hello world')

670

print(result) # 'HELLO WORLD'

671

672

# Named groups

673

pattern = r'(?P<name>\w+): (?P<value>\d+)'

674

match = re.search(pattern, 'age: 25')

675

if match:

676

print(match.groupdict()) # {'name': 'age', 'value': '25'}

677

678

# Split and findall

679

words = re.split(r'\s+', 'one two three')

680

numbers = re.findall(r'\d+', 'a1b2c3d')

681

```