foldkit-guard 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +209 -44
  2. package/dist/agent.d.mts +1 -1
  3. package/dist/agent.mjs +1 -1
  4. package/dist/{attach-CRCF5XHS.mjs → attach-CEGlbWu5.mjs} +17 -2
  5. package/dist/attach-CEGlbWu5.mjs.map +1 -0
  6. package/dist/{attach-BepaL930.d.mts → attach-DPgyv78F.d.mts} +83 -8
  7. package/dist/attach-DPgyv78F.d.mts.map +1 -0
  8. package/dist/{condition-Dx54lL7v.mjs → condition-dNSbUHzE.mjs} +98 -10
  9. package/dist/condition-dNSbUHzE.mjs.map +1 -0
  10. package/dist/drizzle.d.mts +1 -1
  11. package/dist/drizzle.mjs +8 -6
  12. package/dist/drizzle.mjs.map +1 -1
  13. package/dist/index.d.mts +1 -1
  14. package/dist/index.mjs +34 -17
  15. package/dist/index.mjs.map +1 -1
  16. package/dist/may-DprCmMgK.mjs +200 -0
  17. package/dist/may-DprCmMgK.mjs.map +1 -0
  18. package/dist/{me-BYpuVqJE.mjs → me-C-gX1paZ.mjs} +3 -3
  19. package/dist/{me-BYpuVqJE.mjs.map → me-C-gX1paZ.mjs.map} +1 -1
  20. package/dist/media.d.mts +1 -1
  21. package/dist/{placed-BvdNmZJu.mjs → placed-CGyo-NRR.mjs} +2 -2
  22. package/dist/{placed-BvdNmZJu.mjs.map → placed-CGyo-NRR.mjs.map} +1 -1
  23. package/dist/server.d.mts +50 -17
  24. package/dist/server.d.mts.map +1 -1
  25. package/dist/server.mjs +264 -145
  26. package/dist/server.mjs.map +1 -1
  27. package/dist/sync.d.mts +5 -3
  28. package/dist/sync.d.mts.map +1 -1
  29. package/dist/sync.mjs +18 -8
  30. package/dist/sync.mjs.map +1 -1
  31. package/package.json +19 -18
  32. package/dist/attach-BepaL930.d.mts.map +0 -1
  33. package/dist/attach-CRCF5XHS.mjs.map +0 -1
  34. package/dist/condition-Dx54lL7v.mjs.map +0 -1
  35. package/dist/may-DzCAt_5M.mjs +0 -75
  36. package/dist/may-DzCAt_5M.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Who may do what, declared once on the domain.\n *\n * A guard set names its guards once, in shared code the client imports too.\n * A **principal guard** is declared by name and implemented only on the\n * server (`G.implement`), so its logic never ships. A **row guard** is an\n * `Expr` over one Entity's fields with the principal's fields as inputs: data,\n * which the SQL compiler and `evaluate` both run. See `guard-DESIGN.md`.\n */\nimport { Context, Effect, Match, Option, Schema } from 'effect'\nimport { Attaching, attached, type InteractionKey } from './attach.js'\nimport {\n deciding,\n readsPrincipal,\n type Condition,\n type MemberRead,\n type RowRule,\n} from './condition.js'\nimport { May } from './may.js'\nimport { me } from './me.js'\nimport { providedFrom } from './origin.js'\nimport {\n Expr,\n Operators,\n Query,\n evaluate,\n type AnyEntity,\n type MemoryOperators,\n type AnyQuery,\n type InputExpr,\n type Predicate,\n} from 'foldkit-entity'\n\n/** A guard's answer: allowed, refused, or refused with a sentence the caller may read. */\nexport type Decision = boolean | { readonly allowed: false; readonly reason: string }\n\n/** What a principal guard is asked about. */\nexport interface About {\n /** The interaction attempted: `Read`, `Update`, or one the application names. */\n readonly interaction: string\n}\n\n/**\n * The principal's fields as a row guard's body sees them: each an input named\n * `principal.<field>`, typed as the field. A body is built once, so it holds\n * these placeholders and never a value: branching on one is a type error.\n */\nexport type Placeholders<User> = {\n readonly [K in keyof User & string]: InputExpr<User[K]>\n}\n\n/** What `guard.principal()` declares: a name whose body the server supplies. */\nexport interface PrincipalSpec {\n readonly _tag: 'PrincipalSpec'\n}\n\n/** What `guard.row(entity, body)` declares: a predicate over one Entity's rows. */\nexport interface RowSpec<E extends AnyEntity> {\n readonly _tag: 'RowSpec'\n readonly entity: E\n readonly body: Predicate\n}\n\ntype AnySpec = PrincipalSpec | RowSpec<AnyEntity>\n\n/**\n * The principal a guard is for, kept in the type so a guard of one principal\n * cannot stand where another's is wanted. A function type, so it is invariant.\n */\ninterface ForPrincipal<User> {\n readonly '~principal'?: (user: User) => User\n}\n\n/** A guard whose body lives on the server, asked of the principal alone. */\nexport interface PrincipalGuard<User, Set extends string = string> extends ForPrincipal<User> {\n readonly _tag: 'PrincipalGuard'\n readonly name: string\n /** The name of the guard set it belongs to. */\n readonly set: Set\n}\n\n/** A guard over the rows of `E`: its predicate, and the query that asks it of rows. */\nexport interface RowGuard<\n User,\n E extends AnyEntity,\n Set extends string = string,\n> extends ForPrincipal<User> {\n readonly _tag: 'RowGuard'\n readonly name: string\n readonly set: Set\n readonly entity: E\n readonly body: Predicate\n /** `from(entity).where(body)`, for an interpreter that runs queries. */\n readonly query: AnyQuery\n}\n\nexport type AnyGuard<User> = PrincipalGuard<User> | RowGuard<User, AnyEntity>\n\ntype GuardOf<User, Set extends string, S> =\n S extends RowSpec<infer E> ? RowGuard<User, E, Set> : PrincipalGuard<User, Set>\n\n/** The keys of a spec record that are principal guards: what `implement` must supply. */\ntype PrincipalKeys<S> = { [K in keyof S]: S[K] extends PrincipalSpec ? K : never }[keyof S]\n\n/** A principal guard's body, on the server. */\nexport type Body<User, R = never> = (\n principal: Option.Option<User>,\n about: About,\n) => Decision | Effect.Effect<Decision, never, R>\n\n/** Names a guard set reserves for itself, which no guard may take. */\nconst reserved = [\n 'name',\n 'schema',\n 'Principal',\n 'key',\n 'unguarded',\n 'inputOf',\n 'implement',\n] as const\ntype Reserved = (typeof reserved)[number]\n\n/** Who is asking, for one guard set: a visitor is `none`. */\nexport interface PrincipalOf<Name extends string> {\n readonly '~guardSet': Name\n}\n\n/** The guard set of one application, as `Guards.declare` returns it. */\nexport type GuardSet<Name extends string, User, S> = {\n readonly [K in keyof S]: GuardOf<User, Name, S[K]>\n} & {\n readonly name: Name\n /** The principal's schema, whose fields the row guards read. */\n readonly schema: Schema.Codec<User, unknown>\n /** The server's Context key for who is asking. Authentication provides it. */\n readonly Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>\n /** A stable name for the person, whatever their claims: for what is theirs, as a cache's scope. */\n readonly key: (user: User) => string\n readonly unguarded: 'allow' | 'deny'\n /** The principal's fields as row guards' inputs, encoded as stored values are. */\n readonly inputOf: (user: User) => Readonly<Record<string, unknown>>\n /**\n * The bodies of the principal guards: every one, and nothing else. `operators`\n * runs the row guards' primitive operators in memory; `Operators.kernel` when\n * not given.\n */\n readonly implement: <R = never>(\n bodies: { readonly [K in PrincipalKeys<S>]: Body<User, R> },\n options?: { readonly operators?: MemoryOperators | undefined },\n ) => Policy<User, R>\n}\n\n/** The server's half of a guard set: every principal guard's body. */\nexport interface Policy<User, R = never> {\n readonly set: string\n /**\n * How a row guard's primitive operators are run in memory: by `decide`,\n * `Condition.holds` and every guarded server judging a row. Given to\n * `implement`; `Operators.kernel` when not.\n */\n readonly operators: MemoryOperators\n /**\n * Whether `guard` allows `principal`, for a row guard over `row` (its stored,\n * encoded values). A visitor passes no row guard that reads a principal's\n * fields; one over the row alone holds for a visitor too.\n */\n readonly decide: (\n guard: AnyGuard<User>,\n request: {\n readonly principal: Option.Option<User>\n readonly interaction: string\n readonly row?: Readonly<Record<string, unknown>> | undefined\n },\n ) => Effect.Effect<Decision, never, R>\n /**\n * Which rows of `entity` `principal` may read, as a condition over the row\n * with every principal guard already decided. An Entity without guards, or\n * of no set, reads `Always`.\n */\n readonly readable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n ) => Effect.Effect<Condition, never, R>\n /** The read rule of each of `members`, relations included, that has one, decided for `principal`. */\n readonly readMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /**\n * Which rows of `entity` `principal` may write by `interaction` (`Create`,\n * `Update`, `Delete`, or one the application named), as a condition over\n * the row, and what a refusal shows.\n */\n readonly writable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: 'Create' | 'Update' | 'Delete' | InteractionKey,\n ) => Effect.Effect<RowRule, never, R>\n /** The rule of each of `members` that has one for setting it, decided for `principal`. */\n readonly writeMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n interaction: 'Create' | 'Update',\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /** A relation's rule for linking or unlinking a row, when it has one. */\n readonly linkable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n relation: string,\n interaction: 'Link' | 'Unlink',\n ) => Effect.Effect<Option.Option<RowRule>, never, R>\n /** The principal's fields as row guards' inputs; a visitor has none. */\n readonly inputOf: (principal: Option.Option<User>) => Readonly<Record<string, unknown>>\n /**\n * Who the principal is: `declare`'s `key`, the same function as `G.key`,\n * here for a server seam that holds the Policy and not the set. Not\n * `keyOf`, which names a principal by every field, for sharing re-reads.\n */\n readonly key: (user: User) => string\n /**\n * Who is asking, as the rules see it: every field of the principal, encoded,\n * a visitor included. Two requests by one person with the same claims answer\n * alike, so a live hub shares their re-reads; a changed claim is not shared.\n *\n * ```ts\n * RemoteServer.liveHub(sources, { key: Policy.keyOf })\n * ```\n */\n readonly keyOf: (principal: Option.Option<User>) => string\n /**\n * Whether `value` is this set's principal, an `Option` of its schema: for a\n * seam that is handed the principal untyped.\n */\n readonly isPrincipal: (value: unknown) => value is Option.Option<User>\n /**\n * This Policy with services its bodies need provided, such as a membership\n * lookup. The read seams (`GuardDrizzle.visible`, `GuardServer.memory`,\n * `GuardSync`) take a Policy that needs nothing more: a read rule runs inside\n * a read whose requirements are its Source's. Provide what stays put here,\n * once; carry what changes per request in the principal. A seam built from\n * the result counts as built from this Policy: `validate` checks the rules,\n * not the services given them. `GuardSync.authorize` runs bodies\n * synchronously, so what it is given must answer without suspending.\n *\n * ```ts\n * const ReadPolicy = Policy.provide(Context.make(Memberships, memberships))\n * ```\n */\n readonly provide: <Provided extends R>(\n context: Context.Context<Provided>,\n ) => Policy<User, Exclude<R, Provided>>\n}\n\n/** `policy` with `context` provided to every body it runs. */\nconst provided = <User, R, Provided extends R>(\n policy: Policy<User, R>,\n context: Context.Context<Provided>,\n): Policy<User, Exclude<R, Provided>> => {\n const run = <A>(effect: Effect.Effect<A, never, R>) => Effect.provide(effect, context)\n const next: Policy<User, Exclude<R, Provided>> = {\n ...policy,\n decide: (guard, request) => run(policy.decide(guard, request)),\n readable: (entity, principal) => run(policy.readable(entity, principal)),\n readMembers: (entity, principal, members) =>\n run(policy.readMembers(entity, principal, members)),\n writable: (entity, principal, interaction) =>\n run(policy.writable(entity, principal, interaction)),\n writeMembers: (entity, principal, members, interaction) =>\n run(policy.writeMembers(entity, principal, members, interaction)),\n linkable: (entity, principal, relation, interaction) =>\n run(policy.linkable(entity, principal, relation, interaction)),\n provide: more => provided(next, more),\n }\n return providedFrom(next, policy)\n}\n\n/** The builders a guard set's declaration is given, typed by its principal. */\nexport interface Builders<User> {\n /** A guard decided from the principal alone, by a body only the server has. */\n readonly principal: () => PrincipalSpec\n /** A guard over `entity`'s rows: a predicate with the principal's fields as inputs. */\n readonly row: <E extends AnyEntity>(\n entity: E,\n body: (principal: Placeholders<User>) => Predicate,\n ) => RowSpec<E>\n}\n\nconst placeholdersOf = <User>(fields: Schema.Struct.Fields): Placeholders<User> => {\n const inputs: Record<string, InputExpr<unknown>> = {}\n for (const key of Object.keys(fields)) {\n inputs[key] = Expr.input(\n `principal.${key}`,\n fields[key] as unknown as Schema.Codec<unknown, unknown>,\n )\n }\n return Object.freeze(inputs) as Placeholders<User>\n}\n\nexport { Condition, type MemberRead, type RowRule } from './condition.js'\nexport { May, MaySchema, type MayAnswer } from './may.js'\nexport { ME, type MeEntity } from './me.js'\nexport {\n Interaction,\n type All,\n type AnyRule,\n type Attach,\n type Attachment,\n type Deny,\n type Explain,\n type Inherit,\n type InteractionKey,\n type On,\n type Redact,\n type RuleFor,\n type Surface,\n} from './attach.js'\n\nexport const Guards = {\n ...Attaching,\n /**\n * Adds the `may` member, the server's answer to what a principal may do\n * with a row, after its guards are attached:\n * `TodoFields.pipe(Guards.attach(G, { … }), Guards.may)`.\n */\n may: May.member,\n /**\n * `Me`, the visitor as an Entity: one row, `me`, that everyone reads and no\n * one writes, with `signedIn`, the principal's `key`, and `may` for the\n * interactions named here. Serve it with `GuardServer.me`.\n *\n * ```ts\n * export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })\n * ```\n */\n me,\n /**\n * One application's guards, under `name` (its principal's Context key, and\n * what the matrix prints). `principal` is a `Schema.Struct`: its fields are\n * what a row guard reads, and its codec encodes a principal's values as\n * stored values are encoded.\n *\n * ```ts\n * const G = Guards.declare('Todos', User, guard => ({\n * isAdmin: guard.principal(),\n * isOwner: guard.row(TodoFields, p => Expr.eq(TodoFields.fields.ownerId, p.id)),\n * }), { key: user => user.id })\n * ```\n */\n declare: <\n const Name extends string,\n Fields extends Schema.Struct.Fields,\n const S extends Readonly<Record<string, AnySpec>> & { readonly [K in Reserved]?: never },\n >(\n name: Name,\n principal: Schema.Struct<Fields>,\n build: (guard: Builders<Schema.Struct.Type<Fields>>) => S,\n options: {\n readonly key: (user: Schema.Struct.Type<Fields>) => string\n /**\n * What a surface of a guarded Entity with no rules decides: `'deny'`\n * refuses it, `'allow'` lets everyone. Required, so an open surface is\n * a decision written down; `Guards.matrix` prints it `closed` or `open`.\n */\n readonly unguarded: 'allow' | 'deny'\n },\n ): GuardSet<Name, Schema.Struct.Type<Fields>, S> => {\n type User = Schema.Struct.Type<Fields>\n // The type requires it; a caller without types (or one that spelled it\n // `'Allow'`) would otherwise get a set that denies, silently.\n if (options.unguarded !== 'allow' && options.unguarded !== 'deny')\n throw new Error(\n `[foldkit-guard] ${name}: unguarded must be 'allow' or 'deny', not ${JSON.stringify(options.unguarded)}`,\n )\n const placeholders = placeholdersOf<User>(principal.fields)\n const specs = build({\n principal: () => Object.freeze({ _tag: 'PrincipalSpec' }),\n row: (entity, body) => Object.freeze({ _tag: 'RowSpec', entity, body: body(placeholders) }),\n })\n const guards: Record<string, AnyGuard<User>> = Object.create(null)\n for (const [guard, spec] of Object.entries(specs)) {\n if ((reserved as ReadonlyArray<string>).includes(guard)) {\n throw new Error(\n `[foldkit-guard] ${name}: \"${guard}\" is a name the guard set keeps for itself`,\n )\n }\n guards[guard] = Match.valueTags(spec, {\n PrincipalSpec: (): AnyGuard<User> =>\n Object.freeze({ _tag: 'PrincipalGuard', name: guard, set: name }),\n RowSpec: ({ entity, body }): AnyGuard<User> =>\n Object.freeze({\n _tag: 'RowGuard',\n name: guard,\n set: name,\n entity,\n body,\n // Checks the body reads only this Entity's fields, where it is declared.\n query: Query.from(entity).pipe(Query.where(body)),\n }),\n })\n }\n const principalNames = Object.keys(guards).filter(\n guard => guards[guard]!._tag === 'PrincipalGuard',\n )\n const encoders = Object.fromEntries(\n Object.entries(principal.fields).map(([field, schema]) => [\n field,\n Schema.encodeSync(schema as unknown as Schema.Codec<unknown, unknown>),\n ]),\n )\n const inputOf = (user: User): Readonly<Record<string, unknown>> => {\n const input: Record<string, unknown> = {}\n for (const [field, encode] of Object.entries(encoders)) {\n input[`principal.${field}`] = encode((user as Record<string, unknown>)[field])\n }\n return input\n }\n\n const isPrincipal = Schema.is(Schema.Option(principal))\n // Every claim as JSON keeps it, a set, a number past JSON's or a date\n // included: two principals that differ in one never share a key.\n const asJson = Schema.encodeSync(\n Schema.toCodecJson(principal) as unknown as Schema.Codec<unknown, unknown>,\n )\n\n const implement = <R>(\n bodies: Readonly<Record<string, Body<User, R>>>,\n implementation: { readonly operators?: MemoryOperators | undefined } = {},\n ): Policy<User, R> => {\n const operators = implementation.operators ?? Operators.kernel\n const missing = principalNames.filter(guard => !Object.hasOwn(bodies, guard))\n const extra = Object.keys(bodies).filter(guard => !principalNames.includes(guard))\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `[foldkit-guard] ${name}.implement: ${[\n missing.length > 0 ? `no body for ${missing.join(', ')}` : '',\n extra.length > 0 ? `${extra.join(', ')} is not a principal guard` : '',\n ]\n .filter(part => part !== '')\n .join('; ')}`,\n )\n }\n const decide: Policy<User, R>['decide'] = (guard, { principal, interaction, row }) => {\n if (guard.set !== name) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: \"${guard.name}\" belongs to ${guard.set}`),\n )\n }\n return Match.valueTags(guard, {\n PrincipalGuard: ({ name: body }) => {\n const decided = bodies[body]!(principal, { interaction })\n return Effect.isEffect(decided) ? decided : Effect.succeed(decided)\n },\n RowGuard: rowGuard =>\n Effect.succeed(\n row !== undefined &&\n Option.match(principal, {\n // A visitor has no fields: only a guard over the row alone can hold.\n onNone: () =>\n !readsPrincipal(rowGuard) &&\n evaluate(rowGuard.query, {}, [row], { operators }).length === 1,\n onSome: user =>\n evaluate(rowGuard.query, inputOf(user), [row], { operators }).length === 1,\n }),\n ),\n })\n }\n const decidingFor = (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: string,\n ) => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== name) {\n throw new Error(`[foldkit-guard] ${name}: ${entity.name} carries the guards of ${set}`)\n }\n })\n return deciding(\n guard =>\n Effect.map(decide(guard, { principal, interaction }), decision => decision === true),\n Option.isNone(principal),\n interaction,\n )\n }\n const policy: Policy<User, R> = {\n set: name,\n operators,\n decide,\n readable: (entity, principal) =>\n Effect.map(\n decidingFor(entity, principal, 'Read').row(entity),\n ({ condition }) => condition,\n ),\n readMembers: (entity, principal, members) =>\n decidingFor(entity, principal, 'Read').members(entity, members),\n writable: (entity, principal, interaction) =>\n decidingFor(entity, principal, interaction).row(entity),\n writeMembers: (entity, principal, members, interaction) =>\n decidingFor(entity, principal, interaction).members(entity, members),\n linkable: (entity, principal, relation, interaction) =>\n decidingFor(entity, principal, interaction).relation(entity, relation),\n inputOf: principal =>\n Option.match(principal, { onNone: () => ({}), onSome: user => inputOf(user) }),\n key: options.key,\n // Prefixed, so no user's key is the visitor's. Not `declare`'s `key`\n // alone: a re-read shared under it would read a newer request as an\n // older one's claims.\n keyOf: principal =>\n Option.match(principal, {\n onNone: () => 'visitor',\n onSome: user => `user:${JSON.stringify(asJson(user))}`,\n }),\n isPrincipal,\n provide: context => provided(policy, context),\n }\n return policy\n }\n\n return Object.freeze({\n ...guards,\n name,\n schema: principal as unknown as Schema.Codec<User, unknown>,\n Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>(\n `foldkit-guard/Principal/${name}`,\n ),\n key: options.key,\n unguarded: options.unguarded,\n inputOf,\n implement,\n }) as unknown as GuardSet<Name, User, S>\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA+GA,MAAM,WAAW;CACf;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAyIA,MAAM,YACJ,QACA,YACuC;CACvC,MAAM,OAAU,WAAuC,OAAO,QAAQ,QAAQ,OAAO;CACrF,MAAM,OAA2C;EAC/C,GAAG;EACH,SAAS,OAAO,YAAY,IAAI,OAAO,OAAO,OAAO,OAAO,CAAC;EAC7D,WAAW,QAAQ,cAAc,IAAI,OAAO,SAAS,QAAQ,SAAS,CAAC;EACvE,cAAc,QAAQ,WAAW,YAC/B,IAAI,OAAO,YAAY,QAAQ,WAAW,OAAO,CAAC;EACpD,WAAW,QAAQ,WAAW,gBAC5B,IAAI,OAAO,SAAS,QAAQ,WAAW,WAAW,CAAC;EACrD,eAAe,QAAQ,WAAW,SAAS,gBACzC,IAAI,OAAO,aAAa,QAAQ,WAAW,SAAS,WAAW,CAAC;EAClE,WAAW,QAAQ,WAAW,UAAU,gBACtC,IAAI,OAAO,SAAS,QAAQ,WAAW,UAAU,WAAW,CAAC;EAC/D,UAAS,SAAQ,SAAS,MAAM,IAAI;CACtC;CACA,OAAO,aAAa,MAAM,MAAM;AAClC;AAaA,MAAM,kBAAwB,WAAqD;CACjF,MAAM,SAA6C,CAAC;CACpD,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAClC,OAAO,OAAO,KAAK,MACjB,aAAa,OACb,OAAO,IACT;CAEF,OAAO,OAAO,OAAO,MA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AAQ,KAAK,UAAU,OAAO,IAAI,CAAC;IACrD,CAAC;IACH;IACA,UAAS,YAAW,SAAS,QAAQ,OAAO;GAC9C;GACA,OAAO;EACT;EAEA,OAAO,OAAO,OAAO;GACnB,GAAG;GACH;GACA,QAAQ;GACR,WAAW,QAAQ,QACjB,2BAA2B,MAC7B;GACA,KAAK,QAAQ;GACb,WAAW,QAAQ;GACnB;GACA;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Who may do what, declared once on the domain.\n *\n * A guard set names its guards once, in shared code the client imports too.\n * A **principal guard** is declared by name and implemented only on the\n * server (`G.implement`), so its logic never ships. A **row guard** is an\n * `Expr` over one Entity's fields with the principal's fields as inputs: data,\n * which the SQL compiler and `evaluate` both run. See `guard-DESIGN.md`.\n */\nimport { Context, Effect, Match, Option, Schema } from 'effect'\nimport { Attaching, attached, type InteractionKey } from './attach.js'\nimport {\n deciding,\n readsPrincipal,\n type Condition,\n type MemberRead,\n type RowRule,\n} from './condition.js'\nimport { May } from './may.js'\nimport { me } from './me.js'\nimport { providedFrom } from './origin.js'\nimport {\n Expr,\n Operators,\n Query,\n evaluate,\n type AnyEntity,\n type EntityRef,\n type ExprContext,\n type MemoryOperators,\n type AnyQuery,\n type InputExpr,\n type Predicate,\n} from 'foldkit-entity'\n\n/** A guard's answer: allowed, refused, or refused with a sentence the caller may read. */\nexport type Decision = boolean | { readonly allowed: false; readonly reason: string }\n\n/** What a principal guard is asked about. */\nexport interface About {\n /** The interaction attempted: `Read`, `Update`, or one the application names. */\n readonly interaction: string\n}\n\n/**\n * The principal's fields as a row guard's body sees them: each an input named\n * `principal.<field>`, typed as the field. A body is built once, so it holds\n * these placeholders and never a value: branching on one is a type error.\n */\nexport type Placeholders<User> = {\n readonly [K in keyof User & string]: InputExpr<User[K]>\n}\n\n/** What `guard.principal()` declares: a name whose body the server supplies. */\nexport interface PrincipalSpec {\n readonly _tag: 'PrincipalSpec'\n}\n\n/** What `guard.row(entity, body)` declares: a predicate over one Entity's rows. */\nexport interface RowSpec<E extends AnyEntity> {\n readonly _tag: 'RowSpec'\n readonly entity: E\n readonly body: Predicate\n}\n\ntype AnySpec = PrincipalSpec | RowSpec<AnyEntity>\n\n/**\n * The principal a guard is for, kept in the type so a guard of one principal\n * cannot stand where another's is wanted. A function type, so it is invariant.\n */\ninterface ForPrincipal<User> {\n readonly '~principal'?: (user: User) => User\n}\n\n/** A guard whose body lives on the server, asked of the principal alone. */\nexport interface PrincipalGuard<User, Set extends string = string> extends ForPrincipal<User> {\n readonly _tag: 'PrincipalGuard'\n readonly name: string\n /** The name of the guard set it belongs to. */\n readonly set: Set\n}\n\n/** A guard over the rows of `E`: its predicate, and the query that asks it of rows. */\nexport interface RowGuard<\n User,\n E extends AnyEntity,\n Set extends string = string,\n> extends ForPrincipal<User> {\n readonly _tag: 'RowGuard'\n readonly name: string\n readonly set: Set\n readonly entity: E\n readonly body: Predicate\n /** `from(entity).where(body)`, for an interpreter that runs queries. */\n readonly query: AnyQuery\n}\n\nexport type AnyGuard<User> = PrincipalGuard<User> | RowGuard<User, AnyEntity>\n\ntype GuardOf<User, Set extends string, S> =\n S extends RowSpec<infer E> ? RowGuard<User, E, Set> : PrincipalGuard<User, Set>\n\n/** The keys of a spec record that are principal guards: what `implement` must supply. */\ntype PrincipalKeys<S> = { [K in keyof S]: S[K] extends PrincipalSpec ? K : never }[keyof S]\n\n/** A principal guard's body, on the server. */\nexport type Body<User, R = never> = (\n principal: Option.Option<User>,\n about: About,\n) => Decision | Effect.Effect<Decision, never, R>\n\n/** Names a guard set reserves for itself, which no guard may take. */\nconst reserved = [\n 'name',\n 'schema',\n 'Principal',\n 'key',\n 'unguarded',\n 'inputOf',\n 'implement',\n] as const\ntype Reserved = (typeof reserved)[number]\n\n/** Who is asking, for one guard set: a visitor is `none`. */\nexport interface PrincipalOf<Name extends string> {\n readonly '~guardSet': Name\n}\n\n/** The guard set of one application, as `Guards.declare` returns it. */\nexport type GuardSet<Name extends string, User, S> = {\n readonly [K in keyof S]: GuardOf<User, Name, S[K]>\n} & {\n readonly name: Name\n /** The principal's schema, whose fields the row guards read. */\n readonly schema: Schema.Codec<User, unknown>\n /** The server's Context key for who is asking. Authentication provides it. */\n readonly Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>\n /** A stable name for the person, whatever their claims: for what is theirs, as a cache's scope. */\n readonly key: (user: User) => string\n readonly unguarded: 'allow' | 'deny'\n /** The principal's fields as row guards' inputs, encoded as stored values are. */\n readonly inputOf: (user: User) => Readonly<Record<string, unknown>>\n /**\n * The bodies of the principal guards: every one, and nothing else. `operators`\n * runs the row guards' primitive operators in memory; `Operators.kernel` when\n * not given.\n */\n readonly implement: <R = never>(\n bodies: { readonly [K in PrincipalKeys<S>]: Body<User, R> },\n options?: { readonly operators?: MemoryOperators | undefined },\n ) => Policy<User, R>\n}\n\n/** The server's half of a guard set: every principal guard's body. */\nexport interface Policy<User, R = never> {\n readonly set: string\n /**\n * How a row guard's primitive operators are run in memory: by `decide`,\n * `Condition.holds` and every guarded server judging a row. Given to\n * `implement`; `Operators.kernel` when not.\n */\n readonly operators: MemoryOperators\n /**\n * Whether `guard` allows `principal`, for a row guard over `row` (its stored,\n * encoded values). A visitor passes no row guard that reads a principal's\n * fields; one over the row alone holds for a visitor too.\n */\n readonly decide: (\n guard: AnyGuard<User>,\n request: {\n readonly principal: Option.Option<User>\n readonly interaction: string\n readonly row?: Readonly<Record<string, unknown>> | undefined\n },\n ) => Effect.Effect<Decision, never, R>\n /**\n * Which rows of `entity` `principal` may read, as a condition over the row\n * with every principal guard already decided. An Entity without guards, or\n * of no set, reads `Always`.\n */\n readonly readable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n ) => Effect.Effect<Condition, never, R>\n /** The read rule of each of `members`, relations included, that has one, decided for `principal`. */\n readonly readMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /**\n * Which rows of `entity` `principal` may write by `interaction` (`Create`,\n * `Update`, `Delete`, or one the application named), as a condition over\n * the row, and what a refusal shows.\n */\n readonly writable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: 'Create' | 'Update' | 'Delete' | InteractionKey,\n ) => Effect.Effect<RowRule, never, R>\n /** The rule of each of `members` that has one for setting it, decided for `principal`. */\n readonly writeMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n interaction: 'Create' | 'Update',\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /** A relation's rule for linking or unlinking a row, when it has one. */\n readonly linkable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n relation: string,\n interaction: 'Link' | 'Unlink',\n ) => Effect.Effect<Option.Option<RowRule>, never, R>\n /** The principal's fields as row guards' inputs; a visitor has none. */\n readonly inputOf: (principal: Option.Option<User>) => Readonly<Record<string, unknown>>\n /**\n * Who the principal is as a row: `declare`'s `viewer` Entity, by `key`.\n * What a rule's `Expr.viewer` reads, and the server's viewer:\n * `RemoteServer.make({ viewer: Policy.viewer })`. None for a visitor, and\n * for a set that names no `viewer`.\n */\n readonly viewer: (principal: Option.Option<User>) => Option.Option<EntityRef>\n /**\n * Who the principal is: `declare`'s `key`, the same function as `G.key`,\n * here for a server seam that holds the Policy and not the set. Not\n * `keyOf`, which names a principal by every field, for sharing re-reads.\n */\n readonly key: (user: User) => string\n /**\n * Who is asking, as the rules see it: every field of the principal, encoded,\n * a visitor included. Two requests by one person with the same claims answer\n * alike, so a live hub shares their re-reads; a changed claim is not shared.\n *\n * ```ts\n * RemoteServer.liveHub(sources, { key: Policy.keyOf })\n * ```\n */\n readonly keyOf: (principal: Option.Option<User>) => string\n /**\n * Whether `value` is this set's principal, an `Option` of its schema: for a\n * seam that is handed the principal untyped.\n */\n readonly isPrincipal: (value: unknown) => value is Option.Option<User>\n /**\n * This Policy with services its bodies need provided, such as a membership\n * lookup. The read seams (`GuardDrizzle.visible`, `GuardServer.memory`,\n * `GuardSync`) take a Policy that needs nothing more: a read rule runs inside\n * a read whose requirements are its Source's. Provide what stays put here,\n * once; carry what changes per request in the principal. A seam built from\n * the result counts as built from this Policy: `validate` checks the rules,\n * not the services given them. `GuardSync.authorize` runs bodies\n * synchronously, so what it is given must answer without suspending.\n *\n * ```ts\n * const ReadPolicy = Policy.provide(Context.make(Memberships, memberships))\n * ```\n */\n readonly provide: <Provided extends R>(\n context: Context.Context<Provided>,\n ) => Policy<User, Exclude<R, Provided>>\n}\n\n/** `policy` with `context` provided to every body it runs. */\nconst provided = <User, R, Provided extends R>(\n policy: Policy<User, R>,\n context: Context.Context<Provided>,\n): Policy<User, Exclude<R, Provided>> => {\n const run = <A>(effect: Effect.Effect<A, never, R>) => Effect.provide(effect, context)\n const next: Policy<User, Exclude<R, Provided>> = {\n ...policy,\n decide: (guard, request) => run(policy.decide(guard, request)),\n readable: (entity, principal) => run(policy.readable(entity, principal)),\n readMembers: (entity, principal, members) =>\n run(policy.readMembers(entity, principal, members)),\n writable: (entity, principal, interaction) =>\n run(policy.writable(entity, principal, interaction)),\n writeMembers: (entity, principal, members, interaction) =>\n run(policy.writeMembers(entity, principal, members, interaction)),\n linkable: (entity, principal, relation, interaction) =>\n run(policy.linkable(entity, principal, relation, interaction)),\n provide: more => provided(next, more),\n }\n return providedFrom(next, policy)\n}\n\n/** The builders a guard set's declaration is given, typed by its principal. */\nexport interface Builders<User> {\n /** A guard decided from the principal alone, by a body only the server has. */\n readonly principal: () => PrincipalSpec\n /** A guard over `entity`'s rows: a predicate with the principal's fields as inputs. */\n readonly row: <E extends AnyEntity>(\n entity: E,\n body: (principal: Placeholders<User>) => Predicate,\n ) => RowSpec<E>\n}\n\nconst placeholdersOf = <User>(fields: Schema.Struct.Fields): Placeholders<User> =>\n // Built as entries, so a field named `__proto__` is a key of its own, not the prototype.\n Object.freeze(\n Object.fromEntries(\n Object.entries(fields).map(([key, schema]): [string, InputExpr<unknown>] => [\n key,\n Expr.input(`principal.${key}`, schema as unknown as Schema.Codec<unknown, unknown>),\n ]),\n ),\n ) as Placeholders<User>\n\nexport { Condition, type MemberRead, type RowRule } from './condition.js'\nexport { May, MaySchema, type MayAnswer } from './may.js'\nexport { ME, type MeEntity } from './me.js'\nexport {\n Interaction,\n type All,\n type AnyRule,\n type Attach,\n type Attachment,\n type Deny,\n type Explain,\n type Inherit,\n type InteractionKey,\n type On,\n type Redact,\n type RuleFor,\n type Surface,\n} from './attach.js'\n\nexport const Guards = {\n ...Attaching,\n /**\n * Adds the `may` member, the server's answer to what a principal may do\n * with a row, after its guards are attached:\n * `TodoFields.pipe(Guards.attach(G, { … }), Guards.may)`.\n */\n may: May.member,\n /**\n * `Me`, the visitor as an Entity: one row, `me`, that everyone reads and no\n * one writes, with `signedIn`, the principal's `key`, and `may` for the\n * interactions named here. Serve it with `GuardServer.me`.\n *\n * ```ts\n * export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })\n * ```\n */\n me,\n /**\n * One application's guards, under `name` (its principal's Context key, and\n * what the matrix prints). `principal` is a `Schema.Struct`: its fields are\n * what a row guard reads, and its codec encodes a principal's values as\n * stored values are encoded.\n *\n * ```ts\n * const G = Guards.declare('Todos', User, guard => ({\n * isAdmin: guard.principal(),\n * isOwner: guard.row(TodoFields, p => Expr.eq(TodoFields.fields.ownerId, p.id)),\n * }), { key: user => user.id })\n * ```\n */\n declare: <\n const Name extends string,\n Fields extends Schema.Struct.Fields,\n const S extends Readonly<Record<string, AnySpec>> & { readonly [K in Reserved]?: never },\n >(\n name: Name,\n principal: Schema.Struct<Fields>,\n build: (guard: Builders<Schema.Struct.Type<Fields>>) => S,\n options: {\n readonly key: (user: Schema.Struct.Type<Fields>) => string\n /**\n * What a surface of a guarded Entity with no rules decides: `'deny'`\n * refuses it, `'allow'` lets everyone. Required, so an open surface is\n * a decision written down; `Guards.matrix` prints it `closed` or `open`.\n */\n readonly unguarded: 'allow' | 'deny'\n /**\n * The Entity whose row each principal is, by `key`: what a row guard's\n * `Expr.viewer` of it reads, on the server and the client alike. A set\n * without one refuses a rule that reads the viewer.\n */\n readonly viewer?: AnyEntity | undefined\n },\n ): GuardSet<Name, Schema.Struct.Type<Fields>, S> => {\n type User = Schema.Struct.Type<Fields>\n // The type requires it; a caller without types (or one that spelled it\n // `'Allow'`) would otherwise get a set that denies, silently.\n if (options.unguarded !== 'allow' && options.unguarded !== 'deny')\n throw new Error(\n `[foldkit-guard] ${name}: unguarded must be 'allow' or 'deny', not ${JSON.stringify(options.unguarded)}`,\n )\n const placeholders = placeholdersOf<User>(principal.fields)\n const specs = build({\n principal: () => Object.freeze({ _tag: 'PrincipalSpec' }),\n row: (entity, body) => {\n const predicate = body(placeholders)\n const { operations } = Query.dependencies(Query.from(entity).pipe(Query.where(predicate)))\n // Who may is decided when asked, not at a write's time, which the rule is never given.\n if (operations.includes('now')) {\n throw new Error(\n `[foldkit-guard] ${name}: a rule over ${entity.name} reads Expr.now; who may do something does not move with the clock here`,\n )\n }\n if (operations.includes('viewer') && options.viewer === undefined) {\n throw new Error(\n `[foldkit-guard] ${name}: a rule over ${entity.name} reads Expr.viewer, but the set names no viewer Entity; declare it with { viewer }`,\n )\n }\n return Object.freeze({ _tag: 'RowSpec', entity, body: predicate })\n },\n })\n const guards: Record<string, AnyGuard<User>> = Object.create(null)\n for (const [guard, spec] of Object.entries(specs)) {\n if ((reserved as ReadonlyArray<string>).includes(guard)) {\n throw new Error(\n `[foldkit-guard] ${name}: \"${guard}\" is a name the guard set keeps for itself`,\n )\n }\n guards[guard] = Match.valueTags(spec, {\n PrincipalSpec: (): AnyGuard<User> =>\n Object.freeze({ _tag: 'PrincipalGuard', name: guard, set: name }),\n RowSpec: ({ entity, body }): AnyGuard<User> =>\n Object.freeze({\n _tag: 'RowGuard',\n name: guard,\n set: name,\n entity,\n body,\n // Checks the body reads only this Entity's fields, where it is declared.\n query: Query.from(entity).pipe(Query.where(body)),\n }),\n })\n }\n const principalNames = Object.keys(guards).filter(\n guard => guards[guard]!._tag === 'PrincipalGuard',\n )\n const encoders = Object.fromEntries(\n Object.entries(principal.fields).map(([field, schema]) => [\n field,\n Schema.encodeSync(schema as unknown as Schema.Codec<unknown, unknown>),\n ]),\n )\n const inputOf = (user: User): Readonly<Record<string, unknown>> => {\n const input: Record<string, unknown> = {}\n for (const [field, encode] of Object.entries(encoders)) {\n input[`principal.${field}`] = encode((user as Record<string, unknown>)[field])\n }\n return input\n }\n\n const viewerOf = (user: Option.Option<User>): Option.Option<EntityRef> =>\n Option.flatMap(Option.fromUndefinedOr(options.viewer), entity =>\n Option.map(user, each => ({ entity: entity.name, id: options.key(each) })),\n )\n // A rule reads who asks, never a time.\n const contextOf = (user: Option.Option<User>): ExprContext => ({\n viewer: viewerOf(user),\n now: Option.none(),\n })\n\n const isPrincipal = Schema.is(Schema.Option(principal))\n // Every claim as JSON keeps it, a set, a number past JSON's or a date\n // included: two principals that differ in one never share a key.\n const asJson = Schema.encodeSync(\n Schema.toCodecJson(principal) as unknown as Schema.Codec<unknown, unknown>,\n )\n\n const implement = <R>(\n bodies: Readonly<Record<string, Body<User, R>>>,\n implementation: { readonly operators?: MemoryOperators | undefined } = {},\n ): Policy<User, R> => {\n const operators = implementation.operators ?? Operators.kernel\n const missing = principalNames.filter(guard => !Object.hasOwn(bodies, guard))\n const extra = Object.keys(bodies).filter(guard => !principalNames.includes(guard))\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `[foldkit-guard] ${name}.implement: ${[\n missing.length > 0 ? `no body for ${missing.join(', ')}` : '',\n extra.length > 0 ? `${extra.join(', ')} is not a principal guard` : '',\n ]\n .filter(part => part !== '')\n .join('; ')}`,\n )\n }\n const decide: Policy<User, R>['decide'] = (guard, { principal, interaction, row }) => {\n if (guard.set !== name) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: \"${guard.name}\" belongs to ${guard.set}`),\n )\n }\n return Match.valueTags(guard, {\n PrincipalGuard: ({ name: body }) => {\n const decided = bodies[body]!(principal, { interaction })\n return Effect.isEffect(decided) ? decided : Effect.succeed(decided)\n },\n RowGuard: rowGuard =>\n Effect.succeed(\n row !== undefined &&\n Option.match(principal, {\n // A visitor has no fields: only a guard over the row alone can hold.\n onNone: () =>\n !readsPrincipal(rowGuard) &&\n evaluate(rowGuard.query, {}, [row], {\n operators,\n context: contextOf(principal),\n }).length === 1,\n onSome: user =>\n evaluate(rowGuard.query, inputOf(user), [row], {\n operators,\n context: contextOf(principal),\n }).length === 1,\n }),\n ),\n })\n }\n const decidingFor = (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: string,\n ) => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== name) {\n throw new Error(`[foldkit-guard] ${name}: ${entity.name} carries the guards of ${set}`)\n }\n })\n return deciding(\n guard =>\n Effect.map(decide(guard, { principal, interaction }), decision => decision === true),\n Option.isNone(principal),\n interaction,\n contextOf(principal),\n )\n }\n const policy: Policy<User, R> = {\n set: name,\n operators,\n decide,\n readable: (entity, principal) =>\n Effect.map(\n decidingFor(entity, principal, 'Read').row(entity),\n ({ condition }) => condition,\n ),\n readMembers: (entity, principal, members) =>\n decidingFor(entity, principal, 'Read').members(entity, members),\n writable: (entity, principal, interaction) =>\n decidingFor(entity, principal, interaction).row(entity),\n writeMembers: (entity, principal, members, interaction) =>\n decidingFor(entity, principal, interaction).members(entity, members),\n linkable: (entity, principal, relation, interaction) =>\n decidingFor(entity, principal, interaction).relation(entity, relation),\n inputOf: principal =>\n Option.match(principal, { onNone: () => ({}), onSome: user => inputOf(user) }),\n viewer: viewerOf,\n key: options.key,\n // Prefixed, so no user's key is the visitor's. Not `declare`'s `key`\n // alone: a re-read shared under it would read a newer request as an\n // older one's claims.\n keyOf: principal =>\n Option.match(principal, {\n onNone: () => 'visitor',\n onSome: user => `user:${JSON.stringify(asJson(user))}`,\n }),\n isPrincipal,\n provide: context => provided(policy, context),\n }\n return policy\n }\n\n return Object.freeze({\n ...guards,\n name,\n schema: principal as unknown as Schema.Codec<User, unknown>,\n Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>(\n `foldkit-guard/Principal/${name}`,\n ),\n key: options.key,\n unguarded: options.unguarded,\n inputOf,\n implement,\n }) as unknown as GuardSet<Name, User, S>\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiHA,MAAM,WAAW;CACf;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAgJA,MAAM,YACJ,QACA,YACuC;CACvC,MAAM,OAAU,WAAuC,OAAO,QAAQ,QAAQ,OAAO;CACrF,MAAM,OAA2C;EAC/C,GAAG;EACH,SAAS,OAAO,YAAY,IAAI,OAAO,OAAO,OAAO,OAAO,CAAC;EAC7D,WAAW,QAAQ,cAAc,IAAI,OAAO,SAAS,QAAQ,SAAS,CAAC;EACvE,cAAc,QAAQ,WAAW,YAC/B,IAAI,OAAO,YAAY,QAAQ,WAAW,OAAO,CAAC;EACpD,WAAW,QAAQ,WAAW,gBAC5B,IAAI,OAAO,SAAS,QAAQ,WAAW,WAAW,CAAC;EACrD,eAAe,QAAQ,WAAW,SAAS,gBACzC,IAAI,OAAO,aAAa,QAAQ,WAAW,SAAS,WAAW,CAAC;EAClE,WAAW,QAAQ,WAAW,UAAU,gBACtC,IAAI,OAAO,SAAS,QAAQ,WAAW,UAAU,WAAW,CAAC;EAC/D,UAAS,SAAQ,SAAS,MAAM,IAAI;CACtC;CACA,OAAO,aAAa,MAAM,MAAM;AAClC;AAaA,MAAM,kBAAwB,WAE5B,OAAO,OACL,OAAO,YACL,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,CAAC,KAAK,YAA0C,CAC1E,KACA,KAAK,MAAM,aAAa,OAAO,MAAmD,CACpF,CAAC,CACH,CACF;AAqBF,MAAa,SAAS;CACpB,GAAG;;;;;;CAMH,KAAK,IAAI;;;;;;;;;;CAUT;;;;;;;;;;;;;;CAcA,UAKE,MACA,WACA,OACA,YAekD;EAIlD,IAAI,QA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YAC/B,YAAY,QAAQ,WAAW,MAAM,CAAC,CAAC,QAAQ,QAAQ,OAAO;IAChE,WAAW,QAAQ,WAAW,gBAC5B,YAAY,QAAQ,WAAW,WAAW,CAAC,CAAC,IAAI,MAAM;IACxD,eAAe,QAAQ,WAAW,SAAS,gBACzC,YAAY,QAAQ,WAAW,WAAW,CAAC,CAAC,QAAQ,QAAQ,OAAO;IACrE,WAAW,QAAQ,WAAW,UAAU,gBACtC,YAAY,QAAQ,WAAW,WAAW,CAAC,CAAC,SAAS,QAAQ,QAAQ;IACvE,UAAS,cACP,OAAO,MAAM,WAAW;KAAE,eAAe,CAAC;KAAI,SAAQ,SAAQ,QAAQ,IAAI;IAAE,CAAC;IAC/E,QAAQ;IACR,KAAK,QAAQ;IAIb,QAAO,cACL,OAAO,MAAM,WAAW;KACtB,cAAc;KACd,SAAQ,SAAQ,QAAQ,KAAK,UAAU,OAAO,IAAI,CAAC;IACrD,CAAC;IACH;IACA,UAAS,YAAW,SAAS,QAAQ,OAAO;GAC9C;GACA,OAAO;EACT;EAEA,OAAO,OAAO,OAAO;GACnB,GAAG;GACH;GACA,QAAQ;GACR,WAAW,QAAQ,QACjB,2BAA2B,MAC7B;GACA,KAAK,QAAQ;GACb,WAAW,QAAQ;GACnB;GACA;EACF,CAAC;CACH;AACF"}
@@ -0,0 +1,200 @@
1
+ import { r as attached } from "./attach-CEGlbWu5.mjs";
2
+ import { n as deciding, t as Condition } from "./condition-dNSbUHzE.mjs";
3
+ import { Effect, Match, Option, Record, Schema } from "effect";
4
+ import { Derived, Entity } from "foldkit-entity";
5
+ // src/may.ts
6
+ /**
7
+ * `may`: what a principal may do with a row, as a derived member the client
8
+ * reads like any other. The server answers it for the row as it was read; a
9
+ * client foresees it for a row it writes, from the same rules, where they
10
+ * decide it whatever it does not know. Either way it is a hint for a
11
+ * greyed-out button, never the check: the write is checked again when made.
12
+ */
13
+ /**
14
+ * The answer: per row interaction (`Update`, `Delete`, and each one the
15
+ * application named), per member with its own `Update` rule, and per relation
16
+ * with a `Link` or `Unlink` rule; and, for a row interaction refused with an
17
+ * `explain`, its sentence.
18
+ */
19
+ const MaySchema = Schema.Struct({
20
+ row: Schema.Record(Schema.String, Schema.Boolean),
21
+ reasons: Schema.Record(Schema.String, Schema.String),
22
+ members: Schema.Record(Schema.String, Schema.Boolean),
23
+ relations: Schema.Record(Schema.String, Schema.Struct({
24
+ Link: Schema.Boolean,
25
+ Unlink: Schema.Boolean
26
+ }))
27
+ });
28
+ const can = (may, interaction) => may.row[interaction] === true;
29
+ /** The row's `Update`, and the member's own rule when it has one. */
30
+ const setting = (may, member) => can(may, "Update") && (!Object.hasOwn(may.members, member) || may.members[member] === true);
31
+ /** The row's `Update`, and the relation's own rule for the direction when it has one. */
32
+ const linking = (may, relation, interaction) => can(may, "Update") && (!Object.hasOwn(may.relations, relation) || may.relations[relation][interaction]);
33
+ const isMay = Schema.is(MaySchema);
34
+ const sameMay = Schema.toEquivalence(MaySchema);
35
+ /** The interactions a row answers `may` for: `Update`, `Delete`, and each one the set named. */
36
+ const builtInRow = /* @__PURE__ */ new Set([
37
+ "Read",
38
+ "Create",
39
+ "Update",
40
+ "Delete"
41
+ ]);
42
+ /** The rules `may` answers for `entity`, each decided by `ask`. */
43
+ const mayRules = (entity, ask) => {
44
+ const attachment = attached(entity);
45
+ const named = Option.match(attachment, {
46
+ onNone: () => [],
47
+ onSome: ({ row }) => Object.keys(row).filter((interaction) => !builtInRow.has(interaction))
48
+ });
49
+ const ruledMembers = Option.match(attachment, {
50
+ onNone: () => [],
51
+ onSome: ({ members }) => Object.keys(members)
52
+ });
53
+ const ruledRelations = Option.match(attachment, {
54
+ onNone: () => [],
55
+ onSome: ({ relations }) => Object.keys(relations)
56
+ });
57
+ return Effect.map(Effect.all([
58
+ Effect.forEach([
59
+ "Update",
60
+ "Delete",
61
+ ...named
62
+ ], (interaction) => Effect.map(ask.row(interaction), (rule) => [interaction, rule])),
63
+ ask.members(ruledMembers),
64
+ Effect.forEach(ruledRelations, (relation) => Effect.map(Effect.all([ask.relation(relation, "Link"), ask.relation(relation, "Unlink")]), ([link, unlink]) => ({
65
+ relation,
66
+ link,
67
+ unlink
68
+ })))
69
+ ]), ([rows, members, relations]) => ({
70
+ rows,
71
+ members,
72
+ relations
73
+ }));
74
+ };
75
+ /** Every condition the rules hold a row to. */
76
+ const mayConditions = (rules) => [
77
+ ...rules.rows.map(([, { condition }]) => condition),
78
+ ...rules.members.map(({ condition }) => condition),
79
+ ...rules.relations.flatMap(({ link, unlink }) => [...Option.toArray(link), ...Option.toArray(unlink)].map(({ condition }) => condition))
80
+ ];
81
+ /**
82
+ * The answer over one row, each condition decided by `decide`. A row
83
+ * interaction it cannot decide over one row (a rule reading another row,
84
+ * which the write's statement judges) is left out, and so refuses nothing.
85
+ */
86
+ const answerOf = (rules, decide) => {
87
+ const holds = (condition) => Option.getOrElse(decide(condition), () => false);
88
+ const allows = (rule) => Option.match(rule, {
89
+ onNone: () => true,
90
+ onSome: ({ condition }) => holds(condition)
91
+ });
92
+ const decided = rules.rows.flatMap(([interaction, rule]) => Option.match(decide(rule.condition), {
93
+ onNone: () => [],
94
+ onSome: (answer) => [{
95
+ interaction,
96
+ rule,
97
+ answer
98
+ }]
99
+ }));
100
+ return {
101
+ row: Object.fromEntries(decided.map(({ interaction, answer }) => [interaction, answer])),
102
+ reasons: Object.fromEntries(decided.flatMap(({ interaction, rule: { deny }, answer }) => answer ? [] : Match.valueTags(deny, {
103
+ Explain: ({ reason }) => [[interaction, reason]],
104
+ Forbidden: () => [],
105
+ NotFound: () => [],
106
+ Omit: () => [],
107
+ Redact: () => []
108
+ }))),
109
+ members: Object.fromEntries(rules.members.map(({ member, condition }) => [member, holds(condition)])),
110
+ relations: Object.fromEntries(rules.relations.map(({ relation, link, unlink }) => [relation, {
111
+ Link: allows(link),
112
+ Unlink: allows(unlink)
113
+ }]))
114
+ };
115
+ };
116
+ /**
117
+ * `may` foreseen for a row the client writes. A principal guard's body is
118
+ * the server's, and the principal's fields are not the client's to know, so
119
+ * each is unknown, as is a rule over a row or field the store lacks. Every
120
+ * rule is a conjunction and disjunction of its parts, so it is decided when
121
+ * it comes out the same with every unknown part taken to hold and taken not
122
+ * to: the answer is foreseen only when the whole of it is.
123
+ */
124
+ const predict = ({ entity, row, rows, context }) => {
125
+ const answerAssuming = (assumed) => {
126
+ const decide = (interaction) => deciding(() => Effect.succeed(assumed), false, interaction, context);
127
+ const rules = Effect.runSync(mayRules(entity, {
128
+ row: (interaction) => decide(interaction).row(entity),
129
+ members: (members) => decide("Update").members(entity, members),
130
+ relation: (relation, interaction) => decide(interaction).relation(entity, relation)
131
+ }));
132
+ return answerOf(rules, (condition) => Option.some(Condition.judge(condition, row, rows, assumed)));
133
+ };
134
+ const held = answerAssuming(true);
135
+ return sameMay(held, answerAssuming(false)) ? Option.some(held) : Option.none();
136
+ };
137
+ /** Whether `answer` names `key`, and says no to it. */
138
+ const refuses = (answer, key) => Object.hasOwn(answer, key) && answer[key] === false;
139
+ /**
140
+ * The write a held `may` refuses, as the server would: the row's `Update` or
141
+ * `Delete`, a written member's own `Update`, a relation's `Link` or `Unlink`,
142
+ * each judged over the row as read, where the answer says `false`. What it
143
+ * does not name refuses nothing, and neither does a value that is no answer.
144
+ */
145
+ const forbids = (value, surface) => {
146
+ if (!isMay(value)) return Option.none();
147
+ if (refuses(value.row, surface.kind)) return Option.some({ reason: Option.fromUndefinedOr(Object.hasOwn(value.reasons, surface.kind) ? value.reasons[surface.kind] : void 0) });
148
+ const member = surface.members.some((key) => refuses(value.members, key));
149
+ const relation = surface.relations.some(({ relation, interaction }) => Object.hasOwn(value.relations, relation) && !value.relations[relation][interaction]);
150
+ return member || relation ? Option.some({ reason: Option.none() }) : Option.none();
151
+ };
152
+ const May = {
153
+ /**
154
+ * Adds the `may` member to an Entity, after its guards are attached:
155
+ * `TodoFields.pipe(Guards.attach(G, { … }), Guards.may)`. Select it as any
156
+ * member (`may: true`); `GuardServer.filter` answers it. A client holding it
157
+ * refuses, where it is made, a write it says no to (`Forbidden`).
158
+ */
159
+ member: Entity.derived({ may: Derived.make(MaySchema, {
160
+ predict,
161
+ forbids
162
+ }) }),
163
+ /**
164
+ * Whether the row's rule for `interaction` let the principal, when it was
165
+ * read. An interaction the answer does not name was not ruled where the row
166
+ * was read, and reads `false`: a hint errs on the side of asking.
167
+ */
168
+ can: (may, interaction) => can(may, interaction),
169
+ /**
170
+ * Why the row's rule for `interaction` refused, when it was refused with an
171
+ * `explain`: words for whoever asked. None where it was allowed (the server
172
+ * gives none then), or refused without one.
173
+ */
174
+ reason: (may, interaction) => Record.get(may.reasons, interaction),
175
+ /** Whether the principal may set `member` on this row: the row's `Update`, and the member's own rule. */
176
+ canSet: (may, _entity, member) => setting(may, member),
177
+ /** Whether the principal may point `relation` at a row, or away from one. */
178
+ canLink: (may, _entity, relation, interaction) => linking(may, relation, interaction),
179
+ /**
180
+ * `foldkit-crud`'s `locks` for `entity`: an editor loads `may` beside the
181
+ * form's members and locks each the reader may not set. A relation is locked
182
+ * unless it may be both unlinked and linked. Nothing is locked while `may`
183
+ * is not answered (a Source without the filter): the write is checked anyway.
184
+ *
185
+ * ```ts
186
+ * Crud.editor('todo', { form, mutation: EditTodo, locks: May.locks(Todo) })
187
+ * ```
188
+ */
189
+ locks: (entity) => ({
190
+ select: { may: true },
191
+ locked: (row, member) => {
192
+ const may = row.may;
193
+ if (!isMay(may)) return false;
194
+ return Object.hasOwn(entity.relations, member) ? !(linking(may, member, "Unlink") && linking(may, member, "Link")) : !setting(may, member);
195
+ }
196
+ })
197
+ };
198
+ export { mayRules as a, mayConditions as i, MaySchema as n, answerOf as r, May as t };
199
+
200
+ //# sourceMappingURL=may-DprCmMgK.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"may-DprCmMgK.mjs","names":[],"sources":["../src/may.ts"],"sourcesContent":["/**\n * `may`: what a principal may do with a row, as a derived member the client\n * reads like any other. The server answers it for the row as it was read; a\n * client foresees it for a row it writes, from the same rules, where they\n * decide it whatever it does not know. Either way it is a hint for a\n * greyed-out button, never the check: the write is checked again when made.\n */\nimport { Effect, Match, Option, Record, Schema } from 'effect'\nimport { Derived, Entity, type AnyEntity, type Forbids, type Predict } from 'foldkit-entity'\nimport { attached, type InteractionKey } from './attach.js'\nimport { Condition, deciding, type MemberRead, type RowRule } from './condition.js'\n\n/**\n * The answer: per row interaction (`Update`, `Delete`, and each one the\n * application named), per member with its own `Update` rule, and per relation\n * with a `Link` or `Unlink` rule; and, for a row interaction refused with an\n * `explain`, its sentence.\n */\nexport const MaySchema = Schema.Struct({\n row: Schema.Record(Schema.String, Schema.Boolean),\n reasons: Schema.Record(Schema.String, Schema.String),\n members: Schema.Record(Schema.String, Schema.Boolean),\n relations: Schema.Record(\n Schema.String,\n Schema.Struct({ Link: Schema.Boolean, Unlink: Schema.Boolean }),\n ),\n})\nexport type MayAnswer = typeof MaySchema.Type\n\ntype MemberKeys<E extends AnyEntity> = (keyof E['fields'] | keyof E['derived']) & string\n\nconst can = (may: MayAnswer, interaction: string): boolean => may.row[interaction] === true\n\n/** The row's `Update`, and the member's own rule when it has one. */\nconst setting = (may: MayAnswer, member: string): boolean =>\n can(may, 'Update') && (!Object.hasOwn(may.members, member) || may.members[member] === true)\n\n/** The row's `Update`, and the relation's own rule for the direction when it has one. */\nconst linking = (may: MayAnswer, relation: string, interaction: 'Link' | 'Unlink'): boolean =>\n can(may, 'Update') &&\n (!Object.hasOwn(may.relations, relation) || may.relations[relation]![interaction])\n\nconst isMay = Schema.is(MaySchema)\nconst sameMay = Schema.toEquivalence(MaySchema)\n\n/** The interactions a row answers `may` for: `Update`, `Delete`, and each one the set named. */\nconst builtInRow = new Set(['Read', 'Create', 'Update', 'Delete'])\n\n/**\n * What `may` asks, for one principal: each row interaction's rule, each\n * member's own `Update`, each relation's `Link` and `Unlink`.\n */\nexport interface MayRules {\n readonly rows: ReadonlyArray<readonly [string, RowRule]>\n readonly members: ReadonlyArray<MemberRead>\n readonly relations: ReadonlyArray<{\n readonly relation: string\n readonly link: Option.Option<RowRule>\n readonly unlink: Option.Option<RowRule>\n }>\n}\n\n/** How one side decides a rule for its principal: a Policy's bodies, or a client's assumption. */\nexport interface MayAsk<R> {\n readonly row: (interaction: string) => Effect.Effect<RowRule, never, R>\n readonly members: (\n members: ReadonlyArray<string>,\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n readonly relation: (\n relation: string,\n interaction: 'Link' | 'Unlink',\n ) => Effect.Effect<Option.Option<RowRule>, never, R>\n}\n\n/** The rules `may` answers for `entity`, each decided by `ask`. */\nexport const mayRules = <R>(\n entity: AnyEntity,\n ask: MayAsk<R>,\n): Effect.Effect<MayRules, never, R> => {\n const attachment = attached(entity)\n const named = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ row }) => Object.keys(row).filter(interaction => !builtInRow.has(interaction)),\n })\n const ruledMembers = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ members }) => Object.keys(members),\n })\n const ruledRelations = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ relations }) => Object.keys(relations),\n })\n return Effect.map(\n Effect.all([\n Effect.forEach(['Update', 'Delete', ...named], interaction =>\n Effect.map(ask.row(interaction), rule => [interaction, rule] as const),\n ),\n ask.members(ruledMembers),\n Effect.forEach(ruledRelations, relation =>\n Effect.map(\n Effect.all([ask.relation(relation, 'Link'), ask.relation(relation, 'Unlink')]),\n ([link, unlink]) => ({ relation, link, unlink }),\n ),\n ),\n ]),\n ([rows, members, relations]) => ({ rows, members, relations }),\n )\n}\n\n/** Every condition the rules hold a row to. */\nexport const mayConditions = (rules: MayRules): ReadonlyArray<Condition> => [\n ...rules.rows.map(([, { condition }]) => condition),\n ...rules.members.map(({ condition }) => condition),\n ...rules.relations.flatMap(({ link, unlink }) =>\n [...Option.toArray(link), ...Option.toArray(unlink)].map(({ condition }) => condition),\n ),\n]\n\n/**\n * The answer over one row, each condition decided by `decide`. A row\n * interaction it cannot decide over one row (a rule reading another row,\n * which the write's statement judges) is left out, and so refuses nothing.\n */\nexport const answerOf = (\n rules: MayRules,\n decide: (condition: Condition) => Option.Option<boolean>,\n): MayAnswer => {\n // Member and relation rules never read another row (`Guards.attach` refuses one).\n const holds = (condition: Condition) => Option.getOrElse(decide(condition), () => false)\n // A relation without a rule for one direction leaves it to the row's Update.\n const allows = (rule: Option.Option<RowRule>) =>\n Option.match(rule, { onNone: () => true, onSome: ({ condition }) => holds(condition) })\n const decided = rules.rows.flatMap(([interaction, rule]) =>\n Option.match(decide(rule.condition), {\n onNone: () => [],\n onSome: answer => [{ interaction, rule, answer }],\n }),\n )\n return {\n row: Object.fromEntries(decided.map(({ interaction, answer }) => [interaction, answer])),\n // Only an `explain`'s sentence is for whoever asked.\n reasons: Object.fromEntries(\n decided.flatMap(({ interaction, rule: { deny }, answer }) =>\n answer\n ? []\n : Match.valueTags(deny, {\n Explain: ({ reason }) => [[interaction, reason] as const],\n Forbidden: () => [],\n NotFound: () => [],\n Omit: () => [],\n Redact: () => [],\n }),\n ),\n ),\n members: Object.fromEntries(\n rules.members.map(({ member, condition }) => [member, holds(condition)]),\n ),\n relations: Object.fromEntries(\n rules.relations.map(({ relation, link, unlink }) => [\n relation,\n { Link: allows(link), Unlink: allows(unlink) },\n ]),\n ),\n }\n}\n\n/**\n * `may` foreseen for a row the client writes. A principal guard's body is\n * the server's, and the principal's fields are not the client's to know, so\n * each is unknown, as is a rule over a row or field the store lacks. Every\n * rule is a conjunction and disjunction of its parts, so it is decided when\n * it comes out the same with every unknown part taken to hold and taken not\n * to: the answer is foreseen only when the whole of it is.\n */\nconst predict: Predict = ({ entity, row, rows, context }) => {\n // Never a visitor here: a client without a viewer may be one that was not told it.\n const answerAssuming = (assumed: boolean): MayAnswer => {\n const decide = (interaction: string) =>\n deciding(() => Effect.succeed(assumed), false, interaction, context)\n const rules = Effect.runSync(\n mayRules(entity, {\n row: interaction => decide(interaction).row(entity),\n members: members => decide('Update').members(entity, members),\n relation: (relation, interaction) => decide(interaction).relation(entity, relation),\n }),\n )\n return answerOf(rules, condition => Option.some(Condition.judge(condition, row, rows, assumed)))\n }\n const held = answerAssuming(true)\n return sameMay(held, answerAssuming(false)) ? Option.some(held) : Option.none()\n}\n\n/** Whether `answer` names `key`, and says no to it. */\nconst refuses = (answer: Readonly<Record<string, boolean>>, key: string): boolean =>\n Object.hasOwn(answer, key) && answer[key] === false\n\n/**\n * The write a held `may` refuses, as the server would: the row's `Update` or\n * `Delete`, a written member's own `Update`, a relation's `Link` or `Unlink`,\n * each judged over the row as read, where the answer says `false`. What it\n * does not name refuses nothing, and neither does a value that is no answer.\n */\nconst forbids: Forbids = (value, surface) => {\n if (!isMay(value)) return Option.none()\n // Only a row interaction's refusal carries the `explain` the server would give.\n if (refuses(value.row, surface.kind)) {\n return Option.some({\n reason: Option.fromUndefinedOr(\n Object.hasOwn(value.reasons, surface.kind) ? value.reasons[surface.kind] : undefined,\n ),\n })\n }\n const member = surface.members.some(key => refuses(value.members, key))\n const relation = surface.relations.some(\n ({ relation, interaction }) =>\n Object.hasOwn(value.relations, relation) && !value.relations[relation]![interaction],\n )\n return member || relation ? Option.some({ reason: Option.none() }) : Option.none()\n}\n\nexport const May = {\n /**\n * Adds the `may` member to an Entity, after its guards are attached:\n * `TodoFields.pipe(Guards.attach(G, { … }), Guards.may)`. Select it as any\n * member (`may: true`); `GuardServer.filter` answers it. A client holding it\n * refuses, where it is made, a write it says no to (`Forbidden`).\n */\n member: Entity.derived({ may: Derived.make(MaySchema, { predict, forbids }) }),\n\n /**\n * Whether the row's rule for `interaction` let the principal, when it was\n * read. An interaction the answer does not name was not ruled where the row\n * was read, and reads `false`: a hint errs on the side of asking.\n */\n can: (may: MayAnswer, interaction: 'Update' | 'Delete' | InteractionKey): boolean =>\n can(may, interaction),\n\n /**\n * Why the row's rule for `interaction` refused, when it was refused with an\n * `explain`: words for whoever asked. None where it was allowed (the server\n * gives none then), or refused without one.\n */\n reason: (\n may: MayAnswer,\n interaction: 'Update' | 'Delete' | InteractionKey,\n ): Option.Option<string> => Record.get(may.reasons, interaction),\n\n /** Whether the principal may set `member` on this row: the row's `Update`, and the member's own rule. */\n canSet: <E extends AnyEntity>(may: MayAnswer, _entity: E, member: MemberKeys<E>): boolean =>\n setting(may, member),\n\n /** Whether the principal may point `relation` at a row, or away from one. */\n canLink: <E extends AnyEntity>(\n may: MayAnswer,\n _entity: E,\n relation: keyof E['relations'] & string,\n interaction: 'Link' | 'Unlink',\n ): boolean => linking(may, relation, interaction),\n\n /**\n * `foldkit-crud`'s `locks` for `entity`: an editor loads `may` beside the\n * form's members and locks each the reader may not set. A relation is locked\n * unless it may be both unlinked and linked. Nothing is locked while `may`\n * is not answered (a Source without the filter): the write is checked anyway.\n *\n * ```ts\n * Crud.editor('todo', { form, mutation: EditTodo, locks: May.locks(Todo) })\n * ```\n */\n locks: (entity: AnyEntity) => ({\n select: { may: true } as const,\n locked: (row: Readonly<Record<string, unknown>>, member: string): boolean => {\n const may = row.may\n if (!isMay(may)) return false\n return Object.hasOwn(entity.relations, member)\n ? !(linking(may, member, 'Unlink') && linking(may, member, 'Link'))\n : !setting(may, member)\n },\n }),\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,MAAa,YAAY,OAAO,OAAO;CACrC,KAAK,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;CAChD,SAAS,OAAO,OAAO,OAAO,QAAQ,OAAO,MAAM;CACnD,SAAS,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;CACpD,WAAW,OAAO,OAChB,OAAO,QACP,OAAO,OAAO;EAAE,MAAM,OAAO;EAAS,QAAQ,OAAO;CAAQ,CAAC,CAChE;AACF,CAAC;AAKD,MAAM,OAAO,KAAgB,gBAAiC,IAAI,IAAI,iBAAiB;;AAGvF,MAAM,WAAW,KAAgB,WAC/B,IAAI,KAAK,QAAQ,MAAM,CAAC,OAAO,OAAO,IAAI,SAAS,MAAM,KAAK,IAAI,QAAQ,YAAY;;AAGxF,MAAM,WAAW,KAAgB,UAAk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AAE,QAAQ,OAAO,KAAK,EAAE,CAAC,IAAI,OAAO,KAAK;AACnF;AAEA,MAAa,MAAM;;;;;;;CAOjB,QAAQ,OAAO,QAAQ,EAAE,KAAK,QAAQ,KAAK,WAAW;EAAE;EAAS;CAAQ,CAAC,EAAE,CAAC;;;;;;CAO7E,MAAM,KAAgB,gBACpB,IAAI,KAAK,WAAW;;;;;;CAOtB,SACE,KACA,gBAC0B,OAAO,IAAI,IAAI,SAAS,WAAW;;CAG/D,SAA8B,KAAgB,SAAY,WACxD,QAAQ,KAAK,MAAM;;CAGrB,UACE,KACA,SACA,UACA,gBACY,QAAQ,KAAK,UAAU,WAAW;;;;;;;;;;;CAYhD,QAAQ,YAAuB;EAC7B,QAAQ,EAAE,KAAK,KAAK;EACpB,SAAS,KAAwC,WAA4B;GAC3E,MAAM,MAAM,IAAI;GAChB,IAAI,CAAC,MAAM,GAAG,GAAG,OAAO;GACxB,OAAO,OAAO,OAAO,OAAO,WAAW,MAAM,IACzC,EAAE,QAAQ,KAAK,QAAQ,QAAQ,KAAK,QAAQ,KAAK,QAAQ,MAAM,KAC/D,CAAC,QAAQ,KAAK,MAAM;EAC1B;CACF;AACF"}
@@ -1,5 +1,5 @@
1
- import { t as Attaching } from "./attach-CRCF5XHS.mjs";
2
- import { t as May } from "./may-DzCAt_5M.mjs";
1
+ import { t as Attaching } from "./attach-CEGlbWu5.mjs";
2
+ import { t as May } from "./may-DprCmMgK.mjs";
3
3
  import { Schema } from "effect";
4
4
  import { Entity } from "foldkit-entity";
5
5
  // src/me.ts
@@ -36,4 +36,4 @@ const me = (G, options = {}) => MeFields.pipe(Attaching.attach(G, {
36
36
  }), May.member);
37
37
  export { me as n, ME as t };
38
38
 
39
- //# sourceMappingURL=me-BYpuVqJE.mjs.map
39
+ //# sourceMappingURL=me-C-gX1paZ.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"me-BYpuVqJE.mjs","names":[],"sources":["../src/me.ts"],"sourcesContent":["/**\n * The visitor as an Entity: one row, `me`, answered for whoever asks. What a\n * client knows about itself (signed in, as whom, what it may open) is read\n * through Remote like any row, `may` included, so no rule runs on the client.\n */\nimport { Schema } from 'effect'\nimport { Entity } from 'foldkit-entity'\nimport { Attaching, type Attach } from './attach.js'\nimport { May } from './may.js'\n\n/** The one row's id. */\nexport const ME = 'me'\n\nconst MeFields = Entity.define(\n 'Me',\n Schema.Struct({\n id: Schema.String,\n /** Whether the server answered as someone. */\n signedIn: Schema.Boolean,\n /** Who the server answered as: `declare`'s `key` of the principal. */\n key: Schema.OptionFromNullOr(Schema.String),\n }),\n)\n\n/** `Me`'s Entity, with `may`. */\nexport type MeEntity = ReturnType<typeof May.member<typeof MeFields>>\n\n/**\n * `Me` for guard set `G`: everyone reads their own row, no one writes it, and\n * each interaction is answered in `may` as `G`'s bodies decide it for the\n * asker (`May.can(me.may, OpenAdmin.key)`).\n *\n * ```ts\n * const OpenAdmin = Interaction.make('OpenAdmin')\n * export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })\n * ```\n */\nexport const me = <Name extends string, User>(\n G: {\n readonly name: Name\n readonly schema: Schema.Codec<User, unknown>\n readonly unguarded: 'allow' | 'deny'\n },\n options: {\n readonly interactions?: Attach<NoInfer<User>, NoInfer<Name>, typeof MeFields>['interactions']\n } = {},\n): MeEntity =>\n MeFields.pipe(\n Attaching.attach(G, {\n row: { Read: [Attaching.anyone], Write: [] },\n ...(options.interactions === undefined ? {} : { interactions: options.interactions }),\n }),\n May.member,\n )\n"],"mappings":";;;;;;;;;;;AAWA,MAAa,KAAK;AAElB,MAAM,WAAW,OAAO,OACtB,MACA,OAAO,OAAO;CACZ,IAAI,OAAO;;CAEX,UAAU,OAAO;;CAEjB,KAAK,OAAO,iBAAiB,OAAO,MAAM;AAC5C,CAAC,CACH;;;;;;;;;;;AAeA,MAAa,MACX,GAKA,UAEI,CAAC,MAEL,SAAS,KACP,UAAU,OAAO,GAAG;CAClB,KAAK;EAAE,MAAM,CAAC,UAAU,MAAM;EAAG,OAAO,CAAC;CAAE;CAC3C,GAAI,QAAQ,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc,QAAQ,aAAa;AACrF,CAAC,GACD,IAAI,MACN"}
1
+ {"version":3,"file":"me-C-gX1paZ.mjs","names":[],"sources":["../src/me.ts"],"sourcesContent":["/**\n * The visitor as an Entity: one row, `me`, answered for whoever asks. What a\n * client knows about itself (signed in, as whom, what it may open) is read\n * through Remote like any row, `may` included, so no rule runs on the client.\n */\nimport { Schema } from 'effect'\nimport { Entity } from 'foldkit-entity'\nimport { Attaching, type Attach } from './attach.js'\nimport { May } from './may.js'\n\n/** The one row's id. */\nexport const ME = 'me'\n\nconst MeFields = Entity.define(\n 'Me',\n Schema.Struct({\n id: Schema.String,\n /** Whether the server answered as someone. */\n signedIn: Schema.Boolean,\n /** Who the server answered as: `declare`'s `key` of the principal. */\n key: Schema.OptionFromNullOr(Schema.String),\n }),\n)\n\n/** `Me`'s Entity, with `may`. */\nexport type MeEntity = ReturnType<typeof May.member<typeof MeFields>>\n\n/**\n * `Me` for guard set `G`: everyone reads their own row, no one writes it, and\n * each interaction is answered in `may` as `G`'s bodies decide it for the\n * asker (`May.can(me.may, OpenAdmin.key)`).\n *\n * ```ts\n * const OpenAdmin = Interaction.make('OpenAdmin')\n * export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })\n * ```\n */\nexport const me = <Name extends string, User>(\n G: {\n readonly name: Name\n readonly schema: Schema.Codec<User, unknown>\n readonly unguarded: 'allow' | 'deny'\n },\n options: {\n readonly interactions?: Attach<NoInfer<User>, NoInfer<Name>, typeof MeFields>['interactions']\n } = {},\n): MeEntity =>\n MeFields.pipe(\n Attaching.attach(G, {\n row: { Read: [Attaching.anyone], Write: [] },\n ...(options.interactions === undefined ? {} : { interactions: options.interactions }),\n }),\n May.member,\n )\n"],"mappings":";;;;;;;;;;;AAWA,MAAa,KAAK;AAElB,MAAM,WAAW,OAAO,OACtB,MACA,OAAO,OAAO;CACZ,IAAI,OAAO;;CAEX,UAAU,OAAO;;CAEjB,KAAK,OAAO,iBAAiB,OAAO,MAAM;AAC5C,CAAC,CACH;;;;;;;;;;;AAeA,MAAa,MACX,GAKA,UAEI,CAAC,MAEL,SAAS,KACP,UAAU,OAAO,GAAG;CAClB,KAAK;EAAE,MAAM,CAAC,UAAU,MAAM;EAAG,OAAO,CAAC;CAAE;CAC3C,GAAI,QAAQ,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc,QAAQ,aAAa;AACrF,CAAC,GACD,IAAI,MACN"}
package/dist/media.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as PrincipalGuard, S as Policy } from "./attach-BepaL930.mjs";
1
+ import { C as PrincipalGuard, S as Policy } from "./attach-DPgyv78F.mjs";
2
2
  import { Effect, Layer, Option } from "effect";
3
3
  import { UploadPolicy } from "foldkit-media/server";
4
4
  export interface UploadPolicyConfig<User, E, R> {
@@ -1,4 +1,4 @@
1
- import { r as attached } from "./attach-CRCF5XHS.mjs";
1
+ import { r as attached } from "./attach-CEGlbWu5.mjs";
2
2
  import { t as originOf } from "./origin-igJoiz74.mjs";
3
3
  import { Option } from "effect";
4
4
  // src/placed.ts
@@ -36,4 +36,4 @@ const memberRules = record(/* @__PURE__ */ new WeakMap());
36
36
  const writeRules = record(/* @__PURE__ */ new WeakMap());
37
37
  export { rowRules as n, writeRules as r, memberRules as t };
38
38
 
39
- //# sourceMappingURL=placed-BvdNmZJu.mjs.map
39
+ //# sourceMappingURL=placed-CGyo-NRR.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"placed-BvdNmZJu.mjs","names":[],"sources":["../src/placed.ts"],"sourcesContent":["/**\n * What each guard seam built, and for which Policy and Entities, so\n * `GuardServer.validate` can tell a Source that applies a guard set's rules\n * from one that only looks as if it does.\n */\nimport { Option } from 'effect'\nimport type { AnyEntity } from 'foldkit-entity'\nimport { attached, type Attachment } from './attach.js'\nimport type { Policy } from './index.js'\nimport { originOf } from './origin.js'\n\ninterface Placed {\n readonly policy: Policy<any, any>\n /** Each Entity's attachment as it was built from: none for one built before `attach`. */\n readonly entities: ReadonlyMap<string, Attachment | undefined>\n}\n\n/** An Entity's guards, by identity: the same attachment is the same rules. */\nconst guardsOf = (entity: AnyEntity) => Option.getOrUndefined(attached(entity))\n\nconst record = (registry: WeakMap<object, Placed>) => ({\n add: <F extends object>(built: F, policy: Policy<any, any>, entities: Iterable<AnyEntity>): F => {\n registry.set(built, {\n policy,\n entities: new Map([...entities].map(entity => [entity.name, guardsOf(entity)])),\n })\n return built\n },\n /**\n * Whether `built` applies `entity`'s guards from `policy`: built for it,\n * not for another Entity of its name, nor for it before its guards were\n * attached, which decides nothing.\n */\n has: (built: unknown, policy: Policy<any, any>, entity: AnyEntity): boolean => {\n if (typeof built !== 'function' && (typeof built !== 'object' || built === null)) return false\n const placed = registry.get(built)\n return (\n placed !== undefined &&\n originOf(placed.policy) === originOf(policy) &&\n placed.entities.has(entity.name) &&\n placed.entities.get(entity.name) === guardsOf(entity)\n )\n },\n})\n\n/** Row rules: `GuardDrizzle.visible`'s, and `GuardServer.memory`'s `readable`. */\nexport const rowRules = record(new WeakMap())\n\n/** Member and relation rules: `GuardServer.filter`'s. */\nexport const memberRules = record(new WeakMap())\n\n/** Write rules: `GuardServer.writer`'s. */\nexport const writeRules = record(new WeakMap())\n"],"mappings":";;;;;;;;;;AAkBA,MAAM,YAAY,WAAsB,OAAO,eAAe,SAAS,MAAM,CAAC;AAE9E,MAAM,UAAU,cAAuC;CACrD,MAAwB,OAAU,QAA0B,aAAqC;EAC/F,SAAS,IAAI,OAAO;GAClB;GACA,UAAU,IAAI,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC,KAAI,WAAU,CAAC,OAAO,MAAM,SAAS,MAAM,CAAC,CAAC,CAAC;EAChF,CAAC;EACD,OAAO;CACT;;;;;;CAMA,MAAM,OAAgB,QAA0B,WAA+B;EAC7E,IAAI,OAAO,UAAU,eAAe,OAAO,UAAU,YAAY,UAAU,OAAO,OAAO;EACzF,MAAM,SAAS,SAAS,IAAI,KAAK;EACjC,OACE,WAAW,KAAA,KACX,SAAS,OAAO,MAAM,MAAM,SAAS,MAAM,KAC3C,OAAO,SAAS,IAAI,OAAO,IAAI,KAC/B,OAAO,SAAS,IAAI,OAAO,IAAI,MAAM,SAAS,MAAM;CAExD;AACF;;AAGA,MAAa,WAAW,uBAAO,IAAI,QAAQ,CAAC;;AAG5C,MAAa,cAAc,uBAAO,IAAI,QAAQ,CAAC;;AAG/C,MAAa,aAAa,uBAAO,IAAI,QAAQ,CAAC"}
1
+ {"version":3,"file":"placed-CGyo-NRR.mjs","names":[],"sources":["../src/placed.ts"],"sourcesContent":["/**\n * What each guard seam built, and for which Policy and Entities, so\n * `GuardServer.validate` can tell a Source that applies a guard set's rules\n * from one that only looks as if it does.\n */\nimport { Option } from 'effect'\nimport type { AnyEntity } from 'foldkit-entity'\nimport { attached, type Attachment } from './attach.js'\nimport type { Policy } from './index.js'\nimport { originOf } from './origin.js'\n\ninterface Placed {\n readonly policy: Policy<any, any>\n /** Each Entity's attachment as it was built from: none for one built before `attach`. */\n readonly entities: ReadonlyMap<string, Attachment | undefined>\n}\n\n/** An Entity's guards, by identity: the same attachment is the same rules. */\nconst guardsOf = (entity: AnyEntity) => Option.getOrUndefined(attached(entity))\n\nconst record = (registry: WeakMap<object, Placed>) => ({\n add: <F extends object>(built: F, policy: Policy<any, any>, entities: Iterable<AnyEntity>): F => {\n registry.set(built, {\n policy,\n entities: new Map([...entities].map(entity => [entity.name, guardsOf(entity)])),\n })\n return built\n },\n /**\n * Whether `built` applies `entity`'s guards from `policy`: built for it,\n * not for another Entity of its name, nor for it before its guards were\n * attached, which decides nothing.\n */\n has: (built: unknown, policy: Policy<any, any>, entity: AnyEntity): boolean => {\n if (typeof built !== 'function' && (typeof built !== 'object' || built === null)) return false\n const placed = registry.get(built)\n return (\n placed !== undefined &&\n originOf(placed.policy) === originOf(policy) &&\n placed.entities.has(entity.name) &&\n placed.entities.get(entity.name) === guardsOf(entity)\n )\n },\n})\n\n/** Row rules: `GuardDrizzle.visible`'s, and `GuardServer.memory`'s `readable`. */\nexport const rowRules = record(new WeakMap())\n\n/** Member and relation rules: `GuardServer.filter`'s. */\nexport const memberRules = record(new WeakMap())\n\n/** Write rules: `GuardServer.writer`'s. */\nexport const writeRules = record(new WeakMap())\n"],"mappings":";;;;;;;;;;AAkBA,MAAM,YAAY,WAAsB,OAAO,eAAe,SAAS,MAAM,CAAC;AAE9E,MAAM,UAAU,cAAuC;CACrD,MAAwB,OAAU,QAA0B,aAAqC;EAC/F,SAAS,IAAI,OAAO;GAClB;GACA,UAAU,IAAI,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC,KAAI,WAAU,CAAC,OAAO,MAAM,SAAS,MAAM,CAAC,CAAC,CAAC;EAChF,CAAC;EACD,OAAO;CACT;;;;;;CAMA,MAAM,OAAgB,QAA0B,WAA+B;EAC7E,IAAI,OAAO,UAAU,eAAe,OAAO,UAAU,YAAY,UAAU,OAAO,OAAO;EACzF,MAAM,SAAS,SAAS,IAAI,KAAK;EACjC,OACE,WAAW,KAAA,KACX,SAAS,OAAO,MAAM,MAAM,SAAS,MAAM,KAC3C,OAAO,SAAS,IAAI,OAAO,IAAI,KAC/B,OAAO,SAAS,IAAI,OAAO,IAAI,MAAM,SAAS,MAAM;CAExD;AACF;;AAGA,MAAa,WAAW,uBAAO,IAAI,QAAQ,CAAC;;AAG5C,MAAa,cAAc,uBAAO,IAAI,QAAQ,CAAC;;AAG/C,MAAa,aAAa,uBAAO,IAAI,QAAQ,CAAC"}
package/dist/server.d.mts CHANGED
@@ -1,8 +1,29 @@
1
- import { S as Policy, k as MeEntity, l as InteractionKey } from "./attach-BepaL930.mjs";
1
+ import { S as Policy, k as MeEntity, l as InteractionKey } from "./attach-DPgyv78F.mjs";
2
2
  import { Effect, Option } from "effect";
3
3
  import { AnyEntity, AnyQuery } from "foldkit-entity";
4
+ import { Diagnostic, MutationDescriptor, RemoteForbidden, ReportDiagnostic } from "foldkit-remote";
4
5
  import { EntitySource, EntityWriter, MemoryReadable, MutationOutcome, MutationRefused, MutationSource, ReadPlan, RemoteServerError, ServerDefinition } from "foldkit-remote-server";
5
- import { MutationDescriptor, RemoteForbidden } from "foldkit-remote";
6
+ /**
7
+ * An operator refused to work out a value a guarded write computes (text
8
+ * holding NUL, an implementation that throws). The write was refused with a
9
+ * fixed message, since the operator's own may say anything.
10
+ */
11
+ interface ComputeRefused extends Diagnostic {
12
+ readonly _tag: 'ComputeRefused';
13
+ readonly entity: string;
14
+ /** The operator's own refusal. */
15
+ readonly error: Error;
16
+ }
17
+ /**
18
+ * Writes through a `GuardServer.writer` given no revision, where a change can
19
+ * come between the check and the write, which is then not seen.
20
+ */
21
+ interface UnpinnedWrites extends Diagnostic {
22
+ readonly _tag: 'UnpinnedWrites';
23
+ readonly mutations: ReadonlyArray<string>;
24
+ }
25
+ /** Every diagnostic `foldkit-guard` reports. */
26
+ type GuardDiagnostic = ComputeRefused | UnpinnedWrites;
6
27
  export declare const GuardServer: {
7
28
  /**
8
29
  * `Guards.me`'s Source: the one row, `me`, as the asker is, with `may`
@@ -41,19 +62,25 @@ export declare const GuardServer: {
41
62
  * `RemoteServer.write`. An update or a delete reads the row first under
42
63
  * the writer's own `read` (its Source's read rule): a row the writer may not
43
64
  * see is refused as one that is not there, and a delete of it changes
44
- * nothing. Then the row's rule for the command must hold over the row (an
45
- * update's over the row as it would be after it too, so a write cannot move
46
- * a row out of its writer's reach), each member it sets must allow setting
47
- * it, and each relation it points elsewhere must allow the unlink and the
48
- * link. A create's rules hold over the values it proposes, where a field the
65
+ * nothing. Then the row's rule for the command must hold over the row, each
66
+ * member it sets must allow setting it, and each relation it points
67
+ * elsewhere must allow the unlink and the link. An update's row rule holds
68
+ * over the row as it would be after it too, so a write cannot move a row out
69
+ * of its writer's reach. Each of its member and `Link` rules holds over the
70
+ * row after with that one change undone (that member's value, or where that
71
+ * relation pointed, as before): the change must be allowed given everything
72
+ * else the write does, so one write cannot set together what each change
73
+ * alone would be refused, while a rule reading its own member ("only while
74
+ * a draft") still allows the change. An increment or a computed assignment
75
+ * to a member is that member's own change. An `Unlink` rule holds over the
76
+ * row before alone. A create's rules hold over the values it proposes, where a field the
49
77
  * create leaves unset matches no guard, not even one for an empty value. A refusal is
50
78
  * `Forbidden`, with the sentence an `explain` gave; the write never runs.
51
79
  *
52
- * `presets` are fields a create takes from who is asking, never from the
53
- * client (`ownerId: user => user.id`): set before the rules are checked, so
54
- * a rule over them holds of the creator. A visitor has nothing to preset
55
- * from, and a create whose input sets a preset field is a mistake of the
56
- * server's, refused.
80
+ * What the Entity sets from the write's context (`Entity.sets`: who asks,
81
+ * when) reaches a create or an update already set by `RemoteServer.write`,
82
+ * so a rule over it holds of the creator. A member rule over such a member
83
+ * judges the server's value like any other: declare none there.
57
84
  *
58
85
  * `revision` names a field stored as a number, which the writer moves on by
59
86
  * one with each write it lands. An update or a delete then lands only on the
@@ -61,7 +88,8 @@ export declare const GuardServer: {
61
88
  * between the check and the write is never written over; it is decided
62
89
  * again against the row as it now is, up to three times. A change that does
63
90
  * not move the revision (a handler's, `applyEdits`', raw SQL) is not seen.
64
- * Without `revision`, none is, and `validate` warns. An input that expects a
91
+ * Without `revision`, none is, and `validate` warns of an update, or a delete
92
+ * of an Entity the server updates (an insert has no row). An input that expects a
65
93
  * revision the row read is not at is a `Conflict`, decided before any rule;
66
94
  * an input may expect only the field the writer pins.
67
95
  *
@@ -70,7 +98,6 @@ export declare const GuardServer: {
70
98
  * ```
71
99
  */
72
100
  writer: <E extends AnyEntity, User, R, RW>(entity: E, policy: Policy<User, R>, writer: EntityWriter<Option.Option<User>, RW>, options?: {
73
- readonly presets?: { readonly [K in keyof E['fields']]?: (user: User) => E['fields'][K]['schema']['Type']; };
74
101
  readonly revision?: keyof E['fields'] & string;
75
102
  }) => EntityWriter<Option.Option<User>, R | RW>;
76
103
  /**
@@ -120,11 +147,14 @@ export declare const GuardServer: {
120
147
  * `GuardServer.memory`), its Source applies its members' and relations'
121
148
  * (`GuardServer.filter`), and each declared write of it lands through
122
149
  * `GuardServer.writer`, all built from `policy`; and that no query's body
123
- * filters or orders by a member with a Read rule, which would answer for the
124
- * value it hides. A hand-written Source over a guarded Entity would serve
150
+ * filters or orders by a member with a Read rule, its own or one of a row it
151
+ * reaches through a path or an exists, which would answer for the value it
152
+ * hides. A hand-written Source over a guarded Entity would serve
125
153
  * every row, and a bare writer would take every write; this throws instead,
126
154
  * naming each. A handler (`RemoteServer.mutation`) writes what its code
127
- * writes, which no check at startup can read.
155
+ * writes, which no check at startup can read. A write a change can come
156
+ * between, through a writer given no revision, is not refused but reported:
157
+ * `UnpinnedWrites`, a warning, to `diagnostics`.
128
158
  *
129
159
  * ```ts
130
160
  * GuardServer.validate(Policy, { entities: [Todo, Project], domain: Data, server: Server })
@@ -142,6 +172,9 @@ export declare const GuardServer: {
142
172
  };
143
173
  };
144
174
  readonly server: ServerDefinition<any, any>;
175
+ /** Where the `UnpinnedWrites` warning goes; `Diagnostics.Reporter`'s default, the log, when not given. */
176
+ readonly diagnostics?: ReportDiagnostic | undefined;
145
177
  }) => void;
146
178
  };
179
+ export type { ComputeRefused, GuardDiagnostic, UnpinnedWrites };
147
180
  //# sourceMappingURL=server.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.mts","names":[],"sources":["../src/server.ts"],"mappings":";;;;;qBA4Ea;;;;;;;;;;EAUX,KAAK,MAAM,GAAC,QACF,UAAQ,QACR,OAAO,MAAM,OACpB,aAAa,OAAO,OAAO,OAAO;;;;;;;;;;EA6CrC,SAAS,MAAM,GAAC,QAAU,WAAS,QAAU,OAAO,MAAM,QAAE,WAG3C,OAAO,OAAO,OAAK,8BAE7B,OAAO,OAAO,iBAAiB;;;;;;;EAuEtC,SAAS,MAAI,QAAU,OAAO,OAAK,UAAY,cAAc;IAC3D,WAAQ,WAEO,OAAO,OAAO,OAAK,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