foldkit-guard 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/sync.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"sync.mjs","names":[],"sources":["../src/sync.ts"],"sourcesContent":["/**\n * `foldkit-guard/sync`: a guard set's rules on `foldkit-sync`'s edits to a\n * server-owned Entity. A cell edit is a write to a member of a row, through\n * the journal instead of a Remote mutation, so it answers to the same rules.\n *\n * Writes are checked in two halves, by where each can run. What needs only\n * the principal (`always`, the row's and each member's `Update` principal\n * guards) is the journal's `authorize`, under its lock. What reads the row is\n * the exchange's `admit`, before the journal sees the edit, reading the row\n * through the Entity's guarded Source.\n *\n * Reads are one audience: every replica that opens a document receives every\n * edit committed to it. So a document names its `readers`, who alone may open\n * it, and is refused where it is declared when an edit could carry a value to\n * someone the Entity's Read rules would not show it to.\n */\nimport { Effect, Match, Option, Schema } from 'effect'\nimport type { AnyEntity } from 'foldkit-entity'\nimport type { EntitySource } from 'foldkit-remote-server'\nimport type { AuthorizeDecision, Operation } from 'foldkit-sync'\nimport { attached, surfaceOf, type Deny } from './attach.js'\nimport { Condition } from './condition.js'\nimport type { Policy, PrincipalGuard } from './index.js'\n\n/** One cell's change, as `foldkit-sync/entity`'s `Change` carries it. */\nexport interface CellChange {\n readonly id: unknown\n readonly member: string\n readonly value: unknown\n}\n\n/** A document of edits to an Entity's members, and who may open it. */\nexport interface GuardedDocument<User> {\n readonly entity: AnyEntity\n readonly members: ReadonlyArray<string>\n readonly readers: ReadonlyArray<PrincipalGuard<User>>\n}\n\nconst refusal = (deny: Deny): AuthorizeDecision =>\n Match.valueTags(deny, {\n Explain: ({ reason }): AuthorizeDecision => ({ allowed: false, reason }),\n Forbidden: () => false,\n NotFound: () => false,\n Omit: () => false,\n Redact: () => false,\n })\n\n/** The first rule of `rules` that does not hold over `values`, as the decision it makes. */\nconst first = (\n rules: ReadonlyArray<{ readonly condition: Condition; readonly deny: Deny }>,\n holds: (condition: Condition) => boolean,\n): AuthorizeDecision =>\n Option.match(Option.fromUndefinedOr(rules.find(({ condition }) => !holds(condition))), {\n onNone: () => true,\n onSome: ({ deny }) => refusal(deny),\n })\n\nconst isNever = (condition: Condition) => condition === Condition.never\n\n/** The schema of `member` when the document edits it: none for a name it does not own. */\nconst memberOf = <User>(\n entity: AnyEntity,\n document: GuardedDocument<User>,\n member: string,\n): Option.Option<Schema.Codec<unknown, unknown>> => {\n const fields = entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>\n // `document` refused a member that is not a field, so one it names is one.\n return document.members.includes(member)\n ? Option.some(fields[member]!.schema as unknown as Schema.Codec<unknown, unknown>)\n : Option.none()\n}\n\nexport const GuardSync = {\n /**\n * A document of edits to `edits.entity`'s `edits.members`, opened by any of\n * `readers`. Refused here, not discovered later: a member that is not a\n * field of the Entity, a member with a Read rule\n * of its own (its value would reach a reader the rule hides it from), a\n * reader the row's Read rule does not name (it would receive edits to rows\n * it cannot read), a guarded row with no readers, and `always` rules that\n * read the row (no reader could be shown to pass them).\n *\n * ```ts\n * const Edits = GuardSync.document(ProductEdits, { readers: [G.isStaff] })\n * ```\n */\n document: <User>(\n edits: { readonly entity: AnyEntity; readonly members: ReadonlyArray<string> },\n options: { readonly readers: ReadonlyArray<PrincipalGuard<User>> },\n ): GuardedDocument<User> => {\n const { entity, members } = edits\n const fail = (why: string): never => {\n throw new Error(`[foldkit-guard] GuardSync.document of ${entity.name}: ${why}`)\n }\n for (const member of members) {\n if (!Object.hasOwn(entity.fields, member)) fail(`${member} is not a field of it`)\n }\n Option.map(attached(entity), attachment => {\n for (const member of members) {\n if (Option.isSome(surfaceOf(attachment, { _tag: 'Member', member, interaction: 'Read' })))\n fail(`${member} has a Read rule of its own, and every reader receives every edit`)\n }\n const read = surfaceOf(attachment, { _tag: 'Row', interaction: 'Read' })\n if (Option.isSome(read)) {\n if (options.readers.length === 0)\n fail('its rows have a Read rule, so the document names its readers')\n for (const reader of options.readers) {\n const named = read.value.rules.some(\n rule =>\n rule._tag === 'PrincipalGuard' &&\n rule.name === reader.name &&\n rule.set === reader.set,\n )\n if (!named) fail(`${reader.name} is not in its rows' Read rule, so may not read them`)\n }\n }\n if (attachment.always.some(rule => rule._tag !== 'PrincipalGuard'))\n fail('its `always` rules read the row, which no reader can be shown to pass')\n })\n return Object.freeze({ entity, members, readers: options.readers })\n },\n\n /**\n * Whether `principal` may open the document: any of its readers (anyone,\n * when it names none), and every `always` rule of the Entity. For\n * `journalExchange`'s `opens`.\n */\n opens: <User>(\n policy: Policy<User>,\n document: GuardedDocument<User>,\n principal: Option.Option<User>,\n ): Effect.Effect<boolean> => {\n const always = Option.match(attached(document.entity), {\n onNone: () => [],\n onSome: ({ always }) => always.filter(rule => rule._tag === 'PrincipalGuard'),\n }) as ReadonlyArray<PrincipalGuard<User>>\n const decided = (guards: ReadonlyArray<PrincipalGuard<User>>) =>\n Effect.forEach(guards, guard =>\n Effect.map(policy.decide(guard, { principal, interaction: 'Read' }), d => d === true),\n )\n return Effect.map(\n Effect.all([decided(document.readers), decided(always)]),\n // No readers named: its rows have no Read rule, so it is everyone's.\n ([readers, rules]) =>\n (document.readers.length === 0 || readers.some(Boolean)) && rules.every(Boolean),\n )\n },\n\n /**\n * The journal's `authorize` for a Message of cell edits: refuses one whose\n * row's `Update` or a changed member's `Update` the principal guards settle\n * as refused, with an `explain`'s sentence. It runs under the journal's\n * lock, so it reads no row (`admit` does), and its bodies must not suspend.\n *\n * ```ts\n * authorize: { EditedProducts: GuardSync.authorize(Policy, Edits) }\n * ```\n */\n authorize:\n <User>(policy: Policy<User>, document: GuardedDocument<User>) =>\n (request: {\n readonly principal: Option.Option<User>\n readonly message: { readonly changes: ReadonlyArray<CellChange> }\n }): AuthorizeDecision => {\n const { principal, message } = request\n const row = Effect.runSync(policy.writable(document.entity, principal, 'Update'))\n if (isNever(row.condition)) return refusal(row.deny)\n const members = Effect.runSync(\n policy.writeMembers(\n document.entity,\n principal,\n [...new Set(message.changes.map(change => change.member))],\n 'Update',\n ),\n )\n return first(members, condition => !isNever(condition))\n },\n\n /**\n * The exchange's `admit` for `principal`: each row an operation's edits\n * name is read through `source` (the Entity's guarded Source) and must let\n * the principal update it, as it is and as it would be after all of the\n * operation's edits to it, and each changed member must too. A row the\n * principal cannot see is refused, as is an edit to a member outside the\n * document or a value its member cannot encode. `changesOf` reads the edits\n * from an operation; one with none is admitted.\n *\n * The row is read from the table, which takes an edit only once its exchange\n * settles: an edit that changes what a rule reads lets another, admitted\n * before it lands, be judged against the row as it was.\n */\n admit:\n <User, R>(\n policy: Policy<User>,\n document: GuardedDocument<User>,\n options: {\n readonly principal: Option.Option<User>\n readonly source: EntitySource<Option.Option<User>, R>\n readonly changesOf: (operation: Operation) => ReadonlyArray<CellChange>\n },\n ) =>\n (operation: Operation): Effect.Effect<AuthorizeDecision, unknown, R> =>\n Effect.gen(function* () {\n const { principal, source } = options\n const changes = options.changesOf(operation)\n if (changes.length === 0) return true\n const { entity } = document\n // A member is a client's word: only the document's own, by own key.\n const encoded = Option.all(\n changes.map(change =>\n Option.flatMap(memberOf(entity, document, change.member), schema =>\n Option.map(Schema.encodeUnknownOption(schema)(change.value), value => ({\n id: String(change.id),\n member: change.member,\n value,\n })),\n ),\n ),\n )\n if (Option.isNone(encoded)) return false\n const row = yield* policy.writable(entity, principal, 'Update')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n [...new Set(changes.map(change => change.member))],\n 'Update',\n )\n const input = policy.inputOf(principal)\n const fields = [\n ...new Set([\n 'id',\n ...[row, ...members].flatMap(({ condition }) => Condition.members(condition)),\n ]),\n ]\n const holdsOver = (values: Readonly<Record<string, unknown>>) => (condition: Condition) =>\n Condition.holds(condition, values, input, () => false)\n // Every edit to one row is judged together: two may each keep it in reach, and both not.\n const byRow = new Map<string, Record<string, unknown>>()\n for (const { id, member, value } of encoded.value) {\n byRow.set(id, { ...byRow.get(id), [member]: value })\n }\n for (const [id, edits] of byRow) {\n const records = yield* source.read({ ids: [id], fields, principal })\n const current = Option.fromUndefinedOr(records.find(record => record.id === id)?.values)\n if (Option.isNone(current)) return refusal(row.deny)\n const changed = new Set(Object.keys(edits))\n const before = first(\n [row, ...members.filter(({ member }) => changed.has(member))],\n holdsOver(current.value),\n )\n if (before !== true) return before\n const moved = first([row], holdsOver({ ...current.value, ...edits }))\n if (moved !== true) return moved\n }\n return true\n }),\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,WAAW,SACf,MAAM,UAAU,MAAM;CACpB,UAAU,EAAE,cAAiC;EAAE,SAAS;EAAO;CAAO;CACtE,iBAAiB;CACjB,gBAAgB;CAChB,YAAY;CACZ,cAAc;AAChB,CAAC;;AAGH,MAAM,SACJ,OACA,UAEA,OAAO,MAAM,OAAO,gBAAgB,MAAM,MAAM,EAAE,gBAAgB,CAAC,MAAM,SAAS,CAAC,CAAC,GAAG;CACrF,cAAc;CACd,SAAS,EAAE,WAAW,QAAQ,IAAI;AACpC,CAAC;AAEH,MAAM,WAAW,cAAyB,cAAc,UAAU;;AAGlE,MAAM,YACJ,QACA,UACA,WACkD;CAClD,MAAM,SAAS,OAAO;CAEtB,OAAO,SAAS,QAAQ,SAAS,MAAM,IACnC,OAAO,KAAK,OAAO,OAAO,CAAE,MAAmD,IAC/E,OAAO,KAAK;AAClB;AAEA,MAAa,YAAY;;;;;;;;;;;;;;CAcvB,WACE,OACA,YAC0B;EAC1B,MAAM,EAAE,QAAQ,YAAY;EAC5B,MAAM,QAAQ,QAAuB;GACnC,MAAM,IAAI,MAAM,yCAAyC,OAAO,KAAK,IAAI,KAAK;EAChF;EACA,KAAK,MAAM,UAAU,SACnB,IAAI,CAAC,OAAO,OAAO,OAAO,QAAQ,MAAM,GAAG,KAAK,GAAG,OAAO,sBAAsB;EAElF,OAAO,IAAI,SAAS,MAAM,IAAG,eAAc;GACzC,KAAK,MAAM,UAAU,SACnB,IAAI,OAAO,OAAO,UAAU,YAA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Aa,KAAK;EAEvD,MAAM,wBAAQ,IAAI,IAAqC;EACvD,KAAK,MAAM,EAAE,IAAI,QAAQ,WAAW,QAAQ,OAC1C,MAAM,IAAI,IAAI;GAAE,GAAG,MAAM,IAAI,EAAE;IAAI,SAAS;EAAM,CAAC;EAErD,KAAK,MAAM,CAAC,IAAI,UAAU,OAAO;GAC/B,MAAM,UAAU,OAAO,OAAO,KAAK;IAAE,KAAK,CAAC,EAAE;IAAG;IAAQ;GAAU,CAAC;GACnE,MAAM,UAAU,OAAO,gBAAgB,QAAQ,MAAK,WAAU,OAAO,OAAO,EAAE,CAAC,EAAE,MAAM;GACvF,IAAI,OAAO,OAAO,OAAO,GAAG,OAAO,QAAQ,IAAI,IAAI;GACnD,MAAM,UAAU,IAAI,IAAI,OAAO,KAAK,KAAK,CAAC;GAC1C,MAAM,SAAS,MACb,CAAC,KAAK,GAAG,QAAQ,QAAQ,EAAE,aAAa,QAAQ,IAAI,MAAM,CAAC,CAAC,GAC5D,UAAU,QAAQ,KAAK,CACzB;GACA,IAAI,WAAW,MAAM,OAAO;GAC5B,MAAM,QAAQ,MAAM,CAAC,GAAG,GAAG,UAAU;IAAE,GAAG,QAAQ;IAAO,GAAG;GAAM,CAAC,CAAC;GACpE,IAAI,UAAU,MAAM,OAAO;EAC7B;EACA,OAAO;CACT,CAAC;AACP"}
1
+ {"version":3,"file":"sync.mjs","names":[],"sources":["../src/sync.ts"],"sourcesContent":["/**\n * `foldkit-guard/sync`: a guard set's rules on `foldkit-sync`'s edits to a\n * server-owned Entity. A cell edit is a write to a member of a row, through\n * the journal instead of a Remote mutation, so it answers to the same rules.\n *\n * Writes are checked in two halves, by where each can run. What needs only\n * the principal (`always`, the row's and each member's `Update` principal\n * guards) is the journal's `authorize`, under its lock. What reads the row is\n * the exchange's `admit`, before the journal sees the edit, reading the row\n * through the Entity's guarded Source.\n *\n * Reads are one audience: every replica that opens a document receives every\n * edit committed to it. So a document names its `readers`, who alone may open\n * it, and is refused where it is declared when an edit could carry a value to\n * someone the Entity's Read rules would not show it to.\n */\nimport { Effect, Match, Option, Schema } from 'effect'\nimport type { AnyEntity } from 'foldkit-entity'\nimport type { EntitySource } from 'foldkit-remote-server'\nimport type { AuthorizeDecision, Operation } from 'foldkit-sync'\nimport { attached, isAnyone, restricts, surfaceOf, type Deny } from './attach.js'\nimport { Condition } from './condition.js'\nimport type { Policy, PrincipalGuard } from './index.js'\n\n/** One cell's change, as `foldkit-sync/entity`'s `Change` carries it. */\nexport interface CellChange {\n readonly id: unknown\n readonly member: string\n readonly value: unknown\n}\n\n/** A document of edits to an Entity's members, and who may open it. */\nexport interface GuardedDocument<User> {\n readonly entity: AnyEntity\n readonly members: ReadonlyArray<string>\n readonly readers: ReadonlyArray<PrincipalGuard<User>>\n}\n\nconst refusal = (deny: Deny): AuthorizeDecision =>\n Match.valueTags(deny, {\n Explain: ({ reason }): AuthorizeDecision => ({ allowed: false, reason }),\n Forbidden: () => false,\n NotFound: () => false,\n Omit: () => false,\n Redact: () => false,\n })\n\n/** The first rule of `rules` that does not hold over `values`, as the decision it makes. */\nconst first = (\n rules: ReadonlyArray<{ readonly condition: Condition; readonly deny: Deny }>,\n holds: (condition: Condition) => boolean,\n): AuthorizeDecision =>\n Option.match(Option.fromUndefinedOr(rules.find(({ condition }) => !holds(condition))), {\n onNone: () => true,\n onSome: ({ deny }) => refusal(deny),\n })\n\nconst isNever = (condition: Condition) => condition === Condition.never\n\n/** The schema of `member` when the document edits it: none for a name it does not own. */\nconst memberOf = <User>(\n entity: AnyEntity,\n document: GuardedDocument<User>,\n member: string,\n): Option.Option<Schema.Codec<unknown, unknown>> => {\n const fields = entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>\n // `document` refused a member that is not a field, so one it names is one.\n return document.members.includes(member)\n ? Option.some(fields[member]!.schema as unknown as Schema.Codec<unknown, unknown>)\n : Option.none()\n}\n\nexport const GuardSync = {\n /**\n * A document of edits to `edits.entity`'s `edits.members`, opened by any of\n * `readers`. Refused here, not discovered later: a member that is not a\n * field of the Entity, a member with a Read rule\n * of its own (its value would reach a reader the rule hides it from), a\n * reader the row's Read rule does not name (it would receive edits to rows\n * it cannot read), a guarded row with no readers, and `always` rules that\n * read the row (no reader could be shown to pass them).\n *\n * ```ts\n * const Edits = GuardSync.document(ProductEdits, { readers: [G.isStaff] })\n * ```\n */\n document: <User>(\n edits: { readonly entity: AnyEntity; readonly members: ReadonlyArray<string> },\n options: { readonly readers: ReadonlyArray<PrincipalGuard<User>> },\n ): GuardedDocument<User> => {\n const { entity, members } = edits\n const fail = (why: string): never => {\n throw new Error(`[foldkit-guard] GuardSync.document of ${entity.name}: ${why}`)\n }\n for (const member of members) {\n if (!Object.hasOwn(entity.fields, member)) fail(`${member} is not a field of it`)\n }\n Option.map(attached(entity), attachment => {\n for (const member of members) {\n if (restricts(surfaceOf(attachment, { _tag: 'Member', member, interaction: 'Read' })))\n fail(`${member} has a Read rule of its own, and every reader receives every edit`)\n }\n const read = surfaceOf(attachment, { _tag: 'Row', interaction: 'Read' })\n if (Option.isSome(read) && restricts(read)) {\n if (options.readers.length === 0)\n fail('its rows have a Read rule, so the document names its readers')\n for (const reader of options.readers) {\n const named = read.value.rules.some(\n rule =>\n rule._tag === 'PrincipalGuard' &&\n rule.name === reader.name &&\n rule.set === reader.set,\n )\n if (!named) fail(`${reader.name} is not in its rows' Read rule, so may not read them`)\n }\n }\n if (attachment.always.some(rule => rule._tag !== 'PrincipalGuard' && !isAnyone(rule)))\n fail('its `always` rules read the row, which no reader can be shown to pass')\n })\n return Object.freeze({ entity, members, readers: options.readers })\n },\n\n /**\n * Whether `principal` may open the document: any of its readers (anyone,\n * when it names none), and every `always` rule of the Entity. For\n * `journalExchange`'s `opens`.\n */\n opens: <User>(\n policy: Policy<User>,\n document: GuardedDocument<User>,\n principal: Option.Option<User>,\n ): Effect.Effect<boolean> => {\n const always = Option.match(attached(document.entity), {\n onNone: () => [],\n onSome: ({ always }) => always.filter(rule => rule._tag === 'PrincipalGuard'),\n }) as ReadonlyArray<PrincipalGuard<User>>\n const decided = (guards: ReadonlyArray<PrincipalGuard<User>>) =>\n Effect.forEach(guards, guard =>\n Effect.map(policy.decide(guard, { principal, interaction: 'Read' }), d => d === true),\n )\n return Effect.map(\n Effect.all([decided(document.readers), decided(always)]),\n // No readers named: its rows have no Read rule, so it is everyone's.\n ([readers, rules]) =>\n (document.readers.length === 0 || readers.some(Boolean)) && rules.every(Boolean),\n )\n },\n\n /**\n * The journal's `authorize` for a Message of cell edits: refuses one whose\n * row's `Update` or a changed member's `Update` the principal guards settle\n * as refused, with an `explain`'s sentence. It runs under the journal's\n * lock, so it reads no row (`admit` does), and its bodies must not suspend.\n *\n * ```ts\n * authorize: { EditedProducts: GuardSync.authorize(Policy, Edits) }\n * ```\n */\n authorize:\n <User>(policy: Policy<User>, document: GuardedDocument<User>) =>\n (request: {\n readonly principal: Option.Option<User>\n readonly message: { readonly changes: ReadonlyArray<CellChange> }\n }): AuthorizeDecision => {\n const { principal, message } = request\n const row = Effect.runSync(policy.writable(document.entity, principal, 'Update'))\n if (isNever(row.condition)) return refusal(row.deny)\n const members = Effect.runSync(\n policy.writeMembers(\n document.entity,\n principal,\n [...new Set(message.changes.map(change => change.member))],\n 'Update',\n ),\n )\n return first(members, condition => !isNever(condition))\n },\n\n /**\n * The exchange's `admit` for `principal`: each row an operation's edits\n * name is read through `source` (the Entity's guarded Source) and must let\n * the principal update it, as it is and as it would be after all of the\n * operation's edits to it, and each changed member must too. A row the\n * principal cannot see is refused, as is an edit to a member outside the\n * document or a value its member cannot encode. `changesOf` reads the edits\n * from an operation; one with none is admitted.\n *\n * The row is read from the table, which takes an edit only once its exchange\n * settles: an edit that changes what a rule reads lets another, admitted\n * before it lands, be judged against the row as it was.\n */\n admit:\n <User, R>(\n policy: Policy<User>,\n document: GuardedDocument<User>,\n options: {\n readonly principal: Option.Option<User>\n readonly source: EntitySource<Option.Option<User>, R>\n readonly changesOf: (operation: Operation) => ReadonlyArray<CellChange>\n },\n ) =>\n (operation: Operation): Effect.Effect<AuthorizeDecision, unknown, R> =>\n Effect.gen(function* () {\n const { principal, source } = options\n const changes = options.changesOf(operation)\n if (changes.length === 0) return true\n const { entity } = document\n // A member is a client's word: only the document's own, by own key.\n const encoded = Option.all(\n changes.map(change =>\n Option.flatMap(memberOf(entity, document, change.member), schema =>\n Option.map(Schema.encodeUnknownOption(schema)(change.value), value => ({\n id: String(change.id),\n member: change.member,\n value,\n })),\n ),\n ),\n )\n if (Option.isNone(encoded)) return false\n const row = yield* policy.writable(entity, principal, 'Update')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n [...new Set(changes.map(change => change.member))],\n 'Update',\n )\n const input = policy.inputOf(principal)\n const fields = [\n ...new Set([\n 'id',\n ...[row, ...members].flatMap(({ condition }) => Condition.members(condition)),\n ]),\n ]\n const holdsOver = (values: Readonly<Record<string, unknown>>) => (condition: Condition) =>\n Condition.holds(condition, values, input, () => false)\n // Every edit to one row is judged together: two may each keep it in reach, and both not.\n const byRow = new Map<string, Record<string, unknown>>()\n for (const { id, member, value } of encoded.value) {\n byRow.set(id, { ...byRow.get(id), [member]: value })\n }\n for (const [id, edits] of byRow) {\n const records = yield* source.read({ ids: [id], fields, principal })\n const current = Option.fromUndefinedOr(records.find(record => record.id === id)?.values)\n if (Option.isNone(current)) return refusal(row.deny)\n const changed = new Set(Object.keys(edits))\n const before = first(\n [row, ...members.filter(({ member }) => changed.has(member))],\n holdsOver(current.value),\n )\n if (before !== true) return before\n const moved = first([row], holdsOver({ ...current.value, ...edits }))\n if (moved !== true) return moved\n }\n return true\n }),\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,WAAW,SACf,MAAM,UAAU,MAAM;CACpB,UAAU,EAAE,cAAiC;EAAE,SAAS;EAAO;CAAO;CACtE,iBAAiB;CACjB,gBAAgB;CAChB,YAAY;CACZ,cAAc;AAChB,CAAC;;AAGH,MAAM,SACJ,OACA,UAEA,OAAO,MAAM,OAAO,gB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AAI,OAAO,KAAK,KAAK,CAAC;GAC1C,MAAM,SAAS,MACb,CAAC,KAAK,GAAG,QAAQ,QAAQ,EAAE,aAAa,QAAQ,IAAI,MAAM,CAAC,CAAC,GAC5D,UAAU,QAAQ,KAAK,CACzB;GACA,IAAI,WAAW,MAAM,OAAO;GAC5B,MAAM,QAAQ,MAAM,CAAC,GAAG,GAAG,UAAU;IAAE,GAAG,QAAQ;IAAO,GAAG;GAAM,CAAC,CAAC;GACpE,IAAI,UAAU,MAAM,OAAO;EAC7B;EACA,OAAO;CACT,CAAC;AACP"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-guard",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Who may do what, declared once on a Foldkit Plus domain: principal guards implemented on the server, row guards as query expressions.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -56,16 +56,16 @@
56
56
  "LICENSE"
57
57
  ],
58
58
  "dependencies": {
59
- "foldkit-entity": "0.10.0",
60
- "foldkit-metadata": "0.1.0"
59
+ "foldkit-metadata": "0.1.0",
60
+ "foldkit-entity": "0.10.0"
61
61
  },
62
62
  "peerDependencies": {
63
63
  "drizzle-orm": "1.0.0-rc.4",
64
64
  "effect": "^4.0.0",
65
- "foldkit-remote": "^0.17.0",
66
- "foldkit-remote-server": "^0.13.4",
67
- "foldkit-remote-drizzle": "^0.12.1",
68
- "foldkit-sync": "^0.11.1"
65
+ "foldkit-remote-drizzle": "^0.12.2",
66
+ "foldkit-remote-server": "^0.14.0",
67
+ "foldkit-remote": "^0.18.0",
68
+ "foldkit-sync": "^0.12.0"
69
69
  },
70
70
  "peerDependenciesMeta": {
71
71
  "drizzle-orm": {
@@ -90,11 +90,11 @@
90
90
  "foldkit": "0.168.0",
91
91
  "tsdown": "^0.23.1",
92
92
  "typescript": "7.0.2",
93
- "foldkit-remote": "0.17.0",
94
- "foldkit-remote-drizzle": "0.12.1",
95
- "foldkit-remote-server": "0.13.4",
93
+ "foldkit-remote": "0.18.0",
96
94
  "foldkit-agent": "0.8.1",
97
- "foldkit-sync": "0.11.1",
95
+ "foldkit-remote-server": "0.14.0",
96
+ "foldkit-remote-drizzle": "0.12.2",
97
+ "foldkit-sync": "0.12.0",
98
98
  "foldkit-surface": "0.10.0"
99
99
  },
100
100
  "scripts": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"attach-BdHNdPNM.d.mts","names":["MemberKeys","_$__attach_js0.Attach","_$__attach_js0.AnyRule","_$__attach_js0.Inherit","_$__attach_js0.All","_$__attach_js0.Redact","_$__attach_js0.Explain","_$__attach_js0.On"],"sources":["../src/condition.ts","../src/may.ts","../src/index.ts","../src/attach.ts"],"mappings":";;;KAWY;WACG;;WACA;;WACA;WAAsB,OAAO,cAAc;;;;WAE3C;WAA0B;;WAC1B;WAAsB,YAAY,cAAc;;WAChD;WAAqB,YAAY,cAAc;;;cAMxD,MAAG,YAAgB,cAAc,eAAa;;cAY9C,KAAE,YAAgB,cAAc,eAAa;cAWtC;;aAnCQ;;;aACA;;;;;;;;;EA8CN,QAAA,WAAA,WAAS,QACZ,SAAS,0BAAwB,OAClC,SAAS,0BAAwB,UAC9B;;;;;;;EAoBW,YAAA,WAAA,WAAS,OAAS,wBAAsB;;EAiB1C,UAAA,WAAA,cAAY;;;UAelB;WACN;WACA,WAAW;WACX,MAAM;;;UAwDA;WACN,WAAW;WACX,MAAM;;;;;;;;;;cC/JJ,WAAS,OAAA;;;;;;;;;KASV,mBAAmB,UAAU;KAEpCA,aAAW,UAAU,oBAAoB,oBAAoB;cAerD;;;;;;EAMX,SAAM,UAAA,WAAA,QAAA,mBAAA;;;;;;;;;;;;;;;;;;EAON,MAAG,KAAQ,WAAS,mCAAqC;;;;;;EAQzD,SAAM,KACC,WAAS,mCACqB,mBAClC,OAAO;;EAGV,SAAS,UAAU,WAAS,KAAO,WAAS,SAAW,GAAC,QAAUA,aAAW;;EAI7E,UAAU,UAAU,WAAS,KACtB,WAAS,SACL,GAAC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AM,OAAO,OAAO;;KAG1B,WAAW,SAAS,eAAe;;UAGvB;WACN;WACA;WACA,KAAK;WACL,SAAS,SAAS,eAAe;WACjC,WAAW,SAAS,eAAe;WACnC,QAAQ,cAAc;;cAoPpB,WAAQ,QAAY,cAAY,OAAO,OAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"attach-COgJIox7.mjs","names":[],"sources":["../src/attach.ts"],"sourcesContent":["/**\n * Attaching a guard set's guards to an Entity, per surface and interaction,\n * as metadata only `foldkit-guard` reads. See `guard-DESIGN.md` §3.2.\n */\nimport { Match, Option, type Schema } from 'effect'\nimport { Entity, Query, ReadFilter, type AnyEntity } from 'foldkit-entity'\nimport { Metadata } from 'foldkit-metadata'\nimport type { PrincipalGuard, RowGuard } from './index.js'\n\ndeclare const InteractionBrand: unique symbol\n\n/** An interaction the application names, used as a computed key: `[Archive.key]`. */\nexport type InteractionKey<Name extends string = string> = Name & {\n readonly [InteractionBrand]: Name\n}\n\nexport interface Interaction<Name extends string> {\n readonly name: Name\n readonly key: InteractionKey<Name>\n}\n\n/** The interactions every row has, and the ones a relation member has. */\nconst builtIn = ['Read', 'Create', 'Update', 'Delete', 'Write', 'Link', 'Unlink'] as const\n\nexport const Interaction = {\n /** An interaction beyond Read, Create, Update and Delete, such as `Archive`. */\n make: <const Name extends string>(name: Name): Interaction<Name> => {\n if ((builtIn as ReadonlyArray<string>).includes(name)) {\n throw new Error(`[foldkit-guard] Interaction.make: \"${name}\" is an interaction already`)\n }\n return Object.freeze({ name, key: name as InteractionKey<Name> })\n },\n}\n\n/** Every guard of `Rules` must allow, as one guard: `Guards.all(signedIn, isOwner)`. */\nexport interface All<Rules> {\n readonly _tag: 'All'\n readonly rules: ReadonlyArray<Rules>\n}\n\n/** This row's Read is the Read of the row its `one` relation points at. */\nexport interface Inherit<Relation extends string> {\n readonly _tag: 'Inherit'\n readonly relation: Relation\n}\n\n/** What a member hidden by its Read guards reads as instead of its value. */\nexport interface Redact<A> {\n readonly _tag: 'Redact'\n readonly value: A\n}\n\n/** A refused write's sentence, for the application's own users. */\nexport interface Explain {\n readonly _tag: 'Explain'\n readonly reason: string\n}\n\n/**\n * What a refusal looks like. The defaults need no constructor: a row Read\n * answers `NotFound`, a member or relation Read `Omit`, a write `Forbidden`.\n */\nexport type Deny =\n | { readonly _tag: 'NotFound' }\n | { readonly _tag: 'Omit' }\n | Redact<unknown>\n | { readonly _tag: 'Forbidden' }\n | Explain\n\n/** A surface's guards with a refusal other than its default. */\nexport interface On<Rules, D extends Deny> {\n readonly _tag: 'On'\n readonly rules: ReadonlyArray<Rules>\n readonly deny: D\n}\n\n/** Anything a surface's list may hold, of any guard set. */\nexport type AnyRule =\n PrincipalGuard<any, string> | RowGuard<any, AnyEntity, string> | All<any> | Inherit<string>\n\n/**\n * What a surface of the Entity named `Name` accepts from the guard set `Set`:\n * its principal guards, its row guards over that Entity, and conjunctions of\n * both. A row guard over another Entity, or a guard of another set, is refused.\n */\nexport type RuleFor<User, Set extends string, Name extends string> =\n | PrincipalGuard<User, Set>\n | RowGuard<User, Entity<Name, any, any, any>, Set>\n | All<RuleFor<User, Set, Name>>\n\ntype Slot<Rule, D extends Deny> = ReadonlyArray<Rule> | On<Rule, D>\n\ntype WriteSlot<Rule> = Slot<Rule, Explain>\n\ntype OneRelations<E extends AnyEntity> = {\n [K in keyof E['relations']]: E['relations'][K] extends { readonly cardinality: 'one' } ? K : never\n}[keyof E['relations']] &\n string\n\ntype MemberKeys<E extends AnyEntity> = (keyof E['fields'] | keyof E['derived']) & string\n\ntype TypeOf<E extends AnyEntity, K extends keyof E['members']> = E['members'][K]['schema']['Type']\n\n/** What `Guards.attach` takes for the Entity `E`, every key checked against it. */\nexport type Attach<User, Set extends string, E extends AnyEntity> = {\n readonly row?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']> | Inherit<OneRelations<E>>>\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Delete?: WriteSlot<RuleFor<User, Set, E['name']>>\n /** The same guards on Create, Update and Delete. */\n readonly Write?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /**\n * The row's interactions the application named, by key:\n * `{ [Archive.key]: [G.isAdmin] }`. Apart from `row`, whose `Read` may\n * inherit: a literal with a computed key is typed as an index signature,\n * which `Read`'s rules would have to fit too.\n */\n readonly interactions?: {\n readonly [K: InteractionKey]: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /** Narrow a field or derived member: a member is reachable only if its row is. */\n readonly members?: {\n readonly [K in MemberKeys<E>]?: {\n readonly Read?: Slot<RuleFor<User, Set, E['name']>, Redact<TypeOf<E, K>>>\n /** When absent, `Update`'s guards govern setting the member on creation too. */\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n readonly relations?: {\n readonly [K in keyof E['relations']]?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n readonly Link?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Unlink?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n /** ANDed with every surface's guards, and never out-voted by them. */\n readonly always?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n}\n\n/** One surface's guards as attached: a disjunction, and a refusal if one was chosen. */\nexport interface Surface {\n readonly rules: ReadonlyArray<AnyRule>\n readonly deny: Option.Option<Deny>\n}\n\ntype Surfaces = Readonly<Record<string, Surface>>\n\n/** An Entity's guards, every attachment merged. */\nexport interface Attachment {\n readonly set: string\n readonly unguarded: 'allow' | 'deny'\n readonly row: Surfaces\n readonly members: Readonly<Record<string, Surfaces>>\n readonly relations: Readonly<Record<string, Surfaces>>\n readonly always: ReadonlyArray<AnyRule>\n}\n\n/** Which surface a rule is asked about. */\ntype Target =\n | { readonly _tag: 'Row'; readonly interaction: string }\n | { readonly _tag: 'Member'; readonly member: string; readonly interaction: string }\n | { readonly _tag: 'Relation'; readonly relation: string; readonly interaction: string }\n\nconst record = <A>(): Record<string, A> => Object.create(null)\n\nconst appendSurface = (into: Record<string, Surface>, interaction: string, added: Surface) => {\n const before = into[interaction]\n into[interaction] =\n before === undefined\n ? added\n : {\n rules: [...before.rules, ...added.rules],\n deny: Option.orElse(added.deny, () => before.deny),\n }\n}\n\nconst appendSurfaces = (into: Record<string, Surface>, added: Surfaces) => {\n for (const [interaction, surface] of Object.entries(added)) {\n appendSurface(into, interaction, surface)\n }\n}\n\nconst freezeSurfaces = (surfaces: Record<string, Surfaces>) => {\n for (const key of Object.keys(surfaces)) Object.freeze(surfaces[key])\n return Object.freeze(surfaces)\n}\n\n/** Later attachments append to each surface's disjunction and replace its refusal. */\nconst mergeAttachments = (attachments: ReadonlyArray<Attachment>): Attachment => {\n const row = record<Surface>()\n const members = record<Record<string, Surface>>()\n const relations = record<Record<string, Surface>>()\n const always: Array<AnyRule> = []\n for (const attachment of attachments) {\n appendSurfaces(row, attachment.row)\n for (const [key, surfaces] of Object.entries(attachment.members)) {\n appendSurfaces((members[key] ??= record()), surfaces)\n }\n for (const [key, surfaces] of Object.entries(attachment.relations)) {\n appendSurfaces((relations[key] ??= record()), surfaces)\n }\n always.push(...attachment.always)\n }\n const { set, unguarded } = attachments[0]!\n return Object.freeze({\n set,\n unguarded,\n row: Object.freeze(row),\n members: freezeSurfaces(members),\n relations: freezeSurfaces(relations),\n always: Object.freeze(always),\n })\n}\n\nconst showRule = (rule: AnyRule): string =>\n Match.valueTags(rule, {\n PrincipalGuard: ({ name }) => name,\n RowGuard: ({ name }) => name,\n All: ({ rules }) => `all(${rules.map(showRule).join(', ')})`,\n Inherit: ({ relation }) => `inherit(${relation})`,\n })\n\nconst showDeny = (deny: Deny): string =>\n Match.valueTags(deny, {\n NotFound: () => 'not_found',\n Omit: () => 'omit',\n Redact: ({ value }) => `redact(${JSON.stringify(value)})`,\n Forbidden: () => 'forbidden',\n Explain: ({ reason }) => `explain(${JSON.stringify(reason)})`,\n })\n\nconst notFound: Deny = Object.freeze({ _tag: 'NotFound' })\nconst omit: Deny = Object.freeze({ _tag: 'Omit' })\nconst forbidden: Deny = Object.freeze({ _tag: 'Forbidden' })\n\n/** The refusal a surface takes when none was chosen. */\nexport const defaultDeny = (target: Target): Deny =>\n target.interaction === 'Read'\n ? Match.valueTags(target, { Row: () => notFound, Member: () => omit, Relation: () => omit })\n : forbidden\n\n/** The guards a surface carries; `none` where it falls to the set's `unguarded`. */\nexport const surfaceOf = (attachment: Attachment, target: Target): Option.Option<Surface> =>\n Match.valueTags(target, {\n Row: ({ interaction }) => Option.fromUndefinedOr(attachment.row[interaction]),\n Member: ({ member, interaction }) => {\n const surfaces = attachment.members[member]\n if (surfaces === undefined) return Option.none()\n const own = surfaces[interaction]\n // A member a caller may not change is rarely one it may set freely on creation.\n return Option.fromUndefinedOr(\n own === undefined && interaction === 'Create' ? surfaces['Update'] : own,\n )\n },\n Relation: ({ relation, interaction }) =>\n Option.fromUndefinedOr(attachment.relations[relation]?.[interaction]),\n })\n\n/** Whether who may read the rows depends on who is asking: a row Read rule, or `always`. */\nexport const readRowsRuled = (attachment: Attachment): boolean =>\n attachment.row['Read'] !== undefined || attachment.always.length > 0\n\n/** Whether `member`, a field or a relation, has a Read rule of its own. */\nexport const readRuled = (attachment: Attachment, member: string): boolean =>\n Option.isSome(surfaceOf(attachment, { _tag: 'Member', member, interaction: 'Read' })) ||\n Option.isSome(surfaceOf(attachment, { _tag: 'Relation', relation: member, interaction: 'Read' }))\n\nconst key = Metadata.key<Attachment>('foldkit-guard/attachment', {\n merge: attachments => [mergeAttachments(attachments)],\n summarize: attachment =>\n linesOf(attachment)\n .map(([where, rule]) => `${where}: ${rule}`)\n .join('; '),\n})\n\n/** The rows of an attachment's matrix: each surface it decides, and how. */\nconst linesOf = (attachment: Attachment): ReadonlyArray<readonly [string, string]> => {\n const open = attachment.unguarded === 'allow' ? 'open' : 'closed'\n const show = (target: Target) =>\n Option.match(surfaceOf(attachment, target), {\n onNone: () => open,\n onSome: ({ rules, deny }) =>\n // An empty disjunction allows no one.\n `${rules.length === 0 ? 'nobody' : rules.map(showRule).join(' | ')} → ${showDeny(Option.getOrElse(deny, () => defaultDeny(target)))}`,\n })\n const interactions = [\n 'Read',\n 'Create',\n 'Update',\n 'Delete',\n ...Object.keys(attachment.row).filter(interaction => !builtIn.includes(interaction as never)),\n ]\n return [\n ...(attachment.always.length > 0\n ? [['always', attachment.always.map(showRule).join(' & ')] as const]\n : []),\n ...interactions.map(interaction => [interaction, show({ _tag: 'Row', interaction })] as const),\n ...Object.keys(attachment.members).flatMap(member =>\n ['Read', 'Create', 'Update'].flatMap(interaction => {\n const target: Target = { _tag: 'Member', member, interaction }\n return Option.isSome(surfaceOf(attachment, target))\n ? [[`${member}.${interaction}`, show(target)] as const]\n : []\n }),\n ),\n ...Object.entries(attachment.relations).flatMap(([relation, surfaces]) =>\n Object.keys(surfaces).map(\n interaction =>\n [\n `${relation}.${interaction}`,\n show({ _tag: 'Relation', relation, interaction }),\n ] as const,\n ),\n ),\n ]\n}\n\nconst isOn = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): slot is On<AnyRule, Deny> =>\n !Array.isArray(slot)\n\nconst surfaceFrom = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): Surface =>\n isOn(slot)\n ? { rules: slot.rules, deny: Option.some(slot.deny) }\n : { rules: Object.freeze([...slot]), deny: Option.none() }\n\n/** Throws for a row guard over another Entity that shares the target's name. */\nconst checkRules = (\n set: string,\n entity: AnyEntity,\n where: string,\n rules: ReadonlyArray<AnyRule>,\n): void => {\n for (const rule of rules) {\n Match.valueTags(rule, {\n PrincipalGuard: () => {},\n RowGuard: guard => {\n if (!Entity.same(guard.entity, entity)) {\n throw new Error(\n `[foldkit-guard] ${set}.attach: ${where} names ${guard.name}, a guard over another Entity named ${entity.name}`,\n )\n }\n },\n All: ({ rules }) => checkRules(set, entity, where, rules),\n Inherit: () => {},\n })\n }\n}\n\nconst surfacesFrom = (\n set: string,\n entity: AnyEntity,\n where: string,\n slots: Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>>,\n): Surfaces => {\n const surfaces = record<Surface>()\n // `Write` goes first, whatever order the keys were written in: beside it, a\n // slot of its own adds rules to it and its refusal replaces Write's.\n const ordered = Object.entries(slots).sort(\n ([left], [right]) => Number(right === 'Write') - Number(left === 'Write'),\n )\n for (const [interaction, slot] of ordered) {\n if (slot === undefined) continue\n const added = surfaceFrom(slot)\n checkRules(set, entity, `${where}${interaction}`, added.rules)\n // Write is shorthand, so it is stored as the three it stands for.\n for (const each of interaction === 'Write' ? ['Create', 'Update', 'Delete'] : [interaction]) {\n appendSurface(surfaces, each, added)\n }\n }\n return Object.freeze(surfaces)\n}\n\nconst nested = (\n set: string,\n entity: AnyEntity,\n given: Readonly<\n Record<\n string,\n Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>> | undefined\n >\n >,\n): Readonly<Record<string, Surfaces>> => {\n const surfaces = record<Surfaces>()\n for (const [member, slots] of Object.entries(given)) {\n if (slots !== undefined) surfaces[member] = surfacesFrom(set, entity, `${member}.`, slots)\n }\n return Object.freeze(surfaces)\n}\n\n/** A row guard's own fields, and the relation an inherited Read follows. */\nconst membersRead = (rule: AnyRule): ReadonlyArray<string> =>\n Match.valueTags(rule, {\n PrincipalGuard: () => [],\n RowGuard: ({ query }) => Query.dependencies(query).predicate.map(field => field.key),\n All: ({ rules }) => rules.flatMap(membersRead),\n Inherit: ({ relation }) => [relation],\n })\n\nexport const attached = (entity: AnyEntity): Option.Option<Attachment> =>\n Option.fromUndefinedOr(key.get(entity.metadata)[0])\n\nexport const Attaching = {\n /**\n * Attaches guards to an Entity, per surface and interaction. A surface's list\n * is a disjunction; `always` is ANDed after it. Attaching twice appends to a\n * surface's list and replaces its refusal.\n */\n attach:\n <Name extends string, User, E extends AnyEntity>(\n G: {\n readonly name: Name\n readonly schema: Schema.Codec<User, unknown>\n readonly unguarded: 'allow' | 'deny'\n },\n config: Attach<NoInfer<User>, NoInfer<Name>, E>,\n ) =>\n (entity: E): E => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== G.name) {\n throw new Error(\n `[foldkit-guard] ${G.name}.attach: ${entity.name} carries the guards of ${set} already`,\n )\n }\n })\n const always = config.always ?? []\n checkRules(G.name, entity, 'always', always)\n const attachment: Attachment = Object.freeze({\n set: G.name,\n unguarded: G.unguarded,\n // A named interaction is the row's, as the matrix and the decisions read it.\n row: surfacesFrom(G.name, entity, '', { ...config.row, ...config.interactions }),\n members: nested(G.name, entity, config.members ?? {}),\n relations: nested(G.name, entity, config.relations ?? {}),\n always: Object.freeze([...always]),\n })\n // What the row's Read rules read, so a client placing rows knows it cannot judge a change to them.\n const filtered = [\n ...new Set(\n [...(attachment.row['Read']?.rules ?? []), ...attachment.always].flatMap(membersRead),\n ),\n ]\n return entity.pipe(\n Entity.annotate(Metadata.combine([key.of(attachment), ReadFilter.of(filtered)])),\n )\n },\n\n /** The guards attached to `entity`, every attachment merged. */\n attached,\n\n /** Every rule must allow, as one rule. Principal and row guards may mix. */\n all: <const Rules extends ReadonlyArray<Exclude<AnyRule, Inherit<string>>>>(\n ...rules: Rules\n ): All<Rules[number]> => Object.freeze({ _tag: 'All', rules: Object.freeze([...rules]) }),\n\n /** This row's Read is the Read of the row its `one` relation points at. */\n inherit: <const Relation extends string>(relation: Relation): Inherit<Relation> =>\n Object.freeze({ _tag: 'Inherit', relation }),\n\n /** A surface's guards with a refusal other than its default. */\n on: <const Rules extends ReadonlyArray<AnyRule>, D extends Redact<unknown> | Explain>(\n rules: Rules,\n deny: D,\n ): On<Rules[number], D> => Object.freeze({ _tag: 'On', rules: Object.freeze([...rules]), deny }),\n\n /** A hidden member reads as `value`, typed by the member's schema. */\n redact: <const A>(value: A): Redact<A> => Object.freeze({ _tag: 'Redact', value }),\n\n /** A refused write tells the caller `reason`. */\n explain: (reason: string): Explain => Object.freeze({ _tag: 'Explain', reason }),\n\n /**\n * The members a row interaction's guards read, `always` included: a change\n * to one can change whether a principal may. A relation an inherited Read\n * follows counts.\n */\n guardFields: (\n entity: AnyEntity,\n interaction: 'Read' | 'Create' | 'Update' | 'Delete' | InteractionKey,\n ): ReadonlyArray<string> =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => [\n ...new Set(\n [...(attachment.row[interaction]?.rules ?? []), ...attachment.always].flatMap(\n membersRead,\n ),\n ),\n ],\n }),\n\n /** Who may do what, one line per surface, for review and for a committed snapshot. */\n matrix: (entities: ReadonlyArray<AnyEntity>): string =>\n entities\n .flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [`${entity.name}: no guards`],\n onSome: attachment =>\n linesOf(attachment).map(([where, rule]) => `${entity.name}.${where}: ${rule}`),\n }),\n )\n .join('\\n'),\n}\n"],"mappings":";;;;;;;;;AAsBA,MAAM,UAAU;CAAC;CAAQ;CAAU;CAAU;CAAU;CAAS;CAAQ;AAAQ;AAEhF,MAAa,cAAc;;AAEzB,OAAkC,SAAkC;CAClE,IAAK,QAAkC,SAAS,IAAI,GAClD,MAAM,IAAI,MAAM,sCAAsC,KAAK,4BAA4B;CAEzF,OAAO,OAAO,OAAO;EAAE;EAAM,KAAK;CAA6B,CAAC;AAClE,EACF;AAsIA,MAAM,eAAqC,OAAO,OAAO,IAAI;AAE7D,MAAM,iBAAiB,MAA+B,aAAqB,UAAmB;CAC5F,MAAM,SAAS,KAAK;CACpB,KAAK,eACH,WAAW,KAAA,IACP,QACA;EACE,OAAO,CAAC,GAAG,OAAO,OAAO,GAAG,MAAM,KAAK;EACvC,MAAM,OAAO,OAAO,MAAM,YAAY,OAAO,IAAI;CACnD;AACR;AAEA,MAAM,kBAAkB,MAA+B,UAAoB;CACzE,KAAK,MAAM,CAAC,aAAa,YAAY,OAAO,QAAQ,KAAK,GACvD,cAAc,MAAM,aAAa,OAAO;AAE5C;AAEA,MAAM,kBAAkB,aAAuC;CAC7D,KAAK,MAAM,OAAO,OAAO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F;;CAGA,MACE,GAAG,UACoB,OAAO,OAAO;EAAE,MAAM;EAAO,OAAO,OAAO,OAAO,CAAC,GAAG,KAAK,CAAC;CAAE,CAAC;;CAGxF,UAAyC,aACvC,OAAO,OAAO;EAAE,MAAM;EAAW;CAAS,CAAC;;CAG7C,KACE,OACA,SACyB,OAAO,OAAO;EAAE,MAAM;EAAM,OAAO,OAAO,OAAO,CAAC,GAAG,KAAK,CAAC;EAAG;CAAK,CAAC;;CAG/F,SAAkB,UAAwB,OAAO,OAAO;EAAE,MAAM;EAAU;CAAM,CAAC;;CAGjF,UAAU,WAA4B,OAAO,OAAO;EAAE,MAAM;EAAW;CAAO,CAAC;;;;;;CAO/E,cACE,QACA,gBAEA,OAAO,MAAM,SAAS,MAAM,GAAG;EAC7B,cAAc,CAAC;EACf,SAAQ,eAAc,CACpB,GAAG,IAAI,IACL,CAAC,GAAI,WAAW,IAAI,YAAY,EAAE,SAAS,CAAC,GAAI,GAAG,WAAW,MAAM,CAAC,CAAC,QACpE,WACF,CACF,CACF;CACF,CAAC;;CAGH,SAAS,aACP,SACG,SAAQ,WACP,OAAO,MAAM,SAAS,MAAM,GAAG;EAC7B,cAAc,CAAC,GAAG,OAAO,KAAK,YAAY;EAC1C,SAAQ,eACN,QAAQ,UAAU,CAAC,CAAC,KAAK,CAAC,OAAO,UAAU,GAAG,OAAO,KAAK,GAAG,MAAM,IAAI,MAAM;CACjF,CAAC,CACH,CAAC,CACA,KAAK,IAAI;AAChB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"placed-Bs_mnBTF.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'\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 placed.policy === 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":";;;;;;;;;AAiBA,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,OAAO,WAAW,UAClB,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"}