tjs-lang 0.8.4 → 0.8.6

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.
@@ -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';
@@ -0,0 +1,2 @@
1
+ declare const shim: any;
2
+ export default shim;
@@ -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 d of a.anyOf)if(U(p,d))return!0;return u("Union mismatch")}if(a.const!==void 0)return p===a.const||u("Const mismatch");if(p===null){let d=a.type==="null"&&!a["x-tjs-undefined"],m=Array.isArray(a.type)&&a.type.includes("null");return d||m||!a.type||u("Expected value, got null")}if(p===void 0){let d=a.type==="null"&&a["x-tjs-undefined"],m=Array.isArray(a.type)&&a.type.includes("null");return d||m||!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 d=Math.abs(p%a.multipleOf),m=1e-10;if(d>1e-10&&Math.abs(d-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 d=a.minProperties!==void 0,m=o&&a.maxProperties!==void 0;if(d||m){let h=0;for(let y in p)Object.prototype.hasOwnProperty.call(p,y)&&h++;if(d&&h<a.minProperties)return u("Too few props");if(m&&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 d=p.length;if(a.minItems!==void 0&&d<a.minItems)return u("Array too short");if(a.maxItems!==void 0&&d>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 m=o||d<=97?1:Math.floor(d/97);for(let h=0;h<d;h+=m){let y=m>1&&h>d-1-m?d-1:h;i.push(String(y));let x=f(p[y],a.items);if(i.pop(),!x)return!1;if(y===d-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],d="any";V(c)?d=c.description:c!==void 0&&(d=typeof c=="string"?"string":JSON.stringify(c)),f=f.replace(new RegExp(`\\b${p}\\b`,"g"),d)}),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),d=Object.keys(p.params);for(let m=0;m<c.length;m++){let h=p.params[d[m]],y=n[c[m]];if(h?.type?.kind&&y!==void 0){let x=Mt(y);if(x&&h.type.kind!==x&&h.type.kind!=="any")return`param '${c[m]}' 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.6",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",d=function(...m){if(ne>0)return e.apply(this,m);let h=o||!r&&I.safety!=="none",y=s&&(u||!i&&I.safety==="all");if(!h&&!y)return e.apply(this,m);if(m.length>0&&q(m[0]))return m[0];if(h){let k=m.length===1&&typeof m[0]=="object"&&m[0]!==null&&!Array.isArray(m[0]),j=[];if(k){let w=m[0];for(let N=0;N<a;N++){let[P,v]=p[N],M=w[P];if(q(M)){j.push(M);continue}if(v.required&&M===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(M!==void 0){let _=te(M,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=m[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 M=te(v,P.type,`${c}.${N}`);M&&(P.loc&&(M.loc=P.loc),j.push(M))}}if(j.length>0)return Je(j,c)}let x=I.callStacks||I.debug;x&&it(c);try{let k=e.apply(this,m);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(d,"name",{value:e.name}),d.__tjs=t,d.__tjs.schema=()=>he(t),d}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 d(){return{...e}}function m(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 O=0;O<r;O++)g.push(n[(b+O)%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,O){N.has(g)||N.set(g,new Map),N.get(g).set(b,O)}function v(g,b){let O=typeof g,C;if(g==null)return;if(O==="string")C="String";else if(O==="number")C="Number";else if(O==="boolean")C="Boolean";else if(Array.isArray(g))C="Array";else if(O==="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(O==="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 M(g,b,O){let C=O===null?"null":typeof O,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 O=0;O<f;O++)g.push(i[(b+O)%o]);return g}function T(){let g=_();return u=0,f=0,p=0,g}function $(){return p}function S(g,b){let O={$error:!0,message:g,...b};if((e.callStacks||e.debug)&&r>0){let C=b?.path?[...y(),b.path]:y();O.stack=C}return O}function R(g,b){return g==null?M(`bang.${b}`,"non-null",g):Ke(g)?g:g[b]}return{version:et,MonadicError:G,typeError:M,isMonadicError:Ke,bang:R,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:d,pushStack:m,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 A(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=A(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`[${A(r.typeArguments[0],t,n,s)}]`;if(o==="Promise"||o==="Generator"||o==="AsyncGenerator"||o==="IterableIterator"||o==="AsyncIterableIterator")return r.typeArguments?.length?A(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 A(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),d=A(a.type,t,n,{...s,visited:u});p.push(`${c}: ${d}`)}return`{ ${p.join(", ")} }`}if(s?.typeParams?.has(o)){let u=s.typeParams.get(o);if(u.constraint)return A(u.constraint,t,n,s);if(u.default)return A(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=A(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=A(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=>A(c,t,n,s)).filter((c,d,m)=>m.indexOf(c)===d);return a.some(c=>c==="any")?"any":a.length===1?a[0]:a.length>0?a.some(d=>/[()]/.test(d)||d.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 A(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=A(f.type,t,n,s);a==="any"&&(a="null"),o.push(`${p}: ${a}`)}let i=A(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)?A(i.type,t):A(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 d={kind:l.SyntaxKind.TypeReference,typeName:{getText:()=>c}},m=K(d,{...t,visited:o});m.kind==="object"&&m.shape&&Object.assign(u,m.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=A(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=A(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),d=A(a.type,void 0,n);d==="any"&&(d="null"),p.push(`${c}: ${d}`)}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 d=A(a.default,void 0,n);o.push(`${c} = ${d}`)}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(m=>m.name.getText(t)),c=["typeof x === 'object'","x !== null"];for(let m of e.members)if(l.isPropertySignature(m)&&m.name){let h=m.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`),m.type&&l.isTypeReferenceNode(m.type)){let k=m.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 d=c.name.getText(t),m=c.questionToken?"?":"",h=c.type?A(c.type,void 0,n):"null";a.push(`${d}${m}: ${h}`)}else if(l.isMethodSignature(c)&&c.name){let d=c.name.getText(t),m=c.type?A(c.type,void 0,n):"null";a.push(`${d}: FunctionPredicate('function', { returns: ${m} })`)}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 d=c.name?.getText(t)||"_";if(d==="this")continue;let m=A(c.type,void 0,n);m==="any"&&(m="null"),f.push(`${d}: ${m}`)}let p=A(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=A(e.type,void 0,n);if(i==="any"||i==="undefined"){let u=e.type.getText(t).trim().replace(/\s+/g," ");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 d=c.name.getText(t);if(o.add(d),c.default){let m=A(c.default,void 0,n);i.push(`${d} = ${m}`)}else i.push(d)}let u=[];for(let c of r.parameters){let d=c.name?.getText(t)||"_";if(d==="this")continue;let m=c.type?.getText(t)||"any";if(o.has(m))u.push(`${d}: ${m}`);else{let h=A(c.type,void 0,n);h==="any"&&(h="null"),u.push(`${d}: ${h}`)}}let f=r.type?.getText(t)||"void",p;f!=="void"&&(o.has(f)?p=f:(p=A(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 d=c.name.getText(t);if(c.default){let m=A(c.default,void 0,n);o.push(`${d} = ${m}`)}else o.push(d)}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 d=[];for(let m of c.members)if(l.isPropertySignature(m)&&m.name){let h=m.name.getText(t),y=m.questionToken?"?":"",x=m.type?A(m.type,void 0,n):"null";d.push(`${h}${y}: ${x}`)}else if(l.isMethodSignature(m)&&m.name){let h=m.name.getText(t),y=m.type?A(m.type,void 0,n):"null";d.push(`${h}: FunctionPredicate('function', { returns: ${y} })`)}d.length>0&&a.push(`declaration {
27
+ ${d.join(`
28
+ `)}
29
+ }`)}else if(c){let d=c.getText(t).trim().replace(/\s+/g," ");a.push(`declaration {
30
+ // TS: ${d}
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 M of e.typeParameters)i.set(M.name.getText(t),{constraint:M.constraint,default:M.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
+ `:"",d=n||(l.isFunctionDeclaration(e)&&e.name?e.name.getText(t):""),m=e.type?A(e.type,void 0,s,u):"",h=m&&m!=="undefined"&&m!=="any"&&!m.startsWith("new ")?`:! ${m}`:"";if(e.type&&(m==="any"||m==="undefined")){let M=e.type.getText(t);M!=="any"&&M!=="unknown"&&M!=="void"&&f.push(`return: ${M}`)}let y;if(e.body){let M=l.isBlock(e.body)?e.body.getText(t):`{ return ${e.body.getText(t)} }`;y=l.transpileModule(M,{compilerOptions:{target:l.ScriptTarget.ESNext,module:l.ModuleKind.ESNext,removeComments:!1}}).outputText.trim()}else y="{ }";let x=e.modifiers?.some(M=>M.kind===l.SyntaxKind.ExportKeyword),k=e.modifiers?.some(M=>M.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}${d}(${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 m=t.body.getText(n);f=l.transpileModule(m,{compilerOptions:{target:l.ScriptTarget.ESNext,module:l.ModuleKind.ESNext,removeComments:!1}}).outputText.trim()}let p=t.modifiers?.some(m=>m.kind===l.SyntaxKind.AsyncKeyword),a=!!t.asteriskToken,c=p?"async ":"",d=a?"function* ":"function ";i.push(`${c}${d}${o}(${u.join(", ")}) ${f}`);for(let m of e){let h=re(m.parameters,n,s),y=m.parameters.map(P=>P.name.getText(n)),x=m.type?A(m.type,void 0,s):"",k=x&&x!=="undefined"&&x!=="any"?`:! ${x}`:"",{line:j}=n.getLineAndCharacterOfPosition(m.getStart(n)),w=`/* line ${j+1} */
37
+ `,N=a?"yield* ":"return ";i.push(`${w}${c}${d}${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?A(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 M=!!y.asteriskToken,_=k?"static ":"",T=j?"async ":"",$=M?"*":"";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?A(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,M=l.transpileModule(P,{compilerOptions:{target:l.ScriptTarget.ESNext,module:l.ModuleKind.ESNext,removeComments:!1}}).outputText.trim();P!==N&&(M=M.replace(/^\(/,"").replace(/\);?\s*$/,"")),c.push(` ${j}${w} = ${M}`)}else c.push(` ${j}${w}`)}}let m=e.modifiers?.some(y=>y.kind===l.SyntaxKind.ExportKeyword)?"export ":"",h=f?` extends ${f}`:"";return`${m}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=A(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,d;if(p.initializer){let m=p.initializer.getText(t);try{d=JSON.parse(m)}catch{d=m}}i[a]={type:K(p.type,r),required:!c,default:d}}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 d of a.parameters){let m=d.name.getText(t),h=!!d.questionToken||!!d.initializer,y;if(d.initializer){let x=d.initializer.getText(t);try{y=JSON.parse(x)}catch{y=x}}c[m]={type:K(d.type,r),required:!h,default:y}}f={params:c}}if(l.isMethodDeclaration(a)&&a.name){let c=a.name.getText(t),d=a.modifiers?.some(y=>y.kind===l.SyntaxKind.StaticKeyword),m={};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}}m[x]={type:K(y.type,r),required:!k,default:j}}let h={name:c,params:m,returns:a.type?K(a.type,r):void 0};d?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 d=c.name.getText(t),m={};c.constraint&&(m.constraint=A(c.constraint,void 0,n,s)),c.default&&(m.default=A(c.default,void 0,n,s)),a[d]=m}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,d=[],m=new Set,h={},y={},x=new Set,k=T=>{for(let $=0;$<i.length;$++){let S=i[$];!x.has($)&&S.index<T&&(d.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 R=l.factory.updateInterfaceDeclaration(S,S.modifiers,S.name,S.typeParameters,S.heritageClauses,[...S.members,...T.members]);w.set($,R)}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 R=v.get(S);if(R){if(T.body)if(n)d.push(...en(R.signatures,T,a,r));else{let g=[];for(let O of R.signatures)g.push(ye(O,a,r,P));let b=ye(T,a,r,P);b.overloads=g,h[S]=b}}else n?d.push(xt(T,a,void 0,r,!0,P)):h[S]=ye(T,a,r,P)}if(l.isVariableStatement(T)){let S=!1,R=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),O=g.initializer;if(n){let C=xt(O,a,b,r,!0,P);if(R&&!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}d.push(C)}else{let C=ye(O,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}});d.push(g.outputText.trim())}$=!0}if(l.isInterfaceDeclaration(T)&&($=!0,n)){let S=T.name.getText(a),R=c.get(S);if(!m.has(S)&&(m.add(S),!R?.some(g=>g.kind==="skip"))){let g=w.get(S)||T,b=Vt(g,a,r,R);if(b){let O=T.modifiers?.some(C=>C.kind===l.SyntaxKind.ExportKeyword);d.push(O?b.replace(/^(\/\*[\s\S]*?\*\/\s*)?/,"$1export "):b)}}}if(l.isTypeAliasDeclaration(T)&&($=!0,n)){let S=T.name.getText(a),R=c.get(S);if(!m.has(S)&&(m.add(S),!R?.some(g=>g.kind==="skip"))){let g=Xt(T,a,r,R);if(g){let b=T.modifiers?.some(O=>O.kind===l.SyntaxKind.ExportKeyword);d.push(b?g.replace(/^(\/\*[\s\S]*?\*\/\s*)?/,"$1export "):g)}}}if(l.isEnumDeclaration(T)&&($=!0,n)){let S=T.name.getText(a),R=c.get(S);if(!m.has(S)&&(m.add(S),!R?.some(g=>g.kind==="skip"))){let g=Yt(T,a,r);g&&d.push(g)}}if(l.isClassDeclaration(T)&&T.name){let S=T.name.getText(a);if($=!0,n){let R=tn(T,a,r,void 0,p);d.push(R)}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(R=>R.isTypeOnly))))if(T.importClause?.namedBindings&&l.isNamedImports(T.importClause.namedBindings)){let R=T.importClause.namedBindings.elements.filter(g=>!g.isTypeOnly).map(g=>{let b=g.name.getText(a),O=g.propertyName?.getText(a);return O?`${O} as ${b}`:b});if(R.length>0){let g=T.moduleSpecifier.text;d.push(`import { ${R.join(", ")} } from '${g}'`)}}else{let g=T.getText(a).replace(/\btype\s+/g,"").replace(/\s*:\s*\w+/g,"");d.push(g)}if((l.isExportDeclaration(T)||l.isExportAssignment(T))&&($=!0,n)){let R=l.transpileModule(T.getText(a),{compilerOptions:{target:l.ScriptTarget.ESNext,module:l.ModuleKind.ESNext,removeComments:!1}}).outputText.trim();R&&d.push(R)}if(!$&&n){let R=l.transpileModule(T.getText(a),{compilerOptions:{target:l.ScriptTarget.ESNext,module:l.ModuleKind.ESNext,removeComments:!1}}).outputText.trim();R&&d.push(R)}}if(n){k(1/0);let T=s||"unknown",S=`${f.length>0?f.join(`
41
+ `)+`
42
+
43
+ `:""}/* tjs <- ${T} */
44
+
45
+ `,R=o.length>0?`
46
+
47
+ `+o.join(`
48
+
49
+ `):"";return{code:S+d.join(`
50
+
51
+ `)+R,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 R=JSON.stringify(S,null,2);_+=`
52
+ ${T}.__tjs = ${R};
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(([O,C])=>[O,{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(([O,C])=>[O,{type:C.type.kind,required:C.required}])),returns:b.returns?{type:b.returns.kind}:void 0}]))};$.typeParams&&(S.typeParams=$.typeParams);let R=JSON.stringify(S,null,2);_+=`
54
+ ${T}.__tjs = ${R};
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