foldkit-guard 0.3.1 → 0.5.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 (40) hide show
  1. package/README.md +73 -7
  2. package/dist/agent.d.mts +1 -3
  3. package/dist/agent.d.mts.map +1 -1
  4. package/dist/agent.mjs +2 -3
  5. package/dist/{attach-BVG6LsFf.d.mts → attach-BnP9_Uca.d.mts} +18 -15
  6. package/dist/attach-BnP9_Uca.d.mts.map +1 -0
  7. package/dist/{attach-BZyVvs7H.mjs → attach-CRCF5XHS.mjs} +16 -4
  8. package/dist/attach-CRCF5XHS.mjs.map +1 -0
  9. package/dist/{condition-Dunujvzy.mjs → condition-Bl1UgEpM.mjs} +6 -6
  10. package/dist/condition-Bl1UgEpM.mjs.map +1 -0
  11. package/dist/drizzle.d.mts +8 -5
  12. package/dist/drizzle.d.mts.map +1 -1
  13. package/dist/drizzle.mjs +11 -14
  14. package/dist/drizzle.mjs.map +1 -1
  15. package/dist/index.d.mts +1 -1
  16. package/dist/index.mjs +12 -11
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/{may-DK-2lomO.mjs → may-DzCAt_5M.mjs} +2 -3
  19. package/dist/{may-DK-2lomO.mjs.map → may-DzCAt_5M.mjs.map} +1 -1
  20. package/dist/{me-DeSZOGt3.mjs → me-BYpuVqJE.mjs} +4 -5
  21. package/dist/{me-DeSZOGt3.mjs.map → me-BYpuVqJE.mjs.map} +1 -1
  22. package/dist/media.d.mts +1 -3
  23. package/dist/media.d.mts.map +1 -1
  24. package/dist/media.mjs +1 -2
  25. package/dist/{origin-CN6ThFTp.mjs → origin-igJoiz74.mjs} +2 -3
  26. package/dist/{origin-CN6ThFTp.mjs.map → origin-igJoiz74.mjs.map} +1 -1
  27. package/dist/{placed-CkyMqxFw.mjs → placed-BvdNmZJu.mjs} +4 -5
  28. package/dist/{placed-CkyMqxFw.mjs.map → placed-BvdNmZJu.mjs.map} +1 -1
  29. package/dist/server.d.mts +12 -3
  30. package/dist/server.d.mts.map +1 -1
  31. package/dist/server.mjs +211 -67
  32. package/dist/server.mjs.map +1 -1
  33. package/dist/sync.d.mts +1 -3
  34. package/dist/sync.d.mts.map +1 -1
  35. package/dist/sync.mjs +4 -5
  36. package/dist/sync.mjs.map +1 -1
  37. package/package.json +14 -14
  38. package/dist/attach-BVG6LsFf.d.mts.map +0 -1
  39. package/dist/attach-BZyVvs7H.mjs.map +0 -1
  40. package/dist/condition-Dunujvzy.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,11 +1,11 @@
1
- import { n as Interaction, r as attached, t as Attaching } from "./attach-BZyVvs7H.mjs";
2
- import { n as deciding, r as readsPrincipal, t as Condition } from "./condition-Dunujvzy.mjs";
3
- import { n as MaySchema, t as May } from "./may-DK-2lomO.mjs";
4
- import { n as me, t as ME } from "./me-DeSZOGt3.mjs";
5
- import { n as providedFrom } from "./origin-CN6ThFTp.mjs";
1
+ import { n as Interaction, r as attached, t as Attaching } from "./attach-CRCF5XHS.mjs";
2
+ import { n as deciding, r as readsPrincipal, t as Condition } from "./condition-Bl1UgEpM.mjs";
3
+ import { n as MaySchema, t as May } from "./may-DzCAt_5M.mjs";
4
+ import { n as me, t as ME } from "./me-BYpuVqJE.mjs";
5
+ import { n as providedFrom } from "./origin-igJoiz74.mjs";
6
6
  import { Context, Effect, Match, Option, Schema } from "effect";
