@directive-run/core 1.23.0 → 1.24.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/{chunk-WVP3GOY2.js → chunk-C3FW27S5.js} +2 -2
- package/dist/chunk-C3FW27S5.js.map +1 -0
- package/dist/{chunk-PJIIBQTK.js → chunk-QR2756CJ.js} +2 -2
- package/dist/{chunk-PJIIBQTK.js.map → chunk-QR2756CJ.js.map} +1 -1
- package/dist/{chunk-AFPLATPV.js → chunk-SERVIHA3.js} +3 -3
- package/dist/{chunk-AFPLATPV.js.map → chunk-SERVIHA3.js.map} +1 -1
- package/dist/{chunk-FCCJUQB2.cjs → chunk-UDSP7U54.cjs} +3 -3
- package/dist/{chunk-FCCJUQB2.cjs.map → chunk-UDSP7U54.cjs.map} +1 -1
- package/dist/{chunk-WKGNK4QK.cjs → chunk-UQZ2SMGS.cjs} +2 -2
- package/dist/{chunk-WKGNK4QK.cjs.map → chunk-UQZ2SMGS.cjs.map} +1 -1
- package/dist/{chunk-XKXTRVJF.cjs → chunk-WU4AXN3P.cjs} +2 -2
- package/dist/chunk-WU4AXN3P.cjs.map +1 -0
- package/dist/{index-n8oQmdOZ.d.ts → index-Bz6DOdDN.d.ts} +3 -3
- package/dist/{index-DpvgHVHR.d.cts → index-Cpgj4byM.d.cts} +3 -3
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/internals.cjs +1 -1
- package/dist/internals.js +1 -1
- package/dist/plugins/index.cjs +2 -2
- package/dist/plugins/index.d.cts +1 -1
- package/dist/plugins/index.d.ts +1 -1
- package/dist/plugins/index.js +1 -1
- package/dist/system-T6EZ6EYN.js +2 -0
- package/dist/{system-HOP37Z4V.js.map → system-T6EZ6EYN.js.map} +1 -1
- package/dist/system-V7B4YUIR.cjs +2 -0
- package/dist/{system-VZUHL56W.cjs.map → system-V7B4YUIR.cjs.map} +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.js +1 -1
- package/dist/worker.cjs +1 -1
- package/dist/worker.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-WVP3GOY2.js.map +0 -1
- package/dist/chunk-XKXTRVJF.cjs.map +0 -1
- package/dist/system-HOP37Z4V.js +0 -2
- package/dist/system-VZUHL56W.cjs +0 -2
package/dist/index.d.cts
CHANGED
|
@@ -2,7 +2,7 @@ import { C as ClauseResult, F as FactPredicate, S as SchemaType, D as Definition
|
|
|
2
2
|
export { A as AnySystem, B as BatchConfig, t as Change, u as ChangeKind, v as ConstraintDefinition, w as ConstraintDiff, x as ConstraintStatus, y as ConstraintsDefinition, z as CrossModuleConstraintDefinition, G as CrossModuleEffectDefinition, H as DiffRulesOptions, I as DirectiveError, J as DistributableSnapshot, K as DistributableSnapshotOptions, L as DynamicConstraintDef, L as DynamicConstraintDefinition, O as DynamicEffectDef, Q as DynamicResolverDef, Q as DynamicResolverDefinition, U as EffectDefinition, V as EventsDefinition, W as FactTemplate, X as FactsSnapshot, Y as HistoryAPI, Z as HistoryOption, _ as HistoryState, $ as InferDerivations, a0 as InferEvents, a1 as InferFacts, a2 as InferRequirementTypes, a3 as InferRequirements, a4 as InferSchemaType, a5 as InferSelectorState, a6 as KeySelector, a7 as LeafClause, a8 as MetaAccessor, a9 as MetaMatch, aa as ObservationEvent, ab as OperatorObject, ac as PatchSpec, ad as PatchValue, ae as PayloadRef, af as PredicateClause, ag as PredicateCombinator, ah as PredicateCombinatorKey, ai as PredicateObject, aj as PredicateOp, ak as PredicateOverlapProof, al as ResolverAbortReason, am as ResolverDefinition, an as ResolversDefinition, ao as RetryPolicy, ap as RulesDiffReport, aq as RulesMapInput, ar as Schema, as as SchemaTypedResolversDefinition, at as ShouldRetryContext, au as Snapshot, av as SourceDef, av as SourceDefinition, aw as SourceDropReason, ax as SourcePublish, ax as SourcePublishFn, ay as SourceReportError, az as SourceUnsubscribe, az as SourceUnsubscribeFn, aA as System, aB as SystemConfig, aC as SystemDerived, aD as SystemFacts, aE as SystemInspection, aF as SystemMode, aG as SystemSnapshot, aH as TraceEntry, aI as TypedConstraintDefinition, aJ as TypedResolverDefinition, aK as diffClauses, aL as diffRules, aM as flattenPredicate, aN as isNamespacedSystem, aO as isSingleModuleSystem, aP as toRulesMap } from './plugins-CaPMTICa.cjs';
|
|
3
3
|
import { S as SchemaKindNode } from './predicate-CU0YC1i6.cjs';
|
|
4
4
|
export { D as DerivationDefWithMeta, a as DerivationDefinition, D as DerivationDefinitionWithMeta, b as DerivationsDefinition, c as SchemaKind, d as SchemaValidationError, e as SchemaValidationOptions, f as SchemaValidationResult, g as applyPatch, h as evaluateKeySelector, i as evaluatePredicate, j as evaluatePredicateExplained, k as evaluateTemplate, l as extractDeps, m as extractTemplateKeys, n as getKind, o as getOperatorsForKind, p as getSchemaFieldKinds, q as isPredicate, r as isTemplate, s as listAllPredicateOperators, t as memoizePredicate, u as typedConstraint, v as typedResolver, w as validatePredicate, x as validatePredicateAgainstSchema } from './predicate-CU0YC1i6.cjs';
|
|
5
|
-
export { A as AuditEntry, a as AuditEntryKind, b as AuditLedger, c as AuditLedgerOptions, d as AuditLedgerSink, Q as QueryFilter, V as VerifyResult, e as createAuditLedger, m as memorySink } from './index-
|
|
5
|
+
export { A as AuditEntry, a as AuditEntryKind, b as AuditLedger, c as AuditLedgerOptions, d as AuditLedgerSink, Q as QueryFilter, V as VerifyResult, e as createAuditLedger, m as memorySink } from './index-Cpgj4byM.cjs';
|
|
6
6
|
export { D as DistributableSnapshotLike, S as SignedSnapshot, a as SnapshotDiff, b as SnapshotDiffEntry, d as diffSnapshots, i as isSignedSnapshot, c as isSnapshotExpired, s as shallowEqual, e as signSnapshot, v as validateSnapshot, f as verifySnapshotSignature } from './utils-DY8KTiD6.cjs';
|
|
7
7
|
|
|
8
8
|
/**
|
|
@@ -1900,8 +1900,8 @@ declare function virtualClock(initialMs?: number): SignalClock;
|
|
|
1900
1900
|
* Returns `realClock()` always.
|
|
1901
1901
|
*
|
|
1902
1902
|
* Earlier drafts auto-detected vitest (`process.env.VITEST === 'true'`)
|
|
1903
|
-
* and returned a `virtualClock()` in that environment.
|
|
1904
|
-
*
|
|
1903
|
+
* and returned a `virtualClock()` in that environment. That behavior
|
|
1904
|
+
* turned out to be a footgun: tests that legitimately need real time
|
|
1905
1905
|
* (sleep-based debounce checks, real-`setTimeout`-bound integration
|
|
1906
1906
|
* fixtures) silently received a virtual clock that never advanced
|
|
1907
1907
|
* unless the test author called `advanceBy()`, producing apparent
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { C as ClauseResult, F as FactPredicate, S as SchemaType, D as Definition
|
|
|
2
2
|
export { A as AnySystem, B as BatchConfig, t as Change, u as ChangeKind, v as ConstraintDefinition, w as ConstraintDiff, x as ConstraintStatus, y as ConstraintsDefinition, z as CrossModuleConstraintDefinition, G as CrossModuleEffectDefinition, H as DiffRulesOptions, I as DirectiveError, J as DistributableSnapshot, K as DistributableSnapshotOptions, L as DynamicConstraintDef, L as DynamicConstraintDefinition, O as DynamicEffectDef, Q as DynamicResolverDef, Q as DynamicResolverDefinition, U as EffectDefinition, V as EventsDefinition, W as FactTemplate, X as FactsSnapshot, Y as HistoryAPI, Z as HistoryOption, _ as HistoryState, $ as InferDerivations, a0 as InferEvents, a1 as InferFacts, a2 as InferRequirementTypes, a3 as InferRequirements, a4 as InferSchemaType, a5 as InferSelectorState, a6 as KeySelector, a7 as LeafClause, a8 as MetaAccessor, a9 as MetaMatch, aa as ObservationEvent, ab as OperatorObject, ac as PatchSpec, ad as PatchValue, ae as PayloadRef, af as PredicateClause, ag as PredicateCombinator, ah as PredicateCombinatorKey, ai as PredicateObject, aj as PredicateOp, ak as PredicateOverlapProof, al as ResolverAbortReason, am as ResolverDefinition, an as ResolversDefinition, ao as RetryPolicy, ap as RulesDiffReport, aq as RulesMapInput, ar as Schema, as as SchemaTypedResolversDefinition, at as ShouldRetryContext, au as Snapshot, av as SourceDef, av as SourceDefinition, aw as SourceDropReason, ax as SourcePublish, ax as SourcePublishFn, ay as SourceReportError, az as SourceUnsubscribe, az as SourceUnsubscribeFn, aA as System, aB as SystemConfig, aC as SystemDerived, aD as SystemFacts, aE as SystemInspection, aF as SystemMode, aG as SystemSnapshot, aH as TraceEntry, aI as TypedConstraintDefinition, aJ as TypedResolverDefinition, aK as diffClauses, aL as diffRules, aM as flattenPredicate, aN as isNamespacedSystem, aO as isSingleModuleSystem, aP as toRulesMap } from './plugins-CaPMTICa.js';
|
|
3
3
|
import { S as SchemaKindNode } from './predicate-CgpwJqf4.js';
|
|
4
4
|
export { D as DerivationDefWithMeta, a as DerivationDefinition, D as DerivationDefinitionWithMeta, b as DerivationsDefinition, c as SchemaKind, d as SchemaValidationError, e as SchemaValidationOptions, f as SchemaValidationResult, g as applyPatch, h as evaluateKeySelector, i as evaluatePredicate, j as evaluatePredicateExplained, k as evaluateTemplate, l as extractDeps, m as extractTemplateKeys, n as getKind, o as getOperatorsForKind, p as getSchemaFieldKinds, q as isPredicate, r as isTemplate, s as listAllPredicateOperators, t as memoizePredicate, u as typedConstraint, v as typedResolver, w as validatePredicate, x as validatePredicateAgainstSchema } from './predicate-CgpwJqf4.js';
|
|
5
|
-
export { A as AuditEntry, a as AuditEntryKind, b as AuditLedger, c as AuditLedgerOptions, d as AuditLedgerSink, Q as QueryFilter, V as VerifyResult, e as createAuditLedger, m as memorySink } from './index-
|
|
5
|
+
export { A as AuditEntry, a as AuditEntryKind, b as AuditLedger, c as AuditLedgerOptions, d as AuditLedgerSink, Q as QueryFilter, V as VerifyResult, e as createAuditLedger, m as memorySink } from './index-Bz6DOdDN.js';
|
|
6
6
|
export { D as DistributableSnapshotLike, S as SignedSnapshot, a as SnapshotDiff, b as SnapshotDiffEntry, d as diffSnapshots, i as isSignedSnapshot, c as isSnapshotExpired, s as shallowEqual, e as signSnapshot, v as validateSnapshot, f as verifySnapshotSignature } from './utils-DY8KTiD6.js';
|
|
7
7
|
|
|
8
8
|
/**
|
|
@@ -1900,8 +1900,8 @@ declare function virtualClock(initialMs?: number): SignalClock;
|
|
|
1900
1900
|
* Returns `realClock()` always.
|
|
1901
1901
|
*
|
|
1902
1902
|
* Earlier drafts auto-detected vitest (`process.env.VITEST === 'true'`)
|
|
1903
|
-
* and returned a `virtualClock()` in that environment.
|
|
1904
|
-
*
|
|
1903
|
+
* and returned a `virtualClock()` in that environment. That behavior
|
|
1904
|
+
* turned out to be a footgun: tests that legitimately need real time
|
|
1905
1905
|
* (sleep-based debounce checks, real-`setTimeout`-bound integration
|
|
1906
1906
|
* fixtures) silently received a virtual clock that never advanced
|
|
1907
1907
|
* unless the test author called `advanceBy()`, producing apparent
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export{i as createAuditLedger,d as diffClauses,c as diffRules,f as doctor,b as flattenPredicate,h as memorySink,a as toRulesMap}from'./chunk-PJIIBQTK.js';import {a as a$2}from'./chunk-AFPLATPV.js';export{a as createSystem}from'./chunk-AFPLATPV.js';export{b as DirectiveError,o as RequirementSet,n as forType,k as generateRequirementId,h as isNamespacedSystem,m as isRequirementType,g as isSingleModuleSystem,l as req,e as typedConstraint,f as typedResolver}from'./chunk-WVP3GOY2.js';import {o,p as p$1,i as i$1,g,a as a$1,l,h,b}from'./chunk-LN5H74CU.js';export{v as applyPatch,u as evaluateKeySelector,o as evaluatePredicate,p as evaluatePredicateExplained,s as evaluateTemplate,r as extractDeps,t as extractTemplateKeys,c as getKind,e as getOperatorsForKind,d as getSchemaFieldKinds,h as isPredicate,k as isTemplate,f as listAllPredicateOperators,q as memoizePredicate,l as validatePredicate,n as validatePredicateAgainstSchema}from'./chunk-LN5H74CU.js';import {k}from'./chunk-WD47DB52.js';import {i,a}from'./chunk-IZNOPHPL.js';export{l as diffSnapshots,m as isSignedSnapshot,j as isSnapshotExpired,h as shallowEqual,n as signSnapshot,k as validateSnapshot,o as verifySnapshotSignature}from'./chunk-IZNOPHPL.js';var R=1e6;function $e(e,t){try{l(e);}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`[Directive] replayUnder: the ${t} predicate is invalid \u2014 ${i}`)}if(!h(e)){let r=e===null||typeof e!="object"?`${typeof e} \u2014 ${JSON.stringify(e)}`:JSON.stringify(e).slice(0,80);throw new Error(`[Directive] replayUnder: the ${t} predicate is not a valid FactPredicate (got ${r})`)}let n;if(i$1(e,{operator(r,i){n===void 0&&i.startsWith("$")&&!a$1.has(i)&&(n=i);},strayOperatorKey(r){n===void 0&&!a$1.has(r)&&!b.has(r)&&(n=r);}}),n!==void 0)throw new Error(`[Directive] replayUnder: the ${t} predicate uses an unknown operator "${n}" \u2014 known operators: ${[...a$1].join(", ")}`)}function be(e){if(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.snapshots))return Te(e);let t=Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.frames)?e.frames:null;if(!t)throw new Error("[Directive] toReplayFrames: history must be a JSON array of frames, an object with a `frames` array, or a history export with a `snapshots` array");if(t.length>R)throw new Error(`[Directive] toReplayFrames: history has ${t.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${R}) \u2014 split or down-sample the history`);return t.map((n,r)=>{if(n&&typeof n=="object"&&"facts"in n){let i=n,s={id:i.id??`#${r}`,facts:i.facts??{}};return typeof i.timestamp=="number"&&(s.timestamp=i.timestamp),s}return {id:`#${r}`,facts:n??{}}})}function Te(e){let t=typeof e=="string"?JSON.parse(e):e;if(Array.isArray(t))return ne(t);if(!t||typeof t!="object")throw new Error("[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())");let n=t;if(n.version!==void 0&&n.version!==1)throw new Error(`[Directive] framesFromHistory: unsupported history export version ${JSON.stringify(n.version)} \u2014 expected 1`);if(!Array.isArray(n.snapshots))throw new Error("[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())");return ne(n.snapshots)}function ne(e){if(!Array.isArray(e))throw new Error("[Directive] framesFromSnapshots: expected an array of fact-state snapshots");if(e.length>R)throw new Error(`[Directive] framesFromSnapshots: history has ${e.length} snapshots, exceeds the MAX_REPLAY_FRAMES limit (${R}) \u2014 split or down-sample the history`);for(let t=0;t<e.length;t++){let n=e[t];if(!n||typeof n!="object"||!("facts"in n))throw new Error(`[Directive] framesFromSnapshots: snapshot at index ${t} is not a { facts, ... } object`)}return be(e)}function U(e){let{frames:t,original:n,proposed:r,entityKey:i}=e,s=e.maxSamples??20,o$1=s>0?s:0;if(t.length>R)throw new Error(`[Directive] replayUnder: history has ${t.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${R}) \u2014 split or down-sample the history`);$e(n,"original"),$e(r,"proposed");let u=0,a=0,c=0,l=0,f=0,h=[],b=[],v=i?new Set:void 0,D=i?new Set:void 0,S;for(let O of t){let $=O.facts,T=o(n,$,S),k=o(r,$,S);T&&(u++,v?.add($[i])),k&&(a++,D?.add($[i])),T===k?f++:!T&&k?(c++,h.length<o$1&&h.push(we(O,n,r,S))):(l++,b.length<o$1&&b.push(we(O,n,r,S))),S=$;}let E={framesEvaluated:t.length,original:{matched:u},proposed:{matched:a},delta:a-u,newMatchCount:c,lostMatchCount:l,unchanged:f,newMatches:h,lostMatches:b};return v&&D&&(E.original.matchedEntities=v.size,E.proposed.matchedEntities=D.size),E}function we(e,t,n,r){let i=e.facts,s={frameId:e.id,facts:i,originalExplain:p$1(t,i,r),proposedExplain:p$1(n,i,r)};return e.timestamp!==void 0&&(s.timestamp=e.timestamp),s}var re=1e4,Se=5e7;function Pt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===1&&typeof e.$hole=="string"}function ie(e,t,n=new Set,r=0){if(r>g)throw new Error(`[Directive] sweepUnder: template exceeds MAX_PREDICATE_DEPTH (${g}) \u2014 flatten the template or split the sweep`);if(Pt(e)){let i=e.$hole;if(!(i in t))throw new Error(`[Directive] sweepUnder: template references hole "${i}" but sweep has no values for it`);return t[i]}if(e===null||typeof e!="object")return e;if(n.has(e))throw new Error("[Directive] sweepUnder: template contains a cycle \u2014 predicate templates must be a tree");n.add(e);try{if(Array.isArray(e))return e.map(s=>ie(s,t,n,r+1));let i={};for(let[s,o]of Object.entries(e))i[s]=ie(o,t,n,r+1);return i}finally{n.delete(e);}}function*Me(e,t){if(e.length===0){yield {};return}let n=e[0],r=e.slice(1),i=t[n]??[];for(let s of i)for(let o of Me(r,t))yield {[n]:s,...o};}function Ot(e){let t=1;for(let n of Object.values(e))t*=n.length;return t}function jt(e){let{frames:t,original:n,template:r,sweep:i,objective:s=$=>$.proposed.matched,entityKey:o,maxSamples:u=0}=e,a=Object.keys(i);if(a.length===0)throw new Error("[Directive] sweepUnder: `sweep` must contain at least one hole name");let c=Ot(i);if(c>re)throw new Error(`[Directive] sweepUnder: grid has ${c} points, exceeds the MAX_SWEEP_POINTS limit (${re}) \u2014 narrow the sweep ranges or split the run`);if(c===0)throw new Error("[Directive] sweepUnder: at least one hole has zero candidate values");let l=c*t.length;if(l>Se)throw new Error(`[Directive] sweepUnder: ${c} points \xD7 ${t.length} frames = ${l} per-frame evaluations, exceeds the MAX_SWEEP_EVALUATIONS limit (${Se}) \u2014 narrow the sweep, down-sample the history, or split the run`);let f=false,h=$=>{let T;try{T=s($);}catch(k){return f||(f=true,console.warn(`[Directive] sweepUnder: objective threw \u2014 point will not rank (${k.message})`)),Number.NEGATIVE_INFINITY}return typeof T!="number"||!Number.isFinite(T)?(f||(f=true,console.warn(`[Directive] sweepUnder: objective returned a non-finite number (${String(T)}) \u2014 point will not rank`)),Number.NEGATIVE_INFINITY):T},b=U({frames:t,original:n,proposed:n,entityKey:o,maxSamples:u}),v={values:{},report:b,score:h(b)},D=[],S=0,E=Number.NEGATIVE_INFINITY;for(let $ of Me(a,i)){let T=ie(r,$),k=U({frames:t,original:n,proposed:T,entityKey:o,maxSamples:u}),Z=h(k);Z>E&&(E=Z,S=D.length),D.push({values:$,report:k,score:Z});}let O=D[S];return {points:D,bestIndex:S,best:O,baseline:v}}function Ft(e){return i(e)}function B(e){return e===null?"null":e===void 0?"undefined":e instanceof Date?e.toISOString():typeof e=="string"||typeof e=="object"?JSON.stringify(e):String(e)}function _t(e){let t=e.path,n=B(e.expected),r=B(e.actual);switch(e.op){case "$eq":return `set ${t} to ${n} (currently ${r})`;case "$ne":return `change ${t} to anything other than ${n} (currently ${r})`;case "$gt":return `set ${t} above ${n} (currently ${r})`;case "$gte":return `set ${t} to at least ${n} (currently ${r})`;case "$lt":return `set ${t} below ${n} (currently ${r})`;case "$lte":return `set ${t} to at most ${n} (currently ${r})`;case "$in":return `set ${t} to one of ${n} (currently ${r})`;case "$nin":return `set ${t} to something other than ${n} (currently ${r})`;case "$exists":return e.expected===true?`set ${t} to a non-null value (currently null/missing)`:`unset ${t} (currently ${r})`;case "$between":return Array.isArray(e.expected)&&e.expected.length===2?`set ${t} between ${B(e.expected[0])} and ${B(e.expected[1])} (currently ${r})`:`set ${t} within range ${n} (currently ${r})`;case "$startsWith":return `set ${t} to start with ${n} (currently ${r})`;case "$endsWith":return `set ${t} to end with ${n} (currently ${r})`;case "$contains":return `set ${t} to contain ${n} (currently ${r})`;case "$matches":return `set ${t} to match the pattern ${n} (currently ${r})`;case "$changed":return `the previous-vs-current change of ${t} is required to differ (currently they match: ${r})`;case "$all":case "$any":case "$not":return `the ${e.op} group at "${t}" did not pass \u2014 see its child clauses`;default:return `clause at ${t} (${e.op}) failed: expected ${n}, got ${r}`}}function De(e,t){for(let n of e)if(!n.pass){if((n.op==="$all"||n.op==="$any"||n.op==="$not")&&n.children){De(n.children,t);continue}t.push({path:n.path,op:n.op,expected:n.expected,actual:n.actual,suggestion:_t(n)});}}function Nt(e,t,n){let r=p$1(e,t,n),i=r.every(o=>o.pass),s=[];if(i||De(r,s),!i&&n===void 0){let o=[];i$1(e,{operator(u,a){a==="$changed"&&o.push(u);}});for(let u of o)s.push({path:u,op:"$changed",expected:true,actual:void 0,suggestion:`$changed clause at "${u}" cannot be evaluated without a \`prev\` snapshot \u2014 pass predict(predicate, facts, prev).`});}return {wouldFire:i,whenExplain:r,missingChanges:s}}var j=new Map,It=50;function Lt(e){let t=j.get(e);if(!t){try{t=new Intl.NumberFormat(e);}catch{t=new Intl.NumberFormat("en-US");}if(j.size>=It){let n=j.keys().next().value;n!==void 0&&j.delete(n);}j.set(e,t);}return t}function qt(e,t={}){let n=t.style??"natural",r=t.parenthesize??true,i=t.locale??"en-US",s=t.factName??(a=>a);if(e===null||typeof e!="object")return "<invalid predicate>";let o={style:n,parenthesize:r,locale:i,factName:s,seen:new WeakSet,cycle:false},u=K(e,o,0);return o.cycle?"<invalid predicate: cycle>":u}var Re=" AND ",Wt=" OR ",Ut="NOT",Ee=" \u2227 ",Bt=" \u2228 ",Kt="\xAC";function _(e){return typeof e!="object"||e===null||Array.isArray(e)?false:!(e instanceof Date)&&!(e instanceof RegExp)}function zt(e){if(!_(e))return false;let t=Object.keys(e);if(t.length===0)return false;for(let n of t)if(!n.startsWith("$"))return false;return true}function K(e,t,n){if(n>g)return a&&console.warn(`[Directive] describePredicate: depth limit (${g}) exceeded \u2014 bailing.`),t.style==="formal"?"\u22A5":"always true";if(Array.isArray(e))return Ht(e,t);if(!_(e))return d(e,t);if(t.seen.has(e))return t.cycle=true,"<invalid predicate: cycle>";t.seen.add(e);let r=e,i=Object.keys(r);for(let o of ["$all","$any","$not"])if(o in r)return Qt(o,r[o],t,n);let s=[];for(let o of i)o.startsWith("$")||s.push(Ae(o,r[o],t,n));return z(s,t)}function Ht(e,t,n){let r=[];for(let i of e){if(!_(i))continue;let s=i;typeof s.fact!="string"||typeof s.op!="string"||r.push(F(s.fact,s.op,s.value,t));}return r.length===0?t.style==="formal"?"\u22A4":"always true":z(r,t)}function Qt(e,t,n,r){if(e==="$not"){if(_(t)&&Object.keys(t).length===0)return n.style==="formal"?"\u22A5":"never";let o=K(t,n,r+1);return o==="always true"?"never":o==="\u22A4"?"\u22A5":`${n.style==="formal"?Kt:`${Ut} `}(${o})`}if(!Array.isArray(t))return n.style==="formal"?"\u22A5":"<invalid predicate>";if(t.length===0)return e==="$all"?n.style==="formal"?"\u22A4":"always true":n.style==="formal"?"\u22A5":"never";let i=[];for(let o of t){let u=K(o,n,r+1);i.push(u);}if(i.length===1)return i[0];let s=n.parenthesize?i.map(o=>`(${o})`):i;return e==="$all"?s.join(n.style==="formal"?Ee:Re):s.join(n.style==="formal"?Bt:Wt)}function Ae(e,t,n,r){if(zt(t)){let i=t,s=Object.keys(i);if(s.length===1)return F(e,s[0],i[s[0]],n);let o=s.map(u=>F(e,u,i[u],n));return z(o,n)}if(_(t)){let i=t;if("$all"in i||"$any"in i||"$not"in i)return K(t,n,r+1);let o=[];for(let u of Object.keys(i))u.startsWith("$")||o.push(Ae(`${e}.${u}`,i[u],n,r+1));return o.length===0?F(e,"$eq",t,n):z(o,n)}return F(e,"$eq",t,n)}function F(e,t,n,r){let i=r.style==="formal"?e:r.factName(e);return r.style==="formal"?Xt(i,t,n,r):Jt(i,t,n,r)}function Jt(e,t,n,r){switch(t){case "$eq":return n===null?`${e} is null`:`${e} is ${d(n,r)}`;case "$ne":return n===null?`${e} is not null`:`${e} is not ${d(n,r)}`;case "$gt":return `${e} is more than ${d(n,r)}`;case "$gte":return `${e} is at least ${d(n,r)}`;case "$lt":return `${e} is less than ${d(n,r)}`;case "$lte":return `${e} is at most ${d(n,r)}`;case "$in":return `${e} is one of ${ke(n,r)}`;case "$nin":return `${e} is not one of ${ke(n,r)}`;case "$exists":return n===true?`${e} is set`:`${e} is not set`;case "$between":return Array.isArray(n)&&n.length===2?`${e} is between ${d(n[0],r)} and ${d(n[1],r)}`:`${e} is between ${d(n,r)}`;case "$startsWith":return `${e} starts with ${C(n,r,true)}`;case "$endsWith":return `${e} ends with ${C(n,r,true)}`;case "$contains":return `${e} contains ${C(n,r,true)}`;case "$matches":return n instanceof RegExp?`${e} matches ${n.toString()}`:`${e} matches ${d(n,r)}`;case "$changed":return `${e} changed`;default:return a&&!a$1.has(t)&&console.warn(`[Directive] describePredicate: unknown operator "${t}" \u2014 falling through to generic rendering.`),`${e} ${t} ${d(n,r)}`}}function Xt(e,t,n,r){switch(t){case "$eq":return `${e} = ${d(n,r)}`;case "$ne":return `${e} \u2260 ${d(n,r)}`;case "$gt":return `${e} > ${d(n,r)}`;case "$gte":return `${e} \u2265 ${d(n,r)}`;case "$lt":return `${e} < ${d(n,r)}`;case "$lte":return `${e} \u2264 ${d(n,r)}`;case "$in":return `${e} \u2208 {${ve(n,r)}}`;case "$nin":return `${e} \u2209 {${ve(n,r)}}`;case "$exists":return n===true?`\u2203 ${e}`:`\u2204 ${e}`;case "$between":return Array.isArray(n)&&n.length===2?`${d(n[0],r)} \u2264 ${e} \u2264 ${d(n[1],r)}`:`${e} \u2208 [${d(n,r)}]`;case "$startsWith":return `${e} ^= ${C(n,r,true)}`;case "$endsWith":return `${e} $= ${C(n,r,true)}`;case "$contains":return `${e} \u2287 ${C(n,r,true)}`;case "$matches":return n instanceof RegExp?`${e} ~ ${n.toString()}`:`${e} ~ ${d(n,r)}`;case "$changed":return `\u0394${e}`;default:return a&&!a$1.has(t)&&console.warn(`[Directive] describePredicate: unknown operator "${t}" \u2014 falling through to generic rendering.`),`${e} ${t} ${d(n,r)}`}}function H(e){return e.length===0?true:/[\s,"']/.test(e)}function C(e,t,n){return typeof e!="string"||n||H(e)?JSON.stringify(e):e}function d(e,t){if(e===null)return "null";if(e===void 0)return "undefined";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))return String(e);try{return Lt(t.locale).format(e)}catch{return String(e)}}if(typeof e=="bigint")return t.style==="formal"?`${e.toString()}n`:e.toString();if(typeof e=="string")return t.style==="formal"||H(e)?JSON.stringify(e):e;if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return `[${e.map(n=>d(n,t)).join(", ")}]`;if(typeof e=="object")try{return JSON.stringify(e)}catch{return "[object]"}return String(e)}function ke(e,t){return Array.isArray(e)?e.map(n=>typeof n=="string"?H(n)?JSON.stringify(n):n:d(n,t)).join(", "):d(e,t)}function ve(e,t){return Array.isArray(e)?e.map(n=>typeof n=="string"?H(n)?JSON.stringify(n):n:d(n,t)).join(", "):d(e,t)}function z(e,t){if(e.length===0)return t.style==="formal"?"\u22A4":"always true";if(e.length===1)return e[0];let n=t.style==="formal"?Ee:Re;return t.parenthesize,e.join(n)}var Zt=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?$/;function I(e,t){if(typeof e!="string"||!Zt.test(e))throw new Error(`[Directive] predicateToSQL: invalid ${t} identifier "${e}" \u2014 must match /^[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)?$/`)}function Ce(e,t){if(t&&!t.includes(e))throw new Error(`[Directive] predicateToSQL: column "${e}" is not in the allowedKeys list \u2014 add it to options.allowedKeys or remove it from the predicate`)}function Yt(e){if(Array.isArray(e)){if(e.length===0)throw new Error("[Directive] predicateToSQL: select must not be empty");for(let n of e)I(n,"column");return e.join(", ")}let t=e;return t==="*"?"*":(I(t,"column"),t)}function m(e,t){return e.params.push(t),e.placeholder(e.params.length)}function oe(e,t,n,r){switch(t){case "$eq":return `${e} = ${m(r,n)}`;case "$ne":return `${e} <> ${m(r,n)}`;case "$gt":return `${e} > ${m(r,n)}`;case "$gte":return `${e} >= ${m(r,n)}`;case "$lt":return `${e} < ${m(r,n)}`;case "$lte":return `${e} <= ${m(r,n)}`;case "$in":if(!Array.isArray(n))throw new Error("[Directive] predicateToSQL: $in operand must be an array");return `${e} = ANY(${m(r,n)})`;case "$nin":if(!Array.isArray(n))throw new Error("[Directive] predicateToSQL: $nin operand must be an array");return `NOT (${e} = ANY(${m(r,n)}))`;case "$exists":return n===true?`${e} IS NOT NULL`:`${e} IS NULL`;case "$between":{if(!Array.isArray(n)||n.length!==2)throw new Error("[Directive] predicateToSQL: $between operand must be a [low, high] tuple");return `${e} BETWEEN ${m(r,n[0])} AND ${m(r,n[1])}`}case "$startsWith":if(typeof n!="string")throw new Error("[Directive] predicateToSQL: $startsWith operand must be a string");return `${e} LIKE ${m(r,se(n))} || '%' ESCAPE '\\'`;case "$endsWith":if(typeof n!="string")throw new Error("[Directive] predicateToSQL: $endsWith operand must be a string");return `${e} LIKE '%' || ${m(r,se(n))} ESCAPE '\\'`;case "$contains":if(typeof n!="string")throw new Error("[Directive] predicateToSQL: $contains only supports string operands \u2014 array containment requires a JOIN, not a predicate");return `${e} LIKE '%' || ${m(r,se(n))} || '%' ESCAPE '\\'`;case "$matches":{if(!(n instanceof RegExp))throw new Error("[Directive] predicateToSQL: $matches operand must be a RegExp");let i=n.flags.includes("i")?"~*":"~";return `${e} ${i} ${m(r,n.source)}`}case "$changed":throw new Error('[Directive] predicateToSQL: $changed is an effects-only operator \u2014 no server-side translation (a database row has no "prev" snapshot)');default:throw new Error(`[Directive] predicateToSQL: unknown operator "${t}" \u2014 known: ${[...a$1].join(", ")}`)}}function se(e){return e.replace(/[\\%_]/g,"\\$&")}function xe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Gt(e){if(!xe(e))return false;let t=Object.keys(e);if(t.length===0)return false;for(let n of t)if(!n.startsWith("$"))return false;return true}function ae(e,t){let n=Object.keys(e).filter(r=>r!==t);if(n.length>0)throw new Error(`[Directive] predicateToSQL: ${t} cannot coexist with sibling keys (${n.join(", ")}) \u2014 wrap them in $all together, or move them inside the ${t} children`)}function N(e,t,n){if(n>g)throw new Error(`[Directive] predicateToSQL: predicate depth limit (${g}) exceeded \u2014 flatten the predicate or check for a cyclic spec object`);if(e===null||typeof e!="object")throw new Error(`[Directive] predicateToSQL: predicate must be an object or array, got ${typeof e}`);if(Array.isArray(e)){if(e.length===0)return "TRUE";let i=e.map(s=>{if(!s||typeof s!="object"||!("fact"in s)||!("op"in s))throw new Error("[Directive] predicateToSQL: array-form clause must be { fact, op, value }");let o=s;return I(o.fact,"column"),Ce(o.fact,t.allowed),oe(o.fact,o.op,o.value,t)});return i.length===1?i[0]:`(${i.join(" AND ")})`}if("$all"in e){ae(e,"$all");let i=e.$all;if(!Array.isArray(i))throw new Error("[Directive] predicateToSQL: $all must be an array");if(i.length===0)return "TRUE";let s=i.map(o=>N(o,t,n+1));return s.length===1?s[0]:`(${s.join(" AND ")})`}if("$any"in e){ae(e,"$any");let i=e.$any;if(!Array.isArray(i))throw new Error("[Directive] predicateToSQL: $any must be an array");if(i.length===0)return "FALSE";let s=i.map(o=>N(o,t,n+1));return s.length===1?s[0]:`(${s.join(" OR ")})`}if("$not"in e){ae(e,"$not");let i=e.$not;return `NOT (${N(i,t,n+1)})`}let r=[];for(let[i,s]of Object.entries(e))if(I(i,"column"),Ce(i,t.allowed),Gt(s))for(let[o,u]of Object.entries(s)){if(!a$1.has(o))throw new Error(`[Directive] predicateToSQL: unknown operator "${o}" on column "${i}" \u2014 known: ${[...a$1].join(", ")}`);r.push(oe(i,o,u,t));}else {if(xe(s))throw new Error(`[Directive] predicateToSQL: nested predicate at "${i}" \u2014 cross-module / partial-match predicates have no SQL equivalent (single-table queries only in v1; pass a flat predicate or build JOIN by hand with predicateToWhere)`);r.push(oe(i,"$eq",s,t));}return r.length===0?"TRUE":r.length===1?r[0]:`(${r.join(" AND ")})`}var Pe=e=>`$${e}`;function Vt(e,t){let{table:n,allowedKeys:r}=t,i=t.placeholder??Pe,s=t.select??"*";I(n,"table");let o=Yt(s),u={params:[],placeholder:i,allowed:r},a=N(e,u,0);return {sql:`SELECT ${o} FROM ${n} WHERE ${a}`,where:a,params:u.params}}function en(e,t={}){let n=t.placeholder??Pe,r={params:[],placeholder:n,allowed:t.allowedKeys};return {where:N(e,r,0),params:r.params}}function ue(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function le(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tn(e){if(!le(e))return false;let t=Object.keys(e);if(t.length===0)return false;for(let n of t)if(!n.startsWith("$"))return false;return true}var nn=/^[A-Za-z_][A-Za-z0-9_]*$/,rn=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/;function Oe(e,t){if(typeof e!="string"||e.length===0)throw new Error(`[Directive] predicateToMongo: field name must be a non-empty string, got ${typeof e}`);if(e.startsWith("$"))throw new Error(`[Directive] predicateToMongo: field name "${e}" starts with "$" \u2014 reserved for Mongo operators (a top-level $where would be an injection vector)`);if(!(t.allowDottedPaths?rn:nn).test(e))throw new Error(`[Directive] predicateToMongo: invalid field name "${e}"${t.allowDottedPaths?"":' \u2014 pass options.allowDottedPaths=true to permit sub-document paths like "user.role"'}`)}function je(e,t){if(t&&!t.includes(e))throw new Error(`[Directive] predicateToMongo: field "${e}" is not in the allowedKeys list \u2014 add it to options.allowedKeys or remove it from the predicate`)}function ce(e,t){let n=Object.keys(e).filter(r=>r!==t);if(n.length>0)throw new Error(`[Directive] predicateToMongo: ${t} cannot coexist with sibling keys (${n.join(", ")}) \u2014 wrap them in $all together, or move them inside the ${t} children`)}function Fe(e,t){switch(e){case "$eq":case "$ne":case "$gt":case "$gte":case "$lt":case "$lte":case "$in":case "$nin":case "$exists":return {[e]:t};case "$between":{if(!Array.isArray(t)||t.length!==2)throw new Error("[Directive] predicateToMongo: $between operand must be a [low, high] tuple");return {$gte:t[0],$lte:t[1]}}case "$startsWith":if(typeof t!="string")throw new Error("[Directive] predicateToMongo: $startsWith operand must be a string");return {$regex:`^${ue(t)}`};case "$endsWith":if(typeof t!="string")throw new Error("[Directive] predicateToMongo: $endsWith operand must be a string");return {$regex:`${ue(t)}$`};case "$contains":if(typeof t=="string")return {$regex:ue(t)};throw new Error("[Directive] predicateToMongo: $contains in Mongo expects a string operand \u2014 for array element membership use $elemMatch or $in directly");case "$matches":{if(t instanceof RegExp)return t.flags?{$regex:t.source,$options:t.flags}:{$regex:t.source};if(typeof t=="string")return {$regex:t};throw new Error("[Directive] predicateToMongo: $matches operand must be a RegExp or string")}case "$changed":throw new Error("[Directive] predicateToMongo: $changed is an effects-only operator \u2014 no MongoDB query equivalent");default:throw new Error(`[Directive] predicateToMongo: unknown operator "${e}" \u2014 known: ${[...a$1].join(", ")}`)}}function x(e,t,n){if(n>g)throw new Error(`[Directive] predicateToMongo: predicate depth limit (${g}) exceeded \u2014 flatten the predicate or check for a cyclic spec object`);if(e===null||typeof e!="object")throw new Error(`[Directive] predicateToMongo: predicate must be an object or array, got ${typeof e}`);if(Array.isArray(e)){if(e.length===0)return {};let i={},s=[];for(let o of e){if(!o||typeof o!="object"||!("fact"in o)||!("op"in o))throw new Error("[Directive] predicateToMongo: array-form clause must be { fact, op, value }");let u=o;Oe(u.fact,t),je(u.fact,t.allowedKeys);let a=Fe(u.op,u.value);if(u.fact in i&&le(i[u.fact])){let c=i[u.fact];Object.keys(a).some(f=>f in c)?s.push({[u.fact]:a}):i[u.fact]={...c,...a};}else u.fact in i?s.push({[u.fact]:a}):i[u.fact]=a;}if(s.length>0){let o=[];for(let[u,a]of Object.entries(i))o.push({[u]:a});return o.push(...s),{$and:o}}return i}if("$all"in e){ce(e,"$all");let i=e.$all;if(!Array.isArray(i))throw new Error("[Directive] predicateToMongo: $all must be an array");return i.length===0?{}:i.length===1?x(i[0],t,n+1):{$and:i.map(s=>x(s,t,n+1))}}if("$any"in e){ce(e,"$any");let i=e.$any;if(!Array.isArray(i))throw new Error("[Directive] predicateToMongo: $any must be an array");return i.length===0?{$expr:{$eq:[1,0]}}:i.length===1?x(i[0],t,n+1):{$or:i.map(s=>x(s,t,n+1))}}if("$not"in e){ce(e,"$not");let i=e.$not;return {$nor:[x(i,t,n+1)]}}let r={};for(let[i,s]of Object.entries(e))if(Oe(i,t),je(i,t.allowedKeys),tn(s)){let o={};for(let[u,a]of Object.entries(s)){if(!a$1.has(u))throw new Error(`[Directive] predicateToMongo: unknown operator "${u}" on field "${i}" \u2014 known: ${[...a$1].join(", ")}`);Object.assign(o,Fe(u,a));}r[i]=o;}else r[i]=s;return r}function on(e,t={}){return x(e,t,0)}var sn=/^[A-Za-z_][A-Za-z0-9_]*$/;function _e(e,t){if(typeof e!="string"||!sn.test(e))throw new Error(`[Directive] predicateToPostgrest: invalid column identifier "${e}"`);if(t&&!t.includes(e))throw new Error(`[Directive] predicateToPostgrest: column "${e}" is not in the allowedKeys list \u2014 add it to options.allowedKeys or remove it from the predicate`)}function fe(e,t){let n=Object.keys(e).filter(r=>r!==t);if(n.length>0)throw new Error(`[Directive] predicateToPostgrest: ${t} cannot coexist with sibling keys (${n.join(", ")}) \u2014 wrap them in $all together, or move them inside the ${t} children`)}function w(e){if(e==null)return "null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"||typeof e=="bigint")return String(e);if(e instanceof Date)return e.toISOString();if(typeof e=="string")return /[,.():"\\\s]/.test(e)?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e;throw new Error(`[Directive] predicateToPostgrest: cannot encode value of type ${typeof e}`)}function Ne(e){return `(${e.map(w).join(",")})`}function de(e){return e.replace(/[\\%_*]/g,"\\$&")}function P(e,t){switch(e){case "$eq":return `eq.${w(t)}`;case "$ne":return `neq.${w(t)}`;case "$gt":return `gt.${w(t)}`;case "$gte":return `gte.${w(t)}`;case "$lt":return `lt.${w(t)}`;case "$lte":return `lte.${w(t)}`;case "$in":if(!Array.isArray(t))throw new Error("[Directive] predicateToPostgrest: $in operand must be an array");return `in.${Ne(t)}`;case "$nin":if(!Array.isArray(t))throw new Error("[Directive] predicateToPostgrest: $nin operand must be an array");return `not.in.${Ne(t)}`;case "$exists":return t===true?"not.is.null":"is.null";case "$startsWith":if(typeof t!="string")throw new Error("[Directive] predicateToPostgrest: $startsWith operand must be a string");return `like.${w(`${de(t)}*`)}`;case "$endsWith":if(typeof t!="string")throw new Error("[Directive] predicateToPostgrest: $endsWith operand must be a string");return `like.${w(`*${de(t)}`)}`;case "$contains":if(typeof t!="string")throw new Error("[Directive] predicateToPostgrest: $contains expects a string operand (array containment is the cs operator with a different shape \u2014 out of scope for v1)");return `like.${w(`*${de(t)}*`)}`;case "$matches":if(t instanceof RegExp)return `${t.flags.includes("i")?"imatch":"match"}.${w(t.source)}`;if(typeof t=="string")return `match.${w(t)}`;throw new Error("[Directive] predicateToPostgrest: $matches operand must be a RegExp or string");case "$changed":throw new Error("[Directive] predicateToPostgrest: $changed is an effects-only operator \u2014 no server query equivalent");default:throw new Error(`[Directive] predicateToPostgrest: unknown operator "${e}" \u2014 known: ${[...a$1].join(", ")}`)}}function Ie(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function an(e){if(!Ie(e))return false;let t=Object.keys(e);if(t.length===0)return false;for(let n of t)if(!n.startsWith("$"))return false;return true}function pe(e,t){return `${e}=${t}`}function Q(e,t){return `${e}=(${t.join(",")})`}function ge(e,t,n,r){if(t==="$between"){if(!Array.isArray(n)||n.length!==2)throw new Error("[Directive] predicateToPostgrest: $between operand must be a [low, high] tuple");let i=r?pe(e,P("$gte",n[0])):`${e}.${P("$gte",n[0])}`,s=r?pe(e,P("$lte",n[1])):`${e}.${P("$lte",n[1])}`;return [i,s]}return [r?pe(e,P(t,n)):`${e}.${P(t,n)}`]}function L(e,t,n,r){if(r>g)throw new Error(`[Directive] predicateToPostgrest: predicate depth limit (${g}) exceeded \u2014 flatten the predicate or check for a cyclic spec object`);if(e===null||typeof e!="object")throw new Error("[Directive] predicateToPostgrest: predicate must be an object or array");if(Array.isArray(e)){let s=[];for(let o of e){if(!o||typeof o!="object"||!("fact"in o)||!("op"in o))throw new Error("[Directive] predicateToPostgrest: array-form clause must be { fact, op, value }");let u=o;_e(u.fact,t),s.push(...ge(u.fact,u.op,u.value,n));}return s}if("$all"in e){fe(e,"$all");let s=e.$all;if(!Array.isArray(s))throw new Error("[Directive] predicateToPostgrest: $all must be an array");if(n){let u=[];for(let a of s)u.push(...L(a,t,true,r+1));return u}let o=[];for(let u of s)o.push(...L(u,t,false,r+1));return [Q("and",o)]}if("$any"in e){fe(e,"$any");let s=e.$any;if(!Array.isArray(s))throw new Error("[Directive] predicateToPostgrest: $any must be an array");if(s.length===0)return n?["id=is.null","id=not.is.null"]:[Q("and",["id.is.null","id.not.is.null"])];let o=[];for(let u of s)o.push(...L(u,t,false,r+1));return [Q("or",o)]}if("$not"in e){fe(e,"$not");let s=e.$not,o=L(s,t,false,r+1);return [Q("not.and",o)]}let i=[];for(let[s,o]of Object.entries(e))if(_e(s,t),an(o))for(let[u,a]of Object.entries(o)){if(!a$1.has(u))throw new Error(`[Directive] predicateToPostgrest: unknown operator "${u}" on column "${s}" \u2014 known: ${[...a$1].join(", ")}`);i.push(...ge(s,u,a,n));}else {if(Ie(o))throw new Error(`[Directive] predicateToPostgrest: nested predicate at "${s}" \u2014 single-table queries only`);i.push(...ge(s,"$eq",o,n));}return i}function un(e){let t=e.indexOf("=");if(t<0)return encodeURIComponent(e);let n=e.slice(0,t),r=e.slice(t+1);return `${n}=${encodeURIComponent(r)}`}function cn(e,t={}){let n=t.mode??"querystring",r=L(e,t.allowedKeys,true,0);return r.length===0?"":n==="raw"?r.join("&"):r.map(un).join("&")}function J(e=[],t,n,r,i,s,o){return {_type:void 0,_validators:e,_typeName:t,_default:n,_transform:r,_description:i,_refinements:s,_meta:o,validate(u){return J([...e,u],t,n,r,i,s,o)}}}function p(e,t,n,r,i,s,o){return {...J(e,t,n,r,i,s,o),default(a){return p(e,t,a,r,i,s,o)},transform(a){return p([],t,void 0,l=>{let f=r?r(l):l;return a(f)},i,void 0,o)},brand(){return p(e,`Branded<${t}>`,n,r,i,s,o)},describe(a){return p(e,t,n,r,a,s,o)},refine(a,c){let l=[...s??[],{predicate:a,message:c}];return p([...e,a],t,n,r,i,l,o)},nullable(){return p([a=>a===null||e.every(c=>c(a))],`${t} | null`,n,r,i,void 0,o)},optional(){return p([a=>a===void 0||e.every(c=>c(a))],`${t} | undefined`,n,r,i,void 0,o)},meta(a){return p(e,t,n,r,i,s,a)}}}var ln=((...e)=>{if(e.length===0)return p([],"union");let t=e.map(n=>n._typeName??"unknown");return p([n=>e.some(r=>r._validators.every(i=>i(n)))],t.join(" | "))}),fn={string(){let e=(t,n,r,i,s,o)=>({...p(t,"string",n,r,i,s,o),minLength(a){return e([...t,c=>c.length>=a],n,r,i,s,o)},maxLength(a){return e([...t,c=>c.length<=a],n,r,i,s,o)},pattern(a){return e([...t,c=>a.test(c)],n,r,i,s,o)},default(a){return e(t,a,r,i,s,o)},describe(a){return e(t,n,r,a,s,o)},refine(a,c){let l=[...s??[],{predicate:a,message:c}];return e([...t,a],n,r,i,l,o)},meta(a){return e(t,n,r,i,s,a)}});return e([t=>typeof t=="string"])},number(){let e=(t,n,r,i,s,o)=>({...p(t,"number",n,r,i,s,o),min(a){return e([...t,c=>c>=a],n,r,i,s,o)},max(a){return e([...t,c=>c<=a],n,r,i,s,o)},default(a){return e(t,a,r,i,s,o)},describe(a){return e(t,n,r,a,s,o)},refine(a,c){let l=[...s??[],{predicate:a,message:c}];return e([...t,a],n,r,i,l,o)},meta(a){return e(t,n,r,i,s,a)}});return e([t=>typeof t=="number"])},boolean(){return p([e=>typeof e=="boolean"],"boolean")},array(){let e=(t,n,r,i,s,o)=>{let u=p(t,"array",r,void 0,i,void 0,o),a=s??{value:-1};return {...u,get _lastFailedIndex(){return a.value},set _lastFailedIndex(l){a.value=l;},of(l){let f={value:-1};return e([...t,h=>{for(let b=0;b<h.length;b++)if(!l._validators.every(v=>v(h[b])))return f.value=b,false;return true}],l,r,i,f,o)},nonEmpty(){return e([...t,l=>l.length>0],n,r,i,a,o)},maxLength(l){return e([...t,f=>f.length<=l],n,r,i,a,o)},minLength(l){return e([...t,f=>f.length>=l],n,r,i,a,o)},default(l){return e(t,n,l,i,a,o)},describe(l){return e(t,n,r,l,a,o)},meta(l){return e(t,n,r,i,a,l)}}};return e([t=>Array.isArray(t)])},object(){let e=(t,n,r,i)=>({...p(t,"object",n,void 0,r,void 0,i),shape(o){return e([...t,u=>{for(let[a,c]of Object.entries(o)){let l=u[a],f=c;if(f&&!f._validators.every(h=>h(l)))return false}return true}],n,r,i)},nonNull(){return e([...t,o=>o!=null],n,r,i)},hasKeys(...o){return e([...t,u=>o.every(a=>a in u)],n,r,i)},default(o){return e(t,o,r,i)},describe(o){return e(t,n,o,i)},meta(o){return e(t,n,r,o)}});return e([t=>typeof t=="object"&&t!==null&&!Array.isArray(t)])},enum(...e){a&&e.length===0&&console.warn("[Directive] t.enum() called with no values - this will reject all strings");let t=new Set(e);return p([n=>typeof n=="string"&&t.has(n)],`enum(${e.join("|")})`)},literal(e){return p([t=>t===e],`literal(${String(e)})`)},nullable(e){let t=e._typeName??"unknown";return J([n=>n===null?true:e._validators.every(r=>r(n))],`${t} | null`)},optional(e){let t=e._typeName??"unknown";return J([n=>n===void 0?true:e._validators.every(r=>r(n))],`${t} | undefined`)},union:ln,record(e){let t=e._typeName??"unknown";return p([n=>typeof n!="object"||n===null||Array.isArray(n)?false:Object.values(n).every(r=>e._validators.every(i=>i(r)))],`Record<string, ${t}>`)},tuple(...e){a&&e.length===0&&console.warn("[Directive] t.tuple() called with no types - this will only accept empty arrays");let t=e.map(n=>n._typeName??"unknown");return p([n=>!Array.isArray(n)||n.length!==e.length?false:e.every((r,i)=>r._validators.every(s=>s(n[i])))],`[${t.join(", ")}]`)},date(){return p([e=>e instanceof Date&&!Number.isNaN(e.getTime())],"Date")},uuid(){let e=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;return p([t=>typeof t=="string"&&e.test(t)],"uuid")},email(){let e=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return p([t=>typeof t=="string"&&e.test(t)],"email")},url(){return p([e=>{if(typeof e!="string")return false;try{return new URL(e),!0}catch{return false}}],"url")},bigint(){return p([e=>typeof e=="bigint"],"bigint")},any(){return p([],"any")},unknown(){return p([],"unknown")}};function dn(e){if(!e||typeof e!="string"){console.warn("[Directive] Module ID must be a non-empty string");return}/^(__[a-z][a-z0-9_-]*|[a-z][a-z0-9-]*)$/i.test(e)||console.warn(`[Directive] Module ID "${e}" should follow kebab-case convention (e.g., "my-module")`);}function Le(e,t,n,r,i){for(let s of e)t.has(s)||console.warn(`[Directive] ${n} "${s}" not declared in ${r}`);for(let s of t)e.has(s)||console.warn(`[Directive] ${r}["${s}"] ${i}`);}function pn(e,t){e.length===0&&console.warn("[Directive] history.snapshotEvents is an empty array \u2014 no events will create history snapshots. Omit history.snapshotEvents entirely to snapshot all events, or list specific events.");let n=new Set(Object.keys(t));for(let r of e)n.has(r)||console.warn(`[Directive] history.snapshotEvents entry "${r}" not declared in schema.events. Available events: ${[...n].join(", ")||"(none)"}`);}function gn(e,t){let n=new Set(Object.keys(t));for(let[r,i]of Object.entries(e)){let s=i;typeof s.requirement=="string"&&!n.has(s.requirement)&&console.warn(`[Directive] Resolver "${r}" references unknown requirement type "${s.requirement}". Available types: ${[...n].join(", ")||"(none)"}`);}}function yn(e,t){let n=t.schema?.facts??{},r=Object.keys(n);if(r.length===0)return;let i=new Set(["self","prev","current"]),s="crossModuleDeps"in t&&t.crossModuleDeps?Object.keys(t.crossModuleDeps):[];for(let o of s)i.add(o);for(let o of r)if(i.has(o))throw new Error(`[Directive] module '${e}': fact key '${o}' conflicts with a reserved namespace pivot or evaluation alias (self / prev / current / a crossModuleDep namespace). Three fixes:
|
|
1
|
+
export{i as createAuditLedger,d as diffClauses,c as diffRules,f as doctor,b as flattenPredicate,h as memorySink,a as toRulesMap}from'./chunk-QR2756CJ.js';import {a as a$2}from'./chunk-SERVIHA3.js';export{a as createSystem}from'./chunk-SERVIHA3.js';export{b as DirectiveError,o as RequirementSet,n as forType,k as generateRequirementId,h as isNamespacedSystem,m as isRequirementType,g as isSingleModuleSystem,l as req,e as typedConstraint,f as typedResolver}from'./chunk-C3FW27S5.js';import {o,p as p$1,i as i$1,g,a as a$1,l,h,b}from'./chunk-LN5H74CU.js';export{v as applyPatch,u as evaluateKeySelector,o as evaluatePredicate,p as evaluatePredicateExplained,s as evaluateTemplate,r as extractDeps,t as extractTemplateKeys,c as getKind,e as getOperatorsForKind,d as getSchemaFieldKinds,h as isPredicate,k as isTemplate,f as listAllPredicateOperators,q as memoizePredicate,l as validatePredicate,n as validatePredicateAgainstSchema}from'./chunk-LN5H74CU.js';import {k}from'./chunk-WD47DB52.js';import {i,a}from'./chunk-IZNOPHPL.js';export{l as diffSnapshots,m as isSignedSnapshot,j as isSnapshotExpired,h as shallowEqual,n as signSnapshot,k as validateSnapshot,o as verifySnapshotSignature}from'./chunk-IZNOPHPL.js';var R=1e6;function $e(e,t){try{l(e);}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`[Directive] replayUnder: the ${t} predicate is invalid \u2014 ${i}`)}if(!h(e)){let r=e===null||typeof e!="object"?`${typeof e} \u2014 ${JSON.stringify(e)}`:JSON.stringify(e).slice(0,80);throw new Error(`[Directive] replayUnder: the ${t} predicate is not a valid FactPredicate (got ${r})`)}let n;if(i$1(e,{operator(r,i){n===void 0&&i.startsWith("$")&&!a$1.has(i)&&(n=i);},strayOperatorKey(r){n===void 0&&!a$1.has(r)&&!b.has(r)&&(n=r);}}),n!==void 0)throw new Error(`[Directive] replayUnder: the ${t} predicate uses an unknown operator "${n}" \u2014 known operators: ${[...a$1].join(", ")}`)}function be(e){if(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.snapshots))return Te(e);let t=Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.frames)?e.frames:null;if(!t)throw new Error("[Directive] toReplayFrames: history must be a JSON array of frames, an object with a `frames` array, or a history export with a `snapshots` array");if(t.length>R)throw new Error(`[Directive] toReplayFrames: history has ${t.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${R}) \u2014 split or down-sample the history`);return t.map((n,r)=>{if(n&&typeof n=="object"&&"facts"in n){let i=n,s={id:i.id??`#${r}`,facts:i.facts??{}};return typeof i.timestamp=="number"&&(s.timestamp=i.timestamp),s}return {id:`#${r}`,facts:n??{}}})}function Te(e){let t=typeof e=="string"?JSON.parse(e):e;if(Array.isArray(t))return ne(t);if(!t||typeof t!="object")throw new Error("[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())");let n=t;if(n.version!==void 0&&n.version!==1)throw new Error(`[Directive] framesFromHistory: unsupported history export version ${JSON.stringify(n.version)} \u2014 expected 1`);if(!Array.isArray(n.snapshots))throw new Error("[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())");return ne(n.snapshots)}function ne(e){if(!Array.isArray(e))throw new Error("[Directive] framesFromSnapshots: expected an array of fact-state snapshots");if(e.length>R)throw new Error(`[Directive] framesFromSnapshots: history has ${e.length} snapshots, exceeds the MAX_REPLAY_FRAMES limit (${R}) \u2014 split or down-sample the history`);for(let t=0;t<e.length;t++){let n=e[t];if(!n||typeof n!="object"||!("facts"in n))throw new Error(`[Directive] framesFromSnapshots: snapshot at index ${t} is not a { facts, ... } object`)}return be(e)}function U(e){let{frames:t,original:n,proposed:r,entityKey:i}=e,s=e.maxSamples??20,o$1=s>0?s:0;if(t.length>R)throw new Error(`[Directive] replayUnder: history has ${t.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${R}) \u2014 split or down-sample the history`);$e(n,"original"),$e(r,"proposed");let u=0,a=0,c=0,l=0,f=0,h=[],b=[],v=i?new Set:void 0,D=i?new Set:void 0,S;for(let O of t){let $=O.facts,T=o(n,$,S),k=o(r,$,S);T&&(u++,v?.add($[i])),k&&(a++,D?.add($[i])),T===k?f++:!T&&k?(c++,h.length<o$1&&h.push(we(O,n,r,S))):(l++,b.length<o$1&&b.push(we(O,n,r,S))),S=$;}let E={framesEvaluated:t.length,original:{matched:u},proposed:{matched:a},delta:a-u,newMatchCount:c,lostMatchCount:l,unchanged:f,newMatches:h,lostMatches:b};return v&&D&&(E.original.matchedEntities=v.size,E.proposed.matchedEntities=D.size),E}function we(e,t,n,r){let i=e.facts,s={frameId:e.id,facts:i,originalExplain:p$1(t,i,r),proposedExplain:p$1(n,i,r)};return e.timestamp!==void 0&&(s.timestamp=e.timestamp),s}var re=1e4,Se=5e7;function Pt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===1&&typeof e.$hole=="string"}function ie(e,t,n=new Set,r=0){if(r>g)throw new Error(`[Directive] sweepUnder: template exceeds MAX_PREDICATE_DEPTH (${g}) \u2014 flatten the template or split the sweep`);if(Pt(e)){let i=e.$hole;if(!(i in t))throw new Error(`[Directive] sweepUnder: template references hole "${i}" but sweep has no values for it`);return t[i]}if(e===null||typeof e!="object")return e;if(n.has(e))throw new Error("[Directive] sweepUnder: template contains a cycle \u2014 predicate templates must be a tree");n.add(e);try{if(Array.isArray(e))return e.map(s=>ie(s,t,n,r+1));let i={};for(let[s,o]of Object.entries(e))i[s]=ie(o,t,n,r+1);return i}finally{n.delete(e);}}function*Me(e,t){if(e.length===0){yield {};return}let n=e[0],r=e.slice(1),i=t[n]??[];for(let s of i)for(let o of Me(r,t))yield {[n]:s,...o};}function Ot(e){let t=1;for(let n of Object.values(e))t*=n.length;return t}function jt(e){let{frames:t,original:n,template:r,sweep:i,objective:s=$=>$.proposed.matched,entityKey:o,maxSamples:u=0}=e,a=Object.keys(i);if(a.length===0)throw new Error("[Directive] sweepUnder: `sweep` must contain at least one hole name");let c=Ot(i);if(c>re)throw new Error(`[Directive] sweepUnder: grid has ${c} points, exceeds the MAX_SWEEP_POINTS limit (${re}) \u2014 narrow the sweep ranges or split the run`);if(c===0)throw new Error("[Directive] sweepUnder: at least one hole has zero candidate values");let l=c*t.length;if(l>Se)throw new Error(`[Directive] sweepUnder: ${c} points \xD7 ${t.length} frames = ${l} per-frame evaluations, exceeds the MAX_SWEEP_EVALUATIONS limit (${Se}) \u2014 narrow the sweep, down-sample the history, or split the run`);let f=false,h=$=>{let T;try{T=s($);}catch(k){return f||(f=true,console.warn(`[Directive] sweepUnder: objective threw \u2014 point will not rank (${k.message})`)),Number.NEGATIVE_INFINITY}return typeof T!="number"||!Number.isFinite(T)?(f||(f=true,console.warn(`[Directive] sweepUnder: objective returned a non-finite number (${String(T)}) \u2014 point will not rank`)),Number.NEGATIVE_INFINITY):T},b=U({frames:t,original:n,proposed:n,entityKey:o,maxSamples:u}),v={values:{},report:b,score:h(b)},D=[],S=0,E=Number.NEGATIVE_INFINITY;for(let $ of Me(a,i)){let T=ie(r,$),k=U({frames:t,original:n,proposed:T,entityKey:o,maxSamples:u}),Z=h(k);Z>E&&(E=Z,S=D.length),D.push({values:$,report:k,score:Z});}let O=D[S];return {points:D,bestIndex:S,best:O,baseline:v}}function Ft(e){return i(e)}function B(e){return e===null?"null":e===void 0?"undefined":e instanceof Date?e.toISOString():typeof e=="string"||typeof e=="object"?JSON.stringify(e):String(e)}function _t(e){let t=e.path,n=B(e.expected),r=B(e.actual);switch(e.op){case "$eq":return `set ${t} to ${n} (currently ${r})`;case "$ne":return `change ${t} to anything other than ${n} (currently ${r})`;case "$gt":return `set ${t} above ${n} (currently ${r})`;case "$gte":return `set ${t} to at least ${n} (currently ${r})`;case "$lt":return `set ${t} below ${n} (currently ${r})`;case "$lte":return `set ${t} to at most ${n} (currently ${r})`;case "$in":return `set ${t} to one of ${n} (currently ${r})`;case "$nin":return `set ${t} to something other than ${n} (currently ${r})`;case "$exists":return e.expected===true?`set ${t} to a non-null value (currently null/missing)`:`unset ${t} (currently ${r})`;case "$between":return Array.isArray(e.expected)&&e.expected.length===2?`set ${t} between ${B(e.expected[0])} and ${B(e.expected[1])} (currently ${r})`:`set ${t} within range ${n} (currently ${r})`;case "$startsWith":return `set ${t} to start with ${n} (currently ${r})`;case "$endsWith":return `set ${t} to end with ${n} (currently ${r})`;case "$contains":return `set ${t} to contain ${n} (currently ${r})`;case "$matches":return `set ${t} to match the pattern ${n} (currently ${r})`;case "$changed":return `the previous-vs-current change of ${t} is required to differ (currently they match: ${r})`;case "$all":case "$any":case "$not":return `the ${e.op} group at "${t}" did not pass \u2014 see its child clauses`;default:return `clause at ${t} (${e.op}) failed: expected ${n}, got ${r}`}}function De(e,t){for(let n of e)if(!n.pass){if((n.op==="$all"||n.op==="$any"||n.op==="$not")&&n.children){De(n.children,t);continue}t.push({path:n.path,op:n.op,expected:n.expected,actual:n.actual,suggestion:_t(n)});}}function Nt(e,t,n){let r=p$1(e,t,n),i=r.every(o=>o.pass),s=[];if(i||De(r,s),!i&&n===void 0){let o=[];i$1(e,{operator(u,a){a==="$changed"&&o.push(u);}});for(let u of o)s.push({path:u,op:"$changed",expected:true,actual:void 0,suggestion:`$changed clause at "${u}" cannot be evaluated without a \`prev\` snapshot \u2014 pass predict(predicate, facts, prev).`});}return {wouldFire:i,whenExplain:r,missingChanges:s}}var j=new Map,It=50;function Lt(e){let t=j.get(e);if(!t){try{t=new Intl.NumberFormat(e);}catch{t=new Intl.NumberFormat("en-US");}if(j.size>=It){let n=j.keys().next().value;n!==void 0&&j.delete(n);}j.set(e,t);}return t}function qt(e,t={}){let n=t.style??"natural",r=t.parenthesize??true,i=t.locale??"en-US",s=t.factName??(a=>a);if(e===null||typeof e!="object")return "<invalid predicate>";let o={style:n,parenthesize:r,locale:i,factName:s,seen:new WeakSet,cycle:false},u=K(e,o,0);return o.cycle?"<invalid predicate: cycle>":u}var Re=" AND ",Wt=" OR ",Ut="NOT",Ee=" \u2227 ",Bt=" \u2228 ",Kt="\xAC";function _(e){return typeof e!="object"||e===null||Array.isArray(e)?false:!(e instanceof Date)&&!(e instanceof RegExp)}function zt(e){if(!_(e))return false;let t=Object.keys(e);if(t.length===0)return false;for(let n of t)if(!n.startsWith("$"))return false;return true}function K(e,t,n){if(n>g)return a&&console.warn(`[Directive] describePredicate: depth limit (${g}) exceeded \u2014 bailing.`),t.style==="formal"?"\u22A5":"always true";if(Array.isArray(e))return Ht(e,t);if(!_(e))return d(e,t);if(t.seen.has(e))return t.cycle=true,"<invalid predicate: cycle>";t.seen.add(e);let r=e,i=Object.keys(r);for(let o of ["$all","$any","$not"])if(o in r)return Qt(o,r[o],t,n);let s=[];for(let o of i)o.startsWith("$")||s.push(Ae(o,r[o],t,n));return z(s,t)}function Ht(e,t,n){let r=[];for(let i of e){if(!_(i))continue;let s=i;typeof s.fact!="string"||typeof s.op!="string"||r.push(F(s.fact,s.op,s.value,t));}return r.length===0?t.style==="formal"?"\u22A4":"always true":z(r,t)}function Qt(e,t,n,r){if(e==="$not"){if(_(t)&&Object.keys(t).length===0)return n.style==="formal"?"\u22A5":"never";let o=K(t,n,r+1);return o==="always true"?"never":o==="\u22A4"?"\u22A5":`${n.style==="formal"?Kt:`${Ut} `}(${o})`}if(!Array.isArray(t))return n.style==="formal"?"\u22A5":"<invalid predicate>";if(t.length===0)return e==="$all"?n.style==="formal"?"\u22A4":"always true":n.style==="formal"?"\u22A5":"never";let i=[];for(let o of t){let u=K(o,n,r+1);i.push(u);}if(i.length===1)return i[0];let s=n.parenthesize?i.map(o=>`(${o})`):i;return e==="$all"?s.join(n.style==="formal"?Ee:Re):s.join(n.style==="formal"?Bt:Wt)}function Ae(e,t,n,r){if(zt(t)){let i=t,s=Object.keys(i);if(s.length===1)return F(e,s[0],i[s[0]],n);let o=s.map(u=>F(e,u,i[u],n));return z(o,n)}if(_(t)){let i=t;if("$all"in i||"$any"in i||"$not"in i)return K(t,n,r+1);let o=[];for(let u of Object.keys(i))u.startsWith("$")||o.push(Ae(`${e}.${u}`,i[u],n,r+1));return o.length===0?F(e,"$eq",t,n):z(o,n)}return F(e,"$eq",t,n)}function F(e,t,n,r){let i=r.style==="formal"?e:r.factName(e);return r.style==="formal"?Xt(i,t,n,r):Jt(i,t,n,r)}function Jt(e,t,n,r){switch(t){case "$eq":return n===null?`${e} is null`:`${e} is ${d(n,r)}`;case "$ne":return n===null?`${e} is not null`:`${e} is not ${d(n,r)}`;case "$gt":return `${e} is more than ${d(n,r)}`;case "$gte":return `${e} is at least ${d(n,r)}`;case "$lt":return `${e} is less than ${d(n,r)}`;case "$lte":return `${e} is at most ${d(n,r)}`;case "$in":return `${e} is one of ${ke(n,r)}`;case "$nin":return `${e} is not one of ${ke(n,r)}`;case "$exists":return n===true?`${e} is set`:`${e} is not set`;case "$between":return Array.isArray(n)&&n.length===2?`${e} is between ${d(n[0],r)} and ${d(n[1],r)}`:`${e} is between ${d(n,r)}`;case "$startsWith":return `${e} starts with ${C(n,r,true)}`;case "$endsWith":return `${e} ends with ${C(n,r,true)}`;case "$contains":return `${e} contains ${C(n,r,true)}`;case "$matches":return n instanceof RegExp?`${e} matches ${n.toString()}`:`${e} matches ${d(n,r)}`;case "$changed":return `${e} changed`;default:return a&&!a$1.has(t)&&console.warn(`[Directive] describePredicate: unknown operator "${t}" \u2014 falling through to generic rendering.`),`${e} ${t} ${d(n,r)}`}}function Xt(e,t,n,r){switch(t){case "$eq":return `${e} = ${d(n,r)}`;case "$ne":return `${e} \u2260 ${d(n,r)}`;case "$gt":return `${e} > ${d(n,r)}`;case "$gte":return `${e} \u2265 ${d(n,r)}`;case "$lt":return `${e} < ${d(n,r)}`;case "$lte":return `${e} \u2264 ${d(n,r)}`;case "$in":return `${e} \u2208 {${ve(n,r)}}`;case "$nin":return `${e} \u2209 {${ve(n,r)}}`;case "$exists":return n===true?`\u2203 ${e}`:`\u2204 ${e}`;case "$between":return Array.isArray(n)&&n.length===2?`${d(n[0],r)} \u2264 ${e} \u2264 ${d(n[1],r)}`:`${e} \u2208 [${d(n,r)}]`;case "$startsWith":return `${e} ^= ${C(n,r,true)}`;case "$endsWith":return `${e} $= ${C(n,r,true)}`;case "$contains":return `${e} \u2287 ${C(n,r,true)}`;case "$matches":return n instanceof RegExp?`${e} ~ ${n.toString()}`:`${e} ~ ${d(n,r)}`;case "$changed":return `\u0394${e}`;default:return a&&!a$1.has(t)&&console.warn(`[Directive] describePredicate: unknown operator "${t}" \u2014 falling through to generic rendering.`),`${e} ${t} ${d(n,r)}`}}function H(e){return e.length===0?true:/[\s,"']/.test(e)}function C(e,t,n){return typeof e!="string"||n||H(e)?JSON.stringify(e):e}function d(e,t){if(e===null)return "null";if(e===void 0)return "undefined";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))return String(e);try{return Lt(t.locale).format(e)}catch{return String(e)}}if(typeof e=="bigint")return t.style==="formal"?`${e.toString()}n`:e.toString();if(typeof e=="string")return t.style==="formal"||H(e)?JSON.stringify(e):e;if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return `[${e.map(n=>d(n,t)).join(", ")}]`;if(typeof e=="object")try{return JSON.stringify(e)}catch{return "[object]"}return String(e)}function ke(e,t){return Array.isArray(e)?e.map(n=>typeof n=="string"?H(n)?JSON.stringify(n):n:d(n,t)).join(", "):d(e,t)}function ve(e,t){return Array.isArray(e)?e.map(n=>typeof n=="string"?H(n)?JSON.stringify(n):n:d(n,t)).join(", "):d(e,t)}function z(e,t){if(e.length===0)return t.style==="formal"?"\u22A4":"always true";if(e.length===1)return e[0];let n=t.style==="formal"?Ee:Re;return t.parenthesize,e.join(n)}var Zt=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?$/;function I(e,t){if(typeof e!="string"||!Zt.test(e))throw new Error(`[Directive] predicateToSQL: invalid ${t} identifier "${e}" \u2014 must match /^[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)?$/`)}function Ce(e,t){if(t&&!t.includes(e))throw new Error(`[Directive] predicateToSQL: column "${e}" is not in the allowedKeys list \u2014 add it to options.allowedKeys or remove it from the predicate`)}function Yt(e){if(Array.isArray(e)){if(e.length===0)throw new Error("[Directive] predicateToSQL: select must not be empty");for(let n of e)I(n,"column");return e.join(", ")}let t=e;return t==="*"?"*":(I(t,"column"),t)}function m(e,t){return e.params.push(t),e.placeholder(e.params.length)}function oe(e,t,n,r){switch(t){case "$eq":return `${e} = ${m(r,n)}`;case "$ne":return `${e} <> ${m(r,n)}`;case "$gt":return `${e} > ${m(r,n)}`;case "$gte":return `${e} >= ${m(r,n)}`;case "$lt":return `${e} < ${m(r,n)}`;case "$lte":return `${e} <= ${m(r,n)}`;case "$in":if(!Array.isArray(n))throw new Error("[Directive] predicateToSQL: $in operand must be an array");return `${e} = ANY(${m(r,n)})`;case "$nin":if(!Array.isArray(n))throw new Error("[Directive] predicateToSQL: $nin operand must be an array");return `NOT (${e} = ANY(${m(r,n)}))`;case "$exists":return n===true?`${e} IS NOT NULL`:`${e} IS NULL`;case "$between":{if(!Array.isArray(n)||n.length!==2)throw new Error("[Directive] predicateToSQL: $between operand must be a [low, high] tuple");return `${e} BETWEEN ${m(r,n[0])} AND ${m(r,n[1])}`}case "$startsWith":if(typeof n!="string")throw new Error("[Directive] predicateToSQL: $startsWith operand must be a string");return `${e} LIKE ${m(r,se(n))} || '%' ESCAPE '\\'`;case "$endsWith":if(typeof n!="string")throw new Error("[Directive] predicateToSQL: $endsWith operand must be a string");return `${e} LIKE '%' || ${m(r,se(n))} ESCAPE '\\'`;case "$contains":if(typeof n!="string")throw new Error("[Directive] predicateToSQL: $contains only supports string operands \u2014 array containment requires a JOIN, not a predicate");return `${e} LIKE '%' || ${m(r,se(n))} || '%' ESCAPE '\\'`;case "$matches":{if(!(n instanceof RegExp))throw new Error("[Directive] predicateToSQL: $matches operand must be a RegExp");let i=n.flags.includes("i")?"~*":"~";return `${e} ${i} ${m(r,n.source)}`}case "$changed":throw new Error('[Directive] predicateToSQL: $changed is an effects-only operator \u2014 no server-side translation (a database row has no "prev" snapshot)');default:throw new Error(`[Directive] predicateToSQL: unknown operator "${t}" \u2014 known: ${[...a$1].join(", ")}`)}}function se(e){return e.replace(/[\\%_]/g,"\\$&")}function xe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Gt(e){if(!xe(e))return false;let t=Object.keys(e);if(t.length===0)return false;for(let n of t)if(!n.startsWith("$"))return false;return true}function ae(e,t){let n=Object.keys(e).filter(r=>r!==t);if(n.length>0)throw new Error(`[Directive] predicateToSQL: ${t} cannot coexist with sibling keys (${n.join(", ")}) \u2014 wrap them in $all together, or move them inside the ${t} children`)}function N(e,t,n){if(n>g)throw new Error(`[Directive] predicateToSQL: predicate depth limit (${g}) exceeded \u2014 flatten the predicate or check for a cyclic spec object`);if(e===null||typeof e!="object")throw new Error(`[Directive] predicateToSQL: predicate must be an object or array, got ${typeof e}`);if(Array.isArray(e)){if(e.length===0)return "TRUE";let i=e.map(s=>{if(!s||typeof s!="object"||!("fact"in s)||!("op"in s))throw new Error("[Directive] predicateToSQL: array-form clause must be { fact, op, value }");let o=s;return I(o.fact,"column"),Ce(o.fact,t.allowed),oe(o.fact,o.op,o.value,t)});return i.length===1?i[0]:`(${i.join(" AND ")})`}if("$all"in e){ae(e,"$all");let i=e.$all;if(!Array.isArray(i))throw new Error("[Directive] predicateToSQL: $all must be an array");if(i.length===0)return "TRUE";let s=i.map(o=>N(o,t,n+1));return s.length===1?s[0]:`(${s.join(" AND ")})`}if("$any"in e){ae(e,"$any");let i=e.$any;if(!Array.isArray(i))throw new Error("[Directive] predicateToSQL: $any must be an array");if(i.length===0)return "FALSE";let s=i.map(o=>N(o,t,n+1));return s.length===1?s[0]:`(${s.join(" OR ")})`}if("$not"in e){ae(e,"$not");let i=e.$not;return `NOT (${N(i,t,n+1)})`}let r=[];for(let[i,s]of Object.entries(e))if(I(i,"column"),Ce(i,t.allowed),Gt(s))for(let[o,u]of Object.entries(s)){if(!a$1.has(o))throw new Error(`[Directive] predicateToSQL: unknown operator "${o}" on column "${i}" \u2014 known: ${[...a$1].join(", ")}`);r.push(oe(i,o,u,t));}else {if(xe(s))throw new Error(`[Directive] predicateToSQL: nested predicate at "${i}" \u2014 cross-module / partial-match predicates have no SQL equivalent (single-table queries only in v1; pass a flat predicate or build JOIN by hand with predicateToWhere)`);r.push(oe(i,"$eq",s,t));}return r.length===0?"TRUE":r.length===1?r[0]:`(${r.join(" AND ")})`}var Pe=e=>`$${e}`;function Vt(e,t){let{table:n,allowedKeys:r}=t,i=t.placeholder??Pe,s=t.select??"*";I(n,"table");let o=Yt(s),u={params:[],placeholder:i,allowed:r},a=N(e,u,0);return {sql:`SELECT ${o} FROM ${n} WHERE ${a}`,where:a,params:u.params}}function en(e,t={}){let n=t.placeholder??Pe,r={params:[],placeholder:n,allowed:t.allowedKeys};return {where:N(e,r,0),params:r.params}}function ue(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function le(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tn(e){if(!le(e))return false;let t=Object.keys(e);if(t.length===0)return false;for(let n of t)if(!n.startsWith("$"))return false;return true}var nn=/^[A-Za-z_][A-Za-z0-9_]*$/,rn=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/;function Oe(e,t){if(typeof e!="string"||e.length===0)throw new Error(`[Directive] predicateToMongo: field name must be a non-empty string, got ${typeof e}`);if(e.startsWith("$"))throw new Error(`[Directive] predicateToMongo: field name "${e}" starts with "$" \u2014 reserved for Mongo operators (a top-level $where would be an injection vector)`);if(!(t.allowDottedPaths?rn:nn).test(e))throw new Error(`[Directive] predicateToMongo: invalid field name "${e}"${t.allowDottedPaths?"":' \u2014 pass options.allowDottedPaths=true to permit sub-document paths like "user.role"'}`)}function je(e,t){if(t&&!t.includes(e))throw new Error(`[Directive] predicateToMongo: field "${e}" is not in the allowedKeys list \u2014 add it to options.allowedKeys or remove it from the predicate`)}function ce(e,t){let n=Object.keys(e).filter(r=>r!==t);if(n.length>0)throw new Error(`[Directive] predicateToMongo: ${t} cannot coexist with sibling keys (${n.join(", ")}) \u2014 wrap them in $all together, or move them inside the ${t} children`)}function Fe(e,t){switch(e){case "$eq":case "$ne":case "$gt":case "$gte":case "$lt":case "$lte":case "$in":case "$nin":case "$exists":return {[e]:t};case "$between":{if(!Array.isArray(t)||t.length!==2)throw new Error("[Directive] predicateToMongo: $between operand must be a [low, high] tuple");return {$gte:t[0],$lte:t[1]}}case "$startsWith":if(typeof t!="string")throw new Error("[Directive] predicateToMongo: $startsWith operand must be a string");return {$regex:`^${ue(t)}`};case "$endsWith":if(typeof t!="string")throw new Error("[Directive] predicateToMongo: $endsWith operand must be a string");return {$regex:`${ue(t)}$`};case "$contains":if(typeof t=="string")return {$regex:ue(t)};throw new Error("[Directive] predicateToMongo: $contains in Mongo expects a string operand \u2014 for array element membership use $elemMatch or $in directly");case "$matches":{if(t instanceof RegExp)return t.flags?{$regex:t.source,$options:t.flags}:{$regex:t.source};if(typeof t=="string")return {$regex:t};throw new Error("[Directive] predicateToMongo: $matches operand must be a RegExp or string")}case "$changed":throw new Error("[Directive] predicateToMongo: $changed is an effects-only operator \u2014 no MongoDB query equivalent");default:throw new Error(`[Directive] predicateToMongo: unknown operator "${e}" \u2014 known: ${[...a$1].join(", ")}`)}}function x(e,t,n){if(n>g)throw new Error(`[Directive] predicateToMongo: predicate depth limit (${g}) exceeded \u2014 flatten the predicate or check for a cyclic spec object`);if(e===null||typeof e!="object")throw new Error(`[Directive] predicateToMongo: predicate must be an object or array, got ${typeof e}`);if(Array.isArray(e)){if(e.length===0)return {};let i={},s=[];for(let o of e){if(!o||typeof o!="object"||!("fact"in o)||!("op"in o))throw new Error("[Directive] predicateToMongo: array-form clause must be { fact, op, value }");let u=o;Oe(u.fact,t),je(u.fact,t.allowedKeys);let a=Fe(u.op,u.value);if(u.fact in i&&le(i[u.fact])){let c=i[u.fact];Object.keys(a).some(f=>f in c)?s.push({[u.fact]:a}):i[u.fact]={...c,...a};}else u.fact in i?s.push({[u.fact]:a}):i[u.fact]=a;}if(s.length>0){let o=[];for(let[u,a]of Object.entries(i))o.push({[u]:a});return o.push(...s),{$and:o}}return i}if("$all"in e){ce(e,"$all");let i=e.$all;if(!Array.isArray(i))throw new Error("[Directive] predicateToMongo: $all must be an array");return i.length===0?{}:i.length===1?x(i[0],t,n+1):{$and:i.map(s=>x(s,t,n+1))}}if("$any"in e){ce(e,"$any");let i=e.$any;if(!Array.isArray(i))throw new Error("[Directive] predicateToMongo: $any must be an array");return i.length===0?{$expr:{$eq:[1,0]}}:i.length===1?x(i[0],t,n+1):{$or:i.map(s=>x(s,t,n+1))}}if("$not"in e){ce(e,"$not");let i=e.$not;return {$nor:[x(i,t,n+1)]}}let r={};for(let[i,s]of Object.entries(e))if(Oe(i,t),je(i,t.allowedKeys),tn(s)){let o={};for(let[u,a]of Object.entries(s)){if(!a$1.has(u))throw new Error(`[Directive] predicateToMongo: unknown operator "${u}" on field "${i}" \u2014 known: ${[...a$1].join(", ")}`);Object.assign(o,Fe(u,a));}r[i]=o;}else r[i]=s;return r}function on(e,t={}){return x(e,t,0)}var sn=/^[A-Za-z_][A-Za-z0-9_]*$/;function _e(e,t){if(typeof e!="string"||!sn.test(e))throw new Error(`[Directive] predicateToPostgrest: invalid column identifier "${e}"`);if(t&&!t.includes(e))throw new Error(`[Directive] predicateToPostgrest: column "${e}" is not in the allowedKeys list \u2014 add it to options.allowedKeys or remove it from the predicate`)}function fe(e,t){let n=Object.keys(e).filter(r=>r!==t);if(n.length>0)throw new Error(`[Directive] predicateToPostgrest: ${t} cannot coexist with sibling keys (${n.join(", ")}) \u2014 wrap them in $all together, or move them inside the ${t} children`)}function w(e){if(e==null)return "null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"||typeof e=="bigint")return String(e);if(e instanceof Date)return e.toISOString();if(typeof e=="string")return /[,.():"\\\s]/.test(e)?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e;throw new Error(`[Directive] predicateToPostgrest: cannot encode value of type ${typeof e}`)}function Ne(e){return `(${e.map(w).join(",")})`}function de(e){return e.replace(/[\\%_*]/g,"\\$&")}function P(e,t){switch(e){case "$eq":return `eq.${w(t)}`;case "$ne":return `neq.${w(t)}`;case "$gt":return `gt.${w(t)}`;case "$gte":return `gte.${w(t)}`;case "$lt":return `lt.${w(t)}`;case "$lte":return `lte.${w(t)}`;case "$in":if(!Array.isArray(t))throw new Error("[Directive] predicateToPostgrest: $in operand must be an array");return `in.${Ne(t)}`;case "$nin":if(!Array.isArray(t))throw new Error("[Directive] predicateToPostgrest: $nin operand must be an array");return `not.in.${Ne(t)}`;case "$exists":return t===true?"not.is.null":"is.null";case "$startsWith":if(typeof t!="string")throw new Error("[Directive] predicateToPostgrest: $startsWith operand must be a string");return `like.${w(`${de(t)}*`)}`;case "$endsWith":if(typeof t!="string")throw new Error("[Directive] predicateToPostgrest: $endsWith operand must be a string");return `like.${w(`*${de(t)}`)}`;case "$contains":if(typeof t!="string")throw new Error("[Directive] predicateToPostgrest: $contains expects a string operand (array containment is the cs operator with a different shape \u2014 out of scope for v1)");return `like.${w(`*${de(t)}*`)}`;case "$matches":if(t instanceof RegExp)return `${t.flags.includes("i")?"imatch":"match"}.${w(t.source)}`;if(typeof t=="string")return `match.${w(t)}`;throw new Error("[Directive] predicateToPostgrest: $matches operand must be a RegExp or string");case "$changed":throw new Error("[Directive] predicateToPostgrest: $changed is an effects-only operator \u2014 no server query equivalent");default:throw new Error(`[Directive] predicateToPostgrest: unknown operator "${e}" \u2014 known: ${[...a$1].join(", ")}`)}}function Ie(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function an(e){if(!Ie(e))return false;let t=Object.keys(e);if(t.length===0)return false;for(let n of t)if(!n.startsWith("$"))return false;return true}function pe(e,t){return `${e}=${t}`}function Q(e,t){return `${e}=(${t.join(",")})`}function ge(e,t,n,r){if(t==="$between"){if(!Array.isArray(n)||n.length!==2)throw new Error("[Directive] predicateToPostgrest: $between operand must be a [low, high] tuple");let i=r?pe(e,P("$gte",n[0])):`${e}.${P("$gte",n[0])}`,s=r?pe(e,P("$lte",n[1])):`${e}.${P("$lte",n[1])}`;return [i,s]}return [r?pe(e,P(t,n)):`${e}.${P(t,n)}`]}function L(e,t,n,r){if(r>g)throw new Error(`[Directive] predicateToPostgrest: predicate depth limit (${g}) exceeded \u2014 flatten the predicate or check for a cyclic spec object`);if(e===null||typeof e!="object")throw new Error("[Directive] predicateToPostgrest: predicate must be an object or array");if(Array.isArray(e)){let s=[];for(let o of e){if(!o||typeof o!="object"||!("fact"in o)||!("op"in o))throw new Error("[Directive] predicateToPostgrest: array-form clause must be { fact, op, value }");let u=o;_e(u.fact,t),s.push(...ge(u.fact,u.op,u.value,n));}return s}if("$all"in e){fe(e,"$all");let s=e.$all;if(!Array.isArray(s))throw new Error("[Directive] predicateToPostgrest: $all must be an array");if(n){let u=[];for(let a of s)u.push(...L(a,t,true,r+1));return u}let o=[];for(let u of s)o.push(...L(u,t,false,r+1));return [Q("and",o)]}if("$any"in e){fe(e,"$any");let s=e.$any;if(!Array.isArray(s))throw new Error("[Directive] predicateToPostgrest: $any must be an array");if(s.length===0)return n?["id=is.null","id=not.is.null"]:[Q("and",["id.is.null","id.not.is.null"])];let o=[];for(let u of s)o.push(...L(u,t,false,r+1));return [Q("or",o)]}if("$not"in e){fe(e,"$not");let s=e.$not,o=L(s,t,false,r+1);return [Q("not.and",o)]}let i=[];for(let[s,o]of Object.entries(e))if(_e(s,t),an(o))for(let[u,a]of Object.entries(o)){if(!a$1.has(u))throw new Error(`[Directive] predicateToPostgrest: unknown operator "${u}" on column "${s}" \u2014 known: ${[...a$1].join(", ")}`);i.push(...ge(s,u,a,n));}else {if(Ie(o))throw new Error(`[Directive] predicateToPostgrest: nested predicate at "${s}" \u2014 single-table queries only`);i.push(...ge(s,"$eq",o,n));}return i}function un(e){let t=e.indexOf("=");if(t<0)return encodeURIComponent(e);let n=e.slice(0,t),r=e.slice(t+1);return `${n}=${encodeURIComponent(r)}`}function cn(e,t={}){let n=t.mode??"querystring",r=L(e,t.allowedKeys,true,0);return r.length===0?"":n==="raw"?r.join("&"):r.map(un).join("&")}function J(e=[],t,n,r,i,s,o){return {_type:void 0,_validators:e,_typeName:t,_default:n,_transform:r,_description:i,_refinements:s,_meta:o,validate(u){return J([...e,u],t,n,r,i,s,o)}}}function p(e,t,n,r,i,s,o){return {...J(e,t,n,r,i,s,o),default(a){return p(e,t,a,r,i,s,o)},transform(a){return p([],t,void 0,l=>{let f=r?r(l):l;return a(f)},i,void 0,o)},brand(){return p(e,`Branded<${t}>`,n,r,i,s,o)},describe(a){return p(e,t,n,r,a,s,o)},refine(a,c){let l=[...s??[],{predicate:a,message:c}];return p([...e,a],t,n,r,i,l,o)},nullable(){return p([a=>a===null||e.every(c=>c(a))],`${t} | null`,n,r,i,void 0,o)},optional(){return p([a=>a===void 0||e.every(c=>c(a))],`${t} | undefined`,n,r,i,void 0,o)},meta(a){return p(e,t,n,r,i,s,a)}}}var ln=((...e)=>{if(e.length===0)return p([],"union");let t=e.map(n=>n._typeName??"unknown");return p([n=>e.some(r=>r._validators.every(i=>i(n)))],t.join(" | "))}),fn={string(){let e=(t,n,r,i,s,o)=>({...p(t,"string",n,r,i,s,o),minLength(a){return e([...t,c=>c.length>=a],n,r,i,s,o)},maxLength(a){return e([...t,c=>c.length<=a],n,r,i,s,o)},pattern(a){return e([...t,c=>a.test(c)],n,r,i,s,o)},default(a){return e(t,a,r,i,s,o)},describe(a){return e(t,n,r,a,s,o)},refine(a,c){let l=[...s??[],{predicate:a,message:c}];return e([...t,a],n,r,i,l,o)},meta(a){return e(t,n,r,i,s,a)}});return e([t=>typeof t=="string"])},number(){let e=(t,n,r,i,s,o)=>({...p(t,"number",n,r,i,s,o),min(a){return e([...t,c=>c>=a],n,r,i,s,o)},max(a){return e([...t,c=>c<=a],n,r,i,s,o)},default(a){return e(t,a,r,i,s,o)},describe(a){return e(t,n,r,a,s,o)},refine(a,c){let l=[...s??[],{predicate:a,message:c}];return e([...t,a],n,r,i,l,o)},meta(a){return e(t,n,r,i,s,a)}});return e([t=>typeof t=="number"])},boolean(){return p([e=>typeof e=="boolean"],"boolean")},array(){let e=(t,n,r,i,s,o)=>{let u=p(t,"array",r,void 0,i,void 0,o),a=s??{value:-1};return {...u,get _lastFailedIndex(){return a.value},set _lastFailedIndex(l){a.value=l;},of(l){let f={value:-1};return e([...t,h=>{for(let b=0;b<h.length;b++)if(!l._validators.every(v=>v(h[b])))return f.value=b,false;return true}],l,r,i,f,o)},nonEmpty(){return e([...t,l=>l.length>0],n,r,i,a,o)},maxLength(l){return e([...t,f=>f.length<=l],n,r,i,a,o)},minLength(l){return e([...t,f=>f.length>=l],n,r,i,a,o)},default(l){return e(t,n,l,i,a,o)},describe(l){return e(t,n,r,l,a,o)},meta(l){return e(t,n,r,i,a,l)}}};return e([t=>Array.isArray(t)])},object(){let e=(t,n,r,i)=>({...p(t,"object",n,void 0,r,void 0,i),shape(o){return e([...t,u=>{for(let[a,c]of Object.entries(o)){let l=u[a],f=c;if(f&&!f._validators.every(h=>h(l)))return false}return true}],n,r,i)},nonNull(){return e([...t,o=>o!=null],n,r,i)},hasKeys(...o){return e([...t,u=>o.every(a=>a in u)],n,r,i)},default(o){return e(t,o,r,i)},describe(o){return e(t,n,o,i)},meta(o){return e(t,n,r,o)}});return e([t=>typeof t=="object"&&t!==null&&!Array.isArray(t)])},enum(...e){a&&e.length===0&&console.warn("[Directive] t.enum() called with no values - this will reject all strings");let t=new Set(e);return p([n=>typeof n=="string"&&t.has(n)],`enum(${e.join("|")})`)},literal(e){return p([t=>t===e],`literal(${String(e)})`)},nullable(e){let t=e._typeName??"unknown";return J([n=>n===null?true:e._validators.every(r=>r(n))],`${t} | null`)},optional(e){let t=e._typeName??"unknown";return J([n=>n===void 0?true:e._validators.every(r=>r(n))],`${t} | undefined`)},union:ln,record(e){let t=e._typeName??"unknown";return p([n=>typeof n!="object"||n===null||Array.isArray(n)?false:Object.values(n).every(r=>e._validators.every(i=>i(r)))],`Record<string, ${t}>`)},tuple(...e){a&&e.length===0&&console.warn("[Directive] t.tuple() called with no types - this will only accept empty arrays");let t=e.map(n=>n._typeName??"unknown");return p([n=>!Array.isArray(n)||n.length!==e.length?false:e.every((r,i)=>r._validators.every(s=>s(n[i])))],`[${t.join(", ")}]`)},date(){return p([e=>e instanceof Date&&!Number.isNaN(e.getTime())],"Date")},uuid(){let e=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;return p([t=>typeof t=="string"&&e.test(t)],"uuid")},email(){let e=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return p([t=>typeof t=="string"&&e.test(t)],"email")},url(){return p([e=>{if(typeof e!="string")return false;try{return new URL(e),!0}catch{return false}}],"url")},bigint(){return p([e=>typeof e=="bigint"],"bigint")},any(){return p([],"any")},unknown(){return p([],"unknown")}};function dn(e){if(!e||typeof e!="string"){console.warn("[Directive] Module ID must be a non-empty string");return}/^(__[a-z][a-z0-9_-]*|[a-z][a-z0-9-]*)$/i.test(e)||console.warn(`[Directive] Module ID "${e}" should follow kebab-case convention (e.g., "my-module")`);}function Le(e,t,n,r,i){for(let s of e)t.has(s)||console.warn(`[Directive] ${n} "${s}" not declared in ${r}`);for(let s of t)e.has(s)||console.warn(`[Directive] ${r}["${s}"] ${i}`);}function pn(e,t){e.length===0&&console.warn("[Directive] history.snapshotEvents is an empty array \u2014 no events will create history snapshots. Omit history.snapshotEvents entirely to snapshot all events, or list specific events.");let n=new Set(Object.keys(t));for(let r of e)n.has(r)||console.warn(`[Directive] history.snapshotEvents entry "${r}" not declared in schema.events. Available events: ${[...n].join(", ")||"(none)"}`);}function gn(e,t){let n=new Set(Object.keys(t));for(let[r,i]of Object.entries(e)){let s=i;typeof s.requirement=="string"&&!n.has(s.requirement)&&console.warn(`[Directive] Resolver "${r}" references unknown requirement type "${s.requirement}". Available types: ${[...n].join(", ")||"(none)"}`);}}function yn(e,t){let n=t.schema?.facts??{},r=Object.keys(n);if(r.length===0)return;let i=new Set(["self","prev","current"]),s="crossModuleDeps"in t&&t.crossModuleDeps?Object.keys(t.crossModuleDeps):[];for(let o of s)i.add(o);for(let o of r)if(i.has(o))throw new Error(`[Directive] module '${e}': fact key '${o}' conflicts with a reserved namespace pivot or evaluation alias (self / prev / current / a crossModuleDep namespace). Three fixes:
|
|
2
2
|
1. Rename the fact (e.g. ${o}_)
|
|
3
3
|
2. Remove '${o}' from this module's crossModuleDeps if it's not actually needed
|
|
4
4
|
3. Move the fact under a wrapping namespace (t.object({ inner: ... }))`)}function mn(e,t){let n=t.constraints;if(n)for(let[r,i]of Object.entries(n)){let s=i?.abortOn;if(s){for(let o of s)if(k.has(o)||o.startsWith("$"))throw new Error(`[Directive] module '${e}' constraint '${r}': abortOn key '${o}' is reserved (BLOCKED_PROPS or $-prefixed)`)}}}function hn(e,t){let n=t.constraints;if(n)for(let[r,i]of Object.entries(n)){let s=i?.bind;if(s){for(let o of s)if(k.has(o)||o.startsWith("$"))throw new Error(`[Directive] module '${e}' constraint '${r}': bind key '${o}' is reserved (BLOCKED_PROPS or $-prefixed)`)}}}function $n(e,t){dn(e),t.schema?t.schema.facts||(Object.values(t.schema).some(r=>r!=null&&typeof r=="object"&&"_typeName"in r)&&console.warn(`[Directive] Module "${e}" schema appears to contain fact declarations directly. Did you mean \`schema: { facts: { ... } }\` instead of \`schema: { ... }\`?`),console.warn("[Directive] Module schema.facts is required")):console.warn("[Directive] Module schema is required"),Le(new Set(Object.keys(t.derive??{})),new Set(Object.keys(t.schema?.derivations??{})),"Derivation","schema.derivations","has no matching implementation in derive"),Le(new Set(Object.keys(t.events??{})),new Set(Object.keys(t.schema?.events??{})),"Event","schema.events","has no matching handler in events"),t.history?.snapshotEvents&&pn(t.history.snapshotEvents,t.schema?.events??{}),t.resolvers&&t.schema?.requirements&&gn(t.resolvers,t.schema.requirements);}function qe(e,t){yn(e,t),mn(e,t),hn(e,t),a&&$n(e,t);let n="crossModuleDeps"in t?t.crossModuleDeps:void 0;return {id:e,schema:t.schema,init:t.init,derive:t.derive??{},events:t.events??{},effects:t.effects,sources:t.sources,constraints:t.constraints,resolvers:t.resolvers,hooks:t.hooks,meta:t.meta,history:t.history,crossModuleDeps:n}}function wn(e){return t=>qe(t,e)}function ye(){let e={pending:new Map,inflight:new Map,failed:new Map,errors:new Map,listeners:new Set};function t(){for(let a of e.listeners)a();}function n(a,c){let l=a.get(c);return l||(l=new Set,a.set(c,l)),l}function r(a){let c=e.pending.get(a)??new Set,l=e.inflight.get(a)??new Set,f=e.failed.get(a)??new Set,h=e.errors.get(a)??null;return {pending:c.size,inflight:l.size,failed:f.size,isLoading:c.size>0||l.size>0,hasError:f.size>0,lastError:h}}function i(){let a=new Set([...e.pending.keys(),...e.inflight.keys(),...e.failed.keys()]),c=new Map;for(let l of a)c.set(l,r(l));return c}function s(a){return e.listeners.add(a),()=>e.listeners.delete(a)}function o(){e.pending.clear(),e.inflight.clear(),e.failed.clear(),e.errors.clear(),t();}return {plugin:{name:"requirement-status",onRequirementCreated(a){let c=a.requirement.type;n(e.pending,c).add(a.id),e.failed.get(c)?.delete(a.id),t();},onResolverStart(a,c){let l=c.requirement.type;e.pending.get(l)?.delete(c.id),n(e.inflight,l).add(c.id),t();},onResolverComplete(a,c){let l=c.requirement.type;e.inflight.get(l)?.delete(c.id),e.pending.get(l)?.delete(c.id),t();},onResolverError(a,c,l){let f=c.requirement.type;e.inflight.get(f)?.delete(c.id),n(e.failed,f).add(c.id),e.errors.set(f,l instanceof Error?l:new Error(String(l))),t();},onResolverCancel(a,c){let l=c.requirement.type;e.pending.get(l)?.delete(c.id),e.inflight.get(l)?.delete(c.id),t();},onRequirementMet(a){let c=a.requirement.type;e.pending.get(c)?.delete(a.id),e.inflight.get(c)?.delete(a.id),t();}},getStatus:r,getAllStatus:i,subscribe:s,reset:o}}function bn(e){return t=>e.getStatus(t)}function Tn(e){let t=ye(),r=[...e.plugins??[],t.plugin];return {system:a$2({module:e.module,plugins:r,trace:e.trace,errorBoundary:e.errorBoundary,tickMs:e.tickMs,zeroConfig:e.zeroConfig,initialFacts:e.initialFacts}),statusPlugin:t}}function We(){return {now:()=>Date.now(),setTimeout:(e,t)=>{let n=globalThis.setTimeout(e,t);return ()=>globalThis.clearTimeout(n)}}}function Sn(e=0){let t=e,n=0,r=[];return {now:()=>t,setTimeout:(i,s)=>{let o={id:n++,deadlineMs:t+s,cb:i,canceled:false};return r.push(o),()=>{o.canceled=true;}},advanceBy:i=>{let s=t+i;for(;;){let o=r.filter(a=>!a.canceled&&a.deadlineMs<=s).sort((a,c)=>a.deadlineMs!==c.deadlineMs?a.deadlineMs-c.deadlineMs:a.id-c.id);if(o.length===0)break;let u=o[0];t=Math.max(t,u.deadlineMs),u.canceled=true,u.cb();}t=Math.max(t,s);}}}function Mn(){return We()}function me(){return {startedAtMs:null,pausedDurationMs:0,pausedAtMs:null,status:"idle",repeats:0}}function X(e,t){return e.startedAtMs===null?0:e.status==="paused"&&e.pausedAtMs!==null?Math.max(0,e.pausedAtMs-e.startedAtMs-e.pausedDurationMs):Math.max(0,t-e.startedAtMs-e.pausedDurationMs)}function Ue(e,t,n){return Math.max(0,n-X(e,t))}function Be(e,t){return e.status==="running"||e.status==="paused"?e:{...e,startedAtMs:t,pausedDurationMs:0,pausedAtMs:null,status:"running",repeats:0}}function Ke(e,t){return e.status!=="running"?e:{...e,pausedAtMs:t,status:"paused"}}function ze(e,t){if(e.status!=="paused"||e.pausedAtMs===null)return e;let n=Math.max(0,t-e.pausedAtMs);return {...e,pausedDurationMs:e.pausedDurationMs+n,pausedAtMs:null,status:"running"}}function He(){return me()}function Qe(e){return {...e,status:"completed"}}function Je(e,t){return e.startedAtMs===null||e.status==="paused"?e:{...e,startedAtMs:e.startedAtMs+t,pausedDurationMs:0,pausedAtMs:null,repeats:e.repeats+1}}function Xe(e,t,n){if(e.status!=="running")return {kind:"no-op"};let r=X(e,t);return n.mode==="up"?{kind:"no-op"}:n.mode==="repeat"?r>=n.ms?{kind:"repeat"}:{kind:"no-op"}:r>=n.ms?{kind:"complete"}:{kind:"no-op"}}function Dn(e){return {initial:me,start:Be,pause:Ke,resume:ze,reset:He,complete:Qe,registerRepeat:t=>Je(t,e.ms),tick:(t,n)=>Xe(t,n,e),elapsedMs:X,remainingMs:(t,n)=>Ue(t,n,e.ms)}}var or={None:"none",Linear:"linear",Exponential:"exponential"};export{or as Backoff,R as MAX_REPLAY_FRAMES,re as MAX_SWEEP_POINTS,Qe as completeTimer,qe as createModule,wn as createModuleFactory,ye as createRequirementStatusPlugin,bn as createStatusHook,Tn as createSystemWithStatus,Mn as defaultClock,qt as describePredicate,X as elapsedMs,Te as framesFromHistory,ne as framesFromSnapshots,me as initialTimerState,Ke as pauseTimer,Ft as predicateHash,on as predicateToMongo,cn as predicateToPostgrest,Vt as predicateToSQL,en as predicateToWhere,Nt as predict,We as realClock,Je as registerRepeat,Ue as remainingMs,U as replayUnder,He as resetTimer,ze as resumeTimer,Be as startTimer,jt as sweepUnder,fn as t,Xe as tickTimer,Dn as timerOps,be as toReplayFrames,Sn as virtualClock};//# sourceMappingURL=index.js.map
|