tjs-lang 0.8.3 → 0.8.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/CLAUDE.md +23 -1
- package/demo/docs.json +7 -7
- package/dist/experiments/predicates/css.predicates.d.ts +13 -0
- package/dist/experiments/predicates/verify.d.ts +39 -0
- package/dist/index.js +104 -100
- package/dist/index.js.map +4 -4
- package/dist/src/lang/browser-from-ts.d.ts +38 -0
- package/dist/src/lang/browser.d.ts +13 -0
- package/dist/src/lang/index.d.ts +2 -0
- package/dist/src/lang/predicate-schema.d.ts +39 -0
- package/dist/src/lang/predicate.d.ts +103 -0
- package/dist/src/lang/transpiler.d.ts +2 -0
- package/dist/src/lang/ts-cdn-shim.d.ts +2 -0
- package/dist/src/vm/runtime.d.ts +22 -0
- package/dist/tjs-browser-from-ts.js +58 -0
- package/dist/tjs-browser-from-ts.js.map +7 -0
- package/dist/tjs-browser.js +370 -0
- package/dist/tjs-browser.js.map +7 -0
- package/dist/tjs-eval.js +29 -29
- package/dist/tjs-eval.js.map +3 -3
- package/dist/tjs-from-ts.js +1 -1
- package/dist/tjs-from-ts.js.map +2 -2
- package/dist/tjs-lang.js +86 -82
- package/dist/tjs-lang.js.map +4 -4
- package/dist/tjs-vm.js +45 -45
- package/dist/tjs-vm.js.map +3 -3
- package/llms.txt +2 -0
- package/package.json +15 -1
- package/src/lang/browser-bundle.test.ts +69 -0
- package/src/lang/browser-from-ts.ts +81 -0
- package/src/lang/browser.ts +13 -0
- package/src/lang/runtime.test.ts +46 -0
- package/src/lang/ts-cdn-shim.ts +35 -0
- package/src/runtime.test.ts +6 -6
- package/src/vm/equality.test.ts +59 -0
- package/src/vm/runtime.ts +26 -59
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser TypeScript→TJS — lazy-loads the TypeScript compiler from a CDN on
|
|
3
|
+
* demand, so the bundle stays small and only pays the (~MB) compiler download
|
|
4
|
+
* when you actually transpile TS. `acorn` + `tosijs-schema` are bundled in; the
|
|
5
|
+
* `typescript` import in `from-ts.ts` is aliased (at build time) to a Proxy that
|
|
6
|
+
* forwards to the lazily-loaded compiler (see `ts-cdn-shim.ts`).
|
|
7
|
+
*
|
|
8
|
+
* const { fromTS } = await import('https://cdn.jsdelivr.net/npm/tjs-lang/dist/tjs-browser-from-ts.js')
|
|
9
|
+
* const { code } = await fromTS('const x: number = 1', { emitTJS: true })
|
|
10
|
+
*
|
|
11
|
+
* Zero config by default. Override the compiler source with `typescriptUrl` (or
|
|
12
|
+
* preload it yourself onto `globalThis.__TJS_TS__`).
|
|
13
|
+
*/
|
|
14
|
+
import type { FromTSOptions, FromTSResult } from './emitters/from-ts';
|
|
15
|
+
/**
|
|
16
|
+
* Default CDN for the TypeScript compiler. **esm.sh** — verified the only CDN
|
|
17
|
+
* that reliably serves `typescript` as ESM (default export = the compiler
|
|
18
|
+
* namespace), in ~700ms. The on-the-fly bundlers choke on typescript's ~10MB
|
|
19
|
+
* CommonJS size: jsDelivr `+esm`, esm.run → timeout; skypack → dead. So esm.sh
|
|
20
|
+
* it is. Override via `BrowserFromTSOptions.typescriptUrl` (e.g. a self-hosted
|
|
21
|
+
* copy) or preload your own compiler onto `globalThis.__TJS_TS__`.
|
|
22
|
+
*
|
|
23
|
+
* NOTE: only the *TypeScript* path depends on this. The TJS/AJS transpiler
|
|
24
|
+
* (`tjs-lang/browser`) is fully self-contained and loads from ANY CDN.
|
|
25
|
+
*/
|
|
26
|
+
export declare const DEFAULT_TYPESCRIPT_URL = "https://esm.sh/typescript@5";
|
|
27
|
+
export interface BrowserFromTSOptions extends FromTSOptions {
|
|
28
|
+
/** Override the CDN URL the TypeScript compiler is lazy-loaded from. */
|
|
29
|
+
typescriptUrl?: string;
|
|
30
|
+
}
|
|
31
|
+
/** Lazy-load the TypeScript compiler (once) onto `globalThis.__TJS_TS__`. */
|
|
32
|
+
export declare function loadTypeScript(url?: string): Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* Transpile TypeScript → TJS (or JS) in the browser. Lazy-loads the TypeScript
|
|
35
|
+
* compiler on first call, then runs the same `fromTS` logic as Node.
|
|
36
|
+
*/
|
|
37
|
+
export declare function fromTS(source: string, options?: BrowserFromTSOptions): Promise<FromTSResult>;
|
|
38
|
+
export type { FromTSOptions, FromTSResult } from './emitters/from-ts';
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Self-contained browser entry — the TJS/AJS transpiler with `acorn` and
|
|
3
|
+
* `tosijs-schema` bundled in (no external/bare imports). Build target
|
|
4
|
+
* `tjs-browser` (see `scripts/build.ts`) emits a single ESM file you can
|
|
5
|
+
* `import()` from any CDN with zero import-map / config:
|
|
6
|
+
*
|
|
7
|
+
* const { tjs } = await import('https://cdn.jsdelivr.net/npm/tjs-lang/dist/tjs-browser.js')
|
|
8
|
+
* const { code } = tjs("function greet(name: 'x'): '' { return 'hi' }")
|
|
9
|
+
*
|
|
10
|
+
* For TypeScript→TJS in the browser, use `tjs-lang/browser/from-ts` (which
|
|
11
|
+
* lazy-loads the TypeScript compiler from a CDN on demand).
|
|
12
|
+
*/
|
|
13
|
+
export * from './transpiler';
|
package/dist/src/lang/index.d.ts
CHANGED
|
@@ -25,6 +25,8 @@ import type { TranspileOptions, TranspileResult, FunctionSignature } from './typ
|
|
|
25
25
|
export * from './types';
|
|
26
26
|
export { parse, preprocess, extractTDoc, validateSingleFunction, extractFunctions, } from './parser';
|
|
27
27
|
export { dialectForFilename, sourceKindForFilename, type Dialect, type SourceKind, } from './dialect';
|
|
28
|
+
export { verifyPredicate, compilePredicate, suggest, effectfulFromAtoms, formatPredicateDiagnostics, PredicateFuelExhausted, type PredicateDiagnostic, type PredicateVerifyResult, type VerifyPredicateOptions, type CompilePredicateOptions, type Suggestion, type SuggestOptions, } from './predicate';
|
|
29
|
+
export { compilePredicateSchema, validatePredicateSchema, type PredicateSchema, type SchemaError, type SchemaValidationResult, type PredicateSchemaOptions, } from './predicate-schema';
|
|
28
30
|
export { transformFunction } from './emitters/ast';
|
|
29
31
|
export { transpileToJS, stripModuleSyntax, stripTjsPreamble, type TJSTranspileOptions, type TJSTranspileResult, type TJSTypeInfo, } from './emitters/js';
|
|
30
32
|
export { generateDTS, typeDescriptorToTS, type GenerateDTSOptions, } from './emitters/dts';
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { CompilePredicateOptions } from './predicate';
|
|
2
|
+
/** A JSON-Schema node, optionally carrying a `$predicate` (predicate source). */
|
|
3
|
+
export interface PredicateSchema {
|
|
4
|
+
type?: 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array' | 'null';
|
|
5
|
+
properties?: Record<string, PredicateSchema>;
|
|
6
|
+
required?: string[];
|
|
7
|
+
items?: PredicateSchema;
|
|
8
|
+
/**
|
|
9
|
+
* Predicate cluster source. The LAST top-level function is the entry; it
|
|
10
|
+
* receives the value at this node and returns a boolean. Ignored by naive
|
|
11
|
+
* validators (it's a custom keyword); run by predicate-aware ones.
|
|
12
|
+
*/
|
|
13
|
+
$predicate?: string;
|
|
14
|
+
[k: string]: unknown;
|
|
15
|
+
}
|
|
16
|
+
export interface SchemaError {
|
|
17
|
+
/** JSON-pointer-ish path to the offending value, e.g. `/style/color`. */
|
|
18
|
+
path: string;
|
|
19
|
+
message: string;
|
|
20
|
+
}
|
|
21
|
+
export interface SchemaValidationResult {
|
|
22
|
+
valid: boolean;
|
|
23
|
+
errors: SchemaError[];
|
|
24
|
+
}
|
|
25
|
+
export interface PredicateSchemaOptions extends CompilePredicateOptions {
|
|
26
|
+
/**
|
|
27
|
+
* Validate structure only — skip every `$predicate` (i.e. behave like a naive
|
|
28
|
+
* JSON-Schema validator). Useful for demonstrating progressive enhancement.
|
|
29
|
+
*/
|
|
30
|
+
ignorePredicates?: boolean;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Compile a predicate-aware JSON-Schema into a reusable validator. Every
|
|
34
|
+
* `$predicate` cluster is verified + compiled once (fuel-bounded, IO-rejected);
|
|
35
|
+
* an invalid/unsafe predicate throws here, at compile time.
|
|
36
|
+
*/
|
|
37
|
+
export declare function compilePredicateSchema(schema: PredicateSchema, opts?: PredicateSchemaOptions): (value: unknown) => SchemaValidationResult;
|
|
38
|
+
/** One-shot convenience: compile + validate. */
|
|
39
|
+
export declare function validatePredicateSchema(schema: PredicateSchema, value: unknown, opts?: PredicateSchemaOptions): SchemaValidationResult;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
export interface PredicateDiagnostic {
|
|
2
|
+
/** Name of the predicate the problem is in. */
|
|
3
|
+
predicate: string;
|
|
4
|
+
message: string;
|
|
5
|
+
line: number;
|
|
6
|
+
column: number;
|
|
7
|
+
}
|
|
8
|
+
export interface PredicateVerifyResult {
|
|
9
|
+
safe: boolean;
|
|
10
|
+
/** Names of the top-level functions found (the predicate cluster). */
|
|
11
|
+
predicates: string[];
|
|
12
|
+
diagnostics: PredicateDiagnostic[];
|
|
13
|
+
}
|
|
14
|
+
export interface VerifyPredicateOptions {
|
|
15
|
+
/**
|
|
16
|
+
* Names that are effectful and must not be called — IO atoms + JS IO globals.
|
|
17
|
+
* Compose from the atom registry with `effectfulFromAtoms`. The built-in JS IO
|
|
18
|
+
* globals are always included.
|
|
19
|
+
*/
|
|
20
|
+
effectful?: Set<string>;
|
|
21
|
+
/**
|
|
22
|
+
* Externally-verified predicate names this source may compose with (a shared
|
|
23
|
+
* registry), in addition to the functions declared in `source`.
|
|
24
|
+
*/
|
|
25
|
+
knownPredicates?: Set<string>;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Build the effectful-name set from a VM atom registry: every atom tagged
|
|
29
|
+
* `effects: 'io'`, plus the built-in JS IO globals. This is how the verifier
|
|
30
|
+
* consumes the atom-effects classification (the keystone).
|
|
31
|
+
*/
|
|
32
|
+
export declare function effectfulFromAtoms(atoms: Record<string, {
|
|
33
|
+
op?: string;
|
|
34
|
+
effects?: 'pure' | 'io';
|
|
35
|
+
}>): Set<string>;
|
|
36
|
+
/**
|
|
37
|
+
* Verify every top-level function declaration in `source` is predicate-safe.
|
|
38
|
+
* Returns all diagnostics; `safe` is true iff there are none (closure property).
|
|
39
|
+
*/
|
|
40
|
+
export declare function verifyPredicate(source: string, opts?: VerifyPredicateOptions): PredicateVerifyResult;
|
|
41
|
+
/** Format diagnostics for a thrown error / log. */
|
|
42
|
+
export declare function formatPredicateDiagnostics(d: PredicateDiagnostic[]): string;
|
|
43
|
+
export interface Suggestion {
|
|
44
|
+
value: string;
|
|
45
|
+
/**
|
|
46
|
+
* `'value'` — a concrete candidate (a keyword/literal the predicate accepts);
|
|
47
|
+
* `'stub'` — a partial completion to keep typing (e.g. `var(--`, `calc(`),
|
|
48
|
+
* mined from a `startsWith(...)` guard. TS's `string` fallback
|
|
49
|
+
* offers neither; a finite TS union offers only `'value'`.
|
|
50
|
+
*/
|
|
51
|
+
kind: 'value' | 'stub';
|
|
52
|
+
}
|
|
53
|
+
export interface SuggestOptions extends CompilePredicateOptions {
|
|
54
|
+
/** Only return candidates relevant to the text typed so far. */
|
|
55
|
+
prefix?: string;
|
|
56
|
+
/** Cap the number of suggestions (default 50). */
|
|
57
|
+
limit?: number;
|
|
58
|
+
/**
|
|
59
|
+
* Run each mined *value* through the compiled entry predicate and keep only
|
|
60
|
+
* those that actually pass — so completions are guaranteed valid, not merely
|
|
61
|
+
* enumerated. Default true when the cluster is predicate-safe; stubs are never
|
|
62
|
+
* validated (they're partial by construction).
|
|
63
|
+
*/
|
|
64
|
+
validate?: boolean;
|
|
65
|
+
/** Entry predicate to validate against (default: last top-level function). */
|
|
66
|
+
entry?: string;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Mine a predicate cluster's source for autocomplete candidates. Two sources:
|
|
70
|
+
* - **values** — string literals compared with `==`/`===` and members of
|
|
71
|
+
* array literals (the keyword sets a predicate checks membership against).
|
|
72
|
+
* - **stubs** — the argument of a `.startsWith(...)` guard, surfaced as a
|
|
73
|
+
* partial completion (`var(--`, `calc(`) the user keeps typing.
|
|
74
|
+
*
|
|
75
|
+
* Pure syntactic mining over the parsed source — no execution. By default the
|
|
76
|
+
* mined *values* are then run through the compiled entry predicate, so the
|
|
77
|
+
* returned set is exactly what the predicate accepts (a literal that only ever
|
|
78
|
+
* appears in a `!=` / negative context is dropped). This is the autocomplete
|
|
79
|
+
* win over a TS `string` fallback (which suggests nothing) and over a finite TS
|
|
80
|
+
* union (which can't offer the open-ended `var(--`/`calc(` stubs).
|
|
81
|
+
*/
|
|
82
|
+
export declare function suggest(source: string, opts?: SuggestOptions): Suggestion[];
|
|
83
|
+
/** Thrown when a predicate exceeds its fuel budget (likely a pathological input). */
|
|
84
|
+
export declare class PredicateFuelExhausted extends Error {
|
|
85
|
+
constructor(budget: number);
|
|
86
|
+
}
|
|
87
|
+
export interface CompilePredicateOptions extends VerifyPredicateOptions {
|
|
88
|
+
/** Max fuel per top-level predicate call (default 1,000,000). */
|
|
89
|
+
fuel?: number;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Verify, then compile the cluster to native synchronous JS functions —
|
|
93
|
+
* **fuel-bounded and global-shadowed**. Throws (with located diagnostics) at
|
|
94
|
+
* definition time if not predicate-safe.
|
|
95
|
+
*
|
|
96
|
+
* Each compiled predicate runs with a fresh fuel budget; a runaway input throws
|
|
97
|
+
* `PredicateFuelExhausted` rather than hanging. The effectful globals are
|
|
98
|
+
* shadowed to `undefined` as defense-in-depth beneath the static verifier.
|
|
99
|
+
*
|
|
100
|
+
* NOTE: preserves JS semantics (no structural-`==` rewrite yet — a future
|
|
101
|
+
* opt-in). Emission is offset-spliced source, not a full AJS-AST→JS codegen.
|
|
102
|
+
*/
|
|
103
|
+
export declare function compilePredicate(source: string, exportNames: string[], opts?: CompilePredicateOptions): Record<string, (...args: any[]) => any>;
|
|
@@ -12,6 +12,8 @@
|
|
|
12
12
|
export { transpile, ajs, tjs, createAgent, getToolDefinitions } from './core';
|
|
13
13
|
export { parse, preprocess, extractTDoc } from './parser';
|
|
14
14
|
export { dialectForFilename, sourceKindForFilename, type Dialect, type SourceKind, } from './dialect';
|
|
15
|
+
export { verifyPredicate, compilePredicate, suggest, effectfulFromAtoms, formatPredicateDiagnostics, PredicateFuelExhausted, type PredicateDiagnostic, type PredicateVerifyResult, type VerifyPredicateOptions, type CompilePredicateOptions, type Suggestion, type SuggestOptions, } from './predicate';
|
|
16
|
+
export { compilePredicateSchema, validatePredicateSchema, type PredicateSchema, type SchemaError, type SchemaValidationResult, type PredicateSchemaOptions, } from './predicate-schema';
|
|
15
17
|
export { transformFunction } from './emitters/ast';
|
|
16
18
|
export { transpileToJS } from './emitters/js';
|
|
17
19
|
export type { TJSTranspileOptions, TJSTranspileResult, TJSTypeInfo, } from './emitters/js';
|
package/dist/src/vm/runtime.d.ts
CHANGED
|
@@ -89,6 +89,17 @@ export interface RuntimeContext {
|
|
|
89
89
|
callDepth?: number;
|
|
90
90
|
}
|
|
91
91
|
export type AtomExec = (step: any, ctx: RuntimeContext) => Promise<void>;
|
|
92
|
+
/**
|
|
93
|
+
* Effect classification of an atom.
|
|
94
|
+
* - `'pure'`: deterministic, no IO, no capability access, no observable side
|
|
95
|
+
* effects — safe inside a synchronous predicate (see the predicate verifier).
|
|
96
|
+
* - `'io'`: touches `ctx.capabilities` (fetch/store/llm/agent/code), or is
|
|
97
|
+
* nondeterministic (random/uuid), or has side effects (console). Not allowed
|
|
98
|
+
* in a predicate.
|
|
99
|
+
* Defaults to `'pure'`; effectful atoms must opt into `'io'`. The invariant
|
|
100
|
+
* "anything touching ctx.capabilities is tagged 'io'" is guarded by a test.
|
|
101
|
+
*/
|
|
102
|
+
export type AtomEffects = 'pure' | 'io';
|
|
92
103
|
export interface AtomDef {
|
|
93
104
|
op: OpCode;
|
|
94
105
|
inputSchema: any;
|
|
@@ -97,6 +108,7 @@ export interface AtomDef {
|
|
|
97
108
|
docs?: string;
|
|
98
109
|
timeoutMs?: number;
|
|
99
110
|
cost?: number | ((input: any, ctx: RuntimeContext) => number);
|
|
111
|
+
effects?: AtomEffects;
|
|
100
112
|
}
|
|
101
113
|
export interface Atom<I, O> extends AtomDef {
|
|
102
114
|
create(input: I): I & {
|
|
@@ -107,6 +119,8 @@ export interface AtomOptions {
|
|
|
107
119
|
docs?: string;
|
|
108
120
|
timeoutMs?: number;
|
|
109
121
|
cost?: number | ((input: any, ctx: RuntimeContext) => number);
|
|
122
|
+
/** Effect class — defaults to `'pure'`; effectful atoms set `'io'`. */
|
|
123
|
+
effects?: AtomEffects;
|
|
110
124
|
}
|
|
111
125
|
export interface RunResult {
|
|
112
126
|
result: any;
|
|
@@ -349,3 +363,11 @@ export declare const coreAtoms: {
|
|
|
349
363
|
releaseProcedure: Atom<Record<string, any>, boolean>;
|
|
350
364
|
clearExpiredProcedures: Atom<Record<string, any>, number>;
|
|
351
365
|
};
|
|
366
|
+
/**
|
|
367
|
+
* Effectful core atoms — anything that touches `ctx.capabilities`
|
|
368
|
+
* (fetch/store/llm/agent/code), is nondeterministic (random/uuid), or has
|
|
369
|
+
* observable side effects (console). Tagged centrally so the list reads as one
|
|
370
|
+
* audit surface; a test asserts every capability-touching atom is in here.
|
|
371
|
+
* Everything else defaults to `effects: 'pure'`.
|
|
372
|
+
*/
|
|
373
|
+
export declare const EFFECTFUL_CORE_OPS: readonly ["httpFetch", "storeGet", "storeSet", "storeQuery", "storeVectorSearch", "llmPredict", "agentRun", "transpileCode", "runCode", "random", "uuid", "consoleLog", "consoleWarn", "consoleError", "storeProcedure", "releaseProcedure", "clearExpiredProcedures", "cache", "memoize"];
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
var Et=Object.defineProperty;var Y=(e,t)=>()=>(e&&(t=e(e=0)),t);var jt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),wt=(e,t)=>{for(var n in t)Et(e,n,{get:t[n],enumerable:!0})};function Fe(){let e=globalThis[Nt];if(!e)throw new Error("TypeScript not loaded. Use fromTS() from tjs-lang/browser/from-ts, which lazy-loads the compiler before transpiling.");return e}var Nt,Pt,l,Be=Y(()=>{"use strict";Nt="__TJS_TS__";Pt=new Proxy({},{get:(e,t)=>Fe()[t],has:(e,t)=>t in Fe()}),l=Pt});function U(e,t,n){let s=t?.schema||t,r=typeof n=="function"?n:n?.onError,o=typeof n=="object"?n?.strict??n?.fullScan??!1:!1,i=[],u=p=>(r&&r(i.join(".")||"root",p),!1),f=(p,a)=>{if(a.anyOf){for(let m of a.anyOf)if(U(p,m))return!0;return u("Union mismatch")}if(a.const!==void 0)return p===a.const||u("Const mismatch");if(p===null){let m=a.type==="null"&&!a["x-tjs-undefined"],d=Array.isArray(a.type)&&a.type.includes("null");return m||d||!a.type||u("Expected value, got null")}if(p===void 0){let m=a.type==="null"&&a["x-tjs-undefined"],d=Array.isArray(a.type)&&a.type.includes("null");return m||d||!a.type||u("Expected value, got undefined")}let c=Array.isArray(a.type)?a.type[0]:a.type;if(a.enum&&!a.enum.includes(p))return u("Enum mismatch");if(c==="integer"){if(typeof p!="number"||!Number.isInteger(p))return u("Expected integer")}else if(c==="array"){if(!Array.isArray(p))return u("Expected array")}else if(c==="object"){if(typeof p!="object"||Array.isArray(p))return u("Expected object")}else if(c&&typeof p!==c)return u(`Expected ${c}`);if(typeof p=="number"){if(!Number.isFinite(p))return u("Expected finite number");if(a.minimum!==void 0&&p<a.minimum)return u("Value < min");if(a.maximum!==void 0&&p>a.maximum)return u("Value > max");if(a.multipleOf!==void 0){let m=Math.abs(p%a.multipleOf),d=1e-10;if(m>1e-10&&Math.abs(m-Math.abs(a.multipleOf))>1e-10)return u("Value not step")}}if(typeof p=="string"){if(a.minLength!==void 0&&p.length<a.minLength)return u("Len < min");if(a.maxLength!==void 0&&p.length>a.maxLength)return u("Len > max");if(a.pattern&&!new RegExp(a.pattern,a.format==="emoji"?"u":"").test(p))return u("Pattern mismatch");if(a.format&&qe[a.format]&&!qe[a.format](p))return u("Format invalid")}if(c==="object"){let m=a.minProperties!==void 0,d=o&&a.maxProperties!==void 0;if(m||d){let h=0;for(let y in p)Object.prototype.hasOwnProperty.call(p,y)&&h++;if(m&&h<a.minProperties)return u("Too few props");if(d&&h>a.maxProperties)return u("Too many props")}if(a.required){for(let h of a.required)if(!(h in p))return u(`Missing ${h}`)}if(a.properties){for(let h in a.properties)if(h in p){i.push(h);let y=f(p[h],a.properties[h]);if(i.pop(),!y)return!1}}if(a.additionalProperties){let h=[];for(let k in p)a.properties&&k in a.properties||h.push(k);let y=h.length,x=o||y<=97?1:Math.floor(y/97);for(let k=0;k<y;k+=x){let j=x>1&&k>y-1-x?y-1:k,w=h[j];i.push(w);let N=f(p[w],a.additionalProperties);if(i.pop(),!N)return!1;if(j===y-1)break}}return!0}if(c==="array"&&a.items){let m=p.length;if(a.minItems!==void 0&&m<a.minItems)return u("Array too short");if(a.maxItems!==void 0&&m>a.maxItems)return u("Array too long");if(Array.isArray(a.items)){for(let h=0;h<a.items.length;h++){if(i.push(String(h)),!f(p[h],a.items[h]))return i.pop(),!1;i.pop()}return!0}let d=o||m<=97?1:Math.floor(m/97);for(let h=0;h<m;h+=d){let y=d>1&&h>m-1-d?m-1:h;i.push(String(y));let x=f(p[y],a.items);if(i.pop(),!x)return!1;if(y===m-1)break}return!0}return!0};return f(e,s)}function Ge(e,t,n){let s=t?.schema||t,r=typeof n=="function"?n:n?.onError,o=typeof n=="object"?n?.strict??n?.fullScan??!1:!1;if(!(typeof n=="object"&&n?.skipValidation)){let i="",u="";if(!U(e,s,{onError:(f,p)=>{i||(i=f,u=p),r&&r(f,p)},fullScan:o}))return Error(`${i}: ${u}`)}return ce(e,s)}function ce(e,t){if(e==null)return e;let n=t.type;if(n==="object"&&t.properties&&typeof e=="object"&&!Array.isArray(e)){let s={};for(let r of Object.keys(t.properties))r in e&&(s[r]=ce(e[r],t.properties[r]));return s}return n==="array"&&Array.isArray(e)&&t.items?Array.isArray(t.items)?e.slice(0,t.items.length).map((s,r)=>ce(s,t.items[r])):e.map(s=>ce(s,t.items)):e}var E,ge,J,qe,Te=Y(()=>{E=e=>({schema:e,_type:null,validate:(t,n)=>U(t,e,n),get optional(){return E({...e,type:Array.isArray(e.type)?[...e.type,"null"]:[e.type,"null"]})},title:t=>E({...e,title:t}),describe:t=>E({...e,description:t}),default:t=>E({...e,default:t}),meta:t=>E({...t,...e,...t}),min:t=>{let n=e.type==="string"?"minLength":e.type==="array"?"minItems":e.type==="object"?"minProperties":"minimum";return E({...e,[n]:t})},max:t=>{let n=e.type==="string"?"maxLength":e.type==="array"?"maxItems":e.type==="object"?"maxProperties":"maximum";return E({...e,[n]:t})},pattern:t=>E({...e,pattern:typeof t=="string"?t:t.source}),get email(){return E({...e,format:"email"})},get uuid(){return E({...e,format:"uuid"})},get ipv4(){return E({...e,format:"ipv4"})},get url(){return E({...e,format:"uri"})},get datetime(){return E({...e,format:"date-time"})},get emoji(){return E({...e,pattern:"^\\p{Extended_Pictographic}+$",format:"emoji"})},get int(){return E({...e,type:"integer"})},step:t=>E({...e,multipleOf:t})}),ge={get email(){return E({type:"string",format:"email"})},get uuid(){return E({type:"string",format:"uuid"})},get ipv4(){return E({type:"string",format:"ipv4"})},get url(){return E({type:"string",format:"uri"})},get datetime(){return E({type:"string",format:"date-time"})},get emoji(){return E({type:"string",pattern:"^\\p{Extended_Pictographic}+$",format:"emoji"})},get null(){return E({type:"null"})},get undefined(){return E({type:"null","x-tjs-undefined":!0})},get any(){return E({})},pattern:e=>E({type:"string",pattern:typeof e=="string"?e:e.source}),union:e=>E({anyOf:e.map(t=>t.schema)}),enum:e=>E({type:typeof e[0],enum:e}),const:e=>E({const:e}),array:e=>E({type:"array",items:e.schema}),tuple:e=>E({type:"array",items:e.map(t=>t.schema),minItems:e.length,maxItems:e.length}),object:e=>{let t={},n=[];for(let s in e)t[s]=e[s].schema,(!Array.isArray(t[s].type)||!t[s].type.includes("null"))&&n.push(s);return E({type:"object",properties:t,required:n,additionalProperties:!1})},record:e=>E({type:"object",additionalProperties:e.schema}),infer:e=>{if(e===null)return E({type:"null"});if(e===void 0)return E({type:"null","x-tjs-undefined":!0});let t=typeof e;if(t==="string")return E({type:"string"});if(t==="number")return E({type:Number.isInteger(e)?"integer":"number"});if(t==="boolean")return E({type:"boolean"});if(Array.isArray(e))return e.length===0?E({type:"array"}):E({type:"array",items:ge.infer(e[0]).schema});if(t==="object"){let n={},s=[];for(let r in e)n[r]=ge.infer(e[r]).schema,s.push(r);return E({type:"object",properties:n,required:s,additionalProperties:!1})}return E({})}},J=new Proxy(ge,{get(e,t){if(t in e)return e[t];if(t==="string"||t==="number"||t==="boolean"||t==="integer"){let n=E({type:t});return e[t]=n,n}}}),qe={email:e=>/^\S+@\S+\.\S+$/.test(e),uuid:e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),uri:e=>{try{return new URL(e),!0}catch{return!1}},ipv4:e=>/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(e),"date-time":e=>!isNaN(Date.parse(e)),emoji:e=>new RegExp("\\p{Extended_Pictographic}","u").test(e)}});function X(e){if(e.nullable)return{anyOf:[X({...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:X(e.items)}:{type:"array"};case"object":if(e.shape){let t={},n=[];for(let[s,r]of Object.entries(e.shape))t[s]=X(r),n.push(s);return{type:"object",properties:t,required:n,additionalProperties:!1}}return{type:"object"};case"union":return e.members?{anyOf:e.members.map(X)}:{};default:return{}}}function Z(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:Z(e[0])};let t={},n=[];for(let[s,r]of Object.entries(e))t[s]=Z(r),n.push(s);return{type:"object",properties:t,required:n,additionalProperties:!1}}default:return{}}}function he(e){let t={},n=[];for(let[o,i]of Object.entries(e.params))i?.type?.kind?t[o]=X(i.type):i?.example!==void 0?t[o]=Z(i.example):t[o]={},i?.required!==!1&&n.push(o),i?.example!==void 0&&(t[o].examples=[i.example]);let s={type:"object",properties:t,required:n},r;return e.returns&&(e.returns.type?.kind?r=X(e.returns.type):e.returns.example!==void 0&&(r=Z(e.returns.example))),{input:s,output:r}}var xe=Y(()=>{"use strict"});function V(e){return e!==null&&typeof e=="object"&&"__runtimeType"in e&&e.__runtimeType===!0}function ze(e){return e!==null&&typeof e=="object"&&"schema"in e&&typeof e.schema=="object"}function At(e){return e!==null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"}function L(e,t,n,s){let r,o,i,u=n,f=s;if(typeof e=="string")if(r=e,typeof t=="function")o=t,u!==void 0&&(i=J.infer(u));else if(t===void 0&&u!==void 0)i=J.infer(u);else if(ze(t))i=t;else if(At(t))i=t;else if(t!==void 0)u=t,f=u,i=J.infer(u);else throw new Error("Type(description) requires a predicate, schema, or example");else ze(e),i=e,r=Rt(i);let p;if(i){let c=i?.schema??i;c&&typeof c=="object"&&Array.isArray(c.examples)&&(p=c.examples)}return u===void 0&&p&&p.length>0&&(u=p[0]),{description:r,check:c=>o?o(c):i?U(c,i):!1,schema:i,predicate:o,example:u,examples:p,default:f,toJSONSchema(){if(i){let c=i?.schema??i;if(c&&typeof c=="object"&&"type"in c)return c}return u!==void 0?Z(u):{description:r}},strip(c){return i?Ge(c,i):c},__runtimeType:!0}}function Rt(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"}function Ae(e){return L(`${e.description} or null`,t=>t===null||e.check(t)===!0)}function Re(e){return L(`${e.description} (optional)`,t=>t==null||e.check(t)===!0)}function Oe(e,t,...n){if(typeof e=="string"&&Array.isArray(t)){let o=e,i=t,u=new Set(i);return{description:o,check:p=>u.has(p),toJSONSchema:()=>({enum:i}),strip:p=>p,__runtimeType:!0,values:i}}let s=[];V(e)&&s.push(e),V(t)&&s.push(t),s.push(...n);let r=s.map(o=>o.description).join(" | ");return L(r,o=>s.some(i=>i.check(o)===!0))}function Me(e){return L(`array of ${e.description}`,t=>Array.isArray(t)&&t.every(n=>e.check(n)===!0))}function Ot(e){if(V(e))return n=>e.check(n)===!0;if(e&&typeof e=="object"&&"schema"in e)return n=>U(n,e);let t=J.infer(e);return n=>U(n,t)}function se(e,t,n){let s=[],r=[];for(let i of e)typeof i=="string"?(s.push(i),r.push(void 0)):(s.push(i[0]),r.push(i[1]));let o=(...i)=>{let u=s.map((p,a)=>{let c=a<i.length?i[a]:r[a];return c===void 0?()=>!0:Ot(c)}),f=n;return s.forEach((p,a)=>{let c=a<i.length?i[a]:r[a],m="any";V(c)?m=c.description:c!==void 0&&(m=typeof c=="string"?"string":JSON.stringify(c)),f=f.replace(new RegExp(`\\b${p}\\b`,"g"),m)}),L(f,p=>t(p,...u))};return o.params=s,o.description=n,o}function Ie(e,t){let n=Object.values(t),s=new Set(n),r=Object.keys(t),o={};for(let[u,f]of Object.entries(t))o[f]=u;return{description:e,check:u=>s.has(u),toJSONSchema:()=>({enum:n}),strip:u=>u,__runtimeType:!0,members:t,names:o,values:n,keys:r}}function Mt(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 le(e,t,n){if(Array.isArray(t)&&n){let s=t,r=[],o=[];for(let u of s)Array.isArray(u)?(r.push(u[0]),o.push(u[1])):(r.push(u),o.push(void 0));let i=((...u)=>{let f=r.map((a,c)=>c<u.length?u[c]:o[c]),p=n(...f);return le(e,p)});return Object.defineProperties(i,{typeParamNames:{value:r,enumerable:!0},description:{value:e,enumerable:!0},__runtimeType:{value:!0,enumerable:!0}}),i}return vt(e,t)}function vt(e,t){let n={},s,r="assertReturns";if(typeof t=="function"){let i=t.__tjs;if(i){if(i.params)for(let[u,f]of Object.entries(i.params))n[u]=f?.example??null;i.returns&&(s=i.returns?.example??null),i.safeReturn?r="checkedReturns":i.unsafe?r="assertReturns":r="returns"}}else n=t.params??{},s=t.returns,r=t.returnContract??"assertReturns";return{description:e,params:n,returns:s,returnContract:r,toJSONSchema:()=>({description:e,type:"function"}),strip:i=>i,check:i=>{if(typeof i!="function")return`expected function, got ${i===null?"null":typeof i}`;let u=Object.keys(n).length;if(u>0){let p=i.__tjs;if(p?.params){let a=Object.keys(p.params).length;if(a!==u)return`expected ${u} params, got ${a}`;let c=Object.keys(n),m=Object.keys(p.params);for(let d=0;d<c.length;d++){let h=p.params[m[d]],y=n[c[d]];if(h?.type?.kind&&y!==void 0){let x=Mt(y);if(x&&h.type.kind!==x&&h.type.kind!=="any")return`param '${c[d]}' expected ${x}, got ${h.type.kind}`}}}}return!0},__runtimeType:!0}}var Se,be,ke,$e,Ee,je,we,Ve,Ne,Pe,He,We,Ye,Xe,ve,Ce,Ze=Y(()=>{"use strict";Te();xe();Se=L("string",e=>typeof e=="string"?!0:`expected string, got ${e===null?"null":typeof e}`),be=L("number",e=>typeof e=="number"?!0:`expected number, got ${e===null?"null":typeof e}`),ke=L("boolean",e=>typeof e=="boolean"?!0:`expected boolean, got ${e===null?"null":typeof e}`),$e=L("integer",e=>typeof e!="number"?`expected integer, got ${e===null?"null":typeof e}`:Number.isInteger(e)?!0:`${e} is not an integer`),Ee=L("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`),je=L("non-empty string",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:e.length===0?"string is empty":!0),we=L("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`),Ve=e=>{try{return new URL(e),!0}catch{return!1}},Ne=L("URL",e=>typeof e!="string"?`expected string, got ${e===null?"null":typeof e}`:Ve(e)?!0:`"${e}" is not a valid URL`),Pe=L("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`),He=e=>{let t=new Date(e);return!isNaN(t.getTime())&&e.includes("T")},We=e=>{if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let t=new Date(e+"T00:00:00Z");return!isNaN(t.getTime())},Ye=L("ISO 8601 timestamp",e=>typeof e=="string"&&He(e)),Xe=L("date (YYYY-MM-DD)",e=>typeof e=="string"&&We(e));ve=se(["T","U"],(e,t,n)=>Array.isArray(e)&&e.length===2&&t(e[0])&&n(e[1]),"Pair<T, U>"),Ce=se(["V"],(e,t)=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).every(t),"Record<string, V>")});var Qe=jt((bn,Ct)=>{Ct.exports={name:"tjs-lang",version:"0.8.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",typesVersions:{"*":{eval:["./dist/src/lang/eval.d.ts"],lang:["./dist/src/lang/transpiler.d.ts"],"lang/from-ts":["./dist/src/lang/emitters/from-ts.d.ts"],browser:["./dist/src/lang/browser.d.ts"],"browser/from-ts":["./dist/src/lang/browser-from-ts.d.ts"],vm:["./dist/src/vm/index.d.ts"],batteries:["./dist/src/batteries/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"},"./browser":{types:"./dist/src/lang/browser.d.ts",default:"./dist/tjs-browser.js"},"./browser/from-ts":{types:"./dist/src/lang/browser-from-ts.d.ts",default:"./dist/tjs-browser-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"},"./linalg":{bun:"./src/linalg/index.tjs",default:"./dist/tjs-linalg.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","llms.txt"],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","@eslint/js":"^10.0.1","@happy-dom/global-registrator":"^20.1.0","@types/bun":"latest","@types/jsdom":"^21.1.7","acorn-walk":"^8.3.4",chokidar:"^4.0.3",codemirror:"^6.0.2",esbuild:"^0.28.0",eslint:"^10.4.1",firebase:"^10.12.0","firebase-admin":"^13.6.0","firebase-functions":"^7.0.5",globals:"^17.6.0",marked:"^9.1.6",prettier:"^2.8.8",tosijs:"^1.5.6","tosijs-ui":"^1.4.7",typescript:"^5.6.2","typescript-eslint":"^8.61.0",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":"bun run build:demo && firebase deploy --only hosting",deploy:"bun run build:demo && bun run functions:deploy && firebase deploy --only hosting",start:"bun run build:demo && bun run dev"},dependencies:{acorn:"^8.15.0","acorn-loose":"^8.5.2","acorn-walk":"^8.3.4","tosijs-schema":"^1.3.0"}}});function fe(e){let[t=0,n=0,s=0]=e.split(".").map(Number);return{major:t,minor:n,patch:s}}function tt(e,t){let n=fe(e),s=fe(t);return n.major!==s.major?n.major<s.major?-1:1:n.minor!==s.minor?n.minor<s.minor?-1:1:n.patch!==s.patch?n.patch<s.patch?-1:1:0}function nt(e,t){let n=fe(e),s=fe(t);return n.major===s.major}function Kt(e,t,n,s){let r=n===null?"null":typeof n,o=I.callStacks||I.debug?_e():void 0,i=s?`Expected ${t} for '${e}': ${s}`:`Expected ${t} for '${e}', got ${r}`,u=new G(i,e,t,r,o,s);if(I.trackErrors!==!1){let f=I.maxErrors??me;st[Q]=u,Q=(Q+1)%f,W<f&&W++,de++}if(I.logTypeErrors&&console.error(`[TJS TypeError] ${u.message}`),I.throwTypeErrors)throw u;return u}function Ke(e){return e instanceof Error&&e.name==="MonadicError"&&"path"in e}function Lt(){ne++}function _t(){ne>0&&ne--}function Dt(){return ne>0}function Jt(e){I={...I,...e}}function Ut(){return{...I}}function it(e){if((I.callStacks||I.debug)&&e){let t=I.maxStackSize??ae;rt[H]=e,H=(H+1)%t,F<t&&F++}}function pe(){if((I.callStacks||I.debug)&&F>0){let e=I.maxStackSize??ae;H=(H-1+e)%e,F--}}function _e(){if(F===0)return[];let e=I.maxStackSize??ae,t=[],n=(H-F+e)%e;for(let s=0;s<F;s++)t.push(rt[(n+s)%e]);return t}function ot(){if(I.trackErrors===!1||W===0)return[];let e=I.maxErrors??me,t=[],n=(Q-W+e)%e;for(let s=0;s<W;s++)t.push(st[(n+s)%e]);return t}function Ft(){let e=ot();return Q=0,W=0,de=0,e}function Bt(){return de}function qt(){I={...Le},H=0,F=0,Q=0,W=0,de=0,ne=0}function ee(e,t){if(e!==null&&typeof e=="object"&&typeof e[ie]=="function")return e[ie](t);if(t!==null&&typeof t=="object"&&typeof t[ie]=="function")return t[ie](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 r of e)if(!t.has(r))return!1;return!0}if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[r,o]of e)if(!t.has(r)||!ee(o,t.get(r)))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((r,o)=>ee(r,t[o]));if(Array.isArray(e)!==Array.isArray(t))return!1;let n=Object.keys(e),s=Object.keys(t);return n.length!==s.length?!1:n.every(r=>ee(e[r],t[r]))}function at(e,t){return!ee(e,t)}function ut(e){return e===null?"null":typeof e}function ct(e){return e instanceof Boolean||e instanceof Number||e instanceof String?!!e.valueOf():!!e}function De(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 lt(e,t){return!De(e,t)}function q(e){return e!==null&&typeof e=="object"&&e.$error===!0}function B(e,t){let n={$error:!0,message:e,...t};if((I.callStacks||I.debug)&&F>0){let s=_e(),r=t?.path?[...s,t.path]:s;n.stack=r}return n}function Je(e,t){if(e.length===0)return B("Unknown error");if(e.length===1)return e[0];let n=e.map(r=>{if(r.path){let o=r.path.split(".");return o[o.length-1]}return"unknown"}).join(", "),s=`Multiple parameter errors in ${t||"function"}: ${n}`;return B(s,{path:t,errors:e})}function oe(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 pt(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 te(e,t,n){if(q(e))return e;if(typeof t=="object"&&t!==null&&"check"in t){let r=t.check(e);if(r===!0)return null;let o=typeof r=="string"?r:void 0,i=o?`Expected ${t.description} for '${n}': ${o}`:`Expected ${t.description} but got ${oe(e)}`;return B(i,{path:n,expected:t.description,actual:oe(e),reason:o})}let s=oe(e);return t==="any"||t===s||t==="number"&&s==="number"||t==="integer"&&s==="number"&&Number.isInteger(e)||t==="non-negative-integer"&&s==="number"&&Number.isInteger(e)&&e>=0||t==="object"&&s==="object"?null:B(`Expected ${t} but got ${s}`,{path:n,expected:t,actual:s})}function ft(e,t,n,s){if(typeof e!="function")return e;let r=e.__tjs;if(!r||!r.params)return e;let o=Object.entries(r.params);for(let i=0;i<t.length;i++){let u=t[i];if(u==="any")continue;let f=o[i];if(!f)continue;let p=f[1]?.type?.kind;if(!(!p||p==="any")&&p!==u)return new G(`Expected (...arg${i}: ${u}, ...) for '${s}', but callback declares arg${i} as ${p}`,`${s}(arg${i})`,u,p)}if(n!=="any"&&r.returns){let i=r.returns.type?.kind??r.returns.kind;if(i&&i!=="any"&&i!==n)return new G(`Expected callback returning ${n} for '${s}', but callback returns ${i}`,`${s}(return)`,n,i)}return e}function mt(e,t,n){for(let[s,r]of Object.entries(t.params)){let o=e[s];if(q(o))return o;if(r.required&&o===void 0){let u=typeof r.type=="string"?r.type:r.type.description;return B(`Missing required parameter '${s}'`,{path:n?`${n}.${s}`:s,expected:u,actual:"undefined",loc:r.loc})}if(o===void 0)continue;let i=te(o,r.type,n?`${n}.${s}`:s);if(i)return r.loc&&(i.loc=r.loc),i}return null}function dt(e,t){if(e.__tjs=t,e.__tjs.schema=()=>he(t),!(!t.polymorphic&&(t.safe||t.safeReturn||I.safety!=="none"&&!t.unsafe||t.returns&&I.safety==="all"&&!t.unsafeReturn)))return e;let s=!!t.returns,r=!!t.unsafe,o=!!t.safe,i=!!t.unsafeReturn,u=!!t.safeReturn,f=t.returns?.defaults,p=Object.entries(t.params),a=p.length,c=e.name||t.name||"anonymous",m=function(...d){if(ne>0)return e.apply(this,d);let h=o||!r&&I.safety!=="none",y=s&&(u||!i&&I.safety==="all");if(!h&&!y)return e.apply(this,d);if(d.length>0&&q(d[0]))return d[0];if(h){let k=d.length===1&&typeof d[0]=="object"&&d[0]!==null&&!Array.isArray(d[0]),j=[];if(k){let w=d[0];for(let N=0;N<a;N++){let[P,v]=p[N],O=w[P];if(q(O)){j.push(O);continue}if(v.required&&O===void 0){j.push(B(`Missing required parameter '${P}'`,{path:`${c}.${P}`,expected:typeof v.type=="string"?v.type:v.type?.description||"value",actual:"undefined",loc:v.loc}));continue}if(O!==void 0){let _=te(O,v.type,`${c}.${P}`);_&&(v.loc&&(_.loc=v.loc),j.push(_))}}}else for(let w=0;w<a;w++){let[N,P]=p[w],v=d[w];if(q(v)){j.push(v);continue}if(P.required&&v===void 0){j.push(B(`Missing required parameter '${N}'`,{path:`${c}.${N}`,expected:typeof P.type=="string"?P.type:P.type?.description||"value",actual:"undefined",loc:P.loc}));continue}if(v!==void 0){let O=te(v,P.type,`${c}.${N}`);O&&(P.loc&&(O.loc=P.loc),j.push(O))}}if(j.length>0)return Je(j,c)}let x=I.callStacks||I.debug;x&&it(c);try{let k=e.apply(this,d);if(y&&t.returns&&!q(k)){let j=f&&typeof k=="object"&&k!==null?Object.assign({},f,k):k,w=te(j,t.returns.type,`${c}()`);if(w)return x&&pe(),w}return x&&pe(),k}catch(k){return x&&pe(),B(k.message||String(k),{path:c,cause:k})}};return Object.defineProperty(m,"name",{value:e.name}),m.__tjs=t,m.__tjs.schema=()=>he(t),m}function yt(e){let t=new Proxy(e,{construct(n,s,r){return Reflect.construct(n,s,r)},apply(n,s,r){return Reflect.construct(n,r)}});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 gt(){let e={...I},t=e.maxStackSize??ae,n=new Array(t).fill(""),s=0,r=0,o=e.maxErrors??me,i=new Array(o).fill(null),u=0,f=0,p=0,a=0;function c(g){e={...e,...g}}function m(){return{...e}}function d(g){(e.callStacks||e.debug)&&g&&(n[s]=g,s=(s+1)%t,r<t&&r++)}function h(){(e.callStacks||e.debug)&&r>0&&(s=(s-1+t)%t,r--)}function y(){if(r===0)return[];let g=[],b=(s-r+t)%t;for(let R=0;R<r;R++)g.push(n[(b+R)%t]);return g}function x(){e={...Le},s=0,r=0,u=0,f=0,p=0,a=0}function k(){a++}function j(){a>0&&a--}function w(){return a>0}let N=new Map;function P(g,b,R){N.has(g)||N.set(g,new Map),N.get(g).set(b,R)}function v(g,b){let R=typeof g,C;if(g==null)return;if(R==="string")C="String";else if(R==="number")C="Number";else if(R==="boolean")C="Boolean";else if(Array.isArray(g))C="Array";else if(R==="object")C=g.constructor?.name||"Object";else return;let D=C;for(;D;){let Ue=N.get(D);if(Ue?.has(b))return Ue.get(b);if(R==="object"&&!Array.isArray(g)){if(D=Object.getPrototypeOf(D===C?g:Object.getPrototypeOf(g))?.constructor?.name,D==="Object"||D===C)break}else break}let z=N.get("Object");if(z?.has(b))return z.get(b)}function O(g,b,R){let C=R===null?"null":typeof R,D=e.callStacks||e.debug?y():void 0,z=new G(`Expected ${b} for '${g}', got ${C}`,g,b,C,D);if(e.trackErrors!==!1&&(i[u]=z,u=(u+1)%o,f<o&&f++,p++),e.logTypeErrors&&console.error(`[TJS TypeError] ${z.message}`),e.throwTypeErrors)throw z;return z}function _(){if(e.trackErrors===!1||f===0)return[];let g=[],b=(u-f+o)%o;for(let R=0;R<f;R++)g.push(i[(b+R)%o]);return g}function T(){let g=_();return u=0,f=0,p=0,g}function $(){return p}function S(g,b){let R={$error:!0,message:g,...b};if((e.callStacks||e.debug)&&r>0){let C=b?.path?[...y(),b.path]:y();R.stack=C}return R}function A(g,b){return g==null?O(`bang.${b}`,"non-null",g):Ke(g)?g:g[b]}return{version:et,MonadicError:G,typeError:O,isMonadicError:Ke,bang:A,isError:q,error:S,composeErrors:Je,typeOf:oe,isNativeType:pt,checkType:te,validateArgs:mt,wrap:dt,checkFnShape:ft,wrapClass:yt,compareVersions:tt,versionsCompatible:nt,createRuntime:gt,configure:c,getConfig:m,pushStack:d,popStack:h,getStack:y,errors:_,clearErrors:T,getErrorCount:$,resetRuntime:x,enterUnsafe:k,exitUnsafe:j,isUnsafeMode:w,validate:U,infer:J.infer.bind(J),Type:L,isRuntimeType:V,Union:Oe,Generic:se,Enum:Ie,FunctionPredicate:le,Nullable:Ae,Optional:Re,TArray:Me,TString:Se,TNumber:be,TBoolean:ke,TInteger:$e,TPositiveInt:Ee,TNonEmptyString:je,TEmail:we,TUrl:Ne,TUuid:Pe,TPair:ve,TRecord:Ce,Is:ee,IsNot:at,Eq:De,NotEq:lt,TypeOf:ut,toBool:ct,tjsEquals:ie,registerExtension:P,resolveExtension:v}}function Tt(e){return`
|
|
2
|
+
// TJS: callable without new
|
|
3
|
+
${e} = new Proxy(${e}, { apply(t, _, a) { return Reflect.construct(t, a) } });
|
|
4
|
+
`.trim()}var It,et,ie,G,Le,I,ae,rt,H,F,me,st,Q,W,de,ne,jn,ht=Y(()=>{"use strict";Te();xe();Ze();It=Qe(),et=It.version,ie=Symbol.for("tjs.equals");G=class e extends Error{path;expected;actual;callStack;reason;constructor(t,n,s,r,o,i){super(t),this.name="MonadicError",this.path=n,this.expected=s,this.actual=r,this.callStack=o,this.reason=i,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};Le={debug:!1,safety:"inputs",requireReturnTypes:!1,callStacks:!1,maxStackSize:64,trackErrors:!0,maxErrors:64},I={...Le},ae=64,rt=new Array(ae).fill(""),H=0,F=0,me=64,st=new Array(me).fill(null),Q=0,W=0,de=0,ne=0;jn={version:et,MonadicError:G,typeError:Kt,isMonadicError:Ke,isError:q,error:B,composeErrors:Je,typeOf:oe,isNativeType:pt,checkType:te,validateArgs:mt,wrap:dt,checkFnShape:ft,wrapClass:yt,compareVersions:tt,versionsCompatible:nt,configure:Jt,getConfig:Ut,pushStack:it,popStack:pe,getStack:_e,errors:ot,clearErrors:Ft,getErrorCount:Bt,resetRuntime:qt,enterUnsafe:Lt,exitUnsafe:_t,isUnsafeMode:Dt,createRuntime:gt,validate:U,infer:J.infer.bind(J),Type:L,isRuntimeType:V,Union:Oe,Generic:se,Enum:Ie,FunctionPredicate:le,Nullable:Ae,Optional:Re,TArray:Me,TString:Se,TNumber:be,TBoolean:ke,TInteger:$e,TPositiveInt:Ee,TNonEmptyString:je,TEmail:we,TUrl:Ne,TUuid:Pe,Timestamp:Ye,LegalDate:Xe,TPair:ve,TRecord:Ce,Is:ee,IsNot:at,Eq:De,NotEq:lt,TypeOf:ut,toBool:ct}});var bt={};wt(bt,{fromTS:()=>ln});function M(e,t,n,s){if(!e)return"undefined";switch(e.kind){case l.SyntaxKind.StringKeyword:return"''";case l.SyntaxKind.NumberKeyword:return"0.0";case l.SyntaxKind.BooleanKeyword:return"false";case l.SyntaxKind.NullKeyword:return"null";case l.SyntaxKind.UndefinedKeyword:return"undefined";case l.SyntaxKind.VoidKeyword:return"undefined";case l.SyntaxKind.AnyKeyword:return"any";case l.SyntaxKind.UnknownKeyword:return"any";case l.SyntaxKind.NeverKeyword:return"null";case l.SyntaxKind.SymbolKeyword:return"Symbol('example')";case l.SyntaxKind.BigIntKeyword:return"0n";case l.SyntaxKind.ObjectKeyword:return"{}";case l.SyntaxKind.ArrayType:{let o=M(e.elementType,t);return o==="any"&&(o="null"),`[${o}]`}case l.SyntaxKind.TypeReference:{let r=e,o=r.typeName.getText();if(o==="Array"&&r.typeArguments?.length)return`[${M(r.typeArguments[0],t,n,s)}]`;if(o==="Promise"||o==="Generator"||o==="AsyncGenerator"||o==="IterableIterator"||o==="AsyncIterableIterator")return r.typeArguments?.length?M(r.typeArguments[0],t,n,s):"undefined";if(o==="Record")return"{}";let i={Map:"new Map()",Set:"new Set()",WeakMap:"new WeakMap()",WeakSet:"new WeakSet()",WeakRef:"new WeakRef({})",Error:"new Error('example')",TypeError:"new TypeError('example')",RangeError:"new RangeError('example')",SyntaxError:"new SyntaxError('example')",ReferenceError:"new ReferenceError('example')",URIError:"new URIError('example')",EvalError:"new EvalError('example')",Date:"new Date()",RegExp:"/example/",ArrayBuffer:"new ArrayBuffer(0)",SharedArrayBuffer:"new SharedArrayBuffer(0)",DataView:"new DataView(new ArrayBuffer(0))",Float32Array:"new Float32Array(0)",Float64Array:"new Float64Array(0)",Int8Array:"new Int8Array(0)",Int16Array:"new Int16Array(0)",Int32Array:"new Int32Array(0)",Uint8Array:"new Uint8Array(0)",Uint16Array:"new Uint16Array(0)",Uint32Array:"new Uint32Array(0)",Uint8ClampedArray:"new Uint8ClampedArray(0)",BigInt64Array:"new BigInt64Array(0)",BigUint64Array:"new BigUint64Array(0)",URL:"new URL('https://example.com')",URLSearchParams:"new URLSearchParams()",Headers:"new Headers()",FormData:"new FormData()",Blob:"new Blob()",File:"new File([], 'example')",Response:"new Response()",Request:"new Request('https://example.com')",AbortController:"new AbortController()",AbortSignal:"AbortSignal.abort()",ReadableStream:"new ReadableStream()",WritableStream:"new WritableStream()",TransformStream:"new TransformStream()",TextEncoder:"new TextEncoder()",TextDecoder:"new TextDecoder()",Promise:"Promise.resolve(null)"};if(o in i)return i[o];if(s?.typeAliases?.has(o)){let u=s.visited??new Set;if(u.has(o))return n?.push(`Circular type reference '${o}' - using 'any'`),"any";u.add(o);let f=s.typeAliases.get(o);return M(f,t,n,{...s,visited:u})}if(s?.interfaces?.has(o)){let u=s.visited??new Set;if(u.has(o))return n?.push(`Circular type reference '${o}' - using 'any'`),"any";u.add(o);let f=s.interfaces.get(o),p=[];for(let a of f.members)if(l.isPropertySignature(a)&&a.name){let c=a.name.getText(s.sourceFile),m=M(a.type,t,n,{...s,visited:u});p.push(`${c}: ${m}`)}return`{ ${p.join(", ")} }`}if(s?.typeParams?.has(o)){let u=s.typeParams.get(o);if(u.constraint)return M(u.constraint,t,n,s);if(u.default)return M(u.default,t,n,s)}return St.has(o)?"{}":/^[A-Z]$/.test(o)||["T","K","V","U","TKey","TValue","TItem","TResult"].includes(o)?(n?.push(`Generic type parameter '${o}' converted to 'any' - consider specializing`),"any"):(n?.push(`Unknown type '${o}' converted to 'any' - may need manual review`),"any")}case l.SyntaxKind.TypeLiteral:{let r=e,o=[];for(let i of r.members)if(l.isPropertySignature(i)&&i.name){let u=i.name.getText(),f=M(i.type,t);f==="any"&&(f="null"),o.push(`${u}: ${f}`)}return`{ ${o.join(", ")} }`}case l.SyntaxKind.UnionType:{let r=e,o=c=>c.kind===l.SyntaxKind.NullKeyword||l.isLiteralTypeNode(c)&&c.literal.kind===l.SyntaxKind.NullKeyword,i=c=>c.kind===l.SyntaxKind.UndefinedKeyword||l.isLiteralTypeNode(c)&&c.literal.kind===l.SyntaxKind.UndefinedKeyword,u=r.types.filter(c=>!o(c)&&!i(c)),f=r.types.some(o),p=r.types.some(i);if(u.length===0)return f?"null":"undefined";if(u.length===1&&(f||p)){let c=M(u[0],t,n,s);if(c==="any")return"any";if(f)return`${c} | null`;if(p)return`${c} | undefined`}let a=r.types.map(c=>M(c,t,n,s)).filter((c,m,d)=>d.indexOf(c)===m);return a.some(c=>c==="any")?"any":a.length===1?a[0]:a.length>0?a.some(m=>/[()]/.test(m)||m.startsWith("new "))?"any":a.join(" | "):"undefined"}case l.SyntaxKind.LiteralType:{let r=e;return l.isStringLiteral(r.literal)?`'${r.literal.text}'`:l.isNumericLiteral(r.literal)?r.literal.text:r.literal.kind===l.SyntaxKind.TrueKeyword?"true":r.literal.kind===l.SyntaxKind.FalseKeyword?"false":r.literal.kind===l.SyntaxKind.NullKeyword?"null":"undefined"}case l.SyntaxKind.ParenthesizedType:return M(e.type,t);case l.SyntaxKind.FunctionType:{let r=e,o=[];for(let f of r.parameters){let p=f.name?.getText()||"_";if(p==="this")continue;let a=M(f.type,t,n,s);a==="any"&&(a="null"),o.push(`${p}: ${a}`)}let i=M(r.type,t,n,s);i==="any"&&(i="null");let u=[];return o.length>0&&u.push(`params: { ${o.join(", ")} }`),i!=="undefined"&&u.push(`returns: ${i}`),`FunctionPredicate('function', { ${u.join(", ")} })`}case l.SyntaxKind.TupleType:return`[${e.elements.map(i=>{let u=l.isNamedTupleMember(i)?M(i.type,t):M(i,t);return u==="any"?"null":u}).join(", ")}]`;default:return"undefined"}}function K(e,t){if(!e)return{kind:"any"};let n=t?.depth??0;if(n>Gt)return{kind:"any"};switch(t=t?{...t,depth:n+1}:void 0,e.kind){case l.SyntaxKind.StringKeyword:return{kind:"string"};case l.SyntaxKind.NumberKeyword:return{kind:"number"};case l.SyntaxKind.BooleanKeyword:return{kind:"boolean"};case l.SyntaxKind.NullKeyword:return{kind:"null"};case l.SyntaxKind.UndefinedKeyword:case l.SyntaxKind.VoidKeyword:return{kind:"undefined"};case l.SyntaxKind.ArrayType:return{kind:"array",items:K(e.elementType,t)};case l.SyntaxKind.TypeLiteral:{let s=e,r={};for(let o of s.members)if(l.isPropertySignature(o)&&o.name){let i=o.name.getText();r[i]=K(o.type,t)}return{kind:"object",shape:r}}case l.SyntaxKind.UnionType:{let s=e,r=s.types.filter(i=>i.kind!==l.SyntaxKind.NullKeyword&&i.kind!==l.SyntaxKind.UndefinedKeyword),o=s.types.some(i=>i.kind===l.SyntaxKind.NullKeyword);return r.length===1&&o?{...K(r[0],t),nullable:!0}:{kind:"union",members:s.types.map(i=>K(i,t))}}case l.SyntaxKind.IntersectionType:{let s=e,r={};for(let o of s.types){let i=K(o,t);i.kind==="object"&&i.shape&&Object.assign(r,i.shape)}return Object.keys(r).length>0?{kind:"object",shape:r}:{kind:"any"}}case l.SyntaxKind.TupleType:{let s=e,r=[];for(let o of s.elements)l.isNamedTupleMember(o)?r.push(K(o.type,t)):r.push(K(o,t));return{kind:"tuple",elements:r}}case l.SyntaxKind.TypeReference:{let s=e,r=s.typeName.getText();if(r==="Array"&&s.typeArguments?.length)return{kind:"array",items:K(s.typeArguments[0],t)};if(r==="Promise"&&s.typeArguments?.length||(r==="Generator"||r==="AsyncGenerator"||r==="IterableIterator"||r==="AsyncIterableIterator")&&s.typeArguments?.length)return K(s.typeArguments[0],t);if(s.typeArguments?.length){let o=K(s.typeArguments[0],t);if(r==="Partial"||r==="Required"||r==="Readonly")return o;if(r==="Record"&&s.typeArguments.length>=2)return{kind:"object",shape:{"[key]":K(s.typeArguments[1],t)}};if(r==="Pick"||r==="Omit")return o;if(r==="NonNullable")return o.nullable?{...o,nullable:!1}:o;if(["ReturnType","Parameters","ConstructorParameters"].includes(r))return{kind:"any"}}if(t?.typeAliases?.has(r)){if(t.resolvedCache?.has(r))return t.resolvedCache.get(r);let o=t.visited??new Set;if(o.has(r))return{kind:"any"};o.add(r);let i=t.typeAliases.get(r),u=K(i,{...t,visited:o});return t.resolvedCache?.set(r,u),u}if(t?.interfaces?.has(r)){if(t.resolvedCache?.has(r))return t.resolvedCache.get(r);let o=t.visited??new Set;if(o.has(r))return{kind:"any"};o.add(r);let i=t.interfaces.get(r),u={};if(i.heritageClauses){for(let p of i.heritageClauses)if(p.token===l.SyntaxKind.ExtendsKeyword)for(let a of p.types){let c=a.expression.getText(t.sourceFile);if(t.interfaces?.has(c)&&!o.has(c)){let m={kind:l.SyntaxKind.TypeReference,typeName:{getText:()=>c}},d=K(m,{...t,visited:o});d.kind==="object"&&d.shape&&Object.assign(u,d.shape)}}}for(let p of i.members)if(l.isPropertySignature(p)&&p.name){let a=p.name.getText(t.sourceFile);u[a]=K(p.type,{...t,visited:o})}let f={kind:"object",shape:u};return t.resolvedCache?.set(r,f),f}if(t?.typeParams?.has(r)){let o=t.typeParams.get(r);if(o.constraint)return K(o.constraint,t);if(o.default)return K(o.default,t)}return St.has(r)?{kind:"object"}:{kind:"any"}}default:return{kind:"any"}}}function zt(e,t){if(!e.typeParameters||e.typeParameters.length===0)return;let n={};for(let s of e.typeParameters){let r=s.name.getText(),o={};if(s.constraint){let i=M(s.constraint,void 0,t);if(i.startsWith("{"))try{o.constraint=i}catch{o.constraint=i}else o.constraint=i}if(s.default){let i=M(s.default,void 0,t);o.default=i}n[r]=o}return Object.keys(n).length>0?n:void 0}function Vt(e,t,n,s){let r=e.name.getText(t);if(e.typeParameters&&e.typeParameters.length>0)return Ht(e,t,n,s);let o=s?.find(p=>p.kind==="example"),i=s?.find(p=>p.kind==="predicate"),u;if(o?.text)u=o.text;else{let p=[];for(let a of e.members)if(l.isPropertySignature(a)&&a.name){let c=a.name.getText(t),m=M(a.type,void 0,n);m==="any"&&(m="null"),p.push(`${c}: ${m}`)}if(p.length===0&&!i)return`Type ${r} {}`;u=p.length>0?`{ ${p.join(", ")} }`:"{}"}let f=[`example: ${u}`];return i?.text&&f.push(i.text),`Type ${r} {
|
|
5
|
+
${f.join(`
|
|
6
|
+
`)}
|
|
7
|
+
}`}function Ht(e,t,n,s){let r=e.name.getText(t),o=[];for(let a of e.typeParameters||[]){let c=a.name.getText(t);if(a.default){let m=M(a.default,void 0,n);o.push(`${c} = ${m}`)}else o.push(c)}let i=s?.find(a=>a.kind==="predicate"),u=s?.find(a=>a.kind==="declaration"),f;if(i?.text)f=i.text;else{let a=(e.typeParameters||[]).map(d=>d.name.getText(t)),c=["typeof x === 'object'","x !== null"];for(let d of e.members)if(l.isPropertySignature(d)&&d.name){let h=d.name.getText(t),y=h.startsWith("[")&&h.endsWith("]"),x=y?h.slice(1,-1):null;if(y?c.push(`${x} in x`):c.push(`'${h}' in x`),d.type&&l.isTypeReferenceNode(d.type)){let k=d.type.typeName.getText(t);a.includes(k)&&(y?c.push(`${k}(x[${x}])`):c.push(`${k}(x.${h})`))}}f=`predicate(${["x",...a].join(", ")}) { return ${c.join(" && ")} }`}let p=[`description: '${r}'`,f];if(u?.text)p.push(`declaration ${u.text}`);else{let a=[];for(let c of e.members)if(l.isPropertySignature(c)&&c.name){let m=c.name.getText(t),d=c.questionToken?"?":"",h=c.type?c.type.getText(t):"any";a.push(`${m}${d}: ${h}`)}else if(l.isMethodSignature(c)&&c.name){let m=c.getText(t).trim();a.push(m.replace(/;$/,""))}a.length>0&&p.push(`declaration {
|
|
8
|
+
${a.join(`
|
|
9
|
+
`)}
|
|
10
|
+
}`)}return`Generic ${r}<${o.join(", ")}> {
|
|
11
|
+
${p.join(`
|
|
12
|
+
`)}
|
|
13
|
+
}`}function Wt(e,t){if(!l.isUnionTypeNode(e))return null;let n=[];for(let s of e.types)if(l.isLiteralTypeNode(s))if(l.isStringLiteral(s.literal))n.push(`'${s.literal.text}'`);else if(l.isNumericLiteral(s.literal))n.push(s.literal.text);else if(s.literal.kind===l.SyntaxKind.TrueKeyword)n.push("true");else if(s.literal.kind===l.SyntaxKind.FalseKeyword)n.push("false");else if(s.literal.kind===l.SyntaxKind.NullKeyword)n.push("null");else return null;else if(s.kind===l.SyntaxKind.NullKeyword)n.push("null");else if(s.kind===l.SyntaxKind.UndefinedKeyword)n.push("undefined");else return null;return n.length>0?n:null}function Yt(e,t,n){let s=e.name.getText(t),r=[],o=0;for(let i of e.members){let u=i.name.getText(t);if(i.initializer)if(l.isStringLiteral(i.initializer))r.push(` ${u} = '${i.initializer.text}'`);else if(l.isNumericLiteral(i.initializer)){let f=parseInt(i.initializer.text,10);r.push(` ${u} = ${f}`),o=f+1}else if(l.isPrefixUnaryExpression(i.initializer)&&i.initializer.operator===l.SyntaxKind.MinusToken){let f=i.initializer.operand;if(l.isNumericLiteral(f)){let p=-parseInt(f.text,10);r.push(` ${u} = ${p}`),o=p+1}}else r.push(` ${u} = ${i.initializer.getText(t)}`);else r.push(` ${u} = ${o}`),o++}return`Enum ${s} '${s}' {
|
|
14
|
+
${r.join(`
|
|
15
|
+
`)}
|
|
16
|
+
}`}function Xt(e,t,n,s){let r=e.name.getText(t);if(e.typeParameters&&e.typeParameters.length>0)return e.type.kind===l.SyntaxKind.FunctionType?Zt(e,t,n):Qt(e,t,n,s);let o=Wt(e.type,t);if(o)return`Union ${r} '${r}' ${o.join(" | ")}`;if(e.type.kind===l.SyntaxKind.FunctionType){let u=e.type,f=[];for(let c of u.parameters){let m=c.name?.getText(t)||"_";if(m==="this")continue;let d=M(c.type,void 0,n);d==="any"&&(d="null"),f.push(`${m}: ${d}`)}let p=M(u.type,void 0,n);p==="any"&&(p="null");let a=[];return f.length>0&&a.push(`params: { ${f.join(", ")} }`),p!=="undefined"&&a.push(`returns: ${p}`),`FunctionPredicate ${r} {
|
|
17
|
+
${a.join(`
|
|
18
|
+
`)}
|
|
19
|
+
}`}let i=M(e.type,void 0,n);if(i==="any"||i==="undefined"){let u=e.type.getText(t).trim();return`Type ${r} {
|
|
20
|
+
// TS: ${u}
|
|
21
|
+
}`}return i==="''"||i==="0"||i==="true"||i==="null"?`Type ${r} ${i}`:`Type ${r} {
|
|
22
|
+
example: ${i}
|
|
23
|
+
}`}function Zt(e,t,n){let s=e.name.getText(t),r=e.type,o=new Set,i=[];for(let c of e.typeParameters){let m=c.name.getText(t);if(o.add(m),c.default){let d=M(c.default,void 0,n);i.push(`${m} = ${d}`)}else i.push(m)}let u=[];for(let c of r.parameters){let m=c.name?.getText(t)||"_";if(m==="this")continue;let d=c.type?.getText(t)||"any";if(o.has(d))u.push(`${m}: ${d}`);else{let h=M(c.type,void 0,n);h==="any"&&(h="null"),u.push(`${m}: ${h}`)}}let f=r.type?.getText(t)||"void",p;f!=="void"&&(o.has(f)?p=f:(p=M(r.type,void 0,n),p==="any"&&(p="null"),p==="undefined"&&(p=void 0)));let a=[];return u.length>0&&a.push(`params: { ${u.join(", ")} }`),p!==void 0&&a.push(`returns: ${p}`),`FunctionPredicate ${s}<${i.join(", ")}> {
|
|
24
|
+
${a.join(`
|
|
25
|
+
`)}
|
|
26
|
+
}`}function Qt(e,t,n,s){let r=e.name.getText(t),o=[];for(let c of e.typeParameters||[]){let m=c.name.getText(t);if(c.default){let d=M(c.default,void 0,n);o.push(`${m} = ${d}`)}else o.push(m)}let i=(e.typeParameters||[]).map(c=>c.name.getText(t)),u=s?.find(c=>c.kind==="predicate"),f=s?.find(c=>c.kind==="declaration"),p;u?.text?p=u.text:p=`predicate(${["x",...i].join(", ")}) { return true }`;let a=[`description: '${r}'`,p];if(f?.text)a.push(`declaration ${f.text}`);else{let c=e.type;if(c&&l.isTypeLiteralNode(c)){let m=[];for(let d of c.members)if(l.isPropertySignature(d)&&d.name){let h=d.name.getText(t),y=d.questionToken?"?":"",x=d.type?d.type.getText(t):"any";m.push(`${h}${y}: ${x}`)}else l.isMethodSignature(d)&&d.name&&m.push(d.getText(t).trim().replace(/;$/,""));m.length>0&&a.push(`declaration {
|
|
27
|
+
${m.join(`
|
|
28
|
+
`)}
|
|
29
|
+
}`)}else if(c){let m=c.getText(t).trim();a.push(`declaration {
|
|
30
|
+
// TS: ${m}
|
|
31
|
+
}`)}}return`Generic ${r}<${o.join(", ")}> {
|
|
32
|
+
${a.join(`
|
|
33
|
+
`)}
|
|
34
|
+
}`}function xt(e,t,n,s,r,o){let i;if(e.typeParameters&&e.typeParameters.length>0){i=new Map;for(let O of e.typeParameters)i.set(O.name.getText(t),{constraint:O.constraint,default:O.default})}let u=i||o?{...o,typeParams:i??o?.typeParams}:o,f=[],p=re(e.parameters,t,s,f,u),{line:a}=t.getLineAndCharacterOfPosition(e.getStart(t)),c=r?`/* line ${a+1} */
|
|
35
|
+
`:"",m=n||(l.isFunctionDeclaration(e)&&e.name?e.name.getText(t):""),d=e.type?M(e.type,void 0,s,u):"",h=d&&d!=="undefined"&&d!=="any"&&!d.startsWith("new ")?`:! ${d}`:"";if(e.type&&(d==="any"||d==="undefined")){let O=e.type.getText(t);O!=="any"&&O!=="unknown"&&O!=="void"&&f.push(`return: ${O}`)}let y;if(e.body){let O=l.isBlock(e.body)?e.body.getText(t):`{ return ${e.body.getText(t)} }`;y=l.transpileModule(O,{compilerOptions:{target:l.ScriptTarget.ESNext,module:l.ModuleKind.ESNext,removeComments:!1}}).outputText.trim()}else y="{ }";let x=e.modifiers?.some(O=>O.kind===l.SyntaxKind.ExportKeyword),k=e.modifiers?.some(O=>O.kind===l.SyntaxKind.AsyncKeyword),j=!!e.asteriskToken,w=x?"export ":"",N=k?"async ":"",P=j?"function* ":"function ",v=f.length>0?`/* TODO: TS types degraded \u2014 ${f.join(", ")} */
|
|
36
|
+
`:"";return`${c}${v}${w}${N}${P}${m}(${p.join(", ")})${h} ${y}`}function en(e,t,n,s){let r=t.name?.getText(n)||"",o=`_${r}_impl`,i=[],u=re(t.parameters,n,s),f="{ }";if(t.body){let d=t.body.getText(n);f=l.transpileModule(d,{compilerOptions:{target:l.ScriptTarget.ESNext,module:l.ModuleKind.ESNext,removeComments:!1}}).outputText.trim()}let p=t.modifiers?.some(d=>d.kind===l.SyntaxKind.AsyncKeyword),a=!!t.asteriskToken,c=p?"async ":"",m=a?"function* ":"function ";i.push(`${c}${m}${o}(${u.join(", ")}) ${f}`);for(let d of e){let h=re(d.parameters,n,s),y=d.parameters.map(P=>P.name.getText(n)),x=d.type?M(d.type,void 0,s):"",k=x&&x!=="undefined"&&x!=="any"?`:! ${x}`:"",{line:j}=n.getLineAndCharacterOfPosition(d.getStart(n)),w=`/* line ${j+1} */
|
|
37
|
+
`,N=a?"yield* ":"return ";i.push(`${w}${c}${m}${r}(${h.join(", ")})${k} { ${N}${o}(${y.join(", ")}) }`)}return i}function tn(e,t,n,s,r=!1){let o=s;if(e.typeParameters&&e.typeParameters.length>0){let y=new Map;for(let x of e.typeParameters)y.set(x.name.getText(t),{constraint:x.constraint,default:x.default});o={...s,typeParams:y}}let i=e.name?.getText(t)||"Anonymous",f=e.heritageClauses?.find(y=>y.token===l.SyntaxKind.ExtendsKeyword)?.types[0]?.expression?.getText(t),p=new Map;if(r){for(let y of e.members)if(l.isPropertyDeclaration(y)&&y.name){let x=y.name.getText(t);y.modifiers?.some(j=>j.kind===l.SyntaxKind.PrivateKeyword)&&!x.startsWith("#")&&p.set(x,`#${x}`)}}let a=y=>{let x=y;for(let[k,j]of p)x=x.replace(new RegExp(`(\\b\\w+)\\.${k}\\b`,"g"),`$1.${j}`);return x},c=[];for(let y of e.members){if(l.isConstructorDeclaration(y)){let x=re(y.parameters,t,n),k="{ }";if(y.body){let j=l.transpileModule(y.body.getText(t),{compilerOptions:{target:l.ScriptTarget.ESNext,module:l.ModuleKind.ESNext,removeComments:!1}});k=a(j.outputText.trim())}c.push(` constructor(${x.join(", ")}) ${k}`)}if(l.isMethodDeclaration(y)&&y.name){let x=y.name.getText(t),k=y.modifiers?.some(S=>S.kind===l.SyntaxKind.StaticKeyword),j=y.modifiers?.some(S=>S.kind===l.SyntaxKind.AsyncKeyword),w=re(y.parameters,t,n,void 0,o),N=y.type?M(y.type,void 0,n,o):"",P=N&&N!=="undefined"&&N!=="any"?`:! ${N}`:"",v="{ }";if(y.body){let S=l.transpileModule(y.body.getText(t),{compilerOptions:{target:l.ScriptTarget.ESNext,module:l.ModuleKind.ESNext,removeComments:!1}});v=a(S.outputText.trim())}let O=!!y.asteriskToken,_=k?"static ":"",T=j?"async ":"",$=O?"*":"";c.push(` ${_}${T}${$}${x}(${w.join(", ")})${P} ${v}`)}if(l.isGetAccessorDeclaration(y)&&y.name){let x=y.name.getText(t),j=y.modifiers?.some(v=>v.kind===l.SyntaxKind.StaticKeyword)?"static ":"",w=y.type?M(y.type,void 0,n,o):"",N=w&&w!=="undefined"&&w!=="any"&&!w.startsWith("new ")?`: ${w}`:"",P="{ }";if(y.body){let v=l.transpileModule(y.body.getText(t),{compilerOptions:{target:l.ScriptTarget.ESNext,module:l.ModuleKind.ESNext,removeComments:!1}});P=a(v.outputText.trim())}c.push(` ${j}get ${x}()${N} ${P}`)}if(l.isSetAccessorDeclaration(y)&&y.name){let x=y.name.getText(t),j=y.modifiers?.some(P=>P.kind===l.SyntaxKind.StaticKeyword)?"static ":"",w=re(y.parameters,t,n),N="{ }";if(y.body){let P=l.transpileModule(y.body.getText(t),{compilerOptions:{target:l.ScriptTarget.ESNext,module:l.ModuleKind.ESNext,removeComments:!1}});N=a(P.outputText.trim())}c.push(` ${j}set ${x}(${w.join(", ")}) ${N}`)}if(l.isPropertyDeclaration(y)&&y.name){let x=y.name.getText(t),j=y.modifiers?.some(N=>N.kind===l.SyntaxKind.StaticKeyword)?"static ":"",w=p.get(x)||x;if(y.initializer){let N=y.initializer.getText(t),P=N.trimStart().startsWith("{")?`(${N})`:N,O=l.transpileModule(P,{compilerOptions:{target:l.ScriptTarget.ESNext,module:l.ModuleKind.ESNext,removeComments:!1}}).outputText.trim();P!==N&&(O=O.replace(/^\(/,"").replace(/\);?\s*$/,"")),c.push(` ${j}${w} = ${O}`)}else c.push(` ${j}${w}`)}}let d=e.modifiers?.some(y=>y.kind===l.SyntaxKind.ExportKeyword)?"export ":"",h=f?` extends ${f}`:"";return`${d}class ${i}${h} {
|
|
38
|
+
${c.join(`
|
|
39
|
+
`)}
|
|
40
|
+
}`}function re(e,t,n,s,r){let o=[];for(let i of e){let u=i.name.getText(t);if(u==="this")continue;let f=!!i.dotDotDotToken,p=!!i.questionToken||!!i.initializer,a=M(i.type,void 0,n,r);if(f)a==="any"||a==="undefined"?o.push(`...${u}: [null]`):o.push(`...${u}: ${a}`);else if(i.initializer){let c=i.initializer.getText(t);o.push(`${u} = ${c}`)}else if(a==="any"||a==="undefined"){if(o.push(u),s&&i.type){let c=i.type.getText(t);c!=="any"&&c!=="unknown"&&s.push(`${u}: ${c}`)}}else p?o.push(`${u}: ${a} | undefined`):o.push(`${u}: ${a}`)}return o}function ye(e,t,n,s){let r=s;if(e.typeParameters&&e.typeParameters.length>0){let p=new Map;for(let a of e.typeParameters)p.set(a.name.getText(t),{constraint:a.constraint,default:a.default});r={...s,typeParams:p}}let o=l.isFunctionDeclaration(e)&&e.name?e.name.getText(t):"anonymous",i={};for(let p of e.parameters){let a=p.name.getText(t),c=!!p.questionToken||!!p.initializer,m;if(p.initializer){let d=p.initializer.getText(t);try{m=JSON.parse(d)}catch{m=d}}i[a]={type:K(p.type,r),required:!c,default:m}}let u={name:o,params:i,returns:e.type?K(e.type,r):void 0},f=zt(e,n);return f&&(u.typeParams=f),u}function nn(e,t,n,s){let r=s;if(e.typeParameters&&e.typeParameters.length>0){let a=new Map;for(let c of e.typeParameters)a.set(c.name.getText(t),{constraint:c.constraint,default:c.default});r={...s,typeParams:a}}let o=e.name?.getText(t)||"anonymous",i={},u={},f;for(let a of e.members){if(l.isConstructorDeclaration(a)){let c={};for(let m of a.parameters){let d=m.name.getText(t),h=!!m.questionToken||!!m.initializer,y;if(m.initializer){let x=m.initializer.getText(t);try{y=JSON.parse(x)}catch{y=x}}c[d]={type:K(m.type,r),required:!h,default:y}}f={params:c}}if(l.isMethodDeclaration(a)&&a.name){let c=a.name.getText(t),m=a.modifiers?.some(y=>y.kind===l.SyntaxKind.StaticKeyword),d={};for(let y of a.parameters){let x=y.name.getText(t),k=!!y.questionToken||!!y.initializer,j;if(y.initializer){let w=y.initializer.getText(t);try{j=JSON.parse(w)}catch{j=w}}d[x]={type:K(y.type,r),required:!k,default:j}}let h={name:c,params:d,returns:a.type?K(a.type,r):void 0};m?u[c]=h:i[c]=h}}let p={name:o,methods:i,staticMethods:u,constructor:f};if(e.typeParameters&&e.typeParameters.length>0){let a={};for(let c of e.typeParameters){let m=c.name.getText(t),d={};c.constraint&&(d.constraint=M(c.constraint,void 0,n,s)),c.default&&(d.default=M(c.default,void 0,n,s)),a[m]=d}p.typeParams=a}return p}function sn(e){let t=[],n=/\/\*\s*@tjs\s+((?:Tjs\w+\s*)+)\*\//g,s;for(;(s=n.exec(e))!==null;){let r=s[1].trim().split(/\s+/);for(let o of r)rn.has(o)&&!t.includes(o)&&t.push(o)}return t}function on(e){let t=[],n=/\/\*\s*@tjs-skip\s*\*\//g,s;for(;(s=n.exec(e))!==null;)t.push({index:s.index,kind:"skip"});let r=/\/\*\s*@tjs\s+predicate(\([^)]*\)\s*\{[\s\S]*?\})\s*\*\//g;for(;(s=r.exec(e))!==null;)t.push({index:s.index,kind:"predicate",text:`predicate${s[1].trim()}`});let o=/\/\*\s*@tjs\s+example:\s*([\s\S]*?)\s*\*\//g;for(;(s=o.exec(e))!==null;)t.push({index:s.index,kind:"example",text:s[1].trim()});let i=/\/\*\s*@tjs\s+declaration\s*(\{[\s\S]*?\})\s*\*\//g;for(;(s=i.exec(e))!==null;)t.push({index:s.index,kind:"declaration",text:s[1].trim()});return t.sort((u,f)=>u.index-f.index)}function an(e,t){let n=new Map;if(e.length===0)return n;let s=t.statements;for(let r=0;r<s.length;r++){let o=s[r],i;if((l.isInterfaceDeclaration(o)||l.isTypeAliasDeclaration(o)||l.isEnumDeclaration(o))&&(i=o.name.getText(t)),!i)continue;let u=o.getStart(t),f=r>0?s[r-1].getEnd():0,p=e.filter(a=>a.index>=f&&a.index<u);p.length>0&&n.set(i,p)}return n}function un(e){let t=[],n=/\/\*test\s+(['"`])([^'"`]*)\1\s*\{[\s\S]*?\}\s*\*\/|\/\*test\s*\{[\s\S]*?\}\s*\*\//g,s;for(;(s=n.exec(e))!==null;)t.push(s[0]);return t}function cn(e){let t=[],n=/\/\*#[\s\S]*?\*\//g,s=0,r=null,o=[];for(let u=0;u<e.length;u++){let f=e[u],p=u>0?e[u-1]:"";!r&&(f==='"'||f==="'"||f==="`")?r=f:r&&f===r&&p!=="\\"&&(r=null),r||(f==="{"&&s++,f==="}"&&s--),o[u]=s}let i;for(;(i=n.exec(e))!==null;)o[i.index]===0&&t.push({content:i[0],index:i.index});return t}function ln(e,t={}){let{emitTJS:n=!1,filename:s="input.ts"}=t,r=[],o=un(e),i=n?cn(e):[],u=n?on(e):[],f=sn(e),p=f.includes("TjsClass")||f.includes("TjsStrict"),a=l.createSourceFile(s,e,l.ScriptTarget.Latest,!0),c=n?an(u,a):new Map,m=[],d=new Set,h={},y={},x=new Set,k=T=>{for(let $=0;$<i.length;$++){let S=i[$];!x.has($)&&S.index<T&&(m.push(S.content),x.add($))}},j=new Map,w=new Map;function N(T){if(l.isTypeAliasDeclaration(T)&&j.set(T.name.getText(a),T.type),l.isInterfaceDeclaration(T)){let $=T.name.getText(a),S=w.get($);if(S){let A=l.factory.updateInterfaceDeclaration(S,S.modifiers,S.name,S.typeParameters,S.heritageClauses,[...S.members,...T.members]);w.set($,A)}else w.set($,T)}l.forEachChild(T,N)}N(a);let P={typeAliases:j,interfaces:w,sourceFile:a,warnings:r,resolvedCache:new Map},v=new Map;for(let T of a.statements)if(l.isFunctionDeclaration(T)&&T.name){let $=T.name.getText(a);v.has($)||v.set($,{signatures:[],implementation:null});let S=v.get($);T.body?S.implementation=T:S.signatures.push(T)}for(let[T,$]of v)($.signatures.length===0||!$.implementation)&&v.delete(T);for(let T of a.statements){let $=!1;if(n&&k(T.getStart(a)),l.isFunctionDeclaration(T)&&T.name){let S=T.name.getText(a);$=!0;let A=v.get(S);if(A){if(T.body)if(n)m.push(...en(A.signatures,T,a,r));else{let g=[];for(let R of A.signatures)g.push(ye(R,a,r,P));let b=ye(T,a,r,P);b.overloads=g,h[S]=b}}else n?m.push(xt(T,a,void 0,r,!0,P)):h[S]=ye(T,a,r,P)}if(l.isVariableStatement(T)){let S=!1,A=T.modifiers?.some(g=>g.kind===l.SyntaxKind.ExportKeyword);for(let g of T.declarationList.declarations)if(l.isIdentifier(g.name)&&g.initializer&&(l.isArrowFunction(g.initializer)||l.isFunctionExpression(g.initializer))){S=!0;let b=g.name.getText(a),R=g.initializer;if(n){let C=xt(R,a,b,r,!0,P);if(A&&!C.includes("export ")){let D=C.search(/^(async\s+)?function[\s*]/m);D>0?C=C.slice(0,D)+"export "+C.slice(D):C="export "+C}m.push(C)}else{let C=ye(R,a,r,P);C.name=b,h[b]=C}}if(!S&&n){let g=l.transpileModule(T.getText(a),{compilerOptions:{target:l.ScriptTarget.ESNext,module:l.ModuleKind.ESNext,removeComments:!1}});m.push(g.outputText.trim())}$=!0}if(l.isInterfaceDeclaration(T)&&($=!0,n)){let S=T.name.getText(a),A=c.get(S);if(!d.has(S)&&(d.add(S),!A?.some(g=>g.kind==="skip"))){let g=w.get(S)||T,b=Vt(g,a,r,A);if(b){let R=T.modifiers?.some(C=>C.kind===l.SyntaxKind.ExportKeyword);m.push(R?b.replace(/^(\/\*[\s\S]*?\*\/\s*)?/,"$1export "):b)}}}if(l.isTypeAliasDeclaration(T)&&($=!0,n)){let S=T.name.getText(a),A=c.get(S);if(!d.has(S)&&(d.add(S),!A?.some(g=>g.kind==="skip"))){let g=Xt(T,a,r,A);if(g){let b=T.modifiers?.some(R=>R.kind===l.SyntaxKind.ExportKeyword);m.push(b?g.replace(/^(\/\*[\s\S]*?\*\/\s*)?/,"$1export "):g)}}}if(l.isEnumDeclaration(T)&&($=!0,n)){let S=T.name.getText(a),A=c.get(S);if(!d.has(S)&&(d.add(S),!A?.some(g=>g.kind==="skip"))){let g=Yt(T,a,r);g&&m.push(g)}}if(l.isClassDeclaration(T)&&T.name){let S=T.name.getText(a);if($=!0,n){let A=tn(T,a,r,void 0,p);m.push(A)}else y[S]=nn(T,a,r,P)}if(l.isImportDeclaration(T)&&($=!0,n&&!(T.importClause?.isTypeOnly||T.importClause?.namedBindings&&l.isNamedImports(T.importClause.namedBindings)&&T.importClause.namedBindings.elements.every(A=>A.isTypeOnly))))if(T.importClause?.namedBindings&&l.isNamedImports(T.importClause.namedBindings)){let A=T.importClause.namedBindings.elements.filter(g=>!g.isTypeOnly).map(g=>{let b=g.name.getText(a),R=g.propertyName?.getText(a);return R?`${R} as ${b}`:b});if(A.length>0){let g=T.moduleSpecifier.text;m.push(`import { ${A.join(", ")} } from '${g}'`)}}else{let g=T.getText(a).replace(/\btype\s+/g,"").replace(/\s*:\s*\w+/g,"");m.push(g)}if((l.isExportDeclaration(T)||l.isExportAssignment(T))&&($=!0,n)){let A=l.transpileModule(T.getText(a),{compilerOptions:{target:l.ScriptTarget.ESNext,module:l.ModuleKind.ESNext,removeComments:!1}}).outputText.trim();A&&m.push(A)}if(!$&&n){let A=l.transpileModule(T.getText(a),{compilerOptions:{target:l.ScriptTarget.ESNext,module:l.ModuleKind.ESNext,removeComments:!1}}).outputText.trim();A&&m.push(A)}}if(n){k(1/0);let T=s||"unknown",S=`${f.length>0?f.join(`
|
|
41
|
+
`)+`
|
|
42
|
+
|
|
43
|
+
`:""}/* tjs <- ${T} */
|
|
44
|
+
|
|
45
|
+
`,A=o.length>0?`
|
|
46
|
+
|
|
47
|
+
`+o.join(`
|
|
48
|
+
|
|
49
|
+
`):"";return{code:S+m.join(`
|
|
50
|
+
|
|
51
|
+
`)+A,warnings:r.length>0?r:void 0}}let _=l.transpileModule(e,{compilerOptions:{target:l.ScriptTarget.ESNext,module:l.ModuleKind.ESNext,removeComments:!1}}).outputText;for(let[T,$]of Object.entries(h)){let S={params:Object.fromEntries(Object.entries($.params).map(([g,b])=>[g,{type:b.type.kind,required:b.required,default:b.default}])),returns:$.returns?{type:$.returns.kind}:void 0};$.typeParams&&(S.typeParams=$.typeParams);let A=JSON.stringify(S,null,2);_+=`
|
|
52
|
+
${T}.__tjs = ${A};
|
|
53
|
+
`}for(let[T,$]of Object.entries(y)){let S={constructor:$.constructor?{params:Object.fromEntries(Object.entries($.constructor.params??{}).map(([g,b])=>[g,{type:b.type.kind,required:b.required,default:b.default}]))}:void 0,methods:Object.fromEntries(Object.entries($.methods??{}).map(([g,b])=>[g,{params:Object.fromEntries(Object.entries(b.params??{}).map(([R,C])=>[R,{type:C.type.kind,required:C.required}])),returns:b.returns?{type:b.returns.kind}:void 0}])),staticMethods:Object.fromEntries(Object.entries($.staticMethods??{}).map(([g,b])=>[g,{params:Object.fromEntries(Object.entries(b.params??{}).map(([R,C])=>[R,{type:C.type.kind,required:C.required}])),returns:b.returns?{type:b.returns.kind}:void 0}]))};$.typeParams&&(S.typeParams=$.typeParams);let A=JSON.stringify(S,null,2);_+=`
|
|
54
|
+
${T}.__tjs = ${A};
|
|
55
|
+
`,_+=`
|
|
56
|
+
${Tt(T)}
|
|
57
|
+
`}return{code:_,types:h,classes:Object.keys(y).length>0?y:void 0,warnings:r.length>0?r:void 0}}var Gt,St,rn,kt=Y(()=>{"use strict";Be();ht();Gt=20,St=new Set(["Event","CustomEvent","MouseEvent","KeyboardEvent","PointerEvent","TouchEvent","FocusEvent","InputEvent","CompositionEvent","WheelEvent","DragEvent","AnimationEvent","TransitionEvent","ClipboardEvent","UIEvent","ProgressEvent","ErrorEvent","MessageEvent","PopStateEvent","HashChangeEvent","PageTransitionEvent","StorageEvent","BeforeUnloadEvent","SubmitEvent","EventTarget","EventListener","Node","Element","HTMLElement","SVGElement","Document","DocumentFragment","ShadowRoot","Text","Comment","Attr","HTMLInputElement","HTMLTextAreaElement","HTMLSelectElement","HTMLButtonElement","HTMLFormElement","HTMLAnchorElement","HTMLImageElement","HTMLVideoElement","HTMLAudioElement","HTMLCanvasElement","HTMLDivElement","HTMLSpanElement","HTMLParagraphElement","HTMLTableElement","HTMLTemplateElement","HTMLSlotElement","HTMLDialogElement","HTMLDetailsElement","HTMLLabelElement","HTMLOptionElement","HTMLIFrameElement","HTMLScriptElement","HTMLStyleElement","HTMLLinkElement","HTMLMetaElement","HTMLHeadElement","HTMLBodyElement","HTMLMediaElement","SVGSVGElement","SVGPathElement","SVGGElement","SVGCircleElement","SVGRectElement","SVGTextElement","SVGLineElement","SVGPolygonElement","NodeList","HTMLCollection","NamedNodeMap","DOMTokenList","DOMStringMap","CSSStyleDeclaration","DOMRect","DOMRectReadOnly","DOMPoint","DOMMatrix","Range","Selection","StaticRange","MutationObserver","MutationRecord","IntersectionObserver","IntersectionObserverEntry","ResizeObserver","ResizeObserverEntry","PerformanceObserver","PerformanceEntry","Window","Location","History","Navigator","Screen","Storage","CanvasRenderingContext2D","WebGLRenderingContext","WebGL2RenderingContext","OffscreenCanvas","ImageData","ImageBitmap","MediaStream","MediaRecorder","AudioContext","AudioNode","AudioBuffer","Worker","SharedWorker","ServiceWorker","ServiceWorkerRegistration","BroadcastChannel","MessageChannel","MessagePort","WebSocket","XMLHttpRequest","FileReader","FileList","DataTransfer","Crypto","SubtleCrypto","CryptoKey","Geolocation","Notification","PermissionStatus","MediaQueryList","TreeWalker","NodeIterator","ClipboardItem"]);rn=new Set(["TjsStrict","TjsEquals","TjsClass","TjsDate","TjsNoeval","TjsNoVar","TjsStandard","TjsSafeEval"])});var pn="https://esm.sh/typescript@5",$t="__TJS_TS__",ue=null;function fn(e=pn){return globalThis[$t]?Promise.resolve():(ue||(ue=import(e).then(t=>{let n=t?.default??t;if(!n||typeof n.createSourceFile!="function")throw ue=null,new Error(`Loaded ${e} but it is not a usable TypeScript compiler (no createSourceFile). Try a different typescriptUrl.`);globalThis[$t]=n},t=>{throw ue=null,t})),ue)}async function An(e,t={}){let{typescriptUrl:n,...s}=t;await fn(n);let{fromTS:r}=await Promise.resolve().then(()=>(kt(),bt));return r(e,s)}export{pn as DEFAULT_TYPESCRIPT_URL,An as fromTS,fn as loadTypeScript};
|
|
58
|
+
//# sourceMappingURL=tjs-browser-from-ts.js.map
|