7
- import { Expr, Query, evaluate } from "foldkit-entity";
8
- //#region src/index.ts
7
+ import { Expr, Operators, Query, evaluate } from "foldkit-entity";
8
+ // src/index.ts
9
9
  /**
10
10
  * Who may do what, declared once on the domain.
11
11
  *
@@ -115,7 +115,8 @@ const Guards = {
115
115
  };
116
116
  const isPrincipal = Schema.is(Schema.Option(principal));
117
117
  const asJson = Schema.encodeSync(Schema.toCodecJson(principal));
118
- const implement = (bodies) => {
118
+ const implement = (bodies, implementation = {}) => {
119
+ const operators = implementation.operators ?? Operators.kernel;
119
120
  const missing = principalNames.filter((guard) => !Object.hasOwn(bodies, guard));
120
121
  const extra = Object.keys(bodies).filter((guard) => !principalNames.includes(guard));
121
122
  if (missing.length > 0 || extra.length > 0) throw new Error(`[foldkit-guard] ${name}.implement: ${[missing.length > 0 ? `no body for ${missing.join(", ")}` : "", extra.length > 0 ? `${extra.join(", ")} is not a principal guard` : ""].filter((part) => part !== "").join("; ")}`);
@@ -127,8 +128,8 @@ const Guards = {
127
128
  return Effect.isEffect(decided) ? decided : Effect.succeed(decided);
128
129
  },
129
130
  RowGuard: (rowGuard) => Effect.succeed(row !== void 0 && Option.match(principal, {
130
- onNone: () => !readsPrincipal(rowGuard) && evaluate(rowGuard.query, {}, [row]).length === 1,
131
- onSome: (user) => evaluate(rowGuard.query, inputOf(user), [row]).length === 1
131
+ onNone: () => !readsPrincipal(rowGuard) && evaluate(rowGuard.query, {}, [row], { operators }).length === 1,
132
+ onSome: (user) => evaluate(rowGuard.query, inputOf(user), [row], { operators }).length === 1
132
133
  }))
133
134
  });
134
135
  };
@@ -143,6 +144,7 @@ const Guards = {
143
144
  };
144
145
  const policy = {
145
146
  set: name,
147
+ operators,
146
148
  decide,
147
149
  readable: (entity, principal) => Effect.map(decidingFor(entity, principal, "Read").row(entity), ({ condition }) => condition),
148
150
  readMembers: (entity, principal, members) => decidingFor(entity, principal, "Read").members(entity, members),
@@ -175,7 +177,6 @@ const Guards = {
175
177
  });
176
178
  }
177
179
  };
178
- //#endregion
179
180
  export { Condition, Guards, Interaction, ME, May, MaySchema };
180
181
 
181
182
  //# sourceMappingURL=index.mjs.map
@@ -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 Query,\n evaluate,\n type AnyEntity,\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 /** The bodies of the principal guards: every one, and nothing else. */\n readonly implement: <R = never>(bodies: {\n readonly [K in PrincipalKeys<S>]: Body<User, R>\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 * 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>(bodies: Readonly<Record<string, Body<User, R>>>): Policy<User, R> => {\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) && evaluate(rowGuard.query, {}, [row]).length === 1,\n onSome: user => evaluate(rowGuard.query, inputOf(user), [row]).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 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":";;;;;;;;;;;;;;;;;;AA6GA,MAAM,WAAW;CACf;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AA8HA,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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BAC5B,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,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"}
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,CA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,MAAM,IAChD,EAAE,gBAAgB,SACrB;IACF,cAAc,QAAQ,WAAW,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,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"}
@@ -1,6 +1,6 @@
1
1
  import { Record, Schema } from "effect";
2
2
  import { Derived, Entity } from "foldkit-entity";
3
- //#region src/may.ts
3
+ // src/may.ts
4
4
  /**
5
5
  * `may`: what the server says a principal may do with a row, as a derived
6
6
  * member the client reads like any other. The client never runs a rule; this
@@ -70,7 +70,6 @@ const May = {
70
70
  }
71
71
  })
72
72
  };
73
- //#endregion
74
73
  export { MaySchema as n, May as t };
75
74
 
76
- //# sourceMappingURL=may-DK-2lomO.mjs.map
75
+ //# sourceMappingURL=may-DzCAt_5M.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"may-DK-2lomO.mjs","names":[],"sources":["../src/may.ts"],"sourcesContent":["/**\n * `may`: what the server says a principal may do with a row, as a derived\n * member the client reads like any other. The client never runs a rule; this\n * is the server's answer for the row as it was read, a hint for a greyed-out\n * button, never the check (the write is checked again when it is made).\n */\nimport { Option, Record, Schema } from 'effect'\nimport { Derived, Entity, type AnyEntity } from 'foldkit-entity'\nimport type { InteractionKey } from './attach.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)\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.\n */\n member: Entity.derived({ may: Derived.make(MaySchema) }),\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":";;;;;;;;;;;;;;;AAgBA,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,UAAkB,gBACjD,IAAI,KAAK,QAAQ,MAChB,CAAC,OAAO,OAAO,IAAI,WAAW,QAAQ,KAAK,IAAI,UAAU,SAAS,CAAE;AAEvE,MAAM,QAAQ,OAAO,GAAG,SAAS;AAEjC,MAAa,MAAM;;;;;;CAMjB,QAAQ,OAAO,QAAQ,EAAE,KAAK,QAAQ,KAAK,SAAS,EAAE,CAAC;;;;;;CAOvD,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
+ {"version":3,"file":"may-DzCAt_5M.mjs","names":[],"sources":["../src/may.ts"],"sourcesContent":["/**\n * `may`: what the server says a principal may do with a row, as a derived\n * member the client reads like any other. The client never runs a rule; this\n * is the server's answer for the row as it was read, a hint for a greyed-out\n * button, never the check (the write is checked again when it is made).\n */\nimport { Option, Record, Schema } from 'effect'\nimport { Derived, Entity, type AnyEntity } from 'foldkit-entity'\nimport type { InteractionKey } from './attach.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)\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.\n */\n member: Entity.derived({ may: Derived.make(MaySchema) }),\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":";;;;;;;;;;;;;;;AAgBA,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,UAAkB,gBACjD,IAAI,KAAK,QAAQ,MAChB,CAAC,OAAO,OAAO,IAAI,WAAW,QAAQ,KAAK,IAAI,UAAU,SAAS,CAAE;AAEvE,MAAM,QAAQ,OAAO,GAAG,SAAS;AAEjC,MAAa,MAAM;;;;;;CAMjB,QAAQ,OAAO,QAAQ,EAAE,KAAK,QAAQ,KAAK,SAAS,EAAE,CAAC;;;;;;CAOvD,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,8 +1,8 @@
1
- import { t as Attaching } from "./attach-BZyVvs7H.mjs";
2
- import { t as May } from "./may-DK-2lomO.mjs";
1
+ import { t as Attaching } from "./attach-CRCF5XHS.mjs";
2
+ import { t as May } from "./may-DzCAt_5M.mjs";
3
3
  import { Schema } from "effect";
4
4
  import { Entity } from "foldkit-entity";
5
- //#region src/me.ts
5
+ // src/me.ts
6
6
  /**
7
7
  * The visitor as an Entity: one row, `me`, answered for whoever asks. What a
8
8
  * client knows about itself (signed in, as whom, what it may open) is read
@@ -34,7 +34,6 @@ const me = (G, options = {}) => MeFields.pipe(Attaching.attach(G, {
34
34
  },
35
35
  ...options.interactions === void 0 ? {} : { interactions: options.interactions }
36
36
  }), May.member);
37
- //#endregion
38
37
  export { me as n, ME as t };
39
38
 
40
- //# sourceMappingURL=me-DeSZOGt3.mjs.map
39
+ //# sourceMappingURL=me-BYpuVqJE.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"me-DeSZOGt3.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-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"}
package/dist/media.d.mts CHANGED
@@ -1,7 +1,6 @@
1
- import { C as PrincipalGuard, S as Policy } from "./attach-BVG6LsFf.mjs";
1
+ import { C as PrincipalGuard, S as Policy } from "./attach-BnP9_Uca.mjs";
2
2
  import { Effect, Layer, Option } from "effect";
3
3
  import { UploadPolicy } from "foldkit-media/server";
4
- //#region src/media.d.ts
5
4
  export interface UploadPolicyConfig<User, E, R> {
6
5
  /**
7
6
  * Who is asking, from a request holding the upload's URL, method and
@@ -25,6 +24,5 @@ declare const uploadPolicy: <User, E, R>(policy: Policy<User>, config: UploadPol
25
24
  export declare const GuardMedia: {
26
25
  readonly uploadPolicy: typeof uploadPolicy;
27
26
  };
28
- //#endregion
29
27
  export {};
30
28
  //# sourceMappingURL=media.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"media.d.mts","names":[],"sources":["../src/media.ts"],"mappings":";;;;iBAkBiB,mBAAmB,MAAM,GAAG;;;;;;WAMlC,UAAU,SAAS,YAAY,OAAO,OAAO,OAAO,OAAO,OAAO,GAAG;;WAErE,SAAS,cAAc,eAAe;;WAEtC,cAAc,cAAc,eAAe;;;;;;;;;cAyBhD,eAAgB,MAAM,GAAG,GAAC,QACtB,OAAO,OAAK,QACZ,mBAAmB,MAAM,GAAG,OACnC,MAAM,MAAM,qBAAqB;qBAqBvB;gCAAA"}
1
+ {"version":3,"file":"media.d.mts","names":[],"sources":["../src/media.ts"],"mappings":";;;iBAkBiB,mBAAmB,MAAM,GAAG;;;;;;WAMlC,UAAU,SAAS,YAAY,OAAO,OAAO,OAAO,OAAO,OAAO,GAAG;;WAErE,SAAS,cAAc,eAAe;;WAEtC,cAAc,cAAc,eAAe;;;;;;;;;cAyBhD,eAAgB,MAAM,GAAG,GAAC,QACtB,OAAO,OAAK,QACZ,mBAAmB,MAAM,GAAG,OACnC,MAAM,MAAM,qBAAqB;qBAqBvB"}
package/dist/media.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Effect, Layer, Option } from "effect";
2
2
  import { HttpServerRequest } from "effect/http";
3
3
  import { UploadForbidden, UploadPolicy, UploadUnauthenticated } from "foldkit-media/server";
4
- //#region src/media.ts
4
+ // src/media.ts
5
5
  /**
6
6
  * `foldkit-guard/media`: `foldkit-media`'s `UploadPolicy` decided by a guard
7
7
  * set. Who is asking comes from the application's resolver, the one its
@@ -35,7 +35,6 @@ const uploadPolicy = (policy, config) => Layer.effect(UploadPolicy, Effect.map(E
35
35
  return yield* new UploadForbidden({});
36
36
  }).pipe(Effect.provideContext(context)) })));
37
37
  const GuardMedia = { uploadPolicy };
38
- //#endregion
39
38
  export { GuardMedia };
40
39
 
41
40
  //# sourceMappingURL=media.mjs.map
@@ -1,4 +1,4 @@
1
- //#region src/origin.ts
1
+ // src/origin.ts
2
2
  const origins = /* @__PURE__ */ new WeakMap();
3
3
  /** The Policy `G.implement` built that `policy` was provided from: itself, for one it built. */
4
4
  const originOf = (policy) => origins.get(policy) ?? policy;
@@ -7,7 +7,6 @@ const providedFrom = (policy, from) => {
7
7
  origins.set(policy, originOf(from));
8
8
  return policy;
9
9
  };
10
- //#endregion
11
10
  export { providedFrom as n, originOf as t };
12
11
 
13
- //# sourceMappingURL=origin-CN6ThFTp.mjs.map
12
+ //# sourceMappingURL=origin-igJoiz74.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"origin-CN6ThFTp.mjs","names":[],"sources":["../src/origin.ts"],"sourcesContent":["/**\n * Which Policy another was provided from, so a seam built from one counts as\n * built from the other: `Policy.provide` keeps the bodies and rules, and\n * changes only the services they run with. `validate` checks that a seam's\n * rules are the declared ones; it does not check which services they were\n * given.\n */\nimport type { Policy } from './index.js'\n\nconst origins = new WeakMap<object, object>()\n\n/** The Policy `G.implement` built that `policy` was provided from: itself, for one it built. */\nexport const originOf = (policy: Policy<any, any>): object => origins.get(policy) ?? policy\n\n/** Records `policy` as provided from `from`. */\nexport const providedFrom = <P extends Policy<any, any>>(policy: P, from: Policy<any, any>): P => {\n origins.set(policy, originOf(from))\n return policy\n}\n"],"mappings":";AASA,MAAM,0BAAU,IAAI,QAAwB;;AAG5C,MAAa,YAAY,WAAqC,QAAQ,IAAI,MAAM,KAAK;;AAGrF,MAAa,gBAA4C,QAAW,SAA8B;CAChG,QAAQ,IAAI,QAAQ,SAAS,IAAI,CAAC;CAClC,OAAO;AACT"}
1
+ {"version":3,"file":"origin-igJoiz74.mjs","names":[],"sources":["../src/origin.ts"],"sourcesContent":["/**\n * Which Policy another was provided from, so a seam built from one counts as\n * built from the other: `Policy.provide` keeps the bodies and rules, and\n * changes only the services they run with. `validate` checks that a seam's\n * rules are the declared ones; it does not check which services they were\n * given.\n */\nimport type { Policy } from './index.js'\n\nconst origins = new WeakMap<object, object>()\n\n/** The Policy `G.implement` built that `policy` was provided from: itself, for one it built. */\nexport const originOf = (policy: Policy<any, any>): object => origins.get(policy) ?? policy\n\n/** Records `policy` as provided from `from`. */\nexport const providedFrom = <P extends Policy<any, any>>(policy: P, from: Policy<any, any>): P => {\n origins.set(policy, originOf(from))\n return policy\n}\n"],"mappings":";AASA,MAAM,0BAAU,IAAI,QAAwB;;AAG5C,MAAa,YAAY,WAAqC,QAAQ,IAAI,MAAM,KAAK;;AAGrF,MAAa,gBAA4C,QAAW,SAA8B;CAChG,QAAQ,IAAI,QAAQ,SAAS,IAAI,CAAC;CAClC,OAAO;AACT"}
@@ -1,7 +1,7 @@
1
- import { r as attached } from "./attach-BZyVvs7H.mjs";
2
- import { t as originOf } from "./origin-CN6ThFTp.mjs";
1
+ import { r as attached } from "./attach-CRCF5XHS.mjs";
2
+ import { t as originOf } from "./origin-igJoiz74.mjs";
3
3
  import { Option } from "effect";
4
- //#region src/placed.ts
4
+ // src/placed.ts
5
5
  /**
6
6
  * What each guard seam built, and for which Policy and Entities, so
7
7
  * `GuardServer.validate` can tell a Source that applies a guard set's rules
@@ -34,7 +34,6 @@ const rowRules = record(/* @__PURE__ */ new WeakMap());
34
34
  const memberRules = record(/* @__PURE__ */ new WeakMap());
35
35
  /** Write rules: `GuardServer.writer`'s. */
36
36
  const writeRules = record(/* @__PURE__ */ new WeakMap());
37
- //#endregion
38
37
  export { rowRules as n, writeRules as r, memberRules as t };
39
38
 
40
- //# sourceMappingURL=placed-CkyMqxFw.mjs.map
39
+ //# sourceMappingURL=placed-BvdNmZJu.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"placed-CkyMqxFw.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-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"}
package/dist/server.d.mts CHANGED
@@ -1,9 +1,8 @@
1
- import { S as Policy, k as MeEntity, l as InteractionKey } from "./attach-BVG6LsFf.mjs";
1
+ import { S as Policy, k as MeEntity, l as InteractionKey } from "./attach-BnP9_Uca.mjs";
2
2
  import { Effect, Option } from "effect";
3
3
  import { AnyEntity, AnyQuery } from "foldkit-entity";
4
4
  import { EntitySource, EntityWriter, MemoryReadable, MutationOutcome, MutationRefused, MutationSource, ReadPlan, RemoteServerError, ServerDefinition } from "foldkit-remote-server";
5
5
  import { MutationDescriptor, RemoteForbidden } from "foldkit-remote";
6
- //#region src/server.d.ts
7
6
  export declare const GuardServer: {
8
7
  /**
9
8
  * `Guards.me`'s Source: the one row, `me`, as the asker is, with `may`
@@ -56,12 +55,23 @@ export declare const GuardServer: {
56
55
  * from, and a create whose input sets a preset field is a mistake of the
57
56
  * server's, refused.
58
57
  *
58
+ * `revision` names a field stored as a number, which the writer moves on by
59
+ * one with each write it lands. An update or a delete then lands only on the
60
+ * revision its rules were decided over (the writer's `expect`), so a change
61
+ * between the check and the write is never written over; it is decided
62
+ * again against the row as it now is, up to three times. A change that does
63
+ * 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
65
+ * revision the row read is not at is a `Conflict`, decided before any rule;
66
+ * an input may expect only the field the writer pins.
67
+ *
59
68
  * ```ts
60
69
  * RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))
61
70
  * ```
62
71
  */
63
72
  writer: <E extends AnyEntity, User, R, RW>(entity: E, policy: Policy<User, R>, writer: EntityWriter<Option.Option<User>, RW>, options?: {
64
73
  readonly presets?: { readonly [K in keyof E['fields']]?: (user: User) => E['fields'][K]['schema']['Type']; };
74
+ readonly revision?: keyof E['fields'] & string;
65
75
  }) => EntityWriter<Option.Option<User>, R | RW>;
66
76
  /**
67
77
  * A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for
@@ -134,5 +144,4 @@ export declare const GuardServer: {
134
144
  readonly server: ServerDefinition<any, any>;
135
145
  }) => void;
136
146
  };
137
- //#endregion
138
147
  //# sourceMappingURL=server.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.mts","names":[],"sources":["../src/server.ts"],"mappings":";;;;;;qBAyCa;;;;;;;;;;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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