@tslite/checker 0.1.0
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/dist/index.cjs +1 -0
- package/dist/index.d.cts +488 -0
- package/dist/index.d.ts +488 -0
- package/dist/index.js +1 -0
- package/package.json +59 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var core=require('@tslite/core'),capability=require('@tslite/capability'),codec=require('@tslite/codec');var R=e=>Object.freeze(e),i={any:R({t:"any"}),unknown:R({t:"unknown"}),string:R({t:"string"}),number:R({t:"number"}),boolean:R({t:"boolean"}),null:R({t:"null"}),undefined:R({t:"undefined"}),literal:e=>({t:"literal",value:e}),object:e=>({t:"object",props:e}),array:e=>({t:"array",items:e}),fn:(e,n)=>({t:"fn",params:e,returns:n}),ctor:(e,n)=>({t:"fn",params:e,returns:n,construct:{params:e,returns:n}}),var:e=>({t:"var",name:e}),apply:(e,n=[])=>({t:"apply",name:e,args:n}),promise:e=>({t:"apply",name:"Promise",args:[e]}),union:e=>{let n=[];for(let t of e)t.t==="union"?n.push(...t.of):n.push(t);return {t:"union",of:n}}};function q(e){if(e.t==="undefined")return {type:{t:"union",of:[]},hadUndefined:true};if(e.t==="union"&&e.of.some(n=>n.t==="undefined")){let n=e.of.filter(t=>t.t!=="undefined");return {type:n.length===1?n[0]:{t:"union",of:n},hadUndefined:true}}return {type:e,hadUndefined:false}}function z(e,n=new WeakSet){switch(e.t){case "string":case "number":case "boolean":case "null":case "literal":return true;case "array":return n.has(e)?true:(n.add(e),z(q(e.items).type,n));case "object":return n.has(e)?true:(n.add(e),Object.values(e.props).every(t=>z(q(t.type).type,n)));case "union":return n.has(e)?true:(n.add(e),e.of.every(t=>z(t,n)));case "undefined":case "fn":case "var":case "apply":case "any":case "unknown":return false}}var _e=e=>/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e);function b(e,n=new WeakSet){switch(e.t){case "any":case "unknown":case "string":case "number":case "boolean":case "null":case "undefined":return e.t;case "var":return e.name;case "literal":return typeof e.value=="string"?JSON.stringify(e.value):String(e.value);case "array":{let t=b(e.items,n);return Je(e.items)?`(${t})[]`:`${t}[]`}case "union":{if(n.has(e))return "\u2026";n.add(e);let t=e.of.length===0?"never":e.of.map(r=>b(r,n)).join(" | ");return n.delete(e),t}case "object":{if(n.has(e))return "\u2026";n.add(e);let t=Object.entries(e.props),r=t.map(([a,o])=>`${_e(a)?a:JSON.stringify(a)}${o.optional?"?":""}: ${b(o.type,n)}`).join("; ");return n.delete(e),t.length===0?"{}":`{ ${r} }`}case "fn":{if(n.has(e))return "\u2026";n.add(e);let t=e.params.map(a=>{let o=a.variadic?"...":"",s=a.optional&&!a.variadic?"?":"";return `${o}${a.name}${s}: ${b(a.type,n)}`}).join(", "),r=b(e.returns,n);return n.delete(e),`(${t}) => ${r}`}case "apply":{if(n.has(e))return "\u2026";n.add(e);let t=e.args.length===0?e.name:`${e.name}<${e.args.map(r=>b(r,n)).join(", ")}>`;return n.delete(e),t}}}function Je(e){return e.t==="union"&&e.of.length>0||e.t==="fn"}function N(e,n,t=new WeakSet){switch(e.t){case "var":return n[e.name]??e;case "array":return {t:"array",items:N(e.items,n,t)};case "union":return {t:"union",of:e.of.map(r=>N(r,n,t))};case "object":{if(t.has(e))return e;t.add(e);let r={};for(let a in e.props){let o=e.props[a];r[a]={type:N(o.type,n,t),optional:o.optional};}return t.delete(e),{t:"object",props:r}}case "fn":{if(t.has(e))return e;t.add(e);let a={t:"fn",params:e.params.map(o=>({...o,type:N(o.type,n,t)})),returns:N(e.returns,n,t)};return t.delete(e),a}case "apply":return {t:"apply",name:e.name,args:e.args.map(r=>N(r,n,t))};default:return e}}function O(e,n){if(e.t!=="apply")return false;let t=n[e.name];return t!==void 0&&t.params.length===e.args.length}function A(e,n){if(e.t!=="apply")return e;let t=n[e.name];if(!t||t.params.length!==e.args.length)return e;let r={};return t.params.forEach((a,o)=>r[a]=e.args[o]),N(t.body,r)}function B(e){switch(e.t){case "literal":return `#${typeof e.value}:${String(e.value)}`;case "object":return `{${Object.keys(e.props).sort().map(n=>`${n}${e.props[n].optional?"?":""}:${B(e.props[n].type)}`).join(",")}}`;case "array":return `[${B(e.items)}]`;case "union":return `(${e.of.map(B).sort().join("|")})`;case "fn":return `(${e.params.map(n=>B(n.type)).join(",")})=>${B(e.returns)}`;case "var":return `v:${e.name}`;case "apply":return `${e.name}<${e.args.map(B).join(",")}>`;default:return e.t}}function S(e,n,t={}){return T(e,n,{seen:new WeakMap,exp:new Set,schemes:t})}function Q(e,n,t={}){return S(e,n,t)&&S(n,e,t)}function T(e,n,t){if(e.t==="any"||n.t==="any"||n.t==="unknown")return true;if(e.t==="unknown")return false;if(!(e.t==="apply"&&n.t==="apply"&&e.name===n.name&&e.args.length===n.args.length)&&(O(e,t.schemes)||O(n,t.schemes))){let o=`${B(e)}\u2264${B(n)}`;if(t.exp.has(o))return true;t.exp.add(o);let s=T(A(e,t.schemes),A(n,t.schemes),t);return t.exp.delete(o),s}let a=t.seen.get(e);if(a?.has(n))return true;if(a||(a=new WeakSet,t.seen.set(e,a)),a.add(n),e.t==="union")return e.of.every(o=>T(o,n,t));if(n.t==="union")return n.of.some(o=>T(e,o,t));switch(n.t){case "literal":return e.t==="literal"&&e.value===n.value;case "string":case "number":case "boolean":case "null":case "undefined":return e.t===n.t?true:e.t==="literal"&&He(e.value)===n.t;case "array":return e.t==="array"&&T(e.items,n.items,t);case "object":return e.t==="object"&&Ze(e,n,t);case "fn":return e.t==="fn"&&Ye(e,n,t);case "var":return e.t==="var"&&e.name===n.name;case "apply":return e.t==="apply"&&e.name===n.name&&e.args.length===n.args.length&&e.args.every((o,s)=>T(o,n.args[s],t))}}var He=e=>typeof e;function Ze(e,n,t){for(let r in n.props){let a=n.props[r],o=e.props[r];if(!o){if(!a.optional)return false;continue}if(o.optional&&!a.optional||!T(o.type,a.type,t))return false}return true}function Ye(e,n,t){if(!T(e.returns,n.returns,t))return false;for(let r=0;r<e.params.length;r++){let a=e.params[r];if(a.variadic)break;let o=n.params[r];if(!o){if(a.optional)continue;return false}if(!T(o.type,a.type,t))return false}return true}function k(e){let n=[];for(let r of e)r.t==="union"?n.push(...r.of):n.push(r);if(n.some(r=>r.t==="any"))return i.any;let t=[];for(let r of n)if(!t.some(a=>S(r,a))){for(let a=t.length-1;a>=0;a--)S(t[a],r)&&t.splice(a,1);t.push(r);}return t.length===1?t[0]:{t:"union",of:t}}var Qe=i.union([]);function Te(e,n){return X(e,n,new WeakMap)}function Xe(e){return e.reduce(Te,Qe)}function X(e,n,t){if(e.t==="any"||n.t==="any")return i.any;if(e===n)return e;let r=t.get(e)?.get(n);if(r)return r;if(e.t==="object"&&n.t==="object")return en(e,n,t);if(e.t==="array"&&n.t==="array"){let a={t:"array",items:i.unknown};return xe(t,e,n,a),a.items=X(e.items,n.items,t),a}return k([e,n])}function en(e,n,t){let r={t:"object",props:{}};xe(t,e,n,r);for(let a in e.props){let o=e.props[a],s=n.props[a];if(s){let l=X(o.type,s.type,t);r.props[a]=o.optional||s.optional?{type:l,optional:true}:{type:l};}else r.props[a]={type:o.type,optional:true};}for(let a in n.props)a in e.props||(r.props[a]={type:n.props[a].type,optional:true});return r}function xe(e,n,t,r){let a=e.get(n);a||(a=new WeakMap,e.set(n,a)),a.set(t,r);}function F(e,n,t={}){let r=e;for(let a of n){let o=ee(r,a,t);if(o===null)return null;r=o;}return {type:r,completions:ne(r,t)}}var nn=e=>e==="[]"||/^\d+$/.test(e);function ee(e,n,t,r=new Set){if(O(e,t)){let a=B(e);if(r.has(a))return null;r.add(a);let o=ee(A(e,t),n,t,r);return r.delete(a),o}switch(e.t){case "any":return e;case "object":return e.props[n]?.type??null;case "array":return nn(n)?e.items:null;case "union":{let a=e.of.map(o=>ee(o,n,t,r)).filter(o=>o!==null);return a.length?k(a):null}default:return null}}function ne(e,n,t=new WeakSet,r=new Set){if(O(e,n)){let a=B(e);if(r.has(a))return [];r.add(a);let o=ne(A(e,n),n,t,r);return r.delete(a),o}switch(e.t){case "object":return Object.entries(e.props).map(([a,o])=>({key:a,type:o.type,optional:!!o.optional}));case "array":return [{key:"[]",type:e.items,optional:false}];case "union":{if(t.has(e))return [];t.add(e);let a=[],o=new Set;for(let s of e.of)for(let l of ne(s,n,t,r))o.has(l.key)||(o.add(l.key),a.push(l));return t.delete(e),a}default:return []}}function x(e,n,t={}){if(e.t==="var"){let r=t[e.name];return r?S(n,r)||S(r,n)?t:null:{...t,[e.name]:n}}if(n.t==="any"||n.t==="unknown")return t;switch(e.t){case "array":return n.t==="array"?x(e.items,n.items,t):null;case "object":{if(n.t!=="object")return null;let r=t;for(let a in e.props){let o=e.props[a],s=n.props[a];if(!s){if(o.optional)continue;return null}if(r=x(o.type,s.type,r),r===null)return null}return r}case "fn":{if(n.t!=="fn")return null;let r=x(e.returns,n.returns,t);if(r===null)return null;let a=Math.min(e.params.length,n.params.length);for(let o=0;o<a;o++)if(r=x(e.params[o].type,n.params[o].type,r),r===null)return null;return r}case "apply":{if(n.t!=="apply"||n.name!==e.name||n.args.length!==e.args.length)return null;let r=t;for(let a=0;a<e.args.length;a++)if(r=x(e.args[a],n.args[a],r),r===null)return null;return r}default:return S(n,e)?t:null}}function tn(e,n){let t={};for(let r=0;r<e.params.length;r++){let a=e.params[r];if(a.variadic){for(let o=r;o<n.length;o++)if(t=x(a.type,n[o],t),t===null)return null;break}if(r>=n.length){if(a.optional)continue;return null}if(t=x(a.type,n[r],t),t===null)return null}return {returns:N(e.returns,t),bindings:t}}function V(e,n){let t={};for(let r=0;r<e.params.length&&r<n.length;r++){let a=e.params[r],o=x(a.type,n[r],t);o!==null&&(t=o);}return {returns:N(e.returns,t),bindings:t}}function C(e,n=new WeakSet){switch(e.t){case "var":return i.unknown;case "array":return {t:"array",items:C(e.items,n)};case "union":return {t:"union",of:e.of.map(t=>C(t,n))};case "object":{if(n.has(e))return e;n.add(e);let t={};for(let r in e.props){let a=e.props[r];t[r]={type:C(a.type,n),optional:a.optional};}return n.delete(e),{t:"object",props:t}}case "fn":{if(n.has(e))return e;n.add(e);let r={t:"fn",params:e.params.map(a=>({...a,type:C(a.type,n)})),returns:C(e.returns,n)};return n.delete(e),r}case "apply":return {t:"apply",name:e.name,args:e.args.map(t=>C(t,n))};default:return e}}var je=(e={})=>core.rootScope(e),j=(e,n)=>core.childScope(e,n),P=(e,n)=>core.lookup(e,n),te=e=>core.visibleNames(e),ln=(e={},n={},t={},r={})=>({scope:je(e),types:n,schemes:t,accessors:r}),un=(e,n)=>e.types[n],pn=(e,n)=>e.schemes[n];var D=(e,n,t)=>({code:e,severity:"error",node:n,message:t}),E=(e,n,t,r="error")=>({code:e,severity:r,node:n,message:t}),h={notAssignable:(e,n,t)=>D("not-assignable",e,`Type '${b(n)}' is not assignable to type '${b(t)}'.`),unknownName:(e,n)=>D("unknown-name",e,`Cannot find name '${n}'.`),notCallable:(e,n)=>D("not-callable",e,`Type '${b(n)}' is not callable.`),notNewable:(e,n)=>D("not-newable",e,`Type '${b(n)}' is not newable \u2014 only host constructors (with a construct signature) can be used with 'new'.`),noSuchMember:(e,n,t)=>D("no-such-member",e,`Property '${t}' does not exist on type '${b(n)}'.`),notObject:(e,n)=>D("not-object",e,`Type '${b(n)}' has no members to access.`),constNeedsInit:e=>D("const-needs-init",e,"'const' declarations must be initialized."),missingArgument:(e,n,t)=>D("missing-argument",e,`Missing argument '${n}' of type '${b(t)}'.`),unsupported:(e,n)=>D("unsupported",e,`${n} is not supported in this language.`),castUnsound:(e,n,t)=>E("cast-unsound",e,`Conversion of type '${b(n)}' to type '${b(t)}' may be a mistake \u2014 neither sufficiently overlaps the other. Cast through 'unknown' first if intentional.`,"warning")};function re(){let e=[];return {all:e,report(n){e.push(n);},hasErrors(){return e.some(n=>n.severity==="error")}}}function oe(e,n,t={}){return n.flatMap(r=>r(e,t))}function K(e,n){let t=r=>{n(r);for(let a of core.childrenOf(r))t(a);};t(e);}var mn=e=>Array.isArray(e)?e:[e],De=["ArrowFunctionExpression","FunctionExpression","FunctionDeclaration"];function se(e,n="error"){return t=>{let r=[];return K(t,a=>{let o=capability.nodeViolation(a,e);o&&r.push(E("node-not-allowed",a,`'${o}' is not allowed by the capability profile.`,n));}),r}}function ie(e,n="error"){let t=new Set(e);return r=>{let a=[];return K(r,o=>{if(o.type!=="CallExpression")return;let s=o.callee;if(s.type!=="Identifier")a.push(E("name-not-allowed",s,"Only direct calls to allowed functions are permitted.",n));else {let l=s.name;t.has(l)||a.push(E("name-not-allowed",s,`Function '${l}' is not allowed here.`,n));}}),a}}function _(e,n,t={}){let r=new Set(mn(e)),a=t.severity??"error",o=[...r].join("/");return s=>{let l=[],m=(c,f)=>{let d=r.has(c.type),y=d?f+1:f;d&&y>n&&l.push(E("too-deep",c,`Nesting of ${o} exceeds ${n}${t.hint?` \u2014 ${t.hint}`:""}.`,a));for(let g of core.childrenOf(c))m(g,y);};return m(s,0),l}}var le=(e=3,n="error")=>_(De,e,{hint:"use a pipe instead of nesting functions",severity:n}),ue=(e,n="error")=>_("CallExpression",e,{hint:"use a pipe instead of nesting calls",severity:n}),pe=(e,n="error")=>_("MemberExpression",e,{severity:n});function ce(e,n="error"){return t=>{let r=[],a=(o,s)=>{if(s>e){r.push(E("too-deep",o,`Expression nesting exceeds ${e}.`,n));return}for(let l of core.childrenOf(o))a(l,s+1);};return a(t,0),r}}function me(e,n="error"){return t=>{let r=0;return K(t,()=>{r++;}),r>e?[E("too-large",t,`Expression has ${r} nodes (max ${e}).`,n)]:[]}}function ye(e,n="error"){return t=>{let r=[];return K(t,a=>{if(a.type==="CallExpression"){let o=a.arguments;o&&o.length>e&&r.push(E("too-large",a,`Call has ${o.length} arguments (max ${e}).`,n));}}),r}}function fe(e,n={},t="error"){return (r,a)=>{let o=a.overlay?.get(r)?.type;return o?S(o,e,n)?[]:[E("wrong-result-type",r,`Result type '${b(o)}' is not assignable to the required '${b(e)}'.`,t)]:[]}}function $e(e){let n=[se(e)];return e.hostAllow!=="*"&&n.push(ie([...e.hostAllow])),n}function de(e){return $e(capability.compileProfile(e))}var Sn=e=>{let n={};for(let t of Object.keys(e))n[t]={params:[],body:e[t]};return n};function hn(e){let n=[];return e.maxDepth!==void 0&&n.push(ce(e.maxDepth)),e.maxNodes!==void 0&&n.push(me(e.maxNodes)),e.maxArgs!==void 0&&n.push(ye(e.maxArgs)),e.maxFunctionNesting!==void 0&&n.push(le(e.maxFunctionNesting)),e.maxCallNesting!==void 0&&n.push(ue(e.maxCallNesting)),e.memberDepth!==void 0&&n.push(pe(e.memberDepth)),n}function gn(e,n,t={}){let r={...Sn(n.types),...n.schemes,...bn(e)},a={overlay:new WeakMap,sink:re(),env:n,schemes:r},o=p(e,n.scope,a),s=[];t.profile&&s.push(...de(t.profile)),t.limits&&s.push(...hn(t.limits)),t.resultType&&s.push(fe(t.resultType,r));let l=s.length?[...a.sink.all,...oe(e,s,{overlay:a.overlay})]:a.sink.all;return {type:o,overlay:a.overlay,diagnostics:l}}var bn=e=>{let n={};return core.walk(e,{TSTypeAliasDeclaration(t){let r=t;r.id?.name&&r.typeAnnotation&&(n[r.id.name]={params:r.typeParameters??[],body:r.typeAnnotation});}}),n},ke=e=>e.typeAnnotation,Ie=e=>e.returnType,u=(e,n,t,r)=>(e.overlay.set(n,{type:t,scope:r}),t),Se=e=>e.type==="ArrowFunctionExpression",Le=e=>e.t==="apply"&&e.name==="Promise"&&e.args.length===1,he=e=>Le(e)?e.args[0]:e,J=e=>Le(e)?e:i.promise(e);function p(e,n,t){switch(e.type){case "Literal":return u(t,e,Ge(e),n);case "Identifier":{let r=e.name,a=P(n,r);return a===void 0?r==="undefined"?u(t,e,i.undefined,n):(t.sink.report(h.unknownName(e,r)),u(t,e,i.unknown,n)):u(t,e,a,n)}case "MemberExpression":return u(t,e,kn(e,n,t),n);case "CallExpression":return u(t,e,wn(e,n,t),n);case "NewExpression":return u(t,e,Bn(e,n,t),n);case "ArrowFunctionExpression":return Ne(e,n,t);case "FunctionDeclaration":return t.sink.report(h.unsupported(e,"function declaration (use 'const fn = () => \u2026')")),u(t,e,i.unknown,n);case "FunctionExpression":return t.sink.report(h.unsupported(e,"anonymous function (use an arrow)")),u(t,e,i.unknown,n);case "ThisExpression":return t.sink.report(h.unsupported(e,"'this'")),u(t,e,i.unknown,n);case "BlockStatement":return u(t,e,we(e,n,t),n);case "ReturnStatement":{let r=e.argument;return u(t,e,r?p(r,n,t):i.unknown,n)}case "IfStatement":return v(e,n,t),t.overlay.get(e)?.type??i.unknown;case "ForStatement":case "WhileStatement":case "DoWhileStatement":case "ForOfStatement":case "ForInStatement":case "BreakStatement":case "ContinueStatement":case "ThrowStatement":case "TryStatement":case "SwitchStatement":return v(e,n,t),t.overlay.get(e)?.type??i.unknown;case "AssignmentExpression":{let r=e;return p(r.left,n,t),u(t,e,p(r.right,n,t),n)}case "UpdateExpression":return p(e.argument,n,t),u(t,e,i.number,n);case "ExpressionStatement":return u(t,e,p(e.expression,n,t),n);case "VariableDeclaration":return Ee(e,n,t),u(t,e,i.unknown,n);case "TSTypeAliasDeclaration":return u(t,e,i.unknown,n);case "BinaryExpression":return u(t,e,On(e,n,t),n);case "LogicalExpression":{let r=e,a=p(r.left,n,t),o=p(r.right,n,t);return u(t,e,k([a,o]),n)}case "UnaryExpression":return u(t,e,Pn(e,n,t),n);case "ConditionalExpression":{let r=e;p(r.test,n,t);let a=p(r.consequent,n,t),o=p(r.alternate,n,t);return u(t,e,k([a,o]),n)}case "ObjectExpression":return u(t,e,In(e,n,t),n);case "ArrayExpression":return u(t,e,Ln(e,n,t),n);case "TemplateLiteral":{for(let r of e.expressions)p(r,n,t);return u(t,e,i.string,n)}case "AwaitExpression":{let r=e.argument,a=r?p(r,n,t):i.unknown;return u(t,e,he(a),n)}case "Program":return Be(e.body,n,t),u(t,e,i.unknown,n);case "JsonExpression":return u(t,e,be(e.body,n,t,e),n);case "ChainExpression":return u(t,e,k([p(e.expression,n,t),i.undefined]),n);case "TSAsExpression":{let r=e,a=p(r.expression,n,t),o=r.typeAnnotation;return !S(a,o,t.schemes)&&!S(o,a,t.schemes)&&t.sink.report(h.castUnsound(e,a,o)),u(t,e,o,n)}default:return t.sink.report(h.unsupported(e,`'${e.type}'`)),u(t,e,i.unknown,n)}}function Ge(e){let n=e;if(n.regex||n.bigint)return i.unknown;let t=n.value;if(t===null)return i.null;if(t===void 0)return i.undefined;switch(typeof t){case "string":return i.string;case "number":return i.number;case "boolean":return i.boolean;default:return i.unknown}}function kn(e,n,t){let r=p(e.object,n,t);if(e.computed){p(e.property,n,t);let s=F(r,["[]"],t.schemes);return s?s.type:i.unknown}let a=e.property.name,o=F(r,[a],t.schemes);return o?o.type:(r.t==="object"||r.t==="array"||r.t==="union"?t.sink.report(h.noSuchMember(e,r,a)):r.t!=="any"&&r.t!=="unknown"&&t.sink.report(h.notObject(e,r)),i.unknown)}function Nn(e){let n=r=>r&&r.type==="Literal"&&typeof r.value=="string"?r.value:null;if(e.length===1&&e[0].type==="ArrayExpression"){let r=[];for(let a of e[0].elements){let o=n(a);if(o===null)return null;r.push(o);}return r}let t=[];for(let r of e){let a=n(r);if(a===null)return null;t.push(a);}return t.length?t:null}function Me(e){if(e.type==="Identifier")return e.name;if(e.type==="MemberExpression"){let n=e;if(n.computed||n.property.type!=="Identifier")return null;let t=Me(n.object);return t===null?null:`${t}.${n.property.name}`}return null}function wn(e,n,t){let r=e.arguments,a=Me(e.callee);if(a){let f=t.env.accessors?.[a];if(f){let d=Nn(r);if(d){let y=F(f,d,t.schemes);return y?y.type:(t.sink.report(h.noSuchMember(e,f,d.join("."))),i.unknown)}return r.forEach(y=>p(y,n,t)),i.unknown}}let o=p(e.callee,n,t);if(o.t==="any")return r.forEach(f=>p(f,n,t)),i.any;if(o.t!=="fn")return r.forEach(f=>p(f,n,t)),t.sink.report(h.notCallable(e,o)),i.unknown;let s=o,l=r.map(f=>Se(f)?i.any:p(f,n,t)),m=V(s,l).bindings;r.forEach((f,d)=>{if(Se(f)){let y=N(s.params[d]?.type??i.any,m);l[d]=Ne(f,n,t,y);}});let{bindings:c}=V(s,l);return Ue(e,s,l,c,t),C(N(s.returns,c))}function Bn(e,n,t){let r=e.arguments,a=p(e.callee,n,t);if(a.t==="any")return r.forEach(c=>p(c,n,t)),i.any;let o=a.t==="fn"?a.construct:void 0;if(!o)return r.forEach(c=>p(c,n,t)),t.sink.report(h.notNewable(e,a)),i.unknown;let s={params:o.params,returns:o.returns},l=r.map(c=>Se(c)?i.any:p(c,n,t)),{bindings:m}=V(s,l);return Ue(e,s,l,m,t),C(N(o.returns,m))}function Ue(e,n,t,r,a){for(let o=0;o<n.params.length;o++){let s=n.params[o];if(s.variadic)break;let l=N(s.type,r);if(o>=t.length){s.optional||a.sink.report(h.missingArgument(e,s.name,l));continue}S(t[o],l,a.schemes)||a.sink.report(h.notAssignable(e.arguments[o],t[o],l));}}var We=e=>{let n=e.value;return n===null?i.null:typeof n=="string"||typeof n=="number"||typeof n=="boolean"?i.literal(n):Ge(e)},En=(e,n)=>{let t=e;for(let r=0;r<50&&t.t==="apply";r++){let a=A(t,n.schemes);if(a===t||a.t==="apply"&&a.name===t.name)break;t=a;}return t};function L(e,n,t,r){let a=En(n,r);switch(e.type){case "Literal":{let s=We(e);return S(s,n,r.schemes)||r.sink.report(h.notAssignable(e,s,n)),u(r,e,n,t)}case "ArrayExpression":{if(a.t==="array"){for(let s of e.elements){if(!s)continue;let l=s;l.type==="SpreadElement"?L(l.argument,n,t,r):L(l,a.items,t,r);}return u(r,e,n,t)}break}case "ObjectExpression":{if(a.t==="object"){let s={};for(let m of e.properties){let c=m;if(c.type==="SpreadElement"){p(c.argument,t,r);continue}let f=c,d=Ke(f),y=d!==null?a.props[d]?.type:void 0,g=y?L(f.value,y,t,r):p(f.value,t,r);d!==null&&(s[d]={type:g}),u(r,c,g,t);}let l={t:"object",props:s};return S(l,n,r.schemes)||r.sink.report(h.notAssignable(e,l,n)),u(r,e,n,t)}break}case "ArrowFunctionExpression":{if(a.t==="fn"){let s=Ne(e,t,r,a);return S(s,n,r.schemes)||r.sink.report(h.notAssignable(e,s,n)),u(r,e,n,t)}break}case "ConditionalExpression":{let s=e;return p(s.test,t,r),L(s.consequent,n,t,r),L(s.alternate,n,t,r),u(r,e,n,t)}}let o=p(e,t,r);return S(o,n,r.schemes)||r.sink.report(h.notAssignable(e,o,n)),u(r,e,o,t)}function vn(e){let n=Ie(e);return n?{t:"fn",params:e.params.map((r,a)=>({name:G(r)??`arg${a}`,type:ke(r)??i.unknown})),returns:e.async?J(n):n}:null}function Ne(e,n,t,r){let a=r&&r.t==="fn"?r:void 0,o={},s=e.params.map((y,g)=>{let w=y,M=G(w),$=ke(w)??a?.params[g]?.type??i.unknown;return M&&(o[M]=$),t.overlay.set(w,{type:$,scope:n}),{name:M??`arg${g}`,type:$}}),l=j(n,o),m=e.body,c=Ie(e);if(m.type!=="BlockStatement"&&c){let y=e.async?he(c):c;L(m,y,l,t);let g=e.async?J(c):c;return u(t,e,{t:"fn",params:s,returns:g},n)}let f=m.type==="BlockStatement"?u(t,m,we(m,l,t),l):p(m,l,t),d=e.async?J(f):f;if(c){let y=e.async?he(c):c,g=e.async?f:d;S(g,y,t.schemes)||t.sink.report(h.notAssignable(m,d,c));let w=e.async?J(c):c;return u(t,e,{t:"fn",params:s,returns:w},n)}return u(t,e,{t:"fn",params:s,returns:d},n)}function we(e,n,t){let{returns:r}=Be(e.body,n,t);return r.length?k(r):i.unknown}function Be(e,n,t){let r=n,a=[];for(let o of e){let s=o;if(s.type==="VariableDeclaration")r=Ee(s,r,t);else if(s.type==="FunctionDeclaration"){let l=p(s,r,t),m=G(s.id);m&&(r=j(r,{[m]:l}));}else if(s.type==="IfStatement"){a.push(...v(s,r,t));let l=s;!l.alternate&&H(l.consequent)&&(r=ge(r,ze(l.test,r,t.schemes).else));}else a.push(...v(s,r,t));}return {scope:r,returns:a}}var U={then:{},else:{}},Ve={string:i.string,number:i.number,boolean:i.boolean},W=e=>e.t==="union"?[...e.of]:[e];function Oe(e,n){let t=e,r=n;return e.type==="UnaryExpression"&&t.operator==="typeof"&&t.argument.type==="Identifier"&&n.type==="Literal"&&typeof r.value=="string"?{name:t.argument.name,tag:r.value}:null}function Cn(e,n){let t=Ve[n];if(!t)return null;if(e.t==="unknown"||e.t==="any")return t;let r=W(e).filter(a=>S(a,t));return r.length?k(r):t}function An(e,n){let t=Ve[n];if(!t||e.t==="unknown"||e.t==="any")return null;let r=W(e).filter(a=>!S(a,t));return r.length?k(r):null}function Fe(e,n){if(e.type==="Identifier"&&n.type==="Literal"){let t=We(n);if(t.t==="literal"||t.t==="null")return {name:e.name,lit:t}}return null}function Tn(e,n,t){return e.t==="unknown"||e.t==="any"||S(n,e,t)?n:null}function xn(e,n,t){let r=W(e),a=r.filter(o=>!Q(o,n,t));return a.length&&a.length<r.length?k(a):null}var qe=e=>e.t==="null"||e.t==="undefined",jn=e=>{if(e.t==="unknown"||e.t==="any")return null;let n=W(e),t=n.filter(r=>!qe(r));return t.length&&t.length<n.length?k(t):null},Dn=e=>{let n=W(e),t=n.filter(qe);return t.length&&t.length<n.length?k(t):null},Pe=e=>e.type==="Literal"&&e.value===null?"null":e.type==="Identifier"&&e.name==="undefined"?"undefined":null,I=(e,n,t)=>({then:n?{[e]:n}:{},else:t?{[e]:t}:{}}),$n=e=>e==="==="||e==="=="||e==="!=="||e==="!=";function ze(e,n,t){if(e.type==="BinaryExpression"){let r=e;if(!$n(r.operator))return U;let a=r.operator==="!=="||r.operator==="!=",o=r.left,s=r.right,l=Oe(o,s)??Oe(s,o);if(l){let y=P(n,l.name);if(!y)return U;let g=Cn(y,l.tag),w=An(y,l.tag);return a?I(l.name,w,g):I(l.name,g,w)}let m=Pe(o),c=Pe(s),f=m?s:c?o:null;if((m||c)&&f?.type==="Identifier"){let y=f.name,g=P(n,y);if(!g)return U;let M=r.operator==="=="||r.operator==="!="?["null","undefined"]:[m??c],$=W(g),ve=$.filter(Y=>M.includes(Y.t)),Z=$.filter(Y=>!M.includes(Y.t)),Ce=ve.length?k(ve):null,Ae=Z.length&&Z.length<$.length?k(Z):null;return a?I(y,Ae,Ce):I(y,Ce,Ae)}let d=Fe(o,s)??Fe(s,o);if(d){let y=P(n,d.name);if(!y)return U;let g=Tn(y,d.lit,t),w=xn(y,d.lit,t);return a?I(d.name,w,g):I(d.name,g,w)}return U}if(e.type==="Identifier"){let r=e.name,a=P(n,r);if(a)return I(r,jn(a),Dn(a))}return U}var ge=(e,n)=>Object.keys(n).length?j(e,n):e;function H(e){switch(e.type){case "ReturnStatement":case "ThrowStatement":return true;case "BlockStatement":{let n=e.body;return n.length>0&&H(n[n.length-1])}case "IfStatement":{let n=e;return !!n.alternate&&H(n.consequent)&&H(n.alternate)}default:return false}}function v(e,n,t){switch(e.type){case "ReturnStatement":{let r=e.argument,a=r?p(r,n,t):i.unknown;return u(t,e,a,n),[a]}case "IfStatement":{let r=e;p(r.test,n,t);let a=ze(r.test,n,t.schemes),o=v(r.consequent,ge(n,a.then),t);return r.alternate&&o.push(...v(r.alternate,ge(n,a.else),t)),u(t,e,i.unknown,n),o}case "BlockStatement":{let r=we(e,n,t);return u(t,e,r,n),r.t==="unknown"?[]:[r]}case "ForStatement":case "WhileStatement":case "DoWhileStatement":{let r=e,a=n;r.init&&(r.init.type==="VariableDeclaration"?a=Ee(r.init,a,t):p(r.init,a,t)),r.test&&p(r.test,a,t),r.update&&p(r.update,a,t);let o=v(r.body,a,t);return u(t,e,i.unknown,n),o}case "ForOfStatement":case "ForInStatement":{let r=e,a=p(r.right,n,t),o=e.type==="ForOfStatement"?a.t==="array"?a.items:i.unknown:i.string,s=Rn(r.left),l=s?j(n,{[s]:o}):n,m=v(r.body,l,t);return u(t,e,i.unknown,n),m}case "BreakStatement":case "ContinueStatement":return u(t,e,i.unknown,n),[];case "ThrowStatement":{let r=e.argument;return r&&p(r,n,t),u(t,e,i.unknown,n),[]}case "TryStatement":{let r=e,a=v(r.block,n,t);if(r.handler){let o=r.handler.param,s=o?G(o):null,l=s?j(n,{[s]:i.unknown}):n;a.push(...v(r.handler.body,l,t));}return r.finalizer&&a.push(...v(r.finalizer,n,t)),u(t,e,i.unknown,n),a}case "SwitchStatement":{let r=e;p(r.discriminant,n,t);let a=n,o=[];for(let s of r.cases){s.test&&p(s.test,a,t);let l=Be(s.consequent,a,t);a=l.scope,o.push(...l.returns);}return u(t,e,i.unknown,n),o}default:return p(e,n,t),[]}}var Rn=e=>{if(e.type==="VariableDeclaration"){let n=e.declarations[0];return n?G(n.id):null}return G(e)};function Ee(e,n,t){let r={};for(let a of e.declarations){let o=G(a.id),s=ke(a.id);if(!a.init){t.sink.report(h.constNeedsInit(a)),o&&(r[o]=s??i.unknown);continue}let l=s??(a.init.type==="ArrowFunctionExpression"?vn(a.init):null),m=o&&l?j(n,{[o]:l}):n,c;s?(L(a.init,s,m,t),c=s):c=p(a.init,m,t),u(t,a,c,n),o&&(r[o]=c);}return u(t,e,i.unknown,n),j(n,r)}function On(e,n,t){let r=p(e.left,n,t),a=p(e.right,n,t),o=e.operator;return o==="+"?S(r,i.string)||S(a,i.string)?i.string:i.number:Fn.has(o)?i.number:i.boolean}var Fn=new Set(["-","*","/","%","**","&","|","^","<<",">>",">>>"]);function Pn(e,n,t){switch(p(e.argument,n,t),e.operator){case "!":return i.boolean;case "-":case "+":case "~":return i.number;case "typeof":return i.string;case "delete":return i.boolean;case "void":return i.undefined;default:return i.unknown}}function In(e,n,t){let r={};for(let a of e.properties){let o=a;if(o.type==="SpreadElement"){p(o.argument,n,t);continue}let s=o,l=p(s.value,n,t),m=Ke(s);m!==null&&(r[m]={type:l}),u(t,o,l,n);}return {t:"object",props:r}}var Ke=e=>{if(e.computed)return null;let n=e.key;return n.type==="Identifier"?n.name:n.type==="Literal"?String(n.value??""):null};function Ln(e,n,t){let r=[];for(let a of e.elements){if(!a)continue;let o=a;if(o.type==="SpreadElement"){p(o.argument,n,t);continue}r.push(p(o,n,t));}return i.array(r.length?k(r):i.unknown)}function be(e,n,t,r){if(e===null)return i.null;switch(typeof e){case "string":return i.string;case "number":return i.number;case "boolean":return i.boolean;case "object":break;default:return i.unknown}if(Array.isArray(e)){let s=e.map(l=>be(l,n,t,r));return i.array(s.length?k(s):i.unknown)}let a=e;if(core.AST_MARKER in a){let s;try{s=codec.fromJson(a);}catch{return t.sink.report(h.unsupported(r,`'#ast: ${String(a[core.AST_MARKER])}'`)),i.unknown}return p(s,n,t)}let o={};for(let s of Object.keys(a))o[s]={type:be(a[s],n,t,r)};return {t:"object",props:o}}var G=e=>e.type==="Identifier"?e.name:null;var Gn=(e,n)=>({...e,typeAnnotation:n}),Mn=(e,n)=>({...e,returnType:n});function Un(e,n){return e.get(n)?.type}function Wn(e,n){return e.get(n)?.scope}function Vn(e,n){let t=e.get(n)?.type;return t?F(t,[])?.completions??[]:[]}function qn(e,n){let t=e.get(n)?.scope;return t?[...te(t)].map(([r,a])=>({key:r,type:a,optional:false})):[]}function zn(e,n){return e.filter(t=>t.node===n)}exports.FUNCTION_KINDS=De;exports.annotate=Gn;exports.annotateReturn=Mn;exports.calleeAllowlist=ie;exports.capabilityNodes=se;exports.check=gn;exports.childScope=j;exports.createEnv=ln;exports.createSink=re;exports.diag=h;exports.diagnosticsAt=zn;exports.discover=F;exports.equals=Q;exports.expand1=A;exports.format=b;exports.fromCapability=de;exports.groundVars=C;exports.guard=oe;exports.guardsFromCompiled=$e;exports.instantiate=tn;exports.instantiateLoose=V;exports.isScheme=O;exports.isSerializable=z;exports.join=Te;exports.joinAll=Xe;exports.lookup=P;exports.makeDiagnostic=E;exports.maxArgs=ye;exports.maxCallNesting=ue;exports.maxDepth=ce;exports.maxFunctionNesting=le;exports.maxNestingOf=_;exports.maxNodes=me;exports.memberCompletions=Vn;exports.memberDepth=pe;exports.normalizeUnion=k;exports.resolveNamed=un;exports.resolveScheme=pn;exports.resultType=fe;exports.rootScope=je;exports.s=i;exports.scopeAt=Wn;exports.scopeCompletions=qn;exports.substitute=N;exports.subtype=S;exports.typeAt=Un;exports.unify=x;exports.visibleNames=te;exports.withoutUndefined=q;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
import { Scope as Scope$1, BaseNode, Node } from '@tslite/core';
|
|
2
|
+
import { CapabilityProfile, CompiledProfile } from '@tslite/capability';
|
|
3
|
+
|
|
4
|
+
/** Uma propriedade de um tipo objeto. */
|
|
5
|
+
interface Prop {
|
|
6
|
+
readonly type: Schema;
|
|
7
|
+
/** `true` quando a propriedade pode estar ausente (`{ x?: T }`). */
|
|
8
|
+
readonly optional?: boolean;
|
|
9
|
+
}
|
|
10
|
+
/** Um parâmetro de um tipo função. */
|
|
11
|
+
interface Param {
|
|
12
|
+
readonly name: string;
|
|
13
|
+
readonly type: Schema;
|
|
14
|
+
/** `true` quando o argumento pode ser omitido. */
|
|
15
|
+
readonly optional?: boolean;
|
|
16
|
+
/** `true` para o parâmetro rest (`...args: T[]`). */
|
|
17
|
+
readonly variadic?: boolean;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Assinatura de **construção** de um tipo função (`new X(...)`). Separada da
|
|
21
|
+
* assinatura de chamada porque podem diferir (ex.: `Date()` → string, `new Date()`
|
|
22
|
+
* → Date). Só construtor **host** (DI) declara isso — a Linguagem não define
|
|
23
|
+
* construtores (D38).
|
|
24
|
+
*/
|
|
25
|
+
interface ConstructSig {
|
|
26
|
+
readonly params: readonly Param[];
|
|
27
|
+
readonly returns: Schema;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* O tipo de um valor na linguagem TSLite.
|
|
31
|
+
*
|
|
32
|
+
* O discriminador é `t`. Estruturas (object/array/union/fn) referenciam outros
|
|
33
|
+
* `Schema` recursivamente — inclusive de forma cíclica (ex.: `Node` que contém
|
|
34
|
+
* `Node[]`); as operações que percorrem `Schema` são cycle-safe.
|
|
35
|
+
*/
|
|
36
|
+
type Schema = {
|
|
37
|
+
readonly t: "any";
|
|
38
|
+
} | {
|
|
39
|
+
readonly t: "unknown";
|
|
40
|
+
} | {
|
|
41
|
+
readonly t: "string";
|
|
42
|
+
} | {
|
|
43
|
+
readonly t: "number";
|
|
44
|
+
} | {
|
|
45
|
+
readonly t: "boolean";
|
|
46
|
+
} | {
|
|
47
|
+
readonly t: "null";
|
|
48
|
+
} | {
|
|
49
|
+
readonly t: "undefined";
|
|
50
|
+
} | {
|
|
51
|
+
readonly t: "literal";
|
|
52
|
+
readonly value: string | number | boolean;
|
|
53
|
+
} | {
|
|
54
|
+
readonly t: "object";
|
|
55
|
+
readonly props: Readonly<Record<string, Prop>>;
|
|
56
|
+
} | {
|
|
57
|
+
readonly t: "array";
|
|
58
|
+
readonly items: Schema;
|
|
59
|
+
} | {
|
|
60
|
+
readonly t: "union";
|
|
61
|
+
readonly of: readonly Schema[];
|
|
62
|
+
} | {
|
|
63
|
+
readonly t: "fn";
|
|
64
|
+
readonly params: readonly Param[];
|
|
65
|
+
readonly returns: Schema;
|
|
66
|
+
/** Assinatura de `new X(...)` — presente só em construtor host (D38). */
|
|
67
|
+
readonly construct?: ConstructSig;
|
|
68
|
+
} | {
|
|
69
|
+
readonly t: "var";
|
|
70
|
+
readonly name: string;
|
|
71
|
+
} | {
|
|
72
|
+
readonly t: "apply";
|
|
73
|
+
readonly name: string;
|
|
74
|
+
readonly args: readonly Schema[];
|
|
75
|
+
};
|
|
76
|
+
type AnySchema = Extract<Schema, {
|
|
77
|
+
t: "any";
|
|
78
|
+
}>;
|
|
79
|
+
type UnknownSchema = Extract<Schema, {
|
|
80
|
+
t: "unknown";
|
|
81
|
+
}>;
|
|
82
|
+
type LiteralSchema = Extract<Schema, {
|
|
83
|
+
t: "literal";
|
|
84
|
+
}>;
|
|
85
|
+
type ObjectSchema = Extract<Schema, {
|
|
86
|
+
t: "object";
|
|
87
|
+
}>;
|
|
88
|
+
type ArraySchema = Extract<Schema, {
|
|
89
|
+
t: "array";
|
|
90
|
+
}>;
|
|
91
|
+
type UnionSchema = Extract<Schema, {
|
|
92
|
+
t: "union";
|
|
93
|
+
}>;
|
|
94
|
+
type FnSchema = Extract<Schema, {
|
|
95
|
+
t: "fn";
|
|
96
|
+
}>;
|
|
97
|
+
type VarSchema = Extract<Schema, {
|
|
98
|
+
t: "var";
|
|
99
|
+
}>;
|
|
100
|
+
type ApplySchema = Extract<Schema, {
|
|
101
|
+
t: "apply";
|
|
102
|
+
}>;
|
|
103
|
+
type ScalarSchema = Extract<Schema, {
|
|
104
|
+
t: "string" | "number" | "boolean" | "null" | "undefined";
|
|
105
|
+
}>;
|
|
106
|
+
declare const s: {
|
|
107
|
+
readonly any: Schema;
|
|
108
|
+
readonly unknown: Schema;
|
|
109
|
+
readonly string: Schema;
|
|
110
|
+
readonly number: Schema;
|
|
111
|
+
readonly boolean: Schema;
|
|
112
|
+
readonly null: Schema;
|
|
113
|
+
readonly undefined: Schema;
|
|
114
|
+
readonly literal: (value: string | number | boolean) => Schema;
|
|
115
|
+
readonly object: (props: Record<string, Prop>) => Schema;
|
|
116
|
+
readonly array: (items: Schema) => Schema;
|
|
117
|
+
readonly fn: (params: Param[], returns: Schema) => Schema;
|
|
118
|
+
/**
|
|
119
|
+
* Construtor host: `s.ctor(params, Instance)` → função **newável** que devolve
|
|
120
|
+
* `Instance` (tanto via `new` quanto via chamada, p/ simplicidade). O canal é a
|
|
121
|
+
* DI — a Linguagem instancia construtores host, não os define (D38).
|
|
122
|
+
*/
|
|
123
|
+
readonly ctor: (params: Param[], instance: Schema) => Schema;
|
|
124
|
+
readonly var: (name: string) => Schema;
|
|
125
|
+
/** Construtor de tipo aplicado: `apply("Map", [K, V])` ⇒ `Map<K, V>`. */
|
|
126
|
+
readonly apply: (name: string, args?: readonly Schema[]) => Schema;
|
|
127
|
+
/** Açúcar para `Promise<T>` — o que `await` desembrulha. */
|
|
128
|
+
readonly promise: (value: Schema) => Schema;
|
|
129
|
+
/**
|
|
130
|
+
* Constrói uma união achatando uniões aninhadas. Não deduplica nem colapsa
|
|
131
|
+
* união-de-um aqui (isso depende de igualdade estrutural — ver `normalizeUnion`
|
|
132
|
+
* quando `subtype` existir); apenas garante uma lista plana.
|
|
133
|
+
*/
|
|
134
|
+
readonly union: (of: readonly Schema[]) => Schema;
|
|
135
|
+
};
|
|
136
|
+
/**
|
|
137
|
+
* Separa `undefined` de um tipo: devolve o tipo **sem** `undefined` e se ele estava
|
|
138
|
+
* presente. Em posição de **propriedade**, `T | undefined` é uma propriedade
|
|
139
|
+
* **opcional** de tipo `T` — espelha o `JSON.stringify` (chave `undefined` some).
|
|
140
|
+
* Só mexe em `undefined`, nunca em `null` (que é valor JSON presente). Usado pelo
|
|
141
|
+
* `serializable` e pelo `toJsonSchema` (mesma regra dos dois lados).
|
|
142
|
+
*/
|
|
143
|
+
declare function withoutUndefined(t: Schema): {
|
|
144
|
+
type: Schema;
|
|
145
|
+
hadUndefined: boolean;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* `true` quando `schema` descreve **dado puro** (sobrevive a `JSON.stringify`
|
|
150
|
+
* sem perda silenciosa). `fn` é o ponto-chave: uma função é dropada em silêncio
|
|
151
|
+
* pela serialização — por isso `false`.
|
|
152
|
+
*
|
|
153
|
+
* `apply` é **conservador** (`false`): sem registro de construtores-de-dado
|
|
154
|
+
* liberados, não dá pra garantir que `Foo<…>` (ou `Promise<T>`, `Map<K,V>`)
|
|
155
|
+
* vire JSON. `var` (forma desconhecida), `any`/`unknown` (sem garantia) → `false`.
|
|
156
|
+
*/
|
|
157
|
+
declare function isSerializable(schema: Schema, seen?: WeakSet<object>): boolean;
|
|
158
|
+
|
|
159
|
+
/** Renderiza `schema` como uma string no estilo TypeScript. */
|
|
160
|
+
declare function format(schema: Schema, seen?: WeakSet<object>): string;
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Um *type scheme*: um tipo nomeado parametrizado, `type Pair<A, B> = body`.
|
|
164
|
+
* `params` são as variáveis de tipo (na ordem); `body` é o `Schema` que as usa
|
|
165
|
+
* via `var`. Um tipo nomeado não-genérico é só um scheme com `params: []`.
|
|
166
|
+
*/
|
|
167
|
+
interface TypeScheme {
|
|
168
|
+
readonly params: readonly string[];
|
|
169
|
+
readonly body: Schema;
|
|
170
|
+
}
|
|
171
|
+
/** Registro de type schemes por nome — consultado pela expansão (ver `expand`). */
|
|
172
|
+
type Schemes = Readonly<Record<string, TypeScheme>>;
|
|
173
|
+
/**
|
|
174
|
+
* Um nível de escopo léxico (nome → `Schema`), sobre o `Scope<T>` genérico do
|
|
175
|
+
* `core` — a mesma cadeia que o `analysis` usa, com o payload do eixo de tipos.
|
|
176
|
+
*/
|
|
177
|
+
type Scope = Scope$1<Schema>;
|
|
178
|
+
/** Cria um escopo raiz (sem pai). */
|
|
179
|
+
declare const rootScope: (vars?: Record<string, Schema>) => Scope;
|
|
180
|
+
/** Estende `parent` com novos bindings, criando um escopo filho. */
|
|
181
|
+
declare const childScope: (parent: Scope, vars: Record<string, Schema>) => Scope;
|
|
182
|
+
/** Resolve `name` subindo a cadeia léxica. `undefined` se não existir. */
|
|
183
|
+
declare const lookup: (scope: Scope, name: string) => Schema | undefined;
|
|
184
|
+
/**
|
|
185
|
+
* Todos os nomes visíveis a partir de `scope`, com shadowing — o binding mais
|
|
186
|
+
* interno vence. É o que alimenta o autocomplete de identificadores.
|
|
187
|
+
*/
|
|
188
|
+
declare const visibleNames: (scope: Scope) => Map<string, Schema>;
|
|
189
|
+
/**
|
|
190
|
+
* O ambiente injetado pela aplicação — a fronteira de tipos do sistema.
|
|
191
|
+
* `scope` é a raiz da DI; `types` resolve tipos nomeados em anotações.
|
|
192
|
+
*/
|
|
193
|
+
/**
|
|
194
|
+
* O ambiente é **só tipos** (a fronteira da DI). Capability — o que pode ser
|
|
195
|
+
* programado — é ortogonal e mora no `CapabilityProfile` (`@tslite/capability`),
|
|
196
|
+
* passado ao `check` por `{ profile }`. Não há mais noção de capability no Env.
|
|
197
|
+
*/
|
|
198
|
+
interface Env {
|
|
199
|
+
readonly scope: Scope;
|
|
200
|
+
readonly types: Readonly<Record<string, Schema>>;
|
|
201
|
+
/** Type schemes parametrizados (`type Pair<A, B> = …`), expandidos sob demanda. */
|
|
202
|
+
readonly schemes: Schemes;
|
|
203
|
+
/**
|
|
204
|
+
* Acessores **indexados por path literal**: nome → schema-base que ele navega.
|
|
205
|
+
* Ex.: `get` sobre o schema dos States → `get("hp","value")` tipa como
|
|
206
|
+
* `discover(base, ["hp","value"])`. É como a fronteira tipa leituras de estado
|
|
207
|
+
* sem `unknown` (o app declara o shape; o checker indexa). Default: nenhum.
|
|
208
|
+
*/
|
|
209
|
+
readonly accessors?: Readonly<Record<string, Schema>>;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Cria um `Env` a partir das variáveis injetadas, dos tipos nomeados, dos type
|
|
213
|
+
* schemes e dos acessores. Capability é separada (passe um `profile` ao `check`).
|
|
214
|
+
*/
|
|
215
|
+
declare const createEnv: (vars?: Record<string, Schema>, types?: Record<string, Schema>, schemes?: Record<string, TypeScheme>, accessors?: Record<string, Schema>) => Env;
|
|
216
|
+
/** Resolve um tipo nomeado (`type User = …`) declarado no ambiente. */
|
|
217
|
+
declare const resolveNamed: (env: Env, name: string) => Schema | undefined;
|
|
218
|
+
/** Resolve um type scheme (`type Pair<A, B> = …`) declarado no ambiente. */
|
|
219
|
+
declare const resolveScheme: (env: Env, name: string) => TypeScheme | undefined;
|
|
220
|
+
|
|
221
|
+
/** `true` se um valor de tipo `a` pode ser usado onde se espera `b`. */
|
|
222
|
+
declare function subtype(a: Schema, b: Schema, schemes?: Schemes): boolean;
|
|
223
|
+
/** Igualdade estrutural: cada um é atribuível ao outro. */
|
|
224
|
+
declare function equals(a: Schema, b: Schema, schemes?: Schemes): boolean;
|
|
225
|
+
/**
|
|
226
|
+
* Normaliza uma união: achata, absorve `any`/`unknown`, deduplica e remove
|
|
227
|
+
* membros subsumidos por outro (`string | "x"` → `string`). Colapsa união de um
|
|
228
|
+
* membro no próprio membro. União vazia permanece vazia (renderiza `never`).
|
|
229
|
+
*/
|
|
230
|
+
declare function normalizeUnion(members: readonly Schema[]): Schema;
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* O supremo estrutural de `a` e `b`: o menor `Schema` ao qual ambos são
|
|
234
|
+
* atribuíveis. `unknown` é a unidade (sem-evidência); `any` é absorvente.
|
|
235
|
+
*/
|
|
236
|
+
declare function join(a: Schema, b: Schema): Schema;
|
|
237
|
+
/**
|
|
238
|
+
* Dobra uma lista de formas no seu supremo comum. Lista vazia → `never` (⊥, a
|
|
239
|
+
* identidade do supremo). Um membro → ele mesmo. É a operação do schema-reducer:
|
|
240
|
+
* `joinAll(amostras.map(inferValue))` descreve todas as amostras.
|
|
241
|
+
*/
|
|
242
|
+
declare function joinAll(members: readonly Schema[]): Schema;
|
|
243
|
+
|
|
244
|
+
/** Um membro que pode seguir a partir de um tipo (item de autocomplete). */
|
|
245
|
+
interface Completion {
|
|
246
|
+
/** Nome da propriedade, ou `"[]"` para o elemento de um array. */
|
|
247
|
+
readonly key: string;
|
|
248
|
+
readonly type: Schema;
|
|
249
|
+
readonly optional: boolean;
|
|
250
|
+
}
|
|
251
|
+
/** Resultado de navegar um path: o tipo final + o que pode seguir dele. */
|
|
252
|
+
interface Discovery {
|
|
253
|
+
readonly type: Schema;
|
|
254
|
+
readonly completions: readonly Completion[];
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Navega `path` a partir de `schema`. Retorna o tipo alcançado e suas
|
|
258
|
+
* completions, ou `null` se algum segmento não existir no tipo. Path vazio
|
|
259
|
+
* devolve o próprio tipo e suas completions.
|
|
260
|
+
*/
|
|
261
|
+
declare function discover(schema: Schema, path: readonly string[], schemes?: Schemes): Discovery | null;
|
|
262
|
+
|
|
263
|
+
/** Ligações `nome da var → tipo` (o resultado de `unify`/aplicação de scheme). */
|
|
264
|
+
type Bindings = Readonly<Record<string, Schema>>;
|
|
265
|
+
/** Aplica `bindings` a `schema`, trocando cada `var` ligada pelo seu tipo. */
|
|
266
|
+
declare function substitute(schema: Schema, bindings: Bindings, seen?: WeakSet<object>): Schema;
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Liga as `var`s de `pattern` aos tipos correspondentes em `actual`. Devolve as
|
|
270
|
+
* ligações estendidas, ou `null` se forem incompatíveis. `actual` que seja
|
|
271
|
+
* `any`/`unknown` não constrange vars (deixa-as livres).
|
|
272
|
+
*/
|
|
273
|
+
declare function unify(pattern: Schema, actual: Schema, bindings?: Bindings): Bindings | null;
|
|
274
|
+
/** Resultado de instanciar uma assinatura contra argumentos. */
|
|
275
|
+
interface Instantiation {
|
|
276
|
+
readonly returns: Schema;
|
|
277
|
+
readonly bindings: Bindings;
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Instancia uma função genérica: unifica cada argumento contra o parâmetro
|
|
281
|
+
* correspondente (ligando as `var`s) e devolve o retorno já substituído.
|
|
282
|
+
* Falha (`null`) se algum argumento não unificar. Um parâmetro `variadic`
|
|
283
|
+
* absorve os argumentos restantes (cada um unifica contra o tipo do rest).
|
|
284
|
+
*/
|
|
285
|
+
declare function instantiate(sig: FnSchema, args: readonly Schema[]): Instantiation | null;
|
|
286
|
+
/**
|
|
287
|
+
* Versão tolerante de {@link instantiate} para o editor/checker: nunca falha —
|
|
288
|
+
* argumentos que não unificam são ignorados, e `var`s não ligadas permanecem
|
|
289
|
+
* (útil para aplicação parcial e enquanto o usuário ainda digita).
|
|
290
|
+
*/
|
|
291
|
+
declare function instantiateLoose(sig: FnSchema, args: readonly Schema[]): Instantiation;
|
|
292
|
+
/** Aterra as `var`s remanescentes em `unknown` (para exibição do resultado). */
|
|
293
|
+
declare function groundVars(schema: Schema, seen?: WeakSet<object>): Schema;
|
|
294
|
+
|
|
295
|
+
/** Há um scheme registrado para este `apply` (com aridade compatível)? */
|
|
296
|
+
declare function isScheme(t: Schema, schemes: Schemes): boolean;
|
|
297
|
+
/**
|
|
298
|
+
* Expande **um nível**: `apply(name, args)` com scheme registrado vira
|
|
299
|
+
* `substitute(body, { param_i → args_i })`. Qualquer outro tipo (ou `apply` opaco)
|
|
300
|
+
* é devolvido intacto.
|
|
301
|
+
*/
|
|
302
|
+
declare function expand1(t: Schema, schemes: Schemes): Schema;
|
|
303
|
+
|
|
304
|
+
type Severity = "error" | "warning";
|
|
305
|
+
type DiagnosticCode = "not-assignable" | "unknown-name" | "not-callable" | "not-newable" | "no-such-member" | "not-object" | "const-needs-init" | "missing-argument" | "unsupported" | "cast-unsound" | "node-not-allowed" | "name-not-allowed" | "too-deep" | "too-large" | "wrong-result-type";
|
|
306
|
+
interface Diagnostic {
|
|
307
|
+
readonly code: DiagnosticCode;
|
|
308
|
+
readonly severity: Severity;
|
|
309
|
+
/** O nó culpado — identidade por referência. */
|
|
310
|
+
readonly node: BaseNode;
|
|
311
|
+
readonly message: string;
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Builder genérico de diagnóstico (severidade configurável). Usado pelos
|
|
315
|
+
* guardrails, que têm seu próprio catálogo de mensagens em `guard`.
|
|
316
|
+
*/
|
|
317
|
+
declare const makeDiagnostic: (code: DiagnosticCode, node: BaseNode, message: string, severity?: Severity) => Diagnostic;
|
|
318
|
+
/**
|
|
319
|
+
* Fábricas de diagnósticos. Mensagens no estilo do tsc, com tipos renderizados
|
|
320
|
+
* por `format`.
|
|
321
|
+
*/
|
|
322
|
+
declare const diag: {
|
|
323
|
+
notAssignable: (node: BaseNode, actual: Schema, expected: Schema) => Diagnostic;
|
|
324
|
+
unknownName: (node: BaseNode, name: string) => Diagnostic;
|
|
325
|
+
notCallable: (node: BaseNode, type: Schema) => Diagnostic;
|
|
326
|
+
notNewable: (node: BaseNode, type: Schema) => Diagnostic;
|
|
327
|
+
noSuchMember: (node: BaseNode, type: Schema, key: string) => Diagnostic;
|
|
328
|
+
notObject: (node: BaseNode, type: Schema) => Diagnostic;
|
|
329
|
+
constNeedsInit: (node: BaseNode) => Diagnostic;
|
|
330
|
+
missingArgument: (node: BaseNode, name: string, expected: Schema) => Diagnostic;
|
|
331
|
+
unsupported: (node: BaseNode, what: string) => Diagnostic;
|
|
332
|
+
/**
|
|
333
|
+
* Cast (`x as T`) entre tipos que não se sobrepõem em nenhum sentido. Warning
|
|
334
|
+
* (não erro): o cast é um escape-hatch explícito — `unknown`/`any` passam
|
|
335
|
+
* silenciosos; só o cast "torto" (ex.: `number as string`) avisa.
|
|
336
|
+
*/
|
|
337
|
+
castUnsound: (node: BaseNode, from: Schema, to: Schema) => Diagnostic;
|
|
338
|
+
};
|
|
339
|
+
/** Coletor de diagnósticos — acumula durante o walk, sem `throw`. */
|
|
340
|
+
interface DiagnosticSink {
|
|
341
|
+
/** Diagnósticos coletados, na ordem em que foram reportados. */
|
|
342
|
+
readonly all: readonly Diagnostic[];
|
|
343
|
+
report(d: Diagnostic): void;
|
|
344
|
+
/** `true` se há ao menos um diagnóstico de severidade `error`. */
|
|
345
|
+
hasErrors(): boolean;
|
|
346
|
+
}
|
|
347
|
+
/** Cria um coletor vazio. */
|
|
348
|
+
declare function createSink(): DiagnosticSink;
|
|
349
|
+
|
|
350
|
+
/** O overlay de tipos: tipo + escopo de cada nó, por referência (ESTree não tem id). */
|
|
351
|
+
type TypeOverlay = WeakMap<BaseNode, {
|
|
352
|
+
readonly type: Schema;
|
|
353
|
+
readonly scope: Scope;
|
|
354
|
+
}>;
|
|
355
|
+
interface CheckResult {
|
|
356
|
+
/** Tipo do nó raiz. */
|
|
357
|
+
readonly type: Schema;
|
|
358
|
+
readonly overlay: TypeOverlay;
|
|
359
|
+
readonly diagnostics: readonly Diagnostic[];
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Tipa `node` no ambiente `env` (a borda da DI: data, states, funções globais).
|
|
363
|
+
* Nunca lança; devolve o overlay e os diagnósticos coletados.
|
|
364
|
+
*/
|
|
365
|
+
/** Opções do `check`. */
|
|
366
|
+
interface CheckOptions {
|
|
367
|
+
/**
|
|
368
|
+
* Capability profile a enforçar. Quando dado, o `check` roda o guard de capability
|
|
369
|
+
* (`fromCapability`) além do type-checking e funde os diagnósticos (`node-not-allowed`).
|
|
370
|
+
* Sem ele, `check` faz **só type-checking** (sem opinar sobre capability).
|
|
371
|
+
*
|
|
372
|
+
* Capability **desinstala** features (o que pode existir em runtime — junto do
|
|
373
|
+
* interpret/printer); é ortogonal aos `limits`/`resultType` abaixo, que **validam**.
|
|
374
|
+
*/
|
|
375
|
+
readonly profile?: CapabilityProfile;
|
|
376
|
+
/**
|
|
377
|
+
* Limites estruturais (anti-DoS) — validações do checker, cada uma opt-in.
|
|
378
|
+
* Reportam `too-deep`/`too-large`.
|
|
379
|
+
*/
|
|
380
|
+
readonly limits?: {
|
|
381
|
+
/** Profundidade total de aninhamento do AST (qualquer nó). */
|
|
382
|
+
readonly maxDepth?: number;
|
|
383
|
+
/** Número total de nós (custo/complexidade). */
|
|
384
|
+
readonly maxNodes?: number;
|
|
385
|
+
/** Argumentos por chamada. */
|
|
386
|
+
readonly maxArgs?: number;
|
|
387
|
+
/** Aninhamento de funções (função-dentro-de-função). */
|
|
388
|
+
readonly maxFunctionNesting?: number;
|
|
389
|
+
/** Aninhamento de chamadas (`f(g(h(x)))`). */
|
|
390
|
+
readonly maxCallNesting?: number;
|
|
391
|
+
/** Profundidade de cadeia de membros (`a.b.c.d`). */
|
|
392
|
+
readonly memberDepth?: number;
|
|
393
|
+
};
|
|
394
|
+
/**
|
|
395
|
+
* Contrato de tipo de retorno: o tipo da expressão-raiz deve ser atribuível a
|
|
396
|
+
* `resultType`. Reporta `wrong-result-type`. (Ex.: uma condition deve ser `boolean`.)
|
|
397
|
+
*/
|
|
398
|
+
readonly resultType?: Schema;
|
|
399
|
+
}
|
|
400
|
+
declare function check(node: Node, env: Env, opts?: CheckOptions): CheckResult;
|
|
401
|
+
|
|
402
|
+
/** Contexto opcional de um guard (o overlay de tipos, p/ regras type-aware). */
|
|
403
|
+
interface GuardContext {
|
|
404
|
+
readonly overlay?: TypeOverlay;
|
|
405
|
+
}
|
|
406
|
+
/** Um guard: percorre `root` e devolve os diagnósticos que encontrar. */
|
|
407
|
+
type Guard = (root: BaseNode, ctx: GuardContext) => Diagnostic[];
|
|
408
|
+
/** Um profile é uma composição de guards. */
|
|
409
|
+
type Profile = readonly Guard[];
|
|
410
|
+
/** Roda um profile sobre `root`, concatenando todos os diagnósticos. */
|
|
411
|
+
declare function guard(root: BaseNode, profile: Profile, ctx?: GuardContext): Diagnostic[];
|
|
412
|
+
/** Os kinds que **definem** uma função. */
|
|
413
|
+
declare const FUNCTION_KINDS: readonly ["ArrowFunctionExpression", "FunctionExpression", "FunctionDeclaration"];
|
|
414
|
+
/**
|
|
415
|
+
* O guard de **capability**: percorre `root` e reporta `node-not-allowed` em todo
|
|
416
|
+
* nó proibido por `compiled` — via `nodeViolation`, a **fonte única** de gating
|
|
417
|
+
* compartilhada com o interpret e o printer. É o que `fromCapability` monta (+ o
|
|
418
|
+
* host allowlist). Garante que os 3 consumidores concordam por construção.
|
|
419
|
+
*/
|
|
420
|
+
declare function capabilityNodes(compiled: CompiledProfile, severity?: Severity): Guard;
|
|
421
|
+
/**
|
|
422
|
+
* O callee de toda chamada deve ser um identificador direto ∈ `names`. É o gate
|
|
423
|
+
* do **host** (a família `host.allow` do `CapabilityProfile`): só as funções
|
|
424
|
+
* liberadas pela DI podem ser chamadas. Montado por `fromCapability`.
|
|
425
|
+
*/
|
|
426
|
+
declare function calleeAllowlist(names: readonly string[], severity?: Severity): Guard;
|
|
427
|
+
/**
|
|
428
|
+
* Limita o **aninhamento de um kind** ao longo de qualquer caminho raiz→folha.
|
|
429
|
+
* Ex.: `maxNestingOf(FUNCTION_KINDS, 3)` barra a 4ª função aninhada.
|
|
430
|
+
*/
|
|
431
|
+
declare function maxNestingOf(kinds: string | readonly string[], max: number, opts?: {
|
|
432
|
+
hint?: string;
|
|
433
|
+
severity?: Severity;
|
|
434
|
+
}): Guard;
|
|
435
|
+
/** Aninhamento de funções (função-dentro-de-função). Padrão: 3 → use um pipe. */
|
|
436
|
+
declare const maxFunctionNesting: (max?: number, severity?: Severity) => Guard;
|
|
437
|
+
/** Aninhamento de chamadas (`f(g(h(x)))`). */
|
|
438
|
+
declare const maxCallNesting: (max: number, severity?: Severity) => Guard;
|
|
439
|
+
/** Profundidade de cadeia de membros (`a.b.c.d`). */
|
|
440
|
+
declare const memberDepth: (max: number, severity?: Severity) => Guard;
|
|
441
|
+
/** Profundidade total de aninhamento do AST (qualquer nó). */
|
|
442
|
+
declare function maxDepth(max: number, severity?: Severity): Guard;
|
|
443
|
+
/** Número total de nós (custo/complexidade). */
|
|
444
|
+
declare function maxNodes(max: number, severity?: Severity): Guard;
|
|
445
|
+
/** Número máximo de argumentos por chamada. */
|
|
446
|
+
declare function maxArgs(max: number, severity?: Severity): Guard;
|
|
447
|
+
/** O tipo da expressão-raiz deve ser atribuível a `expected`. */
|
|
448
|
+
declare function resultType(expected: Schema, schemes?: Schemes, severity?: Severity): Guard;
|
|
449
|
+
|
|
450
|
+
/** Traduz um `CompiledProfile` (já compilado) num `Profile` de guards. */
|
|
451
|
+
declare function guardsFromCompiled(c: CompiledProfile): Profile;
|
|
452
|
+
/**
|
|
453
|
+
* Compila um `CapabilityProfile` e o traduz num `Profile` de guards. Use com
|
|
454
|
+
* `guard(ast, fromCapability(PRESETS.predicate))`. Assume um profile válido
|
|
455
|
+
* (rode `validateProfile` antes p/ pegar combinações ilegais).
|
|
456
|
+
*/
|
|
457
|
+
declare function fromCapability(profile: CapabilityProfile): Profile;
|
|
458
|
+
|
|
459
|
+
/** Anota uma ligação/parâmetro: `x` → `x: T`. */
|
|
460
|
+
declare const annotate: <N extends BaseNode>(node: N, type: Schema) => N & {
|
|
461
|
+
typeAnnotation: Schema;
|
|
462
|
+
};
|
|
463
|
+
/** Anota o retorno de uma função: `() => …` → `(): R => …`. */
|
|
464
|
+
declare const annotateReturn: <N extends BaseNode>(fn: N, type: Schema) => N & {
|
|
465
|
+
returnType: Schema;
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
/** O tipo inferido de `node`, ou `undefined` se o nó não foi tipado. */
|
|
469
|
+
declare function typeAt(overlay: TypeOverlay, node: BaseNode): Schema | undefined;
|
|
470
|
+
/** O escopo léxico vigente em `node`, ou `undefined` se o nó não foi tipado. */
|
|
471
|
+
declare function scopeAt(overlay: TypeOverlay, node: BaseNode): Scope | undefined;
|
|
472
|
+
/**
|
|
473
|
+
* Completions de **membro**: o que pode seguir a partir do tipo de `node`
|
|
474
|
+
* (ex.: após `obj.` → as props de `obj`; após um array → `[]`). Vazio se o nó
|
|
475
|
+
* não foi tipado ou se o tipo não tem membros navegáveis.
|
|
476
|
+
*/
|
|
477
|
+
declare function memberCompletions(overlay: TypeOverlay, node: BaseNode): readonly Completion[];
|
|
478
|
+
/**
|
|
479
|
+
* Completions de **escopo**: os nomes visíveis no contexto de `node` — params,
|
|
480
|
+
* `const`s já declaradas acima e as raízes injetadas pela DI. É o que pode
|
|
481
|
+
* preencher um slot de expressão livre nesse ponto. O mais interno sombreia o
|
|
482
|
+
* externo. Vazio se o nó não foi tipado.
|
|
483
|
+
*/
|
|
484
|
+
declare function scopeCompletions(overlay: TypeOverlay, node: BaseNode): readonly Completion[];
|
|
485
|
+
/** Os diagnósticos que apontam para `node`. */
|
|
486
|
+
declare function diagnosticsAt(diagnostics: readonly Diagnostic[], node: BaseNode): readonly Diagnostic[];
|
|
487
|
+
|
|
488
|
+
export { type AnySchema, type ApplySchema, type ArraySchema, type Bindings, type CheckOptions, type CheckResult, type Completion, type Diagnostic, type DiagnosticCode, type DiagnosticSink, type Discovery, type Env, FUNCTION_KINDS, type FnSchema, type Guard, type GuardContext, type Instantiation, type LiteralSchema, type ObjectSchema, type Param, type Profile, type Prop, type ScalarSchema, type Schema, type Schemes, type Scope, type Severity, type TypeOverlay, type TypeScheme, type UnionSchema, type UnknownSchema, type VarSchema, annotate, annotateReturn, calleeAllowlist, capabilityNodes, check, childScope, createEnv, createSink, diag, diagnosticsAt, discover, equals, expand1, format, fromCapability, groundVars, guard, guardsFromCompiled, instantiate, instantiateLoose, isScheme, isSerializable, join, joinAll, lookup, makeDiagnostic, maxArgs, maxCallNesting, maxDepth, maxFunctionNesting, maxNestingOf, maxNodes, memberCompletions, memberDepth, normalizeUnion, resolveNamed, resolveScheme, resultType, rootScope, s, scopeAt, scopeCompletions, substitute, subtype, typeAt, unify, visibleNames, withoutUndefined };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
import { Scope as Scope$1, BaseNode, Node } from '@tslite/core';
|
|
2
|
+
import { CapabilityProfile, CompiledProfile } from '@tslite/capability';
|
|
3
|
+
|
|
4
|
+
/** Uma propriedade de um tipo objeto. */
|
|
5
|
+
interface Prop {
|
|
6
|
+
readonly type: Schema;
|
|
7
|
+
/** `true` quando a propriedade pode estar ausente (`{ x?: T }`). */
|
|
8
|
+
readonly optional?: boolean;
|
|
9
|
+
}
|
|
10
|
+
/** Um parâmetro de um tipo função. */
|
|
11
|
+
interface Param {
|
|
12
|
+
readonly name: string;
|
|
13
|
+
readonly type: Schema;
|
|
14
|
+
/** `true` quando o argumento pode ser omitido. */
|
|
15
|
+
readonly optional?: boolean;
|
|
16
|
+
/** `true` para o parâmetro rest (`...args: T[]`). */
|
|
17
|
+
readonly variadic?: boolean;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Assinatura de **construção** de um tipo função (`new X(...)`). Separada da
|
|
21
|
+
* assinatura de chamada porque podem diferir (ex.: `Date()` → string, `new Date()`
|
|
22
|
+
* → Date). Só construtor **host** (DI) declara isso — a Linguagem não define
|
|
23
|
+
* construtores (D38).
|
|
24
|
+
*/
|
|
25
|
+
interface ConstructSig {
|
|
26
|
+
readonly params: readonly Param[];
|
|
27
|
+
readonly returns: Schema;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* O tipo de um valor na linguagem TSLite.
|
|
31
|
+
*
|
|
32
|
+
* O discriminador é `t`. Estruturas (object/array/union/fn) referenciam outros
|
|
33
|
+
* `Schema` recursivamente — inclusive de forma cíclica (ex.: `Node` que contém
|
|
34
|
+
* `Node[]`); as operações que percorrem `Schema` são cycle-safe.
|
|
35
|
+
*/
|
|
36
|
+
type Schema = {
|
|
37
|
+
readonly t: "any";
|
|
38
|
+
} | {
|
|
39
|
+
readonly t: "unknown";
|
|
40
|
+
} | {
|
|
41
|
+
readonly t: "string";
|
|
42
|
+
} | {
|
|
43
|
+
readonly t: "number";
|
|
44
|
+
} | {
|
|
45
|
+
readonly t: "boolean";
|
|
46
|
+
} | {
|
|
47
|
+
readonly t: "null";
|
|
48
|
+
} | {
|
|
49
|
+
readonly t: "undefined";
|
|
50
|
+
} | {
|
|
51
|
+
readonly t: "literal";
|
|
52
|
+
readonly value: string | number | boolean;
|
|
53
|
+
} | {
|
|
54
|
+
readonly t: "object";
|
|
55
|
+
readonly props: Readonly<Record<string, Prop>>;
|
|
56
|
+
} | {
|
|
57
|
+
readonly t: "array";
|
|
58
|
+
readonly items: Schema;
|
|
59
|
+
} | {
|
|
60
|
+
readonly t: "union";
|
|
61
|
+
readonly of: readonly Schema[];
|
|
62
|
+
} | {
|
|
63
|
+
readonly t: "fn";
|
|
64
|
+
readonly params: readonly Param[];
|
|
65
|
+
readonly returns: Schema;
|
|
66
|
+
/** Assinatura de `new X(...)` — presente só em construtor host (D38). */
|
|
67
|
+
readonly construct?: ConstructSig;
|
|
68
|
+
} | {
|
|
69
|
+
readonly t: "var";
|
|
70
|
+
readonly name: string;
|
|
71
|
+
} | {
|
|
72
|
+
readonly t: "apply";
|
|
73
|
+
readonly name: string;
|
|
74
|
+
readonly args: readonly Schema[];
|
|
75
|
+
};
|
|
76
|
+
type AnySchema = Extract<Schema, {
|
|
77
|
+
t: "any";
|
|
78
|
+
}>;
|
|
79
|
+
type UnknownSchema = Extract<Schema, {
|
|
80
|
+
t: "unknown";
|
|
81
|
+
}>;
|
|
82
|
+
type LiteralSchema = Extract<Schema, {
|
|
83
|
+
t: "literal";
|
|
84
|
+
}>;
|
|
85
|
+
type ObjectSchema = Extract<Schema, {
|
|
86
|
+
t: "object";
|
|
87
|
+
}>;
|
|
88
|
+
type ArraySchema = Extract<Schema, {
|
|
89
|
+
t: "array";
|
|
90
|
+
}>;
|
|
91
|
+
type UnionSchema = Extract<Schema, {
|
|
92
|
+
t: "union";
|
|
93
|
+
}>;
|
|
94
|
+
type FnSchema = Extract<Schema, {
|
|
95
|
+
t: "fn";
|
|
96
|
+
}>;
|
|
97
|
+
type VarSchema = Extract<Schema, {
|
|
98
|
+
t: "var";
|
|
99
|
+
}>;
|
|
100
|
+
type ApplySchema = Extract<Schema, {
|
|
101
|
+
t: "apply";
|
|
102
|
+
}>;
|
|
103
|
+
type ScalarSchema = Extract<Schema, {
|
|
104
|
+
t: "string" | "number" | "boolean" | "null" | "undefined";
|
|
105
|
+
}>;
|
|
106
|
+
declare const s: {
|
|
107
|
+
readonly any: Schema;
|
|
108
|
+
readonly unknown: Schema;
|
|
109
|
+
readonly string: Schema;
|
|
110
|
+
readonly number: Schema;
|
|
111
|
+
readonly boolean: Schema;
|
|
112
|
+
readonly null: Schema;
|
|
113
|
+
readonly undefined: Schema;
|
|
114
|
+
readonly literal: (value: string | number | boolean) => Schema;
|
|
115
|
+
readonly object: (props: Record<string, Prop>) => Schema;
|
|
116
|
+
readonly array: (items: Schema) => Schema;
|
|
117
|
+
readonly fn: (params: Param[], returns: Schema) => Schema;
|
|
118
|
+
/**
|
|
119
|
+
* Construtor host: `s.ctor(params, Instance)` → função **newável** que devolve
|
|
120
|
+
* `Instance` (tanto via `new` quanto via chamada, p/ simplicidade). O canal é a
|
|
121
|
+
* DI — a Linguagem instancia construtores host, não os define (D38).
|
|
122
|
+
*/
|
|
123
|
+
readonly ctor: (params: Param[], instance: Schema) => Schema;
|
|
124
|
+
readonly var: (name: string) => Schema;
|
|
125
|
+
/** Construtor de tipo aplicado: `apply("Map", [K, V])` ⇒ `Map<K, V>`. */
|
|
126
|
+
readonly apply: (name: string, args?: readonly Schema[]) => Schema;
|
|
127
|
+
/** Açúcar para `Promise<T>` — o que `await` desembrulha. */
|
|
128
|
+
readonly promise: (value: Schema) => Schema;
|
|
129
|
+
/**
|
|
130
|
+
* Constrói uma união achatando uniões aninhadas. Não deduplica nem colapsa
|
|
131
|
+
* união-de-um aqui (isso depende de igualdade estrutural — ver `normalizeUnion`
|
|
132
|
+
* quando `subtype` existir); apenas garante uma lista plana.
|
|
133
|
+
*/
|
|
134
|
+
readonly union: (of: readonly Schema[]) => Schema;
|
|
135
|
+
};
|
|
136
|
+
/**
|
|
137
|
+
* Separa `undefined` de um tipo: devolve o tipo **sem** `undefined` e se ele estava
|
|
138
|
+
* presente. Em posição de **propriedade**, `T | undefined` é uma propriedade
|
|
139
|
+
* **opcional** de tipo `T` — espelha o `JSON.stringify` (chave `undefined` some).
|
|
140
|
+
* Só mexe em `undefined`, nunca em `null` (que é valor JSON presente). Usado pelo
|
|
141
|
+
* `serializable` e pelo `toJsonSchema` (mesma regra dos dois lados).
|
|
142
|
+
*/
|
|
143
|
+
declare function withoutUndefined(t: Schema): {
|
|
144
|
+
type: Schema;
|
|
145
|
+
hadUndefined: boolean;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* `true` quando `schema` descreve **dado puro** (sobrevive a `JSON.stringify`
|
|
150
|
+
* sem perda silenciosa). `fn` é o ponto-chave: uma função é dropada em silêncio
|
|
151
|
+
* pela serialização — por isso `false`.
|
|
152
|
+
*
|
|
153
|
+
* `apply` é **conservador** (`false`): sem registro de construtores-de-dado
|
|
154
|
+
* liberados, não dá pra garantir que `Foo<…>` (ou `Promise<T>`, `Map<K,V>`)
|
|
155
|
+
* vire JSON. `var` (forma desconhecida), `any`/`unknown` (sem garantia) → `false`.
|
|
156
|
+
*/
|
|
157
|
+
declare function isSerializable(schema: Schema, seen?: WeakSet<object>): boolean;
|
|
158
|
+
|
|
159
|
+
/** Renderiza `schema` como uma string no estilo TypeScript. */
|
|
160
|
+
declare function format(schema: Schema, seen?: WeakSet<object>): string;
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Um *type scheme*: um tipo nomeado parametrizado, `type Pair<A, B> = body`.
|
|
164
|
+
* `params` são as variáveis de tipo (na ordem); `body` é o `Schema` que as usa
|
|
165
|
+
* via `var`. Um tipo nomeado não-genérico é só um scheme com `params: []`.
|
|
166
|
+
*/
|
|
167
|
+
interface TypeScheme {
|
|
168
|
+
readonly params: readonly string[];
|
|
169
|
+
readonly body: Schema;
|
|
170
|
+
}
|
|
171
|
+
/** Registro de type schemes por nome — consultado pela expansão (ver `expand`). */
|
|
172
|
+
type Schemes = Readonly<Record<string, TypeScheme>>;
|
|
173
|
+
/**
|
|
174
|
+
* Um nível de escopo léxico (nome → `Schema`), sobre o `Scope<T>` genérico do
|
|
175
|
+
* `core` — a mesma cadeia que o `analysis` usa, com o payload do eixo de tipos.
|
|
176
|
+
*/
|
|
177
|
+
type Scope = Scope$1<Schema>;
|
|
178
|
+
/** Cria um escopo raiz (sem pai). */
|
|
179
|
+
declare const rootScope: (vars?: Record<string, Schema>) => Scope;
|
|
180
|
+
/** Estende `parent` com novos bindings, criando um escopo filho. */
|
|
181
|
+
declare const childScope: (parent: Scope, vars: Record<string, Schema>) => Scope;
|
|
182
|
+
/** Resolve `name` subindo a cadeia léxica. `undefined` se não existir. */
|
|
183
|
+
declare const lookup: (scope: Scope, name: string) => Schema | undefined;
|
|
184
|
+
/**
|
|
185
|
+
* Todos os nomes visíveis a partir de `scope`, com shadowing — o binding mais
|
|
186
|
+
* interno vence. É o que alimenta o autocomplete de identificadores.
|
|
187
|
+
*/
|
|
188
|
+
declare const visibleNames: (scope: Scope) => Map<string, Schema>;
|
|
189
|
+
/**
|
|
190
|
+
* O ambiente injetado pela aplicação — a fronteira de tipos do sistema.
|
|
191
|
+
* `scope` é a raiz da DI; `types` resolve tipos nomeados em anotações.
|
|
192
|
+
*/
|
|
193
|
+
/**
|
|
194
|
+
* O ambiente é **só tipos** (a fronteira da DI). Capability — o que pode ser
|
|
195
|
+
* programado — é ortogonal e mora no `CapabilityProfile` (`@tslite/capability`),
|
|
196
|
+
* passado ao `check` por `{ profile }`. Não há mais noção de capability no Env.
|
|
197
|
+
*/
|
|
198
|
+
interface Env {
|
|
199
|
+
readonly scope: Scope;
|
|
200
|
+
readonly types: Readonly<Record<string, Schema>>;
|
|
201
|
+
/** Type schemes parametrizados (`type Pair<A, B> = …`), expandidos sob demanda. */
|
|
202
|
+
readonly schemes: Schemes;
|
|
203
|
+
/**
|
|
204
|
+
* Acessores **indexados por path literal**: nome → schema-base que ele navega.
|
|
205
|
+
* Ex.: `get` sobre o schema dos States → `get("hp","value")` tipa como
|
|
206
|
+
* `discover(base, ["hp","value"])`. É como a fronteira tipa leituras de estado
|
|
207
|
+
* sem `unknown` (o app declara o shape; o checker indexa). Default: nenhum.
|
|
208
|
+
*/
|
|
209
|
+
readonly accessors?: Readonly<Record<string, Schema>>;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Cria um `Env` a partir das variáveis injetadas, dos tipos nomeados, dos type
|
|
213
|
+
* schemes e dos acessores. Capability é separada (passe um `profile` ao `check`).
|
|
214
|
+
*/
|
|
215
|
+
declare const createEnv: (vars?: Record<string, Schema>, types?: Record<string, Schema>, schemes?: Record<string, TypeScheme>, accessors?: Record<string, Schema>) => Env;
|
|
216
|
+
/** Resolve um tipo nomeado (`type User = …`) declarado no ambiente. */
|
|
217
|
+
declare const resolveNamed: (env: Env, name: string) => Schema | undefined;
|
|
218
|
+
/** Resolve um type scheme (`type Pair<A, B> = …`) declarado no ambiente. */
|
|
219
|
+
declare const resolveScheme: (env: Env, name: string) => TypeScheme | undefined;
|
|
220
|
+
|
|
221
|
+
/** `true` se um valor de tipo `a` pode ser usado onde se espera `b`. */
|
|
222
|
+
declare function subtype(a: Schema, b: Schema, schemes?: Schemes): boolean;
|
|
223
|
+
/** Igualdade estrutural: cada um é atribuível ao outro. */
|
|
224
|
+
declare function equals(a: Schema, b: Schema, schemes?: Schemes): boolean;
|
|
225
|
+
/**
|
|
226
|
+
* Normaliza uma união: achata, absorve `any`/`unknown`, deduplica e remove
|
|
227
|
+
* membros subsumidos por outro (`string | "x"` → `string`). Colapsa união de um
|
|
228
|
+
* membro no próprio membro. União vazia permanece vazia (renderiza `never`).
|
|
229
|
+
*/
|
|
230
|
+
declare function normalizeUnion(members: readonly Schema[]): Schema;
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* O supremo estrutural de `a` e `b`: o menor `Schema` ao qual ambos são
|
|
234
|
+
* atribuíveis. `unknown` é a unidade (sem-evidência); `any` é absorvente.
|
|
235
|
+
*/
|
|
236
|
+
declare function join(a: Schema, b: Schema): Schema;
|
|
237
|
+
/**
|
|
238
|
+
* Dobra uma lista de formas no seu supremo comum. Lista vazia → `never` (⊥, a
|
|
239
|
+
* identidade do supremo). Um membro → ele mesmo. É a operação do schema-reducer:
|
|
240
|
+
* `joinAll(amostras.map(inferValue))` descreve todas as amostras.
|
|
241
|
+
*/
|
|
242
|
+
declare function joinAll(members: readonly Schema[]): Schema;
|
|
243
|
+
|
|
244
|
+
/** Um membro que pode seguir a partir de um tipo (item de autocomplete). */
|
|
245
|
+
interface Completion {
|
|
246
|
+
/** Nome da propriedade, ou `"[]"` para o elemento de um array. */
|
|
247
|
+
readonly key: string;
|
|
248
|
+
readonly type: Schema;
|
|
249
|
+
readonly optional: boolean;
|
|
250
|
+
}
|
|
251
|
+
/** Resultado de navegar um path: o tipo final + o que pode seguir dele. */
|
|
252
|
+
interface Discovery {
|
|
253
|
+
readonly type: Schema;
|
|
254
|
+
readonly completions: readonly Completion[];
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Navega `path` a partir de `schema`. Retorna o tipo alcançado e suas
|
|
258
|
+
* completions, ou `null` se algum segmento não existir no tipo. Path vazio
|
|
259
|
+
* devolve o próprio tipo e suas completions.
|
|
260
|
+
*/
|
|
261
|
+
declare function discover(schema: Schema, path: readonly string[], schemes?: Schemes): Discovery | null;
|
|
262
|
+
|
|
263
|
+
/** Ligações `nome da var → tipo` (o resultado de `unify`/aplicação de scheme). */
|
|
264
|
+
type Bindings = Readonly<Record<string, Schema>>;
|
|
265
|
+
/** Aplica `bindings` a `schema`, trocando cada `var` ligada pelo seu tipo. */
|
|
266
|
+
declare function substitute(schema: Schema, bindings: Bindings, seen?: WeakSet<object>): Schema;
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Liga as `var`s de `pattern` aos tipos correspondentes em `actual`. Devolve as
|
|
270
|
+
* ligações estendidas, ou `null` se forem incompatíveis. `actual` que seja
|
|
271
|
+
* `any`/`unknown` não constrange vars (deixa-as livres).
|
|
272
|
+
*/
|
|
273
|
+
declare function unify(pattern: Schema, actual: Schema, bindings?: Bindings): Bindings | null;
|
|
274
|
+
/** Resultado de instanciar uma assinatura contra argumentos. */
|
|
275
|
+
interface Instantiation {
|
|
276
|
+
readonly returns: Schema;
|
|
277
|
+
readonly bindings: Bindings;
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Instancia uma função genérica: unifica cada argumento contra o parâmetro
|
|
281
|
+
* correspondente (ligando as `var`s) e devolve o retorno já substituído.
|
|
282
|
+
* Falha (`null`) se algum argumento não unificar. Um parâmetro `variadic`
|
|
283
|
+
* absorve os argumentos restantes (cada um unifica contra o tipo do rest).
|
|
284
|
+
*/
|
|
285
|
+
declare function instantiate(sig: FnSchema, args: readonly Schema[]): Instantiation | null;
|
|
286
|
+
/**
|
|
287
|
+
* Versão tolerante de {@link instantiate} para o editor/checker: nunca falha —
|
|
288
|
+
* argumentos que não unificam são ignorados, e `var`s não ligadas permanecem
|
|
289
|
+
* (útil para aplicação parcial e enquanto o usuário ainda digita).
|
|
290
|
+
*/
|
|
291
|
+
declare function instantiateLoose(sig: FnSchema, args: readonly Schema[]): Instantiation;
|
|
292
|
+
/** Aterra as `var`s remanescentes em `unknown` (para exibição do resultado). */
|
|
293
|
+
declare function groundVars(schema: Schema, seen?: WeakSet<object>): Schema;
|
|
294
|
+
|
|
295
|
+
/** Há um scheme registrado para este `apply` (com aridade compatível)? */
|
|
296
|
+
declare function isScheme(t: Schema, schemes: Schemes): boolean;
|
|
297
|
+
/**
|
|
298
|
+
* Expande **um nível**: `apply(name, args)` com scheme registrado vira
|
|
299
|
+
* `substitute(body, { param_i → args_i })`. Qualquer outro tipo (ou `apply` opaco)
|
|
300
|
+
* é devolvido intacto.
|
|
301
|
+
*/
|
|
302
|
+
declare function expand1(t: Schema, schemes: Schemes): Schema;
|
|
303
|
+
|
|
304
|
+
type Severity = "error" | "warning";
|
|
305
|
+
type DiagnosticCode = "not-assignable" | "unknown-name" | "not-callable" | "not-newable" | "no-such-member" | "not-object" | "const-needs-init" | "missing-argument" | "unsupported" | "cast-unsound" | "node-not-allowed" | "name-not-allowed" | "too-deep" | "too-large" | "wrong-result-type";
|
|
306
|
+
interface Diagnostic {
|
|
307
|
+
readonly code: DiagnosticCode;
|
|
308
|
+
readonly severity: Severity;
|
|
309
|
+
/** O nó culpado — identidade por referência. */
|
|
310
|
+
readonly node: BaseNode;
|
|
311
|
+
readonly message: string;
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Builder genérico de diagnóstico (severidade configurável). Usado pelos
|
|
315
|
+
* guardrails, que têm seu próprio catálogo de mensagens em `guard`.
|
|
316
|
+
*/
|
|
317
|
+
declare const makeDiagnostic: (code: DiagnosticCode, node: BaseNode, message: string, severity?: Severity) => Diagnostic;
|
|
318
|
+
/**
|
|
319
|
+
* Fábricas de diagnósticos. Mensagens no estilo do tsc, com tipos renderizados
|
|
320
|
+
* por `format`.
|
|
321
|
+
*/
|
|
322
|
+
declare const diag: {
|
|
323
|
+
notAssignable: (node: BaseNode, actual: Schema, expected: Schema) => Diagnostic;
|
|
324
|
+
unknownName: (node: BaseNode, name: string) => Diagnostic;
|
|
325
|
+
notCallable: (node: BaseNode, type: Schema) => Diagnostic;
|
|
326
|
+
notNewable: (node: BaseNode, type: Schema) => Diagnostic;
|
|
327
|
+
noSuchMember: (node: BaseNode, type: Schema, key: string) => Diagnostic;
|
|
328
|
+
notObject: (node: BaseNode, type: Schema) => Diagnostic;
|
|
329
|
+
constNeedsInit: (node: BaseNode) => Diagnostic;
|
|
330
|
+
missingArgument: (node: BaseNode, name: string, expected: Schema) => Diagnostic;
|
|
331
|
+
unsupported: (node: BaseNode, what: string) => Diagnostic;
|
|
332
|
+
/**
|
|
333
|
+
* Cast (`x as T`) entre tipos que não se sobrepõem em nenhum sentido. Warning
|
|
334
|
+
* (não erro): o cast é um escape-hatch explícito — `unknown`/`any` passam
|
|
335
|
+
* silenciosos; só o cast "torto" (ex.: `number as string`) avisa.
|
|
336
|
+
*/
|
|
337
|
+
castUnsound: (node: BaseNode, from: Schema, to: Schema) => Diagnostic;
|
|
338
|
+
};
|
|
339
|
+
/** Coletor de diagnósticos — acumula durante o walk, sem `throw`. */
|
|
340
|
+
interface DiagnosticSink {
|
|
341
|
+
/** Diagnósticos coletados, na ordem em que foram reportados. */
|
|
342
|
+
readonly all: readonly Diagnostic[];
|
|
343
|
+
report(d: Diagnostic): void;
|
|
344
|
+
/** `true` se há ao menos um diagnóstico de severidade `error`. */
|
|
345
|
+
hasErrors(): boolean;
|
|
346
|
+
}
|
|
347
|
+
/** Cria um coletor vazio. */
|
|
348
|
+
declare function createSink(): DiagnosticSink;
|
|
349
|
+
|
|
350
|
+
/** O overlay de tipos: tipo + escopo de cada nó, por referência (ESTree não tem id). */
|
|
351
|
+
type TypeOverlay = WeakMap<BaseNode, {
|
|
352
|
+
readonly type: Schema;
|
|
353
|
+
readonly scope: Scope;
|
|
354
|
+
}>;
|
|
355
|
+
interface CheckResult {
|
|
356
|
+
/** Tipo do nó raiz. */
|
|
357
|
+
readonly type: Schema;
|
|
358
|
+
readonly overlay: TypeOverlay;
|
|
359
|
+
readonly diagnostics: readonly Diagnostic[];
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Tipa `node` no ambiente `env` (a borda da DI: data, states, funções globais).
|
|
363
|
+
* Nunca lança; devolve o overlay e os diagnósticos coletados.
|
|
364
|
+
*/
|
|
365
|
+
/** Opções do `check`. */
|
|
366
|
+
interface CheckOptions {
|
|
367
|
+
/**
|
|
368
|
+
* Capability profile a enforçar. Quando dado, o `check` roda o guard de capability
|
|
369
|
+
* (`fromCapability`) além do type-checking e funde os diagnósticos (`node-not-allowed`).
|
|
370
|
+
* Sem ele, `check` faz **só type-checking** (sem opinar sobre capability).
|
|
371
|
+
*
|
|
372
|
+
* Capability **desinstala** features (o que pode existir em runtime — junto do
|
|
373
|
+
* interpret/printer); é ortogonal aos `limits`/`resultType` abaixo, que **validam**.
|
|
374
|
+
*/
|
|
375
|
+
readonly profile?: CapabilityProfile;
|
|
376
|
+
/**
|
|
377
|
+
* Limites estruturais (anti-DoS) — validações do checker, cada uma opt-in.
|
|
378
|
+
* Reportam `too-deep`/`too-large`.
|
|
379
|
+
*/
|
|
380
|
+
readonly limits?: {
|
|
381
|
+
/** Profundidade total de aninhamento do AST (qualquer nó). */
|
|
382
|
+
readonly maxDepth?: number;
|
|
383
|
+
/** Número total de nós (custo/complexidade). */
|
|
384
|
+
readonly maxNodes?: number;
|
|
385
|
+
/** Argumentos por chamada. */
|
|
386
|
+
readonly maxArgs?: number;
|
|
387
|
+
/** Aninhamento de funções (função-dentro-de-função). */
|
|
388
|
+
readonly maxFunctionNesting?: number;
|
|
389
|
+
/** Aninhamento de chamadas (`f(g(h(x)))`). */
|
|
390
|
+
readonly maxCallNesting?: number;
|
|
391
|
+
/** Profundidade de cadeia de membros (`a.b.c.d`). */
|
|
392
|
+
readonly memberDepth?: number;
|
|
393
|
+
};
|
|
394
|
+
/**
|
|
395
|
+
* Contrato de tipo de retorno: o tipo da expressão-raiz deve ser atribuível a
|
|
396
|
+
* `resultType`. Reporta `wrong-result-type`. (Ex.: uma condition deve ser `boolean`.)
|
|
397
|
+
*/
|
|
398
|
+
readonly resultType?: Schema;
|
|
399
|
+
}
|
|
400
|
+
declare function check(node: Node, env: Env, opts?: CheckOptions): CheckResult;
|
|
401
|
+
|
|
402
|
+
/** Contexto opcional de um guard (o overlay de tipos, p/ regras type-aware). */
|
|
403
|
+
interface GuardContext {
|
|
404
|
+
readonly overlay?: TypeOverlay;
|
|
405
|
+
}
|
|
406
|
+
/** Um guard: percorre `root` e devolve os diagnósticos que encontrar. */
|
|
407
|
+
type Guard = (root: BaseNode, ctx: GuardContext) => Diagnostic[];
|
|
408
|
+
/** Um profile é uma composição de guards. */
|
|
409
|
+
type Profile = readonly Guard[];
|
|
410
|
+
/** Roda um profile sobre `root`, concatenando todos os diagnósticos. */
|
|
411
|
+
declare function guard(root: BaseNode, profile: Profile, ctx?: GuardContext): Diagnostic[];
|
|
412
|
+
/** Os kinds que **definem** uma função. */
|
|
413
|
+
declare const FUNCTION_KINDS: readonly ["ArrowFunctionExpression", "FunctionExpression", "FunctionDeclaration"];
|
|
414
|
+
/**
|
|
415
|
+
* O guard de **capability**: percorre `root` e reporta `node-not-allowed` em todo
|
|
416
|
+
* nó proibido por `compiled` — via `nodeViolation`, a **fonte única** de gating
|
|
417
|
+
* compartilhada com o interpret e o printer. É o que `fromCapability` monta (+ o
|
|
418
|
+
* host allowlist). Garante que os 3 consumidores concordam por construção.
|
|
419
|
+
*/
|
|
420
|
+
declare function capabilityNodes(compiled: CompiledProfile, severity?: Severity): Guard;
|
|
421
|
+
/**
|
|
422
|
+
* O callee de toda chamada deve ser um identificador direto ∈ `names`. É o gate
|
|
423
|
+
* do **host** (a família `host.allow` do `CapabilityProfile`): só as funções
|
|
424
|
+
* liberadas pela DI podem ser chamadas. Montado por `fromCapability`.
|
|
425
|
+
*/
|
|
426
|
+
declare function calleeAllowlist(names: readonly string[], severity?: Severity): Guard;
|
|
427
|
+
/**
|
|
428
|
+
* Limita o **aninhamento de um kind** ao longo de qualquer caminho raiz→folha.
|
|
429
|
+
* Ex.: `maxNestingOf(FUNCTION_KINDS, 3)` barra a 4ª função aninhada.
|
|
430
|
+
*/
|
|
431
|
+
declare function maxNestingOf(kinds: string | readonly string[], max: number, opts?: {
|
|
432
|
+
hint?: string;
|
|
433
|
+
severity?: Severity;
|
|
434
|
+
}): Guard;
|
|
435
|
+
/** Aninhamento de funções (função-dentro-de-função). Padrão: 3 → use um pipe. */
|
|
436
|
+
declare const maxFunctionNesting: (max?: number, severity?: Severity) => Guard;
|
|
437
|
+
/** Aninhamento de chamadas (`f(g(h(x)))`). */
|
|
438
|
+
declare const maxCallNesting: (max: number, severity?: Severity) => Guard;
|
|
439
|
+
/** Profundidade de cadeia de membros (`a.b.c.d`). */
|
|
440
|
+
declare const memberDepth: (max: number, severity?: Severity) => Guard;
|
|
441
|
+
/** Profundidade total de aninhamento do AST (qualquer nó). */
|
|
442
|
+
declare function maxDepth(max: number, severity?: Severity): Guard;
|
|
443
|
+
/** Número total de nós (custo/complexidade). */
|
|
444
|
+
declare function maxNodes(max: number, severity?: Severity): Guard;
|
|
445
|
+
/** Número máximo de argumentos por chamada. */
|
|
446
|
+
declare function maxArgs(max: number, severity?: Severity): Guard;
|
|
447
|
+
/** O tipo da expressão-raiz deve ser atribuível a `expected`. */
|
|
448
|
+
declare function resultType(expected: Schema, schemes?: Schemes, severity?: Severity): Guard;
|
|
449
|
+
|
|
450
|
+
/** Traduz um `CompiledProfile` (já compilado) num `Profile` de guards. */
|
|
451
|
+
declare function guardsFromCompiled(c: CompiledProfile): Profile;
|
|
452
|
+
/**
|
|
453
|
+
* Compila um `CapabilityProfile` e o traduz num `Profile` de guards. Use com
|
|
454
|
+
* `guard(ast, fromCapability(PRESETS.predicate))`. Assume um profile válido
|
|
455
|
+
* (rode `validateProfile` antes p/ pegar combinações ilegais).
|
|
456
|
+
*/
|
|
457
|
+
declare function fromCapability(profile: CapabilityProfile): Profile;
|
|
458
|
+
|
|
459
|
+
/** Anota uma ligação/parâmetro: `x` → `x: T`. */
|
|
460
|
+
declare const annotate: <N extends BaseNode>(node: N, type: Schema) => N & {
|
|
461
|
+
typeAnnotation: Schema;
|
|
462
|
+
};
|
|
463
|
+
/** Anota o retorno de uma função: `() => …` → `(): R => …`. */
|
|
464
|
+
declare const annotateReturn: <N extends BaseNode>(fn: N, type: Schema) => N & {
|
|
465
|
+
returnType: Schema;
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
/** O tipo inferido de `node`, ou `undefined` se o nó não foi tipado. */
|
|
469
|
+
declare function typeAt(overlay: TypeOverlay, node: BaseNode): Schema | undefined;
|
|
470
|
+
/** O escopo léxico vigente em `node`, ou `undefined` se o nó não foi tipado. */
|
|
471
|
+
declare function scopeAt(overlay: TypeOverlay, node: BaseNode): Scope | undefined;
|
|
472
|
+
/**
|
|
473
|
+
* Completions de **membro**: o que pode seguir a partir do tipo de `node`
|
|
474
|
+
* (ex.: após `obj.` → as props de `obj`; após um array → `[]`). Vazio se o nó
|
|
475
|
+
* não foi tipado ou se o tipo não tem membros navegáveis.
|
|
476
|
+
*/
|
|
477
|
+
declare function memberCompletions(overlay: TypeOverlay, node: BaseNode): readonly Completion[];
|
|
478
|
+
/**
|
|
479
|
+
* Completions de **escopo**: os nomes visíveis no contexto de `node` — params,
|
|
480
|
+
* `const`s já declaradas acima e as raízes injetadas pela DI. É o que pode
|
|
481
|
+
* preencher um slot de expressão livre nesse ponto. O mais interno sombreia o
|
|
482
|
+
* externo. Vazio se o nó não foi tipado.
|
|
483
|
+
*/
|
|
484
|
+
declare function scopeCompletions(overlay: TypeOverlay, node: BaseNode): readonly Completion[];
|
|
485
|
+
/** Os diagnósticos que apontam para `node`. */
|
|
486
|
+
declare function diagnosticsAt(diagnostics: readonly Diagnostic[], node: BaseNode): readonly Diagnostic[];
|
|
487
|
+
|
|
488
|
+
export { type AnySchema, type ApplySchema, type ArraySchema, type Bindings, type CheckOptions, type CheckResult, type Completion, type Diagnostic, type DiagnosticCode, type DiagnosticSink, type Discovery, type Env, FUNCTION_KINDS, type FnSchema, type Guard, type GuardContext, type Instantiation, type LiteralSchema, type ObjectSchema, type Param, type Profile, type Prop, type ScalarSchema, type Schema, type Schemes, type Scope, type Severity, type TypeOverlay, type TypeScheme, type UnionSchema, type UnknownSchema, type VarSchema, annotate, annotateReturn, calleeAllowlist, capabilityNodes, check, childScope, createEnv, createSink, diag, diagnosticsAt, discover, equals, expand1, format, fromCapability, groundVars, guard, guardsFromCompiled, instantiate, instantiateLoose, isScheme, isSerializable, join, joinAll, lookup, makeDiagnostic, maxArgs, maxCallNesting, maxDepth, maxFunctionNesting, maxNestingOf, maxNodes, memberCompletions, memberDepth, normalizeUnion, resolveNamed, resolveScheme, resultType, rootScope, s, scopeAt, scopeCompletions, substitute, subtype, typeAt, unify, visibleNames, withoutUndefined };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {rootScope,childScope,lookup,visibleNames,walk,AST_MARKER,childrenOf}from'@tslite/core';import {compileProfile,nodeViolation}from'@tslite/capability';import {fromJson}from'@tslite/codec';var R=e=>Object.freeze(e),i={any:R({t:"any"}),unknown:R({t:"unknown"}),string:R({t:"string"}),number:R({t:"number"}),boolean:R({t:"boolean"}),null:R({t:"null"}),undefined:R({t:"undefined"}),literal:e=>({t:"literal",value:e}),object:e=>({t:"object",props:e}),array:e=>({t:"array",items:e}),fn:(e,n)=>({t:"fn",params:e,returns:n}),ctor:(e,n)=>({t:"fn",params:e,returns:n,construct:{params:e,returns:n}}),var:e=>({t:"var",name:e}),apply:(e,n=[])=>({t:"apply",name:e,args:n}),promise:e=>({t:"apply",name:"Promise",args:[e]}),union:e=>{let n=[];for(let t of e)t.t==="union"?n.push(...t.of):n.push(t);return {t:"union",of:n}}};function q(e){if(e.t==="undefined")return {type:{t:"union",of:[]},hadUndefined:true};if(e.t==="union"&&e.of.some(n=>n.t==="undefined")){let n=e.of.filter(t=>t.t!=="undefined");return {type:n.length===1?n[0]:{t:"union",of:n},hadUndefined:true}}return {type:e,hadUndefined:false}}function z(e,n=new WeakSet){switch(e.t){case "string":case "number":case "boolean":case "null":case "literal":return true;case "array":return n.has(e)?true:(n.add(e),z(q(e.items).type,n));case "object":return n.has(e)?true:(n.add(e),Object.values(e.props).every(t=>z(q(t.type).type,n)));case "union":return n.has(e)?true:(n.add(e),e.of.every(t=>z(t,n)));case "undefined":case "fn":case "var":case "apply":case "any":case "unknown":return false}}var _e=e=>/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e);function b(e,n=new WeakSet){switch(e.t){case "any":case "unknown":case "string":case "number":case "boolean":case "null":case "undefined":return e.t;case "var":return e.name;case "literal":return typeof e.value=="string"?JSON.stringify(e.value):String(e.value);case "array":{let t=b(e.items,n);return Je(e.items)?`(${t})[]`:`${t}[]`}case "union":{if(n.has(e))return "\u2026";n.add(e);let t=e.of.length===0?"never":e.of.map(r=>b(r,n)).join(" | ");return n.delete(e),t}case "object":{if(n.has(e))return "\u2026";n.add(e);let t=Object.entries(e.props),r=t.map(([a,o])=>`${_e(a)?a:JSON.stringify(a)}${o.optional?"?":""}: ${b(o.type,n)}`).join("; ");return n.delete(e),t.length===0?"{}":`{ ${r} }`}case "fn":{if(n.has(e))return "\u2026";n.add(e);let t=e.params.map(a=>{let o=a.variadic?"...":"",s=a.optional&&!a.variadic?"?":"";return `${o}${a.name}${s}: ${b(a.type,n)}`}).join(", "),r=b(e.returns,n);return n.delete(e),`(${t}) => ${r}`}case "apply":{if(n.has(e))return "\u2026";n.add(e);let t=e.args.length===0?e.name:`${e.name}<${e.args.map(r=>b(r,n)).join(", ")}>`;return n.delete(e),t}}}function Je(e){return e.t==="union"&&e.of.length>0||e.t==="fn"}function N(e,n,t=new WeakSet){switch(e.t){case "var":return n[e.name]??e;case "array":return {t:"array",items:N(e.items,n,t)};case "union":return {t:"union",of:e.of.map(r=>N(r,n,t))};case "object":{if(t.has(e))return e;t.add(e);let r={};for(let a in e.props){let o=e.props[a];r[a]={type:N(o.type,n,t),optional:o.optional};}return t.delete(e),{t:"object",props:r}}case "fn":{if(t.has(e))return e;t.add(e);let a={t:"fn",params:e.params.map(o=>({...o,type:N(o.type,n,t)})),returns:N(e.returns,n,t)};return t.delete(e),a}case "apply":return {t:"apply",name:e.name,args:e.args.map(r=>N(r,n,t))};default:return e}}function O(e,n){if(e.t!=="apply")return false;let t=n[e.name];return t!==void 0&&t.params.length===e.args.length}function A(e,n){if(e.t!=="apply")return e;let t=n[e.name];if(!t||t.params.length!==e.args.length)return e;let r={};return t.params.forEach((a,o)=>r[a]=e.args[o]),N(t.body,r)}function B(e){switch(e.t){case "literal":return `#${typeof e.value}:${String(e.value)}`;case "object":return `{${Object.keys(e.props).sort().map(n=>`${n}${e.props[n].optional?"?":""}:${B(e.props[n].type)}`).join(",")}}`;case "array":return `[${B(e.items)}]`;case "union":return `(${e.of.map(B).sort().join("|")})`;case "fn":return `(${e.params.map(n=>B(n.type)).join(",")})=>${B(e.returns)}`;case "var":return `v:${e.name}`;case "apply":return `${e.name}<${e.args.map(B).join(",")}>`;default:return e.t}}function S(e,n,t={}){return T(e,n,{seen:new WeakMap,exp:new Set,schemes:t})}function Q(e,n,t={}){return S(e,n,t)&&S(n,e,t)}function T(e,n,t){if(e.t==="any"||n.t==="any"||n.t==="unknown")return true;if(e.t==="unknown")return false;if(!(e.t==="apply"&&n.t==="apply"&&e.name===n.name&&e.args.length===n.args.length)&&(O(e,t.schemes)||O(n,t.schemes))){let o=`${B(e)}\u2264${B(n)}`;if(t.exp.has(o))return true;t.exp.add(o);let s=T(A(e,t.schemes),A(n,t.schemes),t);return t.exp.delete(o),s}let a=t.seen.get(e);if(a?.has(n))return true;if(a||(a=new WeakSet,t.seen.set(e,a)),a.add(n),e.t==="union")return e.of.every(o=>T(o,n,t));if(n.t==="union")return n.of.some(o=>T(e,o,t));switch(n.t){case "literal":return e.t==="literal"&&e.value===n.value;case "string":case "number":case "boolean":case "null":case "undefined":return e.t===n.t?true:e.t==="literal"&&He(e.value)===n.t;case "array":return e.t==="array"&&T(e.items,n.items,t);case "object":return e.t==="object"&&Ze(e,n,t);case "fn":return e.t==="fn"&&Ye(e,n,t);case "var":return e.t==="var"&&e.name===n.name;case "apply":return e.t==="apply"&&e.name===n.name&&e.args.length===n.args.length&&e.args.every((o,s)=>T(o,n.args[s],t))}}var He=e=>typeof e;function Ze(e,n,t){for(let r in n.props){let a=n.props[r],o=e.props[r];if(!o){if(!a.optional)return false;continue}if(o.optional&&!a.optional||!T(o.type,a.type,t))return false}return true}function Ye(e,n,t){if(!T(e.returns,n.returns,t))return false;for(let r=0;r<e.params.length;r++){let a=e.params[r];if(a.variadic)break;let o=n.params[r];if(!o){if(a.optional)continue;return false}if(!T(o.type,a.type,t))return false}return true}function k(e){let n=[];for(let r of e)r.t==="union"?n.push(...r.of):n.push(r);if(n.some(r=>r.t==="any"))return i.any;let t=[];for(let r of n)if(!t.some(a=>S(r,a))){for(let a=t.length-1;a>=0;a--)S(t[a],r)&&t.splice(a,1);t.push(r);}return t.length===1?t[0]:{t:"union",of:t}}var Qe=i.union([]);function Te(e,n){return X(e,n,new WeakMap)}function Xe(e){return e.reduce(Te,Qe)}function X(e,n,t){if(e.t==="any"||n.t==="any")return i.any;if(e===n)return e;let r=t.get(e)?.get(n);if(r)return r;if(e.t==="object"&&n.t==="object")return en(e,n,t);if(e.t==="array"&&n.t==="array"){let a={t:"array",items:i.unknown};return xe(t,e,n,a),a.items=X(e.items,n.items,t),a}return k([e,n])}function en(e,n,t){let r={t:"object",props:{}};xe(t,e,n,r);for(let a in e.props){let o=e.props[a],s=n.props[a];if(s){let l=X(o.type,s.type,t);r.props[a]=o.optional||s.optional?{type:l,optional:true}:{type:l};}else r.props[a]={type:o.type,optional:true};}for(let a in n.props)a in e.props||(r.props[a]={type:n.props[a].type,optional:true});return r}function xe(e,n,t,r){let a=e.get(n);a||(a=new WeakMap,e.set(n,a)),a.set(t,r);}function F(e,n,t={}){let r=e;for(let a of n){let o=ee(r,a,t);if(o===null)return null;r=o;}return {type:r,completions:ne(r,t)}}var nn=e=>e==="[]"||/^\d+$/.test(e);function ee(e,n,t,r=new Set){if(O(e,t)){let a=B(e);if(r.has(a))return null;r.add(a);let o=ee(A(e,t),n,t,r);return r.delete(a),o}switch(e.t){case "any":return e;case "object":return e.props[n]?.type??null;case "array":return nn(n)?e.items:null;case "union":{let a=e.of.map(o=>ee(o,n,t,r)).filter(o=>o!==null);return a.length?k(a):null}default:return null}}function ne(e,n,t=new WeakSet,r=new Set){if(O(e,n)){let a=B(e);if(r.has(a))return [];r.add(a);let o=ne(A(e,n),n,t,r);return r.delete(a),o}switch(e.t){case "object":return Object.entries(e.props).map(([a,o])=>({key:a,type:o.type,optional:!!o.optional}));case "array":return [{key:"[]",type:e.items,optional:false}];case "union":{if(t.has(e))return [];t.add(e);let a=[],o=new Set;for(let s of e.of)for(let l of ne(s,n,t,r))o.has(l.key)||(o.add(l.key),a.push(l));return t.delete(e),a}default:return []}}function x(e,n,t={}){if(e.t==="var"){let r=t[e.name];return r?S(n,r)||S(r,n)?t:null:{...t,[e.name]:n}}if(n.t==="any"||n.t==="unknown")return t;switch(e.t){case "array":return n.t==="array"?x(e.items,n.items,t):null;case "object":{if(n.t!=="object")return null;let r=t;for(let a in e.props){let o=e.props[a],s=n.props[a];if(!s){if(o.optional)continue;return null}if(r=x(o.type,s.type,r),r===null)return null}return r}case "fn":{if(n.t!=="fn")return null;let r=x(e.returns,n.returns,t);if(r===null)return null;let a=Math.min(e.params.length,n.params.length);for(let o=0;o<a;o++)if(r=x(e.params[o].type,n.params[o].type,r),r===null)return null;return r}case "apply":{if(n.t!=="apply"||n.name!==e.name||n.args.length!==e.args.length)return null;let r=t;for(let a=0;a<e.args.length;a++)if(r=x(e.args[a],n.args[a],r),r===null)return null;return r}default:return S(n,e)?t:null}}function tn(e,n){let t={};for(let r=0;r<e.params.length;r++){let a=e.params[r];if(a.variadic){for(let o=r;o<n.length;o++)if(t=x(a.type,n[o],t),t===null)return null;break}if(r>=n.length){if(a.optional)continue;return null}if(t=x(a.type,n[r],t),t===null)return null}return {returns:N(e.returns,t),bindings:t}}function V(e,n){let t={};for(let r=0;r<e.params.length&&r<n.length;r++){let a=e.params[r],o=x(a.type,n[r],t);o!==null&&(t=o);}return {returns:N(e.returns,t),bindings:t}}function C(e,n=new WeakSet){switch(e.t){case "var":return i.unknown;case "array":return {t:"array",items:C(e.items,n)};case "union":return {t:"union",of:e.of.map(t=>C(t,n))};case "object":{if(n.has(e))return e;n.add(e);let t={};for(let r in e.props){let a=e.props[r];t[r]={type:C(a.type,n),optional:a.optional};}return n.delete(e),{t:"object",props:t}}case "fn":{if(n.has(e))return e;n.add(e);let r={t:"fn",params:e.params.map(a=>({...a,type:C(a.type,n)})),returns:C(e.returns,n)};return n.delete(e),r}case "apply":return {t:"apply",name:e.name,args:e.args.map(t=>C(t,n))};default:return e}}var je=(e={})=>rootScope(e),j=(e,n)=>childScope(e,n),P=(e,n)=>lookup(e,n),te=e=>visibleNames(e),ln=(e={},n={},t={},r={})=>({scope:je(e),types:n,schemes:t,accessors:r}),un=(e,n)=>e.types[n],pn=(e,n)=>e.schemes[n];var D=(e,n,t)=>({code:e,severity:"error",node:n,message:t}),E=(e,n,t,r="error")=>({code:e,severity:r,node:n,message:t}),h={notAssignable:(e,n,t)=>D("not-assignable",e,`Type '${b(n)}' is not assignable to type '${b(t)}'.`),unknownName:(e,n)=>D("unknown-name",e,`Cannot find name '${n}'.`),notCallable:(e,n)=>D("not-callable",e,`Type '${b(n)}' is not callable.`),notNewable:(e,n)=>D("not-newable",e,`Type '${b(n)}' is not newable \u2014 only host constructors (with a construct signature) can be used with 'new'.`),noSuchMember:(e,n,t)=>D("no-such-member",e,`Property '${t}' does not exist on type '${b(n)}'.`),notObject:(e,n)=>D("not-object",e,`Type '${b(n)}' has no members to access.`),constNeedsInit:e=>D("const-needs-init",e,"'const' declarations must be initialized."),missingArgument:(e,n,t)=>D("missing-argument",e,`Missing argument '${n}' of type '${b(t)}'.`),unsupported:(e,n)=>D("unsupported",e,`${n} is not supported in this language.`),castUnsound:(e,n,t)=>E("cast-unsound",e,`Conversion of type '${b(n)}' to type '${b(t)}' may be a mistake \u2014 neither sufficiently overlaps the other. Cast through 'unknown' first if intentional.`,"warning")};function re(){let e=[];return {all:e,report(n){e.push(n);},hasErrors(){return e.some(n=>n.severity==="error")}}}function oe(e,n,t={}){return n.flatMap(r=>r(e,t))}function K(e,n){let t=r=>{n(r);for(let a of childrenOf(r))t(a);};t(e);}var mn=e=>Array.isArray(e)?e:[e],De=["ArrowFunctionExpression","FunctionExpression","FunctionDeclaration"];function se(e,n="error"){return t=>{let r=[];return K(t,a=>{let o=nodeViolation(a,e);o&&r.push(E("node-not-allowed",a,`'${o}' is not allowed by the capability profile.`,n));}),r}}function ie(e,n="error"){let t=new Set(e);return r=>{let a=[];return K(r,o=>{if(o.type!=="CallExpression")return;let s=o.callee;if(s.type!=="Identifier")a.push(E("name-not-allowed",s,"Only direct calls to allowed functions are permitted.",n));else {let l=s.name;t.has(l)||a.push(E("name-not-allowed",s,`Function '${l}' is not allowed here.`,n));}}),a}}function _(e,n,t={}){let r=new Set(mn(e)),a=t.severity??"error",o=[...r].join("/");return s=>{let l=[],m=(c,f)=>{let d=r.has(c.type),y=d?f+1:f;d&&y>n&&l.push(E("too-deep",c,`Nesting of ${o} exceeds ${n}${t.hint?` \u2014 ${t.hint}`:""}.`,a));for(let g of childrenOf(c))m(g,y);};return m(s,0),l}}var le=(e=3,n="error")=>_(De,e,{hint:"use a pipe instead of nesting functions",severity:n}),ue=(e,n="error")=>_("CallExpression",e,{hint:"use a pipe instead of nesting calls",severity:n}),pe=(e,n="error")=>_("MemberExpression",e,{severity:n});function ce(e,n="error"){return t=>{let r=[],a=(o,s)=>{if(s>e){r.push(E("too-deep",o,`Expression nesting exceeds ${e}.`,n));return}for(let l of childrenOf(o))a(l,s+1);};return a(t,0),r}}function me(e,n="error"){return t=>{let r=0;return K(t,()=>{r++;}),r>e?[E("too-large",t,`Expression has ${r} nodes (max ${e}).`,n)]:[]}}function ye(e,n="error"){return t=>{let r=[];return K(t,a=>{if(a.type==="CallExpression"){let o=a.arguments;o&&o.length>e&&r.push(E("too-large",a,`Call has ${o.length} arguments (max ${e}).`,n));}}),r}}function fe(e,n={},t="error"){return (r,a)=>{let o=a.overlay?.get(r)?.type;return o?S(o,e,n)?[]:[E("wrong-result-type",r,`Result type '${b(o)}' is not assignable to the required '${b(e)}'.`,t)]:[]}}function $e(e){let n=[se(e)];return e.hostAllow!=="*"&&n.push(ie([...e.hostAllow])),n}function de(e){return $e(compileProfile(e))}var Sn=e=>{let n={};for(let t of Object.keys(e))n[t]={params:[],body:e[t]};return n};function hn(e){let n=[];return e.maxDepth!==void 0&&n.push(ce(e.maxDepth)),e.maxNodes!==void 0&&n.push(me(e.maxNodes)),e.maxArgs!==void 0&&n.push(ye(e.maxArgs)),e.maxFunctionNesting!==void 0&&n.push(le(e.maxFunctionNesting)),e.maxCallNesting!==void 0&&n.push(ue(e.maxCallNesting)),e.memberDepth!==void 0&&n.push(pe(e.memberDepth)),n}function gn(e,n,t={}){let r={...Sn(n.types),...n.schemes,...bn(e)},a={overlay:new WeakMap,sink:re(),env:n,schemes:r},o=p(e,n.scope,a),s=[];t.profile&&s.push(...de(t.profile)),t.limits&&s.push(...hn(t.limits)),t.resultType&&s.push(fe(t.resultType,r));let l=s.length?[...a.sink.all,...oe(e,s,{overlay:a.overlay})]:a.sink.all;return {type:o,overlay:a.overlay,diagnostics:l}}var bn=e=>{let n={};return walk(e,{TSTypeAliasDeclaration(t){let r=t;r.id?.name&&r.typeAnnotation&&(n[r.id.name]={params:r.typeParameters??[],body:r.typeAnnotation});}}),n},ke=e=>e.typeAnnotation,Ie=e=>e.returnType,u=(e,n,t,r)=>(e.overlay.set(n,{type:t,scope:r}),t),Se=e=>e.type==="ArrowFunctionExpression",Le=e=>e.t==="apply"&&e.name==="Promise"&&e.args.length===1,he=e=>Le(e)?e.args[0]:e,J=e=>Le(e)?e:i.promise(e);function p(e,n,t){switch(e.type){case "Literal":return u(t,e,Ge(e),n);case "Identifier":{let r=e.name,a=P(n,r);return a===void 0?r==="undefined"?u(t,e,i.undefined,n):(t.sink.report(h.unknownName(e,r)),u(t,e,i.unknown,n)):u(t,e,a,n)}case "MemberExpression":return u(t,e,kn(e,n,t),n);case "CallExpression":return u(t,e,wn(e,n,t),n);case "NewExpression":return u(t,e,Bn(e,n,t),n);case "ArrowFunctionExpression":return Ne(e,n,t);case "FunctionDeclaration":return t.sink.report(h.unsupported(e,"function declaration (use 'const fn = () => \u2026')")),u(t,e,i.unknown,n);case "FunctionExpression":return t.sink.report(h.unsupported(e,"anonymous function (use an arrow)")),u(t,e,i.unknown,n);case "ThisExpression":return t.sink.report(h.unsupported(e,"'this'")),u(t,e,i.unknown,n);case "BlockStatement":return u(t,e,we(e,n,t),n);case "ReturnStatement":{let r=e.argument;return u(t,e,r?p(r,n,t):i.unknown,n)}case "IfStatement":return v(e,n,t),t.overlay.get(e)?.type??i.unknown;case "ForStatement":case "WhileStatement":case "DoWhileStatement":case "ForOfStatement":case "ForInStatement":case "BreakStatement":case "ContinueStatement":case "ThrowStatement":case "TryStatement":case "SwitchStatement":return v(e,n,t),t.overlay.get(e)?.type??i.unknown;case "AssignmentExpression":{let r=e;return p(r.left,n,t),u(t,e,p(r.right,n,t),n)}case "UpdateExpression":return p(e.argument,n,t),u(t,e,i.number,n);case "ExpressionStatement":return u(t,e,p(e.expression,n,t),n);case "VariableDeclaration":return Ee(e,n,t),u(t,e,i.unknown,n);case "TSTypeAliasDeclaration":return u(t,e,i.unknown,n);case "BinaryExpression":return u(t,e,On(e,n,t),n);case "LogicalExpression":{let r=e,a=p(r.left,n,t),o=p(r.right,n,t);return u(t,e,k([a,o]),n)}case "UnaryExpression":return u(t,e,Pn(e,n,t),n);case "ConditionalExpression":{let r=e;p(r.test,n,t);let a=p(r.consequent,n,t),o=p(r.alternate,n,t);return u(t,e,k([a,o]),n)}case "ObjectExpression":return u(t,e,In(e,n,t),n);case "ArrayExpression":return u(t,e,Ln(e,n,t),n);case "TemplateLiteral":{for(let r of e.expressions)p(r,n,t);return u(t,e,i.string,n)}case "AwaitExpression":{let r=e.argument,a=r?p(r,n,t):i.unknown;return u(t,e,he(a),n)}case "Program":return Be(e.body,n,t),u(t,e,i.unknown,n);case "JsonExpression":return u(t,e,be(e.body,n,t,e),n);case "ChainExpression":return u(t,e,k([p(e.expression,n,t),i.undefined]),n);case "TSAsExpression":{let r=e,a=p(r.expression,n,t),o=r.typeAnnotation;return !S(a,o,t.schemes)&&!S(o,a,t.schemes)&&t.sink.report(h.castUnsound(e,a,o)),u(t,e,o,n)}default:return t.sink.report(h.unsupported(e,`'${e.type}'`)),u(t,e,i.unknown,n)}}function Ge(e){let n=e;if(n.regex||n.bigint)return i.unknown;let t=n.value;if(t===null)return i.null;if(t===void 0)return i.undefined;switch(typeof t){case "string":return i.string;case "number":return i.number;case "boolean":return i.boolean;default:return i.unknown}}function kn(e,n,t){let r=p(e.object,n,t);if(e.computed){p(e.property,n,t);let s=F(r,["[]"],t.schemes);return s?s.type:i.unknown}let a=e.property.name,o=F(r,[a],t.schemes);return o?o.type:(r.t==="object"||r.t==="array"||r.t==="union"?t.sink.report(h.noSuchMember(e,r,a)):r.t!=="any"&&r.t!=="unknown"&&t.sink.report(h.notObject(e,r)),i.unknown)}function Nn(e){let n=r=>r&&r.type==="Literal"&&typeof r.value=="string"?r.value:null;if(e.length===1&&e[0].type==="ArrayExpression"){let r=[];for(let a of e[0].elements){let o=n(a);if(o===null)return null;r.push(o);}return r}let t=[];for(let r of e){let a=n(r);if(a===null)return null;t.push(a);}return t.length?t:null}function Me(e){if(e.type==="Identifier")return e.name;if(e.type==="MemberExpression"){let n=e;if(n.computed||n.property.type!=="Identifier")return null;let t=Me(n.object);return t===null?null:`${t}.${n.property.name}`}return null}function wn(e,n,t){let r=e.arguments,a=Me(e.callee);if(a){let f=t.env.accessors?.[a];if(f){let d=Nn(r);if(d){let y=F(f,d,t.schemes);return y?y.type:(t.sink.report(h.noSuchMember(e,f,d.join("."))),i.unknown)}return r.forEach(y=>p(y,n,t)),i.unknown}}let o=p(e.callee,n,t);if(o.t==="any")return r.forEach(f=>p(f,n,t)),i.any;if(o.t!=="fn")return r.forEach(f=>p(f,n,t)),t.sink.report(h.notCallable(e,o)),i.unknown;let s=o,l=r.map(f=>Se(f)?i.any:p(f,n,t)),m=V(s,l).bindings;r.forEach((f,d)=>{if(Se(f)){let y=N(s.params[d]?.type??i.any,m);l[d]=Ne(f,n,t,y);}});let{bindings:c}=V(s,l);return Ue(e,s,l,c,t),C(N(s.returns,c))}function Bn(e,n,t){let r=e.arguments,a=p(e.callee,n,t);if(a.t==="any")return r.forEach(c=>p(c,n,t)),i.any;let o=a.t==="fn"?a.construct:void 0;if(!o)return r.forEach(c=>p(c,n,t)),t.sink.report(h.notNewable(e,a)),i.unknown;let s={params:o.params,returns:o.returns},l=r.map(c=>Se(c)?i.any:p(c,n,t)),{bindings:m}=V(s,l);return Ue(e,s,l,m,t),C(N(o.returns,m))}function Ue(e,n,t,r,a){for(let o=0;o<n.params.length;o++){let s=n.params[o];if(s.variadic)break;let l=N(s.type,r);if(o>=t.length){s.optional||a.sink.report(h.missingArgument(e,s.name,l));continue}S(t[o],l,a.schemes)||a.sink.report(h.notAssignable(e.arguments[o],t[o],l));}}var We=e=>{let n=e.value;return n===null?i.null:typeof n=="string"||typeof n=="number"||typeof n=="boolean"?i.literal(n):Ge(e)},En=(e,n)=>{let t=e;for(let r=0;r<50&&t.t==="apply";r++){let a=A(t,n.schemes);if(a===t||a.t==="apply"&&a.name===t.name)break;t=a;}return t};function L(e,n,t,r){let a=En(n,r);switch(e.type){case "Literal":{let s=We(e);return S(s,n,r.schemes)||r.sink.report(h.notAssignable(e,s,n)),u(r,e,n,t)}case "ArrayExpression":{if(a.t==="array"){for(let s of e.elements){if(!s)continue;let l=s;l.type==="SpreadElement"?L(l.argument,n,t,r):L(l,a.items,t,r);}return u(r,e,n,t)}break}case "ObjectExpression":{if(a.t==="object"){let s={};for(let m of e.properties){let c=m;if(c.type==="SpreadElement"){p(c.argument,t,r);continue}let f=c,d=Ke(f),y=d!==null?a.props[d]?.type:void 0,g=y?L(f.value,y,t,r):p(f.value,t,r);d!==null&&(s[d]={type:g}),u(r,c,g,t);}let l={t:"object",props:s};return S(l,n,r.schemes)||r.sink.report(h.notAssignable(e,l,n)),u(r,e,n,t)}break}case "ArrowFunctionExpression":{if(a.t==="fn"){let s=Ne(e,t,r,a);return S(s,n,r.schemes)||r.sink.report(h.notAssignable(e,s,n)),u(r,e,n,t)}break}case "ConditionalExpression":{let s=e;return p(s.test,t,r),L(s.consequent,n,t,r),L(s.alternate,n,t,r),u(r,e,n,t)}}let o=p(e,t,r);return S(o,n,r.schemes)||r.sink.report(h.notAssignable(e,o,n)),u(r,e,o,t)}function vn(e){let n=Ie(e);return n?{t:"fn",params:e.params.map((r,a)=>({name:G(r)??`arg${a}`,type:ke(r)??i.unknown})),returns:e.async?J(n):n}:null}function Ne(e,n,t,r){let a=r&&r.t==="fn"?r:void 0,o={},s=e.params.map((y,g)=>{let w=y,M=G(w),$=ke(w)??a?.params[g]?.type??i.unknown;return M&&(o[M]=$),t.overlay.set(w,{type:$,scope:n}),{name:M??`arg${g}`,type:$}}),l=j(n,o),m=e.body,c=Ie(e);if(m.type!=="BlockStatement"&&c){let y=e.async?he(c):c;L(m,y,l,t);let g=e.async?J(c):c;return u(t,e,{t:"fn",params:s,returns:g},n)}let f=m.type==="BlockStatement"?u(t,m,we(m,l,t),l):p(m,l,t),d=e.async?J(f):f;if(c){let y=e.async?he(c):c,g=e.async?f:d;S(g,y,t.schemes)||t.sink.report(h.notAssignable(m,d,c));let w=e.async?J(c):c;return u(t,e,{t:"fn",params:s,returns:w},n)}return u(t,e,{t:"fn",params:s,returns:d},n)}function we(e,n,t){let{returns:r}=Be(e.body,n,t);return r.length?k(r):i.unknown}function Be(e,n,t){let r=n,a=[];for(let o of e){let s=o;if(s.type==="VariableDeclaration")r=Ee(s,r,t);else if(s.type==="FunctionDeclaration"){let l=p(s,r,t),m=G(s.id);m&&(r=j(r,{[m]:l}));}else if(s.type==="IfStatement"){a.push(...v(s,r,t));let l=s;!l.alternate&&H(l.consequent)&&(r=ge(r,ze(l.test,r,t.schemes).else));}else a.push(...v(s,r,t));}return {scope:r,returns:a}}var U={then:{},else:{}},Ve={string:i.string,number:i.number,boolean:i.boolean},W=e=>e.t==="union"?[...e.of]:[e];function Oe(e,n){let t=e,r=n;return e.type==="UnaryExpression"&&t.operator==="typeof"&&t.argument.type==="Identifier"&&n.type==="Literal"&&typeof r.value=="string"?{name:t.argument.name,tag:r.value}:null}function Cn(e,n){let t=Ve[n];if(!t)return null;if(e.t==="unknown"||e.t==="any")return t;let r=W(e).filter(a=>S(a,t));return r.length?k(r):t}function An(e,n){let t=Ve[n];if(!t||e.t==="unknown"||e.t==="any")return null;let r=W(e).filter(a=>!S(a,t));return r.length?k(r):null}function Fe(e,n){if(e.type==="Identifier"&&n.type==="Literal"){let t=We(n);if(t.t==="literal"||t.t==="null")return {name:e.name,lit:t}}return null}function Tn(e,n,t){return e.t==="unknown"||e.t==="any"||S(n,e,t)?n:null}function xn(e,n,t){let r=W(e),a=r.filter(o=>!Q(o,n,t));return a.length&&a.length<r.length?k(a):null}var qe=e=>e.t==="null"||e.t==="undefined",jn=e=>{if(e.t==="unknown"||e.t==="any")return null;let n=W(e),t=n.filter(r=>!qe(r));return t.length&&t.length<n.length?k(t):null},Dn=e=>{let n=W(e),t=n.filter(qe);return t.length&&t.length<n.length?k(t):null},Pe=e=>e.type==="Literal"&&e.value===null?"null":e.type==="Identifier"&&e.name==="undefined"?"undefined":null,I=(e,n,t)=>({then:n?{[e]:n}:{},else:t?{[e]:t}:{}}),$n=e=>e==="==="||e==="=="||e==="!=="||e==="!=";function ze(e,n,t){if(e.type==="BinaryExpression"){let r=e;if(!$n(r.operator))return U;let a=r.operator==="!=="||r.operator==="!=",o=r.left,s=r.right,l=Oe(o,s)??Oe(s,o);if(l){let y=P(n,l.name);if(!y)return U;let g=Cn(y,l.tag),w=An(y,l.tag);return a?I(l.name,w,g):I(l.name,g,w)}let m=Pe(o),c=Pe(s),f=m?s:c?o:null;if((m||c)&&f?.type==="Identifier"){let y=f.name,g=P(n,y);if(!g)return U;let M=r.operator==="=="||r.operator==="!="?["null","undefined"]:[m??c],$=W(g),ve=$.filter(Y=>M.includes(Y.t)),Z=$.filter(Y=>!M.includes(Y.t)),Ce=ve.length?k(ve):null,Ae=Z.length&&Z.length<$.length?k(Z):null;return a?I(y,Ae,Ce):I(y,Ce,Ae)}let d=Fe(o,s)??Fe(s,o);if(d){let y=P(n,d.name);if(!y)return U;let g=Tn(y,d.lit,t),w=xn(y,d.lit,t);return a?I(d.name,w,g):I(d.name,g,w)}return U}if(e.type==="Identifier"){let r=e.name,a=P(n,r);if(a)return I(r,jn(a),Dn(a))}return U}var ge=(e,n)=>Object.keys(n).length?j(e,n):e;function H(e){switch(e.type){case "ReturnStatement":case "ThrowStatement":return true;case "BlockStatement":{let n=e.body;return n.length>0&&H(n[n.length-1])}case "IfStatement":{let n=e;return !!n.alternate&&H(n.consequent)&&H(n.alternate)}default:return false}}function v(e,n,t){switch(e.type){case "ReturnStatement":{let r=e.argument,a=r?p(r,n,t):i.unknown;return u(t,e,a,n),[a]}case "IfStatement":{let r=e;p(r.test,n,t);let a=ze(r.test,n,t.schemes),o=v(r.consequent,ge(n,a.then),t);return r.alternate&&o.push(...v(r.alternate,ge(n,a.else),t)),u(t,e,i.unknown,n),o}case "BlockStatement":{let r=we(e,n,t);return u(t,e,r,n),r.t==="unknown"?[]:[r]}case "ForStatement":case "WhileStatement":case "DoWhileStatement":{let r=e,a=n;r.init&&(r.init.type==="VariableDeclaration"?a=Ee(r.init,a,t):p(r.init,a,t)),r.test&&p(r.test,a,t),r.update&&p(r.update,a,t);let o=v(r.body,a,t);return u(t,e,i.unknown,n),o}case "ForOfStatement":case "ForInStatement":{let r=e,a=p(r.right,n,t),o=e.type==="ForOfStatement"?a.t==="array"?a.items:i.unknown:i.string,s=Rn(r.left),l=s?j(n,{[s]:o}):n,m=v(r.body,l,t);return u(t,e,i.unknown,n),m}case "BreakStatement":case "ContinueStatement":return u(t,e,i.unknown,n),[];case "ThrowStatement":{let r=e.argument;return r&&p(r,n,t),u(t,e,i.unknown,n),[]}case "TryStatement":{let r=e,a=v(r.block,n,t);if(r.handler){let o=r.handler.param,s=o?G(o):null,l=s?j(n,{[s]:i.unknown}):n;a.push(...v(r.handler.body,l,t));}return r.finalizer&&a.push(...v(r.finalizer,n,t)),u(t,e,i.unknown,n),a}case "SwitchStatement":{let r=e;p(r.discriminant,n,t);let a=n,o=[];for(let s of r.cases){s.test&&p(s.test,a,t);let l=Be(s.consequent,a,t);a=l.scope,o.push(...l.returns);}return u(t,e,i.unknown,n),o}default:return p(e,n,t),[]}}var Rn=e=>{if(e.type==="VariableDeclaration"){let n=e.declarations[0];return n?G(n.id):null}return G(e)};function Ee(e,n,t){let r={};for(let a of e.declarations){let o=G(a.id),s=ke(a.id);if(!a.init){t.sink.report(h.constNeedsInit(a)),o&&(r[o]=s??i.unknown);continue}let l=s??(a.init.type==="ArrowFunctionExpression"?vn(a.init):null),m=o&&l?j(n,{[o]:l}):n,c;s?(L(a.init,s,m,t),c=s):c=p(a.init,m,t),u(t,a,c,n),o&&(r[o]=c);}return u(t,e,i.unknown,n),j(n,r)}function On(e,n,t){let r=p(e.left,n,t),a=p(e.right,n,t),o=e.operator;return o==="+"?S(r,i.string)||S(a,i.string)?i.string:i.number:Fn.has(o)?i.number:i.boolean}var Fn=new Set(["-","*","/","%","**","&","|","^","<<",">>",">>>"]);function Pn(e,n,t){switch(p(e.argument,n,t),e.operator){case "!":return i.boolean;case "-":case "+":case "~":return i.number;case "typeof":return i.string;case "delete":return i.boolean;case "void":return i.undefined;default:return i.unknown}}function In(e,n,t){let r={};for(let a of e.properties){let o=a;if(o.type==="SpreadElement"){p(o.argument,n,t);continue}let s=o,l=p(s.value,n,t),m=Ke(s);m!==null&&(r[m]={type:l}),u(t,o,l,n);}return {t:"object",props:r}}var Ke=e=>{if(e.computed)return null;let n=e.key;return n.type==="Identifier"?n.name:n.type==="Literal"?String(n.value??""):null};function Ln(e,n,t){let r=[];for(let a of e.elements){if(!a)continue;let o=a;if(o.type==="SpreadElement"){p(o.argument,n,t);continue}r.push(p(o,n,t));}return i.array(r.length?k(r):i.unknown)}function be(e,n,t,r){if(e===null)return i.null;switch(typeof e){case "string":return i.string;case "number":return i.number;case "boolean":return i.boolean;case "object":break;default:return i.unknown}if(Array.isArray(e)){let s=e.map(l=>be(l,n,t,r));return i.array(s.length?k(s):i.unknown)}let a=e;if(AST_MARKER in a){let s;try{s=fromJson(a);}catch{return t.sink.report(h.unsupported(r,`'#ast: ${String(a[AST_MARKER])}'`)),i.unknown}return p(s,n,t)}let o={};for(let s of Object.keys(a))o[s]={type:be(a[s],n,t,r)};return {t:"object",props:o}}var G=e=>e.type==="Identifier"?e.name:null;var Gn=(e,n)=>({...e,typeAnnotation:n}),Mn=(e,n)=>({...e,returnType:n});function Un(e,n){return e.get(n)?.type}function Wn(e,n){return e.get(n)?.scope}function Vn(e,n){let t=e.get(n)?.type;return t?F(t,[])?.completions??[]:[]}function qn(e,n){let t=e.get(n)?.scope;return t?[...te(t)].map(([r,a])=>({key:r,type:a,optional:false})):[]}function zn(e,n){return e.filter(t=>t.node===n)}export{De as FUNCTION_KINDS,Gn as annotate,Mn as annotateReturn,ie as calleeAllowlist,se as capabilityNodes,gn as check,j as childScope,ln as createEnv,re as createSink,h as diag,zn as diagnosticsAt,F as discover,Q as equals,A as expand1,b as format,de as fromCapability,C as groundVars,oe as guard,$e as guardsFromCompiled,tn as instantiate,V as instantiateLoose,O as isScheme,z as isSerializable,Te as join,Xe as joinAll,P as lookup,E as makeDiagnostic,ye as maxArgs,ue as maxCallNesting,ce as maxDepth,le as maxFunctionNesting,_ as maxNestingOf,me as maxNodes,Vn as memberCompletions,pe as memberDepth,k as normalizeUnion,un as resolveNamed,pn as resolveScheme,fe as resultType,je as rootScope,i as s,Wn as scopeAt,qn as scopeCompletions,N as substitute,S as subtype,Un as typeAt,x as unify,te as visibleNames,q as withoutUndefined};
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tslite/checker",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "TSLite type system — a structural type checker over the AST (the 'TypeScript of TSLite')",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.cjs",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"require": "./dist/index.cjs"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=18"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "https://github.com/andersondrosa/tslite.git",
|
|
26
|
+
"directory": "packages/checker"
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"ast",
|
|
30
|
+
"type-checker",
|
|
31
|
+
"structural-typing",
|
|
32
|
+
"type-inference",
|
|
33
|
+
"schema",
|
|
34
|
+
"typescript"
|
|
35
|
+
],
|
|
36
|
+
"author": "Anderson D. Rosa <andersondrosa@outlook.com>",
|
|
37
|
+
"license": "MIT",
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"@tslite/capability": "0.1.0",
|
|
43
|
+
"@tslite/codec": "0.1.0",
|
|
44
|
+
"@tslite/core": "0.1.0"
|
|
45
|
+
},
|
|
46
|
+
"scripts": {
|
|
47
|
+
"build": "tsup",
|
|
48
|
+
"dev": "tsup --watch",
|
|
49
|
+
"test": "vitest run",
|
|
50
|
+
"test:watch": "vitest",
|
|
51
|
+
"test:coverage": "vitest run --coverage",
|
|
52
|
+
"typecheck": "tsc --noEmit",
|
|
53
|
+
"lint": "eslint src tests",
|
|
54
|
+
"lint:fix": "eslint src tests --fix",
|
|
55
|
+
"clean": "rm -rf dist",
|
|
56
|
+
"format": "prettier --write \"src/**/*.ts\"",
|
|
57
|
+
"format:check": "prettier --check \"src/**/*.ts\""
|
|
58
|
+
}
|
|
59
|
+
}
|