@directive-run/core 1.8.0 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +4 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +168 -1
- package/dist/index.d.ts +168 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/plugins/index.cjs +2 -2
- package/dist/plugins/index.cjs.map +1 -1
- package/dist/plugins/index.js +2 -2
- package/dist/plugins/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -648,6 +648,173 @@ declare function diffRules(options: DiffRulesOptions): RulesDiffReport;
|
|
|
648
648
|
*/
|
|
649
649
|
declare function diffClauses(before: unknown, after: unknown): Change[];
|
|
650
650
|
|
|
651
|
+
/**
|
|
652
|
+
* Compile a `FactPredicate` to a parameterized Postgres-style SQL WHERE
|
|
653
|
+
* clause. The same predicate that gates a constraint on the client can
|
|
654
|
+
* filter rows on the server — *one source of truth, two execution sites*.
|
|
655
|
+
*
|
|
656
|
+
* Pure transformation. No engine, no driver, no string concatenation of
|
|
657
|
+
* user values (all operands flow through the parameter array → safe
|
|
658
|
+
* against SQL injection by construction).
|
|
659
|
+
*/
|
|
660
|
+
|
|
661
|
+
interface PredicateToSqlOptions {
|
|
662
|
+
/** Table to query. Validated against the same identifier rule as columns. */
|
|
663
|
+
table: string;
|
|
664
|
+
/**
|
|
665
|
+
* Allowlist of fact / column keys the predicate may reference. STRONGLY
|
|
666
|
+
* RECOMMENDED for any predicate that crosses a trust boundary (AI
|
|
667
|
+
* generation, user input, JSON-over-the-wire). Without an allowlist, a
|
|
668
|
+
* predicate may reference any column the table has.
|
|
669
|
+
*/
|
|
670
|
+
allowedKeys?: readonly string[];
|
|
671
|
+
/**
|
|
672
|
+
* Customize the `SELECT` projection. Default `"*"`. Accepts:
|
|
673
|
+
* - `"*"`
|
|
674
|
+
* - a column identifier (`"id"` or `"users.id"`)
|
|
675
|
+
* - an array of column identifiers (`["id", "name"]`) — joined with `,`
|
|
676
|
+
* Free-form strings (e.g. `"COUNT(*)"`) are rejected — build the wrapper
|
|
677
|
+
* SQL manually with {@link predicateToWhere} for those cases.
|
|
678
|
+
*/
|
|
679
|
+
select?: string | readonly string[];
|
|
680
|
+
/**
|
|
681
|
+
* Parameter placeholder generator. Default is Postgres-style `$1`, `$2`.
|
|
682
|
+
* Pass `() => "?"` for MySQL/SQLite, or supply your own scheme.
|
|
683
|
+
*/
|
|
684
|
+
placeholder?: (oneBasedIndex: number) => string;
|
|
685
|
+
}
|
|
686
|
+
interface PredicateToSqlResult {
|
|
687
|
+
/** Full `SELECT … FROM table WHERE …` statement. */
|
|
688
|
+
sql: string;
|
|
689
|
+
/** Just the `WHERE` clause body (without the literal `WHERE`). */
|
|
690
|
+
where: string;
|
|
691
|
+
/** Parameters, in `$1`-then-`$2`-then-… order. */
|
|
692
|
+
params: unknown[];
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* Compile a {@link FactPredicate} to a parameterized SQL statement.
|
|
696
|
+
*
|
|
697
|
+
* Operand values **never** appear in the SQL string — they flow through
|
|
698
|
+
* the `params` array. Table and column identifiers are regex-validated.
|
|
699
|
+
*
|
|
700
|
+
* @example
|
|
701
|
+
* ```ts
|
|
702
|
+
* const where = { age: { $gte: 18 }, status: { $in: ["active", "pending"] } };
|
|
703
|
+
*
|
|
704
|
+
* predicateToSQL(where, { table: "users" });
|
|
705
|
+
* // → { sql: "SELECT * FROM users WHERE (age >= $1 AND status = ANY($2))",
|
|
706
|
+
* // where: "(age >= $1 AND status = ANY($2))",
|
|
707
|
+
* // params: [18, ["active", "pending"]] }
|
|
708
|
+
*
|
|
709
|
+
* // MySQL/SQLite placeholder:
|
|
710
|
+
* predicateToSQL(where, { table: "users", placeholder: () => "?" });
|
|
711
|
+
*
|
|
712
|
+
* // Recommended for AI/user-supplied predicates:
|
|
713
|
+
* predicateToSQL(where, { table: "users", allowedKeys: ["age", "status"] });
|
|
714
|
+
* ```
|
|
715
|
+
*/
|
|
716
|
+
declare function predicateToSQL<F = Record<string, unknown>>(predicate: FactPredicate<F>, options: PredicateToSqlOptions): PredicateToSqlResult;
|
|
717
|
+
/**
|
|
718
|
+
* Lower-level variant — returns just the `WHERE` clause body and the
|
|
719
|
+
* `params` array, no `SELECT ... FROM` wrapper. Use this when you need
|
|
720
|
+
* to embed the WHERE in a larger query (JOIN, UPDATE, DELETE, COUNT).
|
|
721
|
+
*
|
|
722
|
+
* @example
|
|
723
|
+
* ```ts
|
|
724
|
+
* const { where, params } = predicateToWhere({ age: { $gte: 18 } });
|
|
725
|
+
* await db.query(`UPDATE users SET tier = 'adult' WHERE ${where}`, params);
|
|
726
|
+
* ```
|
|
727
|
+
*/
|
|
728
|
+
declare function predicateToWhere<F = Record<string, unknown>>(predicate: FactPredicate<F>, options?: Omit<PredicateToSqlOptions, "table" | "select">): {
|
|
729
|
+
where: string;
|
|
730
|
+
params: unknown[];
|
|
731
|
+
};
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Compile a `FactPredicate` to a MongoDB query document. Most of
|
|
735
|
+
* Directive's predicate operator set is already Mongo-compatible by
|
|
736
|
+
* design — this translator handles the few ops that need rewriting
|
|
737
|
+
* (`$startsWith`/`$endsWith`/`$contains` → `$regex`, `$between` →
|
|
738
|
+
* `$gte`+`$lte`, `$matches` → `$regex`/`$options`).
|
|
739
|
+
*
|
|
740
|
+
* Combinators map cleanly: `$all` → `$and`, `$any` → `$or`, `$not` → `$nor`.
|
|
741
|
+
*
|
|
742
|
+
* Pure transformation. No driver dependency.
|
|
743
|
+
*/
|
|
744
|
+
|
|
745
|
+
interface PredicateToMongoOptions {
|
|
746
|
+
/**
|
|
747
|
+
* Allowlist of fact / field keys the predicate may reference. STRONGLY
|
|
748
|
+
* RECOMMENDED for any predicate that crosses a trust boundary.
|
|
749
|
+
*/
|
|
750
|
+
allowedKeys?: readonly string[];
|
|
751
|
+
/**
|
|
752
|
+
* Allow `.` in field names (for sub-document traversal: `"user.role"`).
|
|
753
|
+
* Default is `false` — `.` is rejected so the predicate cannot
|
|
754
|
+
* accidentally read sub-document fields the developer did not anticipate.
|
|
755
|
+
*/
|
|
756
|
+
allowDottedPaths?: boolean;
|
|
757
|
+
}
|
|
758
|
+
/**
|
|
759
|
+
* Compile a {@link FactPredicate} to a MongoDB query document.
|
|
760
|
+
*
|
|
761
|
+
* Field names are validated to NOT start with `$` (which would land
|
|
762
|
+
* `$where` and other server-side JS evaluation operators directly in the
|
|
763
|
+
* query — an injection vector for AI/user-generated predicates).
|
|
764
|
+
*
|
|
765
|
+
* @example
|
|
766
|
+
* ```ts
|
|
767
|
+
* predicateToMongo({ age: { $gte: 18 }, status: { $in: ["active", "pending"] } })
|
|
768
|
+
* // → { age: { $gte: 18 }, status: { $in: ["active", "pending"] } }
|
|
769
|
+
*
|
|
770
|
+
* predicateToMongo({ name: { $startsWith: "Al" } })
|
|
771
|
+
* // → { name: { $regex: "^Al" } }
|
|
772
|
+
*
|
|
773
|
+
* predicateToMongo({ $any: [{ tier: "gold" }, { score: { $gte: 100 } }] })
|
|
774
|
+
* // → { $or: [{ tier: "gold" }, { score: { $gte: 100 } }] }
|
|
775
|
+
* ```
|
|
776
|
+
*/
|
|
777
|
+
declare function predicateToMongo<F = Record<string, unknown>>(predicate: FactPredicate<F>, options?: PredicateToMongoOptions): Record<string, unknown>;
|
|
778
|
+
|
|
779
|
+
/**
|
|
780
|
+
* Compile a `FactPredicate` to a PostgREST querystring.
|
|
781
|
+
*
|
|
782
|
+
* PostgREST's filter grammar is column-scoped: `?age=gte.18&status=in.(active,pending)`.
|
|
783
|
+
* Logical groups use `and=(...)` / `or=(...)` / `not.and=(...)`.
|
|
784
|
+
*
|
|
785
|
+
* Reference: https://postgrest.org/en/stable/api.html#operators
|
|
786
|
+
*/
|
|
787
|
+
|
|
788
|
+
interface PredicateToPostgrestOptions {
|
|
789
|
+
/** Allowlist of column keys the predicate may reference. */
|
|
790
|
+
allowedKeys?: readonly string[];
|
|
791
|
+
/**
|
|
792
|
+
* Encoding mode for the returned string.
|
|
793
|
+
* - `"querystring"` (default): a full querystring without a leading `?`,
|
|
794
|
+
* with each clause value URL-encoded — drops straight into `fetch`.
|
|
795
|
+
* - `"raw"`: the same content, leaving `(`, `)`, `,` unencoded for
|
|
796
|
+
* readability. Use this only when you'll encode the result yourself.
|
|
797
|
+
*/
|
|
798
|
+
mode?: "querystring" | "raw";
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* Compile a {@link FactPredicate} to a PostgREST querystring.
|
|
802
|
+
*
|
|
803
|
+
* @example
|
|
804
|
+
* ```ts
|
|
805
|
+
* predicateToPostgrest({ age: { $gte: 18 }, status: { $in: ["active", "pending"] } })
|
|
806
|
+
* // → "age=gte.18&status=in.%28active%2Cpending%29"
|
|
807
|
+
*
|
|
808
|
+
* // Raw mode for debugging / building URLs by hand:
|
|
809
|
+
* predicateToPostgrest({ age: { $gte: 18 } }, { mode: "raw" })
|
|
810
|
+
* // → "age=gte.18"
|
|
811
|
+
*
|
|
812
|
+
* predicateToPostgrest({ $any: [{ tier: "gold" }, { score: { $gte: 100 } }] }, { mode: "raw" })
|
|
813
|
+
* // → "or=(tier.eq.gold,score.gte.100)"
|
|
814
|
+
* ```
|
|
815
|
+
*/
|
|
816
|
+
declare function predicateToPostgrest<F = Record<string, unknown>>(predicate: FactPredicate<F>, options?: PredicateToPostgrestOptions): string;
|
|
817
|
+
|
|
651
818
|
/** Brand symbol for branded types */
|
|
652
819
|
declare const Brand: unique symbol;
|
|
653
820
|
/** Branded type - adds a unique brand to a base type */
|
|
@@ -1908,4 +2075,4 @@ declare const Backoff: {
|
|
|
1908
2075
|
readonly Exponential: "exponential";
|
|
1909
2076
|
};
|
|
1910
2077
|
|
|
1911
|
-
export { Backoff, type Branded, type ChainableSchemaType, type Change, type ChangeKind, ClauseResult, type ConstraintDiff, type ConstraintStatus, CreateSystemOptionsNamed, CreateSystemOptionsSingle, CrossModuleDeps, DefinitionMeta, type DiffRulesOptions, ErrorBoundaryConfig, type ExtendedSchemaType, FactPredicate, FactTemplate, Facts, type LeafClause, MAX_REPLAY_FRAMES, MAX_SWEEP_POINTS, type ModuleConfig, type ModuleConfigWithDeps, ModuleDef, ModuleHooks, ModuleSchema, ModulesMap, NamespacedSystem, PatchSpec, Plugin, type PredicateBacktestReport, type ReplayDiffSample, type ReplayFrame, type ReplayUnderOptions, Requirement, RequirementSet, type RequirementTypeStatus, RequirementWithId, type RulesDiffReport, type RulesMapInput, SchemaType, type SignalClock, SingleModuleSystem, type SweepHole, type SweepPoint, type SweepReport, type SweepUnderOptions, type TimerFactOpts, type TimerFactState, TraceOption, applyPatch, completeTimer, createModule, createModuleFactory, createRequirementStatusPlugin, createStatusHook, createSystem, createSystemWithStatus, defaultClock, diffClauses, diffRules, elapsedMs, evaluateKeySelector, evaluatePredicate, evaluatePredicateExplained, evaluateTemplate, extractDeps, extractTemplateKeys, flattenPredicate, forType, framesFromHistory, framesFromSnapshots, generateRequirementId, initialTimerState, isPredicate, isRequirementType, isTemplate, memoizePredicate, pauseTimer, realClock, registerRepeat, remainingMs, replayUnder, req, resetTimer, resumeTimer, startTimer, sweepUnder, t, tickTimer, timerOps, toReplayFrames, toRulesMap, validatePredicate, virtualClock };
|
|
2078
|
+
export { Backoff, type Branded, type ChainableSchemaType, type Change, type ChangeKind, ClauseResult, type ConstraintDiff, type ConstraintStatus, CreateSystemOptionsNamed, CreateSystemOptionsSingle, CrossModuleDeps, DefinitionMeta, type DiffRulesOptions, ErrorBoundaryConfig, type ExtendedSchemaType, FactPredicate, FactTemplate, Facts, type LeafClause, MAX_REPLAY_FRAMES, MAX_SWEEP_POINTS, type ModuleConfig, type ModuleConfigWithDeps, ModuleDef, ModuleHooks, ModuleSchema, ModulesMap, NamespacedSystem, PatchSpec, Plugin, type PredicateBacktestReport, type PredicateToMongoOptions, type PredicateToPostgrestOptions, type PredicateToSqlOptions, type PredicateToSqlResult, type ReplayDiffSample, type ReplayFrame, type ReplayUnderOptions, Requirement, RequirementSet, type RequirementTypeStatus, RequirementWithId, type RulesDiffReport, type RulesMapInput, SchemaType, type SignalClock, SingleModuleSystem, type SweepHole, type SweepPoint, type SweepReport, type SweepUnderOptions, type TimerFactOpts, type TimerFactState, TraceOption, applyPatch, completeTimer, createModule, createModuleFactory, createRequirementStatusPlugin, createStatusHook, createSystem, createSystemWithStatus, defaultClock, diffClauses, diffRules, elapsedMs, evaluateKeySelector, evaluatePredicate, evaluatePredicateExplained, evaluateTemplate, extractDeps, extractTemplateKeys, flattenPredicate, forType, framesFromHistory, framesFromSnapshots, generateRequirementId, initialTimerState, isPredicate, isRequirementType, isTemplate, memoizePredicate, pauseTimer, predicateToMongo, predicateToPostgrest, predicateToSQL, predicateToWhere, realClock, registerRepeat, remainingMs, replayUnder, req, resetTimer, resumeTimer, startTimer, sweepUnder, t, tickTimer, timerOps, toReplayFrames, toRulesMap, validatePredicate, virtualClock };
|
package/dist/index.d.ts
CHANGED
|
@@ -648,6 +648,173 @@ declare function diffRules(options: DiffRulesOptions): RulesDiffReport;
|
|
|
648
648
|
*/
|
|
649
649
|
declare function diffClauses(before: unknown, after: unknown): Change[];
|
|
650
650
|
|
|
651
|
+
/**
|
|
652
|
+
* Compile a `FactPredicate` to a parameterized Postgres-style SQL WHERE
|
|
653
|
+
* clause. The same predicate that gates a constraint on the client can
|
|
654
|
+
* filter rows on the server — *one source of truth, two execution sites*.
|
|
655
|
+
*
|
|
656
|
+
* Pure transformation. No engine, no driver, no string concatenation of
|
|
657
|
+
* user values (all operands flow through the parameter array → safe
|
|
658
|
+
* against SQL injection by construction).
|
|
659
|
+
*/
|
|
660
|
+
|
|
661
|
+
interface PredicateToSqlOptions {
|
|
662
|
+
/** Table to query. Validated against the same identifier rule as columns. */
|
|
663
|
+
table: string;
|
|
664
|
+
/**
|
|
665
|
+
* Allowlist of fact / column keys the predicate may reference. STRONGLY
|
|
666
|
+
* RECOMMENDED for any predicate that crosses a trust boundary (AI
|
|
667
|
+
* generation, user input, JSON-over-the-wire). Without an allowlist, a
|
|
668
|
+
* predicate may reference any column the table has.
|
|
669
|
+
*/
|
|
670
|
+
allowedKeys?: readonly string[];
|
|
671
|
+
/**
|
|
672
|
+
* Customize the `SELECT` projection. Default `"*"`. Accepts:
|
|
673
|
+
* - `"*"`
|
|
674
|
+
* - a column identifier (`"id"` or `"users.id"`)
|
|
675
|
+
* - an array of column identifiers (`["id", "name"]`) — joined with `,`
|
|
676
|
+
* Free-form strings (e.g. `"COUNT(*)"`) are rejected — build the wrapper
|
|
677
|
+
* SQL manually with {@link predicateToWhere} for those cases.
|
|
678
|
+
*/
|
|
679
|
+
select?: string | readonly string[];
|
|
680
|
+
/**
|
|
681
|
+
* Parameter placeholder generator. Default is Postgres-style `$1`, `$2`.
|
|
682
|
+
* Pass `() => "?"` for MySQL/SQLite, or supply your own scheme.
|
|
683
|
+
*/
|
|
684
|
+
placeholder?: (oneBasedIndex: number) => string;
|
|
685
|
+
}
|
|
686
|
+
interface PredicateToSqlResult {
|
|
687
|
+
/** Full `SELECT … FROM table WHERE …` statement. */
|
|
688
|
+
sql: string;
|
|
689
|
+
/** Just the `WHERE` clause body (without the literal `WHERE`). */
|
|
690
|
+
where: string;
|
|
691
|
+
/** Parameters, in `$1`-then-`$2`-then-… order. */
|
|
692
|
+
params: unknown[];
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* Compile a {@link FactPredicate} to a parameterized SQL statement.
|
|
696
|
+
*
|
|
697
|
+
* Operand values **never** appear in the SQL string — they flow through
|
|
698
|
+
* the `params` array. Table and column identifiers are regex-validated.
|
|
699
|
+
*
|
|
700
|
+
* @example
|
|
701
|
+
* ```ts
|
|
702
|
+
* const where = { age: { $gte: 18 }, status: { $in: ["active", "pending"] } };
|
|
703
|
+
*
|
|
704
|
+
* predicateToSQL(where, { table: "users" });
|
|
705
|
+
* // → { sql: "SELECT * FROM users WHERE (age >= $1 AND status = ANY($2))",
|
|
706
|
+
* // where: "(age >= $1 AND status = ANY($2))",
|
|
707
|
+
* // params: [18, ["active", "pending"]] }
|
|
708
|
+
*
|
|
709
|
+
* // MySQL/SQLite placeholder:
|
|
710
|
+
* predicateToSQL(where, { table: "users", placeholder: () => "?" });
|
|
711
|
+
*
|
|
712
|
+
* // Recommended for AI/user-supplied predicates:
|
|
713
|
+
* predicateToSQL(where, { table: "users", allowedKeys: ["age", "status"] });
|
|
714
|
+
* ```
|
|
715
|
+
*/
|
|
716
|
+
declare function predicateToSQL<F = Record<string, unknown>>(predicate: FactPredicate<F>, options: PredicateToSqlOptions): PredicateToSqlResult;
|
|
717
|
+
/**
|
|
718
|
+
* Lower-level variant — returns just the `WHERE` clause body and the
|
|
719
|
+
* `params` array, no `SELECT ... FROM` wrapper. Use this when you need
|
|
720
|
+
* to embed the WHERE in a larger query (JOIN, UPDATE, DELETE, COUNT).
|
|
721
|
+
*
|
|
722
|
+
* @example
|
|
723
|
+
* ```ts
|
|
724
|
+
* const { where, params } = predicateToWhere({ age: { $gte: 18 } });
|
|
725
|
+
* await db.query(`UPDATE users SET tier = 'adult' WHERE ${where}`, params);
|
|
726
|
+
* ```
|
|
727
|
+
*/
|
|
728
|
+
declare function predicateToWhere<F = Record<string, unknown>>(predicate: FactPredicate<F>, options?: Omit<PredicateToSqlOptions, "table" | "select">): {
|
|
729
|
+
where: string;
|
|
730
|
+
params: unknown[];
|
|
731
|
+
};
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Compile a `FactPredicate` to a MongoDB query document. Most of
|
|
735
|
+
* Directive's predicate operator set is already Mongo-compatible by
|
|
736
|
+
* design — this translator handles the few ops that need rewriting
|
|
737
|
+
* (`$startsWith`/`$endsWith`/`$contains` → `$regex`, `$between` →
|
|
738
|
+
* `$gte`+`$lte`, `$matches` → `$regex`/`$options`).
|
|
739
|
+
*
|
|
740
|
+
* Combinators map cleanly: `$all` → `$and`, `$any` → `$or`, `$not` → `$nor`.
|
|
741
|
+
*
|
|
742
|
+
* Pure transformation. No driver dependency.
|
|
743
|
+
*/
|
|
744
|
+
|
|
745
|
+
interface PredicateToMongoOptions {
|
|
746
|
+
/**
|
|
747
|
+
* Allowlist of fact / field keys the predicate may reference. STRONGLY
|
|
748
|
+
* RECOMMENDED for any predicate that crosses a trust boundary.
|
|
749
|
+
*/
|
|
750
|
+
allowedKeys?: readonly string[];
|
|
751
|
+
/**
|
|
752
|
+
* Allow `.` in field names (for sub-document traversal: `"user.role"`).
|
|
753
|
+
* Default is `false` — `.` is rejected so the predicate cannot
|
|
754
|
+
* accidentally read sub-document fields the developer did not anticipate.
|
|
755
|
+
*/
|
|
756
|
+
allowDottedPaths?: boolean;
|
|
757
|
+
}
|
|
758
|
+
/**
|
|
759
|
+
* Compile a {@link FactPredicate} to a MongoDB query document.
|
|
760
|
+
*
|
|
761
|
+
* Field names are validated to NOT start with `$` (which would land
|
|
762
|
+
* `$where` and other server-side JS evaluation operators directly in the
|
|
763
|
+
* query — an injection vector for AI/user-generated predicates).
|
|
764
|
+
*
|
|
765
|
+
* @example
|
|
766
|
+
* ```ts
|
|
767
|
+
* predicateToMongo({ age: { $gte: 18 }, status: { $in: ["active", "pending"] } })
|
|
768
|
+
* // → { age: { $gte: 18 }, status: { $in: ["active", "pending"] } }
|
|
769
|
+
*
|
|
770
|
+
* predicateToMongo({ name: { $startsWith: "Al" } })
|
|
771
|
+
* // → { name: { $regex: "^Al" } }
|
|
772
|
+
*
|
|
773
|
+
* predicateToMongo({ $any: [{ tier: "gold" }, { score: { $gte: 100 } }] })
|
|
774
|
+
* // → { $or: [{ tier: "gold" }, { score: { $gte: 100 } }] }
|
|
775
|
+
* ```
|
|
776
|
+
*/
|
|
777
|
+
declare function predicateToMongo<F = Record<string, unknown>>(predicate: FactPredicate<F>, options?: PredicateToMongoOptions): Record<string, unknown>;
|
|
778
|
+
|
|
779
|
+
/**
|
|
780
|
+
* Compile a `FactPredicate` to a PostgREST querystring.
|
|
781
|
+
*
|
|
782
|
+
* PostgREST's filter grammar is column-scoped: `?age=gte.18&status=in.(active,pending)`.
|
|
783
|
+
* Logical groups use `and=(...)` / `or=(...)` / `not.and=(...)`.
|
|
784
|
+
*
|
|
785
|
+
* Reference: https://postgrest.org/en/stable/api.html#operators
|
|
786
|
+
*/
|
|
787
|
+
|
|
788
|
+
interface PredicateToPostgrestOptions {
|
|
789
|
+
/** Allowlist of column keys the predicate may reference. */
|
|
790
|
+
allowedKeys?: readonly string[];
|
|
791
|
+
/**
|
|
792
|
+
* Encoding mode for the returned string.
|
|
793
|
+
* - `"querystring"` (default): a full querystring without a leading `?`,
|
|
794
|
+
* with each clause value URL-encoded — drops straight into `fetch`.
|
|
795
|
+
* - `"raw"`: the same content, leaving `(`, `)`, `,` unencoded for
|
|
796
|
+
* readability. Use this only when you'll encode the result yourself.
|
|
797
|
+
*/
|
|
798
|
+
mode?: "querystring" | "raw";
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* Compile a {@link FactPredicate} to a PostgREST querystring.
|
|
802
|
+
*
|
|
803
|
+
* @example
|
|
804
|
+
* ```ts
|
|
805
|
+
* predicateToPostgrest({ age: { $gte: 18 }, status: { $in: ["active", "pending"] } })
|
|
806
|
+
* // → "age=gte.18&status=in.%28active%2Cpending%29"
|
|
807
|
+
*
|
|
808
|
+
* // Raw mode for debugging / building URLs by hand:
|
|
809
|
+
* predicateToPostgrest({ age: { $gte: 18 } }, { mode: "raw" })
|
|
810
|
+
* // → "age=gte.18"
|
|
811
|
+
*
|
|
812
|
+
* predicateToPostgrest({ $any: [{ tier: "gold" }, { score: { $gte: 100 } }] }, { mode: "raw" })
|
|
813
|
+
* // → "or=(tier.eq.gold,score.gte.100)"
|
|
814
|
+
* ```
|
|
815
|
+
*/
|
|
816
|
+
declare function predicateToPostgrest<F = Record<string, unknown>>(predicate: FactPredicate<F>, options?: PredicateToPostgrestOptions): string;
|
|
817
|
+
|
|
651
818
|
/** Brand symbol for branded types */
|
|
652
819
|
declare const Brand: unique symbol;
|
|
653
820
|
/** Branded type - adds a unique brand to a base type */
|
|
@@ -1908,4 +2075,4 @@ declare const Backoff: {
|
|
|
1908
2075
|
readonly Exponential: "exponential";
|
|
1909
2076
|
};
|
|
1910
2077
|
|
|
1911
|
-
export { Backoff, type Branded, type ChainableSchemaType, type Change, type ChangeKind, ClauseResult, type ConstraintDiff, type ConstraintStatus, CreateSystemOptionsNamed, CreateSystemOptionsSingle, CrossModuleDeps, DefinitionMeta, type DiffRulesOptions, ErrorBoundaryConfig, type ExtendedSchemaType, FactPredicate, FactTemplate, Facts, type LeafClause, MAX_REPLAY_FRAMES, MAX_SWEEP_POINTS, type ModuleConfig, type ModuleConfigWithDeps, ModuleDef, ModuleHooks, ModuleSchema, ModulesMap, NamespacedSystem, PatchSpec, Plugin, type PredicateBacktestReport, type ReplayDiffSample, type ReplayFrame, type ReplayUnderOptions, Requirement, RequirementSet, type RequirementTypeStatus, RequirementWithId, type RulesDiffReport, type RulesMapInput, SchemaType, type SignalClock, SingleModuleSystem, type SweepHole, type SweepPoint, type SweepReport, type SweepUnderOptions, type TimerFactOpts, type TimerFactState, TraceOption, applyPatch, completeTimer, createModule, createModuleFactory, createRequirementStatusPlugin, createStatusHook, createSystem, createSystemWithStatus, defaultClock, diffClauses, diffRules, elapsedMs, evaluateKeySelector, evaluatePredicate, evaluatePredicateExplained, evaluateTemplate, extractDeps, extractTemplateKeys, flattenPredicate, forType, framesFromHistory, framesFromSnapshots, generateRequirementId, initialTimerState, isPredicate, isRequirementType, isTemplate, memoizePredicate, pauseTimer, realClock, registerRepeat, remainingMs, replayUnder, req, resetTimer, resumeTimer, startTimer, sweepUnder, t, tickTimer, timerOps, toReplayFrames, toRulesMap, validatePredicate, virtualClock };
|
|
2078
|
+
export { Backoff, type Branded, type ChainableSchemaType, type Change, type ChangeKind, ClauseResult, type ConstraintDiff, type ConstraintStatus, CreateSystemOptionsNamed, CreateSystemOptionsSingle, CrossModuleDeps, DefinitionMeta, type DiffRulesOptions, ErrorBoundaryConfig, type ExtendedSchemaType, FactPredicate, FactTemplate, Facts, type LeafClause, MAX_REPLAY_FRAMES, MAX_SWEEP_POINTS, type ModuleConfig, type ModuleConfigWithDeps, ModuleDef, ModuleHooks, ModuleSchema, ModulesMap, NamespacedSystem, PatchSpec, Plugin, type PredicateBacktestReport, type PredicateToMongoOptions, type PredicateToPostgrestOptions, type PredicateToSqlOptions, type PredicateToSqlResult, type ReplayDiffSample, type ReplayFrame, type ReplayUnderOptions, Requirement, RequirementSet, type RequirementTypeStatus, RequirementWithId, type RulesDiffReport, type RulesMapInput, SchemaType, type SignalClock, SingleModuleSystem, type SweepHole, type SweepPoint, type SweepReport, type SweepUnderOptions, type TimerFactOpts, type TimerFactState, TraceOption, applyPatch, completeTimer, createModule, createModuleFactory, createRequirementStatusPlugin, createStatusHook, createSystem, createSystemWithStatus, defaultClock, diffClauses, diffRules, elapsedMs, evaluateKeySelector, evaluatePredicate, evaluatePredicateExplained, evaluateTemplate, extractDeps, extractTemplateKeys, flattenPredicate, forType, framesFromHistory, framesFromSnapshots, generateRequirementId, initialTimerState, isPredicate, isRequirementType, isTemplate, memoizePredicate, pauseTimer, predicateToMongo, predicateToPostgrest, predicateToSQL, predicateToWhere, realClock, registerRepeat, remainingMs, replayUnder, req, resetTimer, resumeTimer, startTimer, sweepUnder, t, tickTimer, timerOps, toReplayFrames, toRulesMap, validatePredicate, virtualClock };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-FCOZCTLY.js';export{a as createSystem}from'./chunk-FCOZCTLY.js';import {h,i,g,d as d$1,e,a as a$2,b,c}from'./chunk-ZE2RY5KP.js';export{q as DirectiveError,D as RequirementSet,o as applyPatch,n as evaluateKeySelector,h as evaluatePredicate,i as evaluatePredicateExplained,l as evaluateTemplate,k as extractDeps,m as extractTemplateKeys,C as forType,z as generateRequirementId,w as isNamespacedSystem,d as isPredicate,B as isRequirementType,v as isSingleModuleSystem,f as isTemplate,j as memoizePredicate,A as req,t as typedConstraint,u as typedResolver,g as validatePredicate}from'./chunk-ZE2RY5KP.js';import {a,l}from'./chunk-TZHC4E6S.js';import {d}from'./chunk-T6IJUWYR.js';export{j as diffSnapshots,k as isSignedSnapshot,h as isSnapshotExpired,f as shallowEqual,l as signSnapshot,i as validateSnapshot,m as verifySnapshotSignature}from'./chunk-T6IJUWYR.js';var v=1e6;function J(e$1,n){try{g(e$1);}catch(r){let s=r instanceof Error?r.message:String(r);throw new Error(`[Directive] replayUnder: the ${n} predicate is invalid \u2014 ${s}`)}if(!d$1(e$1)){let r=e$1===null||typeof e$1!="object"?`${typeof e$1} \u2014 ${JSON.stringify(e$1)}`:JSON.stringify(e$1).slice(0,80);throw new Error(`[Directive] replayUnder: the ${n} predicate is not a valid FactPredicate (got ${r})`)}let t;if(e(e$1,{operator(r,s){t===void 0&&s.startsWith("$")&&!a$2.has(s)&&(t=s);},strayOperatorKey(r){t===void 0&&!a$2.has(r)&&!b.has(r)&&(t=r);}}),t!==void 0)throw new Error(`[Directive] replayUnder: the ${n} predicate uses an unknown operator "${t}" \u2014 known operators: ${[...a$2].join(", ")}`)}function Q(e){if(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.snapshots))return Z(e);let n=Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.frames)?e.frames:null;if(!n)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(n.length>v)throw new Error(`[Directive] toReplayFrames: history has ${n.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${v}) \u2014 split or down-sample the history`);return n.map((t,r)=>{if(t&&typeof t=="object"&&"facts"in t){let s=t,o={id:s.id??`#${r}`,facts:s.facts??{}};return typeof s.timestamp=="number"&&(o.timestamp=s.timestamp),o}return {id:`#${r}`,facts:t??{}}})}function Z(e){let n=typeof e=="string"?JSON.parse(e):e;if(Array.isArray(n))return N(n);if(!n||typeof n!="object")throw new Error("[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())");let t=n;if(t.version!==void 0&&t.version!==1)throw new Error(`[Directive] framesFromHistory: unsupported history export version ${JSON.stringify(t.version)} \u2014 expected 1`);if(!Array.isArray(t.snapshots))throw new Error("[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())");return N(t.snapshots)}function N(e){if(!Array.isArray(e))throw new Error("[Directive] framesFromSnapshots: expected an array of fact-state snapshots");if(e.length>v)throw new Error(`[Directive] framesFromSnapshots: history has ${e.length} snapshots, exceeds the MAX_REPLAY_FRAMES limit (${v}) \u2014 split or down-sample the history`);for(let n=0;n<e.length;n++){let t=e[n];if(!t||typeof t!="object"||!("facts"in t))throw new Error(`[Directive] framesFromSnapshots: snapshot at index ${n} is not a { facts, ... } object`)}return Q(e)}function $(e){let{frames:n,original:t,proposed:r,entityKey:s}=e,o=e.maxSamples??20,a=o>0?o:0;if(n.length>v)throw new Error(`[Directive] replayUnder: history has ${n.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${v}) \u2014 split or down-sample the history`);J(t,"original"),J(r,"proposed");let d=0,i=0,u=0,l=0,c=0,m=[],f=[],y=s?new Set:void 0,h$1=s?new Set:void 0,b;for(let D of n){let g=D.facts,S=h(t,g,b),T=h(r,g,b);S&&(d++,y?.add(g[s])),T&&(i++,h$1?.add(g[s])),S===T?c++:!S&&T?(u++,m.length<a&&m.push(G(D,t,r,b))):(l++,f.length<a&&f.push(G(D,t,r,b))),b=g;}let k={framesEvaluated:n.length,original:{matched:d},proposed:{matched:i},delta:i-d,newMatchCount:u,lostMatchCount:l,unchanged:c,newMatches:m,lostMatches:f};return y&&h$1&&(k.original.matchedEntities=y.size,k.proposed.matchedEntities=h$1.size),k}function G(e,n,t,r){let s=e.facts,o={frameId:e.id,facts:s,originalExplain:i(n,s,r),proposedExplain:i(t,s,r)};return e.timestamp!==void 0&&(o.timestamp=e.timestamp),o}var U=1e4,V=5e7;function Be(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===1&&typeof e.$hole=="string"}function q(e,n,t=new Set,r=0){if(r>c)throw new Error(`[Directive] sweepUnder: template exceeds MAX_PREDICATE_DEPTH (${c}) \u2014 flatten the template or split the sweep`);if(Be(e)){let s=e.$hole;if(!(s in n))throw new Error(`[Directive] sweepUnder: template references hole "${s}" but sweep has no values for it`);return n[s]}if(e===null||typeof e!="object")return e;if(t.has(e))throw new Error("[Directive] sweepUnder: template contains a cycle \u2014 predicate templates must be a tree");t.add(e);try{if(Array.isArray(e))return e.map(o=>q(o,n,t,r+1));let s={};for(let[o,a]of Object.entries(e))s[o]=q(a,n,t,r+1);return s}finally{t.delete(e);}}function*ee(e,n){if(e.length===0){yield {};return}let t=e[0],r=e.slice(1),s=n[t]??[];for(let o of s)for(let a of ee(r,n))yield {[t]:o,...a};}function Ne(e){let n=1;for(let t of Object.values(e))n*=t.length;return n}function Ue(e){let{frames:n,original:t,template:r,sweep:s,objective:o=g=>g.proposed.matched,entityKey:a,maxSamples:d=0}=e,i=Object.keys(s);if(i.length===0)throw new Error("[Directive] sweepUnder: `sweep` must contain at least one hole name");let u=Ne(s);if(u>U)throw new Error(`[Directive] sweepUnder: grid has ${u} points, exceeds the MAX_SWEEP_POINTS limit (${U}) \u2014 narrow the sweep ranges or split the run`);if(u===0)throw new Error("[Directive] sweepUnder: at least one hole has zero candidate values");let l=u*n.length;if(l>V)throw new Error(`[Directive] sweepUnder: ${u} points \xD7 ${n.length} frames = ${l} per-frame evaluations, exceeds the MAX_SWEEP_EVALUATIONS limit (${V}) \u2014 narrow the sweep, down-sample the history, or split the run`);let c=false,m=g=>{let S;try{S=o(g);}catch(T){return c||(c=true,console.warn(`[Directive] sweepUnder: objective threw \u2014 point will not rank (${T.message})`)),Number.NEGATIVE_INFINITY}return typeof S!="number"||!Number.isFinite(S)?(c||(c=true,console.warn(`[Directive] sweepUnder: objective returned a non-finite number (${String(S)}) \u2014 point will not rank`)),Number.NEGATIVE_INFINITY):S},f=$({frames:n,original:t,proposed:t,entityKey:a,maxSamples:d}),y={values:{},report:f,score:m(f)},h=[],b=0,k=Number.NEGATIVE_INFINITY;for(let g of ee(i,s)){let S=q(r,g),T=$({frames:n,original:t,proposed:S,entityKey:a,maxSamples:d}),O=m(T);O>k&&(k=O,b=h.length),h.push({values:g,report:T,score:O});}let D=h[b];return {points:h,bestIndex:b,best:D,baseline:y}}function W(e){let n=e&&typeof e=="object"&&!Array.isArray(e)&&"constraints"in e?e.constraints:e;if(Array.isArray(n)){let t={};for(let r of n){if(!r||typeof r!="object"||!("id"in r))throw new Error("[Directive] diffRules: array entries must be `{ id, whenSpec }` objects");let s=r;if(typeof s.id!="string")throw new Error("[Directive] diffRules: constraint `id` must be a string");t[s.id]=s.whenSpec;}return t}if(n&&typeof n=="object")return n;throw new Error("[Directive] diffRules: expected a `{ id: whenSpec }` map, an array of `{ id, whenSpec }`, or `{ constraints: ... }`")}var qe=new Set(["$eq","$ne","$in","$nin","$exists","$gt","$gte","$lt","$lte","$between","$matches","$startsWith","$endsWith","$contains","$changed"]),We=new Set(["$all","$any","$not"]);function ne(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Le(e){if(!ne(e))return false;let n=Object.keys(e);if(n.length===0)return false;let t=false;for(let r of n){if(!r.startsWith("$"))return false;qe.has(r)&&(t=true);}return t}function M(e,n="",t=[]){if(e===null||typeof e!="object")return t;if(Array.isArray(e)){for(let r of e)if(r&&typeof r=="object"&&"fact"in r&&"op"in r){let s=r;t.push({path:n?`${n}.${String(s.fact)}`:String(s.fact),op:String(s.op),value:s.value});}return t}if("$all"in e&&Array.isArray(e.$all))return e.$all.forEach((s,o)=>{M(s,`${n}$all[${o}]`,t);}),t;if("$any"in e&&Array.isArray(e.$any))return e.$any.forEach((s,o)=>{M(s,`${n}$any[${o}]`,t);}),t;if("$not"in e)return M(e.$not,`${n}$not`,t),t;for(let[r,s]of Object.entries(e)){let o=n?`${n}.${r}`:r;if(Le(s))for(let[a,d]of Object.entries(s))t.push({path:o,op:a,value:d});else ne(s)&&!We.has(r)?M(s,o,t):t.push({path:o,op:"$eq",value:s});}return t}function w(e){return typeof e=="number"&&Number.isFinite(e)}function Ke(e,n,t){switch(e){case "$gte":case "$gt":if(w(n)&&w(t)){if(t<n)return "relaxed";if(t>n)return "tightened"}return null;case "$lte":case "$lt":if(w(n)&&w(t)){if(t>n)return "relaxed";if(t<n)return "tightened"}return null;case "$between":{if(Array.isArray(n)&&Array.isArray(t)&&n.length===2&&t.length===2&&w(n[0])&&w(n[1])&&w(t[0])&&w(t[1])){let r=n[1]-n[0],s=t[1]-t[0];if(s>r)return "relaxed";if(s<r)return "tightened"}return null}case "$in":case "$nin":{if(Array.isArray(n)&&Array.isArray(t))if(e==="$in"){if(t.length>n.length)return "relaxed";if(t.length<n.length)return "tightened"}else {if(t.length>n.length)return "tightened";if(t.length<n.length)return "relaxed"}return null}case "$contains":{if(Array.isArray(n)&&Array.isArray(t)){if(t.length>n.length)return "relaxed";if(t.length<n.length)return "tightened"}return null}default:return null}}function He(e){let n=W(e.before),t=W(e.after),s=[...new Set([...Object.keys(n),...Object.keys(t)])].sort(),o=[],a={added:0,removed:0,changed:0,unchanged:0,totalClauseChanges:0};for(let d of s){let i=n[d],u=t[d],l=d in n,c=d in t;if(l&&!c){let f=M(i),y=f.length===0?[{path:"(function-form predicate)",kind:"removed"}]:f.map(h=>({path:h.path,kind:"removed",before:{op:h.op,value:h.value}}));L(y),o.push({id:d,status:"removed",changes:y}),a.removed++,a.totalClauseChanges+=y.length;continue}if(!l&&c){let f=M(u),y=f.length===0?[{path:"(function-form predicate)",kind:"added"}]:f.map(h=>({path:h.path,kind:"added",after:{op:h.op,value:h.value}}));L(y),o.push({id:d,status:"added",changes:y}),a.added++,a.totalClauseChanges+=y.length;continue}let m=te(i,u);m.length===0?(o.push({id:d,status:"unchanged",changes:[]}),a.unchanged++):(o.push({id:d,status:"changed",changes:m}),a.changed++,a.totalClauseChanges+=m.length);}return {constraints:o,summary:a}}function te(e,n){if(e!==void 0&&n!==void 0&&(e===null||n===null||typeof e!="object"||typeof n!="object"))return d(e)===d(n)?[]:[{path:"",kind:"changed",before:{op:"$eq",value:e},after:{op:"$eq",value:n}}];let t=e===void 0?[]:M(e),r=n===void 0?[]:M(n),s=u=>`${u.path}::${u.op}`,o=new Map(t.map(u=>[s(u),u])),a=new Map(r.map(u=>[s(u),u])),d$1=new Set([...o.keys(),...a.keys()]),i=[];for(let u of d$1){let l=o.get(u),c=a.get(u);if(l&&!c){i.push({path:l.path,kind:"removed",before:{op:l.op,value:l.value}});continue}if(!l&&c){i.push({path:c.path,kind:"added",after:{op:c.op,value:c.value}});continue}if(l&&c){if(d(l.value)===d(c.value))continue;let m=Ke(l.op,l.value,c.value);i.push({path:l.path,kind:m??"changed",before:{op:l.op,value:l.value},after:{op:c.op,value:c.value}});}}return L(i),i}function L(e){e.sort((n,t)=>{let r=n.path.localeCompare(t.path);if(r!==0)return r;let s=n.before?.op??n.after?.op??"",o=t.before?.op??t.after?.op??"";return s.localeCompare(o)});}function F(e=[],n,t,r,s,o,a){return {_type:void 0,_validators:e,_typeName:n,_default:t,_transform:r,_description:s,_refinements:o,_meta:a,validate(d){return F([...e,d],n,t,r,s,o,a)}}}function p(e,n,t,r,s,o,a){return {...F(e,n,t,r,s,o,a),default(i){return p(e,n,i,r,s,o,a)},transform(i){return p([],n,void 0,l=>{let c=r?r(l):l;return i(c)},s,void 0,a)},brand(){return p(e,`Branded<${n}>`,t,r,s,o,a)},describe(i){return p(e,n,t,r,i,o,a)},refine(i,u){let l=[...o??[],{predicate:i,message:u}];return p([...e,i],n,t,r,s,l,a)},nullable(){return p([i=>i===null||e.every(u=>u(i))],`${n} | null`,t,r,s,void 0,a)},optional(){return p([i=>i===void 0||e.every(u=>u(i))],`${n} | undefined`,t,r,s,void 0,a)},meta(i){return p(e,n,t,r,s,o,i)}}}var ze=((...e)=>{if(e.length===0)return p([],"union");let n=e.map(t=>t._typeName??"unknown");return p([t=>e.some(r=>r._validators.every(s=>s(t)))],n.join(" | "))}),Xe={string(){let e=(n,t,r,s,o,a)=>({...p(n,"string",t,r,s,o,a),minLength(i){return e([...n,u=>u.length>=i],t,r,s,o,a)},maxLength(i){return e([...n,u=>u.length<=i],t,r,s,o,a)},pattern(i){return e([...n,u=>i.test(u)],t,r,s,o,a)},default(i){return e(n,i,r,s,o,a)},describe(i){return e(n,t,r,i,o,a)},refine(i,u){let l=[...o??[],{predicate:i,message:u}];return e([...n,i],t,r,s,l,a)},meta(i){return e(n,t,r,s,o,i)}});return e([n=>typeof n=="string"])},number(){let e=(n,t,r,s,o,a)=>({...p(n,"number",t,r,s,o,a),min(i){return e([...n,u=>u>=i],t,r,s,o,a)},max(i){return e([...n,u=>u<=i],t,r,s,o,a)},default(i){return e(n,i,r,s,o,a)},describe(i){return e(n,t,r,i,o,a)},refine(i,u){let l=[...o??[],{predicate:i,message:u}];return e([...n,i],t,r,s,l,a)},meta(i){return e(n,t,r,s,o,i)}});return e([n=>typeof n=="number"])},boolean(){return p([e=>typeof e=="boolean"],"boolean")},array(){let e=(n,t,r,s,o,a)=>{let d=p(n,"array",r,void 0,s,void 0,a),i=o??{value:-1};return {...d,get _lastFailedIndex(){return i.value},set _lastFailedIndex(l){i.value=l;},of(l){let c={value:-1};return e([...n,m=>{for(let f=0;f<m.length;f++)if(!l._validators.every(y=>y(m[f])))return c.value=f,false;return true}],l,r,s,c,a)},nonEmpty(){return e([...n,l=>l.length>0],t,r,s,i,a)},maxLength(l){return e([...n,c=>c.length<=l],t,r,s,i,a)},minLength(l){return e([...n,c=>c.length>=l],t,r,s,i,a)},default(l){return e(n,t,l,s,i,a)},describe(l){return e(n,t,r,l,i,a)},meta(l){return e(n,t,r,s,i,l)}}};return e([n=>Array.isArray(n)])},object(){let e=(n,t,r,s)=>({...p(n,"object",t,void 0,r,void 0,s),shape(a){return e([...n,d=>{for(let[i,u]of Object.entries(a)){let l=d[i],c=u;if(c&&!c._validators.every(m=>m(l)))return false}return true}],t,r,s)},nonNull(){return e([...n,a=>a!=null],t,r,s)},hasKeys(...a){return e([...n,d=>a.every(i=>i in d)],t,r,s)},default(a){return e(n,a,r,s)},describe(a){return e(n,t,a,s)},meta(a){return e(n,t,r,a)}});return e([n=>typeof n=="object"&&n!==null&&!Array.isArray(n)])},enum(...e){a&&e.length===0&&console.warn("[Directive] t.enum() called with no values - this will reject all strings");let n=new Set(e);return p([t=>typeof t=="string"&&n.has(t)],`enum(${e.join("|")})`)},literal(e){return p([n=>n===e],`literal(${String(e)})`)},nullable(e){let n=e._typeName??"unknown";return F([t=>t===null?true:e._validators.every(r=>r(t))],`${n} | null`)},optional(e){let n=e._typeName??"unknown";return F([t=>t===void 0?true:e._validators.every(r=>r(t))],`${n} | undefined`)},union:ze,record(e){let n=e._typeName??"unknown";return p([t=>typeof t!="object"||t===null||Array.isArray(t)?false:Object.values(t).every(r=>e._validators.every(s=>s(r)))],`Record<string, ${n}>`)},tuple(...e){a&&e.length===0&&console.warn("[Directive] t.tuple() called with no types - this will only accept empty arrays");let n=e.map(t=>t._typeName??"unknown");return p([t=>!Array.isArray(t)||t.length!==e.length?false:e.every((r,s)=>r._validators.every(o=>o(t[s])))],`[${n.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([n=>typeof n=="string"&&e.test(n)],"uuid")},email(){let e=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return p([n=>typeof n=="string"&&e.test(n)],"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 Ye(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 re(e,n,t,r,s){for(let o of e)n.has(o)||console.warn(`[Directive] ${t} "${o}" not declared in ${r}`);for(let o of n)e.has(o)||console.warn(`[Directive] ${r}["${o}"] ${s}`);}function Je(e,n){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 t=new Set(Object.keys(n));for(let r of e)t.has(r)||console.warn(`[Directive] history.snapshotEvents entry "${r}" not declared in schema.events. Available events: ${[...t].join(", ")||"(none)"}`);}function Ge(e,n){let t=new Set(Object.keys(n));for(let[r,s]of Object.entries(e)){let o=s;typeof o.requirement=="string"&&!t.has(o.requirement)&&console.warn(`[Directive] Resolver "${r}" references unknown requirement type "${o.requirement}". Available types: ${[...t].join(", ")||"(none)"}`);}}function Qe(e,n){let t=n.schema?.facts??{},r=Object.keys(t);if(r.length===0)return;let s=new Set(["self","prev","current"]),o="crossModuleDeps"in n&&n.crossModuleDeps?Object.keys(n.crossModuleDeps):[];for(let a of o)s.add(a);for(let a of r)if(s.has(a))throw new Error(`[Directive] module '${e}': fact key '${a}' conflicts with a reserved namespace pivot or evaluation alias (self / prev / current / a crossModuleDep namespace). Three fixes:
|
|
2
|
-
1. Rename the fact (e.g. ${
|
|
3
|
-
2. Remove '${
|
|
4
|
-
3. Move the fact under a wrapping namespace (t.object({ inner: ... }))`)}function
|
|
1
|
+
import {a as a$1}from'./chunk-FCOZCTLY.js';export{a as createSystem}from'./chunk-FCOZCTLY.js';import {h,i,g,d as d$1,e,a as a$2,b,c}from'./chunk-ZE2RY5KP.js';export{q as DirectiveError,D as RequirementSet,o as applyPatch,n as evaluateKeySelector,h as evaluatePredicate,i as evaluatePredicateExplained,l as evaluateTemplate,k as extractDeps,m as extractTemplateKeys,C as forType,z as generateRequirementId,w as isNamespacedSystem,d as isPredicate,B as isRequirementType,v as isSingleModuleSystem,f as isTemplate,j as memoizePredicate,A as req,t as typedConstraint,u as typedResolver,g as validatePredicate}from'./chunk-ZE2RY5KP.js';import {a,l}from'./chunk-TZHC4E6S.js';import {d}from'./chunk-T6IJUWYR.js';export{j as diffSnapshots,k as isSignedSnapshot,h as isSnapshotExpired,f as shallowEqual,l as signSnapshot,i as validateSnapshot,m as verifySnapshotSignature}from'./chunk-T6IJUWYR.js';var R=1e6;function fe(e$1,t){try{g(e$1);}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`[Directive] replayUnder: the ${t} predicate is invalid \u2014 ${i}`)}if(!d$1(e$1)){let r=e$1===null||typeof e$1!="object"?`${typeof e$1} \u2014 ${JSON.stringify(e$1)}`:JSON.stringify(e$1).slice(0,80);throw new Error(`[Directive] replayUnder: the ${t} predicate is not a valid FactPredicate (got ${r})`)}let n;if(e(e$1,{operator(r,i){n===void 0&&i.startsWith("$")&&!a$2.has(i)&&(n=i);},strayOperatorKey(r){n===void 0&&!a$2.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$2].join(", ")}`)}function he(e){if(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.snapshots))return me(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,o={id:i.id??`#${r}`,facts:i.facts??{}};return typeof i.timestamp=="number"&&(o.timestamp=i.timestamp),o}return {id:`#${r}`,facts:n??{}}})}function me(e){let t=typeof e=="string"?JSON.parse(e):e;if(Array.isArray(t))return Q(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 Q(n.snapshots)}function Q(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 he(e)}function N(e){let{frames:t,original:n,proposed:r,entityKey:i}=e,o=e.maxSamples??20,s=o>0?o: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`);fe(n,"original"),fe(r,"proposed");let c=0,a=0,u=0,l=0,d=0,f=[],g=[],y=i?new Set:void 0,h$1=i?new Set:void 0,v;for(let C of t){let b=C.facts,S=h(n,b,v),k=h(r,b,v);S&&(c++,y?.add(b[i])),k&&(a++,h$1?.add(b[i])),S===k?d++:!S&&k?(u++,f.length<s&&f.push(ge(C,n,r,v))):(l++,g.length<s&&g.push(ge(C,n,r,v))),v=b;}let E={framesEvaluated:t.length,original:{matched:c},proposed:{matched:a},delta:a-c,newMatchCount:u,lostMatchCount:l,unchanged:d,newMatches:f,lostMatches:g};return y&&h$1&&(E.original.matchedEntities=y.size,E.proposed.matchedEntities=h$1.size),E}function ge(e,t,n,r){let i$1=e.facts,o={frameId:e.id,facts:i$1,originalExplain:i(t,i$1,r),proposedExplain:i(n,i$1,r)};return e.timestamp!==void 0&&(o.timestamp=e.timestamp),o}var Z=1e4,ye=5e7;function dt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===1&&typeof e.$hole=="string"}function X(e,t,n=new Set,r=0){if(r>c)throw new Error(`[Directive] sweepUnder: template exceeds MAX_PREDICATE_DEPTH (${c}) \u2014 flatten the template or split the sweep`);if(dt(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(o=>X(o,t,n,r+1));let i={};for(let[o,s]of Object.entries(e))i[o]=X(s,t,n,r+1);return i}finally{n.delete(e);}}function*we(e,t){if(e.length===0){yield {};return}let n=e[0],r=e.slice(1),i=t[n]??[];for(let o of i)for(let s of we(r,t))yield {[n]:o,...s};}function pt(e){let t=1;for(let n of Object.values(e))t*=n.length;return t}function ft(e){let{frames:t,original:n,template:r,sweep:i,objective:o=b=>b.proposed.matched,entityKey:s,maxSamples:c=0}=e,a=Object.keys(i);if(a.length===0)throw new Error("[Directive] sweepUnder: `sweep` must contain at least one hole name");let u=pt(i);if(u>Z)throw new Error(`[Directive] sweepUnder: grid has ${u} points, exceeds the MAX_SWEEP_POINTS limit (${Z}) \u2014 narrow the sweep ranges or split the run`);if(u===0)throw new Error("[Directive] sweepUnder: at least one hole has zero candidate values");let l=u*t.length;if(l>ye)throw new Error(`[Directive] sweepUnder: ${u} points \xD7 ${t.length} frames = ${l} per-frame evaluations, exceeds the MAX_SWEEP_EVALUATIONS limit (${ye}) \u2014 narrow the sweep, down-sample the history, or split the run`);let d=false,f=b=>{let S;try{S=o(b);}catch(k){return d||(d=true,console.warn(`[Directive] sweepUnder: objective threw \u2014 point will not rank (${k.message})`)),Number.NEGATIVE_INFINITY}return typeof S!="number"||!Number.isFinite(S)?(d||(d=true,console.warn(`[Directive] sweepUnder: objective returned a non-finite number (${String(S)}) \u2014 point will not rank`)),Number.NEGATIVE_INFINITY):S},g=N({frames:t,original:n,proposed:n,entityKey:s,maxSamples:c}),y={values:{},report:g,score:f(g)},h=[],v=0,E=Number.NEGATIVE_INFINITY;for(let b of we(a,i)){let S=X(r,b),k=N({frames:t,original:n,proposed:S,entityKey:s,maxSamples:c}),U=f(k);U>E&&(E=U,v=h.length),h.push({values:b,report:k,score:U});}let C=h[v];return {points:h,bestIndex:v,best:C,baseline:y}}function Y(e){let t=e&&typeof e=="object"&&!Array.isArray(e)&&"constraints"in e?e.constraints:e;if(Array.isArray(t)){let n={};for(let r of t){if(!r||typeof r!="object"||!("id"in r))throw new Error("[Directive] diffRules: array entries must be `{ id, whenSpec }` objects");let i=r;if(typeof i.id!="string")throw new Error("[Directive] diffRules: constraint `id` must be a string");n[i.id]=i.whenSpec;}return n}if(t&&typeof t=="object")return t;throw new Error("[Directive] diffRules: expected a `{ id: whenSpec }` map, an array of `{ id, whenSpec }`, or `{ constraints: ... }`")}var gt=new Set(["$eq","$ne","$in","$nin","$exists","$gt","$gte","$lt","$lte","$between","$matches","$startsWith","$endsWith","$contains","$changed"]),ht=new Set(["$all","$any","$not"]);function be(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function mt(e){if(!be(e))return false;let t=Object.keys(e);if(t.length===0)return false;let n=false;for(let r of t){if(!r.startsWith("$"))return false;gt.has(r)&&(n=true);}return n}function M(e,t="",n=[]){if(e===null||typeof e!="object")return n;if(Array.isArray(e)){for(let r of e)if(r&&typeof r=="object"&&"fact"in r&&"op"in r){let i=r;n.push({path:t?`${t}.${String(i.fact)}`:String(i.fact),op:String(i.op),value:i.value});}return n}if("$all"in e&&Array.isArray(e.$all))return e.$all.forEach((i,o)=>{M(i,`${t}$all[${o}]`,n);}),n;if("$any"in e&&Array.isArray(e.$any))return e.$any.forEach((i,o)=>{M(i,`${t}$any[${o}]`,n);}),n;if("$not"in e)return M(e.$not,`${t}$not`,n),n;for(let[r,i]of Object.entries(e)){let o=t?`${t}.${r}`:r;if(mt(i))for(let[s,c]of Object.entries(i))n.push({path:o,op:s,value:c});else be(i)&&!ht.has(r)?M(i,o,n):n.push({path:o,op:"$eq",value:i});}return n}function D(e){return typeof e=="number"&&Number.isFinite(e)}function yt(e,t,n){switch(e){case "$gte":case "$gt":if(D(t)&&D(n)){if(n<t)return "relaxed";if(n>t)return "tightened"}return null;case "$lte":case "$lt":if(D(t)&&D(n)){if(n>t)return "relaxed";if(n<t)return "tightened"}return null;case "$between":{if(Array.isArray(t)&&Array.isArray(n)&&t.length===2&&n.length===2&&D(t[0])&&D(t[1])&&D(n[0])&&D(n[1])){let r=t[1]-t[0],i=n[1]-n[0];if(i>r)return "relaxed";if(i<r)return "tightened"}return null}case "$in":case "$nin":{if(Array.isArray(t)&&Array.isArray(n))if(e==="$in"){if(n.length>t.length)return "relaxed";if(n.length<t.length)return "tightened"}else {if(n.length>t.length)return "tightened";if(n.length<t.length)return "relaxed"}return null}case "$contains":{if(Array.isArray(t)&&Array.isArray(n)){if(n.length>t.length)return "relaxed";if(n.length<t.length)return "tightened"}return null}default:return null}}function wt(e){let t=Y(e.before),n=Y(e.after),i=[...new Set([...Object.keys(t),...Object.keys(n)])].sort(),o=[],s={added:0,removed:0,changed:0,unchanged:0,totalClauseChanges:0};for(let c of i){let a=t[c],u=n[c],l=c in t,d=c in n;if(l&&!d){let g=M(a),y=g.length===0?[{path:"(function-form predicate)",kind:"removed"}]:g.map(h=>({path:h.path,kind:"removed",before:{op:h.op,value:h.value}}));J(y),o.push({id:c,status:"removed",changes:y}),s.removed++,s.totalClauseChanges+=y.length;continue}if(!l&&d){let g=M(u),y=g.length===0?[{path:"(function-form predicate)",kind:"added"}]:g.map(h=>({path:h.path,kind:"added",after:{op:h.op,value:h.value}}));J(y),o.push({id:c,status:"added",changes:y}),s.added++,s.totalClauseChanges+=y.length;continue}let f=Te(a,u);f.length===0?(o.push({id:c,status:"unchanged",changes:[]}),s.unchanged++):(o.push({id:c,status:"changed",changes:f}),s.changed++,s.totalClauseChanges+=f.length);}return {constraints:o,summary:s}}function Te(e,t){if(e!==void 0&&t!==void 0&&(e===null||t===null||typeof e!="object"||typeof t!="object"))return d(e)===d(t)?[]:[{path:"",kind:"changed",before:{op:"$eq",value:e},after:{op:"$eq",value:t}}];let n=e===void 0?[]:M(e),r=t===void 0?[]:M(t),i=u=>`${u.path}::${u.op}`,o=new Map(n.map(u=>[i(u),u])),s=new Map(r.map(u=>[i(u),u])),c=new Set([...o.keys(),...s.keys()]),a=[];for(let u of c){let l=o.get(u),d$1=s.get(u);if(l&&!d$1){a.push({path:l.path,kind:"removed",before:{op:l.op,value:l.value}});continue}if(!l&&d$1){a.push({path:d$1.path,kind:"added",after:{op:d$1.op,value:d$1.value}});continue}if(l&&d$1){if(d(l.value)===d(d$1.value))continue;let f=yt(l.op,l.value,d$1.value);a.push({path:l.path,kind:f??"changed",before:{op:l.op,value:l.value},after:{op:d$1.op,value:d$1.value}});}}return J(a),a}function J(e){e.sort((t,n)=>{let r=t.path.localeCompare(n.path);if(r!==0)return r;let i=t.before?.op??t.after?.op??"",o=n.before?.op??n.after?.op??"";return i.localeCompare(o)});}var bt=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?$/;function F(e,t){if(typeof e!="string"||!bt.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 $e(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 Tt(e){if(Array.isArray(e)){if(e.length===0)throw new Error("[Directive] predicateToSQL: select must not be empty");for(let n of e)F(n,"column");return e.join(", ")}let t=e;return t==="*"?"*":(F(t,"column"),t)}function w(e,t){return e.params.push(t),e.placeholder(e.params.length)}function G(e,t,n,r){switch(t){case "$eq":return `${e} = ${w(r,n)}`;case "$ne":return `${e} <> ${w(r,n)}`;case "$gt":return `${e} > ${w(r,n)}`;case "$gte":return `${e} >= ${w(r,n)}`;case "$lt":return `${e} < ${w(r,n)}`;case "$lte":return `${e} <= ${w(r,n)}`;case "$in":if(!Array.isArray(n))throw new Error("[Directive] predicateToSQL: $in operand must be an array");return `${e} = ANY(${w(r,n)})`;case "$nin":if(!Array.isArray(n))throw new Error("[Directive] predicateToSQL: $nin operand must be an array");return `NOT (${e} = ANY(${w(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 ${w(r,n[0])} AND ${w(r,n[1])}`}case "$startsWith":if(typeof n!="string")throw new Error("[Directive] predicateToSQL: $startsWith operand must be a string");return `${e} LIKE ${w(r,V(n))} || '%' ESCAPE '\\'`;case "$endsWith":if(typeof n!="string")throw new Error("[Directive] predicateToSQL: $endsWith operand must be a string");return `${e} LIKE '%' || ${w(r,V(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 '%' || ${w(r,V(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} ${w(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$2].join(", ")}`)}}function V(e){return e.replace(/[\\%_]/g,"\\$&")}function Se(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function $t(e){if(!Se(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 ee(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 O(e,t,n){if(n>c)throw new Error(`[Directive] predicateToSQL: predicate depth limit (${c}) 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(o=>{if(!o||typeof o!="object"||!("fact"in o)||!("op"in o))throw new Error("[Directive] predicateToSQL: array-form clause must be { fact, op, value }");let s=o;return F(s.fact,"column"),$e(s.fact,t.allowed),G(s.fact,s.op,s.value,t)});return i.length===1?i[0]:`(${i.join(" AND ")})`}if("$all"in e){ee(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 o=i.map(s=>O(s,t,n+1));return o.length===1?o[0]:`(${o.join(" AND ")})`}if("$any"in e){ee(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 o=i.map(s=>O(s,t,n+1));return o.length===1?o[0]:`(${o.join(" OR ")})`}if("$not"in e){ee(e,"$not");let i=e.$not;return `NOT (${O(i,t,n+1)})`}let r=[];for(let[i,o]of Object.entries(e))if(F(i,"column"),$e(i,t.allowed),$t(o))for(let[s,c]of Object.entries(o)){if(!a$2.has(s))throw new Error(`[Directive] predicateToSQL: unknown operator "${s}" on column "${i}" \u2014 known: ${[...a$2].join(", ")}`);r.push(G(i,s,c,t));}else {if(Se(o))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(G(i,"$eq",o,t));}return r.length===0?"TRUE":r.length===1?r[0]:`(${r.join(" AND ")})`}var ve=e=>`$${e}`;function St(e,t){let{table:n,allowedKeys:r}=t,i=t.placeholder??ve,o=t.select??"*";F(n,"table");let s=Tt(o),c={params:[],placeholder:i,allowed:r},a=O(e,c,0);return {sql:`SELECT ${s} FROM ${n} WHERE ${a}`,where:a,params:c.params}}function vt(e,t={}){let n=t.placeholder??ve,r={params:[],placeholder:n,allowed:t.allowedKeys};return {where:O(e,r,0),params:r.params}}function te(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function re(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Mt(e){if(!re(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 kt=/^[A-Za-z_][A-Za-z0-9_]*$/,Dt=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/;function Me(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?Dt:kt).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 ke(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 ne(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 De(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:`^${te(t)}`};case "$endsWith":if(typeof t!="string")throw new Error("[Directive] predicateToMongo: $endsWith operand must be a string");return {$regex:`${te(t)}$`};case "$contains":if(typeof t=="string")return {$regex:te(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$2].join(", ")}`)}}function A(e,t,n){if(n>c)throw new Error(`[Directive] predicateToMongo: predicate depth limit (${c}) 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={},o=[];for(let s of e){if(!s||typeof s!="object"||!("fact"in s)||!("op"in s))throw new Error("[Directive] predicateToMongo: array-form clause must be { fact, op, value }");let c=s;Me(c.fact,t),ke(c.fact,t.allowedKeys);let a=De(c.op,c.value);if(c.fact in i&&re(i[c.fact])){let u=i[c.fact];Object.keys(a).some(d=>d in u)?o.push({[c.fact]:a}):i[c.fact]={...u,...a};}else c.fact in i?o.push({[c.fact]:a}):i[c.fact]=a;}if(o.length>0){let s=[];for(let[c,a]of Object.entries(i))s.push({[c]:a});return s.push(...o),{$and:s}}return i}if("$all"in e){ne(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?A(i[0],t,n+1):{$and:i.map(o=>A(o,t,n+1))}}if("$any"in e){ne(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?A(i[0],t,n+1):{$or:i.map(o=>A(o,t,n+1))}}if("$not"in e){ne(e,"$not");let i=e.$not;return {$nor:[A(i,t,n+1)]}}let r={};for(let[i,o]of Object.entries(e))if(Me(i,t),ke(i,t.allowedKeys),Mt(o)){let s={};for(let[c,a]of Object.entries(o)){if(!a$2.has(c))throw new Error(`[Directive] predicateToMongo: unknown operator "${c}" on field "${i}" \u2014 known: ${[...a$2].join(", ")}`);Object.assign(s,De(c,a));}r[i]=s;}else r[i]=o;return r}function Rt(e,t={}){return A(e,t,0)}var Et=/^[A-Za-z_][A-Za-z0-9_]*$/;function Re(e,t){if(typeof e!="string"||!Et.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 ie(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 $(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 Ee(e){return `(${e.map($).join(",")})`}function oe(e){return e.replace(/[\\%_*]/g,"\\$&")}function x(e,t){switch(e){case "$eq":return `eq.${$(t)}`;case "$ne":return `neq.${$(t)}`;case "$gt":return `gt.${$(t)}`;case "$gte":return `gte.${$(t)}`;case "$lt":return `lt.${$(t)}`;case "$lte":return `lte.${$(t)}`;case "$in":if(!Array.isArray(t))throw new Error("[Directive] predicateToPostgrest: $in operand must be an array");return `in.${Ee(t)}`;case "$nin":if(!Array.isArray(t))throw new Error("[Directive] predicateToPostgrest: $nin operand must be an array");return `not.in.${Ee(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.${$(oe(t)+"*")}`;case "$endsWith":if(typeof t!="string")throw new Error("[Directive] predicateToPostgrest: $endsWith operand must be a string");return `like.${$("*"+oe(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.${$("*"+oe(t)+"*")}`;case "$matches":if(t instanceof RegExp)return `${t.flags.includes("i")?"imatch":"match"}.${$(t.source)}`;if(typeof t=="string")return `match.${$(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$2].join(", ")}`)}}function Ae(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function At(e){if(!Ae(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 se(e,t){return `${e}=${t}`}function L(e,t){return `${e}=(${t.join(",")})`}function ae(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?se(e,x("$gte",n[0])):`${e}.${x("$gte",n[0])}`,o=r?se(e,x("$lte",n[1])):`${e}.${x("$lte",n[1])}`;return [i,o]}return [r?se(e,x(t,n)):`${e}.${x(t,n)}`]}function _(e,t,n,r){if(r>c)throw new Error(`[Directive] predicateToPostgrest: predicate depth limit (${c}) 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 o=[];for(let s of e){if(!s||typeof s!="object"||!("fact"in s)||!("op"in s))throw new Error("[Directive] predicateToPostgrest: array-form clause must be { fact, op, value }");let c=s;Re(c.fact,t),o.push(...ae(c.fact,c.op,c.value,n));}return o}if("$all"in e){ie(e,"$all");let o=e.$all;if(!Array.isArray(o))throw new Error("[Directive] predicateToPostgrest: $all must be an array");if(n){let c=[];for(let a of o)c.push(..._(a,t,true,r+1));return c}let s=[];for(let c of o)s.push(..._(c,t,false,r+1));return [L("and",s)]}if("$any"in e){ie(e,"$any");let o=e.$any;if(!Array.isArray(o))throw new Error("[Directive] predicateToPostgrest: $any must be an array");if(o.length===0)return n?["id=is.null","id=not.is.null"]:[L("and",["id.is.null","id.not.is.null"])];let s=[];for(let c of o)s.push(..._(c,t,false,r+1));return [L("or",s)]}if("$not"in e){ie(e,"$not");let o=e.$not,s=_(o,t,false,r+1);return [L("not.and",s)]}let i=[];for(let[o,s]of Object.entries(e))if(Re(o,t),At(s))for(let[c,a]of Object.entries(s)){if(!a$2.has(c))throw new Error(`[Directive] predicateToPostgrest: unknown operator "${c}" on column "${o}" \u2014 known: ${[...a$2].join(", ")}`);i.push(...ae(o,c,a,n));}else {if(Ae(s))throw new Error(`[Directive] predicateToPostgrest: nested predicate at "${o}" \u2014 single-table queries only`);i.push(...ae(o,"$eq",s,n));}return i}function xt(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 Ct(e,t={}){let n=t.mode??"querystring",r=_(e,t.allowedKeys,true,0);return r.length===0?"":n==="raw"?r.join("&"):r.map(xt).join("&")}function B(e=[],t,n,r,i,o,s){return {_type:void 0,_validators:e,_typeName:t,_default:n,_transform:r,_description:i,_refinements:o,_meta:s,validate(c){return B([...e,c],t,n,r,i,o,s)}}}function p(e,t,n,r,i,o,s){return {...B(e,t,n,r,i,o,s),default(a){return p(e,t,a,r,i,o,s)},transform(a){return p([],t,void 0,l=>{let d=r?r(l):l;return a(d)},i,void 0,s)},brand(){return p(e,`Branded<${t}>`,n,r,i,o,s)},describe(a){return p(e,t,n,r,a,o,s)},refine(a,u){let l=[...o??[],{predicate:a,message:u}];return p([...e,a],t,n,r,i,l,s)},nullable(){return p([a=>a===null||e.every(u=>u(a))],`${t} | null`,n,r,i,void 0,s)},optional(){return p([a=>a===void 0||e.every(u=>u(a))],`${t} | undefined`,n,r,i,void 0,s)},meta(a){return p(e,t,n,r,i,o,a)}}}var jt=((...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(" | "))}),Pt={string(){let e=(t,n,r,i,o,s)=>({...p(t,"string",n,r,i,o,s),minLength(a){return e([...t,u=>u.length>=a],n,r,i,o,s)},maxLength(a){return e([...t,u=>u.length<=a],n,r,i,o,s)},pattern(a){return e([...t,u=>a.test(u)],n,r,i,o,s)},default(a){return e(t,a,r,i,o,s)},describe(a){return e(t,n,r,a,o,s)},refine(a,u){let l=[...o??[],{predicate:a,message:u}];return e([...t,a],n,r,i,l,s)},meta(a){return e(t,n,r,i,o,a)}});return e([t=>typeof t=="string"])},number(){let e=(t,n,r,i,o,s)=>({...p(t,"number",n,r,i,o,s),min(a){return e([...t,u=>u>=a],n,r,i,o,s)},max(a){return e([...t,u=>u<=a],n,r,i,o,s)},default(a){return e(t,a,r,i,o,s)},describe(a){return e(t,n,r,a,o,s)},refine(a,u){let l=[...o??[],{predicate:a,message:u}];return e([...t,a],n,r,i,l,s)},meta(a){return e(t,n,r,i,o,a)}});return e([t=>typeof t=="number"])},boolean(){return p([e=>typeof e=="boolean"],"boolean")},array(){let e=(t,n,r,i,o,s)=>{let c=p(t,"array",r,void 0,i,void 0,s),a=o??{value:-1};return {...c,get _lastFailedIndex(){return a.value},set _lastFailedIndex(l){a.value=l;},of(l){let d={value:-1};return e([...t,f=>{for(let g=0;g<f.length;g++)if(!l._validators.every(y=>y(f[g])))return d.value=g,false;return true}],l,r,i,d,s)},nonEmpty(){return e([...t,l=>l.length>0],n,r,i,a,s)},maxLength(l){return e([...t,d=>d.length<=l],n,r,i,a,s)},minLength(l){return e([...t,d=>d.length>=l],n,r,i,a,s)},default(l){return e(t,n,l,i,a,s)},describe(l){return e(t,n,r,l,a,s)},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(s){return e([...t,c=>{for(let[a,u]of Object.entries(s)){let l=c[a],d=u;if(d&&!d._validators.every(f=>f(l)))return false}return true}],n,r,i)},nonNull(){return e([...t,s=>s!=null],n,r,i)},hasKeys(...s){return e([...t,c=>s.every(a=>a in c)],n,r,i)},default(s){return e(t,s,r,i)},describe(s){return e(t,n,s,i)},meta(s){return e(t,n,r,s)}});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 B([n=>n===null?true:e._validators.every(r=>r(n))],`${t} | null`)},optional(e){let t=e._typeName??"unknown";return B([n=>n===void 0?true:e._validators.every(r=>r(n))],`${t} | undefined`)},union:jt,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(o=>o(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 Ot(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 xe(e,t,n,r,i){for(let o of e)t.has(o)||console.warn(`[Directive] ${n} "${o}" not declared in ${r}`);for(let o of t)e.has(o)||console.warn(`[Directive] ${r}["${o}"] ${i}`);}function Ft(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 _t(e,t){let n=new Set(Object.keys(t));for(let[r,i]of Object.entries(e)){let o=i;typeof o.requirement=="string"&&!n.has(o.requirement)&&console.warn(`[Directive] Resolver "${r}" references unknown requirement type "${o.requirement}". Available types: ${[...n].join(", ")||"(none)"}`);}}function It(e,t){let n=t.schema?.facts??{},r=Object.keys(n);if(r.length===0)return;let i=new Set(["self","prev","current"]),o="crossModuleDeps"in t&&t.crossModuleDeps?Object.keys(t.crossModuleDeps):[];for(let s of o)i.add(s);for(let s of r)if(i.has(s))throw new Error(`[Directive] module '${e}': fact key '${s}' conflicts with a reserved namespace pivot or evaluation alias (self / prev / current / a crossModuleDep namespace). Three fixes:
|
|
2
|
+
1. Rename the fact (e.g. ${s}_)
|
|
3
|
+
2. Remove '${s}' from this module's crossModuleDeps if it's not actually needed
|
|
4
|
+
3. Move the fact under a wrapping namespace (t.object({ inner: ... }))`)}function qt(e,t){let n=t.constraints;if(n)for(let[r,i]of Object.entries(n)){let o=i?.owns;if(o){for(let s of o)if(l.has(s)||s.startsWith("$"))throw new Error(`[Directive] module '${e}' constraint '${r}': owns key '${s}' is reserved (BLOCKED_PROPS or $-prefixed)`)}}}function Nt(e,t){Ot(e),t.schema?t.schema.facts||console.warn("[Directive] Module schema.facts is required"):console.warn("[Directive] Module schema is required"),xe(new Set(Object.keys(t.derive??{})),new Set(Object.keys(t.schema?.derivations??{})),"Derivation","schema.derivations","has no matching implementation in derive"),xe(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&&Ft(t.history.snapshotEvents,t.schema?.events??{}),t.resolvers&&t.schema?.requirements&&_t(t.resolvers,t.schema.requirements);}function Ce(e,t){It(e,t),qt(e,t),a&&Nt(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,constraints:t.constraints,resolvers:t.resolvers,hooks:t.hooks,meta:t.meta,history:t.history,crossModuleDeps:n}}function Lt(e){return t=>Ce(t,e)}function ue(){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,u){let l=a.get(u);return l||(l=new Set,a.set(u,l)),l}function r(a){let u=e.pending.get(a)??new Set,l=e.inflight.get(a)??new Set,d=e.failed.get(a)??new Set,f=e.errors.get(a)??null;return {pending:u.size,inflight:l.size,failed:d.size,isLoading:u.size>0||l.size>0,hasError:d.size>0,lastError:f}}function i(){let a=new Set([...e.pending.keys(),...e.inflight.keys(),...e.failed.keys()]),u=new Map;for(let l of a)u.set(l,r(l));return u}function o(a){return e.listeners.add(a),()=>e.listeners.delete(a)}function s(){e.pending.clear(),e.inflight.clear(),e.failed.clear(),e.errors.clear(),t();}return {plugin:{name:"requirement-status",onRequirementCreated(a){let u=a.requirement.type;n(e.pending,u).add(a.id),e.failed.get(u)?.delete(a.id),t();},onResolverStart(a,u){let l=u.requirement.type;e.pending.get(l)?.delete(u.id),n(e.inflight,l).add(u.id),t();},onResolverComplete(a,u){let l=u.requirement.type;e.inflight.get(l)?.delete(u.id),e.pending.get(l)?.delete(u.id),t();},onResolverError(a,u,l){let d=u.requirement.type;e.inflight.get(d)?.delete(u.id),n(e.failed,d).add(u.id),e.errors.set(d,l instanceof Error?l:new Error(String(l))),t();},onResolverCancel(a,u){let l=u.requirement.type;e.pending.get(l)?.delete(u.id),e.inflight.get(l)?.delete(u.id),t();},onRequirementMet(a){let u=a.requirement.type;e.pending.get(u)?.delete(a.id),e.inflight.get(u)?.delete(a.id),t();}},getStatus:r,getAllStatus:i,subscribe:o,reset:s}}function Bt(e){return t=>e.getStatus(t)}function Wt(e){let t=ue(),r=[...e.plugins??[],t.plugin];return {system:a$1({module:e.module,plugins:r,trace:e.trace,errorBoundary:e.errorBoundary,tickMs:e.tickMs,zeroConfig:e.zeroConfig,initialFacts:e.initialFacts}),statusPlugin:t}}function je(){return {now:()=>Date.now(),setTimeout:(e,t)=>{let n=globalThis.setTimeout(e,t);return ()=>globalThis.clearTimeout(n)}}}function Ut(e=0){let t=e,n=0,r=[];return {now:()=>t,setTimeout:(i,o)=>{let s={id:n++,deadlineMs:t+o,cb:i,canceled:false};return r.push(s),()=>{s.canceled=true;}},advanceBy:i=>{let o=t+i;for(;;){let s=r.filter(a=>!a.canceled&&a.deadlineMs<=o).sort((a,u)=>a.deadlineMs!==u.deadlineMs?a.deadlineMs-u.deadlineMs:a.id-u.id);if(s.length===0)break;let c=s[0];t=Math.max(t,c.deadlineMs),c.canceled=true,c.cb();}t=Math.max(t,o);}}}function Kt(){return je()}function ce(){return {startedAtMs:null,pausedDurationMs:0,pausedAtMs:null,status:"idle",repeats:0}}function W(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 Pe(e,t,n){return Math.max(0,n-W(e,t))}function Oe(e,t){return e.status==="running"||e.status==="paused"?e:{...e,startedAtMs:t,pausedDurationMs:0,pausedAtMs:null,status:"running",repeats:0}}function Fe(e,t){return e.status!=="running"?e:{...e,pausedAtMs:t,status:"paused"}}function _e(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 Ie(){return ce()}function qe(e){return {...e,status:"completed"}}function Ne(e,t){return e.startedAtMs===null||e.status==="paused"?e:{...e,startedAtMs:e.startedAtMs+t,pausedDurationMs:0,pausedAtMs:null,repeats:e.repeats+1}}function Le(e,t,n){if(e.status!=="running")return {kind:"no-op"};let r=W(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 zt(e){return {initial:ce,start:Oe,pause:Fe,resume:_e,reset:Ie,complete:qe,registerRepeat:t=>Ne(t,e.ms),tick:(t,n)=>Le(t,n,e),elapsedMs:W,remainingMs:(t,n)=>Pe(t,n,e.ms)}}var $n={None:"none",Linear:"linear",Exponential:"exponential"};export{$n as Backoff,R as MAX_REPLAY_FRAMES,Z as MAX_SWEEP_POINTS,qe as completeTimer,Ce as createModule,Lt as createModuleFactory,ue as createRequirementStatusPlugin,Bt as createStatusHook,Wt as createSystemWithStatus,Kt as defaultClock,Te as diffClauses,wt as diffRules,W as elapsedMs,M as flattenPredicate,me as framesFromHistory,Q as framesFromSnapshots,ce as initialTimerState,Fe as pauseTimer,Rt as predicateToMongo,Ct as predicateToPostgrest,St as predicateToSQL,vt as predicateToWhere,je as realClock,Ne as registerRepeat,Pe as remainingMs,N as replayUnder,Ie as resetTimer,_e as resumeTimer,Oe as startTimer,ft as sweepUnder,Pt as t,Le as tickTimer,zt as timerOps,he as toReplayFrames,Y as toRulesMap,Ut as virtualClock};//# sourceMappingURL=index.js.map
|
|
5
5
|
//# sourceMappingURL=index.js.map
|