@nmnmcc/ability 2.0.1 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- package/dist/Condition.d.ts +10 -10
- package/dist/Condition.d.ts.map +1 -1
- package/dist/Condition.js.map +1 -1
- package/dist/Policy.d.ts +4 -2
- package/dist/Policy.d.ts.map +1 -1
- package/dist/Policy.js +4 -2
- package/dist/Policy.js.map +1 -1
- package/dist/internal/authorizer.js +13 -7
- package/dist/internal/authorizer.js.map +1 -1
- package/dist/internal/bind.js +27 -10
- package/dist/internal/bind.js.map +1 -1
- package/package.json +1 -1
- package/src/Condition.ts +18 -25
- package/src/Policy.ts +4 -2
- package/src/internal/authorizer.ts +17 -7
- package/src/internal/bind.ts +33 -10
package/README.md
CHANGED
|
@@ -311,9 +311,11 @@ authorizer with a decider asks the decider first.
|
|
|
311
311
|
| `Policy.permittedFields` | The fields of a value that the policy lets a request use. |
|
|
312
312
|
|
|
313
313
|
`Policy.residual` puts the principal into every rule and gives a condition on
|
|
314
|
-
the resource fields only.
|
|
315
|
-
|
|
316
|
-
|
|
314
|
+
the resource fields only. Use it to make a database query. It makes the
|
|
315
|
+
condition smaller, so it is often `True` or `False` when the answer does not
|
|
316
|
+
depend on the value, but it does no search: a condition such as
|
|
317
|
+
`owner = "a" OR owner <> "a"` stays as it is. To ask "may this principal do this
|
|
318
|
+
act on every value, or on some value, of this kind?", use `Policy.coverage`.
|
|
317
319
|
|
|
318
320
|
When a rule that the request may use has a predicate, the residual is one
|
|
319
321
|
predicate with the name `"policy"`. It runs the whole policy for each value, so
|
package/dist/Condition.d.ts
CHANGED
|
@@ -176,23 +176,23 @@ export interface Opaque<out E = never, out R = never> {
|
|
|
176
176
|
};
|
|
177
177
|
}
|
|
178
178
|
/**
|
|
179
|
-
* The error type of the predicates of a mark `X`. A mark that
|
|
180
|
-
*
|
|
179
|
+
* The error type of the predicates of a mark `X`. A mark that is not an
|
|
180
|
+
* {@link Opaque}, as `unknown` or `object`, may have any error.
|
|
181
181
|
*
|
|
182
182
|
* @stability stable
|
|
183
183
|
* @category utility types
|
|
184
184
|
* @since 2.0.0
|
|
185
185
|
*/
|
|
186
|
-
export type ErrorOf<X> =
|
|
186
|
+
export type ErrorOf<X> = X extends Opaque<infer E, infer _R> ? E : unknown;
|
|
187
187
|
/**
|
|
188
|
-
* The service type of the predicates of a mark `X`. A mark that
|
|
189
|
-
*
|
|
188
|
+
* The service type of the predicates of a mark `X`. A mark that is not an
|
|
189
|
+
* {@link Opaque}, as `unknown` or `object`, may need any service.
|
|
190
190
|
*
|
|
191
191
|
* @stability stable
|
|
192
192
|
* @category utility types
|
|
193
193
|
* @since 2.0.0
|
|
194
194
|
*/
|
|
195
|
-
export type ServicesOf<X> =
|
|
195
|
+
export type ServicesOf<X> = X extends Opaque<infer _E, infer R> ? R : unknown;
|
|
196
196
|
/**
|
|
197
197
|
* The mark `X` with no services.
|
|
198
198
|
*
|
|
@@ -200,7 +200,7 @@ export type ServicesOf<X> = unknown extends X ? unknown : X extends Opaque<infer
|
|
|
200
200
|
* @category utility types
|
|
201
201
|
* @since 2.0.0
|
|
202
202
|
*/
|
|
203
|
-
export type Provided<X> =
|
|
203
|
+
export type Provided<X> = X extends Opaque<infer E, infer _R> ? Opaque<E> : Opaque<unknown>;
|
|
204
204
|
/**
|
|
205
205
|
* What the predicates of a condition read: a resource value of the type `V`
|
|
206
206
|
* and a principal of the type `P`. It is only in the types.
|
|
@@ -268,15 +268,15 @@ type Leaf = string | number | boolean | bigint | symbol | null | undefined;
|
|
|
268
268
|
*/
|
|
269
269
|
type Whole = ReadonlyMap<unknown, unknown> | ReadonlySet<unknown> | HashMap.HashMap<unknown, unknown> | HashSet.HashSet<unknown> | Date | URL | Uint8Array | Option.Option<unknown> | BigDecimal.BigDecimal | Duration.Duration | DateTime.DateTime | Redacted.Redacted<unknown> | Chunk.Chunk<unknown> | Cause.Cause<unknown> | Result.Result<unknown, unknown> | Exit.Exit<unknown, unknown> | File | FormData | RegExp | URLSearchParams;
|
|
270
270
|
type PreviousDepth = [never, 0, 1, 2, 3];
|
|
271
|
-
type FieldPathInternal<T, Depth extends number, Arrays extends boolean, Parents extends boolean = false> = [Depth] extends [never] ? never : { [K in keyof T & string]-?: PathsOf
|
|
271
|
+
type FieldPathInternal<T, Depth extends number, Arrays extends boolean, Parents extends boolean = false> = [Depth] extends [never] ? never : { [K in keyof T & (string | number)]-?: PathsOf<`${K}`, NonNullable<T[K]>, Depth, Arrays, Parents>; }[keyof T & (string | number)];
|
|
272
272
|
/**
|
|
273
273
|
* The paths of one field `K` with the values `V`. Each kind of value in `V`
|
|
274
274
|
* gives its own paths, so a field that holds a string or a struct is a field,
|
|
275
275
|
* and the fields of the struct are fields too. A function is no field.
|
|
276
276
|
*/
|
|
277
|
-
type PathsOf<K extends string, V, Depth extends number, Arrays extends boolean, Parents extends boolean> = ([V] extends [never] ? K : never) | ([Extract<V, Leaf | Whole>] extends [never] ? never : K) | ([Extract<V, ReadonlyArray<unknown>>] extends [never] ? never : Arrays extends true ? K : never) | ObjectPaths<K, Exclude<V, Leaf | Whole | Function | ReadonlyArray<unknown>>, Depth, Arrays, Parents>;
|
|
277
|
+
type PathsOf<K extends string, V, Depth extends number, Arrays extends boolean, Parents extends boolean> = ([V] extends [never] ? K : {} extends V ? K : never) | ([Extract<V, Leaf | Whole>] extends [never] ? never : K) | ([Extract<V, ReadonlyArray<unknown>>] extends [never] ? never : Arrays extends true ? K : never) | ObjectPaths<K, Exclude<V, Leaf | Whole | Function | ReadonlyArray<unknown>>, Depth, Arrays, Parents>;
|
|
278
278
|
/** The paths of a field `K` that holds the objects `O`, and of the fields below. */
|
|
279
|
-
type ObjectPaths<K extends string, O, Depth extends number, Arrays extends boolean, Parents extends boolean> = [O] extends [never] ? never : (Parents extends true ? K : Arrays extends true ? string extends keyof O ? K : never : never) | `${K}.${FieldPathInternal<O, PreviousDepth[Depth], Arrays, Parents>}`;
|
|
279
|
+
type ObjectPaths<K extends string, O, Depth extends number, Arrays extends boolean, Parents extends boolean> = [O] extends [never] ? never : (Parents extends true ? K : Arrays extends true ? string extends keyof O ? K : number extends keyof O ? K : never : never) | `${K}.${FieldPathInternal<O, PreviousDepth[Depth], Arrays, Parents>}`;
|
|
280
280
|
/**
|
|
281
281
|
* The paths of the fields of `T` that hold one value, with dots for nested
|
|
282
282
|
* fields. Arrays are left out. A map, a set, a date, a URL, a byte array, an
|
package/dist/Condition.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Condition.d.ts","names":["Nodes.Scalar","Nodes.Literal","Nodes.PrincipalRef","Nodes.CompareOperator","Nodes.True","Nodes.False","Nodes.Compare","Nodes.In","Nodes.Exists","Nodes.Under","Nodes.And","Nodes.Or","Nodes.Not","Nodes.Predicate","Nodes.Node","Resource.PathSegment","Search.Example","Search.Satisfiability"],"sources":["../src/Condition.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;YA4DY,SAASA;;;;;;;;YAST,UAAUC;;;;;;;;;;;;;;YAeV,eAAeC;;;;;;;;;;;YAYf,IAAI,GAAG,aAAa;WACtB,cAAc;WACd,eAAe,WAAW;;;;;;;YAQxB,UAAU,UAAU;;;;;;YAOpB,kBAAkBC;;;;;;;;YASlB,OAAOC;;;;;;;;YASP,QAAQC;;;;;;;;;;YAWR,UAAUC;;;;;;;;YASV,KAAKC;;;;;;;;YASL,SAASC;;;;;;;;;YAUT,QAAQC;;;;;;YAOR,MAAMC;;;;;;YAON,KAAKC;;;;;;YAOL,MAAMC;;;;;;;;YASN,YAAYC;;;;;;;;;;YAWZ,MAAMC;;;;;;;;;iBAUD,WAAW,eAAe;WACjC;aAAsB,GAAG;aAAY,GAAG;;;;;;;;;;;YAWtC,QAAQ,
|
|
1
|
+
{"version":3,"file":"Condition.d.ts","names":["Nodes.Scalar","Nodes.Literal","Nodes.PrincipalRef","Nodes.CompareOperator","Nodes.True","Nodes.False","Nodes.Compare","Nodes.In","Nodes.Exists","Nodes.Under","Nodes.And","Nodes.Or","Nodes.Not","Nodes.Predicate","Nodes.Node","Resource.PathSegment","Search.Example","Search.Satisfiability"],"sources":["../src/Condition.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;YA4DY,SAASA;;;;;;;;YAST,UAAUC;;;;;;;;;;;;;;YAeV,eAAeC;;;;;;;;;;;YAYf,IAAI,GAAG,aAAa;WACtB,cAAc;WACd,eAAe,WAAW;;;;;;;YAQxB,UAAU,UAAU;;;;;;YAOpB,kBAAkBC;;;;;;;;YASlB,OAAOC;;;;;;;;YASP,QAAQC;;;;;;;;;;YAWR,UAAUC;;;;;;;;YASV,KAAKC;;;;;;;;YASL,SAASC;;;;;;;;;YAUT,QAAQC;;;;;;YAOR,MAAMC;;;;;;YAON,KAAKC;;;;;;YAOL,MAAMC;;;;;;;;YASN,YAAYC;;;;;;;;;;YAWZ,MAAMC;;;;;;;;;iBAUD,WAAW,eAAe;WACjC;aAAsB,GAAG;aAAY,GAAG;;;;;;;;;;;YAWtC,QAAQ,KAAK,UAAU,aAAa,SAAS,MAAM;;;;;;;;;YAUnD,WAAW,KAAK,UAAU,aAAa,UAAU,KAAK;;;;;;;;YAStD,SAAS,KACpB,UAAU,aAAa,SAAS,MAAM,OAAO,KAAK;;;;;;;;;iBAUlC,MAAM,GAAG;WAChB,OAAO;WACP,WAAW;;;;;;;;;;;;;;;;YAiBT,UAAU,aAAa,aAAa;WACtC,WAAW,OAAO;WAClB,iBAAiB;;;;;;;;;YAUf,MAAM;;;;;;;;;YAUN,QAAQ,MAAM;WACd,WAAW,aAAa;KAEjC;;;;;;;;YAUS,SAAS,KAAK;WAAqB,uBAAuB;IACnE;KAGE;;;;;;KAMA,QACF,gCACA,uBACA,QAAQ,4BACR,QAAQ,mBACR,OACA,MACA,aACA,OAAO,kBACP,WAAW,aACX,SAAS,WACT,SAAS,WACT,SAAS,oBACT,MAAM,iBACN,MAAM,iBACN,OAAO,2BAC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,OAAO,MAAM,gBAAgB"}
|
package/dist/Condition.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Condition.js","names":["Nodes.literal","Nodes.Compare","Nodes.And","Nodes.Or","Nodes.Not","Nodes.In","Nodes.Exists","Nodes.Under","Nodes.principalRef","Nodes.Predicate","Nodes.always","Nodes.never","Nodes.toNode","Algebra.provide","Algebra.evaluate","Algebra.evaluateSync","Algebra.simplify","Algebra.partial","Algebra.fields","Search.satisfiable","Search.kindsIn","Catalog.catalogOf","Nodes.isNode","Json.decode","Json.toJson"],"sources":["../src/Condition.ts"],"sourcesContent":["/**\n * A condition is a test on a resource value. A rule applies only when its\n * condition is true.\n *\n * A condition is plain data: a tree of nodes. So you can:\n * - test it on a value with {@link evaluate};\n * - put the principal into it and make it smaller with {@link partial}, which\n * gives a \"residual\" condition: the part that still depends on the\n * resource;\n * - change it into a database query with {@link fold};\n * - keep it as JSON with {@link schema}.\n *\n * Make conditions with a {@link Builder}. A rule gives you a builder for its\n * resource, so the field names and the value types are checked.\n *\n * {@link Builder.predicate} is the one way out of plain data. A predicate runs\n * any `Effect`. Its error type and its service type go into the type of the\n * check. A rule with a predicate can not become JSON, and the type system\n * stops you when you try.\n *\n * @stability stable\n * @since 0.3.0\n */\n// A predicate keeps its error type and service type in the public types. The\n// code below works on the nodes with no types, where they are `unknown`, so\n// the language service check for `unknown` in an Effect is off here.\n// @effect-diagnostics anyUnknownInErrorContext:off\nimport * as Arr from \"effect/Array\"\nimport type * as BigDecimal from \"effect/BigDecimal\"\nimport type * as Cause from \"effect/Cause\"\nimport type * as Chunk from \"effect/Chunk\"\nimport type * as DateTime from \"effect/DateTime\"\nimport type * as Duration from \"effect/Duration\"\nimport type * as Exit from \"effect/Exit\"\nimport type * as HashMap from \"effect/HashMap\"\nimport type * as HashSet from \"effect/HashSet\"\nimport type * as Option from \"effect/Option\"\nimport type * as Redacted from \"effect/Redacted\"\nimport type * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\nimport { hasProperty } from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport * as SchemaIssue from \"effect/SchemaIssue\"\nimport * as SchemaTransformation from \"effect/SchemaTransformation\"\nimport * as Result from \"effect/Result\"\nimport * as Algebra from \"./internal/algebra.ts\"\nimport * as Catalog from \"./internal/catalog.ts\"\nimport * as Json from \"./internal/json.ts\"\nimport * as Nodes from \"./internal/nodes.ts\"\nimport * as Search from \"./internal/search.ts\"\nimport * as Resource from \"./Resource.ts\"\n\n/**\n * A value that a condition can compare.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Scalar = Nodes.Scalar\n\n/**\n * A fixed value in a condition.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Literal = Nodes.Literal\n\n/**\n * A field of the principal. {@link partial} puts the value of the field in its\n * place.\n *\n * A principal field that is `null` or missing has no value. A `Compare`, `In`\n * or `Under` test with it is always false, also with `ne`. So a principal with\n * no id never matches a resource with no owner. `not` still turns false into\n * true.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type PrincipalRef = Nodes.PrincipalRef\n\n/**\n * A field of the principal with a known value type `A`, from a principal of\n * the type `P`. The type fields are only in the types. A test with the\n * reference reads a principal of the type `P`, so it can not go into a rule\n * of a domain with another principal.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Ref<A, P = never> = PrincipalRef & {\n\treadonly \"~Ref\": () => A\n\treadonly \"~Principal\": (principal: P) => void\n}\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Operand = Literal | PrincipalRef\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type CompareOperator = Nodes.CompareOperator\n\n/**\n * Always true.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type True = Nodes.True\n\n/**\n * Always false.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type False = Nodes.False\n\n/**\n * Compares a field with a value. A missing field has the value `null`. `lt`,\n * `lte`, `gt` and `gte` are false when the two sides are not both numbers or\n * both strings.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Compare = Nodes.Compare\n\n/**\n * True when a field is equal to one of the values.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type In = Nodes.In\n\n/**\n * True when a field is not `null` and not missing.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Exists = Nodes.Exists\n\n/**\n * True when the path of the resource starts with the prefix. A resource with\n * no path is never under a prefix.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Under = Nodes.Under\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type And = Nodes.And\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Or = Nodes.Or\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Not = Nodes.Not\n\n/**\n * A test that runs an `Effect`. It can not become JSON or a query.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Predicate = Nodes.Predicate\n\n/**\n * The nodes of a condition, without types. Each node is a class, and only the\n * builder, the functions of this module and the Schema make one. So a plain\n * object, or a spread of a node, is not a node.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Ast = Nodes.Node\n\n/**\n * The mark of a condition with a predicate. `E` and `R` are the error type\n * and the service type of its predicates.\n *\n * @stability stable\n * @category models\n * @since 2.0.0\n */\nexport interface Opaque<out E = never, out R = never> {\n\treadonly \"~Opaque\": { readonly E: E; readonly R: R }\n}\n\n/**\n * The error type of the predicates of a mark `X`. A mark that may be\n * anything, as `unknown`, may have any error.\n *\n * @stability stable\n * @category utility types\n * @since 2.0.0\n */\nexport type ErrorOf<X> = unknown extends X\n\t? unknown\n\t: X extends Opaque<infer E, infer _R>\n\t\t? E\n\t\t: never\n\n/**\n * The service type of the predicates of a mark `X`. A mark that may be\n * anything, as `unknown`, may need any service.\n *\n * @stability stable\n * @category utility types\n * @since 2.0.0\n */\nexport type ServicesOf<X> = unknown extends X\n\t? unknown\n\t: X extends Opaque<infer _E, infer R>\n\t\t? R\n\t\t: never\n\n/**\n * The mark `X` with no services.\n *\n * @stability stable\n * @category utility types\n * @since 2.0.0\n */\nexport type Provided<X> = unknown extends X\n\t? Opaque<unknown>\n\t: X extends Opaque<infer E, infer _R>\n\t\t? Opaque<E>\n\t\t: never\n\n/**\n * What the predicates of a condition read: a resource value of the type `V`\n * and a principal of the type `P`. It is only in the types.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport interface Reads<V, P> {\n\treadonly value: V\n\treadonly principal: P\n}\n\n/**\n * A condition. `I` is what its tests read: see {@link Reads}. `X` is\n * {@link Opaque} when the condition has a predicate, and `never` when it is\n * plain data. A plain condition can become JSON or a query.\n *\n * The two type fields are only in the types. `I` goes into a function as an\n * input, so a condition that reads a `Post` does not fit a rule for a\n * `Comment`. `X` comes out of a function, so a plain condition fits where a\n * condition with predicates may go.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Condition<I = unknown, X = never> = Ast & {\n\treadonly \"~Reads\": (reads: I) => void\n\treadonly \"~Opaque\": () => X\n}\n\n/**\n * Any condition.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Any = Condition<any, any>\n\n/**\n * What the tests of a condition read. For a union of conditions, it is what\n * all of them read.\n *\n * @stability stable\n * @category utility types\n * @since 1.0.0\n */\nexport type ReadsOf<C> = [C] extends [\n\t{ readonly \"~Reads\": (reads: infer I) => void },\n]\n\t? I\n\t: unknown\n\n/**\n * The mark of a condition: {@link Opaque} when it has a predicate.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type OpaqueOf<C> = C extends { readonly \"~Opaque\": () => infer X }\n\t? X\n\t: never\n\ntype Leaf = string | number | boolean | bigint | symbol | null | undefined\n/**\n * Values of a class that keeps its data inside. A path does not go into them,\n * as in the field paths of a resource, so a field with such a value is one\n * field. A condition can test only if it exists.\n */\ntype Whole =\n\t| ReadonlyMap<unknown, unknown>\n\t| ReadonlySet<unknown>\n\t| HashMap.HashMap<unknown, unknown>\n\t| HashSet.HashSet<unknown>\n\t| Date\n\t| URL\n\t| Uint8Array\n\t| Option.Option<unknown>\n\t| BigDecimal.BigDecimal\n\t| Duration.Duration\n\t| DateTime.DateTime\n\t| Redacted.Redacted<unknown>\n\t| Chunk.Chunk<unknown>\n\t| Cause.Cause<unknown>\n\t| Result.Result<unknown, unknown>\n\t| Exit.Exit<unknown, unknown>\n\t| File\n\t| FormData\n\t| RegExp\n\t| URLSearchParams\ntype PreviousDepth = [never, 0, 1, 2, 3]\ntype FieldPathInternal<\n\tT,\n\tDepth extends number,\n\tArrays extends boolean,\n\tParents extends boolean = false,\n> = [Depth] extends [never]\n\t? never\n\t: {\n\t\t\t[K in keyof T & string]-?: PathsOf<\n\t\t\t\tK,\n\t\t\t\tNonNullable<T[K]>,\n\t\t\t\tDepth,\n\t\t\t\tArrays,\n\t\t\t\tParents\n\t\t\t>\n\t\t}[keyof T & string]\n\n/**\n * The paths of one field `K` with the values `V`. Each kind of value in `V`\n * gives its own paths, so a field that holds a string or a struct is a field,\n * and the fields of the struct are fields too. A function is no field.\n */\ntype PathsOf<\n\tK extends string,\n\tV,\n\tDepth extends number,\n\tArrays extends boolean,\n\tParents extends boolean,\n> =\n\t// A field that is only ever `null` or missing is a field too.\n\t| ([V] extends [never] ? K : never)\n\t| ([Extract<V, Leaf | Whole>] extends [never] ? never : K)\n\t| ([Extract<V, ReadonlyArray<unknown>>] extends [never]\n\t\t\t? never\n\t\t\t: Arrays extends true\n\t\t\t\t? K\n\t\t\t\t: never)\n\t| ObjectPaths<\n\t\t\tK,\n\t\t\tExclude<V, Leaf | Whole | Function | ReadonlyArray<unknown>>,\n\t\t\tDepth,\n\t\t\tArrays,\n\t\t\tParents\n\t >\n\n/** The paths of a field `K` that holds the objects `O`, and of the fields below. */\ntype ObjectPaths<\n\tK extends string,\n\tO,\n\tDepth extends number,\n\tArrays extends boolean,\n\tParents extends boolean,\n> = [O] extends [never]\n\t? never\n\t: // A record is one field to a rule or a request, as `permittedFields`\n\t\t// lists it.\n\t\t| (Parents extends true\n\t\t\t\t? K\n\t\t\t\t: Arrays extends true\n\t\t\t\t\t? string extends keyof O\n\t\t\t\t\t\t? K\n\t\t\t\t\t\t: never\n\t\t\t\t\t: never)\n\t\t| `${K}.${FieldPathInternal<O, PreviousDepth[Depth], Arrays, Parents>}`\n\n/**\n * The paths of the fields of `T` that hold one value, with dots for nested\n * fields. Arrays are left out. A map, a set, a date, a URL, a byte array, an\n * `Option` and the other value types of Effect, such as `BigDecimal` and\n * `Duration`, are one field, and a path does not go into them. The type goes down four levels, so type\n * checking stays fast. For a union of types, only the common fields are\n * paths.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type FieldPath<T> = [T] extends [object]\n\t? FieldPathInternal<T, 4, false>\n\t: never\n\n/**\n * The paths of the fields of `T` that a rule or a request may name, as in\n * `Rule.Options.fields`. They are the paths of {@link FieldPath}, and the\n * paths of arrays too: a rule may allow or deny a whole array field, and\n * `permittedFields` lists it.\n *\n * @stability stable\n * @category utility types\n * @since 1.0.0\n */\nexport type FieldSelector<T> = [T] extends [object]\n\t? FieldPathInternal<T, 4, true>\n\t: never\n\n/**\n * The names that the `fields` of a rule may have: the paths of\n * {@link FieldSelector}, and the paths of the structs above them. A name of a\n * struct covers the fields below it.\n *\n * @stability stable\n * @category utility types\n * @since 2.0.0\n */\nexport type FieldName<T> = [T] extends [object]\n\t? FieldPathInternal<T, 4, true, true>\n\t: never\n\n/**\n * The value type that fits every field in `F`. For one field, it is the type\n * of the field. For a union of fields, it is the values that each of them can\n * hold, so a value of a union type can not test a field of another type. For\n * a union of data types, as for a rule on two kinds, it is the values that\n * the field can hold in each of them.\n *\n * @stability stable\n * @category utility types\n * @since 1.0.0\n */\nexport type FieldValue<Data, F extends string> = (\n\tData extends unknown\n\t\t? F extends unknown\n\t\t\t? (value: PathValue<Data, F>) => void\n\t\t\t: never\n\t\t: never\n) extends (value: infer V) => void\n\t? V\n\t: never\n\ntype Normalize<A> = Exclude<A, undefined> | (undefined extends A ? null : never)\n\n/**\n * The type of the field of `T` at `Path`. A field that may be missing may also\n * be `null`.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type PathValue<\n\tT,\n\tPath extends string,\n> = Path extends `${infer Head}.${infer Rest}`\n\t? Head extends keyof T\n\t\t? undefined extends T[Head]\n\t\t\t? PathValue<NonNullable<T[Head]>, Rest> | null\n\t\t\t: null extends T[Head]\n\t\t\t\t? PathValue<NonNullable<T[Head]>, Rest> | null\n\t\t\t\t: PathValue<T[Head], Rest>\n\t\t: never\n\t: Path extends keyof T\n\t\t? Normalize<T[Path]>\n\t\t: never\n\n/**\n * A value for a field of type `A`: a fixed value, or a field of the principal\n * with the same type.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type OperandOf<A, P = never> = Extract<A, Scalar> | Ref<A, P>\n\ntype ScalarPath<T> = {\n\t[F in FieldPath<T>]: PathValue<T, F> extends Scalar ? F : never\n}[FieldPath<T>]\n\ntype OrderedPath<T> = {\n\t[F in FieldPath<T>]: Exclude<PathValue<T, F>, null> extends number | string\n\t\t? F\n\t\t: never\n}[FieldPath<T>]\n\n/**\n * A test made by a {@link Builder}. It runs no code, but it keeps the value\n * type of its resource, so a test on the fields of one resource can not go\n * into a rule for another resource. A test with a field of the principal\n * keeps the principal type `P` too.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport type Test<Value, P = unknown> = Condition<Reads<Value, P>>\n\n/**\n * The principal type that a test reads: the principal of each field of the\n * principal in the values `V`, and `unknown` when there is none. A reference\n * from another builder keeps the principal of that builder.\n */\ntype PrincipalOf<V, _P> = [Extract<V, PrincipalRef>] extends [never]\n\t? unknown\n\t: [Extract<V, PrincipalRef>] extends [\n\t\t\t\t{ readonly \"~Principal\": (principal: infer Q) => void },\n\t\t ]\n\t\t? Q\n\t\t: unknown\n\n/**\n * Makes conditions for a resource with the data type `Data` and the value type\n * `Value`, and a principal with the type `P`.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Builder<Data, Value, P> {\n\t/** The field is equal to the value. */\n\treadonly eq: <\n\t\tconst F extends FieldPath<Data>,\n\t\tconst V extends OperandOf<FieldValue<Data, F>, any>,\n\t>(\n\t\tfield: F,\n\t\tvalue: V,\n\t) => Test<Value, PrincipalOf<V, P>>\n\t/** The field is not equal to the value. */\n\treadonly ne: <\n\t\tconst F extends FieldPath<Data>,\n\t\tconst V extends OperandOf<FieldValue<Data, F>, any>,\n\t>(\n\t\tfield: F,\n\t\tvalue: V,\n\t) => Test<Value, PrincipalOf<V, P>>\n\treadonly lt: <\n\t\tconst F extends OrderedPath<Data>,\n\t\tconst V extends OperandOf<Exclude<FieldValue<Data, F>, null>, any>,\n\t>(\n\t\tfield: F,\n\t\tvalue: V,\n\t) => Test<Value, PrincipalOf<V, P>>\n\treadonly lte: <\n\t\tconst F extends OrderedPath<Data>,\n\t\tconst V extends OperandOf<Exclude<FieldValue<Data, F>, null>, any>,\n\t>(\n\t\tfield: F,\n\t\tvalue: V,\n\t) => Test<Value, PrincipalOf<V, P>>\n\treadonly gt: <\n\t\tconst F extends OrderedPath<Data>,\n\t\tconst V extends OperandOf<Exclude<FieldValue<Data, F>, null>, any>,\n\t>(\n\t\tfield: F,\n\t\tvalue: V,\n\t) => Test<Value, PrincipalOf<V, P>>\n\treadonly gte: <\n\t\tconst F extends OrderedPath<Data>,\n\t\tconst V extends OperandOf<Exclude<FieldValue<Data, F>, null>, any>,\n\t>(\n\t\tfield: F,\n\t\tvalue: V,\n\t) => Test<Value, PrincipalOf<V, P>>\n\t/** The field is equal to one of the values. */\n\treadonly in: <\n\t\tconst F extends FieldPath<Data>,\n\t\tconst Vs extends ReadonlyArray<OperandOf<FieldValue<Data, F>, any>>,\n\t>(\n\t\tfield: F,\n\t\tvalues: Vs,\n\t) => Test<Value, PrincipalOf<Vs[number], P>>\n\t/** The field has a value that is not `null`. */\n\treadonly exists: <const F extends FieldPath<Data>>(field: F) => Test<Value>\n\t/** The path of the resource starts with these parts. */\n\treadonly under: <\n\t\tconst Ps extends ReadonlyArray<string | null | Ref<string | null, any>>,\n\t>(\n\t\t...prefix: Ps\n\t) => Test<Value, PrincipalOf<Ps[number], P>>\n\t/**\n\t * A field of the principal, to use as a value. The field must have a\n\t * {@link Scalar} type.\n\t */\n\treadonly principal: <const F extends ScalarPath<P>>(\n\t\tfield: F,\n\t) => Ref<PathValue<P, F>, P>\n\treadonly and: <const Cs extends ReadonlyArray<Any>>(\n\t\t...conditions: Cs\n\t) => Condition<ReadsOf<Cs[number]>, OpaqueOf<Cs[number]>>\n\treadonly or: <const Cs extends ReadonlyArray<Any>>(\n\t\t...conditions: Cs\n\t) => Condition<ReadsOf<Cs[number]>, OpaqueOf<Cs[number]>>\n\treadonly not: <C extends Any>(\n\t\tcondition: C,\n\t) => Condition<ReadsOf<C>, OpaqueOf<C>>\n\t/**\n\t * A test that runs any code. It may give a boolean or an `Effect`. A\n\t * condition with a predicate can not become JSON or a query.\n\t */\n\treadonly predicate: <E = never, R = never>(\n\t\tname: string,\n\t\ttest: (\n\t\t\tvalue: Value,\n\t\t\tprincipal: P,\n\t\t) => boolean | Effect.Effect<boolean, E, R>,\n\t) => Condition<Reads<Value, P>, Opaque<E, R>>\n}\n\nconst isOperand = (u: unknown): u is Operand =>\n\thasProperty(u, \"_tag\") && (u._tag === \"Literal\" || u._tag === \"Principal\")\n\nconst toOperand = (value: unknown): Operand =>\n\tisOperand(value) ? value : Nodes.literal(value as Scalar)\n\nconst compare =\n\t(op: CompareOperator) =>\n\t(field: string, value: unknown): Ast =>\n\t\tnew Nodes.Compare({ op, field, value: toOperand(value) })\n\n// A list of conditions goes in as an array, not as arguments: a call may take\n// only so many arguments, and a decoded condition may have more children.\n// The constructor copies the list, so a later change to the array of a caller\n// does not change the condition.\nconst andOf = (conditions: ReadonlyArray<Ast>): Ast =>\n\tnew Nodes.And(conditions as ReadonlyArray<Nodes.Node>)\n\nconst orOf = (conditions: ReadonlyArray<Ast>): Ast =>\n\tnew Nodes.Or(conditions as ReadonlyArray<Nodes.Node>)\n\nconst makeNot = (condition: Ast): Ast => new Nodes.Not(condition as Nodes.Node)\n\nconst sharedBuilder: Builder<any, any, any> = {\n\teq: compare(\"eq\"),\n\tne: compare(\"ne\"),\n\tlt: compare(\"lt\"),\n\tlte: compare(\"lte\"),\n\tgt: compare(\"gt\"),\n\tgte: compare(\"gte\"),\n\tin: (field: string, values: ReadonlyArray<unknown>) =>\n\t\tnew Nodes.In({ field, values: Arr.map(Array.from(values), toOperand) }),\n\texists: (field: string) => new Nodes.Exists({ field }),\n\tunder: (...prefix: ReadonlyArray<unknown>) =>\n\t\tnew Nodes.Under({ prefix: Arr.map(prefix, toOperand) }),\n\tprincipal: (path: string) => Nodes.principalRef(path),\n\tand: (...conditions: ReadonlyArray<Ast>) => andOf(conditions),\n\tor: (...conditions: ReadonlyArray<Ast>) => orOf(conditions),\n\tnot: makeNot,\n\tpredicate: (\n\t\tname: string,\n\t\ttest: (\n\t\t\tvalue: unknown,\n\t\t\tprincipal: unknown,\n\t\t) => boolean | Effect.Effect<boolean, unknown, unknown>,\n\t) =>\n\t\tnew Nodes.Predicate({\n\t\t\tname,\n\t\t\trun: (value, principal) =>\n\t\t\t\tEffect.suspend(() => {\n\t\t\t\t\tconst result = test(value, principal)\n\t\t\t\t\treturn Effect.isEffect(result) ? result : Effect.succeed(result)\n\t\t\t\t}),\n\t\t}),\n} as never\n\n/**\n * Makes a builder. Rules give you a builder with the right types, so you do not\n * often need this.\n *\n * @stability stable\n * @category constructors\n * @since 0.3.0\n */\nexport const builder = <Data, Value, P>(): Builder<Data, Value, P> =>\n\tsharedBuilder\n\n/**\n * Always true.\n *\n * @stability stable\n * @category constructors\n * @since 0.3.0\n */\nexport const always: Condition = Nodes.always as never\n\n/**\n * Always false.\n *\n * @stability stable\n * @category constructors\n * @since 0.3.0\n */\nexport const never: Condition = Nodes.never as never\n\n/**\n * True when all the conditions are true. With no conditions, it is true.\n *\n * @stability stable\n * @category combinators\n * @since 0.3.0\n */\nexport const and: <const Cs extends ReadonlyArray<Any>>(\n\t...conditions: Cs\n) => Condition<ReadsOf<Cs[number]>, OpaqueOf<Cs[number]>> = ((\n\t...conditions: ReadonlyArray<Ast>\n) => andOf(conditions)) as never\n\n/**\n * The same as {@link and}, for a list of conditions of one type. Use it for a\n * long list: a function call may take only so many arguments.\n *\n * @stability stable\n * @category combinators\n * @since 1.0.0\n */\nexport const andAll: <C extends Any>(\n\tconditions: ReadonlyArray<C>,\n) => Condition<ReadsOf<C>, OpaqueOf<C>> = andOf as never\n\n/**\n * The same as {@link or}, for a list of conditions of one type. Use it for a\n * long list: a function call may take only so many arguments.\n *\n * @stability stable\n * @category combinators\n * @since 1.0.0\n */\nexport const orAll: <C extends Any>(\n\tconditions: ReadonlyArray<C>,\n) => Condition<ReadsOf<C>, OpaqueOf<C>> = orOf as never\n\n/**\n * True when one of the conditions is true. With no conditions, it is false.\n *\n * @stability stable\n * @category combinators\n * @since 0.3.0\n */\nexport const or: <const Cs extends ReadonlyArray<Any>>(\n\t...conditions: Cs\n) => Condition<ReadsOf<Cs[number]>, OpaqueOf<Cs[number]>> = ((\n\t...conditions: ReadonlyArray<Ast>\n) => orOf(conditions)) as never\n\n/**\n * @stability stable\n * @category combinators\n * @since 0.3.0\n */\nexport const not: <C extends Any>(\n\tcondition: C,\n) => Condition<ReadsOf<C>, OpaqueOf<C>> = makeNot as never\n\n/**\n * The data that a condition needs for a test.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Input {\n\t/** The resource value. */\n\treadonly value: object\n\t/**\n\t * The principal. Without it, a principal field has no value. See\n\t * {@link PrincipalRef}.\n\t */\n\treadonly principal?: object | undefined\n\t/** The path of the resource. Without it, `Under` is false. */\n\treadonly path?: ReadonlyArray<Resource.PathSegment> | undefined\n}\n\n/** Gives a condition as a node. A value that no constructor made is a defect. */\nconst nodeOf = (condition: Ast): Nodes.Node => Nodes.toNode(condition)\n\n/**\n * Gives the services in `context` to every predicate of a condition, so the\n * condition needs no services when it runs.\n *\n * @stability stable\n * @category services\n * @since 1.0.0\n */\nexport const provideContext: {\n\t<R>(\n\t\tcontext: Context.Context<R>,\n\t): <I, X>(\n\t\tcondition: Condition<I, X> &\n\t\t\t([ServicesOf<X>] extends [R] ? unknown : never),\n\t) => Condition<I, Provided<X>>\n\t<I, X>(\n\t\tcondition: Condition<I, X>,\n\t\tcontext: Context.Context<ServicesOf<X>>,\n\t): Condition<I, Provided<X>>\n} = dual(2, (condition: Ast, context: Context.Context<never>): Ast =>\n\tAlgebra.provide(nodeOf(condition), context),\n) as never\n\n/**\n * The input of {@link evaluate} that the predicates of a condition need: a\n * value and a principal of the types in `I`. See {@link Reads}.\n */\ntype ReadsInput<I> =\n\tI extends Reads<infer V, infer P>\n\t\t? { readonly value: V } & (unknown extends P\n\t\t\t\t? unknown\n\t\t\t\t: { readonly principal: P })\n\t\t: unknown\n\n/**\n * Tests a condition on a value. A predicate may fail with its error. When the\n * condition has a predicate, the input must have the value and the principal\n * that the predicate reads.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const evaluate: <I, X, In extends Input>(\n\tcondition: Condition<I, X>,\n\tinput: In & ReadsInput<I>,\n) => Effect.Effect<boolean, ErrorOf<X>, ServicesOf<X>> = ((\n\tcondition: Ast,\n\tinput: Input,\n): Effect.Effect<boolean, unknown, unknown> =>\n\tEffect.suspend(() => Algebra.evaluate(nodeOf(condition), input))) as never\n\n/**\n * Tests a condition with no predicate on a value, at once.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const evaluateSync: <I, In extends Input>(\n\tcondition: Condition<I>,\n\tinput: In & ReadsInput<I>,\n) => boolean = (condition: Ast, input: Input): boolean =>\n\tAlgebra.evaluateSync(nodeOf(condition), input)\n\n/**\n * Makes a condition smaller without a change to its meaning. It removes `True`\n * and `False` from `And` and `Or`, joins nested `And` and `Or` nodes, and\n * removes double `Not` nodes and copies of a child.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const simplify: <I, X>(condition: Condition<I, X>) => Condition<I, X> =\n\t((condition: Ast) => condition.pipe(nodeOf, Algebra.simplify)) as never\n\ninterface PartialInput {\n\treadonly principal?: object | undefined\n\treadonly path?: ReadonlyArray<Resource.PathSegment> | undefined\n}\n\n/**\n * The principal that {@link partial} must get for the predicates of a\n * condition. A predicate keeps the principal that it gets, so the principal\n * must have the type that the predicate reads.\n */\ntype PrincipalInput<I> =\n\tI extends Reads<infer _V, infer P>\n\t\t? unknown extends P\n\t\t\t? unknown\n\t\t\t: { readonly principal: P }\n\t\t: unknown\n\n/** What a condition reads after {@link partial}: the value, and no principal. */\ntype Bound<I> = I extends Reads<infer V, infer _P> ? Reads<V, unknown> : I\n\n/**\n * Puts the principal into a condition and expands `Under` with the path of the\n * resource. The result is simplified. It has no principal fields and no\n * `Under` nodes. It is `True` or `False` when the answer does not depend on the\n * resource value.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const partial: <I, X>(\n\tcondition: Condition<I, X>,\n\tinput: PartialInput & PrincipalInput<I>,\n) => Condition<Bound<I>, X> = ((condition: Ast, input: PartialInput): Ast =>\n\tAlgebra.partial(nodeOf(condition), input)) as never\n\n/**\n * The functions that change each node of a condition into another form, such\n * as a database query.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Interpreter<A> {\n\treadonly true: () => A\n\treadonly false: () => A\n\treadonly compare: (op: CompareOperator, field: string, value: Scalar) => A\n\treadonly in: (field: string, values: ReadonlyArray<Scalar>) => A\n\treadonly exists: (field: string) => A\n\treadonly and: (conditions: ReadonlyArray<A>) => A\n\treadonly or: (conditions: ReadonlyArray<A>) => A\n\treadonly not: (condition: A) => A\n\t/** Optional. Without it, a predicate makes `fold` fail. */\n\treadonly predicate?: (name: string) => A\n}\n\n/**\n * The error when `fold` can not change a node.\n *\n * @stability stable\n * @category errors\n * @since 0.3.0\n */\nexport class Untranslatable extends Schema.TaggedError<Untranslatable>(\n\t\"@nmnmcc/ability/Condition/Untranslatable\",\n)(\"Untranslatable\", { reason: Schema.String }) {}\n\nconst literalValue = (operand: Operand, field: string): Scalar => {\n\tif (operand._tag !== \"Literal\") {\n\t\tthrow Untranslatable.make({\n\t\t\treason: `The field \"${field}\" uses a principal field. Call Condition.partial first.`,\n\t\t})\n\t}\n\treturn operand.value\n}\n\n/** Folds a condition. A shared child is folded again for each place. */\nconst foldNode = <A>(node: Nodes.Node, interpreter: Interpreter<A>): A => {\n\tswitch (node._tag) {\n\t\tcase \"True\":\n\t\t\treturn interpreter.true()\n\t\tcase \"False\":\n\t\t\treturn interpreter.false()\n\t\tcase \"Compare\":\n\t\t\treturn interpreter.compare(\n\t\t\t\tnode.op,\n\t\t\t\tnode.field,\n\t\t\t\tliteralValue(node.value, node.field),\n\t\t\t)\n\t\tcase \"In\":\n\t\t\treturn interpreter.in(\n\t\t\t\tnode.field,\n\t\t\t\tArr.map(node.values, (operand) => literalValue(operand, node.field)),\n\t\t\t)\n\t\tcase \"Exists\":\n\t\t\treturn interpreter.exists(node.field)\n\t\tcase \"Under\":\n\t\t\tthrow Untranslatable.make({\n\t\t\t\treason:\n\t\t\t\t\t\"An Under node needs the resource path. Call Condition.partial first.\",\n\t\t\t})\n\t\tcase \"And\":\n\t\t\treturn interpreter.and(\n\t\t\t\tArr.map(node.conditions, (child) => foldNode(child, interpreter)),\n\t\t\t)\n\t\tcase \"Or\":\n\t\t\treturn interpreter.or(\n\t\t\t\tArr.map(node.conditions, (child) => foldNode(child, interpreter)),\n\t\t\t)\n\t\tcase \"Not\":\n\t\t\treturn interpreter.not(foldNode(node.condition, interpreter))\n\t\tcase \"Predicate\":\n\t\t\tif (interpreter.predicate === undefined) {\n\t\t\t\tthrow Untranslatable.make({\n\t\t\t\t\treason: `The predicate \"${node.name}\" can not become a query`,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn interpreter.predicate(node.name)\n\t}\n}\n\n/**\n * Changes a condition into another form with an interpreter. Call\n * {@link partial} first: `fold` fails on principal fields and on `Under`\n * nodes, and on predicates when the interpreter has no `predicate` function.\n *\n * @stability stable\n * @category converting\n * @since 0.3.0\n */\nexport const fold: {\n\t<A>(\n\t\tinterpreter: Interpreter<A>,\n\t): (condition: Any) => Effect.Effect<A, Untranslatable>\n\t<A>(\n\t\tcondition: Any,\n\t\tinterpreter: Interpreter<A>,\n\t): Effect.Effect<A, Untranslatable>\n} = dual(\n\t2,\n\t<A>(\n\t\tcondition: Ast,\n\t\tinterpreter: Interpreter<A>,\n\t): Effect.Effect<A, Untranslatable> =>\n\t\tEffect.try({\n\t\t\ttry: () => foldNode(nodeOf(condition), interpreter),\n\t\t\tcatch: (cause) => {\n\t\t\t\tif (cause instanceof Untranslatable) {\n\t\t\t\t\treturn cause\n\t\t\t\t}\n\t\t\t\tthrow cause\n\t\t\t},\n\t\t}),\n)\n\n/**\n * The fields that a condition uses, in the order that they first come.\n *\n * @stability stable\n * @category getters\n * @since 0.3.0\n */\nexport const fields = (condition: Ast): ReadonlyArray<string> =>\n\tcondition.pipe(nodeOf, Algebra.fields)\n\n// Satisfiability\n\n/**\n * Values of fields, as a nested object. A field that is not in it may have any\n * value. A value with parts that the search does not look into, such as a\n * date, is an empty object.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport type Example = Search.Example\n\n/**\n * The answer of {@link satisfiable}:\n * - `Satisfiable`: some value makes the condition true. `example` is one.\n * - `Unsatisfiable`: no value makes the condition true.\n * - `Unknown`: the search can not say. The condition has a predicate, or\n * the search went past its budget.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport type Satisfiability = Search.Satisfiability\n\n/**\n * The options of {@link satisfiable}.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport interface SatisfiableOptions {\n\t/**\n\t * The Schema of the values. Its shape gives the kinds of values of each\n\t * field. Without it, a field may have any value.\n\t */\n\treadonly schema?: Schema.Top | undefined\n\t/** The most steps that the search may take. The default is 1000000. */\n\treadonly budget?: number | undefined\n}\n\n/**\n * Tests if some value makes a condition true, and gives such a value.\n *\n * Call {@link partial} first: the condition must have no principal fields and\n * no `Under` nodes. A condition with a predicate gives `Unknown`.\n *\n * Each test of a condition compares one field with constants, so the\n * constants cut the values of each field into a few cells. The search tries\n * one value from each cell, one field at a time. The values of a field come\n * from the shape of the Schema in `options.schema`: its literals, `null` for\n * a nullable or optional field, and finite or integer numbers.\n *\n * The search reads the shape of the Schema, not its other checks, such as a\n * minimum length. So `Unsatisfiable` holds for every value of the Schema. A\n * `Satisfiable` example fits the shape, but a check may still stop it.\n *\n * The problem is as hard as boolean satisfiability, so the search has a\n * budget. Past it, the answer is `Unknown`. A condition with more than 256\n * fields gives `Unknown` too.\n *\n * @stability stable\n * @category evaluation\n * @since 1.0.0\n */\nexport const satisfiable = (\n\tcondition: Any,\n\toptions: SatisfiableOptions = {},\n): Satisfiability =>\n\tSearch.satisfiable(\n\t\tnodeOf(condition),\n\t\tSearch.kindsIn(\n\t\t\toptions.schema === undefined\n\t\t\t\t? undefined\n\t\t\t\t: Catalog.catalogOf(options.schema.ast),\n\t\t),\n\t\toptions.budget,\n\t)\n\n/**\n * The JSON form of an operand.\n *\n * @stability stable\n * @category models\n * @since 2.0.0\n */\nexport type EncodedOperand =\n\t| { readonly _tag: \"Literal\"; readonly value: Scalar }\n\t| { readonly _tag: \"Principal\"; readonly path: string }\n\n/**\n * The JSON form of a condition with no predicate.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Encoded =\n\t| { readonly _tag: \"True\" }\n\t| { readonly _tag: \"False\" }\n\t| {\n\t\t\treadonly _tag: \"Compare\"\n\t\t\treadonly op: CompareOperator\n\t\t\treadonly field: string\n\t\t\treadonly value: EncodedOperand\n\t }\n\t| {\n\t\t\treadonly _tag: \"In\"\n\t\t\treadonly field: string\n\t\t\treadonly values: ReadonlyArray<EncodedOperand>\n\t }\n\t| { readonly _tag: \"Exists\"; readonly field: string }\n\t| { readonly _tag: \"Under\"; readonly prefix: ReadonlyArray<EncodedOperand> }\n\t| {\n\t\t\treadonly _tag: \"And\" | \"Or\"\n\t\t\treadonly conditions: ReadonlyArray<Encoded>\n\t }\n\t| { readonly _tag: \"Not\"; readonly condition: Encoded }\n\n/**\n * A condition with no predicate, that may read any values. It is the type of\n * {@link schema}: a decoded condition reads nothing, so it fits any rule, and\n * any plain condition, such as one from a builder or a residual, may be\n * encoded.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\n// `any` for what it reads: the field is contravariant, so no other type both\n// takes every condition and fits every rule.\nexport type PlainCondition = Condition<any>\n\n/**\n * The Schema of a condition with no predicate. It checks the shape only. Use\n * `Policy.schema` to check the field names against a domain too.\n *\n * The decoder takes at most 500 levels of conditions, and at most 1000000\n * objects and array items, with a shared object counted for each place. It\n * reads only the own data fields of the input.\n *\n * @stability stable\n * @category schemas\n * @since 0.3.0\n */\nexport const schema: Schema.Codec<PlainCondition, Encoded> =\n\tSchema.Unknown.pipe(\n\t\tSchema.decodeTo(\n\t\t\tSchema.declare(\n\t\t\t\t(input): input is PlainCondition =>\n\t\t\t\t\tNodes.isNode(input) && !input.opaque,\n\t\t\t),\n\t\t\tSchemaTransformation.transformEffect({\n\t\t\t\tdecode: (input: unknown, options) =>\n\t\t\t\t\tResult.match(Json.decode(input), {\n\t\t\t\t\t\tonSuccess: (node) => Effect.succeed(node as never),\n\t\t\t\t\t\tonFailure: (problem) =>\n\t\t\t\t\t\t\tEffect.fail(\n\t\t\t\t\t\t\t\tnew SchemaIssue.Pointer(\n\t\t\t\t\t\t\t\t\tproblem.path,\n\t\t\t\t\t\t\t\t\tnew SchemaIssue.InvalidValue(\n\t\t\t\t\t\t\t\t\t\t{ message: problem.message },\n\t\t\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\t\t\toptions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;;;;;AAoED,MAAa,SACZ,OAAO,QAAQ,KACd,OAAO,SACN,OAAO,SACL,UACAC,OAAa,KAAK,KAAK,CAAC,MAAM,MAChC,GACA,qBAAqB,gBAAgB;CACpC,SAAS,OAAgB,YACxB,OAAO,MAAMC,OAAY,KAAK,GAAG;EAChC,YAAY,SAAS,OAAO,QAAQ,IAAa;EACjD,YAAY,YACX,OAAO,KACN,IAAI,YAAY,QACf,QAAQ,MACR,IAAI,YAAY,aACf,EAAE,SAAS,QAAQ,QAAQ,GAC3B,OACA,OACD,CACD,CACD;CACF,CAAC;CACF,SAAS,cACR,OAAO,WAAWC,OAAY,SAAkB,CAAC;AACnD,CAAC,CACF,CACD"}
|
|
1
|
+
{"version":3,"file":"Condition.js","names":["Nodes.literal","Nodes.Compare","Nodes.And","Nodes.Or","Nodes.Not","Nodes.In","Nodes.Exists","Nodes.Under","Nodes.principalRef","Nodes.Predicate","Nodes.always","Nodes.never","Nodes.toNode","Algebra.provide","Algebra.evaluate","Algebra.evaluateSync","Algebra.simplify","Algebra.partial","Algebra.fields","Search.satisfiable","Search.kindsIn","Catalog.catalogOf","Nodes.isNode","Json.decode","Json.toJson"],"sources":["../src/Condition.ts"],"sourcesContent":["/**\n * A condition is a test on a resource value. A rule applies only when its\n * condition is true.\n *\n * A condition is plain data: a tree of nodes. So you can:\n * - test it on a value with {@link evaluate};\n * - put the principal into it and make it smaller with {@link partial}, which\n * gives a \"residual\" condition: the part that still depends on the\n * resource;\n * - change it into a database query with {@link fold};\n * - keep it as JSON with {@link schema}.\n *\n * Make conditions with a {@link Builder}. A rule gives you a builder for its\n * resource, so the field names and the value types are checked.\n *\n * {@link Builder.predicate} is the one way out of plain data. A predicate runs\n * any `Effect`. Its error type and its service type go into the type of the\n * check. A rule with a predicate can not become JSON, and the type system\n * stops you when you try.\n *\n * @stability stable\n * @since 0.3.0\n */\n// A predicate keeps its error type and service type in the public types. The\n// code below works on the nodes with no types, where they are `unknown`, so\n// the language service check for `unknown` in an Effect is off here.\n// @effect-diagnostics anyUnknownInErrorContext:off\nimport * as Arr from \"effect/Array\"\nimport type * as BigDecimal from \"effect/BigDecimal\"\nimport type * as Cause from \"effect/Cause\"\nimport type * as Chunk from \"effect/Chunk\"\nimport type * as DateTime from \"effect/DateTime\"\nimport type * as Duration from \"effect/Duration\"\nimport type * as Exit from \"effect/Exit\"\nimport type * as HashMap from \"effect/HashMap\"\nimport type * as HashSet from \"effect/HashSet\"\nimport type * as Option from \"effect/Option\"\nimport type * as Redacted from \"effect/Redacted\"\nimport type * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\nimport { hasProperty } from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport * as SchemaIssue from \"effect/SchemaIssue\"\nimport * as SchemaTransformation from \"effect/SchemaTransformation\"\nimport * as Result from \"effect/Result\"\nimport * as Algebra from \"./internal/algebra.ts\"\nimport * as Catalog from \"./internal/catalog.ts\"\nimport * as Json from \"./internal/json.ts\"\nimport * as Nodes from \"./internal/nodes.ts\"\nimport * as Search from \"./internal/search.ts\"\nimport * as Resource from \"./Resource.ts\"\n\n/**\n * A value that a condition can compare.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Scalar = Nodes.Scalar\n\n/**\n * A fixed value in a condition.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Literal = Nodes.Literal\n\n/**\n * A field of the principal. {@link partial} puts the value of the field in its\n * place.\n *\n * A principal field that is `null` or missing has no value. A `Compare`, `In`\n * or `Under` test with it is always false, also with `ne`. So a principal with\n * no id never matches a resource with no owner. `not` still turns false into\n * true.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type PrincipalRef = Nodes.PrincipalRef\n\n/**\n * A field of the principal with a known value type `A`, from a principal of\n * the type `P`. The type fields are only in the types. A test with the\n * reference reads a principal of the type `P`, so it can not go into a rule\n * of a domain with another principal.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Ref<A, P = never> = PrincipalRef & {\n\treadonly \"~Ref\": () => A\n\treadonly \"~Principal\": (principal: P) => void\n}\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Operand = Literal | PrincipalRef\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type CompareOperator = Nodes.CompareOperator\n\n/**\n * Always true.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type True = Nodes.True\n\n/**\n * Always false.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type False = Nodes.False\n\n/**\n * Compares a field with a value. A missing field has the value `null`. `lt`,\n * `lte`, `gt` and `gte` are false when the two sides are not both numbers or\n * both strings.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Compare = Nodes.Compare\n\n/**\n * True when a field is equal to one of the values.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type In = Nodes.In\n\n/**\n * True when a field is not `null` and not missing.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Exists = Nodes.Exists\n\n/**\n * True when the path of the resource starts with the prefix. A resource with\n * no path is never under a prefix.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Under = Nodes.Under\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type And = Nodes.And\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Or = Nodes.Or\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Not = Nodes.Not\n\n/**\n * A test that runs an `Effect`. It can not become JSON or a query.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Predicate = Nodes.Predicate\n\n/**\n * The nodes of a condition, without types. Each node is a class, and only the\n * builder, the functions of this module and the Schema make one. So a plain\n * object, or a spread of a node, is not a node.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Ast = Nodes.Node\n\n/**\n * The mark of a condition with a predicate. `E` and `R` are the error type\n * and the service type of its predicates.\n *\n * @stability stable\n * @category models\n * @since 2.0.0\n */\nexport interface Opaque<out E = never, out R = never> {\n\treadonly \"~Opaque\": { readonly E: E; readonly R: R }\n}\n\n/**\n * The error type of the predicates of a mark `X`. A mark that is not an\n * {@link Opaque}, as `unknown` or `object`, may have any error.\n *\n * @stability stable\n * @category utility types\n * @since 2.0.0\n */\nexport type ErrorOf<X> = X extends Opaque<infer E, infer _R> ? E : unknown\n\n/**\n * The service type of the predicates of a mark `X`. A mark that is not an\n * {@link Opaque}, as `unknown` or `object`, may need any service.\n *\n * @stability stable\n * @category utility types\n * @since 2.0.0\n */\nexport type ServicesOf<X> = X extends Opaque<infer _E, infer R> ? R : unknown\n\n/**\n * The mark `X` with no services.\n *\n * @stability stable\n * @category utility types\n * @since 2.0.0\n */\nexport type Provided<X> =\n\tX extends Opaque<infer E, infer _R> ? Opaque<E> : Opaque<unknown>\n\n/**\n * What the predicates of a condition read: a resource value of the type `V`\n * and a principal of the type `P`. It is only in the types.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport interface Reads<V, P> {\n\treadonly value: V\n\treadonly principal: P\n}\n\n/**\n * A condition. `I` is what its tests read: see {@link Reads}. `X` is\n * {@link Opaque} when the condition has a predicate, and `never` when it is\n * plain data. A plain condition can become JSON or a query.\n *\n * The two type fields are only in the types. `I` goes into a function as an\n * input, so a condition that reads a `Post` does not fit a rule for a\n * `Comment`. `X` comes out of a function, so a plain condition fits where a\n * condition with predicates may go.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Condition<I = unknown, X = never> = Ast & {\n\treadonly \"~Reads\": (reads: I) => void\n\treadonly \"~Opaque\": () => X\n}\n\n/**\n * Any condition.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Any = Condition<any, any>\n\n/**\n * What the tests of a condition read. For a union of conditions, it is what\n * all of them read.\n *\n * @stability stable\n * @category utility types\n * @since 1.0.0\n */\nexport type ReadsOf<C> = [C] extends [\n\t{ readonly \"~Reads\": (reads: infer I) => void },\n]\n\t? I\n\t: unknown\n\n/**\n * The mark of a condition: {@link Opaque} when it has a predicate.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type OpaqueOf<C> = C extends { readonly \"~Opaque\": () => infer X }\n\t? X\n\t: never\n\ntype Leaf = string | number | boolean | bigint | symbol | null | undefined\n/**\n * Values of a class that keeps its data inside. A path does not go into them,\n * as in the field paths of a resource, so a field with such a value is one\n * field. A condition can test only if it exists.\n */\ntype Whole =\n\t| ReadonlyMap<unknown, unknown>\n\t| ReadonlySet<unknown>\n\t| HashMap.HashMap<unknown, unknown>\n\t| HashSet.HashSet<unknown>\n\t| Date\n\t| URL\n\t| Uint8Array\n\t| Option.Option<unknown>\n\t| BigDecimal.BigDecimal\n\t| Duration.Duration\n\t| DateTime.DateTime\n\t| Redacted.Redacted<unknown>\n\t| Chunk.Chunk<unknown>\n\t| Cause.Cause<unknown>\n\t| Result.Result<unknown, unknown>\n\t| Exit.Exit<unknown, unknown>\n\t| File\n\t| FormData\n\t| RegExp\n\t| URLSearchParams\ntype PreviousDepth = [never, 0, 1, 2, 3]\ntype FieldPathInternal<\n\tT,\n\tDepth extends number,\n\tArrays extends boolean,\n\tParents extends boolean = false,\n> = [Depth] extends [never]\n\t? never\n\t: {\n\t\t\t// A record with number keys has number keys, as `counts.1`.\n\t\t\t[K in keyof T & (string | number)]-?: PathsOf<\n\t\t\t\t`${K}`,\n\t\t\t\tNonNullable<T[K]>,\n\t\t\t\tDepth,\n\t\t\t\tArrays,\n\t\t\t\tParents\n\t\t\t>\n\t\t}[keyof T & (string | number)]\n\n/**\n * The paths of one field `K` with the values `V`. Each kind of value in `V`\n * gives its own paths, so a field that holds a string or a struct is a field,\n * and the fields of the struct are fields too. A function is no field.\n */\ntype PathsOf<\n\tK extends string,\n\tV,\n\tDepth extends number,\n\tArrays extends boolean,\n\tParents extends boolean,\n> =\n\t// A field that is only ever `null` or missing is a field too, and so is a\n\t// field that may hold any value, as one of `Schema.Unknown` may.\n\t| ([V] extends [never] ? K : {} extends V ? K : never)\n\t| ([Extract<V, Leaf | Whole>] extends [never] ? never : K)\n\t| ([Extract<V, ReadonlyArray<unknown>>] extends [never]\n\t\t\t? never\n\t\t\t: Arrays extends true\n\t\t\t\t? K\n\t\t\t\t: never)\n\t| ObjectPaths<\n\t\t\tK,\n\t\t\tExclude<V, Leaf | Whole | Function | ReadonlyArray<unknown>>,\n\t\t\tDepth,\n\t\t\tArrays,\n\t\t\tParents\n\t >\n\n/** The paths of a field `K` that holds the objects `O`, and of the fields below. */\ntype ObjectPaths<\n\tK extends string,\n\tO,\n\tDepth extends number,\n\tArrays extends boolean,\n\tParents extends boolean,\n> = [O] extends [never]\n\t? never\n\t: // A record is one field to a rule or a request, as `permittedFields`\n\t\t// lists it.\n\t\t| (Parents extends true\n\t\t\t\t? K\n\t\t\t\t: Arrays extends true\n\t\t\t\t\t? string extends keyof O\n\t\t\t\t\t\t? K\n\t\t\t\t\t\t: number extends keyof O\n\t\t\t\t\t\t\t? K\n\t\t\t\t\t\t\t: never\n\t\t\t\t\t: never)\n\t\t| `${K}.${FieldPathInternal<O, PreviousDepth[Depth], Arrays, Parents>}`\n\n/**\n * The paths of the fields of `T` that hold one value, with dots for nested\n * fields. Arrays are left out. A map, a set, a date, a URL, a byte array, an\n * `Option` and the other value types of Effect, such as `BigDecimal` and\n * `Duration`, are one field, and a path does not go into them. The type goes down four levels, so type\n * checking stays fast. For a union of types, only the common fields are\n * paths.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type FieldPath<T> = [T] extends [object]\n\t? FieldPathInternal<T, 4, false>\n\t: never\n\n/**\n * The paths of the fields of `T` that a rule or a request may name, as in\n * `Rule.Options.fields`. They are the paths of {@link FieldPath}, and the\n * paths of arrays too: a rule may allow or deny a whole array field, and\n * `permittedFields` lists it.\n *\n * @stability stable\n * @category utility types\n * @since 1.0.0\n */\nexport type FieldSelector<T> = [T] extends [object]\n\t? FieldPathInternal<T, 4, true>\n\t: never\n\n/**\n * The names that the `fields` of a rule may have: the paths of\n * {@link FieldSelector}, and the paths of the structs above them. A name of a\n * struct covers the fields below it.\n *\n * @stability stable\n * @category utility types\n * @since 2.0.0\n */\nexport type FieldName<T> = [T] extends [object]\n\t? FieldPathInternal<T, 4, true, true>\n\t: never\n\n/**\n * The value type that fits every field in `F`. For one field, it is the type\n * of the field. For a union of fields, it is the values that each of them can\n * hold, so a value of a union type can not test a field of another type. For\n * a union of data types, as for a rule on two kinds, it is the values that\n * the field can hold in each of them.\n *\n * @stability stable\n * @category utility types\n * @since 1.0.0\n */\nexport type FieldValue<Data, F extends string> = (\n\tData extends unknown\n\t\t? F extends unknown\n\t\t\t? (value: PathValue<Data, F>) => void\n\t\t\t: never\n\t\t: never\n) extends (value: infer V) => void\n\t? V\n\t: never\n\ntype Normalize<A> = Exclude<A, undefined> | (undefined extends A ? null : never)\n\n/**\n * The type of the field of `T` at `Path`. A field that may be missing may also\n * be `null`.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type PathValue<\n\tT,\n\tPath extends string,\n> = Path extends `${infer Head}.${infer Rest}`\n\t? Head extends keyof T\n\t\t? undefined extends T[Head]\n\t\t\t? PathValue<NonNullable<T[Head]>, Rest> | null\n\t\t\t: null extends T[Head]\n\t\t\t\t? PathValue<NonNullable<T[Head]>, Rest> | null\n\t\t\t\t: PathValue<T[Head], Rest>\n\t\t: never\n\t: Path extends keyof T\n\t\t? Normalize<T[Path]>\n\t\t: never\n\n/**\n * A value for a field of type `A`: a fixed value, or a field of the principal\n * with the same type.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type OperandOf<A, P = never> = Extract<A, Scalar> | Ref<A, P>\n\ntype ScalarPath<T> = {\n\t[F in FieldPath<T>]: PathValue<T, F> extends Scalar ? F : never\n}[FieldPath<T>]\n\ntype OrderedPath<T> = {\n\t[F in FieldPath<T>]: Exclude<PathValue<T, F>, null> extends number | string\n\t\t? F\n\t\t: never\n}[FieldPath<T>]\n\n/**\n * A test made by a {@link Builder}. It runs no code, but it keeps the value\n * type of its resource, so a test on the fields of one resource can not go\n * into a rule for another resource. A test with a field of the principal\n * keeps the principal type `P` too.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport type Test<Value, P = unknown> = Condition<Reads<Value, P>>\n\n/**\n * The principal type that a test reads: the principal of each field of the\n * principal in the values `V`, and `unknown` when there is none. A reference\n * from another builder keeps the principal of that builder.\n */\ntype PrincipalOf<V, _P> = [Extract<V, PrincipalRef>] extends [never]\n\t? unknown\n\t: [Extract<V, PrincipalRef>] extends [\n\t\t\t\t{ readonly \"~Principal\": (principal: infer Q) => void },\n\t\t ]\n\t\t? Q\n\t\t: unknown\n\n/**\n * Makes conditions for a resource with the data type `Data` and the value type\n * `Value`, and a principal with the type `P`.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Builder<Data, Value, P> {\n\t/** The field is equal to the value. */\n\treadonly eq: <\n\t\tconst F extends FieldPath<Data>,\n\t\tconst V extends OperandOf<FieldValue<Data, F>, any>,\n\t>(\n\t\tfield: F,\n\t\tvalue: V,\n\t) => Test<Value, PrincipalOf<V, P>>\n\t/** The field is not equal to the value. */\n\treadonly ne: <\n\t\tconst F extends FieldPath<Data>,\n\t\tconst V extends OperandOf<FieldValue<Data, F>, any>,\n\t>(\n\t\tfield: F,\n\t\tvalue: V,\n\t) => Test<Value, PrincipalOf<V, P>>\n\treadonly lt: <\n\t\tconst F extends OrderedPath<Data>,\n\t\tconst V extends OperandOf<Exclude<FieldValue<Data, F>, null>, any>,\n\t>(\n\t\tfield: F,\n\t\tvalue: V,\n\t) => Test<Value, PrincipalOf<V, P>>\n\treadonly lte: <\n\t\tconst F extends OrderedPath<Data>,\n\t\tconst V extends OperandOf<Exclude<FieldValue<Data, F>, null>, any>,\n\t>(\n\t\tfield: F,\n\t\tvalue: V,\n\t) => Test<Value, PrincipalOf<V, P>>\n\treadonly gt: <\n\t\tconst F extends OrderedPath<Data>,\n\t\tconst V extends OperandOf<Exclude<FieldValue<Data, F>, null>, any>,\n\t>(\n\t\tfield: F,\n\t\tvalue: V,\n\t) => Test<Value, PrincipalOf<V, P>>\n\treadonly gte: <\n\t\tconst F extends OrderedPath<Data>,\n\t\tconst V extends OperandOf<Exclude<FieldValue<Data, F>, null>, any>,\n\t>(\n\t\tfield: F,\n\t\tvalue: V,\n\t) => Test<Value, PrincipalOf<V, P>>\n\t/** The field is equal to one of the values. */\n\treadonly in: <\n\t\tconst F extends FieldPath<Data>,\n\t\tconst Vs extends ReadonlyArray<OperandOf<FieldValue<Data, F>, any>>,\n\t>(\n\t\tfield: F,\n\t\tvalues: Vs,\n\t) => Test<Value, PrincipalOf<Vs[number], P>>\n\t/** The field has a value that is not `null`. */\n\treadonly exists: <const F extends FieldPath<Data>>(field: F) => Test<Value>\n\t/** The path of the resource starts with these parts. */\n\treadonly under: <\n\t\tconst Ps extends ReadonlyArray<string | null | Ref<string | null, any>>,\n\t>(\n\t\t...prefix: Ps\n\t) => Test<Value, PrincipalOf<Ps[number], P>>\n\t/**\n\t * A field of the principal, to use as a value. The field must have a\n\t * {@link Scalar} type.\n\t */\n\treadonly principal: <const F extends ScalarPath<P>>(\n\t\tfield: F,\n\t) => Ref<PathValue<P, F>, P>\n\treadonly and: <const Cs extends ReadonlyArray<Any>>(\n\t\t...conditions: Cs\n\t) => Condition<ReadsOf<Cs[number]>, OpaqueOf<Cs[number]>>\n\treadonly or: <const Cs extends ReadonlyArray<Any>>(\n\t\t...conditions: Cs\n\t) => Condition<ReadsOf<Cs[number]>, OpaqueOf<Cs[number]>>\n\treadonly not: <C extends Any>(\n\t\tcondition: C,\n\t) => Condition<ReadsOf<C>, OpaqueOf<C>>\n\t/**\n\t * A test that runs any code. It may give a boolean or an `Effect`. A\n\t * condition with a predicate can not become JSON or a query.\n\t */\n\treadonly predicate: <E = never, R = never>(\n\t\tname: string,\n\t\ttest: (\n\t\t\tvalue: Value,\n\t\t\tprincipal: P,\n\t\t) => boolean | Effect.Effect<boolean, E, R>,\n\t) => Condition<Reads<Value, P>, Opaque<E, R>>\n}\n\nconst isOperand = (u: unknown): u is Operand =>\n\thasProperty(u, \"_tag\") && (u._tag === \"Literal\" || u._tag === \"Principal\")\n\nconst toOperand = (value: unknown): Operand =>\n\tisOperand(value) ? value : Nodes.literal(value as Scalar)\n\nconst compare =\n\t(op: CompareOperator) =>\n\t(field: string, value: unknown): Ast =>\n\t\tnew Nodes.Compare({ op, field, value: toOperand(value) })\n\n// A list of conditions goes in as an array, not as arguments: a call may take\n// only so many arguments, and a decoded condition may have more children.\n// The constructor copies the list, so a later change to the array of a caller\n// does not change the condition.\nconst andOf = (conditions: ReadonlyArray<Ast>): Ast =>\n\tnew Nodes.And(conditions as ReadonlyArray<Nodes.Node>)\n\nconst orOf = (conditions: ReadonlyArray<Ast>): Ast =>\n\tnew Nodes.Or(conditions as ReadonlyArray<Nodes.Node>)\n\nconst makeNot = (condition: Ast): Ast => new Nodes.Not(condition as Nodes.Node)\n\nconst sharedBuilder: Builder<any, any, any> = {\n\teq: compare(\"eq\"),\n\tne: compare(\"ne\"),\n\tlt: compare(\"lt\"),\n\tlte: compare(\"lte\"),\n\tgt: compare(\"gt\"),\n\tgte: compare(\"gte\"),\n\tin: (field: string, values: ReadonlyArray<unknown>) =>\n\t\tnew Nodes.In({ field, values: Arr.map(Array.from(values), toOperand) }),\n\texists: (field: string) => new Nodes.Exists({ field }),\n\tunder: (...prefix: ReadonlyArray<unknown>) =>\n\t\tnew Nodes.Under({ prefix: Arr.map(prefix, toOperand) }),\n\tprincipal: (path: string) => Nodes.principalRef(path),\n\tand: (...conditions: ReadonlyArray<Ast>) => andOf(conditions),\n\tor: (...conditions: ReadonlyArray<Ast>) => orOf(conditions),\n\tnot: makeNot,\n\tpredicate: (\n\t\tname: string,\n\t\ttest: (\n\t\t\tvalue: unknown,\n\t\t\tprincipal: unknown,\n\t\t) => boolean | Effect.Effect<boolean, unknown, unknown>,\n\t) =>\n\t\tnew Nodes.Predicate({\n\t\t\tname,\n\t\t\trun: (value, principal) =>\n\t\t\t\tEffect.suspend(() => {\n\t\t\t\t\tconst result = test(value, principal)\n\t\t\t\t\treturn Effect.isEffect(result) ? result : Effect.succeed(result)\n\t\t\t\t}),\n\t\t}),\n} as never\n\n/**\n * Makes a builder. Rules give you a builder with the right types, so you do not\n * often need this.\n *\n * @stability stable\n * @category constructors\n * @since 0.3.0\n */\nexport const builder = <Data, Value, P>(): Builder<Data, Value, P> =>\n\tsharedBuilder\n\n/**\n * Always true.\n *\n * @stability stable\n * @category constructors\n * @since 0.3.0\n */\nexport const always: Condition = Nodes.always as never\n\n/**\n * Always false.\n *\n * @stability stable\n * @category constructors\n * @since 0.3.0\n */\nexport const never: Condition = Nodes.never as never\n\n/**\n * True when all the conditions are true. With no conditions, it is true.\n *\n * @stability stable\n * @category combinators\n * @since 0.3.0\n */\nexport const and: <const Cs extends ReadonlyArray<Any>>(\n\t...conditions: Cs\n) => Condition<ReadsOf<Cs[number]>, OpaqueOf<Cs[number]>> = ((\n\t...conditions: ReadonlyArray<Ast>\n) => andOf(conditions)) as never\n\n/**\n * The same as {@link and}, for a list of conditions of one type. Use it for a\n * long list: a function call may take only so many arguments.\n *\n * @stability stable\n * @category combinators\n * @since 1.0.0\n */\nexport const andAll: <C extends Any>(\n\tconditions: ReadonlyArray<C>,\n) => Condition<ReadsOf<C>, OpaqueOf<C>> = andOf as never\n\n/**\n * The same as {@link or}, for a list of conditions of one type. Use it for a\n * long list: a function call may take only so many arguments.\n *\n * @stability stable\n * @category combinators\n * @since 1.0.0\n */\nexport const orAll: <C extends Any>(\n\tconditions: ReadonlyArray<C>,\n) => Condition<ReadsOf<C>, OpaqueOf<C>> = orOf as never\n\n/**\n * True when one of the conditions is true. With no conditions, it is false.\n *\n * @stability stable\n * @category combinators\n * @since 0.3.0\n */\nexport const or: <const Cs extends ReadonlyArray<Any>>(\n\t...conditions: Cs\n) => Condition<ReadsOf<Cs[number]>, OpaqueOf<Cs[number]>> = ((\n\t...conditions: ReadonlyArray<Ast>\n) => orOf(conditions)) as never\n\n/**\n * @stability stable\n * @category combinators\n * @since 0.3.0\n */\nexport const not: <C extends Any>(\n\tcondition: C,\n) => Condition<ReadsOf<C>, OpaqueOf<C>> = makeNot as never\n\n/**\n * The data that a condition needs for a test.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Input {\n\t/** The resource value. */\n\treadonly value: object\n\t/**\n\t * The principal. Without it, a principal field has no value. See\n\t * {@link PrincipalRef}.\n\t */\n\treadonly principal?: object | undefined\n\t/** The path of the resource. Without it, `Under` is false. */\n\treadonly path?: ReadonlyArray<Resource.PathSegment> | undefined\n}\n\n/** Gives a condition as a node. A value that no constructor made is a defect. */\nconst nodeOf = (condition: Ast): Nodes.Node => Nodes.toNode(condition)\n\n/**\n * Gives the services in `context` to every predicate of a condition, so the\n * condition needs no services when it runs.\n *\n * @stability stable\n * @category services\n * @since 1.0.0\n */\nexport const provideContext: {\n\t<R>(\n\t\tcontext: Context.Context<R>,\n\t): <I, X>(\n\t\tcondition: Condition<I, X> &\n\t\t\t([ServicesOf<X>] extends [R] ? unknown : never),\n\t) => Condition<I, Provided<X>>\n\t<I, X>(\n\t\tcondition: Condition<I, X>,\n\t\tcontext: Context.Context<ServicesOf<X>>,\n\t): Condition<I, Provided<X>>\n} = dual(2, (condition: Ast, context: Context.Context<never>): Ast =>\n\tAlgebra.provide(nodeOf(condition), context),\n) as never\n\n/**\n * The input of {@link evaluate} that the predicates of a condition need: a\n * value and a principal of the types in `I`. See {@link Reads}.\n */\ntype ReadsInput<I> =\n\tI extends Reads<infer V, infer P>\n\t\t? { readonly value: V } & (unknown extends P\n\t\t\t\t? unknown\n\t\t\t\t: { readonly principal: P })\n\t\t: unknown\n\n/**\n * Tests a condition on a value. A predicate may fail with its error. When the\n * condition has a predicate, the input must have the value and the principal\n * that the predicate reads.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const evaluate: <I, X, In extends Input>(\n\tcondition: Condition<I, X>,\n\tinput: In & ReadsInput<I>,\n) => Effect.Effect<boolean, ErrorOf<X>, ServicesOf<X>> = ((\n\tcondition: Ast,\n\tinput: Input,\n): Effect.Effect<boolean, unknown, unknown> =>\n\tEffect.suspend(() => Algebra.evaluate(nodeOf(condition), input))) as never\n\n/**\n * Tests a condition with no predicate on a value, at once.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const evaluateSync: <I, In extends Input>(\n\tcondition: Condition<I>,\n\tinput: In & ReadsInput<I>,\n) => boolean = (condition: Ast, input: Input): boolean =>\n\tAlgebra.evaluateSync(nodeOf(condition), input)\n\n/**\n * Makes a condition smaller without a change to its meaning. It removes `True`\n * and `False` from `And` and `Or`, joins nested `And` and `Or` nodes, and\n * removes double `Not` nodes and copies of a child.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const simplify: <I, X>(condition: Condition<I, X>) => Condition<I, X> =\n\t((condition: Ast) => condition.pipe(nodeOf, Algebra.simplify)) as never\n\ninterface PartialInput {\n\treadonly principal?: object | undefined\n\treadonly path?: ReadonlyArray<Resource.PathSegment> | undefined\n}\n\n/**\n * The principal that {@link partial} must get for the predicates of a\n * condition. A predicate keeps the principal that it gets, so the principal\n * must have the type that the predicate reads.\n */\ntype PrincipalInput<I> =\n\tI extends Reads<infer _V, infer P>\n\t\t? unknown extends P\n\t\t\t? unknown\n\t\t\t: { readonly principal: P }\n\t\t: unknown\n\n/** What a condition reads after {@link partial}: the value, and no principal. */\ntype Bound<I> = I extends Reads<infer V, infer _P> ? Reads<V, unknown> : I\n\n/**\n * Puts the principal into a condition and expands `Under` with the path of the\n * resource. The result is simplified. It has no principal fields and no\n * `Under` nodes. It is `True` or `False` when the answer does not depend on the\n * resource value.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const partial: <I, X>(\n\tcondition: Condition<I, X>,\n\tinput: PartialInput & PrincipalInput<I>,\n) => Condition<Bound<I>, X> = ((condition: Ast, input: PartialInput): Ast =>\n\tAlgebra.partial(nodeOf(condition), input)) as never\n\n/**\n * The functions that change each node of a condition into another form, such\n * as a database query.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Interpreter<A> {\n\treadonly true: () => A\n\treadonly false: () => A\n\treadonly compare: (op: CompareOperator, field: string, value: Scalar) => A\n\treadonly in: (field: string, values: ReadonlyArray<Scalar>) => A\n\treadonly exists: (field: string) => A\n\treadonly and: (conditions: ReadonlyArray<A>) => A\n\treadonly or: (conditions: ReadonlyArray<A>) => A\n\treadonly not: (condition: A) => A\n\t/** Optional. Without it, a predicate makes `fold` fail. */\n\treadonly predicate?: (name: string) => A\n}\n\n/**\n * The error when `fold` can not change a node.\n *\n * @stability stable\n * @category errors\n * @since 0.3.0\n */\nexport class Untranslatable extends Schema.TaggedError<Untranslatable>(\n\t\"@nmnmcc/ability/Condition/Untranslatable\",\n)(\"Untranslatable\", { reason: Schema.String }) {}\n\nconst literalValue = (operand: Operand, field: string): Scalar => {\n\tif (operand._tag !== \"Literal\") {\n\t\tthrow Untranslatable.make({\n\t\t\treason: `The field \"${field}\" uses a principal field. Call Condition.partial first.`,\n\t\t})\n\t}\n\treturn operand.value\n}\n\n/** Folds a condition. A shared child is folded again for each place. */\nconst foldNode = <A>(node: Nodes.Node, interpreter: Interpreter<A>): A => {\n\tswitch (node._tag) {\n\t\tcase \"True\":\n\t\t\treturn interpreter.true()\n\t\tcase \"False\":\n\t\t\treturn interpreter.false()\n\t\tcase \"Compare\":\n\t\t\treturn interpreter.compare(\n\t\t\t\tnode.op,\n\t\t\t\tnode.field,\n\t\t\t\tliteralValue(node.value, node.field),\n\t\t\t)\n\t\tcase \"In\":\n\t\t\treturn interpreter.in(\n\t\t\t\tnode.field,\n\t\t\t\tArr.map(node.values, (operand) => literalValue(operand, node.field)),\n\t\t\t)\n\t\tcase \"Exists\":\n\t\t\treturn interpreter.exists(node.field)\n\t\tcase \"Under\":\n\t\t\tthrow Untranslatable.make({\n\t\t\t\treason:\n\t\t\t\t\t\"An Under node needs the resource path. Call Condition.partial first.\",\n\t\t\t})\n\t\tcase \"And\":\n\t\t\treturn interpreter.and(\n\t\t\t\tArr.map(node.conditions, (child) => foldNode(child, interpreter)),\n\t\t\t)\n\t\tcase \"Or\":\n\t\t\treturn interpreter.or(\n\t\t\t\tArr.map(node.conditions, (child) => foldNode(child, interpreter)),\n\t\t\t)\n\t\tcase \"Not\":\n\t\t\treturn interpreter.not(foldNode(node.condition, interpreter))\n\t\tcase \"Predicate\":\n\t\t\tif (interpreter.predicate === undefined) {\n\t\t\t\tthrow Untranslatable.make({\n\t\t\t\t\treason: `The predicate \"${node.name}\" can not become a query`,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn interpreter.predicate(node.name)\n\t}\n}\n\n/**\n * Changes a condition into another form with an interpreter. Call\n * {@link partial} first: `fold` fails on principal fields and on `Under`\n * nodes, and on predicates when the interpreter has no `predicate` function.\n *\n * @stability stable\n * @category converting\n * @since 0.3.0\n */\nexport const fold: {\n\t<A>(\n\t\tinterpreter: Interpreter<A>,\n\t): (condition: Any) => Effect.Effect<A, Untranslatable>\n\t<A>(\n\t\tcondition: Any,\n\t\tinterpreter: Interpreter<A>,\n\t): Effect.Effect<A, Untranslatable>\n} = dual(\n\t2,\n\t<A>(\n\t\tcondition: Ast,\n\t\tinterpreter: Interpreter<A>,\n\t): Effect.Effect<A, Untranslatable> =>\n\t\tEffect.try({\n\t\t\ttry: () => foldNode(nodeOf(condition), interpreter),\n\t\t\tcatch: (cause) => {\n\t\t\t\tif (cause instanceof Untranslatable) {\n\t\t\t\t\treturn cause\n\t\t\t\t}\n\t\t\t\tthrow cause\n\t\t\t},\n\t\t}),\n)\n\n/**\n * The fields that a condition uses, in the order that they first come.\n *\n * @stability stable\n * @category getters\n * @since 0.3.0\n */\nexport const fields = (condition: Ast): ReadonlyArray<string> =>\n\tcondition.pipe(nodeOf, Algebra.fields)\n\n// Satisfiability\n\n/**\n * Values of fields, as a nested object. A field that is not in it may have any\n * value. A value with parts that the search does not look into, such as a\n * date, is an empty object.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport type Example = Search.Example\n\n/**\n * The answer of {@link satisfiable}:\n * - `Satisfiable`: some value makes the condition true. `example` is one.\n * - `Unsatisfiable`: no value makes the condition true.\n * - `Unknown`: the search can not say. The condition has a predicate, or\n * the search went past its budget.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport type Satisfiability = Search.Satisfiability\n\n/**\n * The options of {@link satisfiable}.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport interface SatisfiableOptions {\n\t/**\n\t * The Schema of the values. Its shape gives the kinds of values of each\n\t * field. Without it, a field may have any value.\n\t */\n\treadonly schema?: Schema.Top | undefined\n\t/** The most steps that the search may take. The default is 1000000. */\n\treadonly budget?: number | undefined\n}\n\n/**\n * Tests if some value makes a condition true, and gives such a value.\n *\n * Call {@link partial} first: the condition must have no principal fields and\n * no `Under` nodes. A condition with a predicate gives `Unknown`.\n *\n * Each test of a condition compares one field with constants, so the\n * constants cut the values of each field into a few cells. The search tries\n * one value from each cell, one field at a time. The values of a field come\n * from the shape of the Schema in `options.schema`: its literals, `null` for\n * a nullable or optional field, and finite or integer numbers.\n *\n * The search reads the shape of the Schema, not its other checks, such as a\n * minimum length. So `Unsatisfiable` holds for every value of the Schema. A\n * `Satisfiable` example fits the shape, but a check may still stop it.\n *\n * The problem is as hard as boolean satisfiability, so the search has a\n * budget. Past it, the answer is `Unknown`. A condition with more than 256\n * fields gives `Unknown` too.\n *\n * @stability stable\n * @category evaluation\n * @since 1.0.0\n */\nexport const satisfiable = (\n\tcondition: Any,\n\toptions: SatisfiableOptions = {},\n): Satisfiability =>\n\tSearch.satisfiable(\n\t\tnodeOf(condition),\n\t\tSearch.kindsIn(\n\t\t\toptions.schema === undefined\n\t\t\t\t? undefined\n\t\t\t\t: Catalog.catalogOf(options.schema.ast),\n\t\t),\n\t\toptions.budget,\n\t)\n\n/**\n * The JSON form of an operand.\n *\n * @stability stable\n * @category models\n * @since 2.0.0\n */\nexport type EncodedOperand =\n\t| { readonly _tag: \"Literal\"; readonly value: Scalar }\n\t| { readonly _tag: \"Principal\"; readonly path: string }\n\n/**\n * The JSON form of a condition with no predicate.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Encoded =\n\t| { readonly _tag: \"True\" }\n\t| { readonly _tag: \"False\" }\n\t| {\n\t\t\treadonly _tag: \"Compare\"\n\t\t\treadonly op: CompareOperator\n\t\t\treadonly field: string\n\t\t\treadonly value: EncodedOperand\n\t }\n\t| {\n\t\t\treadonly _tag: \"In\"\n\t\t\treadonly field: string\n\t\t\treadonly values: ReadonlyArray<EncodedOperand>\n\t }\n\t| { readonly _tag: \"Exists\"; readonly field: string }\n\t| { readonly _tag: \"Under\"; readonly prefix: ReadonlyArray<EncodedOperand> }\n\t| {\n\t\t\treadonly _tag: \"And\" | \"Or\"\n\t\t\treadonly conditions: ReadonlyArray<Encoded>\n\t }\n\t| { readonly _tag: \"Not\"; readonly condition: Encoded }\n\n/**\n * A condition with no predicate, that may read any values. It is the type of\n * {@link schema}: a decoded condition reads nothing, so it fits any rule, and\n * any plain condition, such as one from a builder or a residual, may be\n * encoded.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\n// `any` for what it reads: the field is contravariant, so no other type both\n// takes every condition and fits every rule.\nexport type PlainCondition = Condition<any>\n\n/**\n * The Schema of a condition with no predicate. It checks the shape only. Use\n * `Policy.schema` to check the field names against a domain too.\n *\n * The decoder takes at most 500 levels of conditions, and at most 1000000\n * objects and array items, with a shared object counted for each place. It\n * reads only the own data fields of the input.\n *\n * @stability stable\n * @category schemas\n * @since 0.3.0\n */\nexport const schema: Schema.Codec<PlainCondition, Encoded> =\n\tSchema.Unknown.pipe(\n\t\tSchema.decodeTo(\n\t\t\tSchema.declare(\n\t\t\t\t(input): input is PlainCondition =>\n\t\t\t\t\tNodes.isNode(input) && !input.opaque,\n\t\t\t),\n\t\t\tSchemaTransformation.transformEffect({\n\t\t\t\tdecode: (input: unknown, options) =>\n\t\t\t\t\tResult.match(Json.decode(input), {\n\t\t\t\t\t\tonSuccess: (node) => Effect.succeed(node as never),\n\t\t\t\t\t\tonFailure: (problem) =>\n\t\t\t\t\t\t\tEffect.fail(\n\t\t\t\t\t\t\t\tnew SchemaIssue.Pointer(\n\t\t\t\t\t\t\t\t\tproblem.path,\n\t\t\t\t\t\t\t\t\tnew SchemaIssue.InvalidValue(\n\t\t\t\t\t\t\t\t\t\t{ message: problem.message },\n\t\t\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\t\t\toptions,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t}),\n\t\t\t\tencode: (condition: PlainCondition) =>\n\t\t\t\t\tEffect.sync(() => Json.toJson(condition as never)),\n\t\t\t}),\n\t\t),\n\t) as never\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0oBA,MAAM,aAAa,MAClB,YAAY,GAAG,MAAM,MAAM,EAAE,SAAS,aAAa,EAAE,SAAS;AAE/D,MAAM,aAAa,UAClB,UAAU,KAAK,IAAI,QAAQA,QAAc,KAAe;AAEzD,MAAM,WACJ,QACA,OAAe,UACf,IAAIC,QAAc;CAAE;CAAI;CAAO,OAAO,UAAU,KAAK;AAAE,CAAC;AAM1D,MAAM,SAAS,eACd,IAAIC,IAAU,UAAuC;AAEtD,MAAM,QAAQ,eACb,IAAIC,GAAS,UAAuC;AAErD,MAAM,WAAW,cAAwB,IAAIC,IAAU,SAAuB;AAE9E,MAAM,gBAAwC;CAC7C,IAAI,QAAQ,IAAI;CAChB,IAAI,QAAQ,IAAI;CAChB,IAAI,QAAQ,IAAI;CAChB,KAAK,QAAQ,KAAK;CAClB,IAAI,QAAQ,IAAI;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;;;;;AAWA,MAAa,OAQT,KACH,IAEC,WACA,gBAEA,OAAO,IAAI;CACV,WAAW,SAAS,OAAO,SAAS,GAAG,WAAW;CAClD,QAAQ,UAAU;EACjB,IAAI,iBAAiB,gBACpB,OAAO;EAER,MAAM;CACP;AACD,CAAC,CACH;;;;;;;;AASA,MAAa,UAAU,cACtB,UAAU,KAAK,QAAQC,QAAc;;;;;;;;;;;;;;;;;;;;;;;;;AAqEtC,MAAa,eACZ,WACA,UAA8B,CAAC,MAE/BC,cACC,OAAO,SAAS,GAChBC,QACC,QAAQ,WAAW,KAAA,IAChB,KAAA,IACAC,UAAkB,QAAQ,OAAO,GAAG,CACxC,GACA,QAAQ,MACT;;;;;;;;;;;;;AAoED,MAAa,SACZ,OAAO,QAAQ,KACd,OAAO,SACN,OAAO,SACL,UACAC,OAAa,KAAK,KAAK,CAAC,MAAM,MAChC,GACA,qBAAqB,gBAAgB;CACpC,SAAS,OAAgB,YACxB,OAAO,MAAMC,OAAY,KAAK,GAAG;EAChC,YAAY,SAAS,OAAO,QAAQ,IAAa;EACjD,YAAY,YACX,OAAO,KACN,IAAI,YAAY,QACf,QAAQ,MACR,IAAI,YAAY,aACf,EAAE,SAAS,QAAQ,QAAQ,GAC3B,OACA,OACD,CACD,CACD;CACF,CAAC;CACF,SAAS,cACR,OAAO,WAAWC,OAAY,SAAkB,CAAC;AACnD,CAAC,CACF,CACD"}
|
package/dist/Policy.d.ts
CHANGED
|
@@ -559,8 +559,10 @@ export type ResidualReads<D, K> = Reads<(K extends unknown ? (value: ValueOf<D,
|
|
|
559
559
|
/**
|
|
560
560
|
* Gives the condition on resource values for which the policy allows a
|
|
561
561
|
* request. It has no principal fields and no `Under` nodes, so you can give it
|
|
562
|
-
* to `Condition.fold`. It is
|
|
563
|
-
*
|
|
562
|
+
* to `Condition.fold`. It is made smaller, so it is often `True` or `False`
|
|
563
|
+
* when the answer does not depend on the value, but it does no search: a
|
|
564
|
+
* condition that is true for every value may stay a test. To know if the
|
|
565
|
+
* policy allows every value, or some value, use {@link coverage}.
|
|
564
566
|
*
|
|
565
567
|
* With a scope (`within`), the condition is the scope and the residual
|
|
566
568
|
* together, so it is false for every value outside the scope. Give the policy
|
package/dist/Policy.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Policy.d.ts","names":["PolicyNodes.Rules","PolicyNodes.All","PolicyNodes.Any","PolicyNodes.FirstOf","PolicyNodes.Ceiling","PolicyNodes.Node","Domain.Any","Internal.PolicyData","Domain.Kind","Domain.ActionOf","Domain.ValueOf","Domain.DataOf","Condition.FieldSelector","Domain.Principal","Condition.Builder","Condition.Reads","Condition.Condition","Decision.Decision","Domain.Resources","Resource.Kind","Domain.AnyAction","Domain.CommonAction","Domain.AnyValue","Condition.FieldName","Condition.Any","Domain.Meta","Condition.ReadsOf","Condition.OpaqueOf","Internal.PolicyError","Condition.ServicesOf","Condition.Provided","Condition.ErrorOf","Condition.Example","Condition.Encoded"],"sources":["../src/Policy.ts"],"mappings":";;;;;;;;;;;;;;;;;;;YAwDY;;;;;;;;YAUA,YAAYA;;;;;;YAOZ,UAAUC;;;;;;YAOV,UAAUC;;;;;;YAOV,cAAcC;;;;;;YAOd,cAAcC;;;;;;;;;YAUd,OAAOC;;;;;;;;;;YAWP,OAAO,UAAUC,OAAY,aAAaC,WAAoB,GAAG;;;;;;;;YASjE,MAAM;;;;;;;;YASN,SAAS,KAAK,UAAU,aAAa,UAAU;;;;;;;;YAS/C,SAAS,KAAK;WAAqB,uBAAuB;IACnE;;;;;;;;;YAWS,OAAO,QACjB,KAAKC,OAAY;WACR,QAAQC,SAAgB,GAAG;WAC3B,UAAUC,QAAe,GAAG;WAC5B,QAAQE,cAAwBD,OAAc,GAAG;;WAEjD;KAETH,OAAY;;;;;;;;YASF,gBAAgB,QAC1B,KAAKA,OAAY;WACR,QAAQC,SAAgB,GAAG;WAC3B,UAAUC,QAAe,GAAG;WAC5B;KAETF,OAAY;;;;;;;;;;YAWF,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W;;;;;;;;;;;qBAYQ,UAAU,UAAUX,OAAY,GAC5C,QAAQ,OAAO,GAAG,IAClB,SAAS,QAAQ,QAAQ,QACrB,OAAO,OAAO,aAAayB,QAAkB,IAAIF,WAAqB;;;;;;;;;;;;;;qBAgB9D,kBAAkB,UAAUvB,OAAY,GACpD,QAAQ,OAAO,GAAG,IAClB,SAAS,iBAAiB,QAAQ,QAC9B,OAAO,OACX,uBACAyB,QAAkB,IAClBF,WAAqB;;;;;;;;;;;YAeV,cAAc,GAAG,KAAKd,OAEhC,qBAAqB,OAAOL,QAAe,GAAG,wCACpC,aAAa,cACrB
|
|
1
|
+
{"version":3,"file":"Policy.d.ts","names":["PolicyNodes.Rules","PolicyNodes.All","PolicyNodes.Any","PolicyNodes.FirstOf","PolicyNodes.Ceiling","PolicyNodes.Node","Domain.Any","Internal.PolicyData","Domain.Kind","Domain.ActionOf","Domain.ValueOf","Domain.DataOf","Condition.FieldSelector","Domain.Principal","Condition.Builder","Condition.Reads","Condition.Condition","Decision.Decision","Domain.Resources","Resource.Kind","Domain.AnyAction","Domain.CommonAction","Domain.AnyValue","Condition.FieldName","Condition.Any","Domain.Meta","Condition.ReadsOf","Condition.OpaqueOf","Internal.PolicyError","Condition.ServicesOf","Condition.Provided","Condition.ErrorOf","Condition.Example","Condition.Encoded"],"sources":["../src/Policy.ts"],"mappings":";;;;;;;;;;;;;;;;;;;YAwDY;;;;;;;;YAUA,YAAYA;;;;;;YAOZ,UAAUC;;;;;;YAOV,UAAUC;;;;;;YAOV,cAAcC;;;;;;YAOd,cAAcC;;;;;;;;;YAUd,OAAOC;;;;;;;;;;YAWP,OAAO,UAAUC,OAAY,aAAaC,WAAoB,GAAG;;;;;;;;YASjE,MAAM;;;;;;;;YASN,SAAS,KAAK,UAAU,aAAa,UAAU;;;;;;;;YAS/C,SAAS,KAAK;WAAqB,uBAAuB;IACnE;;;;;;;;;YAWS,OAAO,QACjB,KAAKC,OAAY;WACR,QAAQC,SAAgB,GAAG;WAC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AO,cAAc;;WAGrB;WACA,UAAU,cAAc;;WAGxB;WACA,KAAK;WACL,QAAQ;;;;;;;;;;;;;;;;qBAiBP,SAAS,UAAU3B,OAC/B,QAAQ,MACJ,OAAO,MAAM,OAAO,IAAI"}
|
package/dist/Policy.js
CHANGED
|
@@ -171,8 +171,10 @@ const permittedFields = permittedFields$1;
|
|
|
171
171
|
/**
|
|
172
172
|
* Gives the condition on resource values for which the policy allows a
|
|
173
173
|
* request. It has no principal fields and no `Under` nodes, so you can give it
|
|
174
|
-
* to `Condition.fold`. It is
|
|
175
|
-
*
|
|
174
|
+
* to `Condition.fold`. It is made smaller, so it is often `True` or `False`
|
|
175
|
+
* when the answer does not depend on the value, but it does no search: a
|
|
176
|
+
* condition that is true for every value may stay a test. To know if the
|
|
177
|
+
* policy allows every value, or some value, use {@link coverage}.
|
|
176
178
|
*
|
|
177
179
|
* With a scope (`within`), the condition is the scope and the residual
|
|
178
180
|
* together, so it is false for every value outside the scope. Give the policy
|
package/dist/Policy.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Policy.js","names":["RuleData.builder","RuleData.makePlain","Internal.PolicyError","Internal.define","Internal.combine","Internal.ceiling","Internal.provideContext","Decide.decideAny","Decide.decideSync","Decide.explain","Decide.permittedFields","Analysis.residual","Analysis.coverageAny","Internal.schema"],"sources":["../src/Policy.ts"],"sourcesContent":["/**\n * A policy is a tree that gives a {@link Decision.Decision} for a request.\n *\n * The leaves of the tree are lists of rules. A combining algorithm decides\n * which rule gives the answer when more than one rule applies:\n * - `denyOverrides` (the default): a deny rule wins over every allow rule.\n * - `permitOverrides`: an allow rule wins over every deny rule.\n * - `firstApplicable`: the first rule that applies wins.\n * - `lastApplicable`: the last rule that applies wins.\n *\n * The branches put policies together:\n * - {@link all}: every policy must allow, and one deny is enough to deny. Use\n * it when a user token may never do more than its user.\n * - {@link any}: one allow is enough.\n * - {@link firstOf}: the first policy that gives an answer wins. Use it for\n * grants first, then rules.\n * - {@link ceiling}: the deny rules of a second policy are a limit for\n * everyone. Its allow rules do nothing.\n *\n * A policy gives three kinds of answers:\n * - {@link decide}: the decision for one resource value.\n * - {@link residual}: a condition on resource values. A value passes when the\n * policy allows the request for that value. Use it to make a database\n * query, or to ask \"may this principal do this act on some resource of\n * this kind?\"\n * - {@link permittedFields}: the fields that the policy lets a request use.\n *\n * Each of them takes the policy first and the request second, as in\n * `Policy.decide(policy, request)`. The policy gives the domain, so\n * TypeScript checks the request against it.\n *\n * A policy without predicates can become JSON with {@link schema}.\n *\n * @stability stable\n * @since 0.3.0\n */\nimport type * as Context from \"effect/Context\"\nimport type * as Data from \"effect/Data\"\nimport type * as Effect from \"effect/Effect\"\nimport type * as Pipeable from \"effect/Pipeable\"\nimport type * as Schema from \"effect/Schema\"\nimport type * as Condition from \"./Condition.ts\"\nimport * as Analysis from \"./internal/analysis.ts\"\nimport * as Decide from \"./internal/decide.ts\"\nimport * as Internal from \"./internal/policy.ts\"\nimport type * as PolicyNodes from \"./internal/policy-nodes.ts\"\nimport * as RuleData from \"./internal/rule.ts\"\nimport type * as Decision from \"./Decision.ts\"\nimport type * as Domain from \"./Domain.ts\"\nimport type * as Resource from \"./Resource.ts\"\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Algorithm =\n\t\"denyOverrides\" | \"permitOverrides\" | \"firstApplicable\" | \"lastApplicable\"\n\n/**\n * A list of rules with a combining algorithm.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type RulesNode = PolicyNodes.Rules\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type AllNode = PolicyNodes.All\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type AnyNode = PolicyNodes.Any\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type FirstOfNode = PolicyNodes.FirstOf\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type CeilingNode = PolicyNodes.Ceiling\n\n/**\n * The nodes of a policy tree, without types. Each node is a class, and only\n * the functions of this module and the Schema make one.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Node = PolicyNodes.Node\n\n/**\n * A policy for the domain `D`. `X` is `Condition.Opaque` when a rule of the\n * policy has a predicate, and `never` when the policy is plain data. A plain\n * policy can become JSON, and `decideSync` takes it.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Policy<D extends Domain.Any, X = never> = Internal.PolicyData<D, X>\n\n/**\n * Any policy.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Any = Policy<any, any>\n\n/**\n * The domain of a policy.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type DomainOf<P> = P extends Policy<infer D, any> ? D : never\n\n/**\n * The mark of a policy or a rule: `Condition.Opaque` when it has a predicate.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type OpaqueOf<P> = P extends { readonly \"~Opaque\": () => infer X }\n\t? X\n\t: never\n\n/**\n * One act on one resource value, for each kind of the domain. The action must\n * be an action of the kind, and the field must be a field of the kind.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Target<D> = {\n\t[K in Domain.Kind<D>]: {\n\t\treadonly action: Domain.ActionOf<D, K>\n\t\treadonly resource: Domain.ValueOf<D, K>\n\t\treadonly field?: Condition.FieldSelector<Domain.DataOf<D, K>>\n\t\t/** A target has a resource value or a kind, never both. */\n\t\treadonly kind?: never\n\t}\n}[Domain.Kind<D>]\n\n/**\n * A {@link Target} with no field. Each kind keeps its own actions.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type FieldlessTarget<D> = {\n\t[K in Domain.Kind<D>]: {\n\t\treadonly action: Domain.ActionOf<D, K>\n\t\treadonly resource: Domain.ValueOf<D, K>\n\t\treadonly kind?: never\n\t}\n}[Domain.Kind<D>]\n\n/**\n * A scope: a part of a kind, as a condition on its values. It gets a builder\n * with the types of the kind and of the principal, like the condition of a\n * rule. A scope is plain data, so it can not have a predicate.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport type Scope<D, K extends string> = (\n\tbuilder: Condition.Builder<\n\t\tDomain.DataOf<D, K>,\n\t\tDomain.ValueOf<D, K>,\n\t\tDomain.Principal<D>\n\t>,\n) => Condition.Condition<\n\tCondition.Reads<Domain.ValueOf<D, K>, Domain.Principal<D>>\n>\n\n/**\n * One act on one kind of resource, with no value. With `within`, the target is\n * only the values of the kind in the scope. Without it, the target is every\n * value of the kind.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type KindTarget<D> = {\n\t[K in Domain.Kind<D>]: {\n\t\treadonly action: Domain.ActionOf<D, K>\n\t\treadonly kind: K\n\t\treadonly field?: Condition.FieldSelector<Domain.DataOf<D, K>>\n\t\t/** The part of the kind. See {@link Scope}. */\n\t\treadonly within?: Scope<D, K>\n\t\t/** A target has a resource value or a kind, never both. */\n\t\treadonly resource?: never\n\t}\n}[Domain.Kind<D>]\n\n/**\n * A request: a principal, an action, and a resource value.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Request<D> = Target<D> & { readonly principal: Domain.Principal<D> }\n\n/**\n * A {@link Request} with no field.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type FieldlessRequest<D> = FieldlessTarget<D> & {\n\treadonly principal: Domain.Principal<D>\n}\n\n/**\n * A request about a kind of resource, with no value.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type KindRequest<D> = KindTarget<D> & {\n\treadonly principal: Domain.Principal<D>\n}\n\n/**\n * A request with no types.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface AnyRequest {\n\treadonly principal: object\n\treadonly action: string\n\treadonly resource: object\n\treadonly field?: string | undefined\n}\n\n/**\n * One rule that a decision tested. `path` gives the place of the rule in the\n * policy tree: the index of each child, then the index of the rule.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Step {\n\treadonly path: ReadonlyArray<number>\n\treadonly rule: AnyRule\n\treadonly applies: boolean\n}\n\n/**\n * A decision, and the rules that were tested to make it, in order. Keep it in\n * an audit log.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Explanation {\n\treadonly decision: Decision.Decision\n\treadonly steps: ReadonlyArray<Step>\n}\n\n// Rules\n\n/**\n * A rule for the domain `D`. `I` is what the tests of its condition read, and\n * `X` is its mark: see `Condition.Condition`. A predicate reads the values and\n * the principal of its domain, so a rule may go only into a policy of its own\n * domain. A rule from {@link rule} has the domain `any`.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Rule<D = any, I = unknown, X = never>\n\textends RuleShape<I, X>, Pipeable.Pipeable {\n\treadonly \"~Opaque\": () => X\n\treadonly \"~Domain\": (domain: D) => D\n\t[Symbol.iterator](): Generator<Rule<D, I, X>, Rule<D, I, X>, unknown>\n}\n\n/**\n * The data of a rule.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport interface RuleShape<I = unknown, X = never> {\n\treadonly _tag: \"Allow\" | \"Deny\"\n\treadonly actions: ReadonlyArray<string>\n\treadonly resources: ReadonlyArray<string>\n\treadonly when?: Condition.Condition<I, X>\n\treadonly fields?: ReadonlyArray<string>\n\treadonly reason?: string\n\treadonly id?: string\n\treadonly meta?: unknown\n\t/**\n\t * The domain of the builder that made the rule. Two domains may have the\n\t * same types but other paths, so the types can not tell them apart. It is\n\t * not in the JSON form of a rule.\n\t */\n\treadonly domain?: Domain.Any\n}\n\n/**\n * Any rule.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\n// Every rule fits `never` as what it reads, and a condition taken from such a\n// rule fits no rule that reads a value or a principal.\nexport type AnyRule = Rule<any, never, any>\n\n/**\n * A resource in a rule: a kind name, a resource of the domain, or `\"*\"`.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type RuleTarget<D> = Domain.Kind<D> | Domain.Resources<D> | \"*\"\n\n/**\n * The kind name of a target.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type KindOf<T> = T extends string ? T : Resource.Kind<T>\n\n/**\n * The actions that a rule may use for the kinds `K`.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type ActionFor<D, K> =\n\t| \"*\"\n\t| (\"*\" extends K\n\t\t\t? Domain.AnyAction<D>\n\t\t\t: Domain.ActionOf<D, Extract<K, string>>)\n\n/**\n * The targets in the resource argument of a rule: the one target, or the\n * targets of a list.\n *\n * @stability stable\n * @category utility types\n * @since 1.0.0\n */\nexport type TargetOf<Res> = Res extends ReadonlyArray<infer X> ? X : Res\n\n/**\n * The actions that a rule may use for its resource argument. A list of\n * resources may use an action of any of them. One target with a union type\n * may use only an action of every kind in the union, because its value may be\n * any one of them. When the argument may be a list or one target, the rule\n * may use only an action that each of these shapes allows.\n *\n * @stability stable\n * @category utility types\n * @since 1.0.0\n */\nexport type ActionForTargets<D, Res> = (\n\tRes extends ReadonlyArray<infer X>\n\t\t? (action: ActionFor<D, KindOf<X>>) => void\n\t\t: (action: ActionForTarget<D, Res>) => void\n) extends (action: infer A) => void\n\t? A\n\t: never\n\n/** The actions for one target that is not a list. */\ntype ActionForTarget<D, Res> =\n\t| \"*\"\n\t| (\"*\" extends KindOf<Res>\n\t\t\t? Domain.AnyAction<D>\n\t\t\t: Domain.CommonAction<D, Extract<KindOf<Res>, string>>)\n\n/**\n * The data type of the kinds `K`. For `\"*\"` it has no fields.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type DataFor<D, K> = \"*\" extends K\n\t? {}\n\t: Domain.DataOf<D, Extract<K, string>>\n\n/**\n * The value type of the kinds `K`.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type ValueFor<D, K> = \"*\" extends K\n\t? Domain.AnyValue<D>\n\t: Domain.ValueOf<D, Extract<K, string>>\n\n/**\n * A field name or a field pattern of the kinds `K`.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type FieldFor<D, K> =\n\tCondition.FieldName<DataFor<D, K>> | `${string}*${string}`\n\n/**\n * A condition that a rule for the kinds `K` may have. Its predicates may read\n * only the values of these kinds and the principal of the domain.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport type ConditionFor<D, K> = Condition.Condition<\n\tCondition.Reads<ValueFor<D, K>, Domain.Principal<D>>,\n\tany\n>\n\n/**\n * The options of a rule.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface RuleOptions<D, K, C extends Condition.Any> {\n\t/** The condition. It gets a builder with the types of the resource. */\n\treadonly when?: (\n\t\tbuilder: Condition.Builder<\n\t\t\tDataFor<D, K>,\n\t\t\tValueFor<D, K>,\n\t\t\tDomain.Principal<D>\n\t\t>,\n\t) => C\n\treadonly fields?: ReadonlyArray<FieldFor<D, K>>\n\treadonly reason?: string\n\treadonly id?: string\n\treadonly meta?: Domain.Meta<D>\n}\n\ntype SingleOrArray<A> = A | ReadonlyArray<A>\n\n/**\n * Makes rules with the types of a domain.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Builder<D> {\n\treadonly allow: <\n\t\tconst Res extends SingleOrArray<RuleTarget<D>>,\n\t\tconst A extends ActionForTargets<D, Res>,\n\t\tconst C extends ConditionFor<D, KindOf<TargetOf<Res>>> =\n\t\t\tCondition.Condition,\n\t>(\n\t\taction: SingleOrArray<A>,\n\t\tresource: Res,\n\t\toptions?: RuleOptions<D, KindOf<TargetOf<Res>>, C>,\n\t) => Rule<D, Condition.ReadsOf<C>, Condition.OpaqueOf<C>>\n\treadonly deny: <\n\t\tconst Res extends SingleOrArray<RuleTarget<D>>,\n\t\tconst A extends ActionForTargets<D, Res>,\n\t\tconst C extends ConditionFor<D, KindOf<TargetOf<Res>>> =\n\t\t\tCondition.Condition,\n\t>(\n\t\taction: SingleOrArray<A>,\n\t\tresource: Res,\n\t\toptions?: RuleOptions<D, KindOf<TargetOf<Res>>, C>,\n\t) => Rule<D, Condition.ReadsOf<C>, Condition.OpaqueOf<C>>\n}\n\n/**\n * Makes rules with the types of a domain. `Policy.define` gives one to its\n * generator. Use this one to make rules outside of a generator.\n *\n * @example\n * ```ts\n * const _ = Policy.builder(App)\n * const rule = _.allow(\"read\", Document, {\n * when: ($) => $.eq(\"ownerId\", $.principal(\"id\")),\n * })\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const builder = <D extends Domain.Any>(domain: D): Builder<D> =>\n\tRuleData.builder(domain) as never\n\n/**\n * Makes a rule from its data, with no types. It does not check the data\n * against a domain: a policy does that when the rule goes into it. Use\n * {@link builder} for rules with types, or {@link schema} for rules from JSON.\n *\n * The condition may not have a predicate. A policy checks the fields of a\n * condition against the resources of its rule, but it can not check what\n * the code of a predicate reads. A rule from the builder keeps that in its\n * types; this one could give a predicate of one kind to another kind.\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const rule: <I = unknown>(\n\tdata: RuleShape<I, never>,\n\t// The types come from the data only, not from where the rule goes.\n) => Rule<any, NoInfer<I>> = RuleData.makePlain as never\n\n/**\n * The options of a list of rules.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Options {\n\t/** The default is `denyOverrides`. */\n\treadonly algorithm?: Algorithm\n}\n\n/**\n * The error when a rule does not fit its domain: it names a kind, an action,\n * a field or a field of the principal that the domain does not have, or it\n * tests a field with a value that the field can not hold. It has one issue\n * for each problem, with its path, and a suggestion when a name has a mistake.\n *\n * @stability stable\n * @category errors\n * @since 2.0.0\n */\nexport const PolicyError: typeof Internal.PolicyError = Internal.PolicyError\n\n/**\n * @stability stable\n * @category errors\n * @since 2.0.0\n */\nexport type PolicyError = Internal.PolicyError\n\n/** The mark of a union of rules: `Condition.Opaque` when one has a predicate. */\ntype RulesOpaque<Rules> = Rules extends { readonly \"~Opaque\": () => infer X }\n\t? X\n\t: never\n\n/**\n * Makes a policy from a generator function that gives rules. It is pure and it\n * gives its result at once.\n *\n * @example\n * ```ts\n * const policy = Policy.define(App)(function* (_) {\n * yield* _.allow(\"read\", Document)\n * yield* _.allow([\"update\", \"delete\"], Document, {\n * when: ($) => $.eq(\"ownerId\", $.principal(\"id\")),\n * })\n * })\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 0.3.0\n */\nexport const define: <D extends Domain.Any>(\n\tdomain: D,\n\toptions?: Options,\n) => <Rules extends Rule<D, never, any>, A>(\n\tbody: (builder: Builder<D>) => Generator<Rules, A, unknown>,\n) => Policy<D, RulesOpaque<Rules>> = Internal.define as never\n\ntype Combined<D extends Domain.Any, Ps extends ReadonlyArray<Any>> = Policy<\n\tD,\n\tOpaqueOf<Ps[number]>\n>\n\n/**\n * Every policy must allow, and one deny is enough to deny. With some policies\n * not applicable and none that deny, the result is not applicable.\n *\n * @stability stable\n * @category combinators\n * @since 0.3.0\n */\nexport const all: <const Ps extends readonly [Any, ...Array<Any>]>(\n\tpolicies: Ps,\n) => Combined<DomainOf<Ps[0]>, Ps> = Internal.combine(\"All\")\n\n/**\n * One allow is enough. Without an allow, one deny gives a deny.\n *\n * @stability stable\n * @category combinators\n * @since 0.3.0\n */\nexport const any: <const Ps extends readonly [Any, ...Array<Any>]>(\n\tpolicies: Ps,\n) => Combined<DomainOf<Ps[0]>, Ps> = Internal.combine(\"Any\")\n\n/**\n * The first policy that allows or denies gives the answer.\n *\n * @stability stable\n * @category combinators\n * @since 0.3.0\n */\nexport const firstOf: <const Ps extends readonly [Any, ...Array<Any>]>(\n\tpolicies: Ps,\n) => Combined<DomainOf<Ps[0]>, Ps> = Internal.combine(\"FirstOf\")\n\n/**\n * Puts a limit on a policy. A deny from `cap` always wins. An allow from `cap`\n * does nothing.\n *\n * @stability stable\n * @category combinators\n * @since 0.3.0\n */\nexport const ceiling: {\n\t<D extends Domain.Any, X2>(\n\t\tcap: Policy<D, X2>,\n\t): <X>(policy: Policy<D, X>) => Policy<D, X | X2>\n\t<D extends Domain.Any, X, X2>(\n\t\tpolicy: Policy<D, X>,\n\t\tcap: Policy<D, X2>,\n\t): Policy<D, X | X2>\n} = Internal.ceiling as never\n\n/**\n * Gives the services in `context` to every predicate of a policy, so the\n * policy needs no services when it runs.\n *\n * @stability stable\n * @category services\n * @since 1.0.0\n */\nexport const provideContext: {\n\t<R>(\n\t\tcontext: Context.Context<R>,\n\t): <D extends Domain.Any, X>(\n\t\tpolicy: Policy<D, X> &\n\t\t\t([Condition.ServicesOf<X>] extends [R] ? unknown : never),\n\t) => Policy<D, Condition.Provided<X>>\n\t<D extends Domain.Any, X>(\n\t\tpolicy: Policy<D, X>,\n\t\tcontext: Context.Context<Condition.ServicesOf<X>>,\n\t): Policy<D, Condition.Provided<X>>\n} = Internal.provideContext as never\n\n// Decisions\n\n/**\n * Gives the decision of a policy for a request.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const decide: <D extends Domain.Any, X>(\n\tpolicy: Policy<D, X>,\n\trequest: Request<NoInfer<D>>,\n) => Effect.Effect<\n\tDecision.Decision,\n\tCondition.ErrorOf<X>,\n\tCondition.ServicesOf<X>\n> = Decide.decideAny as never\n\n/**\n * Gives the decision of a policy with no predicates, at once.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const decideSync: <D extends Domain.Any>(\n\tpolicy: Policy<D>,\n\trequest: Request<NoInfer<D>>,\n) => Decision.Decision = Decide.decideSync\n\n/**\n * Gives the decision of a policy and the rules that were tested to make it.\n *\n * One node may be a child of many nodes. Its rules are tested, and are in the\n * steps, each time that the decision comes to it.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const explain: <D extends Domain.Any, X>(\n\tpolicy: Policy<D, X>,\n\trequest: Request<NoInfer<D>>,\n) => Effect.Effect<Explanation, Condition.ErrorOf<X>, Condition.ServicesOf<X>> =\n\tDecide.explain as never\n\n/**\n * Gives the fields of a resource value that the policy lets a request use. It\n * tests each field that a list of fields shows: each scalar, record or array\n * of the resource Schema, with dots for nested fields.\n *\n * A field that holds more than one value, such as a record, is left out when a\n * deny rule names a part of it. The list can not name that part, and the whole\n * field would show it.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const permittedFields: <D extends Domain.Any, X>(\n\tpolicy: Policy<D, X>,\n\trequest: FieldlessRequest<NoInfer<D>>,\n) => Effect.Effect<\n\tReadonlyArray<string>,\n\tCondition.ErrorOf<X>,\n\tCondition.ServicesOf<X>\n> = Decide.permittedFields as never\n\n// Residual conditions\n\n/**\n * What a residual condition reads: a value of the kind `K`. The principal is\n * already in it. A residual is for one kind, so when `K` is a union of kinds,\n * the value must be a value of each of them. No value is, so such a residual\n * can not be evaluated on a value of the wrong kind.\n *\n * @stability stable\n * @category utility types\n * @since 1.0.0\n */\nexport type ResidualReads<D, K> = Condition.Reads<\n\t(\n\t\tK extends unknown ? (value: Domain.ValueOf<D, K & string>) => void : never\n\t) extends (value: infer V) => void\n\t\t? V\n\t\t: never,\n\tunknown\n>\n\n/**\n * Gives the condition on resource values for which the policy allows a\n * request. It has no principal fields and no `Under` nodes, so you can give it\n * to `Condition.fold`. It is `True` when the policy allows every value of the\n * kind, and `False` when it allows none.\n *\n * With a scope (`within`), the condition is the scope and the residual\n * together, so it is false for every value outside the scope. Give the policy\n * first to use a scope. The condition comes from its parts, with no search. To\n * know if it allows all of the scope or none of it, use {@link coverage}.\n *\n * When a rule that the request may use has a predicate, the condition is one\n * predicate with the name `\"policy\"`. It runs the whole policy for each value,\n * so its answers and its failures are the same as those of {@link decide}. It\n * takes the principal with it. Give it resource values with their `_tag`. It\n * is false for a value of another kind.\n *\n * A policy tree may use the condition of a child two times, so a small policy\n * may give a very large condition. When the condition would have more than\n * 10000 nodes, this function throws an error. In an `Authorizer`, the error\n * is a defect, so the check fails.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const residual: <\n\tD extends Domain.Any,\n\tX,\n\tconst Req extends KindRequest<NoInfer<D>>,\n>(\n\tpolicy: Policy<D, X>,\n\trequest: Req,\n) => Condition.Condition<ResidualReads<D, Req[\"kind\"]>, X> =\n\tAnalysis.residual as never\n\n/**\n * How much of a scope a policy allows. In each case, `condition` is the exact\n * condition on the values in the scope that the policy allows: give it to\n * `Condition.fold` for a list query.\n * - `All`: the policy allows every value in the scope. `condition` is the\n * scope (`True` with no scope).\n * - `None`: the policy allows no value in the scope. `condition` is `False`.\n * An empty scope is `None` too, so a check on a scope that has a mistake,\n * such as a principal field with no value, never passes.\n * - `Some`: the policy allows some values in the scope and not others.\n * `allowed` is an example of a value that it allows, and `refused` of a\n * value in the scope that it does not allow.\n * - `Unknown`: the answer needs a predicate, or the search went past its\n * budget.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport type Coverage<I = unknown, X = never> = Data.TaggedEnum<{\n\tAll: { readonly condition: Condition.Condition<I, X> }\n\tNone: { readonly condition: Condition.Condition<I, X> }\n\tSome: {\n\t\treadonly condition: Condition.Condition<I, X>\n\t\treadonly allowed: Condition.Example\n\t\treadonly refused: Condition.Example\n\t}\n\tUnknown: {\n\t\treadonly condition: Condition.Condition<I, X>\n\t\treadonly reason: \"predicate\" | \"budget\"\n\t}\n}>\n\n/**\n * Tells how much of a scope the policy allows: all of it, none of it, or some\n * of it. See {@link Coverage}. With no scope (`within`), the scope is every\n * value of the kind.\n *\n * The answer comes from {@link Condition.satisfiable} with the shape of the\n * Schema of the resource. `All` and `None` hold for every value of the\n * Schema. `Some` means that, by the shape of the Schema, a value may get\n * either answer: a check such as a minimum length may still stop one of the\n * examples. `Unknown` comes only from a predicate or from the budget of the\n * search.\n *\n * `Some` does not mean that such a value is in your database. To know that,\n * run `condition` as a query.\n *\n * @stability stable\n * @category evaluation\n * @since 1.0.0\n */\nexport const coverage: <\n\tD extends Domain.Any,\n\tX,\n\tconst Req extends KindRequest<NoInfer<D>>,\n>(\n\tpolicy: Policy<D, X>,\n\trequest: Req,\n) => Coverage<ResidualReads<D, Req[\"kind\"]>, X> = Analysis.coverageAny as never\n\n// Schema\n\n/**\n * The JSON form of a rule.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface EncodedRule {\n\treadonly _tag: \"Allow\" | \"Deny\"\n\treadonly actions: ReadonlyArray<string>\n\treadonly resources: ReadonlyArray<string>\n\treadonly when?: Condition.Encoded\n\treadonly fields?: ReadonlyArray<string>\n\treadonly reason?: string\n\treadonly id?: string\n\treadonly meta?: unknown\n}\n\n/**\n * The JSON form of a policy.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type EncodedNode =\n\t| {\n\t\t\treadonly _tag: \"Rules\"\n\t\t\treadonly algorithm: Algorithm\n\t\t\treadonly rules: ReadonlyArray<EncodedRule>\n\t }\n\t| {\n\t\t\treadonly _tag: \"All\" | \"Any\" | \"FirstOf\"\n\t\t\treadonly policies: ReadonlyArray<EncodedNode>\n\t }\n\t| {\n\t\t\treadonly _tag: \"Ceiling\"\n\t\t\treadonly cap: EncodedNode\n\t\t\treadonly policy: EncodedNode\n\t }\n\n/**\n * The Schema of the policies of a domain with no predicates. Decoding checks\n * every kind, action, field and principal field against the domain, and the\n * `meta` of each rule against the `meta` Schema of the domain.\n *\n * The decoder takes at most 256 levels of policies and 500 levels of\n * conditions, and at most 1000000 objects and array items, with a shared\n * object counted for each place. It reads only the own data fields of the\n * input.\n *\n * @stability stable\n * @category schemas\n * @since 0.3.0\n */\nexport const schema: <D extends Domain.Any>(\n\tdomain: D,\n) => Schema.Codec<Policy<D>, EncodedNode> = Internal.schema as never\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+gBA,MAAa,WAAiC,WAC7CA,UAAiB,MAAM;;;;;;;;;;;;;;;AAgBxB,MAAa,OAGgBC;;;;;;;;;;;AAwB7B,MAAa,cAA2CC;;;;;;;;;;;;;;;;;;;AAgCxD,MAAa,SAKwBC;;;;;;;;;AAerC,MAAa,MAEwBC,QAAiB,KAAK;;;;;;;;AAS3D,MAAa,MAEwBA,QAAiB,KAAK;;;;;;;;AAS3D,MAAa,UAEwBA,QAAiB,SAAS;;;;;;;;;AAU/D,MAAa,UAQTC;;;;;;;;;AAUJ,MAAa,iBAWTC;;;;;;;;AAWJ,MAAa,SAOTC;;;;;;;;AASJ,MAAa,aAGYC;;;;;;;;;;;AAYzB,MAAa,UAIZC;;;;;;;;;;;;;;AAeD,MAAa,kBAOTC;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDJ,MAAa,WAQZC;;;;;;;;;;;;;;;;;;;;AAsDD,MAAa,WAOqCC;;;;;;;;;;;;;;;AA2DlD,MAAa,SAE+BC"}
|
|
1
|
+
{"version":3,"file":"Policy.js","names":["RuleData.builder","RuleData.makePlain","Internal.PolicyError","Internal.define","Internal.combine","Internal.ceiling","Internal.provideContext","Decide.decideAny","Decide.decideSync","Decide.explain","Decide.permittedFields","Analysis.residual","Analysis.coverageAny","Internal.schema"],"sources":["../src/Policy.ts"],"sourcesContent":["/**\n * A policy is a tree that gives a {@link Decision.Decision} for a request.\n *\n * The leaves of the tree are lists of rules. A combining algorithm decides\n * which rule gives the answer when more than one rule applies:\n * - `denyOverrides` (the default): a deny rule wins over every allow rule.\n * - `permitOverrides`: an allow rule wins over every deny rule.\n * - `firstApplicable`: the first rule that applies wins.\n * - `lastApplicable`: the last rule that applies wins.\n *\n * The branches put policies together:\n * - {@link all}: every policy must allow, and one deny is enough to deny. Use\n * it when a user token may never do more than its user.\n * - {@link any}: one allow is enough.\n * - {@link firstOf}: the first policy that gives an answer wins. Use it for\n * grants first, then rules.\n * - {@link ceiling}: the deny rules of a second policy are a limit for\n * everyone. Its allow rules do nothing.\n *\n * A policy gives three kinds of answers:\n * - {@link decide}: the decision for one resource value.\n * - {@link residual}: a condition on resource values. A value passes when the\n * policy allows the request for that value. Use it to make a database\n * query, or to ask \"may this principal do this act on some resource of\n * this kind?\"\n * - {@link permittedFields}: the fields that the policy lets a request use.\n *\n * Each of them takes the policy first and the request second, as in\n * `Policy.decide(policy, request)`. The policy gives the domain, so\n * TypeScript checks the request against it.\n *\n * A policy without predicates can become JSON with {@link schema}.\n *\n * @stability stable\n * @since 0.3.0\n */\nimport type * as Context from \"effect/Context\"\nimport type * as Data from \"effect/Data\"\nimport type * as Effect from \"effect/Effect\"\nimport type * as Pipeable from \"effect/Pipeable\"\nimport type * as Schema from \"effect/Schema\"\nimport type * as Condition from \"./Condition.ts\"\nimport * as Analysis from \"./internal/analysis.ts\"\nimport * as Decide from \"./internal/decide.ts\"\nimport * as Internal from \"./internal/policy.ts\"\nimport type * as PolicyNodes from \"./internal/policy-nodes.ts\"\nimport * as RuleData from \"./internal/rule.ts\"\nimport type * as Decision from \"./Decision.ts\"\nimport type * as Domain from \"./Domain.ts\"\nimport type * as Resource from \"./Resource.ts\"\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Algorithm =\n\t\"denyOverrides\" | \"permitOverrides\" | \"firstApplicable\" | \"lastApplicable\"\n\n/**\n * A list of rules with a combining algorithm.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type RulesNode = PolicyNodes.Rules\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type AllNode = PolicyNodes.All\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type AnyNode = PolicyNodes.Any\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type FirstOfNode = PolicyNodes.FirstOf\n\n/**\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type CeilingNode = PolicyNodes.Ceiling\n\n/**\n * The nodes of a policy tree, without types. Each node is a class, and only\n * the functions of this module and the Schema make one.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Node = PolicyNodes.Node\n\n/**\n * A policy for the domain `D`. `X` is `Condition.Opaque` when a rule of the\n * policy has a predicate, and `never` when the policy is plain data. A plain\n * policy can become JSON, and `decideSync` takes it.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Policy<D extends Domain.Any, X = never> = Internal.PolicyData<D, X>\n\n/**\n * Any policy.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Any = Policy<any, any>\n\n/**\n * The domain of a policy.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type DomainOf<P> = P extends Policy<infer D, any> ? D : never\n\n/**\n * The mark of a policy or a rule: `Condition.Opaque` when it has a predicate.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type OpaqueOf<P> = P extends { readonly \"~Opaque\": () => infer X }\n\t? X\n\t: never\n\n/**\n * One act on one resource value, for each kind of the domain. The action must\n * be an action of the kind, and the field must be a field of the kind.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Target<D> = {\n\t[K in Domain.Kind<D>]: {\n\t\treadonly action: Domain.ActionOf<D, K>\n\t\treadonly resource: Domain.ValueOf<D, K>\n\t\treadonly field?: Condition.FieldSelector<Domain.DataOf<D, K>>\n\t\t/** A target has a resource value or a kind, never both. */\n\t\treadonly kind?: never\n\t}\n}[Domain.Kind<D>]\n\n/**\n * A {@link Target} with no field. Each kind keeps its own actions.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type FieldlessTarget<D> = {\n\t[K in Domain.Kind<D>]: {\n\t\treadonly action: Domain.ActionOf<D, K>\n\t\treadonly resource: Domain.ValueOf<D, K>\n\t\treadonly kind?: never\n\t}\n}[Domain.Kind<D>]\n\n/**\n * A scope: a part of a kind, as a condition on its values. It gets a builder\n * with the types of the kind and of the principal, like the condition of a\n * rule. A scope is plain data, so it can not have a predicate.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport type Scope<D, K extends string> = (\n\tbuilder: Condition.Builder<\n\t\tDomain.DataOf<D, K>,\n\t\tDomain.ValueOf<D, K>,\n\t\tDomain.Principal<D>\n\t>,\n) => Condition.Condition<\n\tCondition.Reads<Domain.ValueOf<D, K>, Domain.Principal<D>>\n>\n\n/**\n * One act on one kind of resource, with no value. With `within`, the target is\n * only the values of the kind in the scope. Without it, the target is every\n * value of the kind.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type KindTarget<D> = {\n\t[K in Domain.Kind<D>]: {\n\t\treadonly action: Domain.ActionOf<D, K>\n\t\treadonly kind: K\n\t\treadonly field?: Condition.FieldSelector<Domain.DataOf<D, K>>\n\t\t/** The part of the kind. See {@link Scope}. */\n\t\treadonly within?: Scope<D, K>\n\t\t/** A target has a resource value or a kind, never both. */\n\t\treadonly resource?: never\n\t}\n}[Domain.Kind<D>]\n\n/**\n * A request: a principal, an action, and a resource value.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type Request<D> = Target<D> & { readonly principal: Domain.Principal<D> }\n\n/**\n * A {@link Request} with no field.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type FieldlessRequest<D> = FieldlessTarget<D> & {\n\treadonly principal: Domain.Principal<D>\n}\n\n/**\n * A request about a kind of resource, with no value.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type KindRequest<D> = KindTarget<D> & {\n\treadonly principal: Domain.Principal<D>\n}\n\n/**\n * A request with no types.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface AnyRequest {\n\treadonly principal: object\n\treadonly action: string\n\treadonly resource: object\n\treadonly field?: string | undefined\n}\n\n/**\n * One rule that a decision tested. `path` gives the place of the rule in the\n * policy tree: the index of each child, then the index of the rule.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Step {\n\treadonly path: ReadonlyArray<number>\n\treadonly rule: AnyRule\n\treadonly applies: boolean\n}\n\n/**\n * A decision, and the rules that were tested to make it, in order. Keep it in\n * an audit log.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Explanation {\n\treadonly decision: Decision.Decision\n\treadonly steps: ReadonlyArray<Step>\n}\n\n// Rules\n\n/**\n * A rule for the domain `D`. `I` is what the tests of its condition read, and\n * `X` is its mark: see `Condition.Condition`. A predicate reads the values and\n * the principal of its domain, so a rule may go only into a policy of its own\n * domain. A rule from {@link rule} has the domain `any`.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Rule<D = any, I = unknown, X = never>\n\textends RuleShape<I, X>, Pipeable.Pipeable {\n\treadonly \"~Opaque\": () => X\n\treadonly \"~Domain\": (domain: D) => D\n\t[Symbol.iterator](): Generator<Rule<D, I, X>, Rule<D, I, X>, unknown>\n}\n\n/**\n * The data of a rule.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport interface RuleShape<I = unknown, X = never> {\n\treadonly _tag: \"Allow\" | \"Deny\"\n\treadonly actions: ReadonlyArray<string>\n\treadonly resources: ReadonlyArray<string>\n\treadonly when?: Condition.Condition<I, X>\n\treadonly fields?: ReadonlyArray<string>\n\treadonly reason?: string\n\treadonly id?: string\n\treadonly meta?: unknown\n\t/**\n\t * The domain of the builder that made the rule. Two domains may have the\n\t * same types but other paths, so the types can not tell them apart. It is\n\t * not in the JSON form of a rule.\n\t */\n\treadonly domain?: Domain.Any\n}\n\n/**\n * Any rule.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\n// Every rule fits `never` as what it reads, and a condition taken from such a\n// rule fits no rule that reads a value or a principal.\nexport type AnyRule = Rule<any, never, any>\n\n/**\n * A resource in a rule: a kind name, a resource of the domain, or `\"*\"`.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type RuleTarget<D> = Domain.Kind<D> | Domain.Resources<D> | \"*\"\n\n/**\n * The kind name of a target.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type KindOf<T> = T extends string ? T : Resource.Kind<T>\n\n/**\n * The actions that a rule may use for the kinds `K`.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type ActionFor<D, K> =\n\t| \"*\"\n\t| (\"*\" extends K\n\t\t\t? Domain.AnyAction<D>\n\t\t\t: Domain.ActionOf<D, Extract<K, string>>)\n\n/**\n * The targets in the resource argument of a rule: the one target, or the\n * targets of a list.\n *\n * @stability stable\n * @category utility types\n * @since 1.0.0\n */\nexport type TargetOf<Res> = Res extends ReadonlyArray<infer X> ? X : Res\n\n/**\n * The actions that a rule may use for its resource argument. A list of\n * resources may use an action of any of them. One target with a union type\n * may use only an action of every kind in the union, because its value may be\n * any one of them. When the argument may be a list or one target, the rule\n * may use only an action that each of these shapes allows.\n *\n * @stability stable\n * @category utility types\n * @since 1.0.0\n */\nexport type ActionForTargets<D, Res> = (\n\tRes extends ReadonlyArray<infer X>\n\t\t? (action: ActionFor<D, KindOf<X>>) => void\n\t\t: (action: ActionForTarget<D, Res>) => void\n) extends (action: infer A) => void\n\t? A\n\t: never\n\n/** The actions for one target that is not a list. */\ntype ActionForTarget<D, Res> =\n\t| \"*\"\n\t| (\"*\" extends KindOf<Res>\n\t\t\t? Domain.AnyAction<D>\n\t\t\t: Domain.CommonAction<D, Extract<KindOf<Res>, string>>)\n\n/**\n * The data type of the kinds `K`. For `\"*\"` it has no fields.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type DataFor<D, K> = \"*\" extends K\n\t? {}\n\t: Domain.DataOf<D, Extract<K, string>>\n\n/**\n * The value type of the kinds `K`.\n *\n * @stability stable\n * @category utility types\n * @since 0.3.0\n */\nexport type ValueFor<D, K> = \"*\" extends K\n\t? Domain.AnyValue<D>\n\t: Domain.ValueOf<D, Extract<K, string>>\n\n/**\n * A field name or a field pattern of the kinds `K`.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type FieldFor<D, K> =\n\tCondition.FieldName<DataFor<D, K>> | `${string}*${string}`\n\n/**\n * A condition that a rule for the kinds `K` may have. Its predicates may read\n * only the values of these kinds and the principal of the domain.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport type ConditionFor<D, K> = Condition.Condition<\n\tCondition.Reads<ValueFor<D, K>, Domain.Principal<D>>,\n\tany\n>\n\n/**\n * The options of a rule.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface RuleOptions<D, K, C extends Condition.Any> {\n\t/** The condition. It gets a builder with the types of the resource. */\n\treadonly when?: (\n\t\tbuilder: Condition.Builder<\n\t\t\tDataFor<D, K>,\n\t\t\tValueFor<D, K>,\n\t\t\tDomain.Principal<D>\n\t\t>,\n\t) => C\n\treadonly fields?: ReadonlyArray<FieldFor<D, K>>\n\treadonly reason?: string\n\treadonly id?: string\n\treadonly meta?: Domain.Meta<D>\n}\n\ntype SingleOrArray<A> = A | ReadonlyArray<A>\n\n/**\n * Makes rules with the types of a domain.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Builder<D> {\n\treadonly allow: <\n\t\tconst Res extends SingleOrArray<RuleTarget<D>>,\n\t\tconst A extends ActionForTargets<D, Res>,\n\t\tconst C extends ConditionFor<D, KindOf<TargetOf<Res>>> =\n\t\t\tCondition.Condition,\n\t>(\n\t\taction: SingleOrArray<A>,\n\t\tresource: Res,\n\t\toptions?: RuleOptions<D, KindOf<TargetOf<Res>>, C>,\n\t) => Rule<D, Condition.ReadsOf<C>, Condition.OpaqueOf<C>>\n\treadonly deny: <\n\t\tconst Res extends SingleOrArray<RuleTarget<D>>,\n\t\tconst A extends ActionForTargets<D, Res>,\n\t\tconst C extends ConditionFor<D, KindOf<TargetOf<Res>>> =\n\t\t\tCondition.Condition,\n\t>(\n\t\taction: SingleOrArray<A>,\n\t\tresource: Res,\n\t\toptions?: RuleOptions<D, KindOf<TargetOf<Res>>, C>,\n\t) => Rule<D, Condition.ReadsOf<C>, Condition.OpaqueOf<C>>\n}\n\n/**\n * Makes rules with the types of a domain. `Policy.define` gives one to its\n * generator. Use this one to make rules outside of a generator.\n *\n * @example\n * ```ts\n * const _ = Policy.builder(App)\n * const rule = _.allow(\"read\", Document, {\n * when: ($) => $.eq(\"ownerId\", $.principal(\"id\")),\n * })\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const builder = <D extends Domain.Any>(domain: D): Builder<D> =>\n\tRuleData.builder(domain) as never\n\n/**\n * Makes a rule from its data, with no types. It does not check the data\n * against a domain: a policy does that when the rule goes into it. Use\n * {@link builder} for rules with types, or {@link schema} for rules from JSON.\n *\n * The condition may not have a predicate. A policy checks the fields of a\n * condition against the resources of its rule, but it can not check what\n * the code of a predicate reads. A rule from the builder keeps that in its\n * types; this one could give a predicate of one kind to another kind.\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const rule: <I = unknown>(\n\tdata: RuleShape<I, never>,\n\t// The types come from the data only, not from where the rule goes.\n) => Rule<any, NoInfer<I>> = RuleData.makePlain as never\n\n/**\n * The options of a list of rules.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface Options {\n\t/** The default is `denyOverrides`. */\n\treadonly algorithm?: Algorithm\n}\n\n/**\n * The error when a rule does not fit its domain: it names a kind, an action,\n * a field or a field of the principal that the domain does not have, or it\n * tests a field with a value that the field can not hold. It has one issue\n * for each problem, with its path, and a suggestion when a name has a mistake.\n *\n * @stability stable\n * @category errors\n * @since 2.0.0\n */\nexport const PolicyError: typeof Internal.PolicyError = Internal.PolicyError\n\n/**\n * @stability stable\n * @category errors\n * @since 2.0.0\n */\nexport type PolicyError = Internal.PolicyError\n\n/** The mark of a union of rules: `Condition.Opaque` when one has a predicate. */\ntype RulesOpaque<Rules> = Rules extends { readonly \"~Opaque\": () => infer X }\n\t? X\n\t: never\n\n/**\n * Makes a policy from a generator function that gives rules. It is pure and it\n * gives its result at once.\n *\n * @example\n * ```ts\n * const policy = Policy.define(App)(function* (_) {\n * yield* _.allow(\"read\", Document)\n * yield* _.allow([\"update\", \"delete\"], Document, {\n * when: ($) => $.eq(\"ownerId\", $.principal(\"id\")),\n * })\n * })\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 0.3.0\n */\nexport const define: <D extends Domain.Any>(\n\tdomain: D,\n\toptions?: Options,\n) => <Rules extends Rule<D, never, any>, A>(\n\tbody: (builder: Builder<D>) => Generator<Rules, A, unknown>,\n) => Policy<D, RulesOpaque<Rules>> = Internal.define as never\n\ntype Combined<D extends Domain.Any, Ps extends ReadonlyArray<Any>> = Policy<\n\tD,\n\tOpaqueOf<Ps[number]>\n>\n\n/**\n * Every policy must allow, and one deny is enough to deny. With some policies\n * not applicable and none that deny, the result is not applicable.\n *\n * @stability stable\n * @category combinators\n * @since 0.3.0\n */\nexport const all: <const Ps extends readonly [Any, ...Array<Any>]>(\n\tpolicies: Ps,\n) => Combined<DomainOf<Ps[0]>, Ps> = Internal.combine(\"All\")\n\n/**\n * One allow is enough. Without an allow, one deny gives a deny.\n *\n * @stability stable\n * @category combinators\n * @since 0.3.0\n */\nexport const any: <const Ps extends readonly [Any, ...Array<Any>]>(\n\tpolicies: Ps,\n) => Combined<DomainOf<Ps[0]>, Ps> = Internal.combine(\"Any\")\n\n/**\n * The first policy that allows or denies gives the answer.\n *\n * @stability stable\n * @category combinators\n * @since 0.3.0\n */\nexport const firstOf: <const Ps extends readonly [Any, ...Array<Any>]>(\n\tpolicies: Ps,\n) => Combined<DomainOf<Ps[0]>, Ps> = Internal.combine(\"FirstOf\")\n\n/**\n * Puts a limit on a policy. A deny from `cap` always wins. An allow from `cap`\n * does nothing.\n *\n * @stability stable\n * @category combinators\n * @since 0.3.0\n */\nexport const ceiling: {\n\t<D extends Domain.Any, X2>(\n\t\tcap: Policy<D, X2>,\n\t): <X>(policy: Policy<D, X>) => Policy<D, X | X2>\n\t<D extends Domain.Any, X, X2>(\n\t\tpolicy: Policy<D, X>,\n\t\tcap: Policy<D, X2>,\n\t): Policy<D, X | X2>\n} = Internal.ceiling as never\n\n/**\n * Gives the services in `context` to every predicate of a policy, so the\n * policy needs no services when it runs.\n *\n * @stability stable\n * @category services\n * @since 1.0.0\n */\nexport const provideContext: {\n\t<R>(\n\t\tcontext: Context.Context<R>,\n\t): <D extends Domain.Any, X>(\n\t\tpolicy: Policy<D, X> &\n\t\t\t([Condition.ServicesOf<X>] extends [R] ? unknown : never),\n\t) => Policy<D, Condition.Provided<X>>\n\t<D extends Domain.Any, X>(\n\t\tpolicy: Policy<D, X>,\n\t\tcontext: Context.Context<Condition.ServicesOf<X>>,\n\t): Policy<D, Condition.Provided<X>>\n} = Internal.provideContext as never\n\n// Decisions\n\n/**\n * Gives the decision of a policy for a request.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const decide: <D extends Domain.Any, X>(\n\tpolicy: Policy<D, X>,\n\trequest: Request<NoInfer<D>>,\n) => Effect.Effect<\n\tDecision.Decision,\n\tCondition.ErrorOf<X>,\n\tCondition.ServicesOf<X>\n> = Decide.decideAny as never\n\n/**\n * Gives the decision of a policy with no predicates, at once.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const decideSync: <D extends Domain.Any>(\n\tpolicy: Policy<D>,\n\trequest: Request<NoInfer<D>>,\n) => Decision.Decision = Decide.decideSync\n\n/**\n * Gives the decision of a policy and the rules that were tested to make it.\n *\n * One node may be a child of many nodes. Its rules are tested, and are in the\n * steps, each time that the decision comes to it.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const explain: <D extends Domain.Any, X>(\n\tpolicy: Policy<D, X>,\n\trequest: Request<NoInfer<D>>,\n) => Effect.Effect<Explanation, Condition.ErrorOf<X>, Condition.ServicesOf<X>> =\n\tDecide.explain as never\n\n/**\n * Gives the fields of a resource value that the policy lets a request use. It\n * tests each field that a list of fields shows: each scalar, record or array\n * of the resource Schema, with dots for nested fields.\n *\n * A field that holds more than one value, such as a record, is left out when a\n * deny rule names a part of it. The list can not name that part, and the whole\n * field would show it.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const permittedFields: <D extends Domain.Any, X>(\n\tpolicy: Policy<D, X>,\n\trequest: FieldlessRequest<NoInfer<D>>,\n) => Effect.Effect<\n\tReadonlyArray<string>,\n\tCondition.ErrorOf<X>,\n\tCondition.ServicesOf<X>\n> = Decide.permittedFields as never\n\n// Residual conditions\n\n/**\n * What a residual condition reads: a value of the kind `K`. The principal is\n * already in it. A residual is for one kind, so when `K` is a union of kinds,\n * the value must be a value of each of them. No value is, so such a residual\n * can not be evaluated on a value of the wrong kind.\n *\n * @stability stable\n * @category utility types\n * @since 1.0.0\n */\nexport type ResidualReads<D, K> = Condition.Reads<\n\t(\n\t\tK extends unknown ? (value: Domain.ValueOf<D, K & string>) => void : never\n\t) extends (value: infer V) => void\n\t\t? V\n\t\t: never,\n\tunknown\n>\n\n/**\n * Gives the condition on resource values for which the policy allows a\n * request. It has no principal fields and no `Under` nodes, so you can give it\n * to `Condition.fold`. It is made smaller, so it is often `True` or `False`\n * when the answer does not depend on the value, but it does no search: a\n * condition that is true for every value may stay a test. To know if the\n * policy allows every value, or some value, use {@link coverage}.\n *\n * With a scope (`within`), the condition is the scope and the residual\n * together, so it is false for every value outside the scope. Give the policy\n * first to use a scope. The condition comes from its parts, with no search. To\n * know if it allows all of the scope or none of it, use {@link coverage}.\n *\n * When a rule that the request may use has a predicate, the condition is one\n * predicate with the name `\"policy\"`. It runs the whole policy for each value,\n * so its answers and its failures are the same as those of {@link decide}. It\n * takes the principal with it. Give it resource values with their `_tag`. It\n * is false for a value of another kind.\n *\n * A policy tree may use the condition of a child two times, so a small policy\n * may give a very large condition. When the condition would have more than\n * 10000 nodes, this function throws an error. In an `Authorizer`, the error\n * is a defect, so the check fails.\n *\n * @stability stable\n * @category evaluation\n * @since 0.3.0\n */\nexport const residual: <\n\tD extends Domain.Any,\n\tX,\n\tconst Req extends KindRequest<NoInfer<D>>,\n>(\n\tpolicy: Policy<D, X>,\n\trequest: Req,\n) => Condition.Condition<ResidualReads<D, Req[\"kind\"]>, X> =\n\tAnalysis.residual as never\n\n/**\n * How much of a scope a policy allows. In each case, `condition` is the exact\n * condition on the values in the scope that the policy allows: give it to\n * `Condition.fold` for a list query.\n * - `All`: the policy allows every value in the scope. `condition` is the\n * scope (`True` with no scope).\n * - `None`: the policy allows no value in the scope. `condition` is `False`.\n * An empty scope is `None` too, so a check on a scope that has a mistake,\n * such as a principal field with no value, never passes.\n * - `Some`: the policy allows some values in the scope and not others.\n * `allowed` is an example of a value that it allows, and `refused` of a\n * value in the scope that it does not allow.\n * - `Unknown`: the answer needs a predicate, or the search went past its\n * budget.\n *\n * @stability stable\n * @category models\n * @since 1.0.0\n */\nexport type Coverage<I = unknown, X = never> = Data.TaggedEnum<{\n\tAll: { readonly condition: Condition.Condition<I, X> }\n\tNone: { readonly condition: Condition.Condition<I, X> }\n\tSome: {\n\t\treadonly condition: Condition.Condition<I, X>\n\t\treadonly allowed: Condition.Example\n\t\treadonly refused: Condition.Example\n\t}\n\tUnknown: {\n\t\treadonly condition: Condition.Condition<I, X>\n\t\treadonly reason: \"predicate\" | \"budget\"\n\t}\n}>\n\n/**\n * Tells how much of a scope the policy allows: all of it, none of it, or some\n * of it. See {@link Coverage}. With no scope (`within`), the scope is every\n * value of the kind.\n *\n * The answer comes from {@link Condition.satisfiable} with the shape of the\n * Schema of the resource. `All` and `None` hold for every value of the\n * Schema. `Some` means that, by the shape of the Schema, a value may get\n * either answer: a check such as a minimum length may still stop one of the\n * examples. `Unknown` comes only from a predicate or from the budget of the\n * search.\n *\n * `Some` does not mean that such a value is in your database. To know that,\n * run `condition` as a query.\n *\n * @stability stable\n * @category evaluation\n * @since 1.0.0\n */\nexport const coverage: <\n\tD extends Domain.Any,\n\tX,\n\tconst Req extends KindRequest<NoInfer<D>>,\n>(\n\tpolicy: Policy<D, X>,\n\trequest: Req,\n) => Coverage<ResidualReads<D, Req[\"kind\"]>, X> = Analysis.coverageAny as never\n\n// Schema\n\n/**\n * The JSON form of a rule.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport interface EncodedRule {\n\treadonly _tag: \"Allow\" | \"Deny\"\n\treadonly actions: ReadonlyArray<string>\n\treadonly resources: ReadonlyArray<string>\n\treadonly when?: Condition.Encoded\n\treadonly fields?: ReadonlyArray<string>\n\treadonly reason?: string\n\treadonly id?: string\n\treadonly meta?: unknown\n}\n\n/**\n * The JSON form of a policy.\n *\n * @stability stable\n * @category models\n * @since 0.3.0\n */\nexport type EncodedNode =\n\t| {\n\t\t\treadonly _tag: \"Rules\"\n\t\t\treadonly algorithm: Algorithm\n\t\t\treadonly rules: ReadonlyArray<EncodedRule>\n\t }\n\t| {\n\t\t\treadonly _tag: \"All\" | \"Any\" | \"FirstOf\"\n\t\t\treadonly policies: ReadonlyArray<EncodedNode>\n\t }\n\t| {\n\t\t\treadonly _tag: \"Ceiling\"\n\t\t\treadonly cap: EncodedNode\n\t\t\treadonly policy: EncodedNode\n\t }\n\n/**\n * The Schema of the policies of a domain with no predicates. Decoding checks\n * every kind, action, field and principal field against the domain, and the\n * `meta` of each rule against the `meta` Schema of the domain.\n *\n * The decoder takes at most 256 levels of policies and 500 levels of\n * conditions, and at most 1000000 objects and array items, with a shared\n * object counted for each place. It reads only the own data fields of the\n * input.\n *\n * @stability stable\n * @category schemas\n * @since 0.3.0\n */\nexport const schema: <D extends Domain.Any>(\n\tdomain: D,\n) => Schema.Codec<Policy<D>, EncodedNode> = Internal.schema as never\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+gBA,MAAa,WAAiC,WAC7CA,UAAiB,MAAM;;;;;;;;;;;;;;;AAgBxB,MAAa,OAGgBC;;;;;;;;;;;AAwB7B,MAAa,cAA2CC;;;;;;;;;;;;;;;;;;;AAgCxD,MAAa,SAKwBC;;;;;;;;;AAerC,MAAa,MAEwBC,QAAiB,KAAK;;;;;;;;AAS3D,MAAa,MAEwBA,QAAiB,KAAK;;;;;;;;AAS3D,MAAa,UAEwBA,QAAiB,SAAS;;;;;;;;;AAU/D,MAAa,UAQTC;;;;;;;;;AAUJ,MAAa,iBAWTC;;;;;;;;AAWJ,MAAa,SAOTC;;;;;;;;AASJ,MAAa,aAGYC;;;;;;;;;;;AAYzB,MAAa,UAIZC;;;;;;;;;;;;;;AAeD,MAAa,kBAOTC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDJ,MAAa,WAQZC;;;;;;;;;;;;;;;;;;;;AAsDD,MAAa,WAOqCC;;;;;;;;;;;;;;;AA2DlD,MAAa,SAE+BC"}
|
|
@@ -47,19 +47,25 @@ const Service = () => (id, options) => {
|
|
|
47
47
|
};
|
|
48
48
|
/**
|
|
49
49
|
* A cache key for a principal. Two keys are equal when they have the same
|
|
50
|
-
* text, so two principals with the same key share one policy.
|
|
51
|
-
*
|
|
52
|
-
*
|
|
50
|
+
* text, so two principals with the same key share one policy. A key from the
|
|
51
|
+
* JSON form also needs equal decoded principals: a Schema may make data when
|
|
52
|
+
* it decodes, as `expired` from a time, so one text may give two principals.
|
|
53
|
+
* The key also keeps the principal, so the cache can load its policy. A plain
|
|
54
|
+
* `Data` value can not do all this, so the key gives its own equality with
|
|
55
|
+
* `Equal.Equal`.
|
|
53
56
|
*/
|
|
54
57
|
var PrincipalKey = class PrincipalKey {
|
|
55
58
|
principal;
|
|
56
59
|
text;
|
|
57
|
-
|
|
60
|
+
/** The key is the JSON form, so the decoded principals must be equal too. */
|
|
61
|
+
exact;
|
|
62
|
+
constructor(principal, text, exact) {
|
|
58
63
|
this.principal = principal;
|
|
59
64
|
this.text = text;
|
|
65
|
+
this.exact = exact;
|
|
60
66
|
}
|
|
61
67
|
[Equal.symbol](that) {
|
|
62
|
-
return that instanceof PrincipalKey && that.text === this.text;
|
|
68
|
+
return that instanceof PrincipalKey && that.text === this.text && (!this.exact || Equal.equals(that.principal, this.principal));
|
|
63
69
|
}
|
|
64
70
|
[Hash.symbol]() {
|
|
65
71
|
return Hash.string(this.text);
|
|
@@ -96,7 +102,7 @@ const jsonKey = (schema) => {
|
|
|
96
102
|
const text = JSON.stringify(json);
|
|
97
103
|
return Result.match(decode(JSON.parse(text)), {
|
|
98
104
|
onFailure: () => void 0,
|
|
99
|
-
onSuccess: (decoded) => Equal.equals(decoded, principal) ? new PrincipalKey(decoded, text) : void 0
|
|
105
|
+
onSuccess: (decoded) => Equal.equals(decoded, principal) ? new PrincipalKey(decoded, text, true) : void 0
|
|
100
106
|
});
|
|
101
107
|
}
|
|
102
108
|
});
|
|
@@ -122,7 +128,7 @@ const makeLayer = (service, options) => {
|
|
|
122
128
|
const keyOf = (principal, canonical) => {
|
|
123
129
|
if (custom === void 0) return canonical;
|
|
124
130
|
const text = custom(principal);
|
|
125
|
-
return text === void 0 ? void 0 : new PrincipalKey(canonical?.principal ?? principal, text);
|
|
131
|
+
return text === void 0 ? void 0 : new PrincipalKey(canonical?.principal ?? principal, text, false);
|
|
126
132
|
};
|
|
127
133
|
return Layer.effect(service, Effect.gen(function* () {
|
|
128
134
|
const services = yield* Effect.context();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authorizer.js","names":["Policies.provideContext","Decide.decideAny","ResourceData.kindOf","DomainData.descriptorOf","Decide.fitsKind","Analysis.decideKind","Decision.reason","Analysis.coverageAny","permittedFields","Decide.permittedFields"],"sources":["../../src/internal/authorizer.ts"],"sourcesContent":["/**\n * The values of authorizers: the errors, the service class and the layer.\n * The types are in `Authorizer.ts`.\n */\n// The service erases the error type and the service type of predicates,\n// principals and deciders to `unknown`. The public types keep them, so the\n// language service check for `unknown` in an Effect is off here.\n// @effect-diagnostics anyUnknownInErrorContext:off\nimport * as Cache from \"effect/Cache\"\nimport * as Context from \"effect/Context\"\nimport type * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Equal from \"effect/Equal\"\nimport * as Hash from \"effect/Hash\"\nimport * as Layer from \"effect/Layer\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Authorizer from \"../Authorizer.ts\"\nimport type * as Condition from \"../Condition.ts\"\nimport * as Decision from \"../Decision.ts\"\nimport type * as Domain from \"../Domain.ts\"\nimport type * as Policy from \"../Policy.ts\"\nimport * as Analysis from \"./analysis.ts\"\nimport * as Decide from \"./decide.ts\"\nimport * as DomainData from \"./domain.ts\"\nimport * as Policies from \"./policy.ts\"\nimport * as ResourceData from \"./resource.ts\"\n\ntype AnyServiceClass = Authorizer.AnyServiceClass\n\n/** The error when a policy says no. */\nexport class Forbidden extends Schema.TaggedError<Forbidden>(\n\t\"@nmnmcc/ability/Authorizer/Forbidden\",\n)(\"Forbidden\", {\n\taction: Schema.String,\n\tkind: Schema.String,\n\tfield: Schema.optionalKey(Schema.String),\n\treason: Schema.optionalKey(Schema.String),\n}) {}\n\n/** The error when the policy of the principal can not be loaded. */\nexport class PolicyUnavailable extends Schema.TaggedError<PolicyUnavailable>(\n\t\"@nmnmcc/ability/Authorizer/PolicyUnavailable\",\n)(\"PolicyUnavailable\", { cause: Schema.Defect() }) {}\n\n/** The error when a decider must wait for an answer. */\nexport class Pending extends Schema.TaggedError<Pending>(\n\t\"@nmnmcc/ability/Authorizer/Pending\",\n)(\"Pending\", {\n\tticket: Schema.String,\n\treason: Schema.optionalKey(Schema.String),\n}) {}\n\n/** Makes an authorizer service class for a domain. */\nexport const Service =\n\t() =>\n\t(\n\t\tid: string,\n\t\toptions: {\n\t\t\treadonly domain: Domain.Any\n\t\t\treadonly principal: Effect.Effect<any, any, any>\n\t\t},\n\t\t// The class has no name, and its type uses types of Effect that a\n\t\t// declaration file can not name. So this function gives a `Context.Key`.\n\t\t// The public module gives the full type.\n\t): Context.Key<any, any> => {\n\t\tconst Base = Context.Service<any, any>()(id)\n\t\treturn class extends Base {\n\t\t\tstatic readonly domain = options.domain\n\t\t\tstatic readonly principal = options.principal\n\t\t\tstatic readonly decide = (target: AnyTarget) =>\n\t\t\t\tthis.use((service: any) => service.decide(target))\n\t\t\tstatic readonly check = (target: AnyTarget) =>\n\t\t\t\tthis.use((service: any) => service.check(target))\n\t\t\tstatic readonly guard = (target: AnyTarget, options: unknown) =>\n\t\t\t\tthis.use((service: any) => service.guard(target, options))\n\t\t\tstatic readonly filter = (target: AnyTarget) =>\n\t\t\t\tthis.use((service: any) => service.filter(target))\n\t\t\tstatic readonly coverage = (target: AnyTarget) =>\n\t\t\t\tthis.use((service: any) => service.coverage(target))\n\t\t\tstatic readonly permittedFields = (target: AnyTarget) =>\n\t\t\t\tthis.use((service: any) => service.permittedFields(target))\n\t\t}\n\t}\n\ntype AnyTarget = {\n\treadonly action: string\n\treadonly resource?: object\n\treadonly kind?: string\n\treadonly field?: string\n\treadonly within?: unknown\n}\n\n/**\n * A cache key for a principal. Two keys are equal when they have the same\n * text, so two principals with the same key share one policy. The key also\n * keeps the principal, so the cache can load its policy. A plain `Data` value\n * can not do both, so the key gives its own equality with `Equal.Equal`.\n */\nclass PrincipalKey implements Equal.Equal {\n\treadonly principal: object\n\treadonly text: string\n\tconstructor(principal: object, text: string) {\n\t\tthis.principal = principal\n\t\tthis.text = text\n\t}\n\t[Equal.symbol](that: unknown): boolean {\n\t\treturn that instanceof PrincipalKey && that.text === this.text\n\t}\n\t[Hash.symbol](): number {\n\t\treturn Hash.string(this.text)\n\t}\n}\n\n/**\n * Makes the cache key of a principal from its JSON form. The key keeps the\n * principal that the Schema decodes from that form, so the loader sees only\n * the data that the key shows. A principal gets no key when it does not\n * encode, or when the decoded value is not `Equal` to it. Two classes, or a\n * string and a number, may have one JSON form, as in a union, and `Equal`\n * tells them apart. So two principals with one key are equal, and the cache\n * can not give one the policy of the other.\n */\n/**\n * Gives the JSON codec of a Schema, or `undefined` when the Schema has no JSON\n * form, as a struct with a symbol key has none.\n */\nconst jsonCodecOf = (\n\tschema: Schema.Top,\n): Schema.Codec<unknown, unknown> | undefined => {\n\ttry {\n\t\treturn Schema.toCodecJson(schema) as unknown as Schema.Codec<\n\t\t\tunknown,\n\t\t\tunknown\n\t\t>\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\nconst jsonKey = (\n\tschema: Schema.Top,\n): ((principal: object) => PrincipalKey | undefined) => {\n\tconst codec = jsonCodecOf(schema)\n\t// A principal with no JSON form is never kept.\n\tif (codec === undefined) {\n\t\treturn () => undefined\n\t}\n\tconst encode = Schema.encodeUnknownResult(codec)\n\tconst decode = Schema.decodeUnknownResult(codec)\n\tconst keyOf = (principal: object): PrincipalKey | undefined =>\n\t\tResult.match(encode(principal), {\n\t\t\tonFailure: () => undefined,\n\t\t\tonSuccess: (json) => {\n\t\t\t\t// The key is the text, so the check decodes the text. The encoded\n\t\t\t\t// value may hold more than its text shows, as an object of a\n\t\t\t\t// `Schema.Any` field does: `JSON.stringify` leaves out a map.\n\t\t\t\tconst text = JSON.stringify(json)\n\t\t\t\treturn Result.match(decode(JSON.parse(text)), {\n\t\t\t\t\tonFailure: () => undefined,\n\t\t\t\t\tonSuccess: (decoded) =>\n\t\t\t\t\t\tEqual.equals(decoded, principal)\n\t\t\t\t\t\t\t? new PrincipalKey(decoded as object, text)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t})\n\t\t\t},\n\t\t})\n\treturn (principal) => {\n\t\t// A very deep principal may fill the stack of the encoder or of\n\t\t// `Equal`. Such a principal is not kept.\n\t\ttry {\n\t\t\treturn keyOf(principal)\n\t\t} catch {\n\t\t\treturn undefined\n\t\t}\n\t}\n}\n\nconst forbidden = (\n\ttarget: AnyTarget,\n\tkind: string,\n\treason: string | undefined,\n): Forbidden =>\n\tForbidden.make({\n\t\taction: target.action,\n\t\tkind,\n\t\t...(target.field === undefined ? {} : { field: target.field }),\n\t\t...(reason === undefined ? {} : { reason }),\n\t})\n\n/** Makes the layer of an authorizer. */\nexport const makeLayer = (\n\tservice: AnyServiceClass,\n\toptions: {\n\t\treadonly policy: (\n\t\t\tprincipal: object,\n\t\t) => Effect.Effect<Policy.Any, unknown, unknown>\n\t\treadonly decider?: (\n\t\t\trequest: object,\n\t\t) => Effect.Effect<Decision.Decision, unknown, unknown>\n\t\treadonly cache?:\n\t\t\t| {\n\t\t\t\t\treadonly capacity?: number\n\t\t\t\t\treadonly timeToLive?: Duration.Input\n\t\t\t\t\treadonly key?: (principal: object) => string | undefined\n\t\t\t }\n\t\t\t| false\n\t},\n) => {\n\tconst domain: Domain.Any = service.domain\n\t// The JSON form of a principal, and the copy that the Schema decodes from\n\t// it. The loader always gets the copy, with a cache or not, so a cache can\n\t// not change an answer: a form may lose data that `Equal` does not see,\n\t// as `-0` becomes `0`. A principal with no such form gives `undefined`.\n\tconst canonicalOf = jsonKey(domain.principal)\n\tconst custom = options.cache === false ? undefined : options.cache?.key\n\t// It gives `undefined` when the principal has no key. Such a principal does\n\t// not use the cache.\n\tconst keyOf = (\n\t\tprincipal: object,\n\t\tcanonical: PrincipalKey | undefined,\n\t): PrincipalKey | undefined => {\n\t\tif (custom === undefined) {\n\t\t\treturn canonical\n\t\t}\n\t\tconst text = custom(principal)\n\t\treturn text === undefined\n\t\t\t? undefined\n\t\t\t: new PrincipalKey(canonical?.principal ?? principal, text)\n\t}\n\treturn Layer.effect(\n\t\tservice,\n\t\tEffect.gen(function* () {\n\t\t\t// The services of the policy loader and of the predicates come from the\n\t\t\t// layer, so a check does not need them.\n\t\t\tconst services = yield* Effect.context<never>()\n\n\t\t\t// The predicates of the policy get the services of the layer, so the\n\t\t\t// policy and its residual conditions need no services.\n\t\t\t// A policy of another domain may have the same types, but its resources\n\t\t\t// may have other paths. So it fails closed, as a policy that can not be\n\t\t\t// loaded.\n\t\t\tconst load = (principal: object) =>\n\t\t\t\toptions.policy(principal).pipe(\n\t\t\t\t\tEffect.provideContext(services),\n\t\t\t\t\tEffect.filterOrFail(\n\t\t\t\t\t\t(value) => value.domain === domain,\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tnew globalThis.Error(\n\t\t\t\t\t\t\t\t\"The loaded policy is not a policy of this domain\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t\tEffect.mapError((cause) => PolicyUnavailable.make({ cause })),\n\t\t\t\t\tEffect.map((value) =>\n\t\t\t\t\t\tPolicies.provideContext(value, services as never),\n\t\t\t\t\t),\n\t\t\t\t)\n\n\t\t\tconst cache =\n\t\t\t\toptions.cache === false\n\t\t\t\t\t? undefined\n\t\t\t\t\t: yield* Cache.make({\n\t\t\t\t\t\t\tcapacity: options.cache?.capacity ?? 1000,\n\t\t\t\t\t\t\ttimeToLive: options.cache?.timeToLive ?? \"30 seconds\",\n\t\t\t\t\t\t\tlookup: (key: PrincipalKey) => load(key.principal),\n\t\t\t\t\t\t})\n\n\t\t\tconst policyFor = (principal: object) => {\n\t\t\t\tconst canonical = canonicalOf(principal)\n\t\t\t\tconst key =\n\t\t\t\t\tcache === undefined ? undefined : keyOf(principal, canonical)\n\t\t\t\tif (cache === undefined || key === undefined) {\n\t\t\t\t\treturn load(canonical?.principal ?? principal)\n\t\t\t\t}\n\t\t\t\t// A failed lookup is kept in the cache. Remove it, so the next check\n\t\t\t\t// tries again.\n\t\t\t\treturn Cache.get(cache, key).pipe(\n\t\t\t\t\tEffect.tapError(() => Cache.invalidate(cache, key)),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst withServices = <A, E>(\n\t\t\t\teffect: Effect.Effect<A, E, unknown>,\n\t\t\t): Effect.Effect<A, E, unknown> => Effect.provideContext(effect, services)\n\n\t\t\tconst current = Effect.gen(function* () {\n\t\t\t\tconst principal = yield* service.principal\n\t\t\t\tconst value = yield* policyFor(principal)\n\t\t\t\treturn { principal, policy: value }\n\t\t\t})\n\n\t\t\t// The principal and its policy, loaded one time. A check that asks\n\t\t\t// the policy two times, such as `guard`, uses one snapshot for both,\n\t\t\t// so the two answers come from one principal.\n\t\t\ttype Snapshot = Effect.Success<typeof current>\n\n\t\t\tconst decideWith = Effect.fnUntraced(function* (\n\t\t\t\t{ principal, policy: value }: Snapshot,\n\t\t\t\ttarget: AnyTarget,\n\t\t\t) {\n\t\t\t\tconst decision: Decision.Decision = yield* withServices(\n\t\t\t\t\tDecide.decideAny(value, { ...target, principal } as never),\n\t\t\t\t)\n\t\t\t\treturn decision\n\t\t\t})\n\n\t\t\tconst decide = (target: AnyTarget) =>\n\t\t\t\tEffect.flatMap(current, (snapshot) => decideWith(snapshot, target))\n\n\t\t\tconst checkWith = Effect.fnUntraced(function* (\n\t\t\t\t{ principal, policy: value }: Snapshot,\n\t\t\t\ttarget: AnyTarget,\n\t\t\t) {\n\t\t\t\tconst kind =\n\t\t\t\t\ttarget.resource === undefined\n\t\t\t\t\t\t? (target.kind ?? \"\")\n\t\t\t\t\t\t: (ResourceData.kindOf(target.resource) ?? \"\")\n\t\t\t\t// A request that does not fit its kind gets a \"no\" at once. The\n\t\t\t\t// decider must not say yes to an action that the kind does not have.\n\t\t\t\tconst descriptor = DomainData.descriptorOf(domain, kind)\n\t\t\t\tif (descriptor === undefined || !Decide.fitsKind(descriptor, target)) {\n\t\t\t\t\treturn yield* forbidden(target, kind, undefined)\n\t\t\t\t}\n\t\t\t\tconst fromPolicy: Decision.Decision =\n\t\t\t\t\ttarget.resource === undefined\n\t\t\t\t\t\t? Analysis.decideKind(value, { ...target, principal } as never)\n\t\t\t\t\t\t: yield* withServices(\n\t\t\t\t\t\t\t\tDecide.decideAny(value, { ...target, principal } as never),\n\t\t\t\t\t\t\t)\n\t\t\t\t// When no rule gives an answer, the decider gives it.\n\t\t\t\tconst decision: Decision.Decision =\n\t\t\t\t\tfromPolicy._tag === \"NotApplicable\" && options.decider !== undefined\n\t\t\t\t\t\t? yield* options.decider({ ...target, principal })\n\t\t\t\t\t\t: fromPolicy\n\t\t\t\tif (decision._tag !== \"Allow\") {\n\t\t\t\t\treturn yield* forbidden(target, kind, Decision.reason(decision))\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tconst check = (target: AnyTarget) =>\n\t\t\t\tEffect.flatMap(current, (snapshot) => checkWith(snapshot, target))\n\n\t\t\tconst guard = Effect.fnUntraced(function* (\n\t\t\t\ttarget: AnyTarget,\n\t\t\t\tguardOptions: {\n\t\t\t\t\treadonly read?: string\n\t\t\t\t\treadonly hide: () => unknown\n\t\t\t\t},\n\t\t\t) {\n\t\t\t\tconst snapshot = yield* current\n\t\t\t\tconst read = guardOptions.read ?? \"read\"\n\t\t\t\tconst { field: _field, ...rest } = target\n\t\t\t\tconst visible: Decision.Decision = yield* decideWith(snapshot, {\n\t\t\t\t\t...rest,\n\t\t\t\t\taction: read,\n\t\t\t\t})\n\t\t\t\tif (visible._tag !== \"Allow\") {\n\t\t\t\t\treturn yield* Effect.fail(guardOptions.hide())\n\t\t\t\t}\n\t\t\t\tif (target.action !== read || target.field !== undefined) {\n\t\t\t\t\tyield* checkWith(snapshot, target)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\t// The filter is the condition of the coverage: the scope for `All`,\n\t\t\t// `False` for `None`, and else the residual condition in the scope.\n\t\t\t// The residual throws an error when it is too large, so the filter\n\t\t\t// fails.\n\t\t\tconst filter = (\n\t\t\t\ttarget: AnyTarget,\n\t\t\t): Effect.Effect<Condition.Ast, unknown, unknown> =>\n\t\t\t\tEffect.map(\n\t\t\t\t\tcurrent,\n\t\t\t\t\t({ principal, policy: value }): Condition.Ast =>\n\t\t\t\t\t\tAnalysis.coverageAny(value, { ...target, principal } as never)\n\t\t\t\t\t\t\t.condition as Condition.Ast,\n\t\t\t\t)\n\n\t\t\tconst coverage = (\n\t\t\t\ttarget: AnyTarget,\n\t\t\t): Effect.Effect<Analysis.AnyCoverage, unknown, unknown> =>\n\t\t\t\tEffect.map(current, ({ principal, policy: value }) =>\n\t\t\t\t\tAnalysis.coverageAny(value, { ...target, principal } as never),\n\t\t\t\t)\n\n\t\t\tconst permittedFields = Effect.fnUntraced(function* (target: AnyTarget) {\n\t\t\t\tconst { principal, policy: value } = yield* current\n\t\t\t\treturn yield* withServices(\n\t\t\t\t\tDecide.permittedFields(value, { ...target, principal } as never),\n\t\t\t\t)\n\t\t\t})\n\n\t\t\tconst invalidate = (principal?: object) => {\n\t\t\t\tif (cache === undefined) {\n\t\t\t\t\treturn Effect.void\n\t\t\t\t}\n\t\t\t\tif (principal === undefined) {\n\t\t\t\t\treturn Cache.invalidateAll(cache)\n\t\t\t\t}\n\t\t\t\tconst key = keyOf(principal, canonicalOf(principal))\n\t\t\t\treturn key === undefined ? Effect.void : Cache.invalidate(cache, key)\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tdomain,\n\t\t\t\tprincipal: service.principal,\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a,QAAQ;GAClC,MAAM,EAAE,OAAO,QAAQ,GAAG,SAAS;GAKnC,KAAI,OAJsC,WAAW,UAAU;IAC9D,GAAG;IACH,QAAQ;GACT,CAAC,EAAA,CACW,SAAS,SACpB,OAAO,OAAO,OAAO,KAAK,aAAa,KAAK,CAAC;GAE9C,IAAI,OAAO,WAAW,QAAQ,OAAO,UAAU,KAAA,GAC9C,OAAO,UAAU,UAAU,MAAM;EAEnC,CAAC;EAMD,MAAM,UACL,WAEA,OAAO,IACN,UACC,EAAE,WAAW,QAAQ,YACrBC,YAAqB,OAAO;GAAE,GAAG;GAAQ;EAAU,CAAU,CAAC,CAC5D,SACJ;EAED,MAAM,YACL,WAEA,OAAO,IAAI,UAAU,EAAE,WAAW,QAAQ,YACzCA,YAAqB,OAAO;GAAE,GAAG;GAAQ;EAAU,CAAU,CAC9D;EAED,MAAMC,oBAAkB,OAAO,WAAW,WAAW,QAAmB;GACvE,MAAM,EAAE,WAAW,QAAQ,UAAU,OAAO;GAC5C,OAAO,OAAO,aACbC,gBAAuB,OAAO;IAAE,GAAG;IAAQ;GAAU,CAAU,CAChE;EACD,CAAC;EAED,MAAM,cAAc,cAAuB;GAC1C,IAAI,UAAU,KAAA,GACb,OAAO,OAAO;GAEf,IAAI,cAAc,KAAA,GACjB,OAAO,MAAM,cAAc,KAAK;GAEjC,MAAM,MAAM,MAAM,WAAW,YAAY,SAAS,CAAC;GACnD,OAAO,QAAQ,KAAA,IAAY,OAAO,OAAO,MAAM,WAAW,OAAO,GAAG;EACrE;EAEA,OAAO;GACN;GACA,WAAW,QAAQ;GACnB,QAAQ,OAAO,IAAI,UAAU,EAAE,QAAQ,YAAY,KAAK;GACxD;GACA;GACA;GACA;GACA;GACA,iBAAA;GACA;EACD;CACD,CAAC,CACF;AACD"}
|
|
1
|
+
{"version":3,"file":"authorizer.js","names":["Policies.provideContext","Decide.decideAny","ResourceData.kindOf","DomainData.descriptorOf","Decide.fitsKind","Analysis.decideKind","Decision.reason","Analysis.coverageAny","permittedFields","Decide.permittedFields"],"sources":["../../src/internal/authorizer.ts"],"sourcesContent":["/**\n * The values of authorizers: the errors, the service class and the layer.\n * The types are in `Authorizer.ts`.\n */\n// The service erases the error type and the service type of predicates,\n// principals and deciders to `unknown`. The public types keep them, so the\n// language service check for `unknown` in an Effect is off here.\n// @effect-diagnostics anyUnknownInErrorContext:off\nimport * as Cache from \"effect/Cache\"\nimport * as Context from \"effect/Context\"\nimport type * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Equal from \"effect/Equal\"\nimport * as Hash from \"effect/Hash\"\nimport * as Layer from \"effect/Layer\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Authorizer from \"../Authorizer.ts\"\nimport type * as Condition from \"../Condition.ts\"\nimport * as Decision from \"../Decision.ts\"\nimport type * as Domain from \"../Domain.ts\"\nimport type * as Policy from \"../Policy.ts\"\nimport * as Analysis from \"./analysis.ts\"\nimport * as Decide from \"./decide.ts\"\nimport * as DomainData from \"./domain.ts\"\nimport * as Policies from \"./policy.ts\"\nimport * as ResourceData from \"./resource.ts\"\n\ntype AnyServiceClass = Authorizer.AnyServiceClass\n\n/** The error when a policy says no. */\nexport class Forbidden extends Schema.TaggedError<Forbidden>(\n\t\"@nmnmcc/ability/Authorizer/Forbidden\",\n)(\"Forbidden\", {\n\taction: Schema.String,\n\tkind: Schema.String,\n\tfield: Schema.optionalKey(Schema.String),\n\treason: Schema.optionalKey(Schema.String),\n}) {}\n\n/** The error when the policy of the principal can not be loaded. */\nexport class PolicyUnavailable extends Schema.TaggedError<PolicyUnavailable>(\n\t\"@nmnmcc/ability/Authorizer/PolicyUnavailable\",\n)(\"PolicyUnavailable\", { cause: Schema.Defect() }) {}\n\n/** The error when a decider must wait for an answer. */\nexport class Pending extends Schema.TaggedError<Pending>(\n\t\"@nmnmcc/ability/Authorizer/Pending\",\n)(\"Pending\", {\n\tticket: Schema.String,\n\treason: Schema.optionalKey(Schema.String),\n}) {}\n\n/** Makes an authorizer service class for a domain. */\nexport const Service =\n\t() =>\n\t(\n\t\tid: string,\n\t\toptions: {\n\t\t\treadonly domain: Domain.Any\n\t\t\treadonly principal: Effect.Effect<any, any, any>\n\t\t},\n\t\t// The class has no name, and its type uses types of Effect that a\n\t\t// declaration file can not name. So this function gives a `Context.Key`.\n\t\t// The public module gives the full type.\n\t): Context.Key<any, any> => {\n\t\tconst Base = Context.Service<any, any>()(id)\n\t\treturn class extends Base {\n\t\t\tstatic readonly domain = options.domain\n\t\t\tstatic readonly principal = options.principal\n\t\t\tstatic readonly decide = (target: AnyTarget) =>\n\t\t\t\tthis.use((service: any) => service.decide(target))\n\t\t\tstatic readonly check = (target: AnyTarget) =>\n\t\t\t\tthis.use((service: any) => service.check(target))\n\t\t\tstatic readonly guard = (target: AnyTarget, options: unknown) =>\n\t\t\t\tthis.use((service: any) => service.guard(target, options))\n\t\t\tstatic readonly filter = (target: AnyTarget) =>\n\t\t\t\tthis.use((service: any) => service.filter(target))\n\t\t\tstatic readonly coverage = (target: AnyTarget) =>\n\t\t\t\tthis.use((service: any) => service.coverage(target))\n\t\t\tstatic readonly permittedFields = (target: AnyTarget) =>\n\t\t\t\tthis.use((service: any) => service.permittedFields(target))\n\t\t}\n\t}\n\ntype AnyTarget = {\n\treadonly action: string\n\treadonly resource?: object\n\treadonly kind?: string\n\treadonly field?: string\n\treadonly within?: unknown\n}\n\n/**\n * A cache key for a principal. Two keys are equal when they have the same\n * text, so two principals with the same key share one policy. A key from the\n * JSON form also needs equal decoded principals: a Schema may make data when\n * it decodes, as `expired` from a time, so one text may give two principals.\n * The key also keeps the principal, so the cache can load its policy. A plain\n * `Data` value can not do all this, so the key gives its own equality with\n * `Equal.Equal`.\n */\nclass PrincipalKey implements Equal.Equal {\n\treadonly principal: object\n\treadonly text: string\n\t/** The key is the JSON form, so the decoded principals must be equal too. */\n\treadonly exact: boolean\n\tconstructor(principal: object, text: string, exact: boolean) {\n\t\tthis.principal = principal\n\t\tthis.text = text\n\t\tthis.exact = exact\n\t}\n\t[Equal.symbol](that: unknown): boolean {\n\t\treturn (\n\t\t\tthat instanceof PrincipalKey &&\n\t\t\tthat.text === this.text &&\n\t\t\t(!this.exact || Equal.equals(that.principal, this.principal))\n\t\t)\n\t}\n\t[Hash.symbol](): number {\n\t\treturn Hash.string(this.text)\n\t}\n}\n\n/**\n * Makes the cache key of a principal from its JSON form. The key keeps the\n * principal that the Schema decodes from that form, so the loader sees only\n * the data that the key shows. A principal gets no key when it does not\n * encode, or when the decoded value is not `Equal` to it. Two classes, or a\n * string and a number, may have one JSON form, as in a union, and `Equal`\n * tells them apart. So two principals with one key are equal, and the cache\n * can not give one the policy of the other.\n */\n/**\n * Gives the JSON codec of a Schema, or `undefined` when the Schema has no JSON\n * form, as a struct with a symbol key has none.\n */\nconst jsonCodecOf = (\n\tschema: Schema.Top,\n): Schema.Codec<unknown, unknown> | undefined => {\n\ttry {\n\t\treturn Schema.toCodecJson(schema) as unknown as Schema.Codec<\n\t\t\tunknown,\n\t\t\tunknown\n\t\t>\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\nconst jsonKey = (\n\tschema: Schema.Top,\n): ((principal: object) => PrincipalKey | undefined) => {\n\tconst codec = jsonCodecOf(schema)\n\t// A principal with no JSON form is never kept.\n\tif (codec === undefined) {\n\t\treturn () => undefined\n\t}\n\tconst encode = Schema.encodeUnknownResult(codec)\n\tconst decode = Schema.decodeUnknownResult(codec)\n\tconst keyOf = (principal: object): PrincipalKey | undefined =>\n\t\tResult.match(encode(principal), {\n\t\t\tonFailure: () => undefined,\n\t\t\tonSuccess: (json) => {\n\t\t\t\t// The key is the text, so the check decodes the text. The encoded\n\t\t\t\t// value may hold more than its text shows, as an object of a\n\t\t\t\t// `Schema.Any` field does: `JSON.stringify` leaves out a map.\n\t\t\t\tconst text = JSON.stringify(json)\n\t\t\t\treturn Result.match(decode(JSON.parse(text)), {\n\t\t\t\t\tonFailure: () => undefined,\n\t\t\t\t\tonSuccess: (decoded) =>\n\t\t\t\t\t\tEqual.equals(decoded, principal)\n\t\t\t\t\t\t\t? new PrincipalKey(decoded as object, text, true)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t})\n\t\t\t},\n\t\t})\n\treturn (principal) => {\n\t\t// A very deep principal may fill the stack of the encoder or of\n\t\t// `Equal`. Such a principal is not kept.\n\t\ttry {\n\t\t\treturn keyOf(principal)\n\t\t} catch {\n\t\t\treturn undefined\n\t\t}\n\t}\n}\n\nconst forbidden = (\n\ttarget: AnyTarget,\n\tkind: string,\n\treason: string | undefined,\n): Forbidden =>\n\tForbidden.make({\n\t\taction: target.action,\n\t\tkind,\n\t\t...(target.field === undefined ? {} : { field: target.field }),\n\t\t...(reason === undefined ? {} : { reason }),\n\t})\n\n/** Makes the layer of an authorizer. */\nexport const makeLayer = (\n\tservice: AnyServiceClass,\n\toptions: {\n\t\treadonly policy: (\n\t\t\tprincipal: object,\n\t\t) => Effect.Effect<Policy.Any, unknown, unknown>\n\t\treadonly decider?: (\n\t\t\trequest: object,\n\t\t) => Effect.Effect<Decision.Decision, unknown, unknown>\n\t\treadonly cache?:\n\t\t\t| {\n\t\t\t\t\treadonly capacity?: number\n\t\t\t\t\treadonly timeToLive?: Duration.Input\n\t\t\t\t\treadonly key?: (principal: object) => string | undefined\n\t\t\t }\n\t\t\t| false\n\t},\n) => {\n\tconst domain: Domain.Any = service.domain\n\t// The JSON form of a principal, and the copy that the Schema decodes from\n\t// it. The loader always gets the copy, with a cache or not, so a cache can\n\t// not change an answer: a form may lose data that `Equal` does not see,\n\t// as `-0` becomes `0`. A principal with no such form gives `undefined`.\n\tconst canonicalOf = jsonKey(domain.principal)\n\tconst custom = options.cache === false ? undefined : options.cache?.key\n\t// It gives `undefined` when the principal has no key. Such a principal does\n\t// not use the cache.\n\tconst keyOf = (\n\t\tprincipal: object,\n\t\tcanonical: PrincipalKey | undefined,\n\t): PrincipalKey | undefined => {\n\t\tif (custom === undefined) {\n\t\t\treturn canonical\n\t\t}\n\t\tconst text = custom(principal)\n\t\treturn text === undefined\n\t\t\t? undefined\n\t\t\t: new PrincipalKey(canonical?.principal ?? principal, text, false)\n\t}\n\treturn Layer.effect(\n\t\tservice,\n\t\tEffect.gen(function* () {\n\t\t\t// The services of the policy loader and of the predicates come from the\n\t\t\t// layer, so a check does not need them.\n\t\t\tconst services = yield* Effect.context<never>()\n\n\t\t\t// The predicates of the policy get the services of the layer, so the\n\t\t\t// policy and its residual conditions need no services.\n\t\t\t// A policy of another domain may have the same types, but its resources\n\t\t\t// may have other paths. So it fails closed, as a policy that can not be\n\t\t\t// loaded.\n\t\t\tconst load = (principal: object) =>\n\t\t\t\toptions.policy(principal).pipe(\n\t\t\t\t\tEffect.provideContext(services),\n\t\t\t\t\tEffect.filterOrFail(\n\t\t\t\t\t\t(value) => value.domain === domain,\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tnew globalThis.Error(\n\t\t\t\t\t\t\t\t\"The loaded policy is not a policy of this domain\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t\tEffect.mapError((cause) => PolicyUnavailable.make({ cause })),\n\t\t\t\t\tEffect.map((value) =>\n\t\t\t\t\t\tPolicies.provideContext(value, services as never),\n\t\t\t\t\t),\n\t\t\t\t)\n\n\t\t\tconst cache =\n\t\t\t\toptions.cache === false\n\t\t\t\t\t? undefined\n\t\t\t\t\t: yield* Cache.make({\n\t\t\t\t\t\t\tcapacity: options.cache?.capacity ?? 1000,\n\t\t\t\t\t\t\ttimeToLive: options.cache?.timeToLive ?? \"30 seconds\",\n\t\t\t\t\t\t\tlookup: (key: PrincipalKey) => load(key.principal),\n\t\t\t\t\t\t})\n\n\t\t\tconst policyFor = (principal: object) => {\n\t\t\t\tconst canonical = canonicalOf(principal)\n\t\t\t\tconst key =\n\t\t\t\t\tcache === undefined ? undefined : keyOf(principal, canonical)\n\t\t\t\tif (cache === undefined || key === undefined) {\n\t\t\t\t\treturn load(canonical?.principal ?? principal)\n\t\t\t\t}\n\t\t\t\t// A failed lookup is kept in the cache. Remove it, so the next check\n\t\t\t\t// tries again.\n\t\t\t\treturn Cache.get(cache, key).pipe(\n\t\t\t\t\tEffect.tapError(() => Cache.invalidate(cache, key)),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst withServices = <A, E>(\n\t\t\t\teffect: Effect.Effect<A, E, unknown>,\n\t\t\t): Effect.Effect<A, E, unknown> => Effect.provideContext(effect, services)\n\n\t\t\tconst current = Effect.gen(function* () {\n\t\t\t\tconst principal = yield* service.principal\n\t\t\t\tconst value = yield* policyFor(principal)\n\t\t\t\treturn { principal, policy: value }\n\t\t\t})\n\n\t\t\t// The principal and its policy, loaded one time. A check that asks\n\t\t\t// the policy two times, such as `guard`, uses one snapshot for both,\n\t\t\t// so the two answers come from one principal.\n\t\t\ttype Snapshot = Effect.Success<typeof current>\n\n\t\t\tconst decideWith = Effect.fnUntraced(function* (\n\t\t\t\t{ principal, policy: value }: Snapshot,\n\t\t\t\ttarget: AnyTarget,\n\t\t\t) {\n\t\t\t\tconst decision: Decision.Decision = yield* withServices(\n\t\t\t\t\tDecide.decideAny(value, { ...target, principal } as never),\n\t\t\t\t)\n\t\t\t\treturn decision\n\t\t\t})\n\n\t\t\tconst decide = (target: AnyTarget) =>\n\t\t\t\tEffect.flatMap(current, (snapshot) => decideWith(snapshot, target))\n\n\t\t\tconst checkWith = Effect.fnUntraced(function* (\n\t\t\t\t{ principal, policy: value }: Snapshot,\n\t\t\t\ttarget: AnyTarget,\n\t\t\t) {\n\t\t\t\tconst kind =\n\t\t\t\t\ttarget.resource === undefined\n\t\t\t\t\t\t? (target.kind ?? \"\")\n\t\t\t\t\t\t: (ResourceData.kindOf(target.resource) ?? \"\")\n\t\t\t\t// A request that does not fit its kind gets a \"no\" at once. The\n\t\t\t\t// decider must not say yes to an action that the kind does not have.\n\t\t\t\tconst descriptor = DomainData.descriptorOf(domain, kind)\n\t\t\t\tif (descriptor === undefined || !Decide.fitsKind(descriptor, target)) {\n\t\t\t\t\treturn yield* forbidden(target, kind, undefined)\n\t\t\t\t}\n\t\t\t\tconst fromPolicy: Decision.Decision =\n\t\t\t\t\ttarget.resource === undefined\n\t\t\t\t\t\t? Analysis.decideKind(value, { ...target, principal } as never)\n\t\t\t\t\t\t: yield* withServices(\n\t\t\t\t\t\t\t\tDecide.decideAny(value, { ...target, principal } as never),\n\t\t\t\t\t\t\t)\n\t\t\t\t// When no rule gives an answer, the decider gives it.\n\t\t\t\tconst decision: Decision.Decision =\n\t\t\t\t\tfromPolicy._tag === \"NotApplicable\" && options.decider !== undefined\n\t\t\t\t\t\t? yield* options.decider({ ...target, principal })\n\t\t\t\t\t\t: fromPolicy\n\t\t\t\tif (decision._tag !== \"Allow\") {\n\t\t\t\t\treturn yield* forbidden(target, kind, Decision.reason(decision))\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tconst check = (target: AnyTarget) =>\n\t\t\t\tEffect.flatMap(current, (snapshot) => checkWith(snapshot, target))\n\n\t\t\tconst guard = Effect.fnUntraced(function* (\n\t\t\t\ttarget: AnyTarget,\n\t\t\t\tguardOptions: {\n\t\t\t\t\treadonly read?: string\n\t\t\t\t\treadonly hide: () => unknown\n\t\t\t\t},\n\t\t\t) {\n\t\t\t\tconst snapshot = yield* current\n\t\t\t\tconst read = guardOptions.read ?? \"read\"\n\t\t\t\tconst { field: _field, ...rest } = target\n\t\t\t\tconst visible: Decision.Decision = yield* decideWith(snapshot, {\n\t\t\t\t\t...rest,\n\t\t\t\t\taction: read,\n\t\t\t\t})\n\t\t\t\tif (visible._tag !== \"Allow\") {\n\t\t\t\t\treturn yield* Effect.fail(guardOptions.hide())\n\t\t\t\t}\n\t\t\t\tif (target.action !== read || target.field !== undefined) {\n\t\t\t\t\tyield* checkWith(snapshot, target)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\t// The filter is the condition of the coverage: the scope for `All`,\n\t\t\t// `False` for `None`, and else the residual condition in the scope.\n\t\t\t// The residual throws an error when it is too large, so the filter\n\t\t\t// fails.\n\t\t\tconst filter = (\n\t\t\t\ttarget: AnyTarget,\n\t\t\t): Effect.Effect<Condition.Ast, unknown, unknown> =>\n\t\t\t\tEffect.map(\n\t\t\t\t\tcurrent,\n\t\t\t\t\t({ principal, policy: value }): Condition.Ast =>\n\t\t\t\t\t\tAnalysis.coverageAny(value, { ...target, principal } as never)\n\t\t\t\t\t\t\t.condition as Condition.Ast,\n\t\t\t\t)\n\n\t\t\tconst coverage = (\n\t\t\t\ttarget: AnyTarget,\n\t\t\t): Effect.Effect<Analysis.AnyCoverage, unknown, unknown> =>\n\t\t\t\tEffect.map(current, ({ principal, policy: value }) =>\n\t\t\t\t\tAnalysis.coverageAny(value, { ...target, principal } as never),\n\t\t\t\t)\n\n\t\t\tconst permittedFields = Effect.fnUntraced(function* (target: AnyTarget) {\n\t\t\t\tconst { principal, policy: value } = yield* current\n\t\t\t\treturn yield* withServices(\n\t\t\t\t\tDecide.permittedFields(value, { ...target, principal } as never),\n\t\t\t\t)\n\t\t\t})\n\n\t\t\tconst invalidate = (principal?: object) => {\n\t\t\t\tif (cache === undefined) {\n\t\t\t\t\treturn Effect.void\n\t\t\t\t}\n\t\t\t\tif (principal === undefined) {\n\t\t\t\t\treturn Cache.invalidateAll(cache)\n\t\t\t\t}\n\t\t\t\tconst key = keyOf(principal, canonicalOf(principal))\n\t\t\t\treturn key === undefined ? Effect.void : Cache.invalidate(cache, key)\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tdomain,\n\t\t\t\tprincipal: service.principal,\n\t\t\t\tpolicy: Effect.map(current, ({ policy: value }) => value),\n\t\t\t\tdecide,\n\t\t\t\tcheck,\n\t\t\t\tguard,\n\t\t\t\tfilter,\n\t\t\t\tcoverage,\n\t\t\t\tpermittedFields,\n\t\t\t\tinvalidate,\n\t\t\t} as never\n\t\t}),\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,YAAb,cAA+B,OAAO,YACrC,sC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K,aAAa,KAAK,CAAC;GAE9C,IAAI,OAAO,WAAW,QAAQ,OAAO,UAAU,KAAA,GAC9C,OAAO,UAAU,UAAU,MAAM;EAEnC,CAAC;EAMD,MAAM,UACL,WAEA,OAAO,IACN,UACC,EAAE,WAAW,QAAQ,YACrBC,YAAqB,OAAO;GAAE,GAAG;GAAQ;EAAU,CAAU,CAAC,CAC5D,SACJ;EAED,MAAM,YACL,WAEA,OAAO,IAAI,UAAU,EAAE,WAAW,QAAQ,YACzCA,YAAqB,OAAO;GAAE,GAAG;GAAQ;EAAU,CAAU,CAC9D;EAED,MAAMC,oBAAkB,OAAO,WAAW,WAAW,QAAmB;GACvE,MAAM,EAAE,WAAW,QAAQ,UAAU,OAAO;GAC5C,OAAO,OAAO,aACbC,gBAAuB,OAAO;IAAE,GAAG;IAAQ;GAAU,CAAU,CAChE;EACD,CAAC;EAED,MAAM,cAAc,cAAuB;GAC1C,IAAI,UAAU,KAAA,GACb,OAAO,OAAO;GAEf,IAAI,cAAc,KAAA,GACjB,OAAO,MAAM,cAAc,KAAK;GAEjC,MAAM,MAAM,MAAM,WAAW,YAAY,SAAS,CAAC;GACnD,OAAO,QAAQ,KAAA,IAAY,OAAO,OAAO,MAAM,WAAW,OAAO,GAAG;EACrE;EAEA,OAAO;GACN;GACA,WAAW,QAAQ;GACnB,QAAQ,OAAO,IAAI,UAAU,EAAE,QAAQ,YAAY,KAAK;GACxD;GACA;GACA;GACA;GACA;GACA,iBAAA;GACA;EACD;CACD,CAAC,CACF;AACD"}
|
package/dist/internal/bind.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { searchSteps } from "./limits.js";
|
|
1
2
|
import { isNode } from "./nodes.js";
|
|
2
3
|
import { accepts, anyKinds, lookup } from "./catalog.js";
|
|
3
4
|
import { fitsCatalog, parse } from "./patterns.js";
|
|
@@ -21,6 +22,10 @@ const makeMemo = () => ({
|
|
|
21
22
|
issues: {
|
|
22
23
|
count: 0,
|
|
23
24
|
noted: false
|
|
25
|
+
},
|
|
26
|
+
work: {
|
|
27
|
+
steps: 0,
|
|
28
|
+
noted: false
|
|
24
29
|
}
|
|
25
30
|
});
|
|
26
31
|
/**
|
|
@@ -83,17 +88,29 @@ const patternIssues = (memo, known, pattern, at) => Result.match(parse(pattern),
|
|
|
83
88
|
path: at,
|
|
84
89
|
issue
|
|
85
90
|
}],
|
|
86
|
-
onSuccess: (parsed) =>
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
91
|
+
onSuccess: (parsed) => {
|
|
92
|
+
const fits = known.length === 0 || Arr.some(known, (descriptor) => {
|
|
93
|
+
const key = `${descriptor.kind}\u0000${pattern}`;
|
|
94
|
+
return Option.getOrElse(MutableHashMap.get(memo.fits, key), () => {
|
|
95
|
+
memo.work.steps += descriptor.catalog.fields.length * Math.max(parsed.length, 1);
|
|
96
|
+
if (memo.work.steps > 1e6) return true;
|
|
97
|
+
const found = fitsCatalog(parsed, descriptor.catalog);
|
|
98
|
+
MutableHashMap.set(memo.fits, key, found);
|
|
99
|
+
return found;
|
|
100
|
+
});
|
|
92
101
|
});
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
102
|
+
if (memo.work.steps > 1e6 && !memo.work.noted) {
|
|
103
|
+
memo.work.noted = true;
|
|
104
|
+
return [{
|
|
105
|
+
path: at,
|
|
106
|
+
issue: `The field patterns of the policy take more than ${String(searchSteps)} steps to check. The most is ${String(searchSteps)}.`
|
|
107
|
+
}];
|
|
108
|
+
}
|
|
109
|
+
return fits ? [] : [{
|
|
110
|
+
path: at,
|
|
111
|
+
issue: `The field pattern "${pattern}" matches no field of the resources of the rule`
|
|
112
|
+
}];
|
|
113
|
+
}
|
|
97
114
|
});
|
|
98
115
|
/** The fields of the resources that a test of the rule may read. */
|
|
99
116
|
const fieldsAt = (context, field) => Arr.flatMap(context.applicable, (descriptor) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bind.js","names":["Catalog.accepts","Catalog.lookup","Patterns.parse","Patterns.fitsCatalog","Catalog.anyKinds","Nodes.isNode"],"sources":["../../src/internal/bind.ts"],"sourcesContent":["/**\n * The binding of rules to a domain. It is the one check of a rule, for a rule\n * from the builder, from `Policy.rule`, and from JSON alike. It reads the\n * catalogs of the resources and of the principal, and it gives one issue for\n * each problem, with the path of the problem and, for a name with a mistake,\n * the name that it may mean.\n */\nimport * as Arr from \"effect/Array\"\nimport * as HashMap from \"effect/HashMap\"\nimport * as MutableHashMap from \"effect/MutableHashMap\"\nimport * as Option from \"effect/Option\"\nimport * as Result from \"effect/Result\"\nimport type * as Domain from \"../Domain.ts\"\nimport type * as Resource from \"../Resource.ts\"\nimport * as Catalog from \"./catalog.ts\"\nimport * as Limits from \"./limits.ts\"\nimport * as Nodes from \"./nodes.ts\"\nimport * as Patterns from \"./patterns.ts\"\nimport { withSuggestion } from \"./suggest.ts\"\n\n/** One problem of a rule or a policy, with its path. */\nexport interface Issue {\n\treadonly path: ReadonlyArray<PropertyKey>\n\treadonly issue: string\n}\n\n/** The data of a rule that the binding reads. */\nexport interface RuleData {\n\treadonly actions: ReadonlyArray<string>\n\treadonly resources: ReadonlyArray<string>\n\treadonly when?: unknown\n\treadonly fields?: ReadonlyArray<string>\n}\n\n/**\n * The memo of one binding, for all its rules. A policy may name one wrong\n * field or one pattern in very many places, so the work on each is done one\n * time. It goes away when the binding ends.\n */\ninterface Memo {\n\t/** The suggestion for each name, by the place where it was looked for. */\n\treadonly suggestions: MutableHashMap.MutableHashMap<string, string>\n\t/** If a pattern matches a field of a kind, by the kind and the pattern. */\n\treadonly fits: MutableHashMap.MutableHashMap<string, boolean>\n\t/** The count of the issues of conditions so far. It belongs to one binding. */\n\treadonly issues: { count: number; noted: boolean }\n}\n\nconst makeMemo = (): Memo => ({\n\tsuggestions: MutableHashMap.empty(),\n\tfits: MutableHashMap.empty(),\n\tissues: { count: 0, noted: false },\n})\n\n/**\n * The most names that one binding makes a suggestion for. A suggestion\n * compares the name with every name of a catalog, so a policy with very many\n * wrong names would take a long time.\n */\nconst maxSuggestions = 32\n\n/** Adds a suggestion to a message, with the memo of the binding. */\nconst suggestIn = (\n\tmemo: Memo,\n\tmessage: string,\n\tname: string,\n\tscope: string,\n\tnames: () => ReadonlyArray<string>,\n): string => {\n\tconst key = `${scope}\\u0000${name}`\n\tconst known = MutableHashMap.get(memo.suggestions, key)\n\tif (Option.isSome(known)) {\n\t\treturn known.value\n\t}\n\tif (MutableHashMap.size(memo.suggestions) >= maxSuggestions) {\n\t\treturn message\n\t}\n\tconst made = withSuggestion(message, name, names())\n\tMutableHashMap.set(memo.suggestions, key, made)\n\treturn made\n}\n\n/** The kinds that a rule may run on, from the view of its checks. */\ninterface Context {\n\treadonly domain: Domain.Any\n\treadonly memo: Memo\n\t/** The rule is for every resource (`\"*\"`). */\n\treadonly all: boolean\n\t/** The resources that the rule names and that the domain has. */\n\treadonly named: ReadonlyArray<Resource.Descriptor>\n\t/** The named resources that have one of the actions of the rule. */\n\treadonly applicable: ReadonlyArray<Resource.Descriptor>\n\t/**\n\t * The resources whose paths a path test may read: every resource with one\n\t * of the actions, for a rule for every resource.\n\t */\n\treadonly paths: ReadonlyArray<Resource.Descriptor>\n}\n\ntype Operand = Nodes.Operand\n\n/**\n * Tests if a field may hold a value of the type of a fixed value. A test with\n * `null` is a test that the field is missing, so `null` always fits. A number\n * fits any field of numbers: a test of an integer field with `1.5` or\n * `Infinity` has a meaning, as `lt` shows.\n */\nconst fitsLiteral = (kinds: Catalog.Kinds, value: unknown): boolean =>\n\tvalue === null ||\n\t(typeof value === \"number\" && kinds.number !== \"none\") ||\n\tCatalog.accepts(kinds, value)\n\n/**\n * Tests if two fields may hold one scalar. A principal field that is `null`\n * or that holds an object is a missing value, and a test with a missing value\n * is false, so only scalars count.\n */\nconst meet = (left: Catalog.Kinds, right: Catalog.Kinds): boolean =>\n\t(left.string && right.string) ||\n\t(left.boolean && right.boolean) ||\n\t(left.number !== \"none\" && right.number !== \"none\") ||\n\tArr.some(left.literals, (value) => Catalog.accepts(right, value)) ||\n\tArr.some(right.literals, (value) => Catalog.accepts(left, value))\n\nconst hasStrings = (kinds: Catalog.Kinds): boolean =>\n\tkinds.string || Arr.some(kinds.literals, (value) => typeof value === \"string\")\n\nconst hasNumbers = (kinds: Catalog.Kinds): boolean =>\n\tkinds.number !== \"none\" ||\n\tArr.some(kinds.literals, (value) => typeof value === \"number\")\n\n/** Tests if a field may hold a value with an order: a number or a string. */\nconst isOrdered = (kinds: Catalog.Kinds): boolean =>\n\thasStrings(kinds) || hasNumbers(kinds)\n\n/** Tests if two fields may hold values of one ordered type. */\nconst orderedMeet = (left: Catalog.Kinds, right: Catalog.Kinds): boolean =>\n\t(hasStrings(left) && hasStrings(right)) ||\n\t(hasNumbers(left) && hasNumbers(right))\n\n/** The texts of the fields of a catalog that have only names, for suggestions. */\nconst namesOf = (catalog: Catalog.Catalog): ReadonlyArray<string> =>\n\tArr.map(\n\t\tArr.filter(catalog.fields, (field) =>\n\t\t\tArr.every(field.path, (segment) => typeof segment === \"string\"),\n\t\t),\n\t\t(field) => field.text,\n\t)\n\n/** The issue of a field that is not a field of every resource of the rule. */\nconst fieldIssue = (\n\tcontext: Context,\n\tfield: string,\n\tat: ReadonlyArray<PropertyKey>,\n): ReadonlyArray<Issue> => {\n\tconst message = `The field \"${field}\" is not a field of every resource of the rule`\n\tif (context.all || context.named.length === 0) {\n\t\treturn [{ path: at, issue: message }]\n\t}\n\tconst without = Arr.filter(\n\t\tcontext.named,\n\t\t(descriptor) => Catalog.lookup(descriptor.catalog, field) === undefined,\n\t)\n\treturn without.length === 0\n\t\t? []\n\t\t: [\n\t\t\t\t{\n\t\t\t\t\tpath: at,\n\t\t\t\t\tissue: suggestIn(context.memo, message, field, without[0]!.kind, () =>\n\t\t\t\t\t\tnamesOf(without[0]!.catalog),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t]\n}\n\n/**\n * The issues of a field pattern: a pattern that does not parse, or that\n * matches no field of the resources of the rule, as a pattern with a mistake\n * in a name does.\n */\nconst patternIssues = (\n\tmemo: Memo,\n\tknown: ReadonlyArray<Resource.Descriptor>,\n\tpattern: string,\n\tat: ReadonlyArray<PropertyKey>,\n): ReadonlyArray<Issue> =>\n\tResult.match(Patterns.parse(pattern), {\n\t\tonFailure: (issue) => [{ path: at, issue }],\n\t\tonSuccess: (parsed) =>\n\t\t\t// A rule with no known resource has an issue for that already.\n\t\t\tknown.length === 0 ||\n\t\t\tArr.some(known, (descriptor) => {\n\t\t\t\tconst key = `${descriptor.kind}\\u0000${pattern}`\n\t\t\t\treturn Option.getOrElse(MutableHashMap.get(memo.fits, key), () => {\n\t\t\t\t\tconst fits = Patterns.fitsCatalog(parsed, descriptor.catalog)\n\t\t\t\t\tMutableHashMap.set(memo.fits, key, fits)\n\t\t\t\t\treturn fits\n\t\t\t\t})\n\t\t\t})\n\t\t\t\t? []\n\t\t\t\t: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: at,\n\t\t\t\t\t\t\tissue: `The field pattern \"${pattern}\" matches no field of the resources of the rule`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t})\n\n/** The fields of the resources that a test of the rule may read. */\nconst fieldsAt = (\n\tcontext: Context,\n\tfield: string,\n): ReadonlyArray<Catalog.Field> =>\n\tArr.flatMap(context.applicable, (descriptor) => {\n\t\tconst found = Catalog.lookup(descriptor.catalog, field)\n\t\treturn found === undefined ? [] : [found]\n\t})\n\n/** The field of the principal that an operand names, or the issue when there is none. */\nconst principalField = (\n\tcontext: Context,\n\tref: string,\n\tat: ReadonlyArray<PropertyKey>,\n): Catalog.Field | Issue => {\n\tconst found = Catalog.lookup(context.domain.principalCatalog, ref)\n\treturn found !== undefined\n\t\t? found\n\t\t: {\n\t\t\t\tpath: at,\n\t\t\t\tissue: suggestIn(\n\t\t\t\t\tcontext.memo,\n\t\t\t\t\t`The principal has no field \"${ref}\"`,\n\t\t\t\t\tref,\n\t\t\t\t\t\"~principal\",\n\t\t\t\t\t() => namesOf(context.domain.principalCatalog),\n\t\t\t\t),\n\t\t\t}\n}\n\nconst isIssue = (value: Catalog.Field | Issue): value is Issue =>\n\t\"issue\" in value\n\n/** The issues of one operand of a test of a field. */\nconst operandIssues = (\n\tcontext: Context,\n\tfield: string,\n\tordered: boolean,\n\toperand: Operand,\n\tat: ReadonlyArray<PropertyKey>,\n): ReadonlyArray<Issue> => {\n\tconst fields = fieldsAt(context, field)\n\tif (operand._tag === \"Literal\") {\n\t\tconst value = operand.value\n\t\tif (ordered && typeof value !== \"string\" && typeof value !== \"number\") {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tpath: at,\n\t\t\t\t\tissue: `The field \"${field}\" has an ordered test with a value that has no order`,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\treturn [\n\t\t\t...(Arr.some(fields, (found) => !fitsLiteral(found.kinds, value))\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: at,\n\t\t\t\t\t\t\tissue: `The field \"${field}\" can not hold the value ${JSON.stringify(value)}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: []),\n\t\t\t...(ordered && Arr.some(fields, (found) => !isOrdered(found.kinds))\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: at,\n\t\t\t\t\t\t\tissue: `The field \"${field}\" has an ordered test with a value that has no order`,\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: []),\n\t\t]\n\t}\n\tconst principal = principalField(context, operand.path, at)\n\tif (isIssue(principal)) {\n\t\treturn [principal]\n\t}\n\treturn [\n\t\t...(Arr.some(fields, (found) => !meet(found.kinds, principal.kinds))\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: at,\n\t\t\t\t\t\tissue: `The field \"${field}\" can not hold a value of the principal field \"${operand.path}\"`,\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: []),\n\t\t...(ordered &&\n\t\tArr.some(fields, (found) => !orderedMeet(found.kinds, principal.kinds))\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: at,\n\t\t\t\t\t\tissue: `The field \"${field}\" has an ordered test with a value that has no order`,\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: []),\n\t]\n}\n\n/**\n * Tests if the path of a resource may start with a prefix: it is as long as\n * the prefix, and each fixed string of the prefix is the string of the path\n * at its place, when the path has a string there.\n */\nconst mayStartWith = (\n\tdescriptor: Resource.Descriptor,\n\tstrings: ReadonlyArray<string | null>,\n): boolean =>\n\t(descriptor.path?.length ?? 0) >= strings.length &&\n\tArr.every(strings, (string, index) => {\n\t\tconst segment = descriptor.path?.[index]\n\t\treturn string === null || typeof segment !== \"string\" || segment === string\n\t})\n\n/** The kinds of the part of the path of a resource at a place. */\nconst pathPartKinds = (\n\tdescriptor: Resource.Descriptor,\n\tindex: number,\n): Catalog.Kinds | string | undefined => {\n\tconst segment = descriptor.path?.[index]\n\treturn segment === undefined || typeof segment === \"string\"\n\t\t? segment\n\t\t: (Catalog.lookup(descriptor.catalog, segment.field)?.kinds ??\n\t\t\t\tCatalog.anyKinds)\n}\n\n/** The issues of the prefix of a path test. */\nconst underIssues = (\n\tcontext: Context,\n\tprefix: ReadonlyArray<Operand>,\n\tat: ReadonlyArray<PropertyKey>,\n): ReadonlyArray<Issue> => {\n\tconst strings = Arr.map(prefix, (operand) =>\n\t\toperand._tag === \"Literal\" && typeof operand.value === \"string\"\n\t\t\t? operand.value\n\t\t\t: null,\n\t)\n\t// The test can match only a path that starts with the fixed strings of\n\t// the prefix, so the other resources are left out.\n\tconst candidates = Arr.filter(context.paths, (descriptor) =>\n\t\tmayStartWith(descriptor, strings),\n\t)\n\treturn Arr.flatMap(prefix, (operand, index): ReadonlyArray<Issue> => {\n\t\tconst place = [...at, \"prefix\", index]\n\t\tif (operand._tag === \"Literal\") {\n\t\t\treturn Arr.some(candidates, (descriptor) => {\n\t\t\t\tconst kinds = pathPartKinds(descriptor, index)\n\t\t\t\treturn typeof kinds === \"object\" && !fitsLiteral(kinds, operand.value)\n\t\t\t})\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: place,\n\t\t\t\t\t\t\tissue: `The path part ${String(index)} can not hold the value ${JSON.stringify(operand.value)}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: []\n\t\t}\n\t\tconst principal = principalField(context, operand.path, place)\n\t\tif (isIssue(principal)) {\n\t\t\treturn [principal]\n\t\t}\n\t\treturn Arr.some(candidates, (descriptor) => {\n\t\t\tconst kinds = pathPartKinds(descriptor, index)\n\t\t\treturn kinds === undefined\n\t\t\t\t? true\n\t\t\t\t: typeof kinds === \"string\"\n\t\t\t\t\t? !Catalog.accepts(principal.kinds, kinds)\n\t\t\t\t\t: !meet(kinds, principal.kinds)\n\t\t})\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: place,\n\t\t\t\t\t\tissue: `The principal field \"${operand.path}\" can not hold a part of the path of the resource`,\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: []\n\t})\n}\n\nconst notWhole = (at: ReadonlyArray<PropertyKey>): Issue => ({\n\tpath: at,\n\tissue: \"The condition is not a whole condition tree\",\n})\n\n/**\n * The most issues that the walk of the conditions of one binding gives. A\n * policy may have very many wrong tests, and each issue keeps its path.\n */\nconst maxIssues = 100\n\n/** A path that the walk makes only when it needs it, for an issue. */\ntype LazyPath = () => ReadonlyArray<PropertyKey>\n\n/**\n * Puts the path of a node before the paths of its issues. A walk keeps no\n * path for a node with no issue, so a deep and wide condition costs little.\n */\nconst under = (\n\tmemo: Memo,\n\tat: LazyPath,\n\tissues: ReadonlyArray<Issue>,\n): ReadonlyArray<Issue> => {\n\tif (issues.length === 0) {\n\t\treturn issues\n\t}\n\tconst room = maxIssues - memo.issues.count\n\tmemo.issues.count += issues.length\n\tconst kept = Arr.map(Arr.take(issues, Math.max(room, 0)), (issue) => ({\n\t\tpath: [...at(), ...issue.path],\n\t\tissue: issue.issue,\n\t}))\n\tconst first = memo.issues.count > maxIssues && !memo.issues.noted\n\tmemo.issues.noted ||= first\n\treturn first\n\t\t? [\n\t\t\t\t...kept,\n\t\t\t\t{\n\t\t\t\t\tpath: [],\n\t\t\t\t\tissue: `The policy has more problems. The first ${String(maxIssues)} are here.`,\n\t\t\t\t},\n\t\t\t]\n\t\t: kept\n}\n\n/**\n * The issues of a condition. The constructors of the nodes checked the shape\n * of each node, so this checks the names and the types against the domain. A\n * node that the condition uses in many places is checked one time. The nodes\n * it has seen are in a native `Set`, because it must find a node by the node\n * itself: `Equal` compares nodes by structure.\n */\nconst conditionIssues = (\n\tcontext: Context,\n\tnode: Nodes.Node,\n\tat: LazyPath,\n\tseen: Set<Nodes.Node>,\n): ReadonlyArray<Issue> => {\n\tif (seen.has(node)) {\n\t\treturn []\n\t}\n\tseen.add(node)\n\tconst here = (issues: ReadonlyArray<Issue>) => under(context.memo, at, issues)\n\tswitch (node._tag) {\n\t\tcase \"Compare\": {\n\t\t\tconst exists = fieldIssue(context, node.field, [\"field\"])\n\t\t\treturn here(\n\t\t\t\texists.length > 0\n\t\t\t\t\t? exists\n\t\t\t\t\t: operandIssues(\n\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\tnode.field,\n\t\t\t\t\t\t\tnode.op !== \"eq\" && node.op !== \"ne\",\n\t\t\t\t\t\t\tnode.value,\n\t\t\t\t\t\t\t[\"value\"],\n\t\t\t\t\t\t),\n\t\t\t)\n\t\t}\n\t\tcase \"In\": {\n\t\t\tconst exists = fieldIssue(context, node.field, [\"field\"])\n\t\t\treturn here(\n\t\t\t\texists.length > 0\n\t\t\t\t\t? exists\n\t\t\t\t\t: Arr.flatMap(node.values, (operand, index) =>\n\t\t\t\t\t\t\toperandIssues(context, node.field, false, operand, [\n\t\t\t\t\t\t\t\t\"values\",\n\t\t\t\t\t\t\t\tindex,\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t),\n\t\t\t)\n\t\t}\n\t\tcase \"Exists\":\n\t\t\treturn here(fieldIssue(context, node.field, [\"field\"]))\n\t\tcase \"Under\":\n\t\t\treturn here(underIssues(context, node.prefix, []))\n\t\tcase \"And\":\n\t\tcase \"Or\":\n\t\t\treturn Arr.flatMap(node.conditions, (child, index) =>\n\t\t\t\tconditionIssues(\n\t\t\t\t\tcontext,\n\t\t\t\t\tchild,\n\t\t\t\t\t() => [...at(), \"conditions\", index],\n\t\t\t\t\tseen,\n\t\t\t\t),\n\t\t\t)\n\t\tcase \"Not\":\n\t\t\treturn conditionIssues(\n\t\t\t\tcontext,\n\t\t\t\tnode.condition,\n\t\t\t\t() => [...at(), \"condition\"],\n\t\t\t\tseen,\n\t\t\t)\n\t\tdefault:\n\t\t\treturn []\n\t}\n}\n\nconst hasAction = (\n\tdescriptor: Resource.Descriptor,\n\tactions: ReadonlyArray<string>,\n): boolean =>\n\tactions.includes(\"*\") ||\n\tArr.some(actions, (action) => descriptor.actions.includes(action))\n\n/**\n * Checks one rule against a domain. It gives one issue for each problem. `at`\n * is the path of the rule, for the paths of the issues.\n */\nexport const ruleIssues = (\n\tdomain: Domain.Any,\n\trule: RuleData,\n\tat: ReadonlyArray<PropertyKey>,\n\tmemo: Memo = makeMemo(),\n): ReadonlyArray<Issue> => {\n\tconst all = rule.resources.includes(\"*\")\n\t// Each kind is checked one time, also when the list names it again.\n\tconst names = Arr.dedupe(Arr.filter(rule.resources, (kind) => kind !== \"*\"))\n\tconst kinds = Array.from(HashMap.keys(domain.resources))\n\tconst named = Arr.flatMap(names, (kind) =>\n\t\tOption.toArray(HashMap.get(domain.resources, kind)),\n\t)\n\tconst known = all ? Array.from(HashMap.values(domain.resources)) : named\n\t// The rule never runs on a kind without one of its actions, so the types\n\t// of its tests are checked only on the kinds with one.\n\tconst applicable = Arr.filter(named, (descriptor) =>\n\t\thasAction(descriptor, rule.actions),\n\t)\n\tconst context: Context = {\n\t\tdomain,\n\t\tmemo,\n\t\tall,\n\t\tnamed,\n\t\tapplicable,\n\t\tpaths: all\n\t\t\t? Arr.filter(known, (descriptor) => hasAction(descriptor, rule.actions))\n\t\t\t: applicable,\n\t}\n\tconst actions = Arr.dedupe(\n\t\tArr.flatMap(known, (descriptor) => descriptor.actions),\n\t)\n\treturn [\n\t\t...Arr.map(\n\t\t\tArr.filter(names, (kind) => !HashMap.has(domain.resources, kind)),\n\t\t\t(kind): Issue => ({\n\t\t\t\tpath: [...at, \"resources\"],\n\t\t\t\tissue: suggestIn(\n\t\t\t\t\tmemo,\n\t\t\t\t\t`There is no resource with the kind \"${kind}\"`,\n\t\t\t\t\tkind,\n\t\t\t\t\t\"~kinds\",\n\t\t\t\t\t() => kinds,\n\t\t\t\t),\n\t\t\t}),\n\t\t),\n\t\t...Arr.map(\n\t\t\tArr.filter(\n\t\t\t\trule.actions,\n\t\t\t\t(action) => action !== \"*\" && !actions.includes(action),\n\t\t\t),\n\t\t\t(action): Issue => ({\n\t\t\t\tpath: [...at, \"actions\"],\n\t\t\t\tissue: suggestIn(\n\t\t\t\t\tmemo,\n\t\t\t\t\t`The action \"${action}\" is not an action of these resources`,\n\t\t\t\t\taction,\n\t\t\t\t\t`~actions\\u0000${names.join(\",\")}`,\n\t\t\t\t\t() => actions,\n\t\t\t\t),\n\t\t\t}),\n\t\t),\n\t\t...Arr.flatMap(rule.fields ?? [], (field, index) =>\n\t\t\tfield.includes(\"*\")\n\t\t\t\t? patternIssues(memo, known, field, [...at, \"fields\", index])\n\t\t\t\t: fieldIssue(context, field, [...at, \"fields\", index]),\n\t\t),\n\t\t...(rule.when === undefined\n\t\t\t? []\n\t\t\t: Nodes.isNode(rule.when)\n\t\t\t\t? conditionIssues(context, rule.when, () => [...at, \"when\"], new Set())\n\t\t\t\t: [notWhole([...at, \"when\"])]),\n\t]\n}\n\n/** The JSON form of a policy tree, or a policy tree, as the binding reads it. */\ntype TreeNode =\n\t| { readonly _tag: \"Rules\"; readonly rules: ReadonlyArray<RuleData> }\n\t| {\n\t\t\treadonly _tag: \"All\" | \"Any\" | \"FirstOf\"\n\t\t\treadonly policies: ReadonlyArray<TreeNode>\n\t }\n\t| {\n\t\t\treadonly _tag: \"Ceiling\"\n\t\t\treadonly cap: TreeNode\n\t\t\treadonly policy: TreeNode\n\t }\n\n/** Checks each rule of a policy tree against a domain. */\nexport const treeIssues = (\n\tdomain: Domain.Any,\n\troot: TreeNode,\n): ReadonlyArray<Issue> => {\n\t// The rules come out of the tree first, and each one is checked after.\n\t// A check of a condition goes down its levels, so a check inside the walk\n\t// of the tree would go down the levels of both.\n\tconst rulesOf = (\n\t\tnode: TreeNode,\n\t\tpath: ReadonlyArray<PropertyKey>,\n\t\tlevel: number,\n\t): ReadonlyArray<Issue | readonly [RuleData, ReadonlyArray<PropertyKey>]> => {\n\t\tif (level > Limits.policyDepth) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tpath,\n\t\t\t\t\tissue: `A policy tree has more than ${String(Limits.policyDepth)} levels. The most is ${String(Limits.policyDepth)}.`,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tswitch (node._tag) {\n\t\t\tcase \"Rules\":\n\t\t\t\treturn Arr.map(\n\t\t\t\t\tnode.rules,\n\t\t\t\t\t(rule, index) => [rule, [...path, \"rules\", index]] as const,\n\t\t\t\t)\n\t\t\tcase \"All\":\n\t\t\tcase \"Any\":\n\t\t\tcase \"FirstOf\":\n\t\t\t\treturn Arr.flatMap(node.policies, (child, index) =>\n\t\t\t\t\trulesOf(child, [...path, \"policies\", index], level + 1),\n\t\t\t\t)\n\t\t\tcase \"Ceiling\":\n\t\t\t\treturn [\n\t\t\t\t\t...rulesOf(node.cap, [...path, \"cap\"], level + 1),\n\t\t\t\t\t...rulesOf(node.policy, [...path, \"policy\"], level + 1),\n\t\t\t\t]\n\t\t}\n\t}\n\tconst memo = makeMemo()\n\treturn Arr.flatMap(rulesOf(root, [], 1), (found) =>\n\t\tArray.isArray(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AAO,+BAA+B,OAAO,GAAkB,EAAE,uBAAuB,OAAO,GAAkB,EAAE;EACpH,CACD;EAED,QAAQ,KAAK,MAAb;GACC,KAAK,SACJ,OAAO,IAAI,IACV,KAAK,QACJ,MAAM,UAAU,CAAC,MAAM;IAAC,GAAG;IAAM;IAAS;GAAK,CAAC,CAClD;GACD,KAAK;GACL,KAAK;GACL,KAAK,WACJ,OAAO,IAAI,QAAQ,KAAK,WAAW,OAAO,UACzC,QAAQ,OAAO;IAAC,GAAG;IAAM;IAAY;GAAK,GAAG,QAAQ,CAAC,CACvD;GACD,KAAK,WACJ,OAAO,CACN,GAAG,QAAQ,KAAK,KAAK,CAAC,GAAG,MAAM,KAAK,GAAG,QAAQ,CAAC,GAChD,GAAG,QAAQ,KAAK,QAAQ,CAAC,GAAG,MAAM,QAAQ,GAAG,QAAQ,CAAC,CACvD;EACF;CACD;CACA,MAAM,OAAO,SAAS;CACtB,OAAO,IAAI,QAAQ,QAAQ,MAAM,CAAC,GAAG,CAAC,IAAI,UACzC,MAAM,QAAQ,KAAK,IAChB,WAAW,QAAQ,MAAM,IAAI,MAAM,IAAI,IAAI,IAC3C,CAAC,KAAc,CACnB;AACD"}
|
|
1
|
+
{"version":3,"file":"bind.js","names":["Catalog.accepts","Catalog.lookup","Patterns.parse","Patterns.fitsCatalog","Limits.searchSteps","Catalog.anyKinds","Nodes.isNode"],"sources":["../../src/internal/bind.ts"],"sourcesContent":["/**\n * The binding of rules to a domain. It is the one check of a rule, for a rule\n * from the builder, from `Policy.rule`, and from JSON alike. It reads the\n * catalogs of the resources and of the principal, and it gives one issue for\n * each problem, with the path of the problem and, for a name with a mistake,\n * the name that it may mean.\n */\nimport * as Arr from \"effect/Array\"\nimport * as HashMap from \"effect/HashMap\"\nimport * as MutableHashMap from \"effect/MutableHashMap\"\nimport * as Option from \"effect/Option\"\nimport * as Result from \"effect/Result\"\nimport type * as Domain from \"../Domain.ts\"\nimport type * as Resource from \"../Resource.ts\"\nimport * as Catalog from \"./catalog.ts\"\nimport * as Limits from \"./limits.ts\"\nimport * as Nodes from \"./nodes.ts\"\nimport * as Patterns from \"./patterns.ts\"\nimport { withSuggestion } from \"./suggest.ts\"\n\n/** One problem of a rule or a policy, with its path. */\nexport interface Issue {\n\treadonly path: ReadonlyArray<PropertyKey>\n\treadonly issue: string\n}\n\n/** The data of a rule that the binding reads. */\nexport interface RuleData {\n\treadonly actions: ReadonlyArray<string>\n\treadonly resources: ReadonlyArray<string>\n\treadonly when?: unknown\n\treadonly fields?: ReadonlyArray<string>\n}\n\n/**\n * The memo of one binding, for all its rules. A policy may name one wrong\n * field or one pattern in very many places, so the work on each is done one\n * time. It goes away when the binding ends.\n */\ninterface Memo {\n\t/** The suggestion for each name, by the place where it was looked for. */\n\treadonly suggestions: MutableHashMap.MutableHashMap<string, string>\n\t/** If a pattern matches a field of a kind, by the kind and the pattern. */\n\treadonly fits: MutableHashMap.MutableHashMap<string, boolean>\n\t/** The count of the issues of conditions so far. It belongs to one binding. */\n\treadonly issues: { count: number; noted: boolean }\n\t/** The steps of the checks of patterns so far. It belongs to one binding. */\n\treadonly work: { steps: number; noted: boolean }\n}\n\nconst makeMemo = (): Memo => ({\n\tsuggestions: MutableHashMap.empty(),\n\tfits: MutableHashMap.empty(),\n\tissues: { count: 0, noted: false },\n\twork: { steps: 0, noted: false },\n})\n\n/**\n * The most names that one binding makes a suggestion for. A suggestion\n * compares the name with every name of a catalog, so a policy with very many\n * wrong names would take a long time.\n */\nconst maxSuggestions = 32\n\n/** Adds a suggestion to a message, with the memo of the binding. */\nconst suggestIn = (\n\tmemo: Memo,\n\tmessage: string,\n\tname: string,\n\tscope: string,\n\tnames: () => ReadonlyArray<string>,\n): string => {\n\tconst key = `${scope}\\u0000${name}`\n\tconst known = MutableHashMap.get(memo.suggestions, key)\n\tif (Option.isSome(known)) {\n\t\treturn known.value\n\t}\n\tif (MutableHashMap.size(memo.suggestions) >= maxSuggestions) {\n\t\treturn message\n\t}\n\tconst made = withSuggestion(message, name, names())\n\tMutableHashMap.set(memo.suggestions, key, made)\n\treturn made\n}\n\n/** The kinds that a rule may run on, from the view of its checks. */\ninterface Context {\n\treadonly domain: Domain.Any\n\treadonly memo: Memo\n\t/** The rule is for every resource (`\"*\"`). */\n\treadonly all: boolean\n\t/** The resources that the rule names and that the domain has. */\n\treadonly named: ReadonlyArray<Resource.Descriptor>\n\t/** The named resources that have one of the actions of the rule. */\n\treadonly applicable: ReadonlyArray<Resource.Descriptor>\n\t/**\n\t * The resources whose paths a path test may read: every resource with one\n\t * of the actions, for a rule for every resource.\n\t */\n\treadonly paths: ReadonlyArray<Resource.Descriptor>\n}\n\ntype Operand = Nodes.Operand\n\n/**\n * Tests if a field may hold a value of the type of a fixed value. A test with\n * `null` is a test that the field is missing, so `null` always fits. A number\n * fits any field of numbers: a test of an integer field with `1.5` or\n * `Infinity` has a meaning, as `lt` shows.\n */\nconst fitsLiteral = (kinds: Catalog.Kinds, value: unknown): boolean =>\n\tvalue === null ||\n\t(typeof value === \"number\" && kinds.number !== \"none\") ||\n\tCatalog.accepts(kinds, value)\n\n/**\n * Tests if two fields may hold one scalar. A principal field that is `null`\n * or that holds an object is a missing value, and a test with a missing value\n * is false, so only scalars count.\n */\nconst meet = (left: Catalog.Kinds, right: Catalog.Kinds): boolean =>\n\t(left.string && right.string) ||\n\t(left.boolean && right.boolean) ||\n\t(left.number !== \"none\" && right.number !== \"none\") ||\n\tArr.some(left.literals, (value) => Catalog.accepts(right, value)) ||\n\tArr.some(right.literals, (value) => Catalog.accepts(left, value))\n\nconst hasStrings = (kinds: Catalog.Kinds): boolean =>\n\tkinds.string || Arr.some(kinds.literals, (value) => typeof value === \"string\")\n\nconst hasNumbers = (kinds: Catalog.Kinds): boolean =>\n\tkinds.number !== \"none\" ||\n\tArr.some(kinds.literals, (value) => typeof value === \"number\")\n\n/** Tests if a field may hold a value with an order: a number or a string. */\nconst isOrdered = (kinds: Catalog.Kinds): boolean =>\n\thasStrings(kinds) || hasNumbers(kinds)\n\n/** Tests if two fields may hold values of one ordered type. */\nconst orderedMeet = (left: Catalog.Kinds, right: Catalog.Kinds): boolean =>\n\t(hasStrings(left) && hasStrings(right)) ||\n\t(hasNumbers(left) && hasNumbers(right))\n\n/** The texts of the fields of a catalog that have only names, for suggestions. */\nconst namesOf = (catalog: Catalog.Catalog): ReadonlyArray<string> =>\n\tArr.map(\n\t\tArr.filter(catalog.fields, (field) =>\n\t\t\tArr.every(field.path, (segment) => typeof segment === \"string\"),\n\t\t),\n\t\t(field) => field.text,\n\t)\n\n/** The issue of a field that is not a field of every resource of the rule. */\nconst fieldIssue = (\n\tcontext: Context,\n\tfield: string,\n\tat: ReadonlyArray<PropertyKey>,\n): ReadonlyArray<Issue> => {\n\tconst message = `The field \"${field}\" is not a field of every resource of the rule`\n\tif (context.all || context.named.length === 0) {\n\t\treturn [{ path: at, issue: message }]\n\t}\n\tconst without = Arr.filter(\n\t\tcontext.named,\n\t\t(descriptor) => Catalog.lookup(descriptor.catalog, field) === undefined,\n\t)\n\treturn without.length === 0\n\t\t? []\n\t\t: [\n\t\t\t\t{\n\t\t\t\t\tpath: at,\n\t\t\t\t\tissue: suggestIn(context.memo, message, field, without[0]!.kind, () =>\n\t\t\t\t\t\tnamesOf(without[0]!.catalog),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t]\n}\n\n/**\n * The issues of a field pattern: a pattern that does not parse, or that\n * matches no field of the resources of the rule, as a pattern with a mistake\n * in a name does.\n */\nconst patternIssues = (\n\tmemo: Memo,\n\tknown: ReadonlyArray<Resource.Descriptor>,\n\tpattern: string,\n\tat: ReadonlyArray<PropertyKey>,\n): ReadonlyArray<Issue> =>\n\tResult.match(Patterns.parse(pattern), {\n\t\tonFailure: (issue) => [{ path: at, issue }],\n\t\tonSuccess: (parsed) => {\n\t\t\t// A rule with no known resource has an issue for that already.\n\t\t\tconst fits =\n\t\t\t\tknown.length === 0 ||\n\t\t\t\tArr.some(known, (descriptor) => {\n\t\t\t\t\tconst key = `${descriptor.kind}\\u0000${pattern}`\n\t\t\t\t\treturn Option.getOrElse(MutableHashMap.get(memo.fits, key), () => {\n\t\t\t\t\t\t// Each check of a pattern reads the fields of a catalog. The\n\t\t\t\t\t\t// work of one binding has a limit, so very many patterns stop\n\t\t\t\t\t\t// with one issue, and the policy does not load.\n\t\t\t\t\t\tmemo.work.steps +=\n\t\t\t\t\t\t\tdescriptor.catalog.fields.length * Math.max(parsed.length, 1)\n\t\t\t\t\t\tif (memo.work.steps > Limits.searchSteps) {\n\t\t\t\t\t\t\treturn true\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst found = Patterns.fitsCatalog(parsed, descriptor.catalog)\n\t\t\t\t\t\tMutableHashMap.set(memo.fits, key, found)\n\t\t\t\t\t\treturn found\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\tif (memo.work.steps > Limits.searchSteps && !memo.work.noted) {\n\t\t\t\tmemo.work.noted = true\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: at,\n\t\t\t\t\t\tissue: `The field patterns of the policy take more than ${String(Limits.searchSteps)} steps to check. The most is ${String(Limits.searchSteps)}.`,\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t}\n\t\t\treturn fits\n\t\t\t\t? []\n\t\t\t\t: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: at,\n\t\t\t\t\t\t\tissue: `The field pattern \"${pattern}\" matches no field of the resources of the rule`,\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t},\n\t})\n\n/** The fields of the resources that a test of the rule may read. */\nconst fieldsAt = (\n\tcontext: Context,\n\tfield: string,\n): ReadonlyArray<Catalog.Field> =>\n\tArr.flatMap(context.applicable, (descriptor) => {\n\t\tconst found = Catalog.lookup(descriptor.catalog, field)\n\t\treturn found === undefined ? [] : [found]\n\t})\n\n/** The field of the principal that an operand names, or the issue when there is none. */\nconst principalField = (\n\tcontext: Context,\n\tref: string,\n\tat: ReadonlyArray<PropertyKey>,\n): Catalog.Field | Issue => {\n\tconst found = Catalog.lookup(context.domain.principalCatalog, ref)\n\treturn found !== undefined\n\t\t? found\n\t\t: {\n\t\t\t\tpath: at,\n\t\t\t\tissue: suggestIn(\n\t\t\t\t\tcontext.memo,\n\t\t\t\t\t`The principal has no field \"${ref}\"`,\n\t\t\t\t\tref,\n\t\t\t\t\t\"~principal\",\n\t\t\t\t\t() => namesOf(context.domain.principalCatalog),\n\t\t\t\t),\n\t\t\t}\n}\n\nconst isIssue = (value: Catalog.Field | Issue): value is Issue =>\n\t\"issue\" in value\n\n/** The issues of one operand of a test of a field. */\nconst operandIssues = (\n\tcontext: Context,\n\tfield: string,\n\tordered: boolean,\n\toperand: Operand,\n\tat: ReadonlyArray<PropertyKey>,\n): ReadonlyArray<Issue> => {\n\tconst fields = fieldsAt(context, field)\n\tif (operand._tag === \"Literal\") {\n\t\tconst value = operand.value\n\t\tif (ordered && typeof value !== \"string\" && typeof value !== \"number\") {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tpath: at,\n\t\t\t\t\tissue: `The field \"${field}\" has an ordered test with a value that has no order`,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\treturn [\n\t\t\t...(Arr.some(fields, (found) => !fitsLiteral(found.kinds, value))\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: at,\n\t\t\t\t\t\t\tissue: `The field \"${field}\" can not hold the value ${JSON.stringify(value)}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: []),\n\t\t\t...(ordered && Arr.some(fields, (found) => !isOrdered(found.kinds))\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: at,\n\t\t\t\t\t\t\tissue: `The field \"${field}\" has an ordered test with a value that has no order`,\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: []),\n\t\t]\n\t}\n\tconst principal = principalField(context, operand.path, at)\n\tif (isIssue(principal)) {\n\t\treturn [principal]\n\t}\n\treturn [\n\t\t...(Arr.some(fields, (found) => !meet(found.kinds, principal.kinds))\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: at,\n\t\t\t\t\t\tissue: `The field \"${field}\" can not hold a value of the principal field \"${operand.path}\"`,\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: []),\n\t\t...(ordered &&\n\t\tArr.some(fields, (found) => !orderedMeet(found.kinds, principal.kinds))\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: at,\n\t\t\t\t\t\tissue: `The field \"${field}\" has an ordered test with a value that has no order`,\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: []),\n\t]\n}\n\n/**\n * Tests if the path of a resource may start with a prefix: it is as long as\n * the prefix, and each fixed string of the prefix is the string of the path\n * at its place, when the path has a string there.\n */\nconst mayStartWith = (\n\tdescriptor: Resource.Descriptor,\n\tstrings: ReadonlyArray<string | null>,\n): boolean =>\n\t(descriptor.path?.length ?? 0) >= strings.length &&\n\tArr.every(strings, (string, index) => {\n\t\tconst segment = descriptor.path?.[index]\n\t\treturn string === null || typeof segment !== \"string\" || segment === string\n\t})\n\n/** The kinds of the part of the path of a resource at a place. */\nconst pathPartKinds = (\n\tdescriptor: Resource.Descriptor,\n\tindex: number,\n): Catalog.Kinds | string | undefined => {\n\tconst segment = descriptor.path?.[index]\n\treturn segment === undefined || typeof segment === \"string\"\n\t\t? segment\n\t\t: (Catalog.lookup(descriptor.catalog, segment.field)?.kinds ??\n\t\t\t\tCatalog.anyKinds)\n}\n\n/** The issues of the prefix of a path test. */\nconst underIssues = (\n\tcontext: Context,\n\tprefix: ReadonlyArray<Operand>,\n\tat: ReadonlyArray<PropertyKey>,\n): ReadonlyArray<Issue> => {\n\tconst strings = Arr.map(prefix, (operand) =>\n\t\toperand._tag === \"Literal\" && typeof operand.value === \"string\"\n\t\t\t? operand.value\n\t\t\t: null,\n\t)\n\t// The test can match only a path that starts with the fixed strings of\n\t// the prefix, so the other resources are left out.\n\tconst candidates = Arr.filter(context.paths, (descriptor) =>\n\t\tmayStartWith(descriptor, strings),\n\t)\n\treturn Arr.flatMap(prefix, (operand, index): ReadonlyArray<Issue> => {\n\t\tconst place = [...at, \"prefix\", index]\n\t\tif (operand._tag === \"Literal\") {\n\t\t\treturn Arr.some(candidates, (descriptor) => {\n\t\t\t\tconst kinds = pathPartKinds(descriptor, index)\n\t\t\t\treturn typeof kinds === \"object\" && !fitsLiteral(kinds, operand.value)\n\t\t\t})\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: place,\n\t\t\t\t\t\t\tissue: `The path part ${String(index)} can not hold the value ${JSON.stringify(operand.value)}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: []\n\t\t}\n\t\tconst principal = principalField(context, operand.path, place)\n\t\tif (isIssue(principal)) {\n\t\t\treturn [principal]\n\t\t}\n\t\treturn Arr.some(candidates, (descriptor) => {\n\t\t\tconst kinds = pathPartKinds(descriptor, index)\n\t\t\treturn kinds === undefined\n\t\t\t\t? true\n\t\t\t\t: typeof kinds === \"string\"\n\t\t\t\t\t? !Catalog.accepts(principal.kinds, kinds)\n\t\t\t\t\t: !meet(kinds, principal.kinds)\n\t\t})\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: place,\n\t\t\t\t\t\tissue: `The principal field \"${operand.path}\" can not hold a part of the path of the resource`,\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: []\n\t})\n}\n\nconst notWhole = (at: ReadonlyArray<PropertyKey>): Issue => ({\n\tpath: at,\n\tissue: \"The condition is not a whole condition tree\",\n})\n\n/**\n * The most issues that the walk of the conditions of one binding gives. A\n * policy may have very many wrong tests, and each issue keeps its path.\n */\nconst maxIssues = 100\n\n/** A path that the walk makes only when it needs it, for an issue. */\ntype LazyPath = () => ReadonlyArray<PropertyKey>\n\n/**\n * Puts the path of a node before the paths of its issues. A walk keeps no\n * path for a node with no issue, so a deep and wide condition costs little.\n */\nconst under = (\n\tmemo: Memo,\n\tat: LazyPath,\n\tissues: ReadonlyArray<Issue>,\n): ReadonlyArray<Issue> => {\n\tif (issues.length === 0) {\n\t\treturn issues\n\t}\n\tconst room = maxIssues - memo.issues.count\n\tmemo.issues.count += issues.length\n\tconst kept = Arr.map(Arr.take(issues, Math.max(room, 0)), (issue) => ({\n\t\tpath: [...at(), ...issue.path],\n\t\tissue: issue.issue,\n\t}))\n\tconst first = memo.issues.count > maxIssues && !memo.issues.noted\n\tmemo.issues.noted ||= first\n\treturn first\n\t\t? [\n\t\t\t\t...kept,\n\t\t\t\t{\n\t\t\t\t\tpath: [],\n\t\t\t\t\tissue: `The policy has more problems. The first ${String(maxIssues)} are here.`,\n\t\t\t\t},\n\t\t\t]\n\t\t: kept\n}\n\n/**\n * The issues of a condition. The constructors of the nodes checked the shape\n * of each node, so this checks the names and the types against the domain. A\n * node that the condition uses in many places is checked one time. The nodes\n * it has seen are in a native `Set`, because it must find a node by the node\n * itself: `Equal` compares nodes by structure.\n */\nconst conditionIssues = (\n\tcontext: Context,\n\tnode: Nodes.Node,\n\tat: LazyPath,\n\tseen: Set<Nodes.Node>,\n): ReadonlyArray<Issue> => {\n\tif (seen.has(node)) {\n\t\treturn []\n\t}\n\tseen.add(node)\n\tconst here = (issues: ReadonlyArray<Issue>) => under(context.memo, at, issues)\n\tswitch (node._tag) {\n\t\tcase \"Compare\": {\n\t\t\tconst exists = fieldIssue(context, node.field, [\"field\"])\n\t\t\treturn here(\n\t\t\t\texists.length > 0\n\t\t\t\t\t? exists\n\t\t\t\t\t: operandIssues(\n\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\tnode.field,\n\t\t\t\t\t\t\tnode.op !== \"eq\" && node.op !== \"ne\",\n\t\t\t\t\t\t\tnode.value,\n\t\t\t\t\t\t\t[\"value\"],\n\t\t\t\t\t\t),\n\t\t\t)\n\t\t}\n\t\tcase \"In\": {\n\t\t\tconst exists = fieldIssue(context, node.field, [\"field\"])\n\t\t\treturn here(\n\t\t\t\texists.length > 0\n\t\t\t\t\t? exists\n\t\t\t\t\t: Arr.flatMap(node.values, (operand, index) =>\n\t\t\t\t\t\t\toperandIssues(context, node.field, false, operand, [\n\t\t\t\t\t\t\t\t\"values\",\n\t\t\t\t\t\t\t\tindex,\n\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t),\n\t\t\t)\n\t\t}\n\t\tcase \"Exists\":\n\t\t\treturn here(fieldIssue(context, node.field, [\"field\"]))\n\t\tcase \"Under\":\n\t\t\treturn here(underIssues(context, node.prefix, []))\n\t\tcase \"And\":\n\t\tcase \"Or\":\n\t\t\treturn Arr.flatMap(node.conditions, (child, index) =>\n\t\t\t\tconditionIssues(\n\t\t\t\t\tcontext,\n\t\t\t\t\tchild,\n\t\t\t\t\t() => [...at(), \"conditions\", index],\n\t\t\t\t\tseen,\n\t\t\t\t),\n\t\t\t)\n\t\tcase \"Not\":\n\t\t\treturn conditionIssues(\n\t\t\t\tcontext,\n\t\t\t\tnode.condition,\n\t\t\t\t() => [...at(), \"condition\"],\n\t\t\t\tseen,\n\t\t\t)\n\t\tdefault:\n\t\t\treturn []\n\t}\n}\n\nconst hasAction = (\n\tdescriptor: Resource.Descriptor,\n\tactions: ReadonlyArray<string>,\n): boolean =>\n\tactions.includes(\"*\") ||\n\tArr.some(actions, (action) => descriptor.actions.includes(action))\n\n/**\n * Checks one rule against a domain. It gives one issue for each problem. `at`\n * is the path of the rule, for the paths of the issues.\n */\nexport const ruleIssues = (\n\tdomain: Domain.Any,\n\trule: RuleData,\n\tat: ReadonlyArray<PropertyKey>,\n\tmemo: Memo = makeMemo(),\n): ReadonlyArray<Issue> => {\n\tconst all = rule.resources.includes(\"*\")\n\t// Each kind is checked one time, also when the list names it again.\n\tconst names = Arr.dedupe(Arr.filter(rule.resources, (kind) => kind !== \"*\"))\n\tconst kinds = Array.from(HashMap.keys(domain.resources))\n\tconst named = Arr.flatMap(names, (kind) =>\n\t\tOption.toArray(HashMap.get(domain.resources, kind)),\n\t)\n\tconst known = all ? Array.from(HashMap.values(domain.resources)) : named\n\t// The rule never runs on a kind without one of its actions, so the types\n\t// of its tests are checked only on the kinds with one.\n\tconst applicable = Arr.filter(named, (descriptor) =>\n\t\thasAction(descriptor, rule.actions),\n\t)\n\tconst context: Context = {\n\t\tdomain,\n\t\tmemo,\n\t\tall,\n\t\tnamed,\n\t\tapplicable,\n\t\tpaths: all\n\t\t\t? Arr.filter(known, (descriptor) => hasAction(descriptor, rule.actions))\n\t\t\t: applicable,\n\t}\n\tconst actions = Arr.dedupe(\n\t\tArr.flatMap(known, (descriptor) => descriptor.actions),\n\t)\n\treturn [\n\t\t...Arr.map(\n\t\t\tArr.filter(names, (kind) => !HashMap.has(domain.resources, kind)),\n\t\t\t(kind): Issue => ({\n\t\t\t\tpath: [...at, \"resources\"],\n\t\t\t\tissue: suggestIn(\n\t\t\t\t\tmemo,\n\t\t\t\t\t`There is no resource with the kind \"${kind}\"`,\n\t\t\t\t\tkind,\n\t\t\t\t\t\"~kinds\",\n\t\t\t\t\t() => kinds,\n\t\t\t\t),\n\t\t\t}),\n\t\t),\n\t\t...Arr.map(\n\t\t\tArr.filter(\n\t\t\t\trule.actions,\n\t\t\t\t(action) => action !== \"*\" && !actions.includes(action),\n\t\t\t),\n\t\t\t(action): Issue => ({\n\t\t\t\tpath: [...at, \"actions\"],\n\t\t\t\tissue: suggestIn(\n\t\t\t\t\tmemo,\n\t\t\t\t\t`The action \"${action}\" is not an action of these resources`,\n\t\t\t\t\taction,\n\t\t\t\t\t`~actions\\u0000${names.join(\",\")}`,\n\t\t\t\t\t() => actions,\n\t\t\t\t),\n\t\t\t}),\n\t\t),\n\t\t...Arr.flatMap(rule.fields ?? [], (field, index) =>\n\t\t\tfield.includes(\"*\")\n\t\t\t\t? patternIssues(memo, known, field, [...at, \"fields\", index])\n\t\t\t\t: fieldIssue(context, field, [...at, \"fields\", index]),\n\t\t),\n\t\t...(rule.when === undefined\n\t\t\t? []\n\t\t\t: Nodes.isNode(rule.when)\n\t\t\t\t? conditionIssues(context, rule.when, () => [...at, \"when\"], new Set())\n\t\t\t\t: [notWhole([...at, \"when\"])]),\n\t]\n}\n\n/** The JSON form of a policy tree, or a policy tree, as the binding reads it. */\ntype TreeNode =\n\t| { readonly _tag: \"Rules\"; readonly rules: ReadonlyArray<RuleData> }\n\t| {\n\t\t\treadonly _tag: \"All\" | \"Any\" | \"FirstOf\"\n\t\t\treadonly policies: ReadonlyArray<TreeNode>\n\t }\n\t| {\n\t\t\treadonly _tag: \"Ceiling\"\n\t\t\treadonly cap: TreeNode\n\t\t\treadonly policy: TreeNode\n\t }\n\n/** Checks each rule of a policy tree against a domain. */\nexport const treeIssues = (\n\tdomain: Domain.Any,\n\troot: TreeNode,\n): ReadonlyArray<Issue> => {\n\t// The rules come out of the tree first, and each one is checked after.\n\t// A check of a condition goes down its levels, so a check inside the walk\n\t// of the tree would go down the levels of both.\n\tconst rulesOf = (\n\t\tnode: TreeNode,\n\t\tpath: ReadonlyArray<PropertyKey>,\n\t\tlevel: number,\n\t): ReadonlyArray<Issue | readonly [RuleData, ReadonlyArray<PropertyKey>]> => {\n\t\tif (level > Limits.policyDepth) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tpath,\n\t\t\t\t\tissue: `A policy tree has more than ${String(Limits.policyDepth)} levels. The most is ${String(Limits.policyDepth)}.`,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tswitch (node._tag) {\n\t\t\tcase \"Rules\":\n\t\t\t\treturn Arr.map(\n\t\t\t\t\tnode.rules,\n\t\t\t\t\t(rule, index) => [rule, [...path, \"rules\", index]] as const,\n\t\t\t\t)\n\t\t\tcase \"All\":\n\t\t\tcase \"Any\":\n\t\t\tcase \"FirstOf\":\n\t\t\t\treturn Arr.flatMap(node.policies, (child, index) =>\n\t\t\t\t\trulesOf(child, [...path, \"policies\", index], level + 1),\n\t\t\t\t)\n\t\t\tcase \"Ceiling\":\n\t\t\t\treturn [\n\t\t\t\t\t...rulesOf(node.cap, [...path, \"cap\"], level + 1),\n\t\t\t\t\t...rulesOf(node.policy, [...path, \"policy\"], level + 1),\n\t\t\t\t]\n\t\t}\n\t}\n\tconst memo = makeMemo()\n\treturn Arr.flatMap(rulesOf(root, [], 1), (found) =>\n\t\tArray.isArray(found)\n\t\t\t? ruleIssues(domain, found[0], found[1], memo)\n\t\t\t: [found as Issue],\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkDA,MAAM,kBAAwB;CAC7B,aAAa,eAAe,MAAM;CAClC,MAAM,eAAe,MAAM;CAC3B,QAAQ;EAAE,OAAO;EAAG,OAAO;CAAM;CACjC,MAAM;EAAE,OAAO;EAAG,OAAO;CAAM;AAChC;;;;;;AAOA,MAAM,iBAAiB;;AAGvB,MAAM,aACL,MACA,SACA,MACA,OACA,UACY;CACZ,MAAM,MAAM,GAAG,MAAM,QAAQ;CAC7B,MAAM,QAAQ,eAAe,IAAI,KAAK,aAAa,GAAG;CACtD,IAAI,OAAO,OAAO,KAAK,GACtB,OAAO,MAAM;CAEd,IAAI,eAAe,KAAK,KAAK,WAAW,KAAK,gBAC5C,OAAO;CAER,MAAM,OAAO,eAAe,SAAS,MAAM,MAAM,CAAC;CAClD,eAAe,IAAI,KAAK,aAAa,KAAK,IAAI;CAC9C,OAAO;AACR;;;;;;;AA2BA,MAAM,eAAe,OAAsB,UAC1C,UAAU,QACT,OAAO,UAAU,YAAY,MAAM,WAAW,UAC/CA,QAAgB,OAAO,KAAK;;;;;;AAO7B,MAAM,QAAQ,MAAqB,UACjC,KAAK,UAAU,MAAM,UACrB,KAAK,WAAW,MAAM,WACtB,KAAK,WAAW,UAAU,MAAM,WAAW,UAC5C,IAAI,KAAK,KAAK,WAAW,UAAUA,QAAgB,OAAO,KAAK,CAAC,KAChE,IAAI,KAAK,MAAM,WAAW,UAAUA,QAAgB,MAAM,KAAK,CAAC;AAEjE,MAAM,cAAc,UACnB,MAAM,UAAU,IA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IAAI,UACzC,MAAM,QAAQ,KAAK,IAChB,WAAW,QAAQ,MAAM,IAAI,MAAM,IAAI,IAAI,IAC3C,CAAC,KAAc,CACnB;AACD"}
|
package/package.json
CHANGED
package/src/Condition.ts
CHANGED
|
@@ -224,32 +224,24 @@ export interface Opaque<out E = never, out R = never> {
|
|
|
224
224
|
}
|
|
225
225
|
|
|
226
226
|
/**
|
|
227
|
-
* The error type of the predicates of a mark `X`. A mark that
|
|
228
|
-
*
|
|
227
|
+
* The error type of the predicates of a mark `X`. A mark that is not an
|
|
228
|
+
* {@link Opaque}, as `unknown` or `object`, may have any error.
|
|
229
229
|
*
|
|
230
230
|
* @stability stable
|
|
231
231
|
* @category utility types
|
|
232
232
|
* @since 2.0.0
|
|
233
233
|
*/
|
|
234
|
-
export type ErrorOf<X> =
|
|
235
|
-
? unknown
|
|
236
|
-
: X extends Opaque<infer E, infer _R>
|
|
237
|
-
? E
|
|
238
|
-
: never
|
|
234
|
+
export type ErrorOf<X> = X extends Opaque<infer E, infer _R> ? E : unknown
|
|
239
235
|
|
|
240
236
|
/**
|
|
241
|
-
* The service type of the predicates of a mark `X`. A mark that
|
|
242
|
-
*
|
|
237
|
+
* The service type of the predicates of a mark `X`. A mark that is not an
|
|
238
|
+
* {@link Opaque}, as `unknown` or `object`, may need any service.
|
|
243
239
|
*
|
|
244
240
|
* @stability stable
|
|
245
241
|
* @category utility types
|
|
246
242
|
* @since 2.0.0
|
|
247
243
|
*/
|
|
248
|
-
export type ServicesOf<X> =
|
|
249
|
-
? unknown
|
|
250
|
-
: X extends Opaque<infer _E, infer R>
|
|
251
|
-
? R
|
|
252
|
-
: never
|
|
244
|
+
export type ServicesOf<X> = X extends Opaque<infer _E, infer R> ? R : unknown
|
|
253
245
|
|
|
254
246
|
/**
|
|
255
247
|
* The mark `X` with no services.
|
|
@@ -258,11 +250,8 @@ export type ServicesOf<X> = unknown extends X
|
|
|
258
250
|
* @category utility types
|
|
259
251
|
* @since 2.0.0
|
|
260
252
|
*/
|
|
261
|
-
export type Provided<X> =
|
|
262
|
-
? Opaque<unknown>
|
|
263
|
-
: X extends Opaque<infer E, infer _R>
|
|
264
|
-
? Opaque<E>
|
|
265
|
-
: never
|
|
253
|
+
export type Provided<X> =
|
|
254
|
+
X extends Opaque<infer E, infer _R> ? Opaque<E> : Opaque<unknown>
|
|
266
255
|
|
|
267
256
|
/**
|
|
268
257
|
* What the predicates of a condition read: a resource value of the type `V`
|
|
@@ -366,14 +355,15 @@ type FieldPathInternal<
|
|
|
366
355
|
> = [Depth] extends [never]
|
|
367
356
|
? never
|
|
368
357
|
: {
|
|
369
|
-
|
|
370
|
-
|
|
358
|
+
// A record with number keys has number keys, as `counts.1`.
|
|
359
|
+
[K in keyof T & (string | number)]-?: PathsOf<
|
|
360
|
+
`${K}`,
|
|
371
361
|
NonNullable<T[K]>,
|
|
372
362
|
Depth,
|
|
373
363
|
Arrays,
|
|
374
364
|
Parents
|
|
375
365
|
>
|
|
376
|
-
}[keyof T & string]
|
|
366
|
+
}[keyof T & (string | number)]
|
|
377
367
|
|
|
378
368
|
/**
|
|
379
369
|
* The paths of one field `K` with the values `V`. Each kind of value in `V`
|
|
@@ -387,8 +377,9 @@ type PathsOf<
|
|
|
387
377
|
Arrays extends boolean,
|
|
388
378
|
Parents extends boolean,
|
|
389
379
|
> =
|
|
390
|
-
// A field that is only ever `null` or missing is a field too
|
|
391
|
-
|
|
380
|
+
// A field that is only ever `null` or missing is a field too, and so is a
|
|
381
|
+
// field that may hold any value, as one of `Schema.Unknown` may.
|
|
382
|
+
| ([V] extends [never] ? K : {} extends V ? K : never)
|
|
392
383
|
| ([Extract<V, Leaf | Whole>] extends [never] ? never : K)
|
|
393
384
|
| ([Extract<V, ReadonlyArray<unknown>>] extends [never]
|
|
394
385
|
? never
|
|
@@ -419,7 +410,9 @@ type ObjectPaths<
|
|
|
419
410
|
: Arrays extends true
|
|
420
411
|
? string extends keyof O
|
|
421
412
|
? K
|
|
422
|
-
:
|
|
413
|
+
: number extends keyof O
|
|
414
|
+
? K
|
|
415
|
+
: never
|
|
423
416
|
: never)
|
|
424
417
|
| `${K}.${FieldPathInternal<O, PreviousDepth[Depth], Arrays, Parents>}`
|
|
425
418
|
|
package/src/Policy.ts
CHANGED
|
@@ -778,8 +778,10 @@ export type ResidualReads<D, K> = Condition.Reads<
|
|
|
778
778
|
/**
|
|
779
779
|
* Gives the condition on resource values for which the policy allows a
|
|
780
780
|
* request. It has no principal fields and no `Under` nodes, so you can give it
|
|
781
|
-
* to `Condition.fold`. It is
|
|
782
|
-
*
|
|
781
|
+
* to `Condition.fold`. It is made smaller, so it is often `True` or `False`
|
|
782
|
+
* when the answer does not depend on the value, but it does no search: a
|
|
783
|
+
* condition that is true for every value may stay a test. To know if the
|
|
784
|
+
* policy allows every value, or some value, use {@link coverage}.
|
|
783
785
|
*
|
|
784
786
|
* With a scope (`within`), the condition is the scope and the residual
|
|
785
787
|
* together, so it is false for every value outside the scope. Give the policy
|
|
@@ -93,19 +93,29 @@ type AnyTarget = {
|
|
|
93
93
|
|
|
94
94
|
/**
|
|
95
95
|
* A cache key for a principal. Two keys are equal when they have the same
|
|
96
|
-
* text, so two principals with the same key share one policy.
|
|
97
|
-
*
|
|
98
|
-
*
|
|
96
|
+
* text, so two principals with the same key share one policy. A key from the
|
|
97
|
+
* JSON form also needs equal decoded principals: a Schema may make data when
|
|
98
|
+
* it decodes, as `expired` from a time, so one text may give two principals.
|
|
99
|
+
* The key also keeps the principal, so the cache can load its policy. A plain
|
|
100
|
+
* `Data` value can not do all this, so the key gives its own equality with
|
|
101
|
+
* `Equal.Equal`.
|
|
99
102
|
*/
|
|
100
103
|
class PrincipalKey implements Equal.Equal {
|
|
101
104
|
readonly principal: object
|
|
102
105
|
readonly text: string
|
|
103
|
-
|
|
106
|
+
/** The key is the JSON form, so the decoded principals must be equal too. */
|
|
107
|
+
readonly exact: boolean
|
|
108
|
+
constructor(principal: object, text: string, exact: boolean) {
|
|
104
109
|
this.principal = principal
|
|
105
110
|
this.text = text
|
|
111
|
+
this.exact = exact
|
|
106
112
|
}
|
|
107
113
|
[Equal.symbol](that: unknown): boolean {
|
|
108
|
-
return
|
|
114
|
+
return (
|
|
115
|
+
that instanceof PrincipalKey &&
|
|
116
|
+
that.text === this.text &&
|
|
117
|
+
(!this.exact || Equal.equals(that.principal, this.principal))
|
|
118
|
+
)
|
|
109
119
|
}
|
|
110
120
|
[Hash.symbol](): number {
|
|
111
121
|
return Hash.string(this.text)
|
|
@@ -160,7 +170,7 @@ const jsonKey = (
|
|
|
160
170
|
onFailure: () => undefined,
|
|
161
171
|
onSuccess: (decoded) =>
|
|
162
172
|
Equal.equals(decoded, principal)
|
|
163
|
-
? new PrincipalKey(decoded as object, text)
|
|
173
|
+
? new PrincipalKey(decoded as object, text, true)
|
|
164
174
|
: undefined,
|
|
165
175
|
})
|
|
166
176
|
},
|
|
@@ -226,7 +236,7 @@ export const makeLayer = (
|
|
|
226
236
|
const text = custom(principal)
|
|
227
237
|
return text === undefined
|
|
228
238
|
? undefined
|
|
229
|
-
: new PrincipalKey(canonical?.principal ?? principal, text)
|
|
239
|
+
: new PrincipalKey(canonical?.principal ?? principal, text, false)
|
|
230
240
|
}
|
|
231
241
|
return Layer.effect(
|
|
232
242
|
service,
|
package/src/internal/bind.ts
CHANGED
|
@@ -44,12 +44,15 @@ interface Memo {
|
|
|
44
44
|
readonly fits: MutableHashMap.MutableHashMap<string, boolean>
|
|
45
45
|
/** The count of the issues of conditions so far. It belongs to one binding. */
|
|
46
46
|
readonly issues: { count: number; noted: boolean }
|
|
47
|
+
/** The steps of the checks of patterns so far. It belongs to one binding. */
|
|
48
|
+
readonly work: { steps: number; noted: boolean }
|
|
47
49
|
}
|
|
48
50
|
|
|
49
51
|
const makeMemo = (): Memo => ({
|
|
50
52
|
suggestions: MutableHashMap.empty(),
|
|
51
53
|
fits: MutableHashMap.empty(),
|
|
52
54
|
issues: { count: 0, noted: false },
|
|
55
|
+
work: { steps: 0, noted: false },
|
|
53
56
|
})
|
|
54
57
|
|
|
55
58
|
/**
|
|
@@ -186,24 +189,44 @@ const patternIssues = (
|
|
|
186
189
|
): ReadonlyArray<Issue> =>
|
|
187
190
|
Result.match(Patterns.parse(pattern), {
|
|
188
191
|
onFailure: (issue) => [{ path: at, issue }],
|
|
189
|
-
onSuccess: (parsed) =>
|
|
192
|
+
onSuccess: (parsed) => {
|
|
190
193
|
// A rule with no known resource has an issue for that already.
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
194
|
+
const fits =
|
|
195
|
+
known.length === 0 ||
|
|
196
|
+
Arr.some(known, (descriptor) => {
|
|
197
|
+
const key = `${descriptor.kind}\u0000${pattern}`
|
|
198
|
+
return Option.getOrElse(MutableHashMap.get(memo.fits, key), () => {
|
|
199
|
+
// Each check of a pattern reads the fields of a catalog. The
|
|
200
|
+
// work of one binding has a limit, so very many patterns stop
|
|
201
|
+
// with one issue, and the policy does not load.
|
|
202
|
+
memo.work.steps +=
|
|
203
|
+
descriptor.catalog.fields.length * Math.max(parsed.length, 1)
|
|
204
|
+
if (memo.work.steps > Limits.searchSteps) {
|
|
205
|
+
return true
|
|
206
|
+
}
|
|
207
|
+
const found = Patterns.fitsCatalog(parsed, descriptor.catalog)
|
|
208
|
+
MutableHashMap.set(memo.fits, key, found)
|
|
209
|
+
return found
|
|
210
|
+
})
|
|
198
211
|
})
|
|
199
|
-
|
|
212
|
+
if (memo.work.steps > Limits.searchSteps && !memo.work.noted) {
|
|
213
|
+
memo.work.noted = true
|
|
214
|
+
return [
|
|
215
|
+
{
|
|
216
|
+
path: at,
|
|
217
|
+
issue: `The field patterns of the policy take more than ${String(Limits.searchSteps)} steps to check. The most is ${String(Limits.searchSteps)}.`,
|
|
218
|
+
},
|
|
219
|
+
]
|
|
220
|
+
}
|
|
221
|
+
return fits
|
|
200
222
|
? []
|
|
201
223
|
: [
|
|
202
224
|
{
|
|
203
225
|
path: at,
|
|
204
226
|
issue: `The field pattern "${pattern}" matches no field of the resources of the rule`,
|
|
205
227
|
},
|
|
206
|
-
]
|
|
228
|
+
]
|
|
229
|
+
},
|
|
207
230
|
})
|
|
208
231
|
|
|
209
232
|
/** The fields of the resources that a test of the rule may read. */
|