palgres 0.55.0 → 0.57.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.
@@ -0,0 +1,399 @@
1
+ /*! palgres 0.57.0 — Palbase SDK License (see LICENSE) */
2
+ import{createHash as Dn}from"node:crypto";function As(t){return`${t}_lookup`}function Os(t,e){let n=s=>s==="cascade"||s==="set null"||s==="set default";return n(t)||n(e)}var Vt=class extends Error{problems;constructor(e){super(`the schema is not valid:
3
+ - ${e.join(`
4
+ - `)}`),this.name="SchemaError",this.problems=e}},Ss=()=>({tables:[],enums:[],extensions:[],raw:[]}),ue=t=>`${t.schema}.${t.name}`,Fn={int:"integer",int4:"integer",int2:"smallint",int8:"bigint",float4:"real",float8:"double precision",bool:"boolean",timestamptz:"timestamp with time zone",timestamp:"timestamp without time zone","timestamp without time zone":"timestamp without time zone",timetz:"time with time zone",time:"time without time zone",varchar:"character varying",char:"character",decimal:"numeric"};function Et(t){let e=t.trim().replace(/\s+/g," "),n="";for(;e.endsWith("[]");)n+="[]",e=e.slice(0,-2).trim();let s=/^((?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_ ]*?)(?:\.(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_]*))?)\s*(\(.*\))?$/.exec(e);if(!s)return t.trim()+n;let o=s[2]?s[2].replace(/\s+/g,""):"",r=Mn(s[1]);return r===void 0?t.trim()+n:r.length===1&&r[0].quoted?`"${r[0].name.replace(/"/g,'""')}"${o}${n}`:r.length===1?`${Fn[r[0].name]??r[0].name}${o}${n}`:`${r.map(p=>mt(p.name)).join(".")}${o}${n}`}var mt=t=>/^[a-z_][a-z0-9_$]*$/.test(t)?t:`"${t.replace(/"/g,'""')}"`,Cs=(t,e)=>`${mt(t)}.${mt(e)}`;function Mn(t){let e=[],n=0;for(;n<t.length;){if(t[n]==='"'){let s=n+1,o="";for(;;){if(s>=t.length)return;if(t[s]==='"'){if(t[s+1]==='"'){o+='"',s+=2;continue}break}o+=t[s++]}e.push({name:o,quoted:!0}),n=s+1}else{let s=/^[A-Za-z_][A-Za-z0-9_ ]*/.exec(t.slice(n));if(!s)return;e.push({name:s[0].trim().toLowerCase(),quoted:!1}),n+=s[0].length}if(n<t.length){if(t[n]!==".")return;n++}}return e}var vn=/^[A-Za-z_][A-Za-z0-9_$]*$/,Un=63;function ae(t,e,n=!1){if(typeof e!="string"||e==="")return`${t} has no name`;if(n?e.includes("\0"):!vn.test(e))return`${t} "${e}": a name is letters, digits and _ (starting with a letter or _)`;if(Buffer.byteLength(e)>Un)return`${t} "${e}": longer than Postgres' 63 bytes, it would be cut`;if(e.startsWith("palgres_")||e.startsWith("_palgres"))return`${t} "${e}": names starting with palgres_ are Palgres' own`}var Pn="vector",Xt=["cosine","euclidean","inner_product"],gt=1536,Gn=2e3,dt=4e3,Hn=/^(text|citext|public\.citext|character varying(\(\d+\))?)$/;function ht(t,e,n){let s=[];e.primaryKey.length!==1&&s.push(`${t} declares search and has ${e.primaryKey.length===0?"no primary key":`a primary key of ${e.primaryKey.length} columns`}: a row's vector is kept by its key \u2014 give the table a single-column primary key (uuid().primaryKey())`),(!Array.isArray(n.from)||n.from.length===0)&&s.push(`${t}: search.from is empty \u2014 name the text columns a row is found by (search: { from: ['title', 'body'], model })`);let o=new Set;for(let r of Array.isArray(n.from)?n.from:[]){o.has(r)&&s.push(`${t}: search.from names "${r}" twice \u2014 name each column once`),o.add(r);let p=e.columns.find(c=>c.name===r);p?p.ignored?s.push(`${t}: search.from names "${r}", which is ignored \u2014 take it out of search.from, or keep the column`):Hn.test(Et(p.type))?p.generated&&s.push(`${t}: search.from names "${r}", a generated column \u2014 no write names it, so nothing would say when to embed the row again: name the columns it is computed from`):s.push(`${t}: search.from names "${r}", which is ${p.type} \u2014 search reads text (text, varchar, citext): name a text column, or keep the text in one`):s.push(`${t}: search.from names "${r}", which the table does not have \u2014 name its text columns`)}return(typeof n.model!="string"||n.model.trim()==="")&&s.push(`${t}: search.model is empty \u2014 name the embedding model (search: { from, model: 'embedding' })`),Xt.includes(n.metric)||s.push(`${t}: search.metric is ${JSON.stringify(n.metric)} \u2014 it is ${Xt.map(r=>`'${r}'`).join(", ")}`),(!Number.isInteger(n.dimensions)||n.dimensions<1||n.dimensions>dt)&&s.push(`${t}: search.dimensions is ${String(n.dimensions)} \u2014 it is 1 to ${dt}: pgvector indexes a vector of at most ${Gn} dimensions and a half-precision one of at most ${dt}; ask the model for fewer (search: { dimensions: ${gt} })`),n.staleness!=="null"&&n.staleness!=="keep"&&s.push(`${t}: search.staleness is ${JSON.stringify(n.staleness)} \u2014 it is 'null' (a changed row is not found by its old meaning) or 'keep' (it is, until embedded again)`),e.columns.some(r=>r.name==="_score"&&!r.ignored)&&s.push(`${t} declares search and has a column "_score": search() answers each row with its _score \u2014 rename the column`),s}function Is(t){let e=[],n=c=>c&&e.push(c),s=new Map,o=new Map,r=(c,l,R)=>{let k=`${c}.${l}`,v=o.get(k);v?e.push(`${R} "${l}" has the name of ${v} in schema ${c}`):o.set(k,R)};for(let c of t.enums)n(ae("an enum",c.name)),c.values.length===0&&e.push(`enum ${c.schema}.${c.name} has no values`),new Set(c.values).size!==c.values.length&&e.push(`enum ${c.schema}.${c.name} names a value twice`);for(let c of t.tables){let l=ue(c);n(ae("a schema",c.schema)),n(ae("a table",c.name)),s.has(l)&&e.push(`table ${l} is declared twice`),s.set(l,c),r(c.schema,c.name,`table ${l}`);let R=new Map,k=(y,j)=>{let G=R.get(y);G?e.push(`${j} "${y}" has the name of a ${G} of table ${l}`):R.set(y,j)},v=new Map;for(let y of c.columns)n(ae(`column ${l}.${y.name}`,y.name)),v.has(y.name)&&e.push(`column ${l}.${y.name} is declared twice`),v.set(y.name,y),y.identity&&y.default!==void 0&&e.push(`column ${l}.${y.name}: an identity column has no default`),y.generated&&(y.default!==void 0||y.identity||y.fill!==void 0)&&e.push(`column ${l}.${y.name}: a generated column has no default, identity or fill`),y.generated&&!y.generated.expr.trim()&&e.push(`column ${l}.${y.name}: a generated column's expression is empty`),y.identity&&!["smallint","integer","bigint"].includes(Et(y.type))&&e.push(`column ${l}.${y.name}: an identity column is smallint, integer or bigint`),y.identity&&y.nullable&&e.push(`column ${l}.${y.name}: an identity column is NOT NULL`);let U=(y,j)=>{let G=v.get(y);G?G.ignored&&e.push(`${j} names column "${y}", which is ignored`):e.push(`${j} names column "${y}", which ${l} does not have`)};for(let y of c.primaryKey)U(y,`the primary key of ${l}`);for(let y of c.primaryKey)v.get(y)?.nullable&&e.push(`column ${l}.${y} is in the primary key, so it is not nullable`);for(let y of c.uniques){n(ae(`a unique constraint of ${l}`,y.name,!0)),r(c.schema,y.name,`unique constraint ${l}.${y.name}`),k(y.name,"unique constraint"),y.columns.length===0&&e.push(`unique constraint ${y.name} names no column`);for(let j of y.columns)U(j,`unique constraint ${y.name}`)}for(let y of c.indexes){n(ae(`an index of ${l}`,y.name,!0)),r(c.schema,y.name,`index ${l}.${y.name}`),y.keys.length===0&&e.push(`index ${y.name} has no key`);for(let j of y.keys)"column"in j&&U(j.column,`index ${y.name}`);for(let j of y.include??[])U(j,`index ${y.name}`)}for(let y of c.checks)n(ae(`a check of ${l}`,y.name,!0)),k(y.name,"check"),y.expr.trim()||e.push(`check ${y.name} has no expression`);for(let y of c.foreignKeys){n(ae(`a foreign key of ${l}`,y.name,!0)),k(y.name,"foreign key"),(y.columns.length===0||y.columns.length!==y.refColumns.length)&&e.push(`foreign key ${y.name} names ${y.columns.length} column(s) and references ${y.refColumns.length}`);for(let j of y.columns)U(j,`foreign key ${y.name}`)}let H=new Set;for(let y of c.policies)n(ae(`a policy of ${l}`,y.name,!0)),H.has(y.name)&&e.push(`policy ${l}.${y.name} is declared twice`),H.add(y.name),y.to.length===0&&e.push(`policy ${l}.${y.name} names no role`),y.for==="insert"&&y.using!==void 0&&e.push(`policy ${l}.${y.name}: an insert policy has only withCheck`),(y.for==="select"||y.for==="delete")&&y.withCheck!==void 0&&e.push(`policy ${l}.${y.name}: a ${y.for} policy has only using`);c.policies.length>0&&!c.rls&&e.push(`table ${l} has policies but row-level security off: they would do nothing`),c.search!==void 0&&e.push(...ht(`table ${l}`,c,c.search))}for(let c of t.tables)for(let l of c.foreignKeys){let R=s.get(`${l.refSchema}.${l.refTable}`);if(!R){e.push(`foreign key ${l.name} of ${ue(c)} references ${l.refSchema}.${l.refTable}, which is not declared`);continue}R.ignored&&e.push(`foreign key ${l.name} of ${ue(c)} references ${ue(R)}, which is ignored`);for(let k of l.refColumns)R.columns.some(v=>v.name===k&&!v.ignored)||e.push(`foreign key ${l.name} references ${ue(R)}.${k}, which it does not have`)}let p=new Set;for(let c of t.raw)n(ae("a raw unit",c.name)),p.has(c.name)&&e.push(`raw unit ${c.name} is declared twice`),p.add(c.name),c.sql.trim()||e.push(`raw unit ${c.name} has no SQL`),c.before&&c.table!==void 0&&e.push(`raw unit ${c.name}: before is for a schema's unit, not a table's \u2014 a table's is made after its table`);return e}function Yt(t){let e=n=>[...n].sort((s,o)=>s.name<o.name?-1:s.name>o.name?1:0);return{tables:[...t.tables].map(n=>({...n,schema:n.schema||"public",columns:n.columns.map(s=>({...s,type:Et(s.type)})),uniques:e(n.uniques),indexes:e(n.indexes),checks:e(n.checks),foreignKeys:e(n.foreignKeys),policies:e(n.policies).map(s=>({...s,to:[...s.to].sort()}))})).sort((n,s)=>ue(n)<ue(s)?-1:ue(n)>ue(s)?1:0),enums:[...t.enums].sort((n,s)=>`${n.schema}.${n.name}`<`${s.schema}.${s.name}`?-1:1),extensions:[...new Set([...t.extensions,...t.tables.some(n=>n.search!==void 0)?[Pn]:[]])].sort(),raw:e(t.raw),...t.access!==void 0?{access:t.access}:{}}}function Ls(t){let e=Yt(t),n=new Map(t.raw.map((s,o)=>[s.name,o]));return e.raw.sort((s,o)=>(n.get(s.name)??0)-(n.get(o.name)??0)),e}function ft(t){return Array.isArray(t)?`[${t.map(ft).join(",")}]`:t&&typeof t=="object"?`{${Object.entries(t).filter(([,n])=>n!==void 0).sort(([n],[s])=>n<s?-1:1).map(([n,s])=>`${JSON.stringify(n)}:${ft(s)}`).join(",")}}`:JSON.stringify(t)}function ks(t){return Dn("sha256").update(ft(Yt(t))).digest("hex").slice(0,32)}var $t=Symbol.for("palbase.table.meta"),be=Symbol.for("palbase.ref.target"),ze=class{_def;constructor(e){if(e.trim()==="")throw new Error("foreignKey(name): a foreign key's name cannot be empty \u2014 Palbase reconciles constraints by name.");this._def={name:e,columns:[],refTable:"",refColumns:[]}}on(...e){return this._def.columns=e.map(n=>{let s=n.expr;if(s.kind!=="col")throw new Error(`foreignKey(${this._def.name}).on(): takes column references only \u2014 an expression cannot be part of a foreign key.`);return s.name}),this}references(e,...n){if(n.length===0)throw new Error(`foreignKey(${this._def.name}).references(): needs at least one target column.`);return this._def.refColumns=[...n],typeof e=="function"?(Object.defineProperty(this._def,be,{value:()=>e()[$t],enumerable:!1,configurable:!0}),this):(this._def.refTable=e[$t].name,Object.defineProperty(this._def,be,{value:e[$t],enumerable:!1,configurable:!0}),this)}onUpdate(e){return this._def.onUpdate=e,this}onDelete(e){return this._def.onDelete=e,this}match(e){return this._def.match=e,this}index(e){if(e!==!1)throw new Error(`foreignKey(${this._def.name}).index(): only index(false) \u2014 an index is made unasked`);return this._def.index=!1,this}deferrable(e){if(e!==!1)throw new Error(`foreignKey(${this._def.name}).deferrable(): only deferrable(false) \u2014 a key with an action is deferrable unasked`);return this._def.deferrable=!1,this}};function Kn(t){return new ze(t)}function zt(t){let e=t instanceof ze?t._def:t;if(e.columns.length===0)throw new Error(`foreignKey(${e.name}): needs at least one local column \u2014 call .on(...).`);let n=typeof e[be]=="function";if(e.refColumns.length===0||e.refTable===""&&!n)throw new Error(`foreignKey(${e.name}): needs the target table and its columns \u2014 call .references(...).`);if(e.columns.length!==e.refColumns.length)throw new Error(`foreignKey(${e.name}): ${e.columns.length} local column(s) (${e.columns.join(", ")}) but ${e.refColumns.length} target column(s) (${e.refColumns.join(", ")}) \u2014 the two lists must be the same length.`);return e}var x=class extends Error{code;line;constructor(e,n,s=0){super(s>0?`line ${s}: ${n}`:n),this.name="AccessError",this.code=e,this.line=s}};var J="user:*",Q="public",Wn=["->","!=","<=",">=","<>",":",",","=","<",">","+","&","-","(",")",".","|","*"],Jt=256*1024,Qt=256,Zt=32;function Bn(t){if(t.length>Jt)throw new x("too_large",`the schema is ${t.length} characters; at most ${Jt}`);let e=[],n=0,s=1,o=r=>{throw new x("syntax",r,s)};for(;n<t.length;){let r=t[n];if(r===`
5
+ `){e.push({k:"nl",v:`
6
+ `,line:s,at:n,end:n+1}),s++,n++;continue}if(r===" "||r===" "||r==="\r"){n++;continue}if(r==="#"||r==="/"&&t[n+1]==="/"){for(;n<t.length&&t[n]!==`
7
+ `;)n++;continue}if(/[A-Za-z_]/.test(r)){let c=n+1;for(;c<t.length&&/[A-Za-z0-9_]/.test(t[c]);)c++;e.push({k:"word",v:t.slice(n,c),line:s,at:n,end:c}),n=c;continue}if(/[0-9]/.test(r)){let c=n+1;for(;c<t.length&&/[0-9]/.test(t[c]);)c++;if(t[c]==="."&&/[0-9]/.test(t[c+1]??""))for(c++;c<t.length&&/[0-9]/.test(t[c]);)c++;/[A-Za-z_]/.test(t[c]??"")&&o(`"${t.slice(n,c+1)}" is not a number`),e.push({k:"number",v:t.slice(n,c),line:s,at:n,end:c}),n=c;continue}if(r==='"'||r==="'"){let c=n+1,l="";for(;;){if((c>=t.length||t[c]===`
8
+ `)&&o(r==='"'?"a quoted name is not closed":"a text value is not closed"),t[c]===r){if(t[c+1]===r){l+=r,c+=2;continue}break}l+=t[c],c++}l.includes("\0")&&o("a NUL character cannot be in a name or a value"),r==='"'&&l===""&&o("a quoted name is empty"),e.push({k:r==='"'?"quoted":"string",v:l,line:s,at:n,end:c+1}),n=c+1;continue}let p=Wn.find(c=>t.startsWith(c,n));p||o(`unexpected character ${JSON.stringify(r)}`),e.push({k:"sym",v:p,line:s,at:n,end:n+p.length}),n+=p.length}return e.push({k:"nl",v:`
9
+ `,line:s,at:n,end:n}),e.push({k:"end",v:"",line:s,at:n,end:n}),e}var qn=["select","insert","update","delete"];function Ae(t){let e=Bn(t),n=0,s=(d=0)=>e[Math.min(n+d,e.length-1)],o=()=>e[Math.min(n++,e.length-1)],r=(d,E=s())=>{throw new x("syntax",d,E.line)},p=d=>d.k==="nl"?"the end of the line":d.k==="end"?"the end of the schema":`"${d.v}"`,c=(d,E=0)=>s(E).k==="sym"&&s(E).v===d,l=(d,E=0)=>s(E).k==="word"&&s(E).v===d,R=(d,E)=>(c(d)||r(`expected "${d}" ${E}, found ${p(s())}`),o()),k=()=>{for(;s().k==="nl";)o()},v=d=>{s().k!=="nl"&&s().k!=="end"&&r(`unexpected ${p(s())} after ${d}`)},U=d=>{let E=o();E.k!=="word"&&r(`expected ${d}, found ${p(E)}`,E);let g=E.v,A=s(),a=s(1);return A.k==="sym"&&A.v==="."&&A.at===E.end&&a.k==="word"&&a.at===A.end&&(o(),o(),g+=`.${a.v}`),g},H=d=>{let E=o();return E.k!=="word"&&E.k!=="quoted"&&r(`expected ${d}, found ${p(E)}`,E),E.v},y=()=>{let d=o();return d.k==="string"?(d.v.length>Qt&&r(`a value is at most ${Qt} characters; this one has ${d.v.length}`,d),{t:"string",v:d.v}):d.k==="number"?{t:"number",v:d.v}:d.k==="sym"&&d.v==="-"&&s().k==="number"&&s().at===d.end?{t:"number",v:`-${o().v}`}:d.k==="word"&&(d.v==="true"||d.v==="false")?{t:"boolean",v:d.v==="true"}:r(`expected a value ('text', a number, true or false), found ${p(d)}`,d)},j=0,G=d=>{if(++j>Zt)throw new x("too_deep",`parentheses and "not" nested more than ${Zt} deep`,s().line);try{return d()}finally{j--}},Y=()=>{let d=P();if(!l("and")&&!l("or"))return d;let E=s().v,g=[d];for(;l("and")||l("or");)s().v!==E&&r(`"${E}" and "${s().v}" in one condition: put parentheses around one of them`),o(),g.push(P());return{op:E,parts:g}},P=()=>{if(l("not"))return o(),{op:"not",part:G(P)};if(c("(")){o();let g=G(Y);return R(")","to close the condition"),g}let d=H("a column");if(l("is")){o();let g=!1;return l("not")&&(o(),g=!0),l("null")||r(`expected "null" after "is", found ${p(s())}`),o(),{op:"null",column:d,negated:g}}if(l("in")){o(),R("(",'after "in"');let g=[y()];for(;c(",");)o(),g.push(y());return R(")","to close the list"),{op:"in",column:d,values:g}}let E=o();return(E.k!=="sym"||!["=","!=","<>","<","<=",">",">="].includes(E.v))&&r(`expected a comparison after "${d}", found ${p(E)}`,E),{op:"cmp",column:d,cmp:E.v==="<>"?"!=":E.v,value:y()}},te=()=>{let d=Z(),E=()=>{let u=0;for(;s(u).k==="nl";)u++;let f=s(u),h=f.k!=="sym"?null:f.v==="+"?"union":f.v==="&"?"intersect":f.v==="-"?"exclude":null;return h!==null&&(n+=u),h},g=E();if(g===null)return d;let A=d,a=[d];for(;;){let u=E();if(u===null)break;u!==g&&r(`"${s().v}" beside another operator: put parentheses around one of them`),o(),k();let f=Z();g==="exclude"?A={op:"exclude",base:A,minus:f}:a.push(f)}return g==="exclude"?A:{op:g,parts:a}},Z=()=>{if(c("(")){o(),k();let E=G(te);return k(),R(")","to close the expression"),E}let d=U("a relation or a permission");return c("->")?(o(),{op:"arrow",relation:d,name:U('a relation or a permission after "->"')}):{op:"ref",name:d}},b=[];for(k();s().k!=="end";){l("type")||r(`expected "type", found ${p(s())}`);let d=o(),E={name:U("the type's name"),table:null,relations:[],permissions:[],rows:[],line:d.line};for(v("the type's name"),k();s().k!=="end"&&!l("type");){let g=o();if(g.k!=="word"&&r(`expected "table", "relation", "permission" or "rows", found ${p(g)}`,g),g.v==="table"){E.table&&r(`type ${E.name} names its table twice`,g);let A=null,a=H("a table");c(".")&&(o(),A=a,a=H("a table"));let u=null;l("key")&&(o(),u=H("the key column")),E.table={schema:A,name:a,key:u,line:g.line},v("the table")}else if(g.v==="relation"){let A=[U("the relation's name")];for(;c(",");)o(),A.push(U("a relation's name"));R(":","after the relation's name");let a=()=>{let h=U('"user", "user:*", "public" or a type');return h!=="user"||!c(":")?h:(o(),c("*")||r(`expected "*" after "user:" (user:* is every signed-in user), found ${p(s())}`),o(),J)},u=[a()];for(;c("|");)o(),u.push(a());let f=h=>h===J||h===Q;if(l("where")){o(),A.length>1&&r("a relation read from the row is declared alone, one per line",g);let h=u[0];u.length>1||!f(h)?r('a relation with "where" and no "from" is read from the row itself: its subject is user:* (every signed-in user) or public, alone',g):E.relations.push({kind:"row",name:A[0],subject:h,where:Y(),line:g.line})}else if(l("from")){o(),A.length>1&&r("a relation read from a column is declared alone, one per line",g),u.length>1&&r("a relation read from a column has one kind of subject",g),f(u[0])&&r(`a column holds a subject's id or an object's: "${u[0]}" is read from the row itself \u2014 write "where" with no "from"`,g);let h=H("a column"),N=null;l("where")&&(o(),N=Y()),E.relations.push({kind:"column",name:A[0],subject:u[0],column:h,where:N,line:g.line})}else for(let h of A)E.relations.push({kind:"stored",name:h,subjects:[...u],line:g.line});v("the relation")}else if(g.v==="permission"){let A=U("the permission's name");R("=","after the permission's name"),k(),E.permissions.push({name:A,expr:te(),line:g.line}),v("the permission")}else if(g.v==="rows"){let A=[];for(;;){let a=o();if((a.k!=="word"||!qn.includes(a.v))&&r(`expected select, insert, update or delete, found ${p(a)}`,a),A.push(a.v),!c(","))break;o()}R(":","after the commands"),E.rows.push({commands:A,name:U("a permission"),line:g.line}),v("the rows rule")}else r(`expected "table", "relation", "permission" or "rows", found "${g.v}"`,g);k()}b.push(E)}return{types:b}}var X="user",le="*",Nt=[X,J,Q],yt=16,en=200,tn=100,nn=200,sn=200,on=50,rn=25e3,an=300,Rt=150,Vn=2,Xn=4,cn=63,Yn=/^[a-z][a-z0-9_]{0,39}$/,zn=/^[a-z][a-z0-9_]{0,39}(\.[a-z][a-z0-9_]{0,39})?$/,Ze=t=>t.replace(".","__"),Oe=t=>t.kind==="stored"?t.subjects.some(e=>Nt.includes(e)):t.kind==="row"||t.subject===X,ce=t=>t.kind==="stored"?t.subjects.filter(e=>!Nt.includes(e)):t.kind==="row"||t.subject===X?[]:[t.subject],ve=t=>t.kind==="stored"&&t.subjects.includes(X),ln=t=>t?t.kind==="stored"?Math.max(1,(ve(t)?1:0)+et(t).length):t.where?1+Qe(t.where):1:1,et=t=>t.kind==="stored"?t.subjects.filter(e=>e===J||e===Q):[],un=t=>t.kind==="stored"?t.subjects.includes(Q):t.kind==="row"&&t.subject===Q;function Je(t){return t.op==="ref"||t.op==="arrow"?1:t.op==="exclude"?1+Je(t.base)+Je(t.minus):1+t.parts.reduce((e,n)=>e+Je(n),0)}function Qe(t){return"parts"in t?t.parts.reduce((e,n)=>e+Qe(n),0):t.op==="not"?Qe(t.part):t.op==="in"?t.values.length:1}function bt(t,e){if("parts"in t)for(let n of t.parts)bt(n,e);else t.op==="not"?bt(t.part,e):e.add(t.column)}function Tt(t){let e=new Set;return t&&bt(t,e),[...e]}function Se(t){if(t.types.length>en)throw new x("too_large",`${t.types.length} types; at most ${en}`);let e=new Map;for(let b of t.types){if(b.name===X)throw new x("invalid_name",'"user" is whoever asks: a type cannot be called that',b.line);if(b.name===Q)throw new x("invalid_name",'"public" is everyone, signed in or not: a type cannot be called that',b.line);if(!Yn.test(b.name)||b.name.includes("__"))throw new x("invalid_name",`type "${b.name}" is not a name: lowercase letters, digits and single underscores, starting with a letter, at most 40`,b.line);if(e.has(b.name))throw new x("duplicate",`type "${b.name}" is declared twice`,b.line);let d=new Map,E=new Map,g=new Map,A=(a,u,f)=>{if(!zn.test(a)||a.includes("__"))throw new x("invalid_name",`${f} "${a}" is not a name: lowercase letters, digits and single underscores, with at most one dot (code.write), at most 40 each side`,u);if(d.has(a)||E.has(a))throw new x("duplicate",`"${a}" is declared twice in type ${b.name}`,u);let h=Ze(a),N=`${b.name}__${h}`;if(N.length>cn)throw new x("invalid_name",`${f} "${a}" of type ${b.name}: together they are asked as access.${N} \u2014 ${N.length} characters, and a name in the database holds ${cn}. Shorten the type's name or this one`,u);let L=g.get(h);if(L!==void 0)throw new x("duplicate",`"${a}" and "${L}" of type ${b.name} would have one name in the database`,u);g.set(h,a)};for(let a of b.relations)A(a.name,a.line,"relation"),d.set(a.name,a);for(let a of b.permissions){if(A(a.name,a.line,"permission"),Je(a.expr)>nn)throw new x("too_large",`permission ${b.name}.${a.name} has more than ${nn} terms`,a.line);E.set(a.name,a)}if(d.size+E.size>tn)throw new x("too_large",`type ${b.name} declares more than ${tn} names`,b.line);e.set(b.name,{name:b.name,table:b.table?{schema:b.table.schema??"public",name:b.table.name,key:b.table.key}:null,relations:d,permissions:E,rows:[]})}let n=new Map;for(let b of e.values()){if(!b.table)continue;let d=`${b.table.schema}\0${b.table.name}`,E=n.get(d);if(E!==void 0)throw new x("duplicate",`types ${E} and ${b.name} name the same table`,t.types.find(g=>g.name===b.name)?.line??0);n.set(d,b.name)}for(let b of t.types){let d=e.get(b.name);for(let E of b.relations)if(E.kind==="stored"){let g=new Set;for(let A of E.subjects){if(g.has(A))throw new x("duplicate",`relation ${d.name}.${E.name} names "${A}" twice`,E.line);if(g.add(A),!Nt.includes(A)&&!e.has(A))throw new x("unknown_type",`relation ${d.name}.${E.name}: there is no type "${A}"`,E.line)}}else{let g=E.kind==="row"?"is read from the row":"reads a column";if(!d.table)throw new x("needs_table",`relation ${d.name}.${E.name} ${g}, and type ${d.name} names no table`,E.line);if(E.where&&Qe(E.where)>on)throw new x("too_large",`relation ${d.name}.${E.name}: its condition holds more than ${on} comparisons`,E.line);if(E.kind==="column"&&E.subject!==X&&!e.has(E.subject))throw new x("unknown_type",`relation ${d.name}.${E.name}: there is no type "${E.subject}"`,E.line)}}let s=(b,d)=>{let E=e.get(b);return E.relations.get(d)??E.permissions.get(d)},o=(b,d)=>e.get(b).permissions.has(d),r=(b,d)=>{let E=e.get(b);if(E.permissions.has(d))return"yes";let g=E.relations.get(d);return g?Oe(g)?"yes":"objects":"missing"},p=new Map,c=(b,d)=>`${b}\0${d}`;for(let b of t.types){let d=e.get(b.name);for(let g of b.permissions){let A=[],a=u=>{if(u.op==="ref"){let f=r(d.name,u.name);if(f==="missing")throw new x("unknown_name",`permission ${d.name}.${g.name}: type ${d.name} has no relation or permission "${u.name}"`,g.line);if(f==="objects")throw new x("not_a_holder",`permission ${d.name}.${g.name}: relation "${u.name}" leads to objects, no subject holds it \u2014 follow it with "->", as in ${u.name}->view`,g.line);A.push({type:d.name,name:u.name})}else if(u.op==="arrow"){let f=d.relations.get(u.relation);if(!f){let N=d.permissions.has(u.relation)?`"${u.relation}" is a permission; an arrow follows a relation`:`type ${d.name} has no relation "${u.relation}"`;throw new x("unknown_name",`permission ${d.name}.${g.name}: ${N}`,g.line)}let h=ce(f);if(h.length===0)throw new x("not_an_object_relation",`permission ${d.name}.${g.name}: relation "${u.relation}" leads to no object (its subjects are users), so "->" has nothing to follow`,g.line);for(let N of h){let L=r(N,u.name);if(L==="missing")throw new x("unknown_name",`permission ${d.name}.${g.name}: ${u.relation}->${u.name} \u2014 type ${N} has no relation or permission "${u.name}"`,g.line);if(L==="objects")throw new x("not_a_holder",`permission ${d.name}.${g.name}: ${u.relation}->${u.name} \u2014 "${u.name}" of type ${N} leads to objects, no subject holds it`,g.line);A.push({type:N,name:u.name})}}else if(u.op==="exclude")a(u.base),a(u.minus);else for(let f of u.parts)a(f)};a(g.expr),p.set(c(d.name,g.name),A)}let E=new Set;for(let g of b.rows){if(!d.table)throw new x("needs_table",`type ${d.name} has a rows rule and names no table`,g.line);let A=r(d.name,g.name);if(A==="missing")throw new x("unknown_name",`rows rule of type ${d.name}: there is no relation or permission "${g.name}"`,g.line);if(A==="objects")throw new x("not_a_holder",`rows rule of type ${d.name}: relation "${g.name}" leads to objects, no subject holds it`,g.line);for(let a of g.commands){if(E.has(a))throw new x("duplicate",`type ${d.name} has two rows rules for ${a}`,g.line);E.add(a),d.rows.push({command:a,name:g.name})}}}let l=[],R=new Map,k=(b,d)=>s(b,d)?.line??0,v=(b,d,E)=>{let g=c(b,d),A=R.get(g);if(typeof A=="number")return A;let a=`${b}.${d}`;if(A==="open"){let f=E.indexOf(a),h=[...E.slice(f),a].join(" \u2192 ");throw new x("cycle",`${h}: a permission derived from itself. A type that contains itself (a folder in a folder) is not supported; fixed levels are (company, product, session), however many`,k(b,d))}R.set(g,"open");let u=0;if(o(b,d))for(let f of p.get(g)??[])u=Math.max(u,1+v(f.type,f.name,[...E,a]));if(u>yt)throw new x("too_deep",`${a} is derived through more than ${yt} levels`,k(b,d));return R.set(g,u),l.push({type:b,name:d}),u};for(let b of e.values()){for(let d of b.relations.values())v(b.name,d.name,[]);for(let d of b.permissions.values())v(b.name,d.name,[])}let U=new Map,H=(b,d)=>{let E=c(b,d),g=U.get(E);if(g!==void 0)return g;let A=e.get(b),a=A.permissions.get(d),u=h=>h.op==="ref"?H(b,h.name):h.op==="arrow"?1+ce(A.relations.get(h.relation)).reduce((N,L)=>N+H(L,h.name),0):h.op==="exclude"?u(h.base)+u(h.minus):h.parts.reduce((N,L)=>N+u(L),0),f=a?u(a.expr):1;return U.set(E,f),f};for(let b of e.values())for(let d of b.permissions.values()){let E=H(b.name,d.name);if(E>sn)throw new x("too_large",`permission ${b.name}.${d.name} comes to ${E} relations once everything it is derived from is written out; at most ${sn}. It names the same permissions through several paths \u2014 derive it from fewer, or from relations directly`,d.line)}let y=new Map,j=(b,d)=>{let E=c(b,d),g=y.get(E);if(g!==void 0)return g;let A=e.get(b),a=A.permissions.get(d),u=ln,f=N=>N.op==="ref"?j(b,N.name):N.op==="arrow"?u(A.relations.get(N.relation)):N.op==="exclude"?f(N.base)+f(N.minus):N.parts.reduce((L,C)=>L+f(C),0),h=a?f(a.expr):u(A.relations.get(d));return y.set(E,h),h},G=new Map,Y=(b,d)=>{let E=c(b,d),g=G.get(E);if(g!==void 0)return g;let A=e.get(b),a=A.permissions.get(d),u=ln,f=N=>{if(N.op==="ref")return Y(b,N.name);if(N.op==="arrow"){let L=A.relations.get(N.relation),C=L.kind==="column"?Vn:Xn;return u(L)+C*ce(L).reduce((q,Ve)=>q+Y(Ve,N.name),0)}return N.op==="exclude"?f(N.base)+f(N.minus):N.parts.reduce((L,C)=>L+f(C),0)},h=a?f(a.expr):u(A.relations.get(d));return G.set(E,h),h};for(let b of e.values())for(let d of b.permissions.values()){let E=Y(b.name,d.name);if(E>an)throw new x("too_large",`permission ${b.name}.${d.name} would be planned as ${E} lookups \u2014 a kept relation is one for each way it can be held (by a user, by every signed-in user, by the public), and what is read through another type is planned inside it, two or four times over; at most ${an} (about 140 KB of the database's memory each, on every statement it guards). Read fewer levels deep through other types' permissions, or through relations read from columns`,d.line)}let P=0;for(let b of e.values())for(let d of[...b.relations.keys(),...b.permissions.keys()])P+=j(b.name,d);if(P>rn)throw new x("too_large",`the schema comes to ${P} terms once each of its names is written out in full (a permission with what it names, a relation with its condition); at most ${rn}. Derive permissions from one another's names through fewer copies, or shorten the conditions they repeat`);let te=new Map,Z=(b,d)=>{let E=c(b,d),g=te.get(E);if(g!==void 0)return g;let A=e.get(b),a=A.relations.get(d),u=A.permissions.get(d),f=N=>N.op==="ref"?Z(b,N.name):N.op==="arrow"?ce(A.relations.get(N.relation)).some(L=>Z(L,N.name)):N.op==="exclude"?f(N.base):N.op==="union"?N.parts.some(f):N.parts.every(f),h=a?un(a):u?f(u.expr):!1;return te.set(E,h),h};return{types:e,order:l,planned:Y,open:Z}}var Ue=63,O=t=>{if(t.includes("\0"))throw new TypeError("a NUL character cannot be in a name");if(new TextEncoder().encode(t).length>Ue)throw new x("invalid_name",`"${t}" is longer than the ${Ue} bytes a name in the database holds`);return`"${t.replace(/"/g,'""')}"`},_t=(t,e)=>`${O(t)}.${O(e)}`;function $(t){if(t.includes("\0"))throw new TypeError("a NUL character cannot be sent to Postgres");return`E'${t.replace(/\\/g,"\\\\").replace(/'/g,"''")}'`}function M(t){let e="access";for(let n=0;t.includes(`$${e}$`);n++)e=`access${n}`;return`$${e}$${t}$${e}$`}var Jn={text:"text",varchar:"text",uuid:"uuid",int2:"int",int4:"int",int8:"int",bool:"bool",numeric:"numeric",float4:"numeric",float8:"numeric"};function wt(t){let e=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(e))throw new x("syntax","the catalog could not be read: its answer is not a list of tables");let n=new Map;for(let s of e){let o=new Map;for(let r of s.columns)o.set(r.name,{type:r.type,family:r.array?null:r.enum?"enum":Jn[r.type]??null});n.set(`${s.schema}\0${s.name}`,{schema:s.schema,name:s.name,kind:s.kind,primaryKey:s.pk,identifying:s.identifying??(s.pk.length===1?[...s.pk]:[]),columns:o,forcesRowSecurity:s.force,hasChildren:s.children===!0,hasParent:s.parent===!0,indexes:Number(s.indexes??(s.pk.length>0?1:0))})}return{table:(s,o)=>n.get(`${s}\0${o}`)}}function xt(t){return wt(t.map(e=>({schema:e.schema??"public",name:e.name,kind:"r",force:e.forcesRowSecurity??!1,pk:e.primaryKey,...e.identifying===void 0?{}:{identifying:e.identifying},...e.indexes===void 0?{}:{indexes:e.indexes},columns:Object.entries(e.columns).map(([n,s])=>({name:n,type:s,enum:e.enums?.includes(n)??!1,array:!1}))})))}var ee="access",Ce="palbase access",Pe="3",me=["!access_fresh","!access_forget","!access_move","!access_empty"],At=[...me].sort((t,e)=>Buffer.from(t)<Buffer.from(e)?-1:1).at(-1),Ot=t=>`(${t}.tgtype & 66) = 0 AND ${t}.tgname COLLATE "C" < ${$(At)}`,Ge={authenticated:"authenticated",service:"service_role",visitor:"anon"},oe="*",pe=t=>`(${t}.expires_at IS NULL OR ${t}.expires_at > pg_catalog.statement_timestamp())`,pn=t=>`coalesce((pg_catalog.to_jsonb(${t}) ->> 'expires_at')::timestamptz > pg_catalog.statement_timestamp(), true)`,dn=t=>`(CASE WHEN ${t}.subject_type = 'user' AND ${t}.subject_id = ${$(oe)} THEN ${$(J)} ELSE ${t}.subject_type END)`;function mn(){let t=O(ee);return`DO $star$
10
+ DECLARE n bigint;
11
+ BEGIN
12
+ IF EXISTS (SELECT 1 FROM ${t}.schemas s WHERE s.active AND (CASE WHEN s.engine ~ '^[0-9]+$' THEN s.engine::int ELSE 0 END) < 3) THEN
13
+ SELECT count(*) INTO n FROM ${t}.relationships r WHERE r.subject_type = 'user' AND r.subject_id = ${$(oe)};
14
+ IF n > 0 THEN
15
+ RAISE EXCEPTION USING ERRCODE = ${$(B.badId)}, MESSAGE = pg_catalog.format('%s relationships are given to a user whose id is "*". From this engine on that is every signed-in user, and nothing is opened by a row that was not given to open it: take them first \u2014 access.revoke(\u2026, ''user'', ''*'') \u2014 then put the schema in', n);
16
+ END IF;
17
+ END IF;
18
+ END $star$`}var St="^-?[0-9]{1,18}$",tt="^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$",He=256,B={unknown:"PA001",noObject:"PA002",badId:"PA003",tooMany:"PA004",notTaken:"PA005",notAllowed:"PA006",badTime:"PA007"},W="SET search_path = pg_catalog, pg_temp";function nt(t=Ge){let e=O(ee),n=`${O(t.authenticated)}, ${O(t.service)}`,s=O(t.service),o=r=>`DO $visitor$ BEGIN IF EXISTS (SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = ${$(t.visitor)}) THEN EXECUTE ${$(r.replaceAll("<visitor>",O(t.visitor)))}; END IF; END $visitor$`;return[`CREATE SCHEMA IF NOT EXISTS ${e}`,`COMMENT ON SCHEMA ${e} IS ${$(Ce)}`,`CREATE TABLE IF NOT EXISTS ${e}.relationships (
19
+ object_type text NOT NULL, object_id text NOT NULL, relation text NOT NULL,
20
+ subject_type text NOT NULL, subject_id text NOT NULL,
21
+ created_at timestamptz NOT NULL DEFAULT now(),
22
+ given_in xid8 NOT NULL DEFAULT pg_current_xact_id(),
23
+ expires_at timestamptz,
24
+ PRIMARY KEY (object_type, object_id, relation, subject_type, subject_id))`,`ALTER TABLE ${e}.relationships ADD COLUMN IF NOT EXISTS given_in xid8 NOT NULL DEFAULT pg_current_xact_id()`,`ALTER TABLE ${e}.relationships ADD COLUMN IF NOT EXISTS expires_at timestamptz`,`CREATE INDEX IF NOT EXISTS relationships_by_subject ON ${e}.relationships (subject_type, subject_id, object_type, relation, object_id)`,`CREATE INDEX IF NOT EXISTS relationships_ending ON ${e}.relationships (expires_at) WHERE expires_at IS NOT NULL`,`CREATE TABLE IF NOT EXISTS ${e}.history (
25
+ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
26
+ at timestamptz NOT NULL DEFAULT now(),
27
+ action text NOT NULL CONSTRAINT history_action_check CHECK (action IN ('grant', 'revoke', 'expire')),
28
+ object_type text NOT NULL, object_id text NOT NULL, relation text NOT NULL,
29
+ subject_type text NOT NULL, subject_id text NOT NULL,
30
+ actor text,
31
+ expires_at timestamptz)`,`ALTER TABLE ${e}.history ADD COLUMN IF NOT EXISTS expires_at timestamptz`,`DO $history$
32
+ BEGIN
33
+ IF NOT EXISTS (SELECT 1 FROM pg_catalog.pg_constraint c WHERE c.conrelid = ${$(`${ee}.history`)}::pg_catalog.regclass AND c.conname = 'history_action_check'
34
+ AND pg_catalog.pg_get_constraintdef(c.oid) LIKE '%expire%') THEN
35
+ ALTER TABLE ${e}.history DROP CONSTRAINT IF EXISTS history_action_check;
36
+ ALTER TABLE ${e}.history ADD CONSTRAINT history_action_check CHECK (action IN ('grant', 'revoke', 'expire'));
37
+ END IF;
38
+ END $history$`,`CREATE INDEX IF NOT EXISTS history_by_object ON ${e}.history (object_type, object_id, id DESC)`,`CREATE INDEX IF NOT EXISTS history_by_subject ON ${e}.history (subject_type, subject_id, id DESC)`,`CREATE TABLE IF NOT EXISTS ${e}.objects_touched (
39
+ object_type text NOT NULL, object_id text NOT NULL, touched xid8 NOT NULL DEFAULT pg_current_xact_id(),
40
+ PRIMARY KEY (object_type, object_id))`,`DROP FUNCTION IF EXISTS ${e}.moved_objects() CASCADE`,`DROP TABLE IF EXISTS ${e}.moves`,`CREATE TABLE IF NOT EXISTS ${e}.schemas (
41
+ digest text PRIMARY KEY, text text NOT NULL, engine text NOT NULL,
42
+ applied_at timestamptz NOT NULL DEFAULT now(), applied_by text NOT NULL DEFAULT session_user,
43
+ active boolean NOT NULL DEFAULT false)`,mn(),`CREATE OR REPLACE FUNCTION ${e}.may_name_a_subject() RETURNS boolean LANGUAGE sql STABLE ${W} AS ${M(`
44
+ SELECT pg_has_role(o.role, ${$(t.service)}, 'MEMBER')
45
+ OR EXISTS (SELECT 1 FROM pg_namespace n WHERE n.nspname = ${$(ee)} AND pg_has_role(o.role, n.nspowner, 'MEMBER'))
46
+ FROM (SELECT CASE WHEN current_setting('role') IN ('none', '') THEN session_user ELSE current_setting('role')::name END AS role) o`)}`,`CREATE OR REPLACE FUNCTION ${e}.asker() RETURNS text LANGUAGE sql STABLE ${W} AS ${M(`
47
+ SELECT CASE WHEN NOT ${e}.may_name_a_subject() THEN c.sub
48
+ WHEN current_setting('access.visitor', true) = 'on' THEN NULL
49
+ ELSE coalesce(nullif(current_setting('access.subject', true), ''), c.sub) END
50
+ FROM (SELECT nullif((nullif(current_setting('request.jwt.claims', true), ''))::jsonb ->> 'sub', '') AS sub) c`)}`,`CREATE OR REPLACE FUNCTION ${e}.subject() RETURNS text LANGUAGE sql STABLE ${W} AS ${M(` SELECT nullif(${e}.asker(), ${$(oe)}) `)}`,`CREATE OR REPLACE FUNCTION ${e}.signed_in() RETURNS boolean LANGUAGE sql STABLE ${W} AS ${M(` SELECT ${e}.asker() IS NOT NULL `)}`,`CREATE OR REPLACE FUNCTION ${e}.subject_uuid() RETURNS uuid LANGUAGE sql STABLE ${W} AS ${M(`
51
+ SELECT CASE WHEN s ~ ${$(tt)} THEN s::uuid END FROM (SELECT ${e}.subject() AS s) q`)}`,`CREATE OR REPLACE FUNCTION ${e}.subject_int() RETURNS bigint LANGUAGE sql STABLE ${W} AS ${M(`
52
+ SELECT CASE WHEN s ~ ${$(St)} THEN s::bigint END FROM (SELECT ${e}.subject() AS s) q`)}`,`CREATE OR REPLACE FUNCTION ${e}.act_as(subject text) RETURNS void LANGUAGE plpgsql VOLATILE ${W} AS ${M(`
53
+ BEGIN
54
+ IF NOT ${e}.may_name_a_subject() THEN
55
+ RAISE EXCEPTION USING ERRCODE = ${$(B.notAllowed)}, MESSAGE = 'this role asks for itself alone: it cannot ask as another subject';
56
+ END IF;
57
+ PERFORM set_config('access.subject', coalesce(subject, ''), true);
58
+ PERFORM set_config('access.visitor', '', true);
59
+ END`)}`,`CREATE OR REPLACE FUNCTION ${e}.act_as_visitor() RETURNS void LANGUAGE plpgsql VOLATILE ${W} AS ${M(`
60
+ BEGIN
61
+ IF NOT ${e}.may_name_a_subject() THEN
62
+ RAISE EXCEPTION USING ERRCODE = ${$(B.notAllowed)}, MESSAGE = 'this role asks for itself alone: it cannot ask as a visitor';
63
+ END IF;
64
+ PERFORM set_config('access.visitor', 'on', true);
65
+ END`)}`,`CREATE OR REPLACE FUNCTION ${e}.touch(object_type text, object_ids text[]) RETURNS void LANGUAGE sql VOLATILE SECURITY DEFINER ${W} AS ${M(`
66
+ INSERT INTO ${e}.objects_touched (object_type, object_id, touched)
67
+ SELECT $1, i, pg_current_xact_id() FROM unnest($2) AS i WHERE i IS NOT NULL ORDER BY 2
68
+ ON CONFLICT (object_type, object_id) DO UPDATE SET touched = excluded.touched`)}`,`CREATE OR REPLACE FUNCTION ${e}.older_snapshot() RETURNS boolean LANGUAGE sql STABLE ${W} AS ${M(`
69
+ SELECT current_setting('transaction_isolation') NOT IN ('read committed', 'read uncommitted')`)}`,`CREATE OR REPLACE FUNCTION ${e}.refuse(state text, message text) RETURNS boolean LANGUAGE plpgsql STABLE ${W} AS ${M(`
70
+ BEGIN RAISE EXCEPTION USING ERRCODE = state, MESSAGE = message; END`)}`,`CREATE OR REPLACE FUNCTION ${e}.refuse_text(state text, message text) RETURNS text LANGUAGE plpgsql STABLE ${W} AS ${M(`
71
+ BEGIN RAISE EXCEPTION USING ERRCODE = state, MESSAGE = message; END`)}`,`CREATE OR REPLACE FUNCTION ${e}.record() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER ${W} AS ${M(`
72
+ DECLARE who text := coalesce(nullif(current_setting('access.actor', true), ''), ${e}.subject(), session_user::text);
73
+ DECLARE ended boolean := TG_OP <> 'INSERT' AND OLD.expires_at IS NOT NULL AND OLD.expires_at <= pg_catalog.statement_timestamp();
74
+ same boolean := TG_OP = 'UPDATE' AND (OLD.object_type, OLD.object_id, OLD.relation, OLD.subject_type, OLD.subject_id) = (NEW.object_type, NEW.object_id, NEW.relation, NEW.subject_type, NEW.subject_id);
75
+ BEGIN
76
+ -- One whose time had passed ended then, whatever takes its row now: said once, at that moment.
77
+ IF ended THEN
78
+ INSERT INTO ${e}.history (at, action, object_type, object_id, relation, subject_type, subject_id, actor, expires_at)
79
+ VALUES (OLD.expires_at, 'expire', OLD.object_type, OLD.object_id, OLD.relation, OLD.subject_type, OLD.subject_id, 'access: its time passed', OLD.expires_at);
80
+ -- (What is given and taken is told at the moment of the statement that did it \u2014 not of its transaction's
81
+ -- beginning: one that began before a relationship ended and gives it again after is told after the ending.)
82
+ ELSIF TG_OP = 'DELETE' OR (TG_OP = 'UPDATE' AND NOT same) THEN
83
+ INSERT INTO ${e}.history (at, action, object_type, object_id, relation, subject_type, subject_id, actor, expires_at)
84
+ VALUES (pg_catalog.statement_timestamp(), 'revoke', OLD.object_type, OLD.object_id, OLD.relation, OLD.subject_type, OLD.subject_id, who, OLD.expires_at);
85
+ END IF;
86
+ -- Given, given again after its time passed, or given another end: one line, with the end it has now.
87
+ IF TG_OP = 'INSERT' OR (TG_OP = 'UPDATE' AND (NOT same OR ended OR OLD.expires_at IS DISTINCT FROM NEW.expires_at)) THEN
88
+ INSERT INTO ${e}.history (at, action, object_type, object_id, relation, subject_type, subject_id, actor, expires_at)
89
+ VALUES (pg_catalog.statement_timestamp(), 'grant', NEW.object_type, NEW.object_id, NEW.relation, NEW.subject_type, NEW.subject_id, who, NEW.expires_at);
90
+ END IF;
91
+ RETURN NULL;
92
+ END`)}`,`CREATE OR REPLACE TRIGGER record AFTER INSERT OR UPDATE OR DELETE ON ${e}.relationships FOR EACH ROW EXECUTE FUNCTION ${e}.record()`,`CREATE OR REPLACE FUNCTION ${e}.forget_object() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER ${W} AS ${M(`
93
+ DECLARE gone text := to_jsonb(OLD) ->> TG_ARGV[1]; was text := current_setting('access.actor', true);
94
+ BEGIN
95
+ IF gone IS NULL THEN RETURN NULL; END IF;
96
+ IF ${e}.older_snapshot() THEN PERFORM ${e}.touch(TG_ARGV[0], ARRAY[gone]); END IF;
97
+ PERFORM set_config('access.actor', 'access: row deleted', true);
98
+ DELETE FROM ${e}.relationships WHERE object_type = TG_ARGV[0] AND object_id = gone;
99
+ DELETE FROM ${e}.relationships WHERE subject_type = TG_ARGV[0] AND subject_id = gone;
100
+ DELETE FROM ${e}.objects_touched WHERE object_type = TG_ARGV[0] AND object_id = gone;
101
+ PERFORM set_config('access.actor', coalesce(was, ''), true);
102
+ RETURN NULL;
103
+ END`)}`,`CREATE OR REPLACE FUNCTION ${e}.move_object() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER ${W} AS ${M(`
104
+ DECLARE old_id text := to_jsonb(OLD) ->> TG_ARGV[1]; new_id text := to_jsonb(NEW) ->> TG_ARGV[1]; was text := current_setting('access.actor', true);
105
+ BEGIN
106
+ IF old_id IS NULL OR new_id IS NULL OR old_id = new_id THEN RETURN NULL; END IF;
107
+ IF ${e}.older_snapshot() THEN PERFORM ${e}.touch(TG_ARGV[0], ARRAY[old_id, new_id]); END IF;
108
+ PERFORM set_config('access.actor', 'access: id used again', true);
109
+ DELETE FROM ${e}.relationships WHERE object_type = TG_ARGV[0] AND object_id = new_id;
110
+ DELETE FROM ${e}.relationships WHERE subject_type = TG_ARGV[0] AND subject_id = new_id;
111
+ -- What had ended is not carried to the new id: it goes here, told once, as ended on the id it was given on.
112
+ DELETE FROM ${e}.relationships WHERE object_type = TG_ARGV[0] AND object_id = old_id AND expires_at <= pg_catalog.statement_timestamp();
113
+ DELETE FROM ${e}.relationships WHERE subject_type = TG_ARGV[0] AND subject_id = old_id AND expires_at <= pg_catalog.statement_timestamp();
114
+ PERFORM set_config('access.actor', 'access: key changed', true);
115
+ UPDATE ${e}.relationships SET object_id = new_id WHERE object_type = TG_ARGV[0] AND object_id = old_id;
116
+ UPDATE ${e}.relationships SET subject_id = new_id WHERE subject_type = TG_ARGV[0] AND subject_id = old_id;
117
+ DELETE FROM ${e}.objects_touched WHERE object_type = TG_ARGV[0] AND object_id = new_id;
118
+ UPDATE ${e}.objects_touched SET object_id = new_id WHERE object_type = TG_ARGV[0] AND object_id = old_id;
119
+ PERFORM set_config('access.actor', coalesce(was, ''), true);
120
+ RETURN NULL;
121
+ END`)}`,`CREATE OR REPLACE FUNCTION ${e}.fresh_objects() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER ${W} AS ${M(`
122
+ DECLARE made text := to_jsonb(NEW) ->> TG_ARGV[1]; cur xid8 := pg_current_xact_id(); was text := current_setting('access.actor', true);
123
+ BEGIN
124
+ IF made IS NULL THEN RETURN NULL; END IF;
125
+ IF NOT EXISTS (SELECT 1 FROM ${e}.relationships r WHERE r.object_type = TG_ARGV[0] AND r.object_id = made AND r.given_in <> cur)
126
+ AND NOT EXISTS (SELECT 1 FROM ${e}.relationships r WHERE r.subject_type = TG_ARGV[0] AND r.subject_id = made AND r.given_in <> cur) THEN
127
+ RETURN NULL;
128
+ END IF;
129
+ PERFORM set_config('access.actor', 'access: id used again', true);
130
+ DELETE FROM ${e}.relationships WHERE object_type = TG_ARGV[0] AND object_id = made AND given_in <> cur;
131
+ DELETE FROM ${e}.relationships WHERE subject_type = TG_ARGV[0] AND subject_id = made AND given_in <> cur;
132
+ PERFORM set_config('access.actor', coalesce(was, ''), true);
133
+ RETURN NULL;
134
+ END`)}`,`CREATE OR REPLACE FUNCTION ${e}.forget_all() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER ${W} AS ${M(`
135
+ DECLARE was text := current_setting('access.actor', true);
136
+ BEGIN
137
+ IF ${e}.older_snapshot() THEN
138
+ RAISE EXCEPTION USING ERRCODE = '55000', MESSAGE = format('TRUNCATE of the table of type %s: in a READ COMMITTED transaction \u2014 by an older snapshot, relationships given since could not be taken with its rows', TG_ARGV[0]);
139
+ END IF;
140
+ PERFORM set_config('access.actor', 'access: table emptied', true);
141
+ DELETE FROM ${e}.relationships WHERE object_type = TG_ARGV[0];
142
+ DELETE FROM ${e}.relationships WHERE subject_type = TG_ARGV[0];
143
+ DELETE FROM ${e}.objects_touched WHERE object_type = TG_ARGV[0];
144
+ PERFORM set_config('access.actor', coalesce(was, ''), true);
145
+ RETURN NULL;
146
+ END`)}`,`CREATE OR REPLACE FUNCTION ${e}.binding_guard() RETURNS trigger LANGUAGE plpgsql ${W} AS ${M(`
147
+ DECLARE i int;
148
+ BEGIN
149
+ FOR i IN 1 .. TG_NARGS - 1 LOOP
150
+ IF NEW.object_type = TG_ARGV[i] OR NEW.subject_type = TG_ARGV[i] THEN
151
+ RAISE EXCEPTION USING ERRCODE = '55000', MESSAGE = format('type %s is being given a table by the deploy of version %s: its relationships can be given once that deploy completes', TG_ARGV[i], TG_ARGV[0]);
152
+ END IF;
153
+ END LOOP;
154
+ RETURN NEW;
155
+ END`)}`,`CREATE OR REPLACE FUNCTION ${e}.forget_subject(subject text) RETURNS bigint LANGUAGE plpgsql VOLATILE SECURITY DEFINER ${W} AS ${M(`
156
+ DECLARE n bigint; was text := current_setting('access.actor', true);
157
+ BEGIN
158
+ -- "*" is nobody's id: what is kept for every signed-in user is not a user's to be forgotten with.
159
+ IF $1 = ${$(oe)} THEN RETURN 0; END IF;
160
+ PERFORM set_config('access.actor', 'access: subject deleted', true);
161
+ DELETE FROM ${e}.relationships WHERE subject_type = 'user' AND subject_id = $1;
162
+ GET DIAGNOSTICS n = ROW_COUNT;
163
+ PERFORM set_config('access.actor', coalesce(was, ''), true);
164
+ RETURN n;
165
+ END`)}`,`CREATE OR REPLACE VIEW ${e}.mine WITH (security_barrier = true) AS
166
+ SELECT r.object_type, r.object_id, r.relation FROM ${e}.relationships r
167
+ WHERE r.subject_type = 'user' AND r.subject_id = (SELECT ${e}.subject()) AND ${pe("r")}`,`CREATE OR REPLACE VIEW ${e}.for_users WITH (security_barrier = true) AS
168
+ SELECT r.object_type, r.object_id, r.relation FROM ${e}.relationships r
169
+ WHERE r.subject_type = 'user' AND r.subject_id = ${$(oe)} AND ${pe("r")} AND (SELECT ${e}.signed_in())`,`CREATE OR REPLACE VIEW ${e}.for_public WITH (security_barrier = true) AS
170
+ SELECT r.object_type, r.object_id, r.relation FROM ${e}.relationships r
171
+ WHERE r.subject_type = 'public' AND r.subject_id = ${$(oe)} AND ${pe("r")}`,`CREATE OR REPLACE VIEW ${e}.past AS
172
+ SELECT h.id, h.at, h.action, h.object_type, h.object_id, h.relation, h.subject_type, h.subject_id, h.actor, h.expires_at FROM ${e}.history h
173
+ UNION ALL
174
+ SELECT NULL::bigint, r.expires_at, 'expire', r.object_type, r.object_id, r.relation, r.subject_type, r.subject_id, 'access: its time passed', r.expires_at
175
+ FROM ${e}.relationships r WHERE r.expires_at <= pg_catalog.statement_timestamp()`,`CREATE OR REPLACE FUNCTION ${e}.sweep(batch integer DEFAULT 10000) RETURNS bigint LANGUAGE sql VOLATILE SECURITY DEFINER ${W} AS ${M(`
176
+ WITH gone AS (
177
+ DELETE FROM ${e}.relationships r
178
+ WHERE (r.object_type, r.object_id, r.relation, r.subject_type, r.subject_id) IN (
179
+ SELECT e.object_type, e.object_id, e.relation, e.subject_type, e.subject_id FROM ${e}.relationships e
180
+ WHERE e.expires_at <= pg_catalog.statement_timestamp() ORDER BY e.expires_at LIMIT greatest(coalesce($1, 0), 0))
181
+ AND r.expires_at <= pg_catalog.statement_timestamp()
182
+ RETURNING 1)
183
+ SELECT count(*) FROM gone`)}`,`DROP FUNCTION IF EXISTS ${e}.speaks(text)`,`REVOKE ALL ON SCHEMA ${e} FROM PUBLIC`,`GRANT USAGE ON SCHEMA ${e} TO ${n}`,`REVOKE ALL ON ALL TABLES IN SCHEMA ${e} FROM PUBLIC`,`REVOKE ALL ON ${e}.relationships, ${e}.history, ${e}.past, ${e}.schemas, ${e}.objects_touched, ${e}.mine, ${e}.for_users, ${e}.for_public FROM ${n}`,`GRANT SELECT ON ${e}.mine, ${e}.for_users, ${e}.for_public TO ${n}`,`GRANT SELECT ON ${e}.relationships, ${e}.history, ${e}.past, ${e}.schemas TO ${s}`,`REVOKE ALL ON ALL FUNCTIONS IN SCHEMA ${e} FROM PUBLIC`,`REVOKE ALL ON FUNCTION ${e}.asker(), ${e}.subject(), ${e}.signed_in(), ${e}.subject_uuid(), ${e}.subject_int(), ${e}.may_name_a_subject(), ${e}.refuse(text, text), ${e}.refuse_text(text, text), ${e}.act_as(text), ${e}.act_as_visitor(), ${e}.forget_subject(text), ${e}.sweep(integer), ${e}.record(), ${e}.forget_object(), ${e}.move_object(), ${e}.fresh_objects(), ${e}.forget_all(), ${e}.binding_guard(), ${e}.touch(text, text[]), ${e}.older_snapshot() FROM ${n}`,`GRANT EXECUTE ON FUNCTION ${e}.asker(), ${e}.subject(), ${e}.signed_in(), ${e}.subject_uuid(), ${e}.subject_int(), ${e}.may_name_a_subject(), ${e}.refuse(text, text), ${e}.refuse_text(text, text) TO ${n}`,`GRANT EXECUTE ON FUNCTION ${e}.act_as(text), ${e}.act_as_visitor(), ${e}.forget_subject(text), ${e}.sweep(integer) TO ${s}`,o(`GRANT USAGE ON SCHEMA ${e} TO <visitor>`),o(`REVOKE ALL ON ${e}.relationships, ${e}.history, ${e}.past, ${e}.schemas, ${e}.objects_touched, ${e}.mine, ${e}.for_users, ${e}.for_public FROM <visitor>`),o(`GRANT SELECT ON ${e}.mine, ${e}.for_users, ${e}.for_public TO <visitor>`),o(`REVOKE ALL ON FUNCTION ${e}.asker(), ${e}.subject(), ${e}.signed_in(), ${e}.subject_uuid(), ${e}.subject_int(), ${e}.may_name_a_subject(), ${e}.refuse(text, text), ${e}.refuse_text(text, text), ${e}.act_as(text), ${e}.act_as_visitor(), ${e}.forget_subject(text), ${e}.sweep(integer), ${e}.record(), ${e}.forget_object(), ${e}.move_object(), ${e}.fresh_objects(), ${e}.forget_all(), ${e}.binding_guard(), ${e}.touch(text, text[]), ${e}.older_snapshot() FROM <visitor>`),o(`GRANT EXECUTE ON FUNCTION ${e}.asker(), ${e}.subject(), ${e}.signed_in(), ${e}.subject_uuid(), ${e}.subject_int(), ${e}.may_name_a_subject(), ${e}.refuse(text, text), ${e}.refuse_text(text, text) TO <visitor>`)]}import{createHash as fn,randomUUID as Qn}from"node:crypto";var Ct=1e4,En=1e5,gn=1e4,hn=1e6,Ne=96*1024,Ke=100,re="SET search_path = pg_catalog, pg_temp",S=O(ee),$n=["text","uuid","int"],Ie=(t,e)=>t==="int"?`(CASE WHEN ${e} ~ ${$(St)} THEN (${e})::bigint END)`:t==="uuid"?`(CASE WHEN ${e} ~ ${$(tt)} THEN (${e})::uuid END)`:e,Zn=t=>t==="int"?`(SELECT ${S}.subject_int())`:t==="uuid"?`(SELECT ${S}.subject_uuid())`:`(SELECT ${S}.subject())`;function es(t,e){let n=new Map;for(let s of t.types.values()){if(!s.table){n.set(s.name,{name:s.name,model:s,table:null,family:"text",idType:"text"});continue}let o=`${s.table.schema}.${s.table.name}`,r=e.table(s.table.schema,s.table.name);if(!r)throw new x("unknown_table",`type ${s.name}: there is no table ${o}`);if(r.kind==="p"||r.hasChildren||r.hasParent)throw new x("not_supported",`type ${s.name}: ${o} is partitioned, a partition, or tied to another table by inheritance; a type's table is one plain table (its rows could be read past its rules through the other)`);if(r.kind!=="r")throw new x("not_supported",`type ${s.name}: ${o} is not a table (a view or a foreign table cannot carry a type)`);if(r.indexes>Rt)throw new x("too_large",`type ${s.name}: ${o} has ${r.indexes} indexes; a type's table has at most ${Rt} \u2014 the database reads every one of them for each lookup through the table, on every statement a rule guards`);if(r.forcesRowSecurity)throw new x("forced_row_security",`type ${s.name}: ${o} forces row-level security on its owner (FORCE ROW LEVEL SECURITY); access reads a type's table as its owner, so it would read nothing`);let p=s.table.key;if(p===null){if(r.primaryKey.length!==1){let R=r.primaryKey.length===0?"has no primary key":`has a primary key of ${r.primaryKey.length} columns`;throw new x("key_not_supported",`type ${s.name}: ${o} ${R}; name one column that identifies a row \u2014 table ${s.table.name} key <column>`)}p=r.primaryKey[0]}let c=r.columns.get(p);if(!c)throw new x("unknown_column",`type ${s.name}: ${o} has no column "${p}"`);if(!r.identifying.includes(p))throw new x("key_not_supported",`type ${s.name}: ${o}.${p} does not identify a row by itself at every moment; an object's key is NOT NULL and unique alone \u2014 the primary key, or a unique constraint or index of that column and no other \u2014 and not DEFERRABLE`);if(!c.family||!$n.includes(c.family))throw new x("key_not_supported",`type ${s.name}: the key ${o}.${p} is ${c.type}; an object's id is text, a uuid or an integer`);let l=c.family;n.set(s.name,{name:s.name,model:s,table:{sql:_t(r.schema,r.name),schema:r.schema,name:r.name,key:p,info:r},family:l,idType:l==="int"?"bigint":l})}for(let s of n.values())for(let o of s.model.relations.values()){if(o.kind==="stored")continue;let r=s.table.info,p=`${r.schema}.${r.name}`,c=`relation ${s.name}.${o.name}`;if(o.kind==="row"){st(o.where,r,c,o.line);continue}let l=r.columns.get(o.column);if(!l)throw new x("unknown_column",`${c}: ${p} has no column "${o.column}"`,o.line);if(!l.family||!$n.includes(l.family))throw new x("type_mismatch",`${c}: ${p}.${o.column} is ${l.type}; an id is text, a uuid or an integer`,o.line);if(o.subject!==X){let R=n.get(o.subject);if(R.table&&R.family!==l.family)throw new x("type_mismatch",`${c}: ${p}.${o.column} is ${l.type}, and the key of type ${R.name} is ${R.table.info.columns.get(R.table.key)?.type}`,o.line)}o.where&&st(o.where,r,c,o.line)}return n}function st(t,e,n,s){if("parts"in t){for(let R of t.parts)st(R,e,n,s);return}if(t.op==="not")return st(t.part,e,n,s);let o=`${e.schema}.${e.name}`,r=e.columns.get(t.column);if(!r)throw new x("unknown_column",`${n}: its condition reads "${t.column}", which ${o} does not have`,s);if(t.op==="null")return;let p=r.family;if(!p)throw new x("not_supported",`${n}: its condition compares ${o}.${t.column}, which is ${r.type}; a condition compares text, an enum, a uuid, a number or a boolean`,s);let c=t.op==="in"?t.values:[t.value];if(t.op==="cmp"&&t.cmp!=="="&&t.cmp!=="!="&&p!=="int"&&p!=="numeric")throw new x("not_supported",`${n}: "${t.column} ${t.op==="cmp"?t.cmp:""}" \u2014 only a number is compared by order; ${o}.${t.column} is ${r.type}`,s);for(let R of c){let k=p==="bool"?"boolean":p==="int"||p==="numeric"?"number":"string";if(R.t!==k)throw new x("type_mismatch",`${n}: ${o}.${t.column} is ${r.type}; its condition compares it with ${R.t==="string"?"a text":R.t==="number"?"a number":"true or false"}`,s);if(p==="int"&&R.t==="number"&&!/^-?[0-9]{1,18}$/.test(R.v))throw new x("type_mismatch",`${n}: ${o}.${t.column} is ${r.type}; ${R.v} is not a whole number it can hold`,s);if(p==="uuid"&&R.t==="string"&&!new RegExp(tt).test(R.v))throw new x("type_mismatch",`${n}: ${o}.${t.column} is a uuid; '${R.v}' is not one`,s)}}var yn=t=>t.t==="string"?$(t.v):t.t==="number"?t.v:t.v?"true":"false";function Re(t,e){return"parts"in t?`(${t.parts.map(n=>Re(n,e)).join(t.op==="and"?" AND ":" OR ")})`:t.op==="not"?`(NOT ${Re(t.part,e)})`:t.op==="null"?`(${e(t.column)} IS ${t.negated?"NOT ":""}NULL)`:t.op==="in"?`(${e(t.column)} IN (${t.values.map(yn).join(", ")}))`:`(${e(t.column)} ${t.cmp==="!="?"<>":t.cmp} ${yn(t.value)})`}function bn(t,e){return`SELECT g.tgname INTO early FROM pg_catalog.pg_trigger g JOIN pg_catalog.pg_proc p ON p.oid = g.tgfoid JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
184
+ WHERE g.tgrelid = ${$(t)}::pg_catalog.regclass AND NOT g.tgisinternal AND n.nspname <> ${$(ee)} AND ${Ot("g")}
185
+ ORDER BY g.tgname COLLATE "C" LIMIT 1;
186
+ IF early IS NOT NULL THEN
187
+ RAISE EXCEPTION '% has a trigger of its own, "%", that fires after a change and is named to come before access'' (${At}): rename it to come after, or make it fire before the change', ${$(e)}, early;
188
+ END IF;`}function ot(t,e,n,s={}){let o={...Ge,...s.roles},r=s.rows!==!1,p=es(t,e),c=`${ee}_${Qn().replaceAll("-","")}`,l=O(c),R=`${O(o.authenticated)}, ${O(o.service)}`,k=O(o.service),v=new Map,U=(i,m)=>{let _=v.get(i);if(_!==void 0&&_!==m)throw new x("invalid_name",`${m} and ${_} would have one name in the database (${i})`);return v.set(i,m),i},H=i=>i.length<=Ue?i:`${i.slice(0,Ue-17)}~${fn("sha256").update(i).digest("hex").slice(0,16)}`,y=(i,m)=>U(`${i}__${Ze(m)}`,`${i}.${m}`),j=(i,m)=>`${l}.${O(y(i,m))}`,G=(i,m,_)=>U(H(`${i}:${m}->${_}`),`the arrow ${i}.${m}->${_}`),Y=(i,m)=>`${l}.${O(U(H(`${i}:${m}?`),`who holds ${i}.${m}`))}`,P=i=>p.get(i),te=(i,m)=>i.table?`(${m.key})::text`:m.key,Z=(i,m,_)=>{if("parts"in m)return`(${m.parts.map(I=>Z(i,I,_)).join(m.op==="union"?" OR ":" AND ")})`;if(m.op==="exclude")return`(${Z(i,m.base,_)} AND (${Z(i,m.minus,_)}) IS NOT TRUE)`;if(m.op==="ref"){let I=i.model.permissions.get(m.name);return I?Z(i,I.expr,_):b(i,i.model.relations.get(m.name),_)}let w=i.model.relations.get(m.relation);if(w.kind==="column"){let I=P(w.subject),T=`EXISTS (SELECT 1 FROM ${j(I.name,m.name)} x WHERE x.id = ${I.table?_.col(w.column):`(${_.col(w.column)})::text`})`;return w.where?`(${T} AND ${Re(w.where,_.col)})`:T}return`EXISTS (SELECT 1 FROM ${l}.${O(G(i.name,w.name,m.name))} h WHERE h.object_id = ${te(i,_)})`},b=(i,m,_)=>{if(m.kind==="stored"){let T=(V,F)=>`EXISTS (SELECT 1 FROM ${S}.${V} ${F} WHERE ${F}.object_type = ${$(i.name)} AND ${F}.relation = ${$(m.name)} AND ${F}.object_id = ${te(i,_)})`,D=et(m),z=[...ve(m)?[T("mine","m")]:[],...D.includes(J)?[T("for_users","eu")]:[],...D.includes(Q)?[T("for_public","ep")]:[]];return z.length===1?z[0]:`(${z.join(" OR ")})`}if(m.kind==="row"){let T=Re(m.where,_.col);return m.subject===Q?`(${T})`:`((SELECT ${S}.signed_in()) AND ${T})`}let w=i.table.info.columns.get(m.column)?.family,I=`${_.col(m.column)} = ${Zn(w)}`;return m.where?`(${I} AND ${Re(m.where,_.col)})`:`(${I})`},d=(i,m)=>{if("parts"in m)return m.parts.flatMap(I=>d(i,I));if(m.op==="exclude")return[...d(i,m.base),...d(i,m.minus)];let _=i.table?"($1)::text":"$1";if(m.op==="ref"){let I=i.model.permissions.get(m.name);if(I)return d(i,I.expr);let T=i.model.relations.get(m.name);if(T.kind==="stored")return ve(T)?[`SELECT m.subject_id FROM ${S}.relationships m WHERE m.object_type = ${$(i.name)} AND m.object_id = ${_} AND m.relation = ${$(T.name)} AND m.subject_type = 'user' AND ${pe("m")}`]:[];if(T.kind==="row")return[];let D=i.table,z=T.where?` AND ${Re(T.where,V=>`t.${O(V)}`)}`:"";return[`SELECT (t.${O(T.column)})::text FROM ${D.sql} AS t WHERE t.${O(D.key)} = $1 AND t.${O(T.column)} IS NOT NULL${z}`]}let w=i.model.relations.get(m.relation);if(w.kind==="column"){let I=i.table,T=P(w.subject),D=T.table?`t.${O(w.column)}`:`(t.${O(w.column)})::text`,z=w.where?` AND ${Re(w.where,V=>`t.${O(V)}`)}`:"";return[`SELECT w FROM ${I.sql} AS t CROSS JOIN LATERAL ${Y(T.name,m.name)}(${D}) AS w WHERE t.${O(I.key)} = $1${z}`]}return ce(w).map(I=>{let T=P(I);return`SELECT w FROM ${S}.relationships e CROSS JOIN LATERAL ${Y(T.name,m.name)}(${Ie(T.family,"e.subject_id")}) AS w WHERE e.object_type = ${$(i.name)} AND e.object_id = ${_} AND e.relation = ${$(w.name)} AND e.subject_type = ${$(T.name)} AND ${pe("e")} AND ${l}.walked(e.subject_id)`})},E=[`CREATE SCHEMA IF NOT EXISTS ${l}`];E.push(`CREATE OR REPLACE FUNCTION ${l}.walked(text) RETURNS boolean LANGUAGE plpgsql VOLATILE ${re} AS ${M(`
189
+ DECLARE n bigint := coalesce(nullif(pg_catalog.current_setting('access.walked', true), ''), '0')::bigint + 1;
190
+ BEGIN
191
+ IF n > ${gn} THEN
192
+ PERFORM ${S}.refuse(${$(B.tooMany)}, 'more than ${gn} objects related to this one would be walked to say who holds it: ask whether one subject holds it (check) instead of who does');
193
+ END IF;
194
+ PERFORM pg_catalog.set_config('access.walked', n::text, true);
195
+ RETURN true;
196
+ END`)}`);let g=[],A=new Set,a=new Set,u=new Set,f=new Set,h=i=>i.op==="arrow"?[i]:i.op==="ref"?[]:i.op==="exclude"?[...h(i.base),...h(i.minus)]:i.parts.flatMap(h);for(let{type:i,name:m}of t.order){let _=P(i),w=_.model.relations.get(m);if(w&&!Oe(w))continue;let I=_.model.permissions.get(m)?.expr??{op:"ref",name:m};for(let V of h(I)){let F=_.model.relations.get(V.relation),Fe=G(_.name,F.name,V.name);if(F.kind!=="stored"||A.has(Fe))continue;A.add(Fe);let $e=ce(F).map(xe=>{let Me=P(xe);return`(e.subject_type = ${$(Me.name)} AND EXISTS (SELECT 1 FROM ${j(Me.name,V.name)} x WHERE x.id = ${Ie(Me.family,"e.subject_id")}))`});E.push(`CREATE OR REPLACE VIEW ${l}.${O(Fe)} WITH (security_barrier = true) AS
197
+ SELECT e.object_id FROM ${S}.relationships e
198
+ WHERE e.object_type = ${$(_.name)} AND e.relation = ${$(F.name)} AND ${pe("e")} AND (${$e.join(" OR ")}) IS TRUE`)}let T=_.table?{col:V=>`t.${O(V)}`,key:`t.${O(_.table.key)}`}:{col:()=>"",key:"t.k"},D=_.table?`${_.table.sql} AS t`:`(SELECT DISTINCT r.object_id AS k FROM ${S}.relationships r WHERE r.object_type = ${$(_.name)} AND ${pe("r")}) AS t`;E.push(`CREATE OR REPLACE VIEW ${j(i,m)} WITH (security_barrier = true) AS SELECT ${T.key} AS id FROM ${D} WHERE (${Z(_,I,T)}) IS TRUE`);let z=d(_,I);E.push(`CREATE OR REPLACE FUNCTION ${Y(i,m)}(${_.idType}) RETURNS SETOF text LANGUAGE sql STABLE SECURITY DEFINER ${re} AS ${M(`
199
+ SELECT c.w FROM (
200
+ ${z.length>0?z.join(`
201
+ UNION ALL
202
+ `):"SELECT NULL::text WHERE false"}
203
+ ) AS c(w) LIMIT ${En+1}`)}`),g.push({type:i,name:m,view:y(i,m),idType:_.table?_.table.info.columns.get(_.table.key)?.type:"text",open:t.open(i,m)})}let N=(i,m,_)=>`${_} = ${$(i.type)} AND ${m} = ${$(i.name)}`,L=(i,m)=>`'type ' || coalesce(${m}, '(null)') || ' has no relation or permission ' || coalesce(${i}, '(null)')`,C=(i,m)=>g.length===0?m:`${g.map((_,w)=>`${w===0?"IF":"ELSIF"} ${N(_,"$1","$2")} THEN
204
+ ${i(_)}`).join(`
205
+ `)}
206
+ ELSE
207
+ ${m}
208
+ END IF;`;E.push(`CREATE OR REPLACE FUNCTION ${l}.can(permission text, object_type text, object_id text) RETURNS boolean LANGUAGE plpgsql STABLE ${re} AS ${M(`
209
+ BEGIN
210
+ ${C(i=>`RETURN EXISTS (SELECT 1 FROM ${j(i.type,i.name)} v WHERE v.id = ${Ie(P(i.type).family,"$3")});`,`RETURN ${S}.refuse(${$(B.unknown)}, ${L("$1","$2")});`)}
211
+ END`)}`,`CREATE OR REPLACE FUNCTION ${l}.my_objects(permission text, object_type text) RETURNS SETOF text LANGUAGE plpgsql STABLE ${re} AS ${M(`
212
+ BEGIN
213
+ ${C(i=>`RETURN QUERY SELECT (v.id)::text FROM ${j(i.type,i.name)} v;`,`PERFORM ${S}.refuse(${$(B.unknown)}, ${L("$1","$2")});`)}
214
+ RETURN;
215
+ END`)}`,`CREATE OR REPLACE FUNCTION ${l}.check(subject text, permission text, object_type text, object_id text) RETURNS boolean LANGUAGE plpgsql VOLATILE ${re} AS ${M(`
216
+ DECLARE was text := current_setting('access.subject', true); answer boolean;
217
+ BEGIN
218
+ IF $1 IS NULL OR $1 = '' THEN RETURN false; END IF;
219
+ PERFORM ${S}.act_as($1);
220
+ answer := ${l}.can($2, $3, $4);
221
+ PERFORM set_config('access.subject', coalesce(was, ''), true);
222
+ RETURN answer;
223
+ END`)}`,`CREATE OR REPLACE FUNCTION ${l}.objects(subject text, permission text, object_type text) RETURNS SETOF text LANGUAGE plpgsql VOLATILE ${re} AS ${M(`
224
+ DECLARE was text := current_setting('access.subject', true);
225
+ BEGIN
226
+ IF $1 IS NULL OR $1 = '' THEN RETURN; END IF;
227
+ PERFORM ${S}.act_as($1);
228
+ RETURN QUERY SELECT o FROM ${l}.my_objects($2, $3) AS o;
229
+ PERFORM set_config('access.subject', coalesce(was, ''), true);
230
+ RETURN;
231
+ END`)}`,`CREATE OR REPLACE FUNCTION ${l}.subjects(permission text, object_type text, object_id text) RETURNS SETOF text LANGUAGE plpgsql VOLATILE ${re} AS ${M(`
232
+ DECLARE named text[]; seen bigint := 0; walked bigint; c text;
233
+ BEGIN
234
+ PERFORM pg_catalog.set_config('access.walked', '0', true);
235
+ ${C(i=>`SELECT array_agg(DISTINCT w) FILTER (WHERE w IS NOT NULL AND w <> '' AND w <> ${$(oe)}), count(*) INTO named, seen FROM ${Y(i.type,i.name)}(${Ie(P(i.type).family,"$3")}) AS w;`,`PERFORM ${S}.refuse(${$(B.unknown)}, ${L("$1","$2")});`)}
236
+ IF seen > ${En} OR coalesce(array_length(named, 1), 0) > ${Ct} THEN
237
+ PERFORM ${S}.refuse(${$(B.tooMany)}, 'more than ${Ct} subjects are related to this object: ask whether one subject holds it (check) instead of who does');
238
+ END IF;
239
+ -- Each one is checked in turn, and a check reads the related objects again.
240
+ walked := coalesce(nullif(pg_catalog.current_setting('access.walked', true), ''), '0')::bigint;
241
+ IF coalesce(array_length(named, 1), 0) * (walked + 1) > ${hn} THEN
242
+ PERFORM ${S}.refuse(${$(B.tooMany)}, pg_catalog.format('saying who holds it would check %s subjects, each through %s related objects: more than ${hn} together; ask whether one subject holds it (check) instead of who does', array_length(named, 1), walked));
243
+ END IF;
244
+ FOREACH c IN ARRAY coalesce(named, '{}'::text[]) LOOP
245
+ IF ${l}.check(c, $1, $2, $3) THEN RETURN NEXT c; END IF;
246
+ END LOOP;
247
+ RETURN;
248
+ END`)}`,`CREATE OR REPLACE FUNCTION ${l}.open(permission text, object_type text, object_id text) RETURNS text LANGUAGE plpgsql VOLATILE ${re} AS ${M(`
249
+ DECLARE was text := current_setting('access.subject', true); visitor boolean; anybody boolean;
250
+ BEGIN
251
+ PERFORM ${S}.act_as_visitor();
252
+ visitor := ${l}.can($1, $2, $3);
253
+ PERFORM set_config('access.visitor', '', true);
254
+ PERFORM ${S}.act_as(${$(oe)});
255
+ anybody := ${l}.can($1, $2, $3);
256
+ PERFORM set_config('access.subject', coalesce(was, ''), true);
257
+ RETURN CASE WHEN visitor AND anybody THEN 'public' WHEN anybody THEN 'users' WHEN visitor THEN 'visitors' END;
258
+ END`)}`);let q=i=>i===J?"'user', true":i===Q?"'public', true":`${$(i)}, false`,Ve=[...p.values()].flatMap(i=>[...i.model.relations.values()].flatMap(m=>m.kind==="stored"?m.subjects.map(_=>`(${$(i.name)}, ${$(m.name)}, ${q(_)})`):[])),jt=(i,m,_,w)=>Ve.length===0?"false":`(${i}, ${m}, ${_}, coalesce(${w} = ${$(oe)}, false)) IN (${Ve.join(", ")})`,Dt=`'type ' || coalesce($1, '(null)') || ' keeps no relation ' || coalesce($3, '(null)') || ' that takes ' || CASE WHEN $4 = ${$(J)} THEN 'every signed-in user (user:*)' WHEN $4 = 'public' THEN 'the public' ELSE coalesce($4, '(null)') END`,Ft=`IF $4 = ${$(J)} OR $4 = 'public' THEN
259
+ IF $5 IS DISTINCT FROM ${$(oe)} THEN PERFORM ${S}.refuse(${$(B.badId)}, 'everyone of a kind is given as (' || pg_catalog.quote_literal($4) || ', ''*''): it has no id'); END IF;
260
+ IF $4 = ${$(J)} THEN st := 'user'; END IF;
261
+ ELSIF $5 = ${$(oe)} THEN
262
+ PERFORM ${S}.refuse(${$(B.badId)}, '"*" is nobody''s id: every signed-in user is given as the kind ''user:*'' \u2014 (\u2026, ''user:*'', ''*'') \u2014 and everyone as (\u2026, ''public'', ''*'')');
263
+ END IF;`,Mt=i=>`${S}.refuse(${$(B.badId)}, ${$(`${i} is empty or longer than ${He} characters`)})`,vt=[...p.values()].filter(i=>i.table).map(i=>$(i.name)),lt=i=>vt.length===0?"false":`${i} IN (${vt.join(", ")})`,Sn=`IF ${lt("$4")} AND ($4, s) < ($1, o) THEN PERFORM ${S}.touch($4, ARRAY[s]); END IF;
264
+ IF ${lt("$1")} THEN PERFORM ${S}.touch($1, ARRAY[o]); END IF;
265
+ IF ${lt("$4")} AND ($4, s) > ($1, o) THEN PERFORM ${S}.touch($4, ARRAY[s]); END IF;`;E.push(`CREATE OR REPLACE FUNCTION ${l}.object(object_type text, object_id text) RETURNS text LANGUAGE plpgsql VOLATILE SECURITY DEFINER ${re} AS ${M(`
266
+ DECLARE canon text;
267
+ BEGIN
268
+ ${[...p.values()].map(i=>i.table?`IF $1 = ${$(i.name)} THEN
269
+ SELECT (t.${O(i.table.key)})::text INTO canon FROM ${i.table.sql} AS t WHERE t.${O(i.table.key)} = ${Ie(i.family,"$2")} FOR KEY SHARE;
270
+ IF canon IS NULL THEN PERFORM ${S}.refuse(${$(B.noObject)}, 'there is no ' || $1 || ' ' || coalesce($2, '(null)')); END IF;
271
+ RETURN canon;
272
+ END IF;`:`IF $1 = ${$(i.name)} THEN
273
+ IF $2 IS NULL OR $2 = '' OR length($2) > ${He} THEN PERFORM ${Mt(`the id of a ${i.name}`)}; END IF;
274
+ RETURN $2;
275
+ END IF;`).join(`
276
+ `)}
277
+ PERFORM ${S}.refuse(${$(B.unknown)}, 'there is no type ' || coalesce($1, '(null)'));
278
+ RETURN NULL;
279
+ END`)}`,`CREATE OR REPLACE FUNCTION ${l}.grant(object_type text, object_id text, relation text, subject_type text, subject_id text, actor text DEFAULT NULL, expires_at timestamptz DEFAULT NULL) RETURNS boolean LANGUAGE plpgsql VOLATILE SECURITY DEFINER ${re} AS ${M(`
280
+ DECLARE o text; s text; st text := $4; given boolean; was text := current_setting('access.actor', true);
281
+ BEGIN
282
+ ${Ft}
283
+ IF (${jt("$1","$3","st","$5")}) IS NOT TRUE THEN PERFORM ${S}.refuse(${$(B.notTaken)}, ${Dt}); END IF;
284
+ IF $7 IS NOT NULL AND $7 <= pg_catalog.statement_timestamp() THEN
285
+ PERFORM ${S}.refuse(${$(B.badTime)}, 'a relationship is given until a moment still to come: ' || $7::text || ' has passed');
286
+ END IF;
287
+ -- Between two objects, an end is given where every schema that still answers reads it. While an app's
288
+ -- deploy is open, the version being replaced answers from the schema it was compiled with \u2014 and one an
289
+ -- engine before 3 compiled reads a team's relationship to a product as it stands, end or no end. (What a
290
+ -- user holds it reads through access.mine, which is this engine's.)
291
+ IF $7 IS NOT NULL AND st <> 'user' AND st <> 'public'
292
+ AND EXISTS (SELECT 1 FROM ${S}.schemas e WHERE e.active AND (CASE WHEN e.engine ~ '^[0-9]+$' THEN e.engine::int ELSE 0 END) < 3) THEN
293
+ PERFORM ${S}.refuse(${$(B.badTime)}, 'a relationship between two objects is given until a moment once the version being replaced has gone: its schema, compiled by an earlier engine, does not read an end');
294
+ END IF;
295
+ o := ${l}.object($1, $2);
296
+ IF st = 'user' OR st = 'public' THEN
297
+ IF $5 IS NULL OR $5 = '' OR length($5) > ${He} THEN PERFORM ${Mt("a subject's id")}; END IF;
298
+ s := $5;
299
+ ELSE
300
+ s := ${l}.object($4, $5);
301
+ END IF;
302
+ -- The rows it is given on, met by whatever takes their relationships away by a snapshot that cannot see it.
303
+ ${Sn}
304
+ -- What has ended on this object goes first, each said in the history at its own moment: given again after its
305
+ -- time, a relationship is given anew.
306
+ DELETE FROM ${S}.relationships r WHERE r.object_type = $1 AND r.object_id = o AND r.expires_at <= pg_catalog.statement_timestamp();
307
+ IF $6 IS NOT NULL AND $6 <> '' THEN PERFORM set_config('access.actor', $6, true); END IF;
308
+ -- Held already, it takes the end said now (none: it no longer ends) and is not given twice.
309
+ INSERT INTO ${S}.relationships AS r (object_type, object_id, relation, subject_type, subject_id, expires_at) VALUES ($1, o, $3, st, s, $7)
310
+ ON CONFLICT ON CONSTRAINT relationships_pkey DO UPDATE SET expires_at = excluded.expires_at
311
+ WHERE r.expires_at IS DISTINCT FROM excluded.expires_at
312
+ RETURNING (r.xmax = 0) INTO given;
313
+ PERFORM set_config('access.actor', coalesce(was, ''), true);
314
+ RETURN coalesce(given, false);
315
+ END`)}`,`CREATE OR REPLACE FUNCTION ${l}.canon(object_type text, object_id text) RETURNS text LANGUAGE sql STABLE ${re} AS ${M(`
316
+ SELECT CASE
317
+ ${[...p.values()].map(i=>`WHEN $1 = ${$(i.name)} THEN ${i.table&&i.family!=="text"?`(${Ie(i.family,"$2")})::text`:"$2"}`).join(`
318
+ `)}
319
+ ELSE $2 END`)}`,`CREATE OR REPLACE FUNCTION ${l}.revoke(object_type text, object_id text, relation text, subject_type text, subject_id text, actor text DEFAULT NULL) RETURNS boolean LANGUAGE plpgsql VOLATILE SECURITY DEFINER ${re} AS ${M(`
320
+ DECLARE held boolean; st text := $4; was text := current_setting('access.actor', true);
321
+ BEGIN
322
+ ${Ft}
323
+ IF (${jt("$1","$3","st","$5")}) IS NOT TRUE THEN PERFORM ${S}.refuse(${$(B.notTaken)}, ${Dt}); END IF;
324
+ IF $6 IS NOT NULL AND $6 <> '' THEN PERFORM set_config('access.actor', $6, true); END IF;
325
+ -- One whose time had passed was not held: its row goes all the same, and nothing was taken.
326
+ DELETE FROM ${S}.relationships r
327
+ WHERE r.object_type = $1 AND r.object_id = ${l}.canon($1, $2) AND r.relation = $3 AND r.subject_type = st
328
+ AND r.subject_id = CASE WHEN st = 'user' OR st = 'public' THEN $5 ELSE ${l}.canon($4, $5) END
329
+ RETURNING ${pe("r")} INTO held;
330
+ PERFORM set_config('access.actor', coalesce(was, ''), true);
331
+ RETURN coalesce(held, false);
332
+ END`)}`);let we=g.filter(i=>i.open);if(we.length>0&&s.visitor!==!0){let i=we[0];throw new x("needs_role",`${i.type}.${i.name} is open to the public, and this database has no role "${o.visitor}" for a request to take when nobody has signed in: create the role, or keep to user:* (every signed-in user)`)}let K=s.visitor===!0?O(o.visitor):null;E.push(`REVOKE ALL ON SCHEMA ${l} FROM PUBLIC, ${R}`,`GRANT USAGE ON SCHEMA ${l} TO ${R}`,`REVOKE ALL ON ALL TABLES IN SCHEMA ${l} FROM PUBLIC, ${R}`,...g.map(i=>`GRANT SELECT ON ${j(i.type,i.name)} TO ${R}`),`REVOKE ALL ON ALL FUNCTIONS IN SCHEMA ${l} FROM PUBLIC, ${R}`,`GRANT EXECUTE ON FUNCTION ${l}.can(text, text, text), ${l}.my_objects(text, text) TO ${R}`,`GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA ${l} TO ${k}`,...K===null?[]:[`REVOKE ALL ON SCHEMA ${l} FROM ${K}`,`REVOKE ALL ON ALL TABLES IN SCHEMA ${l} FROM ${K}`,`REVOKE ALL ON ALL FUNCTIONS IN SCHEMA ${l} FROM ${K}`,...we.length===0?[]:[`GRANT USAGE ON SCHEMA ${l} TO ${K}`,...we.map(i=>`GRANT SELECT ON ${j(i.type,i.name)} TO ${K}`),`GRANT EXECUTE ON FUNCTION ${l}.can(text, text, text), ${l}.my_objects(text, text) TO ${K}`]]);let Ee=[],ut=[],Xe=[],ge=[],de=(i,m,_,w,I)=>Ee.push(`CREATE OR REPLACE FUNCTION ${S}.${O(i)}(${m}) RETURNS ${_} LANGUAGE sql ${w} AS ${M(` SELECT ${l}.${O(i)}(${I}) `)}`);de("can","permission text, object_type text, object_id text","boolean","STABLE","$1, $2, $3"),de("my_objects","permission text, object_type text","SETOF text","STABLE","$1, $2"),de("check","subject text, permission text, object_type text, object_id text","boolean","VOLATILE","$1, $2, $3, $4"),de("objects","subject text, permission text, object_type text","SETOF text","VOLATILE","$1, $2, $3"),de("subjects","permission text, object_type text, object_id text","SETOF text","VOLATILE","$1, $2, $3"),de("open","permission text, object_type text, object_id text","text","VOLATILE","$1, $2, $3"),Ee.push(`DROP FUNCTION IF EXISTS ${S}.${O("grant")}(text, text, text, text, text, text)`),de("grant","object_type text, object_id text, relation text, subject_type text, subject_id text, actor text DEFAULT NULL, expires_at timestamptz DEFAULT NULL","boolean","VOLATILE","$1, $2, $3, $4, $5, $6, $7"),de("revoke","object_type text, object_id text, relation text, subject_type text, subject_id text, actor text DEFAULT NULL","boolean","VOLATILE","$1, $2, $3, $4, $5, $6");let Ut=`${S}.check(text, text, text, text), ${S}.objects(text, text, text), ${S}.subjects(text, text, text), ${S}.open(text, text, text), ${S}.grant(text, text, text, text, text, text, timestamptz), ${S}.revoke(text, text, text, text, text, text)`,Pt=`${S}.can(text, text, text), ${S}.my_objects(text, text), ${Ut}`;Ee.push(`REVOKE ALL ON ALL FUNCTIONS IN SCHEMA ${S} FROM PUBLIC`,`REVOKE ALL ON FUNCTION ${Pt} FROM ${R}`,`GRANT EXECUTE ON FUNCTION ${S}.can(text, text, text), ${S}.my_objects(text, text) TO ${R}`,`GRANT EXECUTE ON FUNCTION ${Ut} TO ${k}`,...K===null?[]:[`REVOKE ALL ON FUNCTION ${Pt} FROM ${K}`,...we.length===0?[]:[`GRANT EXECUTE ON FUNCTION ${S}.can(text, text, text), ${S}.my_objects(text, text) TO ${K}`]]);for(let i of g)s.aliases?.some(m=>m.name===i.view&&m.type!==i.idType)&&Ee.push(`DROP VIEW ${S}.${O(i.view)}`),Ee.push(`CREATE OR REPLACE VIEW ${S}.${O(i.view)} WITH (security_barrier = true) AS SELECT id FROM ${l}.${O(i.view)}`,`REVOKE ALL ON ${S}.${O(i.view)} FROM PUBLIC, ${R}`,`GRANT SELECT ON ${S}.${O(i.view)} TO ${R}`,...K===null?[]:[`REVOKE ALL ON ${S}.${O(i.view)} FROM ${K}`,...i.open?[`GRANT SELECT ON ${S}.${O(i.view)} TO ${K}`]:[]]);let Gt=[],Ht=[];for(let i of p.values()){if(!i.table)continue;let m=i.table;Gt.push({type:i.name,schema:m.schema,name:m.name,key:m.key});let _=`${m.schema}.${m.name}`;if(ut.push(`DO $guard$
333
+ DECLARE early text;
334
+ BEGIN
335
+ IF EXISTS (SELECT 1 FROM pg_catalog.pg_trigger g JOIN pg_catalog.pg_proc p ON p.oid = g.tgfoid JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
336
+ WHERE g.tgrelid = ${$(m.sql)}::pg_catalog.regclass AND NOT g.tgisinternal AND g.tgname IN (${me.map(w=>$(w)).join(", ")}) AND n.nspname <> ${$(ee)}) THEN
337
+ RAISE EXCEPTION '% has a trigger of its own under a name access'' takes (${me.join(", ")}): rename it', ${$(_)};
338
+ END IF;
339
+ ${bn(m.sql,_)}
340
+ END $guard$`,...me.map(w=>`DROP TRIGGER IF EXISTS ${O(w)} ON ${m.sql}`),`CREATE TRIGGER ${O("!access_fresh")} AFTER INSERT ON ${m.sql} FOR EACH ROW EXECUTE FUNCTION ${S}.fresh_objects(${$(i.name)}, ${$(m.key)})`,`CREATE TRIGGER ${O("!access_forget")} AFTER DELETE ON ${m.sql} FOR EACH ROW EXECUTE FUNCTION ${S}.forget_object(${$(i.name)}, ${$(m.key)})`,`CREATE TRIGGER ${O("!access_move")} AFTER UPDATE ON ${m.sql} FOR EACH ROW WHEN (OLD.${O(m.key)} IS DISTINCT FROM NEW.${O(m.key)}) EXECUTE FUNCTION ${S}.move_object(${$(i.name)}, ${$(m.key)})`,`CREATE TRIGGER ${O("!access_empty")} AFTER TRUNCATE ON ${m.sql} FOR EACH STATEMENT EXECUTE FUNCTION ${S}.forget_all(${$(i.name)})`,...me.map(w=>`ALTER TABLE ${m.sql} ENABLE TRIGGER ${O(w)}`)),!(!r||i.model.rows.length===0)){Xe.push(`ALTER TABLE ${m.sql} ENABLE ROW LEVEL SECURITY`);for(let w of i.model.rows){let I=`access_${w.command}`,T=Bt(i.name,w.name),D=w.command==="insert"?"":` USING (${T})`,z=w.command==="insert"||w.command==="update"?` WITH CHECK (${T})`:"";Xe.push(`DO $guard$
341
+ BEGIN
342
+ IF EXISTS (SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = ${$(m.sql)}::pg_catalog.regclass AND p.polname = ${$(I)}
343
+ AND pg_catalog.obj_description(p.oid, 'pg_policy') IS DISTINCT FROM ${$(Ce)}) THEN
344
+ RAISE EXCEPTION '% has a policy of its own named % \u2014 the name a rows rule of the access schema takes: rename it', ${$(_)}, ${$(I)};
345
+ END IF;
346
+ END $guard$`,`DROP POLICY IF EXISTS ${O(I)} ON ${m.sql}`,`CREATE POLICY ${O(I)} ON ${m.sql} FOR ${w.command.toUpperCase()} TO ${O(o.authenticated)}${K!==null&&t.open(i.name,w.name)?`, ${K}`:""}${D}${z}`,`COMMENT ON POLICY ${O(I)} ON ${m.sql} IS ${$(Ce)}`),Ht.push({schema:m.schema,table:m.name,name:I,command:w.command});for(let V of pt(i.name,w.name))a.add(V),t.open(i.name,w.name)&&u.add(V);if(t.open(i.name,w.name))for(let V of qt(i.name,w.name))f.add(V)}}}ge.push(`REVOKE ALL ON ALL TABLES IN SCHEMA ${l} FROM ${R}`,...g.map(i=>`GRANT SELECT ON ${j(i.type,i.name)} TO ${R}`));for(let i of new Set([...a,...(s.policies??[]).flatMap(m=>pt(m.type,m.name))]))ge.push(`GRANT SELECT ON ${l}.${O(i)} TO ${O(o.authenticated)}`);if(K!==null){ge.push(`REVOKE ALL ON ALL TABLES IN SCHEMA ${l} FROM ${K}`,...we.map(i=>`GRANT SELECT ON ${j(i.type,i.name)} TO ${K}`));for(let i of s.policies??[])if(t.open(i.type,i.name)){for(let m of pt(i.type,i.name))u.add(m);for(let m of qt(i.type,i.name))f.add(m)}for(let i of u)ge.push(`GRANT SELECT ON ${l}.${O(i)} TO ${K}`);for(let i of f)ge.push(`GRANT SELECT ON ${i} TO ${K}`)}let Ye=fn("sha256").update(JSON.stringify({engine:Pe,roles:o,sql:[...nt(o),...E,...Ee.filter(i=>!i.startsWith("DROP VIEW ")),...ut,...Xe,...ge].map(i=>i.replaceAll(c,`${ee}_`))})).digest("hex").slice(0,12),Kt=`${ee}_${Ye}`,Wt=[`UPDATE ${S}.schemas SET active = false WHERE active AND digest <> ${$(Ye)}`,`INSERT INTO ${S}.schemas (digest, text, engine, active) VALUES (${$(Ye)}, ${$(n)}, ${$(Pe)}, true)
347
+ ON CONFLICT (digest) DO UPDATE SET active = true, text = excluded.text, engine = excluded.engine, applied_at = now(), applied_by = session_user`],he=i=>i.replaceAll(c,Kt),Cn=g.filter(i=>P(i.type).table).map(i=>({type:i.type,name:i.name,sql:he(Bt(i.type,i.name))})),De={watch:ut.map(he),open:ge.map(he),rows:Xe.map(he),point:Ee.map(he),record:Wt};return{digest:Ye,schema:Kt,build:E.map(he),...De,activate:[...De.point,...De.watch,...De.rows,...De.open,...Wt],recheck:[...Ln(),...kn()],tables:Gt,names:g,policies:Ht,predicates:Cn};function In(i){let m=[...[...p.values()].flatMap(T=>(r&&T.table?T.model.rows:[]).map(D=>({type:T.name,command:D.command,using:D.command==="insert"?null:[D.name],check:D.command==="insert"||D.command==="update"?[D.name]:null}))),...s.guards??[]],_=(T,D)=>T.command===D||T.command==="all",w=T=>T.check??(T.command==="insert"?[]:T.using??[]),I=[];for(let T of p.values()){if(!T.table)continue;let D=m.filter(F=>F.type===T.name);if(D.length===0)continue;let z=D.filter(F=>_(F,"select")).flatMap(F=>F.using??[]),V=[["a SELECT",z],["an INSERT",[...D.filter(F=>_(F,"insert")).flatMap(w),...z]],["an UPDATE",[...D.filter(F=>_(F,"update")).flatMap(F=>[...F.using??[],...w(F)]),...z]],["a DELETE",[...D.filter(F=>_(F,"delete")).flatMap(F=>F.using??[]),...z]],["an INSERT \u2026 ON CONFLICT DO UPDATE",[...D.filter(F=>_(F,"insert")).flatMap(w),...D.filter(F=>_(F,"update")).flatMap(F=>[...F.using??[],...w(F)])]]];for(let[F,Fe]of V){let $e=new Map;for(let ie of Fe){let ye=i.get(`${T.name}.${ie}`);ye!==void 0&&$e.set(ye,{what:`${T.name}.${ie}`,n:($e.get(ye)?.n??0)+1})}if([...$e.values()].reduce((ie,ye)=>ie+ye.n,0)<2)continue;let xe=ie=>[...$e].map(([ye,jn])=>`${jn.n} * ${ie}[${ye}]`).join(" + "),Me=`${F} of ${T.table.schema}.${T.table.name} plans ${[...$e.values()].map(ie=>`${ie.what} ${ie.n===1?"once":`${ie.n} times`}`).join(" and ")}`;I.push(`
348
+ IF (${xe("kbs")}) > ${Ne} OR (${xe("mss")}) > ${Ke} THEN
349
+ RAISE EXCEPTION USING ERRCODE = '54000', MESSAGE = pg_catalog.format('access: %s \u2014 the rows it reads, its USING and its WITH CHECK: %s MB and %s ms to plan, for every such statement; at most ${Ne/1024} MB and ${Ke} ms', ${$(Me)}, round((${xe("kbs")}) / 1024), round(${xe("mss")}));
350
+ END IF;`)}}return I.join("")}function Ln(){let i=[...p.values()].filter(m=>m.table);return i.length===0?[]:[`DO $early$
351
+ DECLARE early text;
352
+ BEGIN
353
+ ${i.map(m=>bn(m.table.sql,`${m.table.schema}.${m.table.name}`)).join(`
354
+ `)}
355
+ END $early$`]}function kn(){if(g.length===0)return[];let i={int:"1",uuid:"00000000-0000-0000-0000-000000000001",text:"1"},m=g.map(T=>({what:`${T.type}.${T.name}`,view:he(j(T.type,T.name)),key:P(T.type).table?i[P(T.type).family]:i.text,size:Math.max(1,t.planned(T.type,T.name))})).sort((T,D)=>T.size-D.size),_=T=>`ARRAY[${T.join(", ")}]`,w=new Map(m.map((T,D)=>[T.what,D+1])),I=In(w);return[`DO $measure$
356
+ DECLARE
357
+ whats text[] := ${_(m.map(T=>$(T.what)))};
358
+ views text[] := ${_(m.map(T=>$(T.view)))};
359
+ keys text[] := ${_(m.map(T=>$(T.key)))};
360
+ sizes int[] := ${_(m.map(T=>String(T.size)))};
361
+ memory boolean := pg_catalog.current_setting('server_version_num')::int >= 170000;
362
+ per numeric := 0;
363
+ p json; kb numeric; ms numeric;
364
+ kbs numeric[] := '{}'; mss numeric[] := '{}';
365
+ BEGIN
366
+ FOR i IN 1 .. pg_catalog.array_length(views, 1) LOOP
367
+ IF per * sizes[i] > ${2*Ne} THEN
368
+ RAISE EXCEPTION USING ERRCODE = '54000', MESSAGE = pg_catalog.format('access: %s would take the database about %s MB to plan, for every statement it guards (as its other names show); at most ${Ne/1024} MB. What its tables carry is planned with it \u2014 their indexes, a partial index''s predicate, an index''s expressions, their statistics \u2014 and the indexes of access.relationships', whats[i], round(per * sizes[i] / 1024));
369
+ END IF;
370
+ ms := NULL;
371
+ -- The time, at its best of three: a database busy with other work is slower, not the schema.
372
+ FOR t IN 1 .. 3 LOOP
373
+ EXECUTE pg_catalog.format('EXPLAIN (%sSUMMARY, FORMAT JSON) SELECT id FROM %s WHERE id = %L', CASE WHEN memory THEN 'MEMORY, ' ELSE '' END, views[i], keys[i]) INTO p;
374
+ kb := coalesce((p -> 0 -> 'Planning' ->> 'Memory Used')::numeric, 0);
375
+ ms := least(coalesce(ms, 'Infinity'::numeric), (p -> 0 ->> 'Planning Time')::numeric);
376
+ EXIT WHEN ms <= ${Ke} OR kb > ${Ne};
377
+ END LOOP;
378
+ IF kb > ${Ne} OR ms > ${Ke} THEN
379
+ RAISE EXCEPTION USING ERRCODE = '54000', MESSAGE = pg_catalog.format('access: %s takes the database %s MB and %s ms to plan, for every statement it guards; at most ${Ne/1024} MB and ${Ke} ms. What its tables carry is planned with it \u2014 their indexes, a partial index''s predicate, an index''s expressions, their statistics \u2014 and the indexes of access.relationships', whats[i], round(kb / 1024), round(ms));
380
+ END IF;
381
+ per := greatest(per, kb / sizes[i]);
382
+ kbs[i] := kb;
383
+ mss[i] := ms;
384
+ END LOOP;${I}
385
+ END $measure$`]}function Bt(i,m){let _=P(i),w=_.table,I={col:T=>`${O(w.name)}.${O(T)}`,key:`${O(w.name)}.${O(w.key)}`};return Z(_,{op:"ref",name:m},I)}function qt(i,m){let _=P(i),w=I=>{if("parts"in I)return I.parts.flatMap(w);if(I.op==="exclude")return[...w(I.base),...w(I.minus)];if(I.op==="ref"){let D=_.model.permissions.get(I.name);return D?w(D.expr):[]}let T=_.model.relations.get(I.relation);return T.kind==="column"?[j(T.subject,I.name)]:[]};return w({op:"ref",name:m})}function pt(i,m){let _=P(i),w=I=>{if("parts"in I)return I.parts.flatMap(w);if(I.op==="exclude")return[...w(I.base),...w(I.minus)];if(I.op==="ref"){let T=_.model.permissions.get(I.name);return T?w(T.expr):[]}return _.model.relations.get(I.relation).kind==="stored"?[G(_.name,I.relation,I.name)]:[]};return w({op:"ref",name:m})}}function ts(t){let e=[];for(let n of t.types.values())for(let s of n.relations.values())if(s.kind!=="stored"){s.kind==="column"&&e.push({type:n.name,column:s.column});for(let o of Tt(s.where))e.push({type:n.name,column:o})}return e}var lo=`^${ee}_[0-9a-f]{12}$`;function ss(t){return[`DO $guard$
386
+ DECLARE held text;
387
+ BEGIN
388
+ SELECT string_agg(DISTINCT pg_catalog.pg_describe_object(d.classid, d.objid, d.objsubid), ', ') INTO held
389
+ FROM pg_catalog.pg_depend d
390
+ JOIN pg_catalog.pg_class c ON d.refclassid = 'pg_catalog.pg_class'::regclass AND d.refobjid = c.oid
391
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace AND n.nspname = ${$(t)}
392
+ WHERE d.deptype = 'n'
393
+ AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_rewrite w JOIN pg_catalog.pg_class v ON v.oid = w.ev_class JOIN pg_catalog.pg_namespace vn ON vn.oid = v.relnamespace
394
+ WHERE d.classid = 'pg_catalog.pg_rewrite'::regclass AND d.objid = w.oid AND vn.nspname = ${$(t)});
395
+ IF held IS NOT NULL THEN
396
+ RAISE EXCEPTION 'the compiled schema % is still read by: % \u2014 these must read access.* instead', ${$(t)}, held;
397
+ END IF;
398
+ END $guard$`,`DROP SCHEMA IF EXISTS ${O(t)} CASCADE`]}function os(){let t=O(ee);return[`DROP FUNCTION IF EXISTS ${t}.can(text, text, text), ${t}.my_objects(text, text), ${t}.check(text, text, text, text), ${t}.objects(text, text, text), ${t}.subjects(text, text, text), ${t}.open(text, text, text), ${t}.grant(text, text, text, text, text, text), ${t}.grant(text, text, text, text, text, text, timestamptz), ${t}.revoke(text, text, text, text, text, text)`,`UPDATE ${t}.schemas SET active = false WHERE active`]}var rs=/^-?[0-9]{1,18}$/,is=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;function fe(t,e){return t==="text"?e:t==="uuid"?is.test(e)?e.toLowerCase():null:t==="int"&&rs.test(e)?BigInt(e).toString():null}function Te(t,e){return e===null?null:t==="int"?typeof e=="bigint"?e.toString():typeof e=="number"&&Number.isInteger(e)?BigInt(e).toString():null:t==="uuid"?typeof e=="string"?fe("uuid",e):null:t==="text"&&typeof e=="string"?e:null}var as=/^(-?)([0-9]+)(?:\.([0-9]+))?$/;function Nn(t){let e=as.exec(t);if(!e)return null;let n=e[3]??"";return{digits:BigInt(`${e[1]}${e[2]}${n}`),scale:n.length}}function It(t,e){let n=t.digits*10n**BigInt(e.scale),s=e.digits*10n**BigInt(t.scale);return n<s?-1:n>s?1:0}var cs=t=>t.t==="string"?`'${t.v}'`:String(t.v),We=(t,e,n)=>new Error(`column "${t}" is ${e}: a condition cannot compare it with ${cs(n)}`),rt=(t,e,n)=>new Error(`column "${t}" is ${e}: ${String(n)} is no value of it`);function Le(t,e){return Object.hasOwn(t,e)?t[e]??null:null}function Tn(t,e,n,s){if(s.t!=="number")throw We(e,t,s);let o=Nn(s.v);if(o===null)throw We(e,t,s);if(typeof n=="bigint")return It({digits:n,scale:0},o);if(typeof n=="number"&&Number.isInteger(n))return It({digits:BigInt(n),scale:0},o);if(typeof n=="number"&&Number.isFinite(n)){let r=Number(s.v);return n<r?-1:n>r?1:0}if(typeof n=="string"&&t==="numeric"){let r=Nn(n);if(r!==null)return It(r,o)}throw rt(e,t,n)}function Rn(t,e,n,s){if(t==="int"||t==="numeric")return Tn(t,e,n,s)===0;if(t==="bool"){if(s.t!=="boolean")throw We(e,t,s);if(typeof n!="boolean")throw rt(e,t,n);return n===s.v}if(s.t!=="string")throw We(e,t,s);if(typeof n!="string")throw rt(e,t,n);if(t==="text")return n===s.v;let o=fe("uuid",n),r=fe("uuid",s.v);if(o===null)throw rt(e,t,n);if(r===null)throw We(e,t,s);return o===r}function _n(t,e){let n=e.now??Date.now(),s=e.relationships.filter(a=>a.expiresAt===void 0||a.expiresAt===null||a.expiresAt>n);function o(a){let u=t.types.get(a);if(!u)throw new Error(`the schema has no type "${a}"`);return u}function r(a,u){if(!a.relations.has(u)&&!a.permissions.has(u))throw new Error(`type ${a.name} has no relation or permission "${u}"`)}function p(a){let u=e.tables.get(a.name);if(!u)throw new Error(`the world has no table for type ${a.name}`);return u}function c(a,u){let f=p(a).shape.columns;if(!Object.hasOwn(f,u))throw new Error(`the world does not say how column "${u}" of type ${a.name}'s table compares`);return f[u]}function l(a,u){let f=p(a).shape.key;return Te(c(a,f),Le(u,f))}function R(a,u){return a.table?p(a).rows.filter(f=>l(a,f)===u):[]}function k(a,u,f){if("parts"in a){let C=a.parts.map(q=>k(q,u,f));return a.op==="and"?C.includes(!1)?!1:C.includes(null)?null:!0:C.includes(!0)?!0:C.includes(null)?null:!1}if(a.op==="not"){let C=k(a.part,u,f);return C===null?null:!C}let h=c(u,a.column),N=Le(f,a.column);if(a.op==="null")return N===null!==a.negated;if(N===null)return null;if(a.op==="in")return a.values.map(C=>Rn(h,a.column,N,C)).includes(!0);if(h==="int"||h==="numeric"){let C=Tn(h,a.column,N,a.value);return a.cmp==="="?C===0:a.cmp==="!="?C!==0:a.cmp==="<"?C<0:a.cmp==="<="?C<=0:a.cmp===">"?C>0:C>=0}if(a.cmp!=="="&&a.cmp!=="!=")throw new Error(`column "${a.column}" is ${h}: "${a.cmp}" does not compare it`);let L=Rn(h,a.column,N,a.value);return a.cmp==="="?L:!L}function v(a,u,f){return Le(u,f.column)===null?!1:f.where===null||k(f.where,a,u)===!0}function U(a,u,f,h){return h.subject!==Q&&a===null?!1:R(u,f).some(N=>k(h.where,u,N)===!0)}function H(a,u,f,h){if(!Oe(h))return!1;if(h.kind==="row")return U(a,u,f,h);if(h.kind==="stored"){let C=s.filter(q=>q.objectType===u.name&&q.objectId===f&&q.relation===h.name);return h.subjects.includes(Q)&&C.some(q=>q.subjectType===Q&&q.subjectId===le)?!0:a===null?!1:h.subjects.includes(J)&&C.some(q=>q.subjectType===X&&q.subjectId===le)?!0:a!==le&&h.subjects.includes(X)&&C.some(q=>q.subjectType===X&&q.subjectId===a)}if(a===null||a===le)return!1;let N=c(u,h.column),L=fe(N,a);return R(u,f).some(C=>v(u,C,h)&&L!==null&&L===Te(N,Le(C,h.column)))}function y(a,u,f){if(f.kind==="stored"){let L=ce(f);return s.filter(C=>C.objectType===a.name&&C.objectId===u&&C.relation===f.name&&L.includes(C.subjectType)).map(C=>({type:C.subjectType,id:C.subjectId}))}if(f.kind==="row"||f.subject===X)return[];let h=c(a,f.column),N=[];for(let L of R(a,u)){if(!v(a,L,f))continue;let C=Te(h,Le(L,f.column));C!==null&&N.push({type:f.subject,id:C})}return N}function j(a,u){let f=a.relations.get(u);if(!f)throw new Error(`type ${a.name} has no relation "${u}"`);return f}function G(a,u,f,h){return a.op==="ref"?Y(u,f,h,a.name):a.op==="arrow"?y(f,h,j(f,a.relation)).some(N=>Y(u,o(N.type),N.id,a.name)):a.op==="exclude"?G(a.base,u,f,h)&&!G(a.minus,u,f,h):a.op==="union"?a.parts.some(N=>G(N,u,f,h)):a.parts.every(N=>G(N,u,f,h))}function Y(a,u,f,h){if(a===""||u.table&&R(u,f).length===0)return!1;let N=u.relations.get(h);if(N)return H(a,u,f,N);let L=u.permissions.get(h);if(!L)throw new Error(`type ${u.name} has no relation or permission "${h}"`);return G(L.expr,a,u,f)}function P(a,u){return a.table?fe(c(a,p(a).shape.key),u):u}function te(a,u,f,h){let N=o(u);r(N,h);let L=P(N,f);return L===null?!1:Y(a,N,L,h)}function Z(a,u,f){let h=o(u);r(h,f);let N=h.table?p(h).rows.map(C=>l(h,C)):s.filter(C=>C.objectType===h.name).map(C=>C.objectId),L=new Set;for(let C of N)C!==null&&te(a,u,C,f)&&L.add(C);return[...L].sort()}function b(a,u,f){if(a.table&&R(a,u).length===0)return[];let h=a.relations.get(f);if(h)return d(a,u,h);let N=a.permissions.get(f);if(!N)throw new Error(`type ${a.name} has no relation or permission "${f}"`);return E(N.expr,a,u)}function d(a,u,f){if(f.kind==="stored")return f.subjects.includes(X)?s.filter(L=>L.objectType===a.name&&L.objectId===u&&L.relation===f.name&&L.subjectType===X&&L.subjectId!==le).map(L=>L.subjectId):[];if(f.kind==="row"||f.subject!==X)return[];let h=c(a,f.column),N=[];for(let L of R(a,u)){if(!v(a,L,f))continue;let C=Te(h,Le(L,f.column));C!==null&&N.push(C)}return N}function E(a,u,f){return a.op==="ref"?b(u,f,a.name):a.op==="arrow"?y(u,f,j(u,a.relation)).flatMap(h=>b(o(h.type),h.id,a.name)):a.op==="exclude"?[...E(a.base,u,f),...E(a.minus,u,f)]:a.parts.flatMap(h=>E(h,u,f))}function g(a,u,f){let h=o(a);r(h,f);let N=P(h,u);if(N===null)return[];let L=new Set;for(let C of b(h,N,f))C!==le&&te(C,a,u,f)&&L.add(C);return[...L].sort()}function A(a,u,f){let h=te(null,a,u,f),N=te(le,a,u,f);return h&&N?"public":N?"users":h?"visitors":null}return{check:te,objects:Z,subjects:g,open:A}}var it=/\{\{access:([a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)?)\}\}/g,wn=t=>`{{access:${t}}}`,ls=t=>t!==void 0&&t.includes("{{access:"),xn=/^[a-z][a-z0-9_]{0,39}(\.[a-z][a-z0-9_]{0,39})?$/,us={text:"text",uuid:"uuid",bigint:"int8",integer:"int4",smallint:"int2",boolean:"bool",numeric:"numeric",real:"float4","double precision":"float8","character varying":"varchar"};function ps(t){let e=new Set(t.enums.flatMap(n=>[`${n.schema}.${n.name}`,n.name]));return xt(t.tables.filter(n=>!n.ignored).map(n=>{let s={},o=[];for(let l of n.columns){if(l.ignored)continue;let R=l.type.replace(/\(.*\)$/,"");e.has(R.replaceAll('"',""))&&o.push(l.name),s[l.name]=us[R]??R}let r=l=>n.columns.some(R=>R.name===l&&!R.nullable&&!R.ignored),p=[...new Set([...n.primaryKey.length===1?n.primaryKey:[],...n.uniques.filter(l=>l.columns.length===1&&r(l.columns[0])).map(l=>l.columns[0])])],c=(n.primaryKey.length>0?1:0)+n.uniques.length+n.indexes.length;return{schema:n.schema,name:n.name,primaryKey:n.primaryKey,identifying:p,indexes:c,columns:s,enums:o}}))}function ds(t,e){let n=[];for(let s of t.tables){let o=e(s);if(o!==void 0)for(let r of s.policies)for(let p of`${r.using??""} ${r.withCheck??""}`.matchAll(it))n.push({type:o,name:p[1]})}return n}function ms(t,e){let n=[],s=o=>o===void 0?null:[...o.matchAll(it)].map(r=>r[1]);for(let o of t.tables){let r=e(o);if(r!==void 0)for(let p of o.policies)n.push({type:r,command:p.for,using:s(p.using),check:s(p.withCheck)})}return n}function fs(t,e,n){if(t.access===void 0)return null;let s=Se(Ae(t.access.text));for(let r of s.types.values())if(r.rows.length>0)throw new x("not_supported",`type ${r.name} has a rows rule: in an app whose tables Palgres makes, a table's row policy is written with the table \u2014 policy(...).using((p) => p.can('${r.rows[0]?.name}'))`);let o=r=>[...s.types.values()].find(p=>p.table?.schema===r.schema&&p.table.name===r.name)?.name;return ot(s,ps(t),t.access.text,{roles:e,visitor:!0,rows:!1,policies:ds(t,o),guards:ms(t,o),...n===void 0?{}:{aliases:n}})}function Ho(t,e,n){return fs({...t,access:{text:e,compiled:""}},n).digest}function Ko(t,e){let n=Se(Ae(e)),s=[];for(let o of n.types.values())for(let r of o.relations.values())if(r.kind==="stored")for(let p of r.subjects)s.push([o.name,r.name,p]);return{digest:t.digest,schema:t.schema,names:t.names,tables:t.tables,predicates:t.predicates,stored:s}}function Wo(t,e,n){let s=n?.tables.find(r=>r.schema===e.schema&&r.name===e.name)?.type;return!n||s===void 0?null:[...new Set(t.flatMap(r=>[...(r??"").matchAll(it)].map(p=>p[1])))].filter(r=>n.names.find(p=>p.type===s&&p.name===r)?.open!==!0).sort()}function Bo(t,e,n){if(!ls(t))return{sql:t};if(!n)return{refused:"the schema declares no access schema for it to read"};let s=n.tables.find(p=>p.schema===e.schema&&p.name===e.name)?.type;if(s===void 0)return{refused:`no type of the access schema names the table ${e.schema}.${e.name}`};let o,r=t.replaceAll(it,(p,c)=>{let l=n.predicates.find(R=>R.type===s&&R.name===c);return l||(o=c),`(${l?.sql??"false"})`});return o!==void 0?{refused:`type ${s} of the access schema has no relation or permission "${o}" a subject can hold`}:{sql:r}}var se=class t{expr;constructor(e){this.expr=e}bin(e,n){return new t({kind:"binop",op:e,left:this.expr,right:Es(n)})}eq(e){return this.bin("eq",e)}neq(e){return this.bin("neq",e)}gt(e){return this.bin("gt",e)}gte(e){return this.bin("gte",e)}lt(e){return this.bin("lt",e)}lte(e){return this.bin("lte",e)}isNull(e=!1){return new t({kind:"isNull",expr:this.expr,negated:e})}and(...e){return new t({kind:"and",parts:[this.expr,...e.map(n=>n.expr)]})}or(...e){return new t({kind:"or",parts:[this.expr,...e.map(n=>n.expr)]})}not(){return new t({kind:"not",expr:this.expr})}};function Es(t){return t instanceof se?t.expr:{kind:"lit",value:t}}function je(t,e=0,n=""){let s=`pb_e${e}`;return{col:o=>new se(e===0?{kind:"col",name:o}:{kind:"col",name:o,alias:s}),auth:{uid:()=>new se({kind:"authUid"})},can:o=>{if(e!==0)throw new Error(`policy expression: can("${o}") is about the policy's own row \u2014 use it outside existsIn`);if(!xn.test(o))throw new Error(`policy expression: can("${o}") \u2014 a relation or a permission is lowercase letters, digits and underscores, with at most one dot (code.write)`);return new se({kind:"access",name:o})},lit:o=>new se({kind:"lit",value:o}),and:(...o)=>new se({kind:"and",parts:o.map(r=>r.expr)}),or:(...o)=>new se({kind:"or",parts:o.map(r=>r.expr)}),not:o=>new se({kind:"not",expr:o.expr}),existsIn:(o,r)=>{let p=o[at],c=je(Object.keys(p.columns),e+1,n),l={kind:"exists",table:p.name,alias:`pb_e${e+1}`,outer:n,predicate:r(c).expr};return Object.defineProperty(l,be,{value:p,enumerable:!1,configurable:!0}),new se(l)}}}function ne(t){return`"${t.replace(/"/g,'""')}"`}var qe=class{_def;constructor(e){this._def={name:e,command:"all",roles:["authenticated"],using:null,withCheck:null,permissive:!0}}for(e){return this._def.command=e,this}to(...e){return this._def.roles=e,this}using(e){return this._def.using=e instanceof se?e.expr:e,this}memberOf(e,n,s={}){if(this._def.using!==null)throw new Error(`policy(${this._def.name}).memberOf(): this policy already has a using() expression. Write one or the other \u2014 memberOf IS the using expression.`);let o=s.column??"id",r=s.userColumn??"user_id";return this._def.using=`${ne(o)} IN (SELECT ${ne(n)} FROM ${ne(e)} WHERE ${ne(r)} = (select auth.uid()))`,this}withCheck(e){return this._def.withCheck=e instanceof se?e.expr:e,this}withoutIndexes(){return this._def.indexes=!1,this}as(e){return this._def.permissive=e==="permissive",this}};function zo(t){return new qe(t)}function Be(t,e){switch(t.kind){case"exists":throw new Error(`check(${e}): \`existsIn(...)\` is a subquery and PostgreSQL forbids subqueries in a CHECK constraint \u2014 express a cross-table rule as a composite FOREIGN KEY (foreignKeys), or as a guard.`);case"access":throw new Error(`check(${e}): \`can("${t.name}")\` asks who the caller is, and a CHECK constraint is true of the row whoever writes it \u2014 say it in a policy (\`withCheck\`)`);case"authUid":throw new Error(`check(${e}): \`auth.uid()\` renders as a subquery \`(SELECT auth.uid())\` and PostgreSQL forbids subqueries in a CHECK constraint \u2014 a caller-dependent rule belongs in an RLS policy, not a CHECK.`);case"binop":Be(t.left,e),Be(t.right,e);return;case"and":case"or":for(let n of t.parts)Be(n,e);return;case"not":case"isNull":Be(t.expr,e);return;default:return}}var gs={eq:"=",neq:"<>",gt:">",gte:">=",lt:"<",lte:"<="};function On(t){if(t===null)return"NULL";if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number"){if(!Number.isFinite(t))throw new Error(`check(): ${t} is not an SQL number literal.`);return String(t)}return`'${t.replace(/'/g,"''")}'`}function ke(t,e){switch(t.kind){case"col":return ne(t.name);case"lit":return On(t.value);case"binop":{let n=gs[t.op];if(n===void 0)throw new Error(`check(${e}): \`${t.op}\` is not supported in a CHECK expression.`);return`(${ke(t.left,e)} ${n} ${ke(t.right,e)})`}case"and":case"or":{if(t.parts.length===0)return t.kind==="and"?"(true)":"(false)";let n=t.kind==="and"?" AND ":" OR ";return`(${t.parts.map(s=>ke(s,e)).join(n)})`}case"not":return`(NOT ${ke(t.expr,e)})`;case"isNull":return`(${ke(t.expr,e)} IS ${t.negated?"NOT NULL":"NULL"})`;default:{let n=t.kind;throw new Error(`check(${e}): a \`${n}\` node is not one a CHECK expression takes.`)}}}function hs(t,e){if(t.trim()==="")throw new Error("check(): the constraint's name cannot be empty \u2014 Palbase reconciles CHECKs by name.");return Be(e.expr,t),{name:t,expr:ke(e.expr,t)}}function Jo(t){if(t!==null)return typeof t=="string"?t:_e(t,"")}var $s={eq:"=",neq:"<>",gt:">",gte:">=",lt:"<",lte:"<="};function An(t){let e=t.indexOf(".");return e<0?`${ne("public")}.${ne(t)}`:`${ne(t.slice(0,e))}.${ne(t.slice(e+1))}`}function _e(t,e){switch(t.kind){case"col":return t.alias!==void 0?`${ne(t.alias)}.${ne(t.name)}`:e===""?ne(t.name):`${An(e)}.${ne(t.name)}`;case"authUid":return"(SELECT auth.uid())";case"access":return wn(t.name);case"lit":return On(t.value);case"binop":{let n=$s[t.op];if(n===void 0)throw new Error(`policy expression: \`${t.op}\` is not an operator a policy can use`);return`(${_e(t.left,e)} ${n} ${_e(t.right,e)})`}case"and":case"or":return t.parts.length===0?t.kind==="and"?"(true)":"(false)":`(${t.parts.map(n=>_e(n,e)).join(t.kind==="and"?" AND ":" OR ")})`;case"not":return`(NOT ${_e(t.expr,e)})`;case"isNull":return`(${_e(t.expr,e)} IS ${t.negated?"NOT NULL":"NULL"})`;case"exists":if(t.outer==="")throw new Error("policy expression: an existsIn carries no outer table \u2014 its correlation would collapse to x = x and filter nothing");return`EXISTS (SELECT 1 FROM ${An(t.table)} ${ne(t.alias)} WHERE (${_e(t.predicate,t.outer)}))`}}function Lt(t,e){return t===""||t==="public"?e:`${t}.${e}`}var ct=class{_def;constructor(e){if(e.trim()==="")throw new Error("index(name): an index's name cannot be empty \u2014 Palbase reconciles indexes by name.");this._def={name:e}}unique(){return this._def.unique=!0,this}on(...e){return this._def.columns=e.map(n=>{let s=n.expr;if(s.kind!=="col")throw new Error(`index(${this._def.name}).on(): takes column references only \u2014 for an expression, use onExpression("\u2026").`);return s.name}),this}onExpression(e){return this._def.expression=e,this}where(e){return this._def.where=e.expr,this}desc(){return this._def.sort="desc",this}asc(){return this._def.sort="asc",this}nulls(e){return this._def.nulls=e,this}include(e){return this._def.include=e,this}};function sr(t){return new ct(t)}function ys(t){return t instanceof qe?t._def:t}var at=Symbol.for("palbase.table.meta");function or(t,e){if(t.trim()==="")throw new Error("defineTable(name, \u2026): name must not be empty");let n=(e.policies?.(je(Object.keys(e.columns),0,t))??[]).map(ys),s=n.length>0||e.rls!==!1,o={};for(let[k,v]of Object.entries(e.columns)){let U=v;_s(t,k,U._def),Rs(t,k,U._def,e.columns);let H=Object.create(Object.getPrototypeOf(U));Object.defineProperty(H,"_def",{value:{...U._def},enumerable:!0,writable:!0}),o[k]=H}let r={name:t,columns:o,rls:s,policies:n};if(e.primaryKey!==void 0&&(r.primaryKey=[...e.primaryKey]),e.search!==void 0&&(r.search=bs(t,e.search,o,r.primaryKey)),e.unique!==void 0&&(r.unique=e.unique.map(k=>({name:k.name,columns:[...k.columns]}))),e.raw!==void 0&&e.raw.length>0){for(let k of e.raw)if(k.drop!==void 0)throw new Error(`defineTable(${JSON.stringify(t)}): raw ${JSON.stringify(k.name)} carries a drop, but a table-level raw() has no teardown \u2014 a drop is run only for a schema-level unit: defineSchema(name, { tables, raw: [raw(name, up, { drop })] })`);r.raw=e.raw.slice()}let p=typeof e.checks=="function"?e.checks(je(Object.keys(e.columns),0,t)):e.checks?.slice()??[];p.length>0&&(r.checks=p);let c=(e.indexes?.(je(Object.keys(e.columns),0,t))??[]).map(k=>k instanceof ct?k._def:k);c.length>0&&(r.indexes=c);let l=(e.foreignKeys?.(je(Object.keys(e.columns),0,t))??[]).map(zt);l.length>0&&(r.foreignKeys=l),e.ignored===!0&&(r.ignored=!0),Ts(t,r);for(let k of Object.values(o))k._def.ownerTable=r;let R={...o};return Object.defineProperty(R,at,{value:r,enumerable:!1}),R}function bs(t,e,n,s){if(e===null||typeof e!="object")throw new Error(`defineTable(${JSON.stringify(t)}): search is { from: [...columns], model } \u2014 got ${e===null?"null":typeof e}`);let o={from:Array.isArray(e.from)?[...e.from]:e.from,model:e.model,dimensions:e.dimensions??gt,metric:e.metric??"cosine",staleness:e.staleness??"null"},r=Object.entries(n).map(([c,l])=>({name:c,def:l._def})),p=ht(`defineTable(${JSON.stringify(t)})`,{columns:r.map(({name:c,def:l})=>({name:c,type:l.type==="sql"?l.sqlType??"sql":l.type,...l.ignored?{ignored:!0}:{},...l.generated?{generated:l.generated}:{}})),primaryKey:s??r.filter(({def:c})=>c.primaryKey===!0).map(({name:c})=>c)},o);if(p.length>0)throw new Error(p.join(`
399
+ `));return o}var kt=new WeakMap;function Ns(t,e){for(let n of Object.values(t))ws(n,`table "${n.name}"`,e);for(let n of Object.values(t))for(let[s,o]of Object.entries(n.columns)){let r=o._def;if(r.selfRefColumn!==void 0){if(!(r.selfRefColumn in n.columns))throw new Error(`table "${n.name}" column "${s}": selfReferences("${r.selfRefColumn}") \u2014 no such column on this table`);r.references={table:Lt(e,n.name),column:r.selfRefColumn};continue}if(r.referencesThunk===void 0)continue;let p=r.referencesThunk(),c=p?._def?.ownerTable;if(c===void 0)throw new Error(`table "${n.name}" column "${s}": references(() => \u2026) must point at a column of a table declared with defineTable(...)`);let l=Object.entries(c.columns).find(([,k])=>k._def===p._def)?.[0];if(l===void 0)throw new Error(`table "${n.name}" column "${s}": the referenced column was not found on table "${c.name}"`);let R=kt.get(c);if(R===void 0)throw new Error(`table "${n.name}" column "${s}": references(() => \u2026) points at table "${c.name}", which no defineSchema(...) has claimed yet \u2014 a foreign key cannot be written without its target's schema. Declare that table's schema first (one file per schema: db/public.ts, db/billing.ts \u2026, imported by this one).`);r.references={table:Lt(R,c.name),column:l}}}function Rs(t,e,n,s){if(n.encrypted===void 0)return;let o=`${e}_lookup`,r=n.defaultValue!==void 0||n.defaultSql!==void 0||n.defaultRandom===!0||n.defaultNow===!0?"it has a default \u2014 the database would write it in plain text; give the value in the write":n.fill!==void 0?".fillWith() is SQL over the row in plain text; give the value in the write":n.primaryKey===!0?"it is the primary key \u2014 a key the database matches rows by cannot be ciphertext; keep an id, and the encrypted value beside it":n.references!==void 0||n.referencesThunk!==void 0?"it references another table \u2014 a foreign key compares values the database cannot read":n.identity!==void 0||n.generated!==void 0?"the database makes its value":n.user!==void 0?"it holds a user's id, which the platform matches rows by":n.codec!==void 0||n.transform!==void 0?"it has a codec or a transform \u2014 encryption is its transform":n.unique===!0&&!n.encrypted.lookup?".unique() needs { lookup: true } \u2014 what equality is kept by is the lookup":o in s?`the table has a column "${o}" of its own, where the lookup is kept`:null;if(r!==null)throw new Error(`defineTable(${JSON.stringify(t)}): column "${e}" \u2014 .encrypted(): ${r}`)}function Ts(t,e){let n=o=>e.columns[o]?._def.encrypted,s=o=>{throw new Error(`defineTable(${JSON.stringify(t)}): ${o}`)};for(let o of e.primaryKey??[])n(o)&&s(`the primary key names "${o}", which is .encrypted() \u2014 keep an id, and the encrypted value beside it`);for(let o of e.unique??[])for(let r of o.columns){let p=n(r);p&&!p.lookup&&s(`unique ${JSON.stringify(o.name)} names "${r}", which is .encrypted() without { lookup: true } \u2014 what equality is kept by is the lookup`)}for(let o of e.indexes??[]){let r=JSON.stringify([o.keys??[],o.columns??[]]);for(let p of Object.keys(e.columns))n(p)&&r.includes(JSON.stringify(p))&&s(`index ${JSON.stringify(o.name)} names "${p}", which is .encrypted() \u2014 an index of ciphertext orders nothing; equality is found by { lookup: true }, which is indexed`)}for(let o of e.search?.from??[])n(o)&&s(`search reads "${o}", which is .encrypted() \u2014 its text is not in the database to embed`)}function _s(t,e,n){if(n.fill===void 0)return;let s=n.defaultValue!==void 0||n.defaultRandom===!0||n.defaultNow===!0||n.defaultSql!==void 0?"the column has a default \u2014 the default already fills every row; keep one of the two":null;if(s!==null)throw new Error(`defineTable(${JSON.stringify(t)}): column "${e}" \u2014 .fillWith(): ${s}`)}function rr(t,e){if(typeof t!="string")throw new Error(`defineSchema(...) takes the schema NAME first: defineSchema("public", { tables: [todos, lists] }). The one-argument form defineSchema({ tables: { \u2026 } }) is gone \u2014 a schema that does not say its own name cannot be told apart from another schema's table of the same name, which is what a cross-schema foreign key has to do. Migrate db/public.ts (one file per schema: db/public.ts, db/billing.ts \u2026): name the schema, and lift each table key onto the table itself with defineTable("todos", { columns: { \u2026 } }), then list the tables in the array.`);if(t.trim()==="")throw new Error("defineSchema(name, \u2026): name must not be empty");let n={};for(let p of e.tables){let c=p[at];if(n[c.name]!==void 0)throw new Error(`defineSchema("${t}"): two tables declare the name "${c.name}" \u2014 table names must be unique within a schema`);n[c.name]=c,kt.set(c,t)}Ns(n,t);let s=[...new Set(e.extensions??[])],o=(e.raw??[]).slice(),r=new Set;for(let p of o){if(typeof p.name!="string"||p.name.trim()==="")throw new Error(`defineSchema("${t}"): a raw unit needs a name`);if(r.has(p.name))throw new Error(`defineSchema("${t}"): two raw units are named "${p.name}" \u2014 a unit's name identifies it`);r.add(p.name)}return{name:t,tables:n,extensions:s,raw:o}}function ws(t,e,n){let s=(p,c)=>{let l=p[be];if(l===void 0)return;let R;try{R=typeof l=="function"?l():l}catch(U){throw new Error(`${e}: ${c} names its target through a callback that failed: ${U.message}`)}if(R==null||typeof R.name!="string")throw new Error(`${e}: ${c}'s callback does not answer a table \u2014 write references(() => otherTable, \u2026)`);let k=kt.get(R);if(k===void 0)throw new Error(`${e}: ${c} points at table "${R.name}", which no defineSchema(...) has claimed yet \u2014 a cross-table reference cannot be written without its target's schema. Declare that table's schema first (one file per schema: db/public.ts, db/billing.ts \u2026, imported by this one).`);let v=Lt(k,R.name);p.refTable!==void 0&&(p.refTable=v),p.table!==void 0&&(p.table=v)};for(let p of t.foreignKeys??[])s(p,`foreignKey("${p.name}")`);let o=`${n}.${t.name}`,r=(p,c)=>{if(!(p==null||typeof p=="string"))switch(p.kind){case"exists":s(p,c),p.table.includes(".")||(p.table=`public.${p.table}`),p.outer=o,r(p.predicate,c);return;case"binop":r(p.left,c),r(p.right,c);return;case"and":case"or":for(let l of p.parts)r(l,c);return;case"not":case"isNull":r(p.expr,c);return;default:return}};for(let p of t.policies)r(p.using,`policy("${p.name}")`),r(p.withCheck,`policy("${p.name}")`);for(let p of t.indexes??[])r(p.where,`index("${p.name}")`)}export{As as a,Os as b,Vt as c,Ss as d,ue as e,Et as f,Cs as g,Gn as h,ht as i,Is as j,Yt as k,Ls as l,ks as m,x as n,J as o,Q as p,Ae as q,X as r,le as s,Oe as t,Se as u,me as v,pn as w,dn as x,mn as y,He as z,nt as A,ts as B,ss as C,os as D,fe as E,_n as F,ls as G,fs as H,Ho as I,Ko as J,Wo as K,Bo as L,ze as M,Kn as N,Lt as O,ct as P,sr as Q,at as R,or as S,rr as T,se as U,je as V,qe as W,zo as X,hs as Y,Jo as Z};