import { M as MatchConditionBuilder, C as Condition, G as GuantrMeta, a as GuantrResourceMap, b as GuantrOptions, c as GuantrContextFromMeta, d as GuantrRule } from './shared/guantr.BxozAIHO.cjs'; export { A as ArrayElementType, e as AstNode, f as ContextRef, g as GuantrResource, h as GuantrResourceAction, i as GuantrResourceModel, I as InferValueRef, L as LiteralRef, j as LogicalNode, k as MatchConditionFn, O as OperatorNode, R as ResourceRef, V as ValueRef } from './shared/guantr.BxozAIHO.cjs'; /** * Error thrown when the circuit breaker trips due to excessive rule iterations. * Indicates that the number of rules evaluated for a single permission check * exceeded the configured `maxRuleIterations` limit. */ declare class GuantrCircuitBreakerError extends Error { /** The action being checked when the circuit breaker tripped. */ action: string; /** The resource key being checked when the circuit breaker tripped. */ resource: string; /** The configured iteration limit that was exceeded. */ limit: number; constructor(action: string, resource: string, limit: number); } /** * Error thrown when a condition references a key that does not exist on the resource * instance being evaluated. This catches typos and misconfigured rules at evaluation * time rather than silently returning `false`. * * **Opt-out:** When the operand of a condition expression is `null` or `undefined`, * the key-existence check is skipped — this signals that the developer intentionally * handles sparse objects where the key may be absent. */ declare class GuantrInvalidConditionKeyError extends Error { /** The key that does not exist on the resource model. */ key: string; constructor(key: string); } /** * Creates a new {@link MatchConditionBuilder} instance that records value * references (`resource`, `context`, `literal`) used when composing conditions. * * The returned builder is a plain object whose methods produce typed * {@link ValueRef} objects carrying phantom type information. The phantom * type (`[ValueRefType]`) enables downstream operator builders (e.g. `eq`, * `gt`) to enforce type-safe operand pairing at compile time while keeping * the runtime objects fully JSON-serializable. */ declare function createMatchConditionBuilder, Context extends Record>(): MatchConditionBuilder; /** * Evaluates a serialized {@link Condition} AST against a resource instance and * evaluation context. * * This is the runtime evaluation engine used by `can` / `cannot`. The condition * tree is walked recursively: * - `operator` nodes resolve left/right values (from the resource, context, or * literals) and apply the operator logic. * - `logical` nodes combine child conditions with `and` / `or` / `not`. * * Key-existence checks are performed for `resource` and `context` references, * throwing {@link GuantrInvalidConditionKeyError} if a field is missing, unless * one operand is an explicit `null` / `undefined` literal (opt-out for sparse * objects). * * @param condition - The serialized condition AST to evaluate. * @param resource - The resource instance to evaluate against. * @param context - The evaluation context (resolved from the `context` option). * @returns `true` if the condition is satisfied, `false` otherwise. * @throws {GuantrInvalidConditionKeyError} When a referenced field does not exist * on the resource or context and no nullish opt-out is present. */ declare function evaluateCondition(condition: Condition, resource: Record, context: Record): boolean; /** * Serializes {@link MatchConditionFn | function-based match conditions} in a rules array * into {@link Condition} AST objects. * * Each rule whose `matchCondition` is a function is executed with a * {@link MatchConditionBuilder} and replaced by the resulting `Condition` object. * Rules with non-function conditions or no conditions are passed through unchanged. * * This is essential for seeding rules into a database or custom storage without * calling `setRules` at runtime. Serialize your rule definitions once, persist * them, and let the storage adapter serve them directly via `queryRules`. * * @param rules - Array of rules, potentially containing function-based `matchCondition` entries. * @returns A new array where every function-based `matchCondition` has been converted * to a serialized `Condition` AST. * * @example * ```ts * import { serializeRules } from 'guantr'; * * const rules = [ * { effect: 'allow', action: 'read', resource: 'post' }, * { * effect: 'deny', * action: 'read', * resource: 'post', * matchCondition: ({ eq, resource, literal }) => * eq(resource('archived'), literal(true)), * }, * ]; * * // Serialize before persisting to a database * const serialized = serializeRules(rules); * // serialized[1].matchCondition is now a Condition object, not a function * await db.insert(serialized); * ``` */ declare function serializeRules | undefined = undefined>(rules: readonly GuantrRule[]): GuantrRule[]; /** * Wraps {@link Condition} objects in a rules array back into function form so * they can be passed to `setRules` for re-registration. * * This is the inverse of {@link serializeRules}. Each `Condition` stored in * `matchCondition` is wrapped inside a {@link MatchConditionFn | function} that * returns the condition directly (ignoring the builder argument). * * Use this when you load rules from an external store and want to feed them * into `setRules` using either the array or callback form. * * @param rules - Array of rules containing `Condition` objects in `matchCondition`. * @returns A new array where every `Condition`-typed `matchCondition` has been * wrapped as a function. * * @example * ```ts * import { deserializeRules } from 'guantr'; * * // Rules loaded from a database already have serialized Condition objects * const rulesFromDb = await db.select('SELECT * FROM rules'); * const deserialized = deserializeRules(rulesFromDb); * await guantr.setRules(deserialized); * ``` */ declare function deserializeRules | undefined = undefined>(rules: readonly GuantrRule[]): GuantrRule[]; type ExtractResourceKeys = Meta extends GuantrMeta ? keyof U : string; type ExtractResourceAction = Meta extends GuantrMeta ? U[K & keyof U]['action'] : string; type ExtractResourceModel = Meta extends GuantrMeta ? U[K & keyof U]['model'] : Record; /** * A check tuple for batch permission methods (`can.all`, `can.any`, etc.). * Each element is a tuple of `[action, [resourceKey, resourceInstance]]`. */ type CanCheckItem | undefined> = Meta extends GuantrMeta ? { [K in keyof ResourceMap]: [ action: ResourceMap[K]['action'], resource: [key: K, instance: ResourceMap[K]['model']] ]; }[keyof ResourceMap] : [action: string, resource: [key: string, instance: Record]]; /** * Typed callable for `guantr.can`. Supports the main call signature and nested `.abstract()`, `.all()`, `.any()` sub-methods. */ type CanMethod | undefined> = { /** * Checks if the user has permission to perform the specified action on the given resource instance. * Evaluates all matching conditions and deny rules. */ , Resource extends ExtractResourceModel = ExtractResourceModel>(action: ExtractResourceAction, resource: [ResourceKey, Resource]): Promise; /** * Abstract permission check. * Returns `true` if ANY allow rule exists for the given action + resource pair. * Does NOT evaluate conditions or deny rules. */ abstract>(action: ExtractResourceAction, resource: ResourceKey): Promise; /** * Checks if ALL specified permissions are granted. * Resolves context once and shares it across all checks. * Short-circuits on the first `false` result. */ all(checks: CanCheckItem[]): Promise; /** * Checks if ANY of the specified permissions is granted. * Resolves context once and shares it across all checks. * Short-circuits on the first `true` result. */ any(checks: CanCheckItem[]): Promise; }; /** * Typed callable for `guantr.cannot`. Logical negation of `CanMethod`. */ type CannotMethod | undefined = undefined> = { , Resource extends ExtractResourceModel = ExtractResourceModel>(action: ExtractResourceAction, resource: [ResourceKey, Resource]): Promise; /** * Abstract permission check (negated). * Returns `true` if NO allow rule exists for the given action + resource pair. * Does NOT evaluate conditions or deny rules. */ abstract>(action: ExtractResourceAction, resource: ResourceKey): Promise; /** * Checks if NONE of the specified permissions is granted. * Resolves context once and shares it across all checks. * Short-circuits on the first `true` result. */ all(checks: CanCheckItem[]): Promise; /** * Checks if ANY of the specified permissions is denied. * Resolves context once and shares it across all checks. * Short-circuits on the first `false` result. */ any(checks: CanCheckItem[]): Promise; }; /** * Core authorization engine for managing and evaluating permission rules. * * Each instance holds a set of rules in a {@link Storage} adapter and provides * methods for checking whether a given action is allowed or denied against a * specific resource instance. Conditions within rules are evaluated using a * builder-based DSL ({@link MatchConditionBuilder}) and serialized as AST * nodes stored in the storage backend. * * @example * ```ts * const guantr = new Guantr({ * storage: new MyStorage(), * context: () => ({ userId: '123' }), * maxRuleIterations: 500, * }); * await guantr.setRules((allow, deny) => { * allow('read', 'post'); * }); * ``` * * @typeParam Meta - A {@link GuantrMeta} type describing the resource map and context shape, * or `undefined` for untyped mode. */ declare class Guantr | undefined = undefined> { private _storage; private _resolveContext; private readonly _maxRuleIterations; readonly can: CanMethod; readonly cannot: CannotMethod; constructor(options?: GuantrOptions>); /** * Replaces all stored rules with a new rule set. * * Accepts either a callback that receives `allow` / `deny` helper functions, or * a direct array of {@link GuantrRule} objects. When using the callback, each call * to `allow(action, resource)` or `deny(action, resource)` adds one rule. * * The `resource` argument to `allow`/`deny` can be: * - A plain resource key string (unconditional rule). * - A tuple `[resourceKey, matchCondition]` where `matchCondition` is either a * builder function (`MatchConditionFn`) or a pre-serialized {@link Condition} object. * * When a `matchCondition` function is provided, it is immediately executed with a * {@link MatchConditionBuilder} and the resulting AST is stored. This serialization * is delegated to {@link serializeRules}. If you need to serialize rules without a * `Guantr` instance, use {@link serializeRules} directly. * * Calling this method **clears the cache**. * * @param callbackOrRules - A callback function that defines rules, or an array of rule objects. * @example * ```ts * // Callback style * await guantr.setRules((allow, deny) => { * allow('read', 'post'); * deny('read', ['post', ({ eq, resource, literal }) => * eq(resource('archived'), literal(true)) * ]); * }); * * // Array style * await guantr.setRules([ * { effect: 'allow', action: 'read', resource: 'post' }, * { * effect: 'deny', * action: 'read', * resource: 'post', * matchCondition: ({ eq, resource, literal }) => * eq(resource('archived'), literal(true)), * }, * ]); * ``` */ setRules(callback: SetRulesCallback): Promise; setRules(rules: GuantrRule[]): Promise; /** * Returns all stored rules as a read-only array. * * Results are cached via the storage adapter's cache layer if available. * * @returns A promise resolving to all stored {@link GuantrRule} objects. */ getRules(): Promise>>; /** * Retrieves all rules matching a specific action and resource key. * * This is a low-level query that returns rules as stored — conditions are * **not** evaluated. Useful for debugging or building custom tooling. * * @param action - The action to filter by (e.g. `'read'`). * @param resource - The resource key to filter by (e.g. `'post'`). * @returns A promise resolving to the matching rule objects. */ relatedRulesFor>(action: ExtractResourceAction, resource: ResourceKey): Promise[]>; private _evaluateCheck; private _cachedEvaluateCheck; private _can; private _canAbstract; private _canAll; private _canAny; private _cannot; private _cannotAbstract; private _cannotAll; private _cannotAny; } type SetRulesCallback | undefined = undefined> = (allow: >(action: GuantrRule['action'], resource: GuantrRule['resource'] | [ GuantrRule['resource'], GuantrRule['matchCondition'] ]) => void, deny: >(action: GuantrRule['action'], resource: GuantrRule['resource'] | [ GuantrRule['resource'], GuantrRule['matchCondition'] ]) => void) => void | Promise; /** * Creates a new Guantr instance. * * This is the recommended entry point. It supports several call signatures: * * - `createGuantr(options)` — with storage and context options. * - `createGuantr(rules, options?)` — with initial rule array. * - `createGuantr(callback, options?)` — with rule-defining callback. * - `createGuantr()` — bare instance, set rules later via `setRules()`. * * @typeParam Meta - A {@link GuantrMeta} type for typed resource maps and context, * or `undefined` for untyped mode. * @param setRulesOrOptions - Optional rules array, callback, or options object. * @param _options - Options when rules are provided as the first argument. * @returns A promise resolving to a configured {@link Guantr} instance. * * @example * ```ts * // With context and custom storage * const guantr = await createGuantr({ * storage: new MyStorage(), * context: () => ({ userId: 1 }), * }); * ``` * * @example * ```ts * // With static context (plain object) * const guantr = await createGuantr({ * context: { userId: 1, role: 'admin' }, * }); * ``` * * @example * ```ts * // With initial rules callback * const guantr = await createGuantr(async (allow, deny) => { * allow('read', 'post'); * }); * ``` */ declare function createGuantr | undefined = undefined>(options: GuantrOptions>): Promise>; declare function createGuantr | undefined = undefined>(setRules: SetRulesCallback, options?: GuantrOptions>): Promise>; declare function createGuantr | undefined = undefined>(setRules: GuantrRule[], options?: GuantrOptions>): Promise>; declare function createGuantr | undefined = undefined>(): Promise>; export { Condition, Guantr, GuantrCircuitBreakerError, GuantrContextFromMeta, GuantrInvalidConditionKeyError, GuantrMeta, GuantrOptions, GuantrResourceMap, GuantrRule, MatchConditionBuilder, createGuantr, createMatchConditionBuilder, deserializeRules, evaluateCondition, serializeRules };