tjs-lang 0.7.4 → 0.7.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/demo/docs.json +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +3 -3
- package/dist/scripts/build.d.ts +8 -4
- package/dist/src/lang/runtime.d.ts +8 -4
- package/dist/src/types/Type.d.ts +5 -5
- package/dist/tjs-from-ts.js +20 -20
- package/dist/tjs-from-ts.js.map +3 -3
- package/dist/tjs-lang.js +51 -51
- package/dist/tjs-lang.js.map +3 -3
- package/package.json +1 -1
- package/src/lang/emitters/js.ts +4 -4
- package/src/lang/function-predicate.test.ts +8 -6
- package/src/lang/runtime.test.ts +58 -0
- package/src/lang/runtime.ts +27 -13
- package/src/types/Type.test.ts +68 -19
- package/src/types/Type.ts +80 -54
package/demo/docs.json
CHANGED
|
@@ -1619,4 +1619,4 @@
|
|
|
1619
1619
|
"navTitle": "TJS for TS Devs",
|
|
1620
1620
|
"text": "<!--{\"section\": \"tjs-for-ts\", \"group\": \"docs\", \"order\": 0, \"navTitle\": \"TJS for TS Devs\"}-->\n\n# TJS for TypeScript Programmers\n\n_What if your types didn't disappear at runtime?_\n\n---\n\nTypeScript is great. It catches bugs at compile time, makes refactoring safer,\nand gives you autocomplete. But it has a fundamental limitation: types are\nfiction. They exist only in your editor, and they vanish completely at runtime.\n\nTJS starts from a different premise: **types are example values that survive\nto runtime**. This gives you everything TypeScript gives you, plus runtime\nvalidation, reflection, documentation, inline tests of private methods, and traceability of errors back to source code -- from a single source of truth.\n\nThis guide is split into two paths:\n\n1. **[Using TJS from TypeScript](#part-1-using-tjs-from-typescript)** -- Keep your TS codebase, use TJS for safe eval and agent execution\n2. **[Migrating to TJS](#part-2-migrating-to-tjs)** -- Convert your codebase from TypeScript to TJS\n\n---\n\n# Part 1: Using TJS from TypeScript\n\nYou don't have to rewrite anything. TJS provides tools you can use directly\nfrom your TypeScript codebase.\n\n## Safe Eval\n\nThe most common reason to reach for TJS from TypeScript: running untrusted\ncode safely.\n\n```typescript\nimport { Eval, SafeFunction } from 'tjs-lang/eval'\n\n// Run user-provided code with a gas limit\nconst { result, fuelUsed } = await Eval({\n code: userCode,\n context: { items: data, threshold: 10 },\n fuel: 1000,\n capabilities: {\n fetch: sandboxedFetch, // your whitelist-wrapped fetch\n },\n})\n\n// Or create a reusable safe function\nconst transform = await SafeFunction({\n body: 'return items.filter(x => x.price < budget)',\n params: ['items', 'budget'],\n fuel: 500,\n})\n\nconst { result } = await transform(products, 100)\n```\n\nNo `eval()`. No CSP violations. No Docker containers. The code runs in a\nfuel-metered sandbox with only the capabilities you inject.\n\n## Agent VM\n\nBuild and execute JSON-serializable agents:\n\n```typescript\nimport { ajs, AgentVM } from 'tjs-lang'\n\n// Parse agent source to JSON AST\nconst agent = ajs`\n function analyze({ data, query }) {\n let filtered = data.filter(x => x.score > 0.5)\n let summary = llmPredict({\n prompt: 'Summarize findings for: ' + query,\n data: filtered\n })\n return { query, summary, count: filtered.length }\n }\n`\n\n// Execute with resource limits\nconst vm = new AgentVM()\nconst { result } = await vm.run(\n agent,\n { data, query },\n {\n fuel: 1000,\n timeoutMs: 5000,\n capabilities: { fetch: myFetch, llm: myLlm },\n }\n)\n```\n\nThe agent AST is JSON. You can store it in a database, send it over the\nnetwork, version it, diff it, audit it.\n\n## Type-Safe Builder\n\nConstruct agents programmatically with full TypeScript support:\n\n```typescript\nimport { Agent, AgentVM, s } from 'tjs-lang'\n\nconst pipeline = Agent.take(s.object({ url: s.string, maxResults: s.number }))\n .httpFetch({ url: { $kind: 'arg', path: 'url' } })\n .as('response')\n .varSet({\n key: 'results',\n value: {\n $expr: 'member',\n object: { $expr: 'ident', name: 'response' },\n property: 'items',\n },\n })\n .return(s.object({ results: s.array(s.any) }))\n\nconst vm = new AgentVM()\nconst { result } = await vm.run(\n pipeline.toJSON(),\n { url, maxResults: 10 },\n {\n fuel: 500,\n capabilities: { fetch },\n }\n)\n```\n\n## TypeScript Entry Points\n\nTJS is tree-shakeable. Import only what you need:\n\n```typescript\nimport { Agent, AgentVM, ajs, tjs } from 'tjs-lang' // Everything\nimport { Eval, SafeFunction } from 'tjs-lang/eval' // Safe eval only\nimport { tjs, transpile } from 'tjs-lang/lang' // Language tools\nimport { fromTS } from 'tjs-lang/lang/from-ts' // TS -> TJS converter\n```\n\n## When to Stay in TypeScript\n\nIf your codebase is TypeScript and you're happy with it, you probably only\nneed TJS for:\n\n- Running user-provided or LLM-generated code safely\n- Building agents that travel over the network\n- Adding runtime type validation at system boundaries\n- Eval without `eval()`\n\nYou don't need to migrate anything. The libraries work from TypeScript.\n\n---\n\n# Part 2: Migrating to TJS\n\nIf you want the full TJS experience -- runtime types, structural equality,\nmonadic errors, inline tests -- here's how to convert.\n\n## The Core Idea: Types as Examples\n\nTypeScript describes types abstractly. TJS describes them concretely:\n\n```typescript\n// TypeScript: what TYPE is this?\nfunction greet(name: string): string { ... }\n\n// TJS: what's an EXAMPLE of this?\nfunction greet(name: 'World'): '' { ... }\n```\n\n`'World'` tells TJS: this is a string, it's required, and here's a valid\nexample. The example doubles as documentation and test data.\n\n## Conversion Reference\n\n### Primitives\n\n```typescript\n// TypeScript // TJS\nname: string name: ''\ncount: number count: 0.0 // float (any number)\nindex: number index: 0 // integer\nage: number age: +0 // non-negative integer\nflag: boolean flag: true\nitems: string[] items: ['']\nnested: number[][] nested: [[0]]\n```\n\n**Important:** The example value determines the _type_, not a literal\nconstraint. `name: 'World'` means \"required string\" -- not \"must be the\nstring `'World'`.\" Any string passes validation. The example is there for\ndocumentation, testing, and type inference. Think of it as `string` with\na built-in `@example` tag.\n\n**Numeric precision:** TJS distinguishes three numeric types using valid\nJavaScript syntax that JS itself ignores:\n\n| You Write | TJS Type | Runtime Check |\n| --------- | ---------------------- | ------------------------------- |\n| `3.14` | `number` (float) | Any number |\n| `0.0` | `number` (float) | Any number |\n| `42` | `integer` | `Number.isInteger(x)` |\n| `0` | `integer` | `Number.isInteger(x)` |\n| `+20` | `non-negative integer` | `Number.isInteger(x) && x >= 0` |\n| `+0` | `non-negative integer` | `Number.isInteger(x) && x >= 0` |\n\nTypeScript's `number` is a single type. TJS gives you three levels of\nprecision -- all using expressions that are already legal JavaScript.\nThe automatic converter maps TypeScript `number` to `0.0` (float) to\npreserve the widest behavior; you can then narrow manually to `0` (integer)\nor `+0` (non-negative integer) where appropriate.\n\n### Optional Parameters\n\n```typescript\n// TypeScript // TJS\nfunction f(x?: string) {}\nfunction f(x = '') {}\nfunction f(x: string = 'hi') {}\nfunction f(x = 'hi') {}\n```\n\nIn TypeScript, `?` means optional with type `string | undefined`.\nIn TJS, `= value` means optional with that default. Same semantics, less syntax.\n\n### Object Shapes\n\n```typescript\n// TypeScript\nfunction createUser(opts: { name: string; age: number; email?: string }) {}\n\n// TJS\nfunction createUser(opts: { name: '', age: 0, email = '' }) {}\n```\n\nRequired properties use `:`, optional ones use `=`.\n\n### Return Types\n\n```typescript\n// TypeScript // TJS\nfunction add(a: number, b: number): number function add(a: 0, b: 0): 0\nfunction getUser(): { name: string } function getUser(): { name: '' }\nfunction fetchData(): Promise<string[]> function fetchData(): ['']\n```\n\nThe `fromTS` converter unwraps `Promise<T>` in return type annotations --\nyou annotate the resolved type, not the wrapper. This only applies when\nconverting from TypeScript; in native TJS you just write normal\n`async`/`await` and annotate what the function resolves to.\n\nThe return annotation also generates an automatic test: `add(0, 0)` must\nreturn a number. If it doesn't, you get an error at transpile time.\n\n### Interfaces and Type Aliases\n\n```typescript\n// TypeScript\ninterface User {\n name: string\n age: number\n email?: string\n}\n\ntype Status = 'active' | 'inactive' | 'banned'\n\n// TJS\nType User {\n description: 'a registered user'\n example: { name: '', age: 0, email = '' }\n}\n\nUnion Status 'account status' 'active' | 'inactive' | 'banned'\n```\n\n### Enums\n\n```typescript\n// TypeScript\nenum Color {\n Red = 'red',\n Green = 'green',\n Blue = 'blue',\n}\n\n// TJS\nEnum Color 'CSS color' {\n Red = 'red'\n Green = 'green'\n Blue = 'blue'\n}\n```\n\n### Classes\n\n```typescript\n// TypeScript\nclass Point {\n private x: number\n private y: number\n\n constructor(x: number, y: number) {\n this.x = x\n this.y = y\n }\n\n distanceTo(other: Point): number {\n return Math.sqrt((this.x - other.x) ** 2 + (this.y - other.y) ** 2)\n }\n}\n\nconst p = new Point(10, 20)\n\n// TJS\nclass Point {\n #x\n #y\n\n constructor(x: 0, y: 0) {\n this.#x = x\n this.#y = y\n }\n\n distanceTo(other: Point): 0 {\n return Math.sqrt((this.#x - other.#x) ** 2 + (this.#y - other.#y) ** 2)\n }\n}\n\nconst p = Point(10, 20) // no 'new' needed\n```\n\nKey differences:\n\n- `private` is stripped by default (TS `private` is compile-time only).\n With `TjsClass` (on by default in native TJS, add via `/* @tjs TjsClass */` for TS-originated code), `private` converts to `#` (true JS runtime privacy).\n- Type annotations become example values\n- With `TjsClass`, `new` is optional (linter warns against it)\n\n### Generics\n\nTJS takes a different approach to generics. TypeScript has function-level\ntype parameters (`<T>`) that vanish at runtime. TJS has `Generic` declarations\nthat produce runtime-checkable type constructors:\n\n```typescript\n// TypeScript -- compile-time only, gone at runtime\nfunction identity<T>(x: T): T { return x }\ninterface Box<T> { value: T }\n\n// TJS -- no function-level generics; use Generic for container types\nGeneric Box<T> {\n description: 'a boxed value'\n predicate(x, T) {\n return typeof x === 'object' && x !== null && 'value' in x && T(x.value)\n }\n}\n\n// Usage: Box(Number) is a runtime type checker\nconst isNumberBox = Box(Number)\nisNumberBox({ value: 42 }) // true\nisNumberBox({ value: 'nope' }) // false\n```\n\nFor simple generic functions like `identity` or `first`, you don't need\ngenerics at all -- just skip the type parameter. TJS validates the\nconcrete types at call sites, not the abstract relationship between them.\n\n```javascript\n// Simple -- no generics needed, the function just works\nfunction first(arr: [0]) { return arr[0] }\n\n// If you need runtime-checked containers, use Generic\nGeneric Pair<T, U> {\n description: 'a typed pair'\n predicate(x, T, U) { return T(x[0]) && U(x[1]) }\n}\n```\n\nWhen converting from TypeScript, the `fromTS` converter preserves generic\nmetadata but types become `any`. This is a place where manual review helps.\n\n### Nullability\n\n```typescript\n// TypeScript\nfunction find(id: number): User | null { ... }\n\n// TJS\nfunction find(id: 0): { name: '', age: 0 } || null { ... }\n```\n\nTJS distinguishes `null` from `undefined` -- they're different types, just\nas `typeOf(null)` returns `'null'` and `typeOf(undefined)` returns\n`'undefined'`. Writing `|| null` means the value can be the base type or\n`null`, but not `undefined`. Optional parameters (using `=`) accept\n`undefined` because that's what you get when the caller omits the argument.\n\n## What TypeScript Has That TJS Doesn't\n\nTJS intentionally skips TypeScript features that don't survive to runtime\nor add complexity without proportional value:\n\n| TypeScript Feature | TJS Equivalent |\n| --------------------------- | ------------------------------------------- |\n| `interface` | `Type` with example |\n| `type` aliases | `Type`, `Union`, or `Enum` |\n| Conditional types | Preserved in `.d.ts` via declaration blocks |\n| Mapped types | Preserved in `.d.ts` via declaration blocks |\n| `keyof`, `typeof` | Use runtime `Object.keys()`, `typeOf()` |\n| `Partial<T>`, `Pick<T>` | Define the shape you need directly |\n| Declaration files (`.d.ts`) | Generated from `__tjs` metadata (`--dts`) |\n| `as` type assertions | Not needed (values are checked) |\n| `any` escape hatch | `safety none` per-module or `!` per-fn |\n| Decorators | Not supported |\n| `namespace` | Use modules |\n\nThe philosophy: if a type feature doesn't do something at runtime, it's\ncomplexity without payoff.\n\n### But What About Narrowing?\n\nTypeScript's type system is Turing-complete. You can express astonishing\nconstraints -- `Pick<Omit<T, K>, Extract<keyof T, string>>` -- but the\nresulting types are often harder to understand than the code they describe.\nAnd they vanish at runtime, so they can't protect you from bad API data.\n\nTJS takes the opposite approach: `Type()` gives you a predicate function.\nIf you can write a boolean expression, you can define a type. No type-level\nprogramming language to learn.\n\n```javascript\n// TypeScript: branded types + manual validation\ntype Email = string & { __brand: 'email' }\nfunction isEmail(s: string): s is Email {\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(s)\n}\nfunction validateEmail(input: string): Email {\n if (!isEmail(input)) throw new Error('Invalid email')\n return input\n}\n\n// TJS: one line, works at runtime\nType Email {\n description: 'email address'\n example: 'user@example.com'\n predicate(v) { return typeof v === 'string' && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(v) }\n}\n```\n\nThe TJS `Type()` built-in handles everything from simple shapes to\nsophisticated domain constraints:\n\n```javascript\n// Simple -- infer from example\nType Name 'Alice' // string\n\n// Constrained -- predicate narrows beyond the base type\nType PositiveInt {\n description: 'a positive integer'\n example: 1\n predicate(v) { return typeof v === 'number' && Number.isInteger(v) && v > 0 }\n}\n\n// Domain-specific -- readable business rules\nType USZipCode {\n description: '5-digit US zip code'\n example: '90210'\n predicate(v) { return typeof v === 'string' && /^\\d{5}$/.test(v) }\n}\n\n// Combinators -- compose types\nType OptionalEmail Nullable(Email) // Email | null\n\n// Schema-based -- use tosijs-schema for structured validation\nType AgeRange {\n description: 'valid age'\n example: 25\n predicate(v) { return typeof v === 'number' && v >= 0 && v <= 150 }\n}\n```\n\nCompare the TypeScript equivalents:\n\n| What you want | TypeScript | TJS |\n| ------------------- | ----------------------------------------------------------- | -------------------------------------- |\n| String with format | Branded type + type guard + validation function | `Type Email { predicate(v) {...} }` |\n| Number in range | Branded type + manual check | `Type Age { predicate(v) {...} }` |\n| Non-empty string | Template literal type (compile-only) | `Type NonEmpty { predicate(v) {...} }` |\n| Nullable variant | `T \\| null` (compile-only) | `Nullable(MyType)` (runtime-checked) |\n| Union of literals | `'a' \\| 'b' \\| 'c'` (compile-only) | `Union Status 'a' \\| 'b' \\| 'c'` |\n| Discriminated union | `type Shape = { kind: 'circle' } \\| ...` + manual narrowing | `Union('kind', { circle: {...} })` |\n| Generic container | `interface Box<T>` (compile-only) | `Generic Box<T> { predicate(...) }` |\n\nEvery row in the TypeScript column is compile-time fiction that disappears\nwhen your code runs. Every row in the TJS column is a runtime check that\nactually catches bugs in production. And the TJS versions are shorter,\nbecause a predicate is just a function -- not a type-level program.\n\nTJS also ships common types out of the box: `TString`, `TNumber`,\n`TBoolean`, `TInteger`, `TPositiveInt`, `TNonEmptyString`, `TEmail`,\n`TUrl`, `TUuid`, `Timestamp`, `LegalDate`. No imports from a validation\nlibrary needed.\n\n### Tooling Comparison\n\n| Concern | TypeScript | TJS |\n| ------------------- | ---------------------------------- | ---------------------------------------------------------------------- |\n| **Type checking** | `tsc` (compile-time only) | Runtime validation (survives build) |\n| **Runtime schemas** | Zod / io-ts / Ajv (separate) | Built-in (types _are_ schemas) |\n| **Linting** | ESLint + plugins | Built-in linter (unused vars, unreachable code, no-explicit-new) |\n| **Testing** | Vitest / Jest (separate files) | Inline `test` blocks (transpile-time) |\n| **Equality** | Reference-based only | Honest `==` (no coercion), `Is`/`IsNot` (structural), `===` (identity) |\n| **Build toolchain** | tsc + bundler (webpack/Vite/etc) | Transpiles in-browser, no build step |\n| **Debugging** | Source maps (brittle, build bloat) | Functions carry source identity via `__tjs` metadata |\n| **Documentation** | JSDoc / TypeDoc (manual) | Generated from `__tjs` metadata |\n| **Editor support** | Mature (VSCode, etc) | Monaco/CodeMirror/Ace + VSCode/Cursor extensions |\n\n## What TJS Has That TypeScript Doesn't\n\n### Runtime Validation\n\nTypeScript:\n\n```typescript\n// Types are a promise. A lie, if the data comes from outside.\nfunction processOrder(order: Order) {\n // If order came from an API, nothing guarantees it matches Order.\n // You need Zod/io-ts/ajv AND the TypeScript type AND keep them in sync.\n}\n```\n\nTJS:\n\n```javascript\n// Types are checked at runtime. One source of truth.\nfunction processOrder(order: { items: [{ id: 0, qty: 0 }], total: 0 }): {\n status: '',\n} {\n // If order doesn't match, caller gets a MonadicError -- no crash.\n}\n```\n\n### Honest Equality\n\nTypeScript inherits JavaScript's broken equality. Native TJS fixes this by default. For TS-originated code, add the `TjsEquals` directive (or use `/* @tjs TjsEquals */` in the source `.ts` file):\n\n```javascript\nTjsEquals // needed for TS-originated code; native TJS has this on by default\n\n// == is honest: no coercion, unwraps boxed primitives\n0 == '' // false (JS: true!)\n[] == ![] // false (JS: true!)\nnew String('foo') == 'foo' // true (unwraps boxed)\nnull == undefined // true (useful pattern preserved)\ntypeof null // 'null' (JS: 'object')\n\n// == is fast: O(1) reference equality for objects/arrays\n{a: 1} == {a: 1} // false (different refs)\n[1, 2] == [1, 2] // false (different refs)\n\n// Is/IsNot for explicit deep structural comparison (O(n))\n{a: 1} Is {a: 1} // true\n[1, 2, 3] Is [1, 2, 3] // true\nnew Set([1,2]) Is new Set([2,1]) // true (Sets are order-independent)\n\n// === unchanged: identity check\nobj === obj // true (same reference)\n```\n\n`==` fixes coercion without the performance cost of deep comparison.\nUse `Is`/`IsNot` when you explicitly need structural comparison.\n\n### Monadic Errors\n\nTypeScript uses exceptions. TJS uses values:\n\n```javascript\n// TypeScript -- you have to remember to try/catch\nfunction divide(a: number, b: number): number {\n if (b === 0) throw new Error('Division by zero')\n return a / b\n}\n// Caller forgets try/catch? Crash.\n\n// TJS -- errors flow through the pipeline\nfunction divide(a: 0, b: 0): 0 {\n if (b === 0) return MonadicError('Division by zero')\n return a / b\n}\n// Caller gets an error value. No crash. Ever.\n```\n\n**How the caller handles it:**\n\n```javascript\n// Option 1: Check the result\nconst result = divide(10, 0)\nif (result instanceof Error) {\n console.log(result.message) // 'Division by zero'\n} else {\n useResult(result)\n}\n\n// Option 2: Just keep going -- errors propagate automatically\nconst a = divide(10, 0) // MonadicError\nconst b = double(a) // Receives error, returns it immediately (skips execution)\nconst c = format(b) // Same -- error flows through the whole chain\n// c is still the original MonadicError from divide()\n```\n\nIf you've used Rust's `Result<T, E>` or Haskell's `Either`, the pattern\nis familiar. The key difference from TypeScript: you never have to guess\nwhether a function might throw. Type errors and validation failures are\nalways values, never exceptions.\n\n### Inline Tests\n\n```javascript\nfunction fibonacci(n: 0): 0 {\n if (n <= 1) return n\n return fibonacci(n - 1) + fibonacci(n - 2)\n}\n\ntest 'fibonacci sequence' {\n expect(fibonacci(0)).toBe(0)\n expect(fibonacci(1)).toBe(1)\n expect(fibonacci(10)).toBe(55)\n}\n```\n\nTests run at transpile time. They're stripped from production output.\nNo separate test files, no test runner configuration.\n\n### Safety Controls\n\n```javascript\nsafety none // This module: skip all validation (performance)\nsafety inputs // This module: validate inputs only (default)\nsafety all // This module: validate everything (debug)\n\n// Per-function overrides\nfunction hot(! x: 0) {} // Skip validation even if module says 'inputs'\nfunction safe(? x: 0) {} // Force validation even if module says 'none'\n```\n\nUse `!` (skip validation) only in hot loops where every microsecond counts\nand the data source is already trusted. In all other cases, the ~1.5x\noverhead of `safety inputs` is negligible compared to the bugs it catches.\n\n#### Additional Safety Features\n\n```javascript\nTjsNoVar // var declarations are syntax errors\nconst! config = {} // Compile-time immutability (zero runtime cost)\n\n// Debug mode: make type errors visible\nimport { configure } from 'tjs-lang/lang'\nconfigure({ logTypeErrors: true }) // console.error on every type error\nconfigure({ throwTypeErrors: true }) // throw instead of returning MonadicError\n```\n\nTypeScript has no equivalent to most of these. You're either all-in on\ntypes or you use `as any` to escape.\n\n---\n\n## Automatic Conversion\n\nTJS includes a TypeScript-to-TJS converter that has been validated against\nthe tosijs production codebase (35 files, 523 tests passing):\n\n```bash\n# Convert a single file\nbun src/cli/tjs.ts convert input.ts --emit-tjs > output.tjs\n\n# Convert a directory (produces .js + .d.ts + .md per file)\nbun src/cli/tjs.ts convert src/ -o tjs-out/\n\n# Emit JavaScript directly\nbun src/cli/tjs.ts convert input.ts > output.js\n```\n\nFrom code:\n\n```typescript\nimport { fromTS } from 'tjs-lang/lang/from-ts'\n\nconst result = fromTS(tsSource, { emitTJS: true })\nconsole.log(result.code) // TJS source\n```\n\n### What `fromTS` Handles\n\n- Primitive annotations (`string`, `number`, `boolean`) → example values\n- Interfaces → `Type` declarations with declaration blocks for `.d.ts` round-tripping\n- Generic interfaces → `Generic` with predicates + declaration blocks\n- Conditional/mapped types → preserved verbatim in declaration blocks\n- Function type aliases → `FunctionPredicate` declarations (including generics)\n- String literal unions → `Union`\n- Enums → `Enum`\n- Rest parameters (`...args: T[]`) → preserved with `...` prefix\n- Nullable types (`T | null`) → proper null guards in runtime checks\n- Optional params, default values\n- `private` → stripped (or `#` with `TjsClass`)\n- Static getters/setters → `static` keyword preserved\n- `Promise<T>` → unwrapped return types\n- DOM types (130+) → `{}` (opaque object, keeps params annotated)\n- JSDoc comments → TDoc comments\n- Exported constants → type-inferred `.d.ts` entries\n\n### `@tjs` Annotations in TypeScript\n\nAnnotate your `.ts` files with `/* @tjs ... */` comments to enrich\nthe TJS output. The TS compiler ignores them.\n\n```typescript\n/* @tjs TjsClass TjsEquals */ // Enable TJS modes (off by default in TS-originated code)\n\n/* @tjs-skip */ // Skip this type declaration\nexport type Unboxed<T> = T extends { value: infer U } ? U : T\n\n/* @tjs predicate(x, T) { return typeof x === 'object' && T(x.value) } */\nexport interface Box<T> {\n value: T\n}\n\n/* @tjs example: { name: 'Alice', age: 30 } */\nexport interface User {\n name: string\n age: number\n}\n\n/* @tjs declaration { value: T; path: string } */\nexport interface BoxedProxy<T> {\n /* complex conditional type */\n}\n```\n\n### `.d.ts` Generation\n\nThe DTS emitter produces TypeScript declarations from TJS transpilation:\n\n```bash\nbun src/cli/tjs.ts emit input.tjs # emits .js, .d.ts, .md\n```\n\n- **Interfaces with declaration blocks** → `export interface Name<T> { ... }`\n- **Conditional/mapped types** → `export type Name<T> = ...` (verbatim TS body)\n- **Function types** → `export type Name = (...) => T`\n- **Simple type aliases** → `export type Name = original TS body`\n- **Constants** → `export declare const Name: type`\n- **Functions** → `export declare function Name(params): returnType`\n- **Classes** → callable function + class declaration\n\n### Constrained Generics\n\nWhen the converter encounters a constrained generic like\n`<T extends { id: number }>`, it uses the constraint shape as the\nexample value instead of falling back to `any`. This means:\n\n```typescript\n// TypeScript\nfunction first<T extends { id: number }>(items: T[]): T {\n return items[0]\n}\n\n// Converted TJS — uses constraint shape, not 'any'\nfunction first(items: [{ id: 0.0 }]):! { id: 0.0 } { ... }\n```\n\nGeneric defaults also work: `<T = string>` uses `string` as the example.\nUnconstrained generics (`<T>` with no `extends` or default) still degrade\nto `any` — there's genuinely no information about what T is.\n\n### What `fromTS` Can't Fully Express\n\nTJS types are example values, not abstract type algebra. Some TypeScript\npatterns have no direct TJS equivalent — but most now preserve their\noriginal TS body for `.d.ts` round-tripping:\n\n| TypeScript Pattern | What Happens |\n| ------------------------------------------- | ----------------------------------------------------- |\n| Conditional types (`T extends U ? X : Y`) | TS body preserved verbatim in `.d.ts` |\n| Mapped types (`{ [K in keyof T]: ... }`) | TS body preserved verbatim in `.d.ts` |\n| Intersection types (`A & B`) | TS body preserved verbatim in `.d.ts` |\n| `Partial<T>`, `Required<T>`, `Pick`, `Omit` | Emits warning, uses base shape |\n| `ReturnType<T>`, `Parameters<T>` | Drops to `any` |\n| Template literal types (`` `${A}-${B}` ``) | Becomes `string` |\n| Deeply nested generics (`Foo<Bar<U>>`) | Inner params become `any` |\n| `readonly`, `as const` | Stripped (use `const!` for compile-time immutability) |\n\nThe key improvement: complex types that can't be expressed as runtime\npredicates are still preserved in the `.d.ts` output via declaration blocks.\nThe runtime code works with `any`, but TypeScript consumers of your library\nget the full type information.\n\n## Migration Strategy\n\n### Incremental Adoption\n\nYou don't have to convert everything at once:\n\n1. **Start at boundaries.** Convert API handlers and validation layers\n first -- these benefit most from runtime types.\n2. **Convert hot modules.** Modules with frequent type-related bugs are\n good candidates.\n3. **Leave internals for last.** Pure computational code that's already\n well-tested benefits least from migration.\n\n### The Bun Plugin\n\nIf you use Bun, `.tjs` files work alongside `.ts` files with zero config:\n\n```javascript\n// bunfig.toml already preloads the TJS plugin\nimport { processOrder } from './orders.tjs' // just works\nimport { validateUser } from './users.ts' // also works\n```\n\n### What to Watch For\n\n**Example values matter.** `count: 0` means \"number, example is 0.\" If\nyour function breaks on 0 (division, array index), the automatic signature\ntest will catch it immediately. Choose examples that exercise the\nhappy path.\n\n**Return types generate tests.** `: 0` means TJS will call your function\nwith the parameter examples and check the result. If your function has\nside effects or requires setup, use `:! 0` to skip the signature test.\n\n**Structural equality changes behavior.** If your code relies on `==`\nfor type coercion (comparing numbers to strings, etc.), you'll need to\nupdate those comparisons. This is almost always a bug fix.\n\n---\n\n## Side-by-Side: A Complete Example\n\n### TypeScript\n\n```typescript\ninterface Product {\n id: string\n name: string\n price: number\n tags: string[]\n}\n\ninterface CartItem {\n product: Product\n quantity: number\n}\n\nfunction calculateTotal(items: CartItem[], taxRate: number = 0.1): number {\n const subtotal = items.reduce(\n (sum, item) => sum + item.product.price * item.quantity,\n 0\n )\n return Math.round(subtotal * (1 + taxRate) * 100) / 100\n}\n\nfunction applyDiscount(\n total: number,\n code: string | null\n): { final: number; discount: number } {\n const discounts: Record<string, number> = {\n SAVE10: 0.1,\n SAVE20: 0.2,\n }\n const rate = code ? discounts[code] ?? 0 : 0\n return {\n final: Math.round(total * (1 - rate) * 100) / 100,\n discount: rate,\n }\n}\n```\n\n### TJS\n\n```javascript\nType Product {\n description: 'a product in the catalog'\n example: { id: '', name: '', price: 0.0, tags: [''] }\n}\n\nType CartItem {\n description: 'a product with quantity'\n example: { product: { id: '', name: '', price: 0.0, tags: [''] }, quantity: +0 }\n}\n\nfunction calculateTotal(items: [CartItem], taxRate = 0.1): 0.0 {\n const subtotal = items.reduce(\n (sum, item) => sum + item.product.price * item.quantity,\n 0\n )\n return Math.round(subtotal * (1 + taxRate) * 100) / 100\n}\n\nfunction applyDiscount(total: 0.0, code: '' || null): { final: 0.0, discount: 0.0 } {\n const discounts = {\n SAVE10: 0.1,\n SAVE20: 0.2,\n }\n const rate = code ? discounts[code] ?? 0 : 0\n return {\n final: Math.round(total * (1 - rate) * 100) / 100,\n discount: rate,\n }\n}\n\ntest 'cart calculation' {\n const items = [\n { product: { id: '1', name: 'Widget', price: 10, tags: [] }, quantity: 3 }\n ]\n expect(calculateTotal(items, 0)).toBe(30)\n expect(calculateTotal(items, 0.1)).toBe(33)\n}\n\ntest 'discount codes' {\n expect(applyDiscount(100, 'SAVE10')).toEqual({ final: 90, discount: 0.1 })\n expect(applyDiscount(100, null)).toEqual({ final: 100, discount: 0 })\n expect(applyDiscount(100, 'INVALID')).toEqual({ final: 100, discount: 0 })\n}\n```\n\nThe TJS version is about the same length, but the types exist at runtime,\nthe tests live with the code, and invalid inputs return errors instead\nof crashing.\n\n---\n\n## Traceability: The Death of Source Maps\n\nTypeScript debugging relies on source maps -- external files that try to\nmap minified, transpiled JavaScript back to your original code. They're\nbrittle, often out of sync, and fail entirely in complex build pipelines.\n\nTJS eliminates source maps. Every function carries its source identity\nin `__tjs` metadata:\n\n```javascript\nfunction add(a: 0, b: 0): 0 {\n return a + b\n}\n\nadd.__tjs.source // \"mymodule.tjs:3\"\n```\n\n- **Zero-config debugging:** If a function fails validation, the error\n points to the exact line in your `.tjs` source, not a generated `.js` file.\n- **Transparent eval:** Even code run via `Eval()` or the `AgentVM`\n provides clear traces because AST and source metadata are preserved.\n- **No build bloat:** You don't ship `.map` files to production just to\n know why your app crashed.\n\n---\n\n## FAQ\n\n### How do I use TJS with existing NPM packages?\n\nTJS is a superset of JavaScript. Import any NPM package as usual:\n\n```javascript\nimport lodash from 'https://esm.sh/lodash@4.17.21'\nimport { z } from 'zod' // works, though you won't need it\n```\n\nWhen you import a vanilla JS library, its exports have no TJS metadata.\nYou can wrap them in a TJS boundary to get runtime safety:\n\n```javascript\nimport { rawGeocode } from 'legacy-geo-pkg'\n\n// Wrap to validate at your system boundary\nfunction geocode(addr: ''): { lat: 0.0, lon: 0.0 } {\n return rawGeocode(addr)\n}\n```\n\nThe untyped library code runs freely. Your TJS wrapper validates the\nresult before it enters your typed world.\n\n### Do Proxies, WeakMaps, and other advanced patterns work?\n\nYes. TJS is purely additive — it adds inline type checks and metadata\nproperties but does not wrap, intercept, or modify JavaScript runtime\nbehavior. Specifically:\n\n- **Proxies** work identically to plain JS. TJS attaches `.__tjs` as a\n plain property on function objects, which doesn't trigger Proxy traps.\n If your Proxy needs custom equality, use the `[tjsEquals]` symbol protocol.\n- **WeakMap/WeakSet** are unaffected. TJS doesn't inspect collection contents.\n- **Symbols** work normally. TJS reserves `Symbol.for('tjs.equals')` for\n custom equality but doesn't interfere with other symbols.\n- **`Object.defineProperty`**, getters/setters, non-enumerable properties\n — all work as expected. TJS validation checks value types, not property\n descriptors.\n- **Prototype chains** are preserved. `instanceof` works correctly with\n TJS-wrapped classes.\n\nIf you're building a Proxy-heavy library (reactive state, ORMs, etc.),\nTJS will not interfere. The transpiled output is plain JavaScript with\nsome `typeof` checks at function entry points.\n\n### Does structural equality (`==`) handle circular references?\n\nNo. Circular structures will cause infinite recursion. Use identity\ncomparison (`===`) for objects that might be circular, or define a\ncustom `.Equals` method on the class.\n\n### What happens to TypeScript's `strict` mode checks?\n\nTJS doesn't have `strictNullChecks` or `noImplicitAny` because the\nproblems they solve don't exist:\n\n- **Null safety:** `|| null` explicitly marks nullable parameters.\n Functions without it reject null at runtime.\n- **Implicit any:** Every TJS parameter has an example value that\n determines its type. There's nothing to be implicit about.\n- **Strict property access:** Runtime validation catches missing\n properties with a clear error message instead of `undefined`.\n\n---\n\n## Learn More\n\n- [TJS Language Reference](DOCS-TJS.md) -- Full syntax and features\n- [TJS for JavaScript Programmers](TJS-FOR-JS.md) -- Coming from vanilla JS?\n- [AJS Agent Language](DOCS-AJS.md) -- The sandboxed agent VM\n- [Playground](https://tjs-platform.web.app) -- Try it live\n"
|
|
1621
1621
|
}
|
|
1622
|
-
]
|
|
1622
|
+
]
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Bi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ws=Bi((mf,ko)=>{ko.exports={name:"tjs-lang",version:"0.7.
|
|
1
|
+
var Bi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ws=Bi((mf,ko)=>{ko.exports={name:"tjs-lang",version:"0.7.5",description:"Type-safe JavaScript dialect with runtime validation, sandboxed VM execution, and AI agent orchestration. Transpiles TypeScript to validated JS with fuel-metered execution for untrusted code.",keywords:["typescript","transpiler","runtime-validation","type-safety","sandbox","virtual-machine","wasm-alternative","ai-agents","llm","orchestration","security","fuel-metering","capability-based","json-ast","untrusted-code"],license:"Apache-2.0",main:"./dist/index.js",types:"./dist/src/index.d.ts",exports:{".":{bun:"./src/index.ts",types:"./dist/src/index.d.ts",default:"./dist/index.js"},"./eval":{bun:"./src/lang/eval.ts",types:"./dist/src/lang/eval.d.ts",default:"./dist/tjs-eval.js"},"./lang":{bun:"./src/lang/transpiler.ts",types:"./dist/src/lang/transpiler.d.ts",default:"./dist/tjs-lang.js"},"./lang/from-ts":{bun:"./src/lang/emitters/from-ts.ts",types:"./dist/src/lang/emitters/from-ts.d.ts",default:"./dist/tjs-from-ts.js"},"./vm":{bun:"./src/vm/index.ts",types:"./dist/src/vm/index.d.ts",default:"./dist/tjs-vm.js"},"./batteries":{bun:"./src/batteries/index.ts",types:"./dist/src/batteries/index.d.ts",default:"./dist/tjs-batteries.js"},"./src":"./src/index.ts","./editors/monaco":"./editors/monaco/ajs-monarch.js","./editors/codemirror":"./editors/codemirror/ajs-language.js","./editors/ace":"./editors/ace/ajs-mode.js"},bin:{tjs:"./src/cli/tjs.ts",tjsx:"./src/cli/tjsx.ts","tjs-playground":"./src/cli/playground.ts","create-tjs-app":"./src/cli/create-app.ts","ajs-install-vscode":"./bin/install-vscode.sh","ajs-install-cursor":"./bin/install-cursor.sh"},type:"module",files:["dist","src","docs","editors","bin","demo","tjs-lang.svg","CONTEXT.md","CLAUDE.md"],sideEffects:!1,repository:{type:"git",url:"https://github.com/tonioloewald/tjs-lang.git"},devDependencies:{"@codemirror/lang-css":"^6.3.1","@codemirror/lang-html":"^6.4.11","@codemirror/lang-javascript":"^6.2.4","@codemirror/lang-markdown":"^6.5.0","@codemirror/state":"^6.5.3","@codemirror/theme-one-dark":"^6.1.3","@codemirror/view":"^6.39.9","@happy-dom/global-registrator":"^20.1.0","@types/bun":"latest","@types/jsdom":"^21.1.7","@typescript-eslint/eslint-plugin":"^5.62.0","@typescript-eslint/parser":"^5.62.0","acorn-walk":"^8.3.4",chokidar:"^4.0.3",codemirror:"^6.0.2",esbuild:"^0.28.0",eslint:"^8.57.1",firebase:"^10.12.0","firebase-admin":"^13.6.0","firebase-functions":"^7.0.5",marked:"^9.1.6",prettier:"^2.8.8",tosijs:"^1.5.6","tosijs-ui":"^1.4.7",typescript:"^5.6.2",valibot:"^0.36.0",vitest:"^2.0.5"},scripts:{format:"bun eslint src --fix && bun prettier --write .",lint:"eslint src","build:grammars":"bun editors/build-grammars.ts","test:fast":"SKIP_LLM_TESTS=1 SKIP_BENCHMARKS=1 bun test","test:llm":"bun test src/batteries/models.integration.test.ts",bench:"bun bin/benchmarks.ts",make:"rm -rf dist && bun format && bun run build:grammars && tsc -p tsconfig.build.json && bun scripts/build.ts","build:bundles":"bun scripts/build.ts",typecheck:"tsc --noEmit",latest:"rm -rf node_modules && bun install",docs:"node bin/docs.js",dev:"bun run bin/dev.ts","build:demo":"bun scripts/build-demo.ts","build:cli":"bun build src/cli/tjs.ts --compile --outfile=dist/tjs && bun build src/cli/tjsx.ts --compile --outfile=dist/tjsx","functions:build":"cd functions && npm run build","functions:deploy":"cd functions && npm run deploy","functions:serve":"cd functions && npm run serve","deploy:hosting":"firebase deploy --only hosting",deploy:"npm run build:demo && npm run functions:deploy && firebase deploy --only hosting",start:"bun run build:demo && bun run dev"},dependencies:{acorn:"^8.15.0","acorn-walk":"^8.3.4","tosijs-schema":"^1.3.0"}}});import*as ms from"acorn";var z=class extends Error{line;column;source;filename;constructor(t,n,r,s){let i=`${s||"<source>"}:${n.line}:${n.column}`;super(`${t} at ${i}`),this.name="TranspileError",this.line=n.line,this.column=n.column,this.source=r,this.filename=s}},ie=class extends z{constructor(t,n,r,s){super(t,n,r,s),this.name="SyntaxError"}formatWithContext(t=2){if(!this.source)return this.message;let n=this.source.split(`
|
|
2
2
|
`),r=this.line-1,s=Math.max(0,r-t),i=Math.min(n.length-1,r+t),o=[],a=String(i+1).length;for(let c=s;c<=i;c++){let l=String(c+1).padStart(a),u=c===r?">":" ";if(o.push(`${u} ${l} | ${n[c]}`),c===r){let p=" ".repeat(a+4+this.column);o.push(`${p}^ ${this.message.split(" at ")[0]}`)}}return o.join(`
|
|
3
3
|
`)}},Or=class extends z{expected;received;suggestion;constructor(t,n,r){super(t,n,r?.source,r?.filename),this.name="TypeError",this.expected=r?.expected,this.received=r?.received,this.suggestion=r?.suggestion}};function pe(e){return{depth:e.depth+1,locals:new Map,parent:e,parameters:e.parameters,atoms:e.atoms,warnings:e.warnings,source:e.source,filename:e.filename,options:e.options}}function Fi(e,t){if(t.locals.has(e))return t.locals.get(e);if(t.parameters.has(e))return t.parameters.get(e)?.type;if(t.parent)return Fi(e,t.parent)}function Z(e){return e.loc?{line:e.loc.start.line,column:e.loc.start.column}:{line:1,column:0}}function Bt(e,t){let n="",r=0,s,i,o="normal",a=[],c=[{type:"top-level",braceDepth:0}],l=0,u=()=>c[c.length-1]?.type||"top-level",p=()=>{let f=c[c.length-1];return f?.type==="class-body"&&l===f.braceDepth+1};for(;r<e.length;){let f=e[r],m=e[r+1];switch(o){case"single-string":if(n+=f,f==="\\"&&r+1<e.length){n+=m,r+=2;continue}f==="'"&&(o="normal"),r++;continue;case"double-string":if(n+=f,f==="\\"&&r+1<e.length){n+=m,r+=2;continue}f==='"'&&(o="normal"),r++;continue;case"template-string":if(n+=f,f==="\\"&&r+1<e.length){n+=m,r+=2;continue}if(f==="$"&&m==="{"){n+=m,r+=2,a.push(1),o="normal";continue}f==="`"&&(o="normal"),r++;continue;case"line-comment":n+=f,f===`
|
|
4
4
|
`&&(o="normal"),r++;continue;case"block-comment":if(n+=f,f==="*"&&m==="/"){n+=m,r+=2,o="normal";continue}r++;continue;case"regex":if(n+=f,f==="\\"&&r+1<e.length){n+=m,r+=2;continue}if(f==="["){for(r++;r<e.length&&e[r]!=="]";)n+=e[r],e[r]==="\\"&&r+1<e.length?(n+=e[r+1],r+=2):r++;r<e.length&&(n+=e[r],r++);continue}if(f==="/"){for(r++;r<e.length&&/[gimsuy]/.test(e[r]);)n+=e[r],r++;o="normal";continue}r++;continue;case"normal":if(a.length>0){if(f==="{")a[a.length-1]++;else if(f==="}"&&(a[a.length-1]--,a[a.length-1]===0)){a.pop(),n+=f,r++,o="template-string";continue}}if(f==="'"){n+=f,r++,o="single-string";continue}if(f==='"'){n+=f,r++,o="double-string";continue}if(f==="`"){n+=f,r++,o="template-string";continue}if(f==="/"&&m==="/"){n+=f+m,r+=2,o="line-comment";continue}if(f==="/"&&m==="*"){n+=f+m,r+=2,o="block-comment";continue}if(f==="/"){let b=n.trimEnd();if(!b[b.length-1]||/[=(!,;:{[&|?+\-*%<>~^]$/.test(b)||/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)\s*$/.test(b)){n+=f,r++,o="regex";continue}}break}if(f==="{"){l++,n+=f,r++;continue}if(f==="}"){l--;let b=c[c.length-1];b&&l===b.braceDepth&&c.pop(),n+=f,r++;continue}let d=e.slice(r).match(/^class\s+\w+(?:\s+extends\s+\w+)?\s*\{/);if(d){let b=d[0].slice(0,-1);n+=b,r+=b.length,c.push({type:"class-body",braceDepth:l});continue}let y=e.slice(r).match(/^function\s+(\w+)\s*\(/);if(y){let b=y[1],T=y[0].length,k=e[r+T],w=null,j=r+T;(k==="?"||k==="!")&&(w=k,j++,w==="!"?t.unsafeFunctions.add(b):t.safeFunctions.add(b)),n+=`function ${b}(`,r=j;let C=Dt(e,r,"(",")");if(!C){n+=e[r],r++;continue}let{content:$,endPos:R}=C;r=R;let A=Wn($,t,!0);n+=A+")";let P=r;for(;P<e.length&&/\s/.test(e[P]);)P++;if(e[P]===":"){let v=e.slice(P,P+2),I;for(v===":?"||v===":!"?(P+=2,I=v===":?"?"safe":"unsafe"):P+=1;P<e.length&&/\s/.test(e[P]);)P++;let O=Jn(e,P);O&&(s===void 0&&(s=O.type,I&&(i=I)),r=O.endPos)}continue}let x=e.slice(r).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/),E=(()=>{for(let b=n.length-1;b>=0;b--)if(!/\s/.test(n[b]))return n[b];return`
|
|
@@ -167,7 +167,7 @@ function expect(actual) {
|
|
|
167
167
|
}
|
|
168
168
|
}
|
|
169
169
|
`,xo=xs+`
|
|
170
|
-
`+Ts;import{validate as Es,s as fn}from"tosijs-schema";function Ee(e){if(e.nullable)return{anyOf:[Ee({...e,nullable:!1}),{type:"null"}]};switch(e.kind){case"string":return{type:"string"};case"number":return{type:"number"};case"integer":return{type:"integer"};case"non-negative-integer":return{type:"integer",minimum:0};case"boolean":return{type:"boolean"};case"null":return{type:"null"};case"undefined":return{};case"any":return{};case"array":return e.items?{type:"array",items:Ee(e.items)}:{type:"array"};case"object":if(e.shape){let t={},n=[];for(let[r,s]of Object.entries(e.shape))t[r]=Ee(s),n.push(r);return{type:"object",properties:t,required:n,additionalProperties:!1}}return{type:"object"};case"union":return e.members?{anyOf:e.members.map(Ee)}:{};default:return{}}}function Oe(e){if(e===null)return{type:"null"};if(e===void 0)return{};switch(typeof e){case"string":return{type:"string"};case"number":return Number.isInteger(e)?{type:"integer"}:{type:"number"};case"boolean":return{type:"boolean"};case"object":{if(Array.isArray(e))return e.length===0?{type:"array"}:{type:"array",items:Oe(e[0])};let t={},n=[];for(let[r,s]of Object.entries(e))t[r]=Oe(s),n.push(r);return{type:"object",properties:t,required:n,additionalProperties:!1}}default:return{}}}function Vt(e){let t={},n=[];for(let[i,o]of Object.entries(e.params))o?.type?.kind?t[i]=Ee(o.type):o?.example!==void 0?t[i]=Oe(o.example):t[i]={},o?.required!==!1&&n.push(i),o?.example!==void 0&&(t[i].examples=[o.example]);let r={type:"object",properties:t,required:n},s;return e.returns&&(e.returns.type?.kind?s=Ee(e.returns.type):e.returns.example!==void 0&&(s=Oe(e.returns.example))),{input:r,output:s}}import{validate as Hn,filter as To,s as Kt}from"tosijs-schema";function ve(e){return e!==null&&typeof e=="object"&&"__runtimeType"in e&&e.__runtimeType===!0}function Ss(e){return e!==null&&typeof e=="object"&&"schema"in e&&typeof e.schema=="object"}function So(e){return e!==null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"}function ee(e,t,n,r){let s,i,o,a=n,c=r;if(typeof e=="string")if(s=e,typeof t=="function")i=t,a!==void 0&&(o=Kt.infer(a));else if(t===void 0&&a!==void 0)o=Kt.infer(a);else if(Ss(t))o=t;else if(So(t))o=t;else if(t!==void 0)a=t,c=a,o=Kt.infer(a);else throw new Error("Type(description) requires a predicate, schema, or example");else Ss(e),o=e,s=wo(o);let l;if(o){let p=o?.schema??o;p&&typeof p=="object"&&Array.isArray(p.examples)&&(l=p.examples)}return a===void 0&&l&&l.length>0&&(a=l[0]),{description:s,check:p=>i?i(p):o?Hn(p,o):!1,schema:o,predicate:i,example:a,examples:l,default:c,toJSONSchema(){if(o){let p=o?.schema??o;if(p&&typeof p=="object"&&"type"in p)return p}return a!==void 0?Oe(a):{description:s}},strip(p){return o?To(p,o):p},__runtimeType:!0}}function wo(e){let t=e?.schema??e;if(t&&typeof t=="object"&&"type"in t){let n=t;switch(n.type){case"string":return n.format?`string (${n.format})`:n.pattern?`string matching ${n.pattern}`:n.minLength!==void 0&&n.maxLength!==void 0?`string (${n.minLength}-${n.maxLength} chars)`:"string";case"number":case"integer":return n.minimum!==void 0&&n.maximum!==void 0?`${n.type} (${n.minimum}-${n.maximum})`:n.minimum!==void 0?`${n.type} >= ${n.minimum}`:n.maximum!==void 0?`${n.type} <= ${n.maximum}`:n.type;case"boolean":return"boolean";case"array":return"array";case"object":return"object";case"null":return"null"}}return"value"}var zt=ee("string",e=>typeof e=="string"),Gt=ee("number",e=>typeof e=="number"),Ht=ee("boolean",e=>typeof e=="boolean"),Zt=ee("integer",e=>typeof e=="number"&&Number.isInteger(e)),Yt=ee("positive integer",e=>typeof e=="number"&&Number.isInteger(e)&&e>0),Xt=ee("non-empty string",e=>typeof e=="string"&&e.length>0),Qt=ee("email address",e=>typeof e=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)),Zn=e=>{try{return new URL(e),!0}catch{return!1}},en=ee("URL",e=>typeof e=="string"&&Zn(e)),tn=ee("UUID",e=>typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)),Yn=e=>{let t=new Date(e);return!isNaN(t.getTime())&&e.includes("T")},Xn=e=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let t=new Date(e+"T00:00:00Z");return!isNaN(t.getTime())},Qn=ee("ISO 8601 timestamp",e=>typeof e=="string"&&Yn(e)),er=ee("date (YYYY-MM-DD)",e=>typeof e=="string"&&Xn(e));function nn(e){return ee(`${e.description} or null`,t=>t===null||e.check(t))}function rn(e){return ee(`${e.description} (optional)`,t=>t==null||e.check(t))}function sn(e,t,...n){if(typeof e=="string"&&Array.isArray(t)){let i=e,o=t,a=new Set(o);return{description:i,check:l=>a.has(l),toJSONSchema:()=>({enum:o}),strip:l=>l,__runtimeType:!0,values:o}}let r=[];ve(e)&&r.push(e),ve(t)&&r.push(t),r.push(...n);let s=r.map(i=>i.description).join(" | ");return ee(s,i=>r.some(o=>o.check(i)))}function on(e){return ee(`array of ${e.description}`,t=>Array.isArray(t)&&t.every(n=>e.check(n)))}function Eo(e){if(ve(e))return n=>e.check(n);if(e&&typeof e=="object"&&"schema"in e)return n=>Hn(n,e);let t=Kt.infer(e);return n=>Hn(n,t)}function Ze(e,t,n){let r=[],s=[];for(let o of e)typeof o=="string"?(r.push(o),s.push(void 0)):(r.push(o[0]),s.push(o[1]));let i=(...o)=>{let a=r.map((l,u)=>{let p=u<o.length?o[u]:s[u];return p===void 0?()=>!0:Eo(p)}),c=n;return r.forEach((l,u)=>{let p=u<o.length?o[u]:s[u],f="any";ve(p)?f=p.description:p!==void 0&&(f=typeof p=="string"?"string":JSON.stringify(p)),c=c.replace(new RegExp(`\\b${l}\\b`,"g"),f)}),ee(c,l=>t(l,...a))};return i.params=r,i.description=n,i}var an=Ze(["T","U"],(e,t,n)=>Array.isArray(e)&&e.length===2&&t(e[0])&&n(e[1]),"Pair<T, U>"),cn=Ze(["V"],(e,t)=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).every(t),"Record<string, V>");function ln(e,t){let n=Object.values(t),r=new Set(n),s=Object.keys(t),i={};for(let[a,c]of Object.entries(t))i[c]=a;return{description:e,check:a=>r.has(a),toJSONSchema:()=>({enum:n}),strip:a=>a,__runtimeType:!0,members:t,names:i,values:n,keys:s}}function _o(e){if(e===null)return"null";if(e===void 0)return"undefined";switch(typeof e){case"string":return"string";case"boolean":return"boolean";case"number":return Number.isInteger(e)?"integer":"number";case"object":return Array.isArray(e)?"array":"object";default:return null}}function xt(e,t,n){if(Array.isArray(t)&&n){let r=t,s=[],i=[];for(let a of r)Array.isArray(a)?(s.push(a[0]),i.push(a[1])):(s.push(a),i.push(void 0));let o=((...a)=>{let c=s.map((u,p)=>p<a.length?a[p]:i[p]),l=n(...c);return xt(e,l)});return Object.defineProperties(o,{typeParamNames:{value:s,enumerable:!0},description:{value:e,enumerable:!0},__runtimeType:{value:!0,enumerable:!0}}),o}return $o(e,t)}function $o(e,t){let n={},r,s="assertReturns";if(typeof t=="function"){let o=t.__tjs;if(o){if(o.params)for(let[a,c]of Object.entries(o.params))n[a]=c?.example??null;o.returns&&(r=o.returns?.example??null),o.safeReturn?s="checkedReturns":o.unsafe?s="assertReturns":s="returns"}}else n=t.params??{},r=t.returns,s=t.returnContract??"assertReturns";return{description:e,params:n,returns:r,returnContract:s,toJSONSchema:()=>({description:e,type:"function"}),strip:o=>o,check:o=>{if(typeof o!="function")return!1;let a=Object.keys(n).length;if(a>0){let l=o.__tjs;if(l?.params){if(Object.keys(l.params).length!==a)return!1;let p=Object.keys(n),f=Object.keys(l.params);for(let m=0;m<p.length;m++){let d=l.params[f[m]],y=n[p[m]];if(d?.type?.kind&&y!==void 0){let x=_o(y);if(x&&d.type.kind!==x&&d.type.kind!=="any")return!1}}}}return!0},__runtimeType:!0}}var jo=ws(),oe=jo.version,Tt=Symbol.for("tjs.equals");function pn(e){let[t=0,n=0,r=0]=e.split(".").map(Number);return{major:t,minor:n,patch:r}}function nr(e,t){let n=pn(e),r=pn(t);return n.major!==r.major?n.major<r.major?-1:1:n.minor!==r.minor?n.minor<r.minor?-1:1:n.patch!==r.patch?n.patch<r.patch?-1:1:0}function rr(e,t){let n=pn(e),r=pn(t);return n.major===r.major}var et=class e extends Error{path;expected;actual;callStack;constructor(t,n,r,s,i){super(t),this.name="MonadicError",this.path=n,this.expected=r,this.actual=s,this.callStack=i,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function vo(e,t,n){let r=n===null?"null":typeof n,s=V.callStacks||V.debug?ir():void 0,i=new et(`Expected ${t} for '${e}', got ${r}`,e,t,r,s);if(V.trackErrors!==!1){let o=V.maxErrors??mn;$s[Ye]=i,Ye=(Ye+1)%o,Fe<o&&Fe++,dn++}if(V.logTypeErrors&&console.error(`[TJS TypeError] ${i.message}`),V.throwTypeErrors)throw i;return i}function tr(e){return e instanceof Error&&e.name==="MonadicError"&&"path"in e}var sr={debug:!1,safety:"inputs",requireReturnTypes:!1,callStacks:!1,maxStackSize:64,trackErrors:!0,maxErrors:64},V={...sr},St=64,_s=new Array(St).fill(""),Be=0,$e=0,mn=64,$s=new Array(mn).fill(null),Ye=0,Fe=0,dn=0,tt=0;function Ao(){tt++}function Mo(){tt>0&&tt--}function Co(){return tt>0}function Ro(e){V={...V,...e}}function No(){return{...V}}function ks(e){if((V.callStacks||V.debug)&&e){let t=V.maxStackSize??St;_s[Be]=e,Be=(Be+1)%t,$e<t&&$e++}}function un(){if((V.callStacks||V.debug)&&$e>0){let e=V.maxStackSize??St;Be=(Be-1+e)%e,$e--}}function ir(){if($e===0)return[];let e=V.maxStackSize??St,t=[],n=(Be-$e+e)%e;for(let r=0;r<$e;r++)t.push(_s[(n+r)%e]);return t}function js(){if(V.trackErrors===!1||Fe===0)return[];let e=V.maxErrors??mn,t=[],n=(Ye-Fe+e)%e;for(let r=0;r<Fe;r++)t.push($s[(n+r)%e]);return t}function Po(){let e=js();return Ye=0,Fe=0,dn=0,e}function Io(){return dn}function Do(){V={...sr},Be=0,$e=0,Ye=0,Fe=0,dn=0,tt=0}function Xe(e,t){if(e!==null&&typeof e=="object"&&typeof e[Tt]=="function")return e[Tt](t);if(t!==null&&typeof t=="object"&&typeof t[Tt]=="function")return t[Tt](e);if(e!==null&&typeof e=="object"&&typeof e.Equals=="function")return e.Equals(t);if(t!==null&&typeof t=="object"&&typeof t.Equals=="function")return t.Equals(e);if((e instanceof String||e instanceof Number||e instanceof Boolean)&&(e=e.valueOf()),(t instanceof String||t instanceof Number||t instanceof Boolean)&&(t=t.valueOf()),e===t||typeof e=="number"&&typeof t=="number"&&isNaN(e)&&isNaN(t)||e==null&&t==null)return!0;if(e==null||t===null||t===void 0||typeof e!=typeof t||typeof e!="object")return!1;if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let s of e)if(!t.has(s))return!1;return!0}if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[s,i]of e)if(!t.has(s)||!Xe(i,t.get(s)))return!1;return!0}if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof RegExp&&t instanceof RegExp)return e.toString()===t.toString();if(Array.isArray(e)&&Array.isArray(t))return e.length!==t.length?!1:e.every((s,i)=>Xe(s,t[i]));if(Array.isArray(e)!==Array.isArray(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>Xe(e[s],t[s]))}function vs(e,t){return!Xe(e,t)}function As(e){return e===null?"null":typeof e}function or(e,t){return(e instanceof String||e instanceof Number||e instanceof Boolean)&&(e=e.valueOf()),(t instanceof String||t instanceof Number||t instanceof Boolean)&&(t=t.valueOf()),!!(e===t||typeof e=="number"&&typeof t=="number"&&isNaN(e)&&isNaN(t)||e==null&&t==null)}function Ms(e,t){return!or(e,t)}function _e(e){return e!==null&&typeof e=="object"&&e.$error===!0}function Se(e,t){let n={$error:!0,message:e,...t};if((V.callStacks||V.debug)&&$e>0){let r=ir(),s=t?.path?[...r,t.path]:r;n.stack=s}return n}function ar(e,t){if(e.length===0)return Se("Unknown error");if(e.length===1)return e[0];let n=e.map(s=>{if(s.path){let i=s.path.split(".");return i[i.length-1]}return"unknown"}).join(", "),r=`Multiple parameter errors in ${t||"function"}: ${n}`;return Se(r,{path:t,errors:e})}function Qe(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";let t=typeof e;if(t!=="object")return t;let n=e.constructor?.name;return n&&n!=="Object"?n:"object"}function Cs(e,t){if(e==null||typeof e!="object"&&typeof e!="function")return!1;let n=e;for(;n!==null;){if(n.constructor?.name===t)return!0;n=Object.getPrototypeOf(n)}return!1}function Ue(e,t,n){if(_e(e))return e;if(typeof t=="object"&&t!==null&&"check"in t)return t.check(e)?null:Se(`Expected ${t.description} but got ${Qe(e)}`,{path:n,expected:t.description,actual:Qe(e)});let r=Qe(e);return t==="any"||t===r||t==="number"&&r==="number"||t==="integer"&&r==="number"&&Number.isInteger(e)||t==="non-negative-integer"&&r==="number"&&Number.isInteger(e)&&e>=0||t==="object"&&r==="object"?null:Se(`Expected ${t} but got ${r}`,{path:n,expected:t,actual:r})}function cr(e,t,n){for(let[r,s]of Object.entries(t.params)){let i=e[r];if(_e(i))return i;if(s.required&&i===void 0){let a=typeof s.type=="string"?s.type:s.type.description;return Se(`Missing required parameter '${r}'`,{path:n?`${n}.${r}`:r,expected:a,actual:"undefined",loc:s.loc})}if(i===void 0)continue;let o=Ue(i,s.type,n?`${n}.${r}`:r);if(o)return s.loc&&(o.loc=s.loc),o}return null}function lr(e,t){if(e.__tjs=t,e.__tjs.schema=()=>Vt(t),!(!t.polymorphic&&(t.safe||t.safeReturn||V.safety!=="none"&&!t.unsafe||t.returns&&V.safety==="all"&&!t.unsafeReturn)))return e;let r=!!t.returns,s=!!t.unsafe,i=!!t.safe,o=!!t.unsafeReturn,a=!!t.safeReturn,c=t.returns?.defaults,l=Object.entries(t.params),u=l.length,p=e.name||t.name||"anonymous",f=function(...m){if(tt>0)return e.apply(this,m);let d=i||!s&&V.safety!=="none",y=r&&(a||!o&&V.safety==="all");if(!d&&!y)return e.apply(this,m);if(m.length>0&&_e(m[0]))return m[0];if(d){let E=m.length===1&&typeof m[0]=="object"&&m[0]!==null&&!Array.isArray(m[0]),_=[];if(E){let b=m[0];for(let T=0;T<u;T++){let[k,w]=l[T],j=b[k];if(_e(j)){_.push(j);continue}if(w.required&&j===void 0){_.push(Se(`Missing required parameter '${k}'`,{path:`${p}.${k}`,expected:typeof w.type=="string"?w.type:w.type?.description||"value",actual:"undefined",loc:w.loc}));continue}if(j!==void 0){let C=Ue(j,w.type,`${p}.${k}`);C&&(w.loc&&(C.loc=w.loc),_.push(C))}}}else for(let b=0;b<u;b++){let[T,k]=l[b],w=m[b];if(_e(w)){_.push(w);continue}if(k.required&&w===void 0){_.push(Se(`Missing required parameter '${T}'`,{path:`${p}.${T}`,expected:typeof k.type=="string"?k.type:k.type?.description||"value",actual:"undefined",loc:k.loc}));continue}if(w!==void 0){let j=Ue(w,k.type,`${p}.${T}`);j&&(k.loc&&(j.loc=k.loc),_.push(j))}}if(_.length>0)return ar(_,p)}let x=V.callStacks||V.debug;x&&ks(p);try{let E=e.apply(this,m);if(y&&t.returns&&!_e(E)){let _=c&&typeof E=="object"&&E!==null?Object.assign({},c,E):E,b=Ue(_,t.returns.type,`${p}()`);if(b)return x&&un(),b}return x&&un(),E}catch(E){return x&&un(),Se(E.message||String(E),{path:p,cause:E})}};return Object.defineProperty(f,"name",{value:e.name}),f.__tjs=t,f.__tjs.schema=()=>Vt(t),f}function Rs(e){let t=new Proxy(e,{construct(n,r,s){return Reflect.construct(n,r,s)},apply(n,r,s){return Reflect.construct(n,s)}});Object.defineProperty(t,"name",{value:e.name});for(let n of Object.getOwnPropertyNames(e))n!=="length"&&n!=="name"&&n!=="prototype"&&Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n));return t}function Ns(){let e={...V},t=e.maxStackSize??St,n=new Array(t).fill(""),r=0,s=0,i=e.maxErrors??mn,o=new Array(i).fill(null),a=0,c=0,l=0,u=0;function p(v){e={...e,...v}}function f(){return{...e}}function m(v){(e.callStacks||e.debug)&&v&&(n[r]=v,r=(r+1)%t,s<t&&s++)}function d(){(e.callStacks||e.debug)&&s>0&&(r=(r-1+t)%t,s--)}function y(){if(s===0)return[];let v=[],I=(r-s+t)%t;for(let O=0;O<s;O++)v.push(n[(I+O)%t]);return v}function x(){e={...sr},r=0,s=0,a=0,c=0,l=0,u=0}function E(){u++}function _(){u>0&&u--}function b(){return u>0}let T=new Map;function k(v,I,O){T.has(v)||T.set(v,new Map),T.get(v).set(I,O)}function w(v,I){let O=typeof v,F;if(v==null)return;if(O==="string")F="String";else if(O==="number")F="Number";else if(O==="boolean")F="Boolean";else if(Array.isArray(v))F="Array";else if(O==="object")F=v.constructor?.name||"Object";else return;let H=F;for(;H;){let Ge=T.get(H);if(Ge?.has(I))return Ge.get(I);if(O==="object"&&!Array.isArray(v)){if(H=Object.getPrototypeOf(H===F?v:Object.getPrototypeOf(v))?.constructor?.name,H==="Object"||H===F)break}else break}let se=T.get("Object");if(se?.has(I))return se.get(I)}function j(v,I,O){let F=O===null?"null":typeof O,H=e.callStacks||e.debug?y():void 0,se=new et(`Expected ${I} for '${v}', got ${F}`,v,I,F,H);if(e.trackErrors!==!1&&(o[a]=se,a=(a+1)%i,c<i&&c++,l++),e.logTypeErrors&&console.error(`[TJS TypeError] ${se.message}`),e.throwTypeErrors)throw se;return se}function C(){if(e.trackErrors===!1||c===0)return[];let v=[],I=(a-c+i)%i;for(let O=0;O<c;O++)v.push(o[(I+O)%i]);return v}function $(){let v=C();return a=0,c=0,l=0,v}function R(){return l}function A(v,I){let O={$error:!0,message:v,...I};if((e.callStacks||e.debug)&&s>0){let F=I?.path?[...y(),I.path]:y();O.stack=F}return O}function P(v,I){return v==null?j(`bang.${I}`,"non-null",v):tr(v)?v:v[I]}return{version:oe,MonadicError:et,typeError:j,isMonadicError:tr,bang:P,isError:_e,error:A,composeErrors:ar,typeOf:Qe,isNativeType:Cs,checkType:Ue,validateArgs:cr,wrap:lr,wrapClass:Rs,compareVersions:nr,versionsCompatible:rr,createRuntime:Ns,configure:p,getConfig:f,pushStack:m,popStack:d,getStack:y,errors:C,clearErrors:$,getErrorCount:R,resetRuntime:x,enterUnsafe:E,exitUnsafe:_,isUnsafeMode:b,validate:Es,infer:fn.infer.bind(fn),Type:ee,isRuntimeType:ve,Union:sn,Generic:Ze,Enum:ln,FunctionPredicate:xt,Nullable:nn,Optional:rn,TArray:on,TString:zt,TNumber:Gt,TBoolean:Ht,TInteger:Zt,TPositiveInt:Yt,TNonEmptyString:Xt,TEmail:Qt,TUrl:en,TUuid:tn,TPair:an,TRecord:cn,Is:Xe,IsNot:vs,Eq:or,NotEq:Ms,TypeOf:As,tjsEquals:Tt,registerExtension:k,resolveExtension:w}}var Le={version:oe,MonadicError:et,typeError:vo,isMonadicError:tr,isError:_e,error:Se,composeErrors:ar,typeOf:Qe,isNativeType:Cs,checkType:Ue,validateArgs:cr,wrap:lr,wrapClass:Rs,compareVersions:nr,versionsCompatible:rr,configure:Ro,getConfig:No,pushStack:ks,popStack:un,getStack:ir,errors:js,clearErrors:Po,getErrorCount:Io,resetRuntime:Do,enterUnsafe:Ao,exitUnsafe:Mo,isUnsafeMode:Co,createRuntime:Ns,validate:Es,infer:fn.infer.bind(fn),Type:ee,isRuntimeType:ve,Union:sn,Generic:Ze,Enum:ln,FunctionPredicate:xt,Nullable:nn,Optional:rn,TArray:on,TString:zt,TNumber:Gt,TBoolean:Ht,TInteger:Zt,TPositiveInt:Yt,TNonEmptyString:Xt,TEmail:Qt,TUrl:en,TUuid:tn,Timestamp:Qn,LegalDate:er,TPair:an,TRecord:cn,Is:Xe,IsNot:vs,Eq:or,NotEq:Ms,TypeOf:As};function ur(){let e=globalThis;if(e.__tjs){let t=e.__tjs.version;if(typeof t!="string")return e.__tjs=Le,Le;let n=nr(oe,t);return n===0||(rr(oe,t)?n>0?(console.info(`TJS runtime: upgrading ${t} \u2192 ${oe}`),e.__tjs=Le):console.info(`TJS runtime: keeping ${t} (newer than ${oe})`):(console.warn(`TJS runtime version conflict: ${t} vs ${oe} (major version mismatch)`),n>0&&(console.warn(`Upgrading to ${oe} - check for breaking changes`),e.__tjs=Le))),e.__tjs}return e.__tjs=Le,Le}function Oo(e){return`
|
|
170
|
+
`+Ts;import{validate as Es,s as fn}from"tosijs-schema";function Ee(e){if(e.nullable)return{anyOf:[Ee({...e,nullable:!1}),{type:"null"}]};switch(e.kind){case"string":return{type:"string"};case"number":return{type:"number"};case"integer":return{type:"integer"};case"non-negative-integer":return{type:"integer",minimum:0};case"boolean":return{type:"boolean"};case"null":return{type:"null"};case"undefined":return{};case"any":return{};case"array":return e.items?{type:"array",items:Ee(e.items)}:{type:"array"};case"object":if(e.shape){let t={},n=[];for(let[r,s]of Object.entries(e.shape))t[r]=Ee(s),n.push(r);return{type:"object",properties:t,required:n,additionalProperties:!1}}return{type:"object"};case"union":return e.members?{anyOf:e.members.map(Ee)}:{};default:return{}}}function Oe(e){if(e===null)return{type:"null"};if(e===void 0)return{};switch(typeof e){case"string":return{type:"string"};case"number":return Number.isInteger(e)?{type:"integer"}:{type:"number"};case"boolean":return{type:"boolean"};case"object":{if(Array.isArray(e))return e.length===0?{type:"array"}:{type:"array",items:Oe(e[0])};let t={},n=[];for(let[r,s]of Object.entries(e))t[r]=Oe(s),n.push(r);return{type:"object",properties:t,required:n,additionalProperties:!1}}default:return{}}}function Vt(e){let t={},n=[];for(let[i,o]of Object.entries(e.params))o?.type?.kind?t[i]=Ee(o.type):o?.example!==void 0?t[i]=Oe(o.example):t[i]={},o?.required!==!1&&n.push(i),o?.example!==void 0&&(t[i].examples=[o.example]);let r={type:"object",properties:t,required:n},s;return e.returns&&(e.returns.type?.kind?s=Ee(e.returns.type):e.returns.example!==void 0&&(s=Oe(e.returns.example))),{input:r,output:s}}import{validate as Hn,filter as To,s as Kt}from"tosijs-schema";function ve(e){return e!==null&&typeof e=="object"&&"__runtimeType"in e&&e.__runtimeType===!0}function Ss(e){return e!==null&&typeof e=="object"&&"schema"in e&&typeof e.schema=="object"}function So(e){return e!==null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"}function ee(e,t,n,r){let s,i,o,a=n,c=r;if(typeof e=="string")if(s=e,typeof t=="function")i=t,a!==void 0&&(o=Kt.infer(a));else if(t===void 0&&a!==void 0)o=Kt.infer(a);else if(Ss(t))o=t;else if(So(t))o=t;else if(t!==void 0)a=t,c=a,o=Kt.infer(a);else throw new Error("Type(description) requires a predicate, schema, or example");else Ss(e),o=e,s=wo(o);let l;if(o){let p=o?.schema??o;p&&typeof p=="object"&&Array.isArray(p.examples)&&(l=p.examples)}return a===void 0&&l&&l.length>0&&(a=l[0]),{description:s,check:p=>i?i(p):o?Hn(p,o):!1,schema:o,predicate:i,example:a,examples:l,default:c,toJSONSchema(){if(o){let p=o?.schema??o;if(p&&typeof p=="object"&&"type"in p)return p}return a!==void 0?Oe(a):{description:s}},strip(p){return o?To(p,o):p},__runtimeType:!0}}function wo(e){let t=e?.schema??e;if(t&&typeof t=="object"&&"type"in t){let n=t;switch(n.type){case"string":return n.format?`string (${n.format})`:n.pattern?`string matching ${n.pattern}`:n.minLength!==void 0&&n.maxLength!==void 0?`string (${n.minLength}-${n.maxLength} chars)`:"string";case"number":case"integer":return n.minimum!==void 0&&n.maximum!==void 0?`${n.type} (${n.minimum}-${n.maximum})`:n.minimum!==void 0?`${n.type} >= ${n.minimum}`:n.maximum!==void 0?`${n.type} <= ${n.maximum}`:n.type;case"boolean":return"boolean";case"array":return"array";case"object":return"object";case"null":return"null"}}return"value"}var zt=ee("string",e=>typeof e=="string"?!0:`expected string, got ${e===null?"null":typeof e}`),Gt=ee("number",e=>typeof e=="number"?!0:`expected number, got ${e===null?"null":typeof e}`),Ht=ee("boolean",e=>typeof e=="boolean"?!0:`expected boolean, got ${e===null?"null":typeof e}`),Zt=ee("integer",e=>typeof e!="number"?`expected integer, got ${e===null?"null":typeof e}`:Number.isInteger(e)?!0:`${e} is not an integer`),Yt=ee("positive integer",e=>typeof e!="number"?`expected positive integer, got ${e===null?"null":typeof e}`:Number.isInteger(e)?e<=0?`${e} is not positive`:!0:`${e} is not an integer`),Xt=ee("non-empty string",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:e.length===0?"string is empty":!0),Qt=ee("email address",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)?!0:`"${e}" is not a valid email`),Zn=e=>{try{return new URL(e),!0}catch{return!1}},en=ee("URL",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:Zn(e)?!0:`"${e}" is not a valid URL`),tn=ee("UUID",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)?!0:`"${e}" is not a valid UUID`),Yn=e=>{let t=new Date(e);return!isNaN(t.getTime())&&e.includes("T")},Xn=e=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let t=new Date(e+"T00:00:00Z");return!isNaN(t.getTime())},Qn=ee("ISO 8601 timestamp",e=>typeof e=="string"&&Yn(e)),er=ee("date (YYYY-MM-DD)",e=>typeof e=="string"&&Xn(e));function nn(e){return ee(`${e.description} or null`,t=>t===null||e.check(t)===!0)}function rn(e){return ee(`${e.description} (optional)`,t=>t==null||e.check(t)===!0)}function sn(e,t,...n){if(typeof e=="string"&&Array.isArray(t)){let i=e,o=t,a=new Set(o);return{description:i,check:l=>a.has(l),toJSONSchema:()=>({enum:o}),strip:l=>l,__runtimeType:!0,values:o}}let r=[];ve(e)&&r.push(e),ve(t)&&r.push(t),r.push(...n);let s=r.map(i=>i.description).join(" | ");return ee(s,i=>r.some(o=>o.check(i)===!0))}function on(e){return ee(`array of ${e.description}`,t=>Array.isArray(t)&&t.every(n=>e.check(n)===!0))}function Eo(e){if(ve(e))return n=>e.check(n)===!0;if(e&&typeof e=="object"&&"schema"in e)return n=>Hn(n,e);let t=Kt.infer(e);return n=>Hn(n,t)}function Ze(e,t,n){let r=[],s=[];for(let o of e)typeof o=="string"?(r.push(o),s.push(void 0)):(r.push(o[0]),s.push(o[1]));let i=(...o)=>{let a=r.map((l,u)=>{let p=u<o.length?o[u]:s[u];return p===void 0?()=>!0:Eo(p)}),c=n;return r.forEach((l,u)=>{let p=u<o.length?o[u]:s[u],f="any";ve(p)?f=p.description:p!==void 0&&(f=typeof p=="string"?"string":JSON.stringify(p)),c=c.replace(new RegExp(`\\b${l}\\b`,"g"),f)}),ee(c,l=>t(l,...a))};return i.params=r,i.description=n,i}var an=Ze(["T","U"],(e,t,n)=>Array.isArray(e)&&e.length===2&&t(e[0])&&n(e[1]),"Pair<T, U>"),cn=Ze(["V"],(e,t)=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).every(t),"Record<string, V>");function ln(e,t){let n=Object.values(t),r=new Set(n),s=Object.keys(t),i={};for(let[a,c]of Object.entries(t))i[c]=a;return{description:e,check:a=>r.has(a),toJSONSchema:()=>({enum:n}),strip:a=>a,__runtimeType:!0,members:t,names:i,values:n,keys:s}}function _o(e){if(e===null)return"null";if(e===void 0)return"undefined";switch(typeof e){case"string":return"string";case"boolean":return"boolean";case"number":return Number.isInteger(e)?"integer":"number";case"object":return Array.isArray(e)?"array":"object";default:return null}}function xt(e,t,n){if(Array.isArray(t)&&n){let r=t,s=[],i=[];for(let a of r)Array.isArray(a)?(s.push(a[0]),i.push(a[1])):(s.push(a),i.push(void 0));let o=((...a)=>{let c=s.map((u,p)=>p<a.length?a[p]:i[p]),l=n(...c);return xt(e,l)});return Object.defineProperties(o,{typeParamNames:{value:s,enumerable:!0},description:{value:e,enumerable:!0},__runtimeType:{value:!0,enumerable:!0}}),o}return $o(e,t)}function $o(e,t){let n={},r,s="assertReturns";if(typeof t=="function"){let o=t.__tjs;if(o){if(o.params)for(let[a,c]of Object.entries(o.params))n[a]=c?.example??null;o.returns&&(r=o.returns?.example??null),o.safeReturn?s="checkedReturns":o.unsafe?s="assertReturns":s="returns"}}else n=t.params??{},r=t.returns,s=t.returnContract??"assertReturns";return{description:e,params:n,returns:r,returnContract:s,toJSONSchema:()=>({description:e,type:"function"}),strip:o=>o,check:o=>{if(typeof o!="function")return`expected function, got ${o===null?"null":typeof o}`;let a=Object.keys(n).length;if(a>0){let l=o.__tjs;if(l?.params){let u=Object.keys(l.params).length;if(u!==a)return`expected ${a} params, got ${u}`;let p=Object.keys(n),f=Object.keys(l.params);for(let m=0;m<p.length;m++){let d=l.params[f[m]],y=n[p[m]];if(d?.type?.kind&&y!==void 0){let x=_o(y);if(x&&d.type.kind!==x&&d.type.kind!=="any")return`param '${p[m]}' expected ${x}, got ${d.type.kind}`}}}}return!0},__runtimeType:!0}}var jo=ws(),oe=jo.version,Tt=Symbol.for("tjs.equals");function pn(e){let[t=0,n=0,r=0]=e.split(".").map(Number);return{major:t,minor:n,patch:r}}function nr(e,t){let n=pn(e),r=pn(t);return n.major!==r.major?n.major<r.major?-1:1:n.minor!==r.minor?n.minor<r.minor?-1:1:n.patch!==r.patch?n.patch<r.patch?-1:1:0}function rr(e,t){let n=pn(e),r=pn(t);return n.major===r.major}var et=class e extends Error{path;expected;actual;callStack;reason;constructor(t,n,r,s,i,o){super(t),this.name="MonadicError",this.path=n,this.expected=r,this.actual=s,this.callStack=i,this.reason=o,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function vo(e,t,n,r){let s=n===null?"null":typeof n,i=V.callStacks||V.debug?ir():void 0,o=r?`Expected ${t} for '${e}': ${r}`:`Expected ${t} for '${e}', got ${s}`,a=new et(o,e,t,s,i,r);if(V.trackErrors!==!1){let c=V.maxErrors??mn;$s[Ye]=a,Ye=(Ye+1)%c,Fe<c&&Fe++,dn++}if(V.logTypeErrors&&console.error(`[TJS TypeError] ${a.message}`),V.throwTypeErrors)throw a;return a}function tr(e){return e instanceof Error&&e.name==="MonadicError"&&"path"in e}var sr={debug:!1,safety:"inputs",requireReturnTypes:!1,callStacks:!1,maxStackSize:64,trackErrors:!0,maxErrors:64},V={...sr},St=64,_s=new Array(St).fill(""),Be=0,$e=0,mn=64,$s=new Array(mn).fill(null),Ye=0,Fe=0,dn=0,tt=0;function Ao(){tt++}function Mo(){tt>0&&tt--}function Co(){return tt>0}function Ro(e){V={...V,...e}}function No(){return{...V}}function ks(e){if((V.callStacks||V.debug)&&e){let t=V.maxStackSize??St;_s[Be]=e,Be=(Be+1)%t,$e<t&&$e++}}function un(){if((V.callStacks||V.debug)&&$e>0){let e=V.maxStackSize??St;Be=(Be-1+e)%e,$e--}}function ir(){if($e===0)return[];let e=V.maxStackSize??St,t=[],n=(Be-$e+e)%e;for(let r=0;r<$e;r++)t.push(_s[(n+r)%e]);return t}function js(){if(V.trackErrors===!1||Fe===0)return[];let e=V.maxErrors??mn,t=[],n=(Ye-Fe+e)%e;for(let r=0;r<Fe;r++)t.push($s[(n+r)%e]);return t}function Po(){let e=js();return Ye=0,Fe=0,dn=0,e}function Io(){return dn}function Do(){V={...sr},Be=0,$e=0,Ye=0,Fe=0,dn=0,tt=0}function Xe(e,t){if(e!==null&&typeof e=="object"&&typeof e[Tt]=="function")return e[Tt](t);if(t!==null&&typeof t=="object"&&typeof t[Tt]=="function")return t[Tt](e);if(e!==null&&typeof e=="object"&&typeof e.Equals=="function")return e.Equals(t);if(t!==null&&typeof t=="object"&&typeof t.Equals=="function")return t.Equals(e);if((e instanceof String||e instanceof Number||e instanceof Boolean)&&(e=e.valueOf()),(t instanceof String||t instanceof Number||t instanceof Boolean)&&(t=t.valueOf()),e===t||typeof e=="number"&&typeof t=="number"&&isNaN(e)&&isNaN(t)||e==null&&t==null)return!0;if(e==null||t===null||t===void 0||typeof e!=typeof t||typeof e!="object")return!1;if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let s of e)if(!t.has(s))return!1;return!0}if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[s,i]of e)if(!t.has(s)||!Xe(i,t.get(s)))return!1;return!0}if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof RegExp&&t instanceof RegExp)return e.toString()===t.toString();if(Array.isArray(e)&&Array.isArray(t))return e.length!==t.length?!1:e.every((s,i)=>Xe(s,t[i]));if(Array.isArray(e)!==Array.isArray(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>Xe(e[s],t[s]))}function vs(e,t){return!Xe(e,t)}function As(e){return e===null?"null":typeof e}function or(e,t){return(e instanceof String||e instanceof Number||e instanceof Boolean)&&(e=e.valueOf()),(t instanceof String||t instanceof Number||t instanceof Boolean)&&(t=t.valueOf()),!!(e===t||typeof e=="number"&&typeof t=="number"&&isNaN(e)&&isNaN(t)||e==null&&t==null)}function Ms(e,t){return!or(e,t)}function _e(e){return e!==null&&typeof e=="object"&&e.$error===!0}function Se(e,t){let n={$error:!0,message:e,...t};if((V.callStacks||V.debug)&&$e>0){let r=ir(),s=t?.path?[...r,t.path]:r;n.stack=s}return n}function ar(e,t){if(e.length===0)return Se("Unknown error");if(e.length===1)return e[0];let n=e.map(s=>{if(s.path){let i=s.path.split(".");return i[i.length-1]}return"unknown"}).join(", "),r=`Multiple parameter errors in ${t||"function"}: ${n}`;return Se(r,{path:t,errors:e})}function Qe(e){if(e===null)return"null";if(e===void 0)return"undefined";if(Array.isArray(e))return"array";let t=typeof e;if(t!=="object")return t;let n=e.constructor?.name;return n&&n!=="Object"?n:"object"}function Cs(e,t){if(e==null||typeof e!="object"&&typeof e!="function")return!1;let n=e;for(;n!==null;){if(n.constructor?.name===t)return!0;n=Object.getPrototypeOf(n)}return!1}function Ue(e,t,n){if(_e(e))return e;if(typeof t=="object"&&t!==null&&"check"in t){let s=t.check(e);if(s===!0)return null;let i=typeof s=="string"?s:void 0,o=i?`Expected ${t.description} for '${n}': ${i}`:`Expected ${t.description} but got ${Qe(e)}`;return Se(o,{path:n,expected:t.description,actual:Qe(e),reason:i})}let r=Qe(e);return t==="any"||t===r||t==="number"&&r==="number"||t==="integer"&&r==="number"&&Number.isInteger(e)||t==="non-negative-integer"&&r==="number"&&Number.isInteger(e)&&e>=0||t==="object"&&r==="object"?null:Se(`Expected ${t} but got ${r}`,{path:n,expected:t,actual:r})}function cr(e,t,n){for(let[r,s]of Object.entries(t.params)){let i=e[r];if(_e(i))return i;if(s.required&&i===void 0){let a=typeof s.type=="string"?s.type:s.type.description;return Se(`Missing required parameter '${r}'`,{path:n?`${n}.${r}`:r,expected:a,actual:"undefined",loc:s.loc})}if(i===void 0)continue;let o=Ue(i,s.type,n?`${n}.${r}`:r);if(o)return s.loc&&(o.loc=s.loc),o}return null}function lr(e,t){if(e.__tjs=t,e.__tjs.schema=()=>Vt(t),!(!t.polymorphic&&(t.safe||t.safeReturn||V.safety!=="none"&&!t.unsafe||t.returns&&V.safety==="all"&&!t.unsafeReturn)))return e;let r=!!t.returns,s=!!t.unsafe,i=!!t.safe,o=!!t.unsafeReturn,a=!!t.safeReturn,c=t.returns?.defaults,l=Object.entries(t.params),u=l.length,p=e.name||t.name||"anonymous",f=function(...m){if(tt>0)return e.apply(this,m);let d=i||!s&&V.safety!=="none",y=r&&(a||!o&&V.safety==="all");if(!d&&!y)return e.apply(this,m);if(m.length>0&&_e(m[0]))return m[0];if(d){let E=m.length===1&&typeof m[0]=="object"&&m[0]!==null&&!Array.isArray(m[0]),_=[];if(E){let b=m[0];for(let T=0;T<u;T++){let[k,w]=l[T],j=b[k];if(_e(j)){_.push(j);continue}if(w.required&&j===void 0){_.push(Se(`Missing required parameter '${k}'`,{path:`${p}.${k}`,expected:typeof w.type=="string"?w.type:w.type?.description||"value",actual:"undefined",loc:w.loc}));continue}if(j!==void 0){let C=Ue(j,w.type,`${p}.${k}`);C&&(w.loc&&(C.loc=w.loc),_.push(C))}}}else for(let b=0;b<u;b++){let[T,k]=l[b],w=m[b];if(_e(w)){_.push(w);continue}if(k.required&&w===void 0){_.push(Se(`Missing required parameter '${T}'`,{path:`${p}.${T}`,expected:typeof k.type=="string"?k.type:k.type?.description||"value",actual:"undefined",loc:k.loc}));continue}if(w!==void 0){let j=Ue(w,k.type,`${p}.${T}`);j&&(k.loc&&(j.loc=k.loc),_.push(j))}}if(_.length>0)return ar(_,p)}let x=V.callStacks||V.debug;x&&ks(p);try{let E=e.apply(this,m);if(y&&t.returns&&!_e(E)){let _=c&&typeof E=="object"&&E!==null?Object.assign({},c,E):E,b=Ue(_,t.returns.type,`${p}()`);if(b)return x&&un(),b}return x&&un(),E}catch(E){return x&&un(),Se(E.message||String(E),{path:p,cause:E})}};return Object.defineProperty(f,"name",{value:e.name}),f.__tjs=t,f.__tjs.schema=()=>Vt(t),f}function Rs(e){let t=new Proxy(e,{construct(n,r,s){return Reflect.construct(n,r,s)},apply(n,r,s){return Reflect.construct(n,s)}});Object.defineProperty(t,"name",{value:e.name});for(let n of Object.getOwnPropertyNames(e))n!=="length"&&n!=="name"&&n!=="prototype"&&Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n));return t}function Ns(){let e={...V},t=e.maxStackSize??St,n=new Array(t).fill(""),r=0,s=0,i=e.maxErrors??mn,o=new Array(i).fill(null),a=0,c=0,l=0,u=0;function p(v){e={...e,...v}}function f(){return{...e}}function m(v){(e.callStacks||e.debug)&&v&&(n[r]=v,r=(r+1)%t,s<t&&s++)}function d(){(e.callStacks||e.debug)&&s>0&&(r=(r-1+t)%t,s--)}function y(){if(s===0)return[];let v=[],I=(r-s+t)%t;for(let O=0;O<s;O++)v.push(n[(I+O)%t]);return v}function x(){e={...sr},r=0,s=0,a=0,c=0,l=0,u=0}function E(){u++}function _(){u>0&&u--}function b(){return u>0}let T=new Map;function k(v,I,O){T.has(v)||T.set(v,new Map),T.get(v).set(I,O)}function w(v,I){let O=typeof v,F;if(v==null)return;if(O==="string")F="String";else if(O==="number")F="Number";else if(O==="boolean")F="Boolean";else if(Array.isArray(v))F="Array";else if(O==="object")F=v.constructor?.name||"Object";else return;let H=F;for(;H;){let Ge=T.get(H);if(Ge?.has(I))return Ge.get(I);if(O==="object"&&!Array.isArray(v)){if(H=Object.getPrototypeOf(H===F?v:Object.getPrototypeOf(v))?.constructor?.name,H==="Object"||H===F)break}else break}let se=T.get("Object");if(se?.has(I))return se.get(I)}function j(v,I,O){let F=O===null?"null":typeof O,H=e.callStacks||e.debug?y():void 0,se=new et(`Expected ${I} for '${v}', got ${F}`,v,I,F,H);if(e.trackErrors!==!1&&(o[a]=se,a=(a+1)%i,c<i&&c++,l++),e.logTypeErrors&&console.error(`[TJS TypeError] ${se.message}`),e.throwTypeErrors)throw se;return se}function C(){if(e.trackErrors===!1||c===0)return[];let v=[],I=(a-c+i)%i;for(let O=0;O<c;O++)v.push(o[(I+O)%i]);return v}function $(){let v=C();return a=0,c=0,l=0,v}function R(){return l}function A(v,I){let O={$error:!0,message:v,...I};if((e.callStacks||e.debug)&&s>0){let F=I?.path?[...y(),I.path]:y();O.stack=F}return O}function P(v,I){return v==null?j(`bang.${I}`,"non-null",v):tr(v)?v:v[I]}return{version:oe,MonadicError:et,typeError:j,isMonadicError:tr,bang:P,isError:_e,error:A,composeErrors:ar,typeOf:Qe,isNativeType:Cs,checkType:Ue,validateArgs:cr,wrap:lr,wrapClass:Rs,compareVersions:nr,versionsCompatible:rr,createRuntime:Ns,configure:p,getConfig:f,pushStack:m,popStack:d,getStack:y,errors:C,clearErrors:$,getErrorCount:R,resetRuntime:x,enterUnsafe:E,exitUnsafe:_,isUnsafeMode:b,validate:Es,infer:fn.infer.bind(fn),Type:ee,isRuntimeType:ve,Union:sn,Generic:Ze,Enum:ln,FunctionPredicate:xt,Nullable:nn,Optional:rn,TArray:on,TString:zt,TNumber:Gt,TBoolean:Ht,TInteger:Zt,TPositiveInt:Yt,TNonEmptyString:Xt,TEmail:Qt,TUrl:en,TUuid:tn,TPair:an,TRecord:cn,Is:Xe,IsNot:vs,Eq:or,NotEq:Ms,TypeOf:As,tjsEquals:Tt,registerExtension:k,resolveExtension:w}}var Le={version:oe,MonadicError:et,typeError:vo,isMonadicError:tr,isError:_e,error:Se,composeErrors:ar,typeOf:Qe,isNativeType:Cs,checkType:Ue,validateArgs:cr,wrap:lr,wrapClass:Rs,compareVersions:nr,versionsCompatible:rr,configure:Ro,getConfig:No,pushStack:ks,popStack:un,getStack:ir,errors:js,clearErrors:Po,getErrorCount:Io,resetRuntime:Do,enterUnsafe:Ao,exitUnsafe:Mo,isUnsafeMode:Co,createRuntime:Ns,validate:Es,infer:fn.infer.bind(fn),Type:ee,isRuntimeType:ve,Union:sn,Generic:Ze,Enum:ln,FunctionPredicate:xt,Nullable:nn,Optional:rn,TArray:on,TString:zt,TNumber:Gt,TBoolean:Ht,TInteger:Zt,TPositiveInt:Yt,TNonEmptyString:Xt,TEmail:Qt,TUrl:en,TUuid:tn,Timestamp:Qn,LegalDate:er,TPair:an,TRecord:cn,Is:Xe,IsNot:vs,Eq:or,NotEq:Ms,TypeOf:As};function ur(){let e=globalThis;if(e.__tjs){let t=e.__tjs.version;if(typeof t!="string")return e.__tjs=Le,Le;let n=nr(oe,t);return n===0||(rr(oe,t)?n>0?(console.info(`TJS runtime: upgrading ${t} \u2192 ${oe}`),e.__tjs=Le):console.info(`TJS runtime: keeping ${t} (newer than ${oe})`):(console.warn(`TJS runtime version conflict: ${t} vs ${oe} (major version mismatch)`),n>0&&(console.warn(`Upgrading to ${oe} - check for breaking changes`),e.__tjs=Le))),e.__tjs}return e.__tjs=Le,Le}function Oo(e){return`
|
|
171
171
|
// TJS runtime wrapper (skips unsafe functions)
|
|
172
172
|
if (typeof ${e}.__tjs === 'object' && !${e}.__tjs.unsafe && typeof globalThis.__tjs?.wrap === 'function') {
|
|
173
173
|
${e} = globalThis.__tjs.wrap(${e}, ${e}.__tjs)
|
|
@@ -339,7 +339,7 @@ ${Un}`}),!Ir&&!Dr){let ue=`${He.file}:${He.line}`,fe=la(K,Pe,ue);fe&&L.body&&L.b
|
|
|
339
339
|
${fe.preamble}
|
|
340
340
|
`}),fe.suffix&&T.push({position:L.body.end-1,text:`
|
|
341
341
|
${fe.suffix}
|
|
342
|
-
`}))}}k.sort((L,K)=>K.start-L.start);let w=_.source;for(let{start:L,end:K}of k)w=w.slice(0,L)+w.slice(K);for(let L of T){let K=0;for(let J of k)J.start<L.position&&(K+=J.end-J.start);L.position-=K}T.sort((L,K)=>K.position-L.position);for(let{position:L,text:K}of T)w=w.slice(0,L)+K+w.slice(L);let j=w.includes("__tjs.typeError("),C=w.includes("__tjs.pushStack("),$=w.includes("Is("),R=w.includes("IsNot("),A=w.includes("Eq("),P=w.includes("NotEq("),v=w.includes("TypeOf("),I=/\bType\(/.test(w),O=/\bGeneric\(/.test(w),F=/\bFunctionPredicate\(/.test(w),H=/\bEnum\(/.test(w),se=/\bUnion\(/.test(w),Ge=w.includes("__tjs.bang("),Bn=_.tjsModes.tjsSafeEval;if(j||C||$||R||A||P||v||I||O||F||H||se||Ge||Bn){let L=[];j&&L.push("class MonadicError extends Error{constructor(m,p,e,a,c){super(m);this.name='MonadicError';this.path=p;this.expected=e;this.actual=a;this.callStack=c}}",`function typeError(p,e,v){const a=v===null?'null':typeof v;const
|
|
342
|
+
`}))}}k.sort((L,K)=>K.start-L.start);let w=_.source;for(let{start:L,end:K}of k)w=w.slice(0,L)+w.slice(K);for(let L of T){let K=0;for(let J of k)J.start<L.position&&(K+=J.end-J.start);L.position-=K}T.sort((L,K)=>K.position-L.position);for(let{position:L,text:K}of T)w=w.slice(0,L)+K+w.slice(L);let j=w.includes("__tjs.typeError("),C=w.includes("__tjs.pushStack("),$=w.includes("Is("),R=w.includes("IsNot("),A=w.includes("Eq("),P=w.includes("NotEq("),v=w.includes("TypeOf("),I=/\bType\(/.test(w),O=/\bGeneric\(/.test(w),F=/\bFunctionPredicate\(/.test(w),H=/\bEnum\(/.test(w),se=/\bUnion\(/.test(w),Ge=w.includes("__tjs.bang("),Bn=_.tjsModes.tjsSafeEval;if(j||C||$||R||A||P||v||I||O||F||H||se||Ge||Bn){let L=[];j&&L.push("class MonadicError extends Error{constructor(m,p,e,a,c,r){super(m);this.name='MonadicError';this.path=p;this.expected=e;this.actual=a;this.callStack=c;this.reason=r}}",`function typeError(p,e,v,r){const a=v===null?'null':typeof v;const m=r?'Expected '+e+" for '"+p+"': "+r:'Expected '+e+" for '"+p+"', got "+a;const err=new MonadicError(m,p,e,a,undefined,r);const c=globalThis.__tjs?.getConfig?.();if(c?.logTypeErrors)console.error('[TJS TypeError] '+err.message);if(c?.throwTypeErrors)throw err;return err}`,"function isMonadicError(v){return v instanceof Error&&v.name==='MonadicError'&&'path' in v}"),C&&L.push("const __stack=[];function pushStack(n){__stack.push(n)}function popStack(){__stack.pop()}function getStack(){return[...__stack]}"),A&&L.push("function Eq(a,b){if(a instanceof String||a instanceof Number||a instanceof Boolean)a=a.valueOf();if(b instanceof String||b instanceof Number||b instanceof Boolean)b=b.valueOf();if(a===b)return true;if(typeof a==='number'&&typeof b==='number'&&isNaN(a)&&isNaN(b))return true;if((a===null||a===undefined)&&(b===null||b===undefined))return true;return false}"),P&&L.push("function NotEq(a,b){return!Eq(a,b)}"),v&&L.push("function TypeOf(v){return v===null?'null':typeof v}"),$&&L.push("const tjsEquals=Symbol.for('tjs.equals');function Is(a,b){if(a!=null&&typeof a==='object'&&typeof a[tjsEquals]==='function')return a[tjsEquals](b);if(b!=null&&typeof b==='object'&&typeof b[tjsEquals]==='function')return b[tjsEquals](a);if(a!=null&&typeof a==='object'&&typeof a.Equals==='function')return a.Equals(b);if(b!=null&&typeof b==='object'&&typeof b.Equals==='function')return b.Equals(a);if(a instanceof String||a instanceof Number||a instanceof Boolean)a=a.valueOf();if(b instanceof String||b instanceof Number||b instanceof Boolean)b=b.valueOf();if(a===b)return true;if(typeof a==='number'&&typeof b==='number'&&isNaN(a)&&isNaN(b))return true;if((a==null)&&(b==null))return true;if(a==null||b==null)return false;if(typeof a!==typeof b)return false;if(typeof a!=='object')return false;if(a instanceof Set&&b instanceof Set){if(a.size!==b.size)return false;for(const v of a)if(!b.has(v))return false;return true}if(a instanceof Map&&b instanceof Map){if(a.size!==b.size)return false;for(const[k,v]of a)if(!b.has(k)||!Is(v,b.get(k)))return false;return true}if(a instanceof Date&&b instanceof Date)return a.getTime()===b.getTime();if(a instanceof RegExp&&b instanceof RegExp)return a.toString()===b.toString();if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return false;return a.every((v,i)=>Is(v,b[i]))}if(Array.isArray(a)!==Array.isArray(b))return false;const ka=Object.keys(a),kb=Object.keys(b);if(ka.length!==kb.length)return false;return ka.every(k=>Is(a[k],b[k]))}"),R&&L.push("function IsNot(a,b){return!Is(a,b)}"),I&&L.push("function Type(d,p,e){const t={description:d,__runtimeType:true};if(typeof p==='function'){t.check=p;t.default=e??null}else{const ex=e??p;t.default=ex;t.check=v=>{if(ex===null)return true;return typeof v===typeof ex}}return t}"),O&&L.push("function Generic(tp,pred,d){const f=(...args)=>{const t={description:d||'generic',__runtimeType:true,check:v=>pred(v,...args)};return t};f.__runtimeType=true;f.description=d;return f}"),F&&L.push("function FunctionPredicate(n,s,b){if(Array.isArray(s)&&b){const f=(...a)=>FunctionPredicate(n,b(...a));f.typeParamNames=s.map(p=>Array.isArray(p)?p[0]:p);f.description=n;f.__runtimeType=true;return f}const spec=typeof s==='function'?{}:s||{};return{description:n,params:spec.params||{},returns:spec.returns,returnContract:spec.returnContract||'assertReturns',check:v=>typeof v==='function',__runtimeType:true}}"),H&&L.push("function Enum(d,m){const vals=typeof m==='object'?Object.values(m):[];return{description:d,check:v=>vals.includes(v),values:vals,__runtimeType:true}}"),se&&L.push("function Union(d,...v){const vals=v.flat();return{description:d,check:x=>vals.includes(x),values:vals,__runtimeType:true}}"),Ge&&(j||L.push("class MonadicError extends Error{constructor(m,p,e,a,c,r){super(m);this.name='MonadicError';this.path=p;this.expected=e;this.actual=a;this.callStack=c;this.reason=r}}",`function typeError(p,e,v,r){const a=v===null?'null':typeof v;const m=r?'Expected '+e+" for '"+p+"': "+r:'Expected '+e+" for '"+p+"', got "+a;const err=new MonadicError(m,p,e,a,undefined,r);const c=globalThis.__tjs?.getConfig?.();if(c?.logTypeErrors)console.error('[TJS TypeError] '+err.message);if(c?.throwTypeErrors)throw err;return err}`,"function isMonadicError(v){return v instanceof Error&&v.name==='MonadicError'&&'path' in v}"),L.push("function bang(o,p){if(o===null||o===undefined)return typeError('bang.'+p,'non-null',o);if(isMonadicError(o))return o;return o[p]}"));let K=L.length>0?L.join(`;
|
|
343
343
|
`)+`;
|
|
344
344
|
`:"",J=[];j&&J.push("typeError","isMonadicError"),C&&J.push("pushStack","popStack","getStack"),A&&J.push("Eq"),P&&J.push("NotEq"),v&&J.push("TypeOf"),$&&J.push("Is","tjsEquals"),R&&J.push("IsNot"),I&&J.push("Type"),O&&J.push("Generic"),F&&J.push("FunctionPredicate"),H&&J.push("Enum"),se&&J.push("Union"),Ge&&(J.push("bang"),j||J.push("typeError","isMonadicError"));let ge=J.length>0?`{${J.join(",")}}`:"undefined";w=K+`const __tjs = globalThis.__tjs?.createRuntime?.() ?? ${ge};
|
|
345
345
|
`+w}Bn&&(w=`import { Eval, SafeFunction } from 'tjs-lang';
|