@final-hill/decorator-contracts 3.0.0 → 3.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/README.md +6 -0
- package/dist/decorator.d.mts +7 -0
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/name.d.mts +3 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -595,6 +595,12 @@ A runtime warning cannot close it either. The body holds the raw target, so `thi
|
|
|
595
595
|
|
|
596
596
|
So the rule is a review question about your class rather than something the compiler or this library can check: a feature that is only ever reached from inside the class needs its guard on the verb a caller actually invokes.
|
|
597
597
|
|
|
598
|
+
**A `protected` or `private` member has no external path, only a peer path.** The modifier is a compile-time refinement of an ordinary public property: the emitted JavaScript carries no record of it, and a standard decorator context reports `private: false` for both (`context.private` is true only for a native `#private` member). A caller outside the class cannot name the member, and the usual access inside it is `this.member`, which runs against the raw target and starts no lifecycle.
|
|
599
|
+
|
|
600
|
+
The arm is therefore reachable only through the [cross-instance case](#the-cross-instance-case-is-checked): a subclass method that reads the member on another instance, as `peer.member`, does cross a proxy and does evaluate it. When no such call exists, the declaration describes a boundary no invocation can reach.
|
|
601
|
+
|
|
602
|
+
The decorator cannot refuse that declaration, because it never sees the modifier, and a check keyed on it would also refuse the public member it is indistinguishable from. The `_` prefix is the one signal the runtime does have, which is why a `_`-prefixed feature is refused outright. Write a member that only the class calls as an undecorated method, as `core` is above; the guard belongs on the public verb, and a declaration that names a member nothing can reach reads as a guarantee it does not give.
|
|
603
|
+
|
|
598
604
|
### Deletion
|
|
599
605
|
|
|
600
606
|
Deletion is an external mutation, so it follows exactly the same rule as assignment: `_`-prefixed properties may be deleted, public properties may not, and the invariant is evaluated around the deletion.
|
package/dist/decorator.d.mts
CHANGED
|
@@ -30,6 +30,13 @@ export declare function assertDecoratorContext(contract: string, context: unknow
|
|
|
30
30
|
* The rule lives here rather than in each decorator so that a constraint added to
|
|
31
31
|
* one applies to all three, instead of being easy to miss in the others.
|
|
32
32
|
*
|
|
33
|
+
* The name is the only visibility the runtime can see, and it is deliberately the
|
|
34
|
+
* only one checked. A `protected` or `private` keyword member is an ordinary public
|
|
35
|
+
* property in the emitted JavaScript, and a standard context reports `private: false`
|
|
36
|
+
* for it; `context.private` is true only for a native `#private` member. The `_`
|
|
37
|
+
* convention is therefore what carries the guarantee, not the modifier: a contract on
|
|
38
|
+
* a non-public keyword member is accepted here, and the documentation says why.
|
|
39
|
+
*
|
|
33
40
|
* The name of the contract is passed in so the messages stay specific.
|
|
34
41
|
*
|
|
35
42
|
* `context` is `unknown` because the protocol is diagnosed here rather than by
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Symbol.metadata??=Symbol.for("Symbol.metadata");class e extends Error{name="AssertionError";violation;constructor(e,t){super(e),this.violation=t}}const t=new WeakMap,n=e=>{const n=t.get(e);if(n)return n;const r=new Proxy(e,{set(e,t){throw new TypeError(`A contract predicate may not assign '${String(t)}'. Contract predicates answer a question; they must not change the state they are asked about.`)},deleteProperty(e,t){throw new TypeError(`A contract predicate may not delete '${String(t)}'. Contract predicates answer a question; they must not change the state they are asked about.`)},defineProperty(){throw new TypeError("A contract predicate may not define properties. Contract predicates answer a question; they must not change the state they are asked about.")}});return t.set(e,r),r},r=e=>"object"==typeof e&&null!==e&&"~standard"in e,o=e=>{if(r(e)){const{vendor:t,version:n}=e["~standard"];return`Standard Schema (vendor: ${String(t)}, version: ${String(n)})`}return String(e)},a=(e,t,n)=>{if(n?.normalize&&!r(e))throw new TypeError(`${t} cannot normalize: only a Standard Schema arm produces a replacement value.`)},s=(e,t,n)=>{if(n?.awaitPredicate&&r(e))throw new TypeError(`${t} cannot declare awaitPredicate on a schema arm: \`validate\` is evaluated synchronously, so there is no verdict to await.`)},i=(e,t)=>{if(void 0!==t?.onViolation&&"function"!=typeof t.onViolation)throw new TypeError(`${e} onViolation must be a function that returns an error object.`)},c=e=>{for(const{options:t}of e)if(t?.onViolation)return t.onViolation},u=(e,t)=>{if(t?.allowWeakening)throw new TypeError(`${e} cannot declare allowWeakening: only a precondition can be weakened, because only \`@demands\` is OR-composed. A subclass arm on an AND-composed contract strengthens the obligation and takes effect, so there is no warning to suppress.`)},l=new WeakMap,d=(e,t,n,o,a,s)=>r(e)?m(e,t.schema(),n,o,a,s):y(e,t.predicate(),n,o,a,s),f=async(e,t,n,o,a,s)=>{if(r(e))return m(e,t.schema(),n,o,a,s);const i=e,c=t.predicate();return s?.awaitPredicate?h(i,c,n,o,a):y(i,c,n,o,a,s)},h=async(e,t,n,r,o)=>{let a;try{a=await p(e,t)}catch(e){return{ok:!1,thrown:e}}return{ok:$(a,n,r,o)}},p=(e,t)=>e("object"==typeof t.self&&null!==t.self?{...t,self:n(t.self)}:t),y=(e,t,n,r,o,a)=>{let s;try{s=p(e,t)}catch(e){return{ok:!1,thrown:e}}if(a?.awaitPredicate&&"function"==typeof s?.then)throw new TypeError(`${n} predicate #${o+1} for ${r()} declared awaitPredicate but returned a Promise, and the feature it guards is not \`async\`, so nothing can await it. Declare the feature \`async\`, or drop the option.`);return{ok:$(s,n,r,o)}},m=(e,t,n,r,o,a)=>{const s=e["~standard"].validate(t);if("function"==typeof s?.then)throw new TypeError(`${n} schema #${o+1} for ${r()} returned a Promise; contract evaluation is synchronous, so use a synchronous schema.`);return s.issues?{ok:!1,issues:s.issues}:a?.normalize?{ok:!0,value:s.value}:{ok:!0}};class w{#e;record(e,t){((e,t,n)=>{e.failed.push(t),n.issues&&e.issues.push(...n.issues),"thrown"in n&&e.thrown.push({index:t,value:n.thrown})})(this.#e??={failed:[],thrown:[],issues:[]},e,t)}get entries(){return this.#e}}const g=()=>new w;function b(t,n="Assertion Error"){if(0==Boolean(t))throw new e(n)}const v=e=>"object"==typeof e&&null!==e&&"function"==typeof e.then?"a Promise (contract predicates must be synchronous)":"string"==typeof e?`the string ${JSON.stringify(e)}`:void 0===e?"undefined":null===e?"null":"object"==typeof e?`an object (${Object.prototype.toString.call(e)})`:`a ${typeof e} (${String(e)})`;function $(t,n,r,o){if("boolean"==typeof t)return t;throw new e(`${n} predicate #${o+1} for ${r()} returned ${v(t)}; contract predicates must return a boolean`)}function O(e,t,n,r,o,a,s,i=String,c){const u=c?.map(e=>e.index),l=c?.map(e=>(e=>{if("object"==typeof e&&null!==e){const t=e,n="string"==typeof t.name?t.name:e.constructor?.name??"Object",r="string"==typeof t.message?t.message:"";return r?`${n}: ${r}`:n}return String(e)})(e.value)),d={contract:e,className:t,feature:n,failedIndices:o,predicates:o.map(e=>i(r[e])),...u&&u.length>0?{thrownIndices:u,thrown:l}:{},...s&&s.length>0?{issues:s}:{}};return{message:j(e,d,r,a,s),violation:d}}const j=(e,t,n,o,a)=>{const s=void 0===t.feature?t.className:`${t.className}.${t.feature}`,i=new Set(t.thrownIndices??[]),c=((e,t,n,o)=>n.map((n,a)=>{const s=t[a];return`${r(e[s])?"schema":"predicate"} #${s+1}${o.has(s)?" threw":""}: ${n}`}).join("; "))(n,t.failedIndices,t.predicates,i);var u,l,d,f,h;return`${e} failed for ${s} (${l=t.failedIndices.length,d=n.length,u=n[0],f=r(u)?"schema":"predicate",h=(e=>r(e)?"schemas":"predicates")(n[0]),`${l} of ${d} ${1===d?f:h}`} unsatisfied: ${c}).${a&&a.length>0?` Reported: ${a.map(e=>(e=>{const t=(e.path??[]).map(e=>"object"==typeof e&&null!==e?e.key:e).join(".");return t?`${t}: ${e.message}`:e.message})(e)).join("; ")}.`:""} ${o}`};function S(t,n,r,o,a,s,i,c=String,u){const{message:l,violation:d}=O(t,n,r,o,a,s,i,c,u);return new e(l,d)}const P=new WeakSet,k=(e,t,n,r=!1)=>{if(!Object.isExtensible(e))return;const o=P.has(e),a=t=>!(o||!Object.hasOwn(e,t)||r&&"violation"===t&&void 0===e.violation);for(const[r,o]of[["violation",t],["cause",n]])a(r)||Object.defineProperty(e,r,{value:o,enumerable:!1,configurable:!0});P.add(e)};function x(e,t,n,r,o,a,s=String,i){const c=S(e,t,n,r,o.failed,a,o.issues,s,o.thrown),u=c.violation;if(i)return((e,t,n,r)=>{const o=r(t);if("object"!=typeof o||null===o)throw new TypeError(`${e} returned ${typeof o}; it must return an object so the violation can be attached.`,{cause:n});return k(o,t,n,!0),o})(`${e} onViolation for ${void 0===n?t:`${t}.${n}`}`,u,c,i);if(0===o.thrown.length)return c;const l=o.thrown[0].value;return"object"==typeof l&&null!==l&&k(l,u,c),l}function z(e,t){return Boolean(e&&t||!e&&!t)}function E(e,t){return!e||Boolean(t)}const R=Symbol.for("Contracted.contractName"),T=e=>{if("function"!=typeof e)return"";try{const t=Object.hasOwn(e,R)?e[R]:void 0;if("string"==typeof t&&t.length>0)return t}catch{}return e.name},C=Symbol.for("nodejs.util.inspect.custom"),A=new Set,W=e=>{switch(e.constructor.name){case"AsyncFunction":return"async";case"GeneratorFunction":return"generator";case"AsyncGeneratorFunction":return"async-generator";default:return"sync"}};function D(e,t){const n=t?.kind;b("string"==typeof n,`${e} was invoked without a standard decorator context, so it received no 'kind'. This happens when the compiler emits the pre-standard protocol, which \`experimentalDecorators\` selects. This library requires the TC39 protocol, so disable \`experimentalDecorators\` (and \`emitDecoratorMetadata\`), and make sure the build lowers decorator syntax rather than passing it through.`)}function _(e,t,n){D(e,n),b("method"===n.kind||"getter"===n.kind||"setter"===n.kind,`${e} decorator can only be applied to methods, getters, or setters`),b(!1===n.static,`${e} decorator cannot be applied to static features`),b(!1===n.private,`${e} decorator cannot be applied to private features`),b(!String(n.name).startsWith("_"),`${e} decorator cannot be applied to private/protected features`),n.addInitializer(function(){b(this instanceof Ce,`${e} decorator can only be applied to classes that extend Contracted`)})}function M(e,t,n,r){if(!r?.awaitPredicate)return;if("method"!==n.kind)throw new TypeError(`${e} cannot declare awaitPredicate on ${"getter"===n.kind?"a getter":"a setter"}: an accessor is read or assigned synchronously, so there is no promise a pending verdict could join.`);const o=W(t);if("async"!==o)throw new TypeError(`${e} cannot declare awaitPredicate on this feature: ${"generator"===o||"async-generator"===o?"a generator has one contract boundary per step, and awaiting a step would make every `next()` asynchronous rather than merely slower":"a synchronous feature has evaluated its contracts by the time the verdict could settle"}. The option is available on an \`async\` method only.`)}function N(e,t,n=ae(e)){if(!n)return;const r=e[Symbol.metadata]?.invariants??[];if(0===r.length)return;const a=()=>T(e),s=g();for(const[e,n]of r.entries()){const r=d(n.arm,{predicate:()=>({self:t}),schema:()=>t},"@invariant",a,e,n.options);r.ok||s.record(e,r)}if(void 0!==s.entries)throw x("@invariant",a(),void 0,r.map(e=>e.arm),s.entries,"The instance left the invariant unsatisfied.",o)}const I=(e,t)=>(n,r)=>{D("@invariant",r),((e,t)=>{if(t?.awaitPredicate)throw new TypeError("@invariant cannot declare awaitPredicate: an invariant is evaluated after construction and on every accessor read and write, where there is no promise a caller could await. Declare the option on the arm of an `async` feature instead.")})(0,t),((e,t)=>{if(t?.normalize)throw new TypeError("@invariant cannot normalize: its subject is the instance, which no arm can replace.")})(0,t),((e,t)=>{if(void 0!==t?.onViolation)throw new TypeError("@invariant cannot declare onViolation: its failure is what signals an unrecoverable instance, so it must stay an AssertionError. Translate it with a `@rescue` handler instead (which does not cover the check in `Contracted.new`).")})(0,t),u("@invariant",t);const{metadata:o}=r;b("class"===r.kind,"@invariant decorator can only be applied to classes"),b(n.prototype instanceof Ce,"@invariant decorator can only be applied to classes that extend Contracted");const a=o.invariants??[];o.invariants=[...a,{arm:e,options:t}]},V=Object.freeze([]),F=(e,t)=>(n,r)=>{_("@demands",0,r),M("@demands",n,r,t),s(e,"@demands",t),a(e,"@demands",t),i("@demands",t),((e,t)=>{const n=l.get(e);return!!n?.has(t)||(n?n.add(t):l.set(e,new Set([t])),!1)})(r.metadata,r.name)||((e,t,n,r)=>{if(0===n.length||r?.allowWeakening)return;const o=`@demands on ${t} adds an arm to a precondition that already has ${n.length} inherited arm(s). \`@demands\` is OR-composed, so this arm cannot narrow what the base permits: satisfying any inherited arm still allows the call. Move the restriction to the base feature, or declare the arm with \`allowWeakening\` if a genuine weakening is what was meant.`;console.warn(o)})(0,String(r.name),((e,t)=>{const n=Object.getPrototypeOf(e??{});return n?.demands?.[t]??[]})(r.metadata,r.name),t);const o=[...r.metadata?.demands?.[r.name]??[],{arm:e,options:t}];r.metadata.demands={...r.metadata?.demands??{},[r.name]:o}},q=(e,t)=>({predicate:()=>({self:e,args:t}),schema:()=>t});function B(e,t,n,r){throw x("@demands",t,String(n),e.map(e=>e.arm),r,"A precondition was not satisfied, so the feature was not entered.",o,c(e))}function K(e,t,n,r=ae(e.constructor)){if(!r)return n;const o=e.constructor,a=o[Symbol.metadata]?.demands?.[t]??V;if(0===a.length)return n;const s=()=>`${T(o)}.${String(t)}`,i=g();for(let t=0;t<a.length;t++){const{arm:r,options:o}=a[t],c=d(r,q(e,n),"@demands",s,t,o);if(c.ok)return void 0===c.value?n:c.value;i.record(t,c)}B(a,T(o),t,i.entries)}async function J(e,t,n,r=ae(e.constructor)){if(!r)return n;const o=e.constructor,a=o[Symbol.metadata]?.demands?.[t]??V;if(0===a.length)return n;const s=()=>`${T(o)}.${String(t)}`,i=g();for(let t=0;t<a.length;t++){const{arm:r,options:o}=a[t],c=await f(r,q(e,n),"@demands",s,t,o);if(c.ok)return void 0===c.value?n:c.value;i.record(t,c)}B(a,T(o),t,i.entries)}const G=Object.freeze([]),U=(e,t)=>(n,r)=>{_("@ensures",0,r),M("@ensures",n,r,t),s(e,"@ensures",t),a(e,"@ensures",t),i("@ensures",t),u("@ensures",t);const o=[...r.metadata?.ensures?.[r.name]??[],{arm:e,options:t}],c=o.filter(e=>e.options?.normalize);if(c.length>1)throw new TypeError(`@ensures for ${String(r.name)} declares ${c.length} normalizing arms; at most one arm may normalize the result, because they would disagree about what the caller receives.`);r.metadata.ensures={...r.metadata?.ensures??{},[r.name]:o}},H=(e,t,n,r,o)=>({predicate:()=>({self:e,args:t,old:n,oldArgs:r,result:o}),schema:()=>o});function L(e,t,n,r){throw x("@ensures",t,String(n),e.map(e=>e.arm),r,"A postcondition was not satisfied after the feature ran.",o,c(e))}const Q=(e,t,n,r)=>n.ok?void 0===n.value?r:n.value:(e.record(t,n),r);function X(e,t,n,r,o,a=[],s=ae(e.constructor)){if(!s)return o;const i=e.constructor,c=i[Symbol.metadata]?.ensures?.[n]??G;if(0===c.length)return o;const u=()=>`${T(i)}.${String(n)}`,l=g();let f=o;for(let n=0;n<c.length;n++){const s=c[n];f=Q(l,n,d(s.arm,H(e,r,t,a,o),"@ensures",u,n,s.options),f)}if(void 0===l.entries)return f;L(c,T(i),n,l.entries)}const Y=(e,t)=>(n,r)=>{if(D("@rescue",r),"class"===r.kind)return b(n.prototype instanceof Ce,"@rescue decorator can only be applied to classes that extend Contracted"),b(void 0===t?.maxRetries||t.maxRetries>=0,"maxRetries must not be negative"),void(r.metadata.classRescue={handler:e,maxRetries:t?.maxRetries});_("@rescue",0,r),b(void 0===t?.maxRetries||t.maxRetries>=0,"maxRetries must not be negative"),r.metadata.rescue={...r.metadata?.rescue??{},[r.name]:{handler:e,maxRetries:t?.maxRetries}},r.addInitializer(function(){b(this instanceof Ce,"@rescue decorator can only be applied to classes that extend Contracted")})},Z=(e,t)=>String(t).startsWith("_")?void 0:e?.rescue?.[t]??e?.classRescue;function ee(e,t){for(let n=e.constructor;n&&n!==Function.prototype;n=Object.getPrototypeOf(n)){const e=n[Symbol.metadata];if(!e)continue;const r=Z(e,t);if(r)return r}}const te=(e,t,n,r)=>{if(!ae(e.constructor))throw n;const o=ee(e,t);if(!o)throw n;let a=!1,s=[];if(o.handler.call(e,{self:e,error:n,args:r,retry:(...e)=>{b(!a,"retry can only be called once per rescue execution"),a=!0,s=e},feature:t}),!a)throw n;return s},ne=Symbol.for("Contracted.checkedMode"),re=Symbol.for("Contracted.encapsulationMode"),oe=(e,t)=>{for(let n=e;"function"==typeof n&&n!==Function.prototype;n=Object.getPrototypeOf(n))if(Object.hasOwn(n,t))return Boolean(n[t]);return!0},ae=e=>oe(e,ne),se=e=>oe(e,re),ie=(e,t)=>{if("object"!=typeof e||null===e)return e;const n=t.get(e);if(void 0!==n)return n;if(e instanceof Date)return new Date(e.getTime());const r=ce(e,t);if(void 0!==r)return r;if(!(e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t})(e))return e;const o=Object.create(Object.getPrototypeOf(e));return t.set(e,o),ue(e,o,t),o},ce=(e,t)=>{if(Array.isArray(e)){const n=[];t.set(e,n);for(const r of e)n.push(ie(r,t));return n}if(e instanceof Map){const n=new Map;t.set(e,n);for(const[r,o]of e)n.set(ie(r,t),ie(o,t));return n}if(e instanceof Set){const n=new Set;t.set(e,n);for(const r of e)n.add(ie(r,t));return n}},ue=(e,t,n)=>{for(const r of Reflect.ownKeys(e)){const o=Object.getOwnPropertyDescriptor(e,r),a="value"in o?{...o,value:ie(o.value,n)}:o;le(t,r,a)}},le=(e,t,n)=>{"value"in n&&n.writable&&n.enumerable&&n.configurable?e[t]=n.value:Reflect.defineProperty(e,t,n)},de=(e,t)=>{if(t)return(({target:e,entries:t})=>{const n=Object.create(e);for(const[e,r]of t)le(n,e,r);return n})(((e,t)=>{const n=[];for(const r of Reflect.ownKeys(e)){const o=Object.getOwnPropertyDescriptor(e,r);n.push([r,"value"in o?{...o,value:ie(o.value,t)}:o])}return{target:e,entries:n}})(e,new WeakMap))},fe=(e,t,n)=>e?((e,t)=>{const n=new WeakMap;return e.map((e,r)=>{try{return((e,t)=>{if("object"!=typeof e||null===e)return e;const n=t.get(e);if(void 0!==n)return n;if(!(e instanceof Ce))return ie(e,t);const r=Object.create(Object.getPrototypeOf(e));return t.set(e,r),ue(e,r,t),r})(e,n)}catch(e){throw new TypeError(`@ensures on '${String(t)}' cannot snapshot argument ${r}: a postcondition that describes an argument's pre-state needs every argument to be readable.`,{cause:e})}})})(t,n):void 0,he=new WeakMap;function pe(e,t){let n=e;for(;n&&n!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=Object.getPrototypeOf(n)}}const ye=(e,t,n)=>"get"===e?[t]:n,me=(e,t)=>"get"===e?[]:t,we=e=>"func"===e||"get"===e,ge=(t,n,r,o)=>{if((t=>t instanceof e&&"@invariant"===t.violation?.contract)(r))return r;try{N(t,n,o)}catch(t){return((t,n)=>(t instanceof e&&"object"==typeof n&&null!==n&&!Object.hasOwn(t,"cause")&&Object.defineProperty(t,"cause",{value:n,enumerable:!1,configurable:!0}),t))(t,r)}return r};function be(e,t,n,r,o,a,s){const i=ee(t,n);if(!i||o>=(i?.maxRetries??1/0))throw ge(e,t,r,s);try{return te(t,n,r,a)}catch(n){throw ge(e,t,n,s)}}function ve(e,t,n,r,o){for(let a=0;;)try{return void N(e,t,o)}catch(s){if(a++>0)throw s;r.args=be(e,t,n,s,r.retries,r.args,o),r.retries++}}function $e(e,t,n,r,o,a,s,i,c,u,l){if(!c)return N(e,n,l),a;const d=ye(t,a,o);if(!u){const t=X(n,s,r,d,a,i,l);return N(e,n,l),t}return async function(e,t,n,r){const o=await n;return N(e,t,r),o}(e,n,async function(e,t,n,r,o,a=[],s=ae(e.constructor)){if(!s)return o;const i=e.constructor,c=i[Symbol.metadata]?.ensures?.[n]??G;if(0===c.length)return o;const u=()=>`${T(i)}.${String(n)}`,l=g();let d=o;for(let n=0;n<c.length;n++){const s=c[n];d=Q(l,n,await f(s.arm,H(e,r,t,a,o),"@ensures",u,n,s.options),d)}if(void 0===l.entries)return d;L(c,T(i),n,l.entries)}(n,s,r,d,a,i,l),l)}function Oe(e,t,n,r,o,a,s="sync"){return"async"===s?async function(e,t,n,r,o,a){const s=t.constructor,i=s[Symbol.metadata]?.ensures?.[n]??[],c=i.length>0,u=function(e,t){const n=e.constructor;return(n[Symbol.metadata]?.demands?.[t]??V).some(e=>e.options?.awaitPredicate)}(t,n),l=function(e,t){const n=e.constructor;return(n[Symbol.metadata]?.ensures?.[t]??G).some(e=>e.options?.awaitPredicate)}(t,n);let d=r,f=0;for(;;){const r=Pe(i)?de(t,a):void 0,h={args:d,retries:f};ve(s,t,n,h,a),d=h.args,f=h.retries,d=u?await J(t,n,d,a):K(t,n,d,a);const p=fe(Pe(i),d,n);let y;try{y=await o(d);const i=$e(s,e,t,n,d,y,r,p,c,l,a);y=l?await i:i}catch(r){d=be(s,t,n,r,f,me(e,d),a),f++;continue}return y}}(e,t,n,r,o,a):"generator"===s||"async-generator"===s?function(e,t,n,r,o,a){const s=e.constructor,i=s[Symbol.metadata]?.ensures?.[t]??[],c=i.length>0;let u,l,d=n,f=0,h=!0;const p=n=>(N(s,e,a),h?(h=!1,K(e,t,d)):n.length>0?K(e,t,n):n),y=(n,r)=>{c&&X(e,r,t,[n],n,[],a),N(s,e,a),l=void 0},m=()=>{if(N(s,e,a),void 0===l)return;const t=l;throw l=void 0,t},w=n=>{d=be(s,e,t,n,f,d,a),f++,u=r(d),h=!0,l=n},g=(t,n)=>{for(;;)try{n=p(n);const r=Pe(i)?de(e,a):void 0,o=t(u,n);return o.done?(m(),o):(y(o.value,r),o)}catch(e){w(e)}},b=async(t,n)=>{for(;;)try{n=p(n);const r=Pe(i)?de(e,a):void 0,o=await t(u,n);return o.done?(m(),o):(y(o.value,r),o)}catch(e){w(e)}},v={args:d,retries:f};ve(s,e,t,v,a),d=v.args,f=v.retries,d=K(e,t,d),h=!1,u=r(d);const $={};return"generator"===o?($.next=function(...e){return g((e,t)=>e.next(t[0]),e)},$.return=function(...e){return g((t,n)=>t.return(e[0]??n[0]),[])},$.throw=function(...e){return g((t,n)=>t.throw(e[0]??n[0]),[])},$[Symbol.iterator]=function(){return this}):($.next=function(...e){return b((e,t)=>e.next(t[0]),e)},$.return=function(...e){return b((t,n)=>t.return(e[0]??n[0]),[])},$.throw=function(...e){return b((t,n)=>t.throw(e[0]??n[0]),[])},$[Symbol.asyncIterator]=function(){return this}),$}(t,n,r,o,s,a):function(e,t,n,r,o,a){const s=t.constructor,i=s[Symbol.metadata]?.ensures?.[n]??[],c=i.length>0;let u=r,l=0;for(;;){const r=Pe(i)?de(t,a):void 0,d={args:u,retries:l};ve(s,t,n,d,a),u=d.args,l=d.retries,u=K(t,n,u,a);const f=fe(Pe(i),u,n);let h;try{h=o(u),we(e)&&xe(h,t,n),c&&(h=X(t,r,n,ye(e,h,u),h,f,a)),N(s,t,a)}catch(r){u=be(s,t,n,r,l,me(e,u),a),l++;continue}return h}}(e,t,n,r,o,a)}const je=new WeakMap,Se=[],Pe=e=>{return e.length>0&&!((t=e).length>0&&t.every(e=>r(e.arm)));var t};function ke(e,t,n,r,o,a){const s=ae(t.constructor);return s?Oe(e,t,n,r,o,s,a):o(r)}const xe=(t,n,r)=>{if(null!==t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then)throw new e(`${T(n.constructor)}.${String(r)} returned a promise but is not declared 'async', so its contracts were evaluated before its body finished. Declare the feature 'async'.`)},ze=(e,t,n,r)=>r?(r.call(e,n),!0):Reflect.set(e,t,n),Ee=e=>{if((e=>e===ne||e===re)(e))throw new TypeError(`Cannot set '${String(e)}' on a Contracted instance: enforcement is switched on the class, not on an instance. Assign '${String(e)}' on the class itself.`)},Re=(e,t,n,r)=>{if(r)return Reflect.get(e,t,n);const o=pe(Object.getPrototypeOf(e),t);return"function"==typeof o?.value?((e,t,n)=>he.get(e)?.get(t)??((e,t,n)=>{let r=he.get(e);return r||(r=new Map,he.set(e,r)),r.set(t,n),n})(e,t,function(e,t,n){const r=W(n);return function(...o){return ke("func",e,t,o,t=>Reflect.apply(n,e,t),r)}}(e,t,n)))(e,t,o.value):"function"==typeof o?.get?ke("get",e,t,Se,()=>o.get.call(e),(e=>{const t=je.get(e);if(void 0!==t)return t;const n=W(e);return je.set(e,n),n})(o.get)):Reflect.get(e,t,n)},Te={get:(e,t,n)=>Re(e,t,n,Object.getOwnPropertyDescriptor(e,t)),set(e,t,n){Ee(t);const r=se(e.constructor),o=pe(Object.getPrototypeOf(e),t),a="function"==typeof o?.set?o.set:void 0;if(r&&!a&&"string"==typeof t&&!t.startsWith("_"))throw new TypeError(`Cannot assign to property '${String(t)}': only properties starting with '_' or with a setter can be set on Contracted instances.`);if(!ae(e.constructor))return ze(e,t,n,a);let s=!0;return Oe("set",e,t,[n],n=>(s=ze(e,t,n[0],a),n[0]),!0),s},defineProperty(e,t,n){if(Ee(t),!se(e.constructor))return Reflect.defineProperty(e,t,n);if(("value"in n||"get"in n||"set"in n)&&"string"==typeof t&&!t.startsWith("_"))throw new TypeError(`Cannot define property '${String(t)}' on Contracted instances: only properties starting with '_' can be defined. A feature body may change its own state, but an external caller must go through a method or a setter.`);return Reflect.defineProperty(e,t,n)},setPrototypeOf(e,t){if(!se(e.constructor))return Reflect.setPrototypeOf(e,t);throw new TypeError("Cannot change the prototype of a Contracted instance: it would detach the instance from the features and contracts it was constructed with.")},preventExtensions:e=>Reflect.preventExtensions(e),deleteProperty(e,t){if(Ee(t),se(e.constructor)&&"string"==typeof t&&!t.startsWith("_"))throw new TypeError(`Cannot delete property '${String(t)}' from Contracted instances: only properties starting with '_' can be deleted.`);return ke("delete",e,t,[],()=>Reflect.deleteProperty(e,t),"sync")}};class Ce{static[Symbol.metadata];static _allowedConstructions=0;static[ne]=!0;static[re]=!0;static new(...e){const t=this._allowedConstructions;this._allowedConstructions=t+1;try{const t=new this(...e);return N(this,t),new Proxy(t,Te)}finally{this._allowedConstructions=t}}constructor(...e){const t=this.constructor;if(t._allowedConstructions<=0)throw new TypeError("Use the static 'new' method to instantiate this class.");t._allowedConstructions--}}var Ae;Ae=Ce.prototype,Object.defineProperty(Ae,C,{value:function(e,t,n){const r=null===e?1/0:e;if(r<0)return"[Object]";if(A.has(this))return"[Circular]";A.add(this);try{const e=T(Object.getPrototypeOf(this)?.constructor),o=Object.entries(Object.getOwnPropertyDescriptors(this)).filter(([,e])=>"value"in e).map(([e,t])=>[e,t.value]).map(([e,o])=>`${e}: ${n(o,{...t,depth:r-1})}`);return 0===o.length?`${e} {}`:`${e} { ${o.join(", ")} }`}finally{A.delete(this)}},enumerable:!1,writable:!0,configurable:!0});const We=Object.freeze([]),De=Object.freeze({invariants:We,demands:Object.freeze({}),ensures:Object.freeze({}),rescue:Object.freeze({}),classRescue:void 0}),_e=e=>Object.freeze({...e,...e.options?{options:Object.freeze({...e.options})}:{}}),Me=e=>Object.freeze({...e}),Ne=e=>{if(!e)return Object.freeze({});const t={};for(const n of Reflect.ownKeys(e))t[n]=Me(e[n]);return Object.freeze(t)},Ie=e=>{if(!e)return Object.freeze({});const t={};for(const n of Reflect.ownKeys(e))t[n]=Object.freeze(e[n].map(_e));return Object.freeze(t)};function Ve(e){const t=e[Symbol.metadata];return t?Object.freeze({invariants:Object.freeze((t.invariants??[]).map(_e)),demands:Ie(t.demands),ensures:Ie(t.ensures),rescue:Ne(t.rescue),classRescue:t.classRescue&&Me(t.classRescue)}):De}function Fe(e,t){const n=Ve(e),r=Z(n,t);return Object.freeze({demands:n.demands[t]??We,ensures:n.ensures[t]??We,rescue:r&&Me(r)})}const qe="toJSON",Be=e=>T(e),Ke=new WeakSet,Je=(e,t)=>{for(let n=e;n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e}},Ge=e=>function(){const t={},n=Object.getPrototypeOf(this);for(const r of e){const e=Je(n,r);e?.get&&(t[r]=e.get.call(this))}return t},Ue=(...e)=>(t,n)=>{if(D("@serializable",n),"class"!==n.kind)throw new TypeError("@serializable decorator can only be applied to classes");!function(e,t){if(null===e||"function"!=typeof e||!(e.prototype instanceof Ce))throw new TypeError("@serializable decorator can only be applied to classes that extend Contracted");if(0===t.length)throw new TypeError("@serializable was given no features, so it would publish an empty object for every instance. Name the getters to publish; a class that publishes nothing does not need the decorator.");if(Object.hasOwn(e.prototype,qe))throw new TypeError(Ke.has(e)?`${Be(e)} declares @serializable more than once, so two shapes were given for one class. Apply it once with the full list.`:`${Be(e)} already declares its own 'toJSON', so the shape it publishes is that method's and not the one @serializable was given. Remove one of the two.`)}(t,e);for(const n of e){const e=Je(t.prototype,n);if("function"!=typeof e?.get)throw new TypeError(`@serializable was given '${n}', which is not a getter on ${Be(t)}. Name the getters that describe the published shape; a field is storage rather than an observable.`)}Object.defineProperty(t.prototype,qe,{value:Ge(e),enumerable:!1,writable:!1,configurable:!1}),Ke.add(t)};export{e as AssertionError,Ce as Contracted,te as applyRescueHandler,b as assert,$ as assertContractResult,K as assertDemands,X as assertEnsures,N as assertInvariants,ne as checkedMode,R as contractName,ae as contractsEnabled,F as demands,O as describeViolation,re as encapsulationMode,U as ensures,Ve as getContractMetadata,Fe as getFeatureContracts,ee as getRescueDeclaration,z as iff,E as implies,I as invariant,Y as rescue,Ue as serializable,S as violationError,x as violationFailure};
|
|
1
|
+
Symbol.metadata??=Symbol.for("Symbol.metadata");class e extends Error{name="AssertionError";violation;constructor(e,t){super(e),this.violation=t}}const t=new WeakMap,n=e=>{const n=t.get(e);if(n)return n;const r=new Proxy(e,{set(e,t){throw new TypeError(`A contract predicate may not assign '${String(t)}'. Contract predicates answer a question; they must not change the state they are asked about.`)},deleteProperty(e,t){throw new TypeError(`A contract predicate may not delete '${String(t)}'. Contract predicates answer a question; they must not change the state they are asked about.`)},defineProperty(){throw new TypeError("A contract predicate may not define properties. Contract predicates answer a question; they must not change the state they are asked about.")}});return t.set(e,r),r},r=e=>"object"==typeof e&&null!==e&&"~standard"in e,o=e=>{if(r(e)){const{vendor:t,version:n}=e["~standard"];return`Standard Schema (vendor: ${String(t)}, version: ${String(n)})`}return String(e)},a=(e,t,n)=>{if(n?.normalize&&!r(e))throw new TypeError(`${t} cannot normalize: only a Standard Schema arm produces a replacement value.`)},s=(e,t,n)=>{if(n?.awaitPredicate&&r(e))throw new TypeError(`${t} cannot declare awaitPredicate on a schema arm: \`validate\` is evaluated synchronously, so there is no verdict to await.`)},i=(e,t)=>{if(void 0!==t?.onViolation&&"function"!=typeof t.onViolation)throw new TypeError(`${e} onViolation must be a function that returns an error object.`)},c=e=>{for(const{options:t}of e)if(t?.onViolation)return t.onViolation},u=(e,t)=>{if(t?.allowWeakening)throw new TypeError(`${e} cannot declare allowWeakening: only a precondition can be weakened, because only \`@demands\` is OR-composed. A subclass arm on an AND-composed contract strengthens the obligation and takes effect, so there is no warning to suppress.`)},l=new WeakMap,d=(e,t,n,o,a,s)=>r(e)?m(e,t.schema(),n,o,a,s):y(e,t.predicate(),n,o,a,s),f=async(e,t,n,o,a,s)=>{if(r(e))return m(e,t.schema(),n,o,a,s);const i=e,c=t.predicate();return s?.awaitPredicate?h(i,c,n,o,a):y(i,c,n,o,a,s)},h=async(e,t,n,r,o)=>{let a;try{a=await p(e,t)}catch(e){return{ok:!1,thrown:e}}return{ok:$(a,n,r,o)}},p=(e,t)=>e("object"==typeof t.self&&null!==t.self?{...t,self:n(t.self)}:t),y=(e,t,n,r,o,a)=>{let s;try{s=p(e,t)}catch(e){return{ok:!1,thrown:e}}if(a?.awaitPredicate&&"function"==typeof s?.then)throw new TypeError(`${n} predicate #${o+1} for ${r()} declared awaitPredicate but returned a Promise, and the feature it guards is not \`async\`, so nothing can await it. Declare the feature \`async\`, or drop the option.`);return{ok:$(s,n,r,o)}},m=(e,t,n,r,o,a)=>{const s=e["~standard"].validate(t);if("function"==typeof s?.then)throw new TypeError(`${n} schema #${o+1} for ${r()} returned a Promise; contract evaluation is synchronous, so use a synchronous schema.`);return s.issues?{ok:!1,issues:s.issues}:a?.normalize?{ok:!0,value:s.value}:{ok:!0}};class w{#e;record(e,t){((e,t,n)=>{e.failed.push(t),n.issues&&e.issues.push(...n.issues),"thrown"in n&&e.thrown.push({index:t,value:n.thrown})})(this.#e??={failed:[],thrown:[],issues:[]},e,t)}get entries(){return this.#e}}const g=()=>new w;function b(t,n="Assertion Error"){if(0==Boolean(t))throw new e(n)}const v=e=>"object"==typeof e&&null!==e&&"function"==typeof e.then?"a Promise (contract predicates must be synchronous)":"string"==typeof e?`the string ${JSON.stringify(e)}`:void 0===e?"undefined":null===e?"null":"object"==typeof e?`an object (${Object.prototype.toString.call(e)})`:`a ${typeof e} (${String(e)})`;function $(t,n,r,o){if("boolean"==typeof t)return t;throw new e(`${n} predicate #${o+1} for ${r()} returned ${v(t)}; contract predicates must return a boolean`)}function O(e,t,n,r,o,a,s,i=String,c){const u=c?.map(e=>e.index),l=c?.map(e=>(e=>{if("object"==typeof e&&null!==e){const t=e,n="string"==typeof t.name?t.name:e.constructor?.name??"Object",r="string"==typeof t.message?t.message:"";return r?`${n}: ${r}`:n}return String(e)})(e.value)),d={contract:e,className:t,feature:n,failedIndices:o,predicates:o.map(e=>i(r[e])),...u&&u.length>0?{thrownIndices:u,thrown:l}:{},...s&&s.length>0?{issues:s}:{}};return{message:j(e,d,r,a,s),violation:d}}const j=(e,t,n,o,a)=>{const s=void 0===t.feature?t.className:`${t.className}.${t.feature}`,i=new Set(t.thrownIndices??[]),c=((e,t,n,o)=>n.map((n,a)=>{const s=t[a];return`${r(e[s])?"schema":"predicate"} #${s+1}${o.has(s)?" threw":""}: ${n}`}).join("; "))(n,t.failedIndices,t.predicates,i);var u,l,d,f,h;return`${e} failed for ${s} (${l=t.failedIndices.length,d=n.length,u=n[0],f=r(u)?"schema":"predicate",h=(e=>r(e)?"schemas":"predicates")(n[0]),`${l} of ${d} ${1===d?f:h}`} unsatisfied: ${c}).${a&&a.length>0?` Reported: ${a.map(e=>(e=>{const t=(e.path??[]).map(e=>"object"==typeof e&&null!==e?e.key:e).join(".");return t?`${t}: ${e.message}`:e.message})(e)).join("; ")}.`:""} ${o}`};function S(t,n,r,o,a,s,i,c=String,u){const{message:l,violation:d}=O(t,n,r,o,a,s,i,c,u);return new e(l,d)}const P=new WeakSet,k=(e,t,n,r=!1)=>{if(!Object.isExtensible(e))return;const o=P.has(e),a=t=>!(o||!Object.hasOwn(e,t)||r&&"violation"===t&&void 0===e.violation);for(const[r,o]of[["violation",t],["cause",n]])a(r)||Object.defineProperty(e,r,{value:o,enumerable:!1,configurable:!0});P.add(e)};function x(e,t,n,r,o,a,s=String,i){const c=S(e,t,n,r,o.failed,a,o.issues,s,o.thrown),u=c.violation;if(i)return((e,t,n,r)=>{const o=r(t);if("object"!=typeof o||null===o)throw new TypeError(`${e} returned ${typeof o}; it must return an object so the violation can be attached.`,{cause:n});return k(o,t,n,!0),o})(`${e} onViolation for ${void 0===n?t:`${t}.${n}`}`,u,c,i);if(0===o.thrown.length)return c;const l=o.thrown[0].value;return"object"==typeof l&&null!==l&&k(l,u,c),l}function z(e,t){return Boolean(e&&t||!e&&!t)}function E(e,t){return!e||Boolean(t)}const R=Symbol.for("Contracted.contractName"),T=e=>{if("function"!=typeof e)return"";try{const t=Object.hasOwn(e,R)?e[R]:void 0;if("string"==typeof t&&t.length>0)return t}catch{}return e.name},C=Symbol.for("nodejs.util.inspect.custom"),A=new Set,W=e=>{switch(e.constructor.name){case"AsyncFunction":return"async";case"GeneratorFunction":return"generator";case"AsyncGeneratorFunction":return"async-generator";default:return"sync"}};function D(e,t){const n=t?.kind;b("string"==typeof n,`${e} was invoked without a standard decorator context, so it received no 'kind'. This happens when the compiler emits the pre-standard protocol, which \`experimentalDecorators\` selects. This library requires the TC39 protocol, so disable \`experimentalDecorators\` (and \`emitDecoratorMetadata\`), and make sure the build lowers decorator syntax rather than passing it through.`)}function _(e,t,n){D(e,n),b("method"===n.kind||"getter"===n.kind||"setter"===n.kind,`${e} decorator can only be applied to methods, getters, or setters`),b(!1===n.static,`${e} decorator cannot be applied to static features`),b(!1===n.private,`${e} decorator cannot be applied to private features`),b(!String(n.name).startsWith("_"),`${e} decorator cannot be applied to a '_'-prefixed feature`),n.addInitializer(function(){b(this instanceof Ce,`${e} decorator can only be applied to classes that extend Contracted`)})}function M(e,t,n,r){if(!r?.awaitPredicate)return;if("method"!==n.kind)throw new TypeError(`${e} cannot declare awaitPredicate on ${"getter"===n.kind?"a getter":"a setter"}: an accessor is read or assigned synchronously, so there is no promise a pending verdict could join.`);const o=W(t);if("async"!==o)throw new TypeError(`${e} cannot declare awaitPredicate on this feature: ${"generator"===o||"async-generator"===o?"a generator has one contract boundary per step, and awaiting a step would make every `next()` asynchronous rather than merely slower":"a synchronous feature has evaluated its contracts by the time the verdict could settle"}. The option is available on an \`async\` method only.`)}function N(e,t,n=ae(e)){if(!n)return;const r=e[Symbol.metadata]?.invariants??[];if(0===r.length)return;const a=()=>T(e),s=g();for(const[e,n]of r.entries()){const r=d(n.arm,{predicate:()=>({self:t}),schema:()=>t},"@invariant",a,e,n.options);r.ok||s.record(e,r)}if(void 0!==s.entries)throw x("@invariant",a(),void 0,r.map(e=>e.arm),s.entries,"The instance left the invariant unsatisfied.",o)}const I=(e,t)=>(n,r)=>{D("@invariant",r),((e,t)=>{if(t?.awaitPredicate)throw new TypeError("@invariant cannot declare awaitPredicate: an invariant is evaluated after construction and on every accessor read and write, where there is no promise a caller could await. Declare the option on the arm of an `async` feature instead.")})(0,t),((e,t)=>{if(t?.normalize)throw new TypeError("@invariant cannot normalize: its subject is the instance, which no arm can replace.")})(0,t),((e,t)=>{if(void 0!==t?.onViolation)throw new TypeError("@invariant cannot declare onViolation: its failure is what signals an unrecoverable instance, so it must stay an AssertionError. Translate it with a `@rescue` handler instead (which does not cover the check in `Contracted.new`).")})(0,t),u("@invariant",t);const{metadata:o}=r;b("class"===r.kind,"@invariant decorator can only be applied to classes"),b(n.prototype instanceof Ce,"@invariant decorator can only be applied to classes that extend Contracted");const a=o.invariants??[];o.invariants=[...a,{arm:e,options:t}]},V=Object.freeze([]),F=(e,t)=>(n,r)=>{_("@demands",0,r),M("@demands",n,r,t),s(e,"@demands",t),a(e,"@demands",t),i("@demands",t),((e,t)=>{const n=l.get(e);return!!n?.has(t)||(n?n.add(t):l.set(e,new Set([t])),!1)})(r.metadata,r.name)||((e,t,n,r)=>{if(0===n.length||r?.allowWeakening)return;const o=`@demands on ${t} adds an arm to a precondition that already has ${n.length} inherited arm(s). \`@demands\` is OR-composed, so this arm cannot narrow what the base permits: satisfying any inherited arm still allows the call. Move the restriction to the base feature, or declare the arm with \`allowWeakening\` if a genuine weakening is what was meant.`;console.warn(o)})(0,String(r.name),((e,t)=>{const n=Object.getPrototypeOf(e??{});return n?.demands?.[t]??[]})(r.metadata,r.name),t);const o=[...r.metadata?.demands?.[r.name]??[],{arm:e,options:t}];r.metadata.demands={...r.metadata?.demands??{},[r.name]:o}},q=(e,t)=>({predicate:()=>({self:e,args:t}),schema:()=>t});function B(e,t,n,r){throw x("@demands",t,String(n),e.map(e=>e.arm),r,"A precondition was not satisfied, so the feature was not entered.",o,c(e))}function K(e,t,n,r=ae(e.constructor)){if(!r)return n;const o=e.constructor,a=o[Symbol.metadata]?.demands?.[t]??V;if(0===a.length)return n;const s=()=>`${T(o)}.${String(t)}`,i=g();for(let t=0;t<a.length;t++){const{arm:r,options:o}=a[t],c=d(r,q(e,n),"@demands",s,t,o);if(c.ok)return void 0===c.value?n:c.value;i.record(t,c)}B(a,T(o),t,i.entries)}async function J(e,t,n,r=ae(e.constructor)){if(!r)return n;const o=e.constructor,a=o[Symbol.metadata]?.demands?.[t]??V;if(0===a.length)return n;const s=()=>`${T(o)}.${String(t)}`,i=g();for(let t=0;t<a.length;t++){const{arm:r,options:o}=a[t],c=await f(r,q(e,n),"@demands",s,t,o);if(c.ok)return void 0===c.value?n:c.value;i.record(t,c)}B(a,T(o),t,i.entries)}const G=Object.freeze([]),U=(e,t)=>(n,r)=>{_("@ensures",0,r),M("@ensures",n,r,t),s(e,"@ensures",t),a(e,"@ensures",t),i("@ensures",t),u("@ensures",t);const o=[...r.metadata?.ensures?.[r.name]??[],{arm:e,options:t}],c=o.filter(e=>e.options?.normalize);if(c.length>1)throw new TypeError(`@ensures for ${String(r.name)} declares ${c.length} normalizing arms; at most one arm may normalize the result, because they would disagree about what the caller receives.`);r.metadata.ensures={...r.metadata?.ensures??{},[r.name]:o}},H=(e,t,n,r,o)=>({predicate:()=>({self:e,args:t,old:n,oldArgs:r,result:o}),schema:()=>o});function L(e,t,n,r){throw x("@ensures",t,String(n),e.map(e=>e.arm),r,"A postcondition was not satisfied after the feature ran.",o,c(e))}const Q=(e,t,n,r)=>n.ok?void 0===n.value?r:n.value:(e.record(t,n),r);function X(e,t,n,r,o,a=[],s=ae(e.constructor)){if(!s)return o;const i=e.constructor,c=i[Symbol.metadata]?.ensures?.[n]??G;if(0===c.length)return o;const u=()=>`${T(i)}.${String(n)}`,l=g();let f=o;for(let n=0;n<c.length;n++){const s=c[n];f=Q(l,n,d(s.arm,H(e,r,t,a,o),"@ensures",u,n,s.options),f)}if(void 0===l.entries)return f;L(c,T(i),n,l.entries)}const Y=(e,t)=>(n,r)=>{if(D("@rescue",r),"class"===r.kind)return b(n.prototype instanceof Ce,"@rescue decorator can only be applied to classes that extend Contracted"),b(void 0===t?.maxRetries||t.maxRetries>=0,"maxRetries must not be negative"),void(r.metadata.classRescue={handler:e,maxRetries:t?.maxRetries});_("@rescue",0,r),b(void 0===t?.maxRetries||t.maxRetries>=0,"maxRetries must not be negative"),r.metadata.rescue={...r.metadata?.rescue??{},[r.name]:{handler:e,maxRetries:t?.maxRetries}},r.addInitializer(function(){b(this instanceof Ce,"@rescue decorator can only be applied to classes that extend Contracted")})},Z=(e,t)=>String(t).startsWith("_")?void 0:e?.rescue?.[t]??e?.classRescue;function ee(e,t){for(let n=e.constructor;n&&n!==Function.prototype;n=Object.getPrototypeOf(n)){const e=n[Symbol.metadata];if(!e)continue;const r=Z(e,t);if(r)return r}}const te=(e,t,n,r)=>{if(!ae(e.constructor))throw n;const o=ee(e,t);if(!o)throw n;let a=!1,s=[];if(o.handler.call(e,{self:e,error:n,args:r,retry:(...e)=>{b(!a,"retry can only be called once per rescue execution"),a=!0,s=e},feature:t}),!a)throw n;return s},ne=Symbol.for("Contracted.checkedMode"),re=Symbol.for("Contracted.encapsulationMode"),oe=(e,t)=>{for(let n=e;"function"==typeof n&&n!==Function.prototype;n=Object.getPrototypeOf(n))if(Object.hasOwn(n,t))return Boolean(n[t]);return!0},ae=e=>oe(e,ne),se=e=>oe(e,re),ie=(e,t)=>{if("object"!=typeof e||null===e)return e;const n=t.get(e);if(void 0!==n)return n;if(e instanceof Date)return new Date(e.getTime());const r=ce(e,t);if(void 0!==r)return r;if(!(e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t})(e))return e;const o=Object.create(Object.getPrototypeOf(e));return t.set(e,o),ue(e,o,t),o},ce=(e,t)=>{if(Array.isArray(e)){const n=[];t.set(e,n);for(const r of e)n.push(ie(r,t));return n}if(e instanceof Map){const n=new Map;t.set(e,n);for(const[r,o]of e)n.set(ie(r,t),ie(o,t));return n}if(e instanceof Set){const n=new Set;t.set(e,n);for(const r of e)n.add(ie(r,t));return n}},ue=(e,t,n)=>{for(const r of Reflect.ownKeys(e)){const o=Object.getOwnPropertyDescriptor(e,r),a="value"in o?{...o,value:ie(o.value,n)}:o;le(t,r,a)}},le=(e,t,n)=>{"value"in n&&n.writable&&n.enumerable&&n.configurable?e[t]=n.value:Reflect.defineProperty(e,t,n)},de=(e,t)=>{if(t)return(({target:e,entries:t})=>{const n=Object.create(e);for(const[e,r]of t)le(n,e,r);return n})(((e,t)=>{const n=[];for(const r of Reflect.ownKeys(e)){const o=Object.getOwnPropertyDescriptor(e,r);n.push([r,"value"in o?{...o,value:ie(o.value,t)}:o])}return{target:e,entries:n}})(e,new WeakMap))},fe=(e,t,n)=>e?((e,t)=>{const n=new WeakMap;return e.map((e,r)=>{try{return((e,t)=>{if("object"!=typeof e||null===e)return e;const n=t.get(e);if(void 0!==n)return n;if(!(e instanceof Ce))return ie(e,t);const r=Object.create(Object.getPrototypeOf(e));return t.set(e,r),ue(e,r,t),r})(e,n)}catch(e){throw new TypeError(`@ensures on '${String(t)}' cannot snapshot argument ${r}: a postcondition that describes an argument's pre-state needs every argument to be readable.`,{cause:e})}})})(t,n):void 0,he=new WeakMap;function pe(e,t){let n=e;for(;n&&n!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=Object.getPrototypeOf(n)}}const ye=(e,t,n)=>"get"===e?[t]:n,me=(e,t)=>"get"===e?[]:t,we=e=>"func"===e||"get"===e,ge=(t,n,r,o)=>{if((t=>t instanceof e&&"@invariant"===t.violation?.contract)(r))return r;try{N(t,n,o)}catch(t){return((t,n)=>(t instanceof e&&"object"==typeof n&&null!==n&&!Object.hasOwn(t,"cause")&&Object.defineProperty(t,"cause",{value:n,enumerable:!1,configurable:!0}),t))(t,r)}return r};function be(e,t,n,r,o,a,s){const i=ee(t,n);if(!i||o>=(i?.maxRetries??1/0))throw ge(e,t,r,s);try{return te(t,n,r,a)}catch(n){throw ge(e,t,n,s)}}function ve(e,t,n,r,o){for(let a=0;;)try{return void N(e,t,o)}catch(s){if(a++>0)throw s;r.args=be(e,t,n,s,r.retries,r.args,o),r.retries++}}function $e(e,t,n,r,o,a,s,i,c,u,l){if(!c)return N(e,n,l),a;const d=ye(t,a,o);if(!u){const t=X(n,s,r,d,a,i,l);return N(e,n,l),t}return async function(e,t,n,r){const o=await n;return N(e,t,r),o}(e,n,async function(e,t,n,r,o,a=[],s=ae(e.constructor)){if(!s)return o;const i=e.constructor,c=i[Symbol.metadata]?.ensures?.[n]??G;if(0===c.length)return o;const u=()=>`${T(i)}.${String(n)}`,l=g();let d=o;for(let n=0;n<c.length;n++){const s=c[n];d=Q(l,n,await f(s.arm,H(e,r,t,a,o),"@ensures",u,n,s.options),d)}if(void 0===l.entries)return d;L(c,T(i),n,l.entries)}(n,s,r,d,a,i,l),l)}function Oe(e,t,n,r,o,a,s="sync"){return"async"===s?async function(e,t,n,r,o,a){const s=t.constructor,i=s[Symbol.metadata]?.ensures?.[n]??[],c=i.length>0,u=function(e,t){const n=e.constructor;return(n[Symbol.metadata]?.demands?.[t]??V).some(e=>e.options?.awaitPredicate)}(t,n),l=function(e,t){const n=e.constructor;return(n[Symbol.metadata]?.ensures?.[t]??G).some(e=>e.options?.awaitPredicate)}(t,n);let d=r,f=0;for(;;){const r=Pe(i)?de(t,a):void 0,h={args:d,retries:f};ve(s,t,n,h,a),d=h.args,f=h.retries,d=u?await J(t,n,d,a):K(t,n,d,a);const p=fe(Pe(i),d,n);let y;try{y=await o(d);const i=$e(s,e,t,n,d,y,r,p,c,l,a);y=l?await i:i}catch(r){d=be(s,t,n,r,f,me(e,d),a),f++;continue}return y}}(e,t,n,r,o,a):"generator"===s||"async-generator"===s?function(e,t,n,r,o,a){const s=e.constructor,i=s[Symbol.metadata]?.ensures?.[t]??[],c=i.length>0;let u,l,d=n,f=0,h=!0;const p=n=>(N(s,e,a),h?(h=!1,K(e,t,d)):n.length>0?K(e,t,n):n),y=(n,r)=>{c&&X(e,r,t,[n],n,[],a),N(s,e,a),l=void 0},m=()=>{if(N(s,e,a),void 0===l)return;const t=l;throw l=void 0,t},w=n=>{d=be(s,e,t,n,f,d,a),f++,u=r(d),h=!0,l=n},g=(t,n)=>{for(;;)try{n=p(n);const r=Pe(i)?de(e,a):void 0,o=t(u,n);return o.done?(m(),o):(y(o.value,r),o)}catch(e){w(e)}},b=async(t,n)=>{for(;;)try{n=p(n);const r=Pe(i)?de(e,a):void 0,o=await t(u,n);return o.done?(m(),o):(y(o.value,r),o)}catch(e){w(e)}},v={args:d,retries:f};ve(s,e,t,v,a),d=v.args,f=v.retries,d=K(e,t,d),h=!1,u=r(d);const $={};return"generator"===o?($.next=function(...e){return g((e,t)=>e.next(t[0]),e)},$.return=function(...e){return g((t,n)=>t.return(e[0]??n[0]),[])},$.throw=function(...e){return g((t,n)=>t.throw(e[0]??n[0]),[])},$[Symbol.iterator]=function(){return this}):($.next=function(...e){return b((e,t)=>e.next(t[0]),e)},$.return=function(...e){return b((t,n)=>t.return(e[0]??n[0]),[])},$.throw=function(...e){return b((t,n)=>t.throw(e[0]??n[0]),[])},$[Symbol.asyncIterator]=function(){return this}),$}(t,n,r,o,s,a):function(e,t,n,r,o,a){const s=t.constructor,i=s[Symbol.metadata]?.ensures?.[n]??[],c=i.length>0;let u=r,l=0;for(;;){const r=Pe(i)?de(t,a):void 0,d={args:u,retries:l};ve(s,t,n,d,a),u=d.args,l=d.retries,u=K(t,n,u,a);const f=fe(Pe(i),u,n);let h;try{h=o(u),we(e)&&xe(h,t,n),c&&(h=X(t,r,n,ye(e,h,u),h,f,a)),N(s,t,a)}catch(r){u=be(s,t,n,r,l,me(e,u),a),l++;continue}return h}}(e,t,n,r,o,a)}const je=new WeakMap,Se=[],Pe=e=>{return e.length>0&&!((t=e).length>0&&t.every(e=>r(e.arm)));var t};function ke(e,t,n,r,o,a){const s=ae(t.constructor);return s?Oe(e,t,n,r,o,s,a):o(r)}const xe=(t,n,r)=>{if(null!==t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then)throw new e(`${T(n.constructor)}.${String(r)} returned a promise but is not declared 'async', so its contracts were evaluated before its body finished. Declare the feature 'async'.`)},ze=(e,t,n,r)=>r?(r.call(e,n),!0):Reflect.set(e,t,n),Ee=e=>{if((e=>e===ne||e===re)(e))throw new TypeError(`Cannot set '${String(e)}' on a Contracted instance: enforcement is switched on the class, not on an instance. Assign '${String(e)}' on the class itself.`)},Re=(e,t,n,r)=>{if("constructor"===t||r)return Reflect.get(e,t,n);const o=pe(Object.getPrototypeOf(e),t);return"function"==typeof o?.value?((e,t,n)=>he.get(e)?.get(t)??((e,t,n)=>{let r=he.get(e);return r||(r=new Map,he.set(e,r)),r.set(t,n),n})(e,t,function(e,t,n){const r=W(n);return function(...o){return ke("func",e,t,o,t=>Reflect.apply(n,e,t),r)}}(e,t,n)))(e,t,o.value):"function"==typeof o?.get?ke("get",e,t,Se,()=>o.get.call(e),(e=>{const t=je.get(e);if(void 0!==t)return t;const n=W(e);return je.set(e,n),n})(o.get)):Reflect.get(e,t,n)},Te={get:(e,t,n)=>Re(e,t,n,Object.getOwnPropertyDescriptor(e,t)),set(e,t,n){Ee(t);const r=se(e.constructor),o=pe(Object.getPrototypeOf(e),t),a="function"==typeof o?.set?o.set:void 0;if(r&&!a&&"string"==typeof t&&!t.startsWith("_"))throw new TypeError(`Cannot assign to property '${String(t)}': only properties starting with '_' or with a setter can be set on Contracted instances.`);if(!ae(e.constructor))return ze(e,t,n,a);let s=!0;return Oe("set",e,t,[n],n=>(s=ze(e,t,n[0],a),n[0]),!0),s},defineProperty(e,t,n){if(Ee(t),!se(e.constructor))return Reflect.defineProperty(e,t,n);if(("value"in n||"get"in n||"set"in n)&&"string"==typeof t&&!t.startsWith("_"))throw new TypeError(`Cannot define property '${String(t)}' on Contracted instances: only properties starting with '_' can be defined. A feature body may change its own state, but an external caller must go through a method or a setter.`);return Reflect.defineProperty(e,t,n)},setPrototypeOf(e,t){if(!se(e.constructor))return Reflect.setPrototypeOf(e,t);throw new TypeError("Cannot change the prototype of a Contracted instance: it would detach the instance from the features and contracts it was constructed with.")},preventExtensions:e=>Reflect.preventExtensions(e),deleteProperty(e,t){if(Ee(t),se(e.constructor)&&"string"==typeof t&&!t.startsWith("_"))throw new TypeError(`Cannot delete property '${String(t)}' from Contracted instances: only properties starting with '_' can be deleted.`);return ke("delete",e,t,[],()=>Reflect.deleteProperty(e,t),"sync")}};class Ce{static[Symbol.metadata];static _allowedConstructions=0;static[ne]=!0;static[re]=!0;static new(...e){const t=this._allowedConstructions;this._allowedConstructions=t+1;try{const t=new this(...e);return N(this,t),new Proxy(t,Te)}finally{this._allowedConstructions=t}}constructor(...e){const t=this.constructor;if(t._allowedConstructions<=0)throw new TypeError("Use the static 'new' method to instantiate this class.");t._allowedConstructions--}}var Ae;Ae=Ce.prototype,Object.defineProperty(Ae,C,{value:function(e,t,n){const r=null===e?1/0:e;if(r<0)return"[Object]";if(A.has(this))return"[Circular]";A.add(this);try{const e=T(Object.getPrototypeOf(this)?.constructor),o=Object.entries(Object.getOwnPropertyDescriptors(this)).filter(([,e])=>"value"in e).map(([e,t])=>[e,t.value]).map(([e,o])=>`${e}: ${n(o,{...t,depth:r-1})}`);return 0===o.length?`${e} {}`:`${e} { ${o.join(", ")} }`}finally{A.delete(this)}},enumerable:!1,writable:!0,configurable:!0});const We=Object.freeze([]),De=Object.freeze({invariants:We,demands:Object.freeze({}),ensures:Object.freeze({}),rescue:Object.freeze({}),classRescue:void 0}),_e=e=>Object.freeze({...e,...e.options?{options:Object.freeze({...e.options})}:{}}),Me=e=>Object.freeze({...e}),Ne=e=>{if(!e)return Object.freeze({});const t={};for(const n of Reflect.ownKeys(e))t[n]=Me(e[n]);return Object.freeze(t)},Ie=e=>{if(!e)return Object.freeze({});const t={};for(const n of Reflect.ownKeys(e))t[n]=Object.freeze(e[n].map(_e));return Object.freeze(t)};function Ve(e){const t=e[Symbol.metadata];return t?Object.freeze({invariants:Object.freeze((t.invariants??[]).map(_e)),demands:Ie(t.demands),ensures:Ie(t.ensures),rescue:Ne(t.rescue),classRescue:t.classRescue&&Me(t.classRescue)}):De}function Fe(e,t){const n=Ve(e),r=Z(n,t);return Object.freeze({demands:n.demands[t]??We,ensures:n.ensures[t]??We,rescue:r&&Me(r)})}const qe="toJSON",Be=e=>T(e),Ke=new WeakSet,Je=(e,t)=>{for(let n=e;n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e}},Ge=e=>function(){const t={},n=Object.getPrototypeOf(this);for(const r of e){const e=Je(n,r);e?.get&&(t[r]=e.get.call(this))}return t},Ue=(...e)=>(t,n)=>{if(D("@serializable",n),"class"!==n.kind)throw new TypeError("@serializable decorator can only be applied to classes");!function(e,t){if(null===e||"function"!=typeof e||!(e.prototype instanceof Ce))throw new TypeError("@serializable decorator can only be applied to classes that extend Contracted");if(0===t.length)throw new TypeError("@serializable was given no features, so it would publish an empty object for every instance. Name the getters to publish; a class that publishes nothing does not need the decorator.");if(Object.hasOwn(e.prototype,qe))throw new TypeError(Ke.has(e)?`${Be(e)} declares @serializable more than once, so two shapes were given for one class. Apply it once with the full list.`:`${Be(e)} already declares its own 'toJSON', so the shape it publishes is that method's and not the one @serializable was given. Remove one of the two.`)}(t,e);for(const n of e){const e=Je(t.prototype,n);if("function"!=typeof e?.get)throw new TypeError(`@serializable was given '${n}', which is not a getter on ${Be(t)}. Name the getters that describe the published shape; a field is storage rather than an observable.`)}Object.defineProperty(t.prototype,qe,{value:Ge(e),enumerable:!1,writable:!1,configurable:!1}),Ke.add(t)};export{e as AssertionError,Ce as Contracted,te as applyRescueHandler,b as assert,$ as assertContractResult,K as assertDemands,X as assertEnsures,N as assertInvariants,ne as checkedMode,R as contractName,ae as contractsEnabled,F as demands,O as describeViolation,re as encapsulationMode,U as ensures,Ve as getContractMetadata,Fe as getFeatureContracts,ee as getRescueDeclaration,z as iff,E as implies,I as invariant,Y as rescue,Ue as serializable,S as violationError,x as violationFailure};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|