@supabase/lite 0.7.1-next.6 → 0.7.1-next.7

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.
@@ -1,4 +1,4 @@
1
- import { I as IConnectionConfig, C as Connection } from '../Connection-Cm9fpZU3.js';
1
+ import { I as IConnectionConfig, C as Connection } from '../Connection-D9UUTsjg.js';
2
2
  import 'kysely';
3
3
 
4
4
  declare function createConnection<E extends IConnectionConfig = IConnectionConfig>(_config?: E): Promise<Connection>;
@@ -1,7 +1,7 @@
1
1
  import { PGliteOptions, PGlite } from '@electric-sql/pglite';
2
2
  export { PGlite } from '@electric-sql/pglite';
3
3
  import { I as IBasePostgresConnectionConfig, B as BasePostgresConnection } from '../BasePostgresConnection-xaPv2E6u.js';
4
- import { ConnectionMigrator, SchemaDiffResult, PlanResult, PlanStep } from '@supabase/lite';
4
+ import { ConnectionMigrator, MigrateScope, SchemaDiffResult, PlanResult, PlanStep } from '@supabase/lite';
5
5
  import 'kysely';
6
6
 
7
7
  declare class PostgresMigrator implements ConnectionMigrator {
@@ -9,13 +9,13 @@ declare class PostgresMigrator implements ConnectionMigrator {
9
9
  private readonly from;
10
10
  private readonly desiredSchema;
11
11
  constructor(from: PgliteConnection, desiredSchema: string);
12
- diff(): Promise<SchemaDiffResult>;
12
+ diff(scope?: MigrateScope): Promise<SchemaDiffResult>;
13
13
  migratePlan(planResult: PlanResult, opts?: {
14
14
  force?: boolean;
15
15
  }): Promise<void>;
16
16
  migrate(opts?: {
17
17
  force?: boolean;
18
- }): Promise<SchemaDiffResult>;
18
+ } & MigrateScope): Promise<SchemaDiffResult>;
19
19
  safeSortPlanSteps(steps: PlanStep[]): PlanStep[];
20
20
  }
21
21
 
@@ -14,7 +14,7 @@ var v=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t;}async acquireConnection(
14
14
  END IF;`).join("")}
15
15
  END $$;
16
16
  `}var K=C(new Set(O));function A(n,e){return n?n.quoted?n.value===e:n.value.toLowerCase()===e:false}function y(n){return n?.quoted?n.value:n?.value.toLowerCase()}function we(n,e){let t="",s=e+1;for(;s<n.length;){if(n[s]==='"'&&n[s+1]==='"'){t+='"',s+=2;continue}if(n[s]==='"')return {token:{value:t,quoted:true},end:s+1};t+=n[s],s++;}return {token:{value:t,quoted:true},end:s}}function Ae(n,e){let t=e+1;for(;t<n.length;){if(n[t]==="'"&&n[t+1]==="'"){t+=2;continue}if(n[t]==="'")return t+1;t++;}return t}function Re(n,e){let t=/^\$[A-Za-z_][A-Za-z0-9_]*\$|^\$\$/.exec(n.slice(e))?.[0];if(!t)return;let s=e+t.length,o=n.indexOf(t,s);return o===-1?n.length:o+t.length}function $(n){let e=[],t=0;for(;t<n.length;){let s=n[t],o=n[t+1];if(/\s/.test(s)){t++;continue}if(s==="-"&&o==="-"){for(t+=2;t<n.length&&n[t]!==`
17
- `;)t++;continue}if(s==="/"&&o==="*"){for(t+=2;t<n.length&&!(n[t]==="*"&&n[t+1]==="/");)t++;t=t<n.length?t+2:t;continue}if(s==="'"){t=Ae(n,t);continue}if(s==="$"){let a=Re(n,t);if(a!==void 0){t=a;continue}}if(s==='"'){let{token:a,end:c}=we(n,t);e.push(a),t=c;continue}if(s===","||s===";"){e.push({value:s,quoted:false}),t++;continue}if(/[A-Za-z_]/.test(s)){let a=t;for(t++;t<n.length&&/[A-Za-z0-9_$]/.test(n[t]);)t++;e.push({value:n.slice(a,t).toLowerCase(),quoted:false});continue}t++;}return e}function Q(n,e){let t=y(n[e]),s=y(n[e+1]);if((t==="create"||t==="alter")&&(s==="role"||s==="user"||s==="group"))return n[e+2]}function L(n){let e=new Set,t=$(n);for(let s=0;s<t.length;s++){if(y(t[s])!=="create")continue;let o=Q(t,s);for(let a of O)A(o,a)&&e.add(a);}return e}function P(n,e,t){let s=new Set([";","as","by","check","for","granted","in","on","option","using","where","with"]);for(let o=e;o<n.length;o++){let a=y(n[o]);if(!a||s.has(a))return;for(let c of O)A(n[o],c)&&t.add(c);}}function be(n){let e=[],t=[];for(let s of n){if(y(s)===";"){t.length>0&&e.push(t),t=[];continue}t.push(s);}return t.length>0&&e.push(t),e}function j(n,e){return n.some(t=>y(t)===e)}function Te(n){let e=new Set,t=be($(n));for(let s of t){let o=y(s[0]);for(let r=0;r<s.length;r++){let l=y(s[r]);l==="to"&&(j(s,"grant")||j(s,"policy")||y(s[r-1])==="owner")&&P(s,r+1,e),l==="from"&&o==="revoke"&&P(s,r+1,e);}let a=s.findIndex(r=>y(r)==="to"),c=s.findIndex(r=>y(r)==="on");o==="grant"&&a>1&&(c===-1||a<c)&&P(s,1,e);}return e}function F(n){let e=L(n);return new Set([...Te(n)].filter(t=>!e.has(t)))}function Y(n){let e=L(n);return new Set(O.filter(t=>!e.has(t)))}function V(n,e){let t=$(n);if(t.length===0)return false;let s=Q(t,0);if(s){for(let c of e)if(A(s,c))return true;return false}let o=y(t[0]),a=y(t[1]);if(o==="drop"&&(a==="role"||a==="user"||a==="group")){for(let c of t.slice(2))for(let r of e)if(A(c,r))return true}if(o==="comment"&&y(t[1])==="on"&&y(t[2])==="role"){for(let c of e)if(A(t[3],c))return true}return false}function M(n){let e=n.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("`")&&e.endsWith("`")||e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function Oe(n){let e=[],t="",s=0,o=null;for(let a=0;a<n.length;a++){let c=n[a];if(o){t+=c,c===o&&(o=null);continue}if(c==='"'||c==="`"||c==="'"){o=c,t+=c;continue}if(c==="("?s++:c===")"&&s>0&&s--,c===","&&s===0){e.push(t.trim()),t="";continue}t+=c;}return t.trim()&&e.push(t.trim()),e}function Ce(n){let e=n.match(/^(.*?)\s+as\s+(.+)$/i),t=e?e[1].trim():n.trim(),s=e?e[2].trim():void 0;if(!s){let c=n.match(/^(.+?)\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+))$/);c&&!/[()]/.test(c[1])&&(t=c[1].trim(),s=c[2].trim());}let o=t.split(".").map(M);if(o.length>2)return null;let a=o.at(-1);return !a||!/^[A-Za-z_][\w$]*$/.test(a)?null:{baseColumn:a,viewColumn:s?M(s):a}}function z(n){return !!(n&&/[A-Za-z0-9_$]/.test(n))}function Le(n){let e=/\bselect\b/i.exec(n);if(!e)return null;let t=0,s=null;for(let o=e.index+e[0].length;o<n.length;o++){let a=n[o];if(s){a===s&&(s=null);continue}if(a==='"'||a==="`"||a==="'"){s=a;continue}if(a==="("){t++;continue}if(a===")"&&t>0){t--;continue}if(t===0&&n.slice(o,o+4).toLowerCase()==="from"&&!z(n[o-1])&&!z(n[o+4]))return {selectList:n.slice(e.index+e[0].length,o).trim(),fromRest:n.slice(o+4).trim()}}return null}function Ie(n){let e=0,t=[];for(;e<n.length;){for(;/\s/.test(n[e]??"");)e++;let s=n[e],o="";if(s==='"'||s==="`"){let r=n.indexOf(s,e+1);if(r===-1)return null;o=n.slice(e,r+1),e=r+1;}else if(s==="["){let r=n.indexOf("]",e+1);if(r===-1)return null;o=n.slice(e,r+1),e=r+1;}else {let r=/^[A-Za-z_][\w$]*/.exec(n.slice(e));if(!r)return null;o=r[0],e+=o.length;}t.push(o);let a=n.slice(e),c=/^\s*\./.exec(a);if(!c)break;e+=c[0].length;}return t.length===0?null:{raw:t.join("."),rest:n.slice(e).trim()}}function X(n,e,t){let s=n.get(e)??[];s.includes(t)||s.push(t),n.set(e,s);}function xe(n,e){if(!n)return null;let t=Le(n);if(!t)return null;let s=Ie(t.fromRest);if(!s)return null;let{raw:o,rest:a}=s;if(/\b(join|union|intersect|except)\b/i.test(a))return null;let c=o.split(".").map(M).at(-1);if(!c)return null;let r=new Map,l=e.get(c)??new Set;for(let f of Oe(t.selectList)){let u=f.trim();if(u==="*"||u.endsWith(".*")){for(let d of l)X(r,d,d);continue}let p=Ce(f);p&&X(r,p.baseColumn,p.viewColumn);}return r.size===0?null:{baseTable:c,columns:r}}function ke(n,e){let t=new Map;for(let[s,o]of e){let a=[];for(let c of o){let r=n.get(c);if(r)for(let l of r)a.includes(l)||a.push(l);}a.length>0&&t.set(s,a);}return t}function Be(n){let e=new Map,t=new Map;for(let r of n.columns??[]){let l=t.get(r.table)??new Set;l.add(r.name),t.set(r.table,l);}let s=(r,l)=>{let f=e.get(r)??[];f.some(u=>u.name===l.name&&u.schema===l.schema)||f.push(l),e.set(r,f);};for(let r of n.tables??[]){if(r.type!=="table")continue;let l=t.get(r.name);l&&s(r.name,{name:r.name,schema:r.schema,columnByBaseColumn:new Map([...l].map(f=>[f,[f]]))});}let o=new Map;for(let r of n.views??[]){let l=xe(r.sql,t);if(!l)continue;let f=t.get(r.name);if(!f)continue;let u=new Map;for(let[d,h]of l.columns){let g=h.filter(_=>f.has(_));g.length>0&&u.set(d,g);}if(u.size===0)continue;let p={name:r.name,schema:r.schema,columnByBaseColumn:u,fromRelation:l.baseTable};o.set(r.name,p);}let a=16;function c(r,l,f){if(l>a)return null;let u=r.fromRelation;if(e.has(u))return {physicalBase:u,columnByBaseColumn:r.columnByBaseColumn};let p=o.get(u);if(!p||f.has(u))return null;f.add(u);let d=c(p,l+1,f);if(f.delete(u),!d)return null;let h=ke(r.columnByBaseColumn,d.columnByBaseColumn);return h.size===0?null:{physicalBase:d.physicalBase,columnByBaseColumn:h}}for(let r of o.values()){let l=c(r,0,new Set([r.name]));l&&s(l.physicalBase,{name:r.name,schema:r.schema,columnByBaseColumn:l.columnByBaseColumn});}return e}function Z(n){return `${n.foreign_key_group??""}:${n.table}.${n.column}->${n.ref_table}.${n.ref_column}`}function ve(n){let e=new Map;for(let t of n){let s=`${t.schema}.${t.table}.${t.foreign_key_name}.${t.ref_schema??""}.${t.ref_table}`,o=e.get(s);o?o.push(t):e.set(s,[t]);}return [...e.values()]}function De(n){let e=[[]];for(let t of n){let s=[];for(let o of e)for(let a of t)s.push([...o,a]);e=s;}return e}function Pe(n,e,t,s){let o=s.map(c=>c.childColumn).join(","),a=s.map(c=>c.parentColumn).join(",");return `${t}:${n.name}(${o})->${e.name}(${a})`}function ee(n){if(!n.foreign_keys?.length||!n.views?.length)return n;let e=Be(n),t=new Set(n.foreign_keys.map(Z)),s=[];for(let o of ve(n.foreign_keys)){let a=o[0],c=e.get(a.table)??[],r=e.get(a.ref_table)??[];for(let l of c)for(let f of r){if(l.schema!==f.schema)continue;let u=[];for(let p of o){let d=l.columnByBaseColumn.get(p.column)??[],h=f.columnByBaseColumn.get(p.ref_column)??[],g=d.flatMap(_=>h.map(S=>({fk:p,childColumn:_,parentColumn:S})));if(g.length===0){u.length=0;break}u.push(g);}for(let p of De(u)){let h=l.name===a.table&&f.name===a.ref_table&&p.every(g=>g.childColumn===g.fk.column&&g.parentColumn===g.fk.ref_column)?void 0:Pe(l,f,a.foreign_key_name,p);for(let g of p){let _={...g.fk,table:l.name,column:g.childColumn,schema:l.schema,ref_table:f.name,ref_column:g.parentColumn,ref_schema:f.schema,foreign_key_group:h},S=Z(_);t.has(S)||(t.add(S),s.push(_));}}}}return s.length?{...n,foreign_keys:[...n.foreign_keys,...s]}:n}var R="anon, authenticated, service_role",Me=new Set(["anon","authenticated","service_role"]);function te(n){return `"${n.replace(/"/g,'""')}"`}var N=class extends Error{constructor(t){super("Force rollback");this.result=t;}},I=class extends Connection{dialect="postgres";harnessHoldingOuterTx=false;constructor(e){super({...e,baseSchema:`
17
+ `;)t++;continue}if(s==="/"&&o==="*"){for(t+=2;t<n.length&&!(n[t]==="*"&&n[t+1]==="/");)t++;t=t<n.length?t+2:t;continue}if(s==="'"){t=Ae(n,t);continue}if(s==="$"){let a=Re(n,t);if(a!==void 0){t=a;continue}}if(s==='"'){let{token:a,end:c}=we(n,t);e.push(a),t=c;continue}if(s===","||s===";"){e.push({value:s,quoted:false}),t++;continue}if(/[A-Za-z_]/.test(s)){let a=t;for(t++;t<n.length&&/[A-Za-z0-9_$]/.test(n[t]);)t++;e.push({value:n.slice(a,t).toLowerCase(),quoted:false});continue}t++;}return e}function Q(n,e){let t=y(n[e]),s=y(n[e+1]);if((t==="create"||t==="alter")&&(s==="role"||s==="user"||s==="group"))return n[e+2]}function L(n){let e=new Set,t=$(n);for(let s=0;s<t.length;s++){if(y(t[s])!=="create")continue;let o=Q(t,s);for(let a of O)A(o,a)&&e.add(a);}return e}function P(n,e,t){let s=new Set([";","as","by","check","for","granted","in","on","option","using","where","with"]);for(let o=e;o<n.length;o++){let a=y(n[o]);if(!a||s.has(a))return;for(let c of O)A(n[o],c)&&t.add(c);}}function be(n){let e=[],t=[];for(let s of n){if(y(s)===";"){t.length>0&&e.push(t),t=[];continue}t.push(s);}return t.length>0&&e.push(t),e}function j(n,e){return n.some(t=>y(t)===e)}function Te(n){let e=new Set,t=be($(n));for(let s of t){let o=y(s[0]);for(let r=0;r<s.length;r++){let l=y(s[r]);l==="to"&&(j(s,"grant")||j(s,"policy")||y(s[r-1])==="owner")&&P(s,r+1,e),l==="from"&&o==="revoke"&&P(s,r+1,e);}let a=s.findIndex(r=>y(r)==="to"),c=s.findIndex(r=>y(r)==="on");o==="grant"&&a>1&&(c===-1||a<c)&&P(s,1,e);}return e}function F(n){let e=L(n);return new Set([...Te(n)].filter(t=>!e.has(t)))}function Y(n){let e=L(n);return new Set(O.filter(t=>!e.has(t)))}function V(n,e){let t=$(n);if(t.length===0)return false;let s=Q(t,0);if(s){for(let c of e)if(A(s,c))return true;return false}let o=y(t[0]),a=y(t[1]);if(o==="drop"&&(a==="role"||a==="user"||a==="group")){for(let c of t.slice(2))for(let r of e)if(A(c,r))return true}if(o==="comment"&&y(t[1])==="on"&&y(t[2])==="role"){for(let c of e)if(A(t[3],c))return true}return false}function M(n){let e=n.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("`")&&e.endsWith("`")||e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function Oe(n){let e=[],t="",s=0,o=null;for(let a=0;a<n.length;a++){let c=n[a];if(o){t+=c,c===o&&(o=null);continue}if(c==='"'||c==="`"||c==="'"){o=c,t+=c;continue}if(c==="("?s++:c===")"&&s>0&&s--,c===","&&s===0){e.push(t.trim()),t="";continue}t+=c;}return t.trim()&&e.push(t.trim()),e}function Ce(n){let e=n.match(/^(.*?)\s+as\s+(.+)$/i),t=e?e[1].trim():n.trim(),s=e?e[2].trim():void 0;if(!s){let c=n.match(/^(.+?)\s+((?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+))$/);c&&!/[()]/.test(c[1])&&(t=c[1].trim(),s=c[2].trim());}let o=t.split(".").map(M);if(o.length>2)return null;let a=o.at(-1);return !a||!/^[A-Za-z_][\w$]*$/.test(a)?null:{baseColumn:a,viewColumn:s?M(s):a}}function z(n){return !!(n&&/[A-Za-z0-9_$]/.test(n))}function Le(n){let e=/\bselect\b/i.exec(n);if(!e)return null;let t=0,s=null;for(let o=e.index+e[0].length;o<n.length;o++){let a=n[o];if(s){a===s&&(s=null);continue}if(a==='"'||a==="`"||a==="'"){s=a;continue}if(a==="("){t++;continue}if(a===")"&&t>0){t--;continue}if(t===0&&n.slice(o,o+4).toLowerCase()==="from"&&!z(n[o-1])&&!z(n[o+4]))return {selectList:n.slice(e.index+e[0].length,o).trim(),fromRest:n.slice(o+4).trim()}}return null}function Ie(n){let e=0,t=[];for(;e<n.length;){for(;/\s/.test(n[e]??"");)e++;let s=n[e],o="";if(s==='"'||s==="`"){let r=n.indexOf(s,e+1);if(r===-1)return null;o=n.slice(e,r+1),e=r+1;}else if(s==="["){let r=n.indexOf("]",e+1);if(r===-1)return null;o=n.slice(e,r+1),e=r+1;}else {let r=/^[A-Za-z_][\w$]*/.exec(n.slice(e));if(!r)return null;o=r[0],e+=o.length;}t.push(o);let a=n.slice(e),c=/^\s*\./.exec(a);if(!c)break;e+=c[0].length;}return t.length===0?null:{raw:t.join("."),rest:n.slice(e).trim()}}function X(n,e,t){let s=n.get(e)??[];s.includes(t)||s.push(t),n.set(e,s);}function xe(n,e){if(!n)return null;let t=Le(n);if(!t)return null;let s=Ie(t.fromRest);if(!s)return null;let{raw:o,rest:a}=s;if(/\b(join|union|intersect|except)\b/i.test(a))return null;let c=o.split(".").map(M).at(-1);if(!c)return null;let r=new Map,l=e.get(c)??new Set;for(let f of Oe(t.selectList)){let m=f.trim();if(m==="*"||m.endsWith(".*")){for(let g of l)X(r,g,g);continue}let p=Ce(f);p&&X(r,p.baseColumn,p.viewColumn);}return r.size===0?null:{baseTable:c,columns:r}}function ke(n,e){let t=new Map;for(let[s,o]of e){let a=[];for(let c of o){let r=n.get(c);if(r)for(let l of r)a.includes(l)||a.push(l);}a.length>0&&t.set(s,a);}return t}function Be(n){let e=new Map,t=new Map;for(let r of n.columns??[]){let l=t.get(r.table)??new Set;l.add(r.name),t.set(r.table,l);}let s=(r,l)=>{let f=e.get(r)??[];f.some(m=>m.name===l.name&&m.schema===l.schema)||f.push(l),e.set(r,f);};for(let r of n.tables??[]){if(r.type!=="table")continue;let l=t.get(r.name);l&&s(r.name,{name:r.name,schema:r.schema,columnByBaseColumn:new Map([...l].map(f=>[f,[f]]))});}let o=new Map;for(let r of n.views??[]){let l=xe(r.sql,t);if(!l)continue;let f=t.get(r.name);if(!f)continue;let m=new Map;for(let[g,h]of l.columns){let d=h.filter(_=>f.has(_));d.length>0&&m.set(g,d);}if(m.size===0)continue;let p={name:r.name,schema:r.schema,columnByBaseColumn:m,fromRelation:l.baseTable};o.set(r.name,p);}let a=16;function c(r,l,f){if(l>a)return null;let m=r.fromRelation;if(e.has(m))return {physicalBase:m,columnByBaseColumn:r.columnByBaseColumn};let p=o.get(m);if(!p||f.has(m))return null;f.add(m);let g=c(p,l+1,f);if(f.delete(m),!g)return null;let h=ke(r.columnByBaseColumn,g.columnByBaseColumn);return h.size===0?null:{physicalBase:g.physicalBase,columnByBaseColumn:h}}for(let r of o.values()){let l=c(r,0,new Set([r.name]));l&&s(l.physicalBase,{name:r.name,schema:r.schema,columnByBaseColumn:l.columnByBaseColumn});}return e}function Z(n){return `${n.foreign_key_group??""}:${n.table}.${n.column}->${n.ref_table}.${n.ref_column}`}function ve(n){let e=new Map;for(let t of n){let s=`${t.schema}.${t.table}.${t.foreign_key_name}.${t.ref_schema??""}.${t.ref_table}`,o=e.get(s);o?o.push(t):e.set(s,[t]);}return [...e.values()]}function De(n){let e=[[]];for(let t of n){let s=[];for(let o of e)for(let a of t)s.push([...o,a]);e=s;}return e}function Pe(n,e,t,s){let o=s.map(c=>c.childColumn).join(","),a=s.map(c=>c.parentColumn).join(",");return `${t}:${n.name}(${o})->${e.name}(${a})`}function ee(n){if(!n.foreign_keys?.length||!n.views?.length)return n;let e=Be(n),t=new Set(n.foreign_keys.map(Z)),s=[];for(let o of ve(n.foreign_keys)){let a=o[0],c=e.get(a.table)??[],r=e.get(a.ref_table)??[];for(let l of c)for(let f of r){if(l.schema!==f.schema)continue;let m=[];for(let p of o){let g=l.columnByBaseColumn.get(p.column)??[],h=f.columnByBaseColumn.get(p.ref_column)??[],d=g.flatMap(_=>h.map(S=>({fk:p,childColumn:_,parentColumn:S})));if(d.length===0){m.length=0;break}m.push(d);}for(let p of De(m)){let h=l.name===a.table&&f.name===a.ref_table&&p.every(d=>d.childColumn===d.fk.column&&d.parentColumn===d.fk.ref_column)?void 0:Pe(l,f,a.foreign_key_name,p);for(let d of p){let _={...d.fk,table:l.name,column:d.childColumn,schema:l.schema,ref_table:f.name,ref_column:d.parentColumn,ref_schema:f.schema,foreign_key_group:h},S=Z(_);t.has(S)||(t.add(S),s.push(_));}}}}return s.length?{...n,foreign_keys:[...n.foreign_keys,...s]}:n}var R="anon, authenticated, service_role",Me=new Set(["anon","authenticated","service_role"]);function te(n){return `"${n.replace(/"/g,'""')}"`}var N=class extends Error{constructor(t){super("Force rollback");this.result=t;}},I=class extends Connection{dialect="postgres";harnessHoldingOuterTx=false;constructor(e){super({...e,baseSchema:`
18
18
  ${e.baseSchema??""}
19
19
 
20
20
  CREATE SCHEMA IF NOT EXISTS auth;
@@ -194,7 +194,7 @@ END $$;
194
194
  'information_schema'
195
195
  , 'pg_catalog')
196
196
  GROUP BY ns.nspname, cl.relname, con.oid
197
- `.execute(this.kysely)).rows.map(i=>({table:i.table,columns:i.columns,schema:i.schema,field_count:i.columns.length})),g=new Set(h.flatMap(i=>i.columns.map(w=>`${i.schema}.${i.table}.${w}`)));for(let i of f)i.is_primary_key=g.has(`${i.schema}.${i.table}.${i.name}`);let S=(await sql`
197
+ `.execute(this.kysely)).rows.map(i=>({table:i.table,columns:i.columns,schema:i.schema,field_count:i.columns.length})),d=new Set(h.flatMap(i=>i.columns.map(w=>`${i.schema}.${i.table}.${w}`)));for(let i of f)i.is_primary_key=d.has(`${i.schema}.${i.table}.${i.name}`);let S=(await sql`
198
198
  SELECT
199
199
  tnsp.nspname AS "schema",
200
200
  cl.relname AS "table",
@@ -321,7 +321,7 @@ END $$;
321
321
  WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
322
322
  AND p.prokind = 'f'
323
323
  ORDER BY n.nspname, p.proname
324
- `.execute(this.kysely)).rows.map(i=>{let w=i.arg_names_raw??[],E=i.arg_modes_raw??null,ye=E&&E.length===w.length?w.filter((b,k)=>E[k]==="i"||E[k]==="b"||E[k]==="v"):w,he=!!E?.some(b=>b==="o"||b==="b"||b==="t");return {schema:i.schema,name:i.name,arg_names:ye,arg_types:i.arg_types_raw??[],arg_defaults:Number(i.arg_defaults??0),has_variadic:i.has_variadic===!0,volatility:i.volatility??"v",return_type:i.return_type??"",return_is_setof:i.return_is_setof===!0,return_rows:Number(i.return_rows??0),return_typtype:i.return_typtype??"",return_base_type:i.return_base_type??void 0,has_out_args:he}}),fe=(await sql`
324
+ `.execute(this.kysely)).rows.map(i=>{let w=i.arg_names_raw??[],E=i.arg_modes_raw??null,he=E&&E.length===w.length?w.filter((b,k)=>E[k]==="i"||E[k]==="b"||E[k]==="v"):w,ye=!!E?.some(b=>b==="o"||b==="b"||b==="t");return {schema:i.schema,name:i.name,arg_names:he,arg_types:i.arg_types_raw??[],arg_defaults:Number(i.arg_defaults??0),has_variadic:i.has_variadic===!0,volatility:i.volatility??"v",return_type:i.return_type??"",return_is_setof:i.return_is_setof===!0,return_rows:Number(i.return_rows??0),return_typtype:i.return_typtype??"",return_base_type:i.return_base_type??void 0,has_out_args:ye}}),fe=(await sql`
325
325
  SELECT
326
326
  c.relname AS "name",
327
327
  n.nspname AS "schema",
@@ -337,7 +337,7 @@ END $$;
337
337
  SELECT DISTINCT n.nspname FROM pg_class c
338
338
  JOIN pg_namespace n ON n.oid = c.relnamespace
339
339
  WHERE c.relrowsecurity = true
340
- `.execute(this.kysely);for(let{nspname:o}of s.rows){let a=te(o);await sql.raw(`GRANT USAGE ON SCHEMA ${a} TO ${R}`).execute(this.kysely),await sql.raw(`GRANT ALL ON ALL TABLES IN SCHEMA ${a} TO ${R}`).execute(this.kysely),await sql.raw(`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${a} TO ${R}`).execute(this.kysely),await sql.raw(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${a} GRANT ALL ON TABLES TO ${R}`).execute(this.kysely),await sql.raw(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${a} GRANT ALL ON SEQUENCES TO ${R}`).execute(this.kysely);}return true}async postgresTransactionActive(e){try{return await sql`SAVEPOINT __supalite_outer_tx_check`.execute(e),await sql`RELEASE SAVEPOINT __supalite_outer_tx_check`.execute(e),!0}catch{return false}}async applyJwtSessionContext(e,t,s){let o=t.auth,a=o?.role||"anon",c=String(o?.uid??""),r=o?.jwt;await sql`SELECT set_config('role', ${a}, true)`.execute(e),await sql`SELECT set_config('request.jwt.claim.sub', ${c}, true)`.execute(e),await sql`SELECT set_config('request.jwt.claim.role', ${a}, true)`.execute(e),s&&await sql.raw(`SET LOCAL ROLE ${te(a)}`).execute(e),r&&typeof r=="object"&&await sql`SELECT set_config('request.jwt.claims', ${JSON.stringify(r)}, true)`.execute(e);}async applyRpcRequestGucs(e,t){await sql`SELECT set_config('response.status', '', true)`.execute(e),await sql`SELECT set_config('response.headers', '', true)`.execute(e),await sql`SELECT set_config('request.method', ${t.method}, true)`.execute(e),await sql`SELECT set_config('request.path', ${t.path}, true)`.execute(e),await sql`SELECT set_config('request.headers', ${JSON.stringify(t.requestHeaders??{})}, true)`.execute(e);}async withContext(e,t,s){let o=s?.forceRollback===true;if(!o&&!e)return t(this.kysely);let a=e?await this.ensureRlsContext():false,r=e?.auth?.role||"anon",l=typeof r=="string"&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&!Me.has(r),f=s?.rpc;if(f){let u=async p=>{e&&(a||l)&&await this.applyJwtSessionContext(p,e,l),await this.applyRpcRequestGucs(p,f),f.readOnly&&await sql`SET LOCAL transaction_read_only = on`.execute(p);};if(this.harnessHoldingOuterTx)return invariant(await this.postgresTransactionActive(this.kysely),"harnessHoldingOuterTx is set but the connection has no open PostgreSQL transaction; wrap REST requests in BEGIN/ROLLBACK in the spec harness"),await u(this.kysely),t(this.kysely);try{return await this.kysely.transaction().execute(async p=>{await u(p);let d=await t(p);if(o)throw new N(d);return d})}catch(p){if(p instanceof N)return p.result;throw p}}if(!o&&!a&&!l)return t(this.kysely);if(!o&&l)return this.harnessHoldingOuterTx?(invariant(await this.postgresTransactionActive(this.kysely),"harnessHoldingOuterTx is set but the connection has no open PostgreSQL transaction; wrap REST requests in BEGIN/ROLLBACK in the spec harness"),await this.applyJwtSessionContext(this.kysely,e,true),t(this.kysely)):this.kysely.transaction().execute(async u=>(await this.applyJwtSessionContext(u,e,true),t(u)));if(!o&&a&&!l)return this.kysely.transaction().execute(async u=>(await this.applyJwtSessionContext(u,e,true),t(u)));try{return await this.kysely.transaction().execute(async u=>{e&&(a||l)&&await this.applyJwtSessionContext(u,e,l);let p=await t(u);if(o)throw new N(p);return p})}catch(u){if(u instanceof N)return u.result;throw u}}async onPostgrestAST(e){if(!e.from)return e;let t=e.schema??"public",s=e.from,o=await this.introspect({useCache:true});if(!o.tables.some(a=>a.name===s&&a.schema===t)&&!o.views.some(a=>a.name===s&&a.schema===t))throw new RelationNotFoundError(t,s);return e}async transaction(e,t){await this.exec("BEGIN");try{for(let s of e)await this.exec(s);await this.exec("COMMIT");}catch(s){throw await this.exec("ROLLBACK"),s}finally{t?.intent==="migration"&&await this.clearSchemaCache();}}get supportsRpc(){return true}async viewOptionsMetadata(e,t){let{rows:s}=await sql`
340
+ `.execute(this.kysely);for(let{nspname:o}of s.rows){let a=te(o);await sql.raw(`GRANT USAGE ON SCHEMA ${a} TO ${R}`).execute(this.kysely),await sql.raw(`GRANT ALL ON ALL TABLES IN SCHEMA ${a} TO ${R}`).execute(this.kysely),await sql.raw(`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${a} TO ${R}`).execute(this.kysely),await sql.raw(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${a} GRANT ALL ON TABLES TO ${R}`).execute(this.kysely),await sql.raw(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${a} GRANT ALL ON SEQUENCES TO ${R}`).execute(this.kysely);}return true}async postgresTransactionActive(e){try{return await sql`SAVEPOINT __supalite_outer_tx_check`.execute(e),await sql`RELEASE SAVEPOINT __supalite_outer_tx_check`.execute(e),!0}catch{return false}}async applyJwtSessionContext(e,t,s){let o=t.auth,a=o?.role||"anon",c=String(o?.uid??""),r=o?.jwt;await sql`SELECT set_config('role', ${a}, true)`.execute(e),await sql`SELECT set_config('request.jwt.claim.sub', ${c}, true)`.execute(e),await sql`SELECT set_config('request.jwt.claim.role', ${a}, true)`.execute(e),s&&await sql.raw(`SET LOCAL ROLE ${te(a)}`).execute(e),r&&typeof r=="object"&&await sql`SELECT set_config('request.jwt.claims', ${JSON.stringify(r)}, true)`.execute(e);}async applyRpcRequestGucs(e,t){await sql`SELECT set_config('response.status', '', true)`.execute(e),await sql`SELECT set_config('response.headers', '', true)`.execute(e),await sql`SELECT set_config('request.method', ${t.method}, true)`.execute(e),await sql`SELECT set_config('request.path', ${t.path}, true)`.execute(e),await sql`SELECT set_config('request.headers', ${JSON.stringify(t.requestHeaders??{})}, true)`.execute(e);}async withContext(e,t,s){let o=s?.forceRollback===true;if(!o&&!e)return t(this.kysely);let a=e?await this.ensureRlsContext():false,r=e?.auth?.role||"anon",l=typeof r=="string"&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&!Me.has(r),f=s?.rpc;if(f){let m=async p=>{e&&(a||l)&&await this.applyJwtSessionContext(p,e,l),await this.applyRpcRequestGucs(p,f),f.readOnly&&await sql`SET LOCAL transaction_read_only = on`.execute(p);};if(this.harnessHoldingOuterTx)return invariant(await this.postgresTransactionActive(this.kysely),"harnessHoldingOuterTx is set but the connection has no open PostgreSQL transaction; wrap REST requests in BEGIN/ROLLBACK in the spec harness"),await m(this.kysely),t(this.kysely);try{return await this.kysely.transaction().execute(async p=>{await m(p);let g=await t(p);if(o)throw new N(g);return g})}catch(p){if(p instanceof N)return p.result;throw p}}if(!o&&!a&&!l)return t(this.kysely);if(!o&&l)return this.harnessHoldingOuterTx?(invariant(await this.postgresTransactionActive(this.kysely),"harnessHoldingOuterTx is set but the connection has no open PostgreSQL transaction; wrap REST requests in BEGIN/ROLLBACK in the spec harness"),await this.applyJwtSessionContext(this.kysely,e,true),t(this.kysely)):this.kysely.transaction().execute(async m=>(await this.applyJwtSessionContext(m,e,true),t(m)));if(!o&&a&&!l)return this.kysely.transaction().execute(async m=>(await this.applyJwtSessionContext(m,e,true),t(m)));try{return await this.kysely.transaction().execute(async m=>{e&&(a||l)&&await this.applyJwtSessionContext(m,e,l);let p=await t(m);if(o)throw new N(p);return p})}catch(m){if(m instanceof N)return m.result;throw m}}async onPostgrestAST(e){if(!e.from)return e;let t=e.schema??"public",s=e.from,o=await this.introspect({useCache:true});if(!o.tables.some(a=>a.name===s&&a.schema===t)&&!o.views.some(a=>a.name===s&&a.schema===t))throw new RelationNotFoundError(t,s);return e}async transaction(e,t){await this.exec("BEGIN");try{for(let s of e)await this.exec(s);await this.exec("COMMIT");}catch(s){throw await this.exec("ROLLBACK"),s}finally{t?.intent==="migration"&&await this.clearSchemaCache();}}get supportsRpc(){return true}async viewOptionsMetadata(e,t){let{rows:s}=await sql`
341
341
  select is_insertable_into, is_updatable,
342
342
  is_trigger_insertable_into, is_trigger_updatable, is_trigger_deletable
343
343
  from information_schema.views
@@ -345,9 +345,9 @@ END $$;
345
345
  `.execute(this.kysely),o=s[0],a=r=>r==="YES",{rows:c}=await sql`
346
346
  select table_schema, table_name from information_schema.view_table_usage
347
347
  where view_schema = ${t} and view_name = ${e}
348
- `.execute(this.kysely);return {canInsert:a(o?.is_insertable_into)||a(o?.is_trigger_insertable_into),canUpdate:a(o?.is_updatable)||a(o?.is_trigger_updatable),canDelete:a(o?.is_updatable)||a(o?.is_trigger_deletable),baseTables:c.map(r=>({schema:r.table_schema,name:r.table_name}))}}};var ne=(n,e=t=>t)=>{if(!n||n==="{}")return [];let t=n.slice(1,-1);if(t==="")return [];let s=[],o="",a=false,c=0;for(let r=0;r<t.length;r++){let l=t[r];l==='"'&&t[r-1]!=="\\"?(a=!a,o+=l):l==="{"&&!a?(c++,o+=l):l==="}"&&!a?(c--,o+=l):l===","&&!a&&c===0?(s.push(e(o)),o=""):o+=l;}return o!==""&&s.push(e(o)),s},He=n=>n==="NULL"?null:n.startsWith('"')&&n.endsWith('"')?n.slice(1,-1).replace(/\\(.)/g,"$1"):n,Ue=n=>n==="NULL"?null:Number.parseInt(n,10);function se(n){return typeof n=="object"&&n!==null&&"text"in n&&"values"in n}function Ge(n,e){if(n==null)return n;switch(e){case 20:return typeof n=="bigint"?n:BigInt(n);case 22:return Array.isArray(n)?n:typeof n=="string"?n.split(" ").map(Number).filter(t=>!Number.isNaN(t)):n;case 1002:case 1009:case 1015:return typeof n=="string"?ne(n,He):n;case 1005:case 1007:case 1016:return typeof n=="string"?ne(n,Ue):n;default:return n}}function U(n){return {async query(e,t){let s=se(e)?e.text:e,o=se(e)?e.values:t??[],a=await n.driver.query(s,[...o]);return {rows:a.rows.map(r=>Object.fromEntries(a.fields.map(l=>[l.name,Ge(r[l.name],l.dataTypeID)])))}}}}var Je=new Set(["public","supabase_migrations"]),We=/\bCREATE\s+SCHEMA\b(?:\s+IF\s+NOT\s+EXISTS)?\s+("?[\w$]+"?)/gi;function qe(n,e){let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`(?<![\\w$"])${t}\\.`);return n.some(o=>s.test(o))}function ae(n,e){let t=new Set;for(let s of e)for(let o of s.matchAll(We))t.add(o[1]);return Object.values(n.schemas).map(s=>s.name).filter(s=>!Je.has(s)&&!t.has(s)&&qe(e,s)).map(s=>`CREATE SCHEMA IF NOT EXISTS ${s};`)}async function Ke(){try{return await import('@supabase/pg-delta')}catch(n){throw new Error("Postgres/PGlite schema diffing now requires a Bun/Node-compatible runtime with pg-delta available.",{cause:n})}}var Qe=["supabase_migrations"];function Ye(n){let e=/^drop table (.+)$/.exec(n);if(e)return {table:e[1],reason:"drop table"};let t=/^drop column (.+) on (.+)$/.exec(n);if(t)return {table:t[2],reason:`drop column ${t[1]}`};let s=/^drop sequence (.+)$/.exec(n);return s?{table:s[1],reason:"drop sequence"}:{table:"unknown",reason:n}}var x=class{constructor(e,t){this.from=e;this.desiredSchema=t;}#e;async#t(e){if(this.#e)return this.#e;let t=new this.from.constructor;try{let s=C(F(this.desiredSchema));return s&&await t.exec(s),await t.exec(this.desiredSchema),this.#e=await e(U(t)),this.#e}finally{await t.close();}}async diff(){let{createPlan:e,extractCatalog:t}=await Ke(),s=U(this.from),o=await this.#t(t),a=await t(s),c=await e(a,o,{filter:{not:{schema:Qe}}});if(!c)return {diff:"",plan:{steps:[],warnings:[],unsafe:false}};let r=c.plan.risk?.level==="data_loss"?c.plan.risk.statements.map(Ye):[],l=Y(this.desiredSchema),f=c.plan.statements.filter(p=>!V(p,l)),u=[...ae(o,f),...f];return {diff:u.join(`
348
+ `.execute(this.kysely);return {canInsert:a(o?.is_insertable_into)||a(o?.is_trigger_insertable_into),canUpdate:a(o?.is_updatable)||a(o?.is_trigger_updatable),canDelete:a(o?.is_updatable)||a(o?.is_trigger_deletable),baseTables:c.map(r=>({schema:r.table_schema,name:r.table_name}))}}};var ne=(n,e=t=>t)=>{if(!n||n==="{}")return [];let t=n.slice(1,-1);if(t==="")return [];let s=[],o="",a=false,c=0;for(let r=0;r<t.length;r++){let l=t[r];l==='"'&&t[r-1]!=="\\"?(a=!a,o+=l):l==="{"&&!a?(c++,o+=l):l==="}"&&!a?(c--,o+=l):l===","&&!a&&c===0?(s.push(e(o)),o=""):o+=l;}return o!==""&&s.push(e(o)),s},He=n=>n==="NULL"?null:n.startsWith('"')&&n.endsWith('"')?n.slice(1,-1).replace(/\\(.)/g,"$1"):n,Ue=n=>n==="NULL"?null:Number.parseInt(n,10);function se(n){return typeof n=="object"&&n!==null&&"text"in n&&"values"in n}function Ge(n,e){if(n==null)return n;switch(e){case 20:return typeof n=="bigint"?n:BigInt(n);case 22:return Array.isArray(n)?n:typeof n=="string"?n.split(" ").map(Number).filter(t=>!Number.isNaN(t)):n;case 1002:case 1009:case 1015:return typeof n=="string"?ne(n,He):n;case 1005:case 1007:case 1016:return typeof n=="string"?ne(n,Ue):n;default:return n}}function U(n){return {async query(e,t){let s=se(e)?e.text:e,o=se(e)?e.values:t??[],a=await n.driver.query(s,[...o]);return {rows:a.rows.map(r=>Object.fromEntries(a.fields.map(l=>[l.name,Ge(r[l.name],l.dataTypeID)])))}}}}var Je=new Set(["public","supabase_migrations"]),We=/\bCREATE\s+SCHEMA\b(?:\s+IF\s+NOT\s+EXISTS)?\s+("?[\w$]+"?)/gi;function qe(n,e){let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`(?<![\\w$"])${t}\\.`);return n.some(o=>s.test(o))}function ae(n,e){let t=new Set;for(let s of e)for(let o of s.matchAll(We))t.add(o[1]);return Object.values(n.schemas).map(s=>s.name).filter(s=>!Je.has(s)&&!t.has(s)&&qe(e,s)).map(s=>`CREATE SCHEMA IF NOT EXISTS ${s};`)}async function Ke(){try{return await import('@supabase/pg-delta')}catch(n){throw new Error("Postgres/PGlite schema diffing now requires a Bun/Node-compatible runtime with pg-delta available.",{cause:n})}}var Qe=["supabase_migrations"];function Ye(n){let e=/^drop table (.+)$/.exec(n);if(e)return {table:e[1],reason:"drop table"};let t=/^drop column (.+) on (.+)$/.exec(n);if(t)return {table:t[2],reason:`drop column ${t[1]}`};let s=/^drop sequence (.+)$/.exec(n);return s?{table:s[1],reason:"drop sequence"}:{table:"unknown",reason:n}}var x=class{constructor(e,t){this.from=e;this.desiredSchema=t;}#e;async#t(e){if(this.#e)return this.#e;let t=new this.from.constructor;try{let s=C(F(this.desiredSchema));return s&&await t.exec(s),await t.exec(this.desiredSchema),this.#e=await e(U(t)),this.#e}finally{await t.close();}}async diff(e){let{createPlan:t,extractCatalog:s}=await Ke(),o=U(this.from),a=await this.#t(s),c=await s(o),r=e?.schemas?{schema:e.schemas}:{not:{schema:Qe}},l=await t(c,a,{filter:r});if(!l)return {diff:"",plan:{steps:[],warnings:[],unsafe:false}};let f=l.plan.risk?.level==="data_loss"?l.plan.risk.statements.map(Ye):[],m=Y(this.desiredSchema),p=l.plan.statements.filter(h=>!V(h,m)),g=[...ae(a,p),...p];return {diff:g.join(`
349
349
 
350
- `),plan:{steps:u.map(p=>({sql:p})),warnings:r,unsafe:c.plan.risk?.level==="data_loss"}}}async migratePlan(e,t){if(e.steps.length===0)return;if(e.unsafe&&!t?.force)throw new DataLossError(e.warnings??[]);let s=e.steps.map(r=>r.sql).join(`
351
- `),o=L(s),a=new Set(e.steps.flatMap(r=>[...F(r.sql)]).filter(r=>!o.has(r))),c=C(a);c&&await this.from.exec(c),await this.from.transaction(e.steps.map(r=>r.sql),{intent:"migration"});}async migrate(e){let t=await this.diff();return await this.migratePlan(t.plan,e),t}safeSortPlanSteps(e){return e}};var G=class extends I{driver;dialect="postgres";#e=false;constructor(e={}){let t=e.url;t&&!t.includes("://")&&!oe.existsSync(t)&&oe.mkdirSync(t,{recursive:true});let s=new PGlite({...e.pgliteOptions,dataDir:e.url??void 0,extensions:{...e.pgliteOptions?.extensions,isn:isn,ltree:ltree,file_fdw:file_fdw,pgcrypto:pgcrypto},parsers:{20:a=>{let c=Number(a);return Number.isSafeInteger(c)?c:BigInt(a)},114:a=>JSON.parse(a),3802:a=>JSON.parse(a),1700:a=>{let c=Number(a);return Number.isFinite(c)&&String(c)===a?c:a},1082:a=>a,1083:a=>a,1114:a=>a,1184:a=>a,1266:a=>a,...e.pgliteOptions?.parsers}}),{dialect:o}=new T(s);super(e),this.driver=s,this.kysely=new Kysely({dialect:o});}async exec(e,...t){try{if(t.length>0){let{rows:o}=await sql(e,...t??[]).execute(this.kysely);return {rows:o}}return {rows:(await this.driver.exec(e))[0].rows}}catch(s){throw console.error(s),new Error(`Failed to execute query: ${e}`)}}async close(){this.#e||(this.#e=true,await this.clearSchemaCache(),await this.kysely.destroy(),await this.driver.close());}createMigrator(e){let t=[this.config.baseSchema,e].filter(Boolean).join(`
350
+ `),plan:{steps:g.map(h=>({sql:h})),warnings:f,unsafe:l.plan.risk?.level==="data_loss"}}}async migratePlan(e,t){if(e.steps.length===0)return;if(e.unsafe&&!t?.force)throw new DataLossError(e.warnings??[]);let s=e.steps.map(r=>r.sql).join(`
351
+ `),o=L(s),a=new Set(e.steps.flatMap(r=>[...F(r.sql)]).filter(r=>!o.has(r))),c=C(a);c&&await this.from.exec(c),await this.from.transaction(e.steps.map(r=>r.sql),{intent:"migration"});}async migrate(e){let t=await this.diff({schemas:e?.schemas});return await this.migratePlan(t.plan,e),t}safeSortPlanSteps(e){return e}};var G=class extends I{driver;dialect="postgres";#e=false;constructor(e={}){let t=e.url;t&&!t.includes("://")&&!oe.existsSync(t)&&oe.mkdirSync(t,{recursive:true});let s=new PGlite({...e.pgliteOptions,dataDir:e.url??void 0,extensions:{...e.pgliteOptions?.extensions,isn:isn,ltree:ltree,file_fdw:file_fdw,pgcrypto:pgcrypto},parsers:{20:a=>{let c=Number(a);return Number.isSafeInteger(c)?c:BigInt(a)},114:a=>JSON.parse(a),3802:a=>JSON.parse(a),1700:a=>{let c=Number(a);return Number.isFinite(c)&&String(c)===a?c:a},1082:a=>a,1083:a=>a,1114:a=>a,1184:a=>a,1266:a=>a,...e.pgliteOptions?.parsers}}),{dialect:o}=new T(s);super(e),this.driver=s,this.kysely=new Kysely({dialect:o});}async exec(e,...t){try{if(t.length>0){let{rows:o}=await sql(e,...t??[]).execute(this.kysely);return {rows:o}}return {rows:(await this.driver.exec(e))[0].rows}}catch(s){throw console.error(s),new Error(`Failed to execute query: ${e}`)}}async close(){this.#e||(this.#e=true,await this.clearSchemaCache(),await this.kysely.destroy(),await this.driver.close());}createMigrator(e){let t=[this.config.baseSchema,e].filter(Boolean).join(`
352
352
 
353
353
  `);return new x(this,t)}};async function Mt(n={}){return new G(n)}export{G as PgliteConnection,Mt as createPgliteConnection};
package/dist/index.d.ts CHANGED
@@ -10,8 +10,8 @@ import * as hono from 'hono';
10
10
  import { MiddlewareHandler, Context } from 'hono';
11
11
  import { Kysely, KyselyPlugin } from 'kysely';
12
12
  import { ReadableStream as ReadableStream$1 } from 'node:stream/web';
13
- import { a as CacheDriver, b as CacheSetOptions, W as Where, c as IntrospectResult, A as AnyAST, V as VarsContext, T as TransactionOptions$1 } from './Connection-Cm9fpZU3.js';
14
- export { d as AST, e as ASTType, f as AggregateFunction, B as BaseAST, g as BodyResult, h as CheckConstraintInfo, i as ColumnDef, j as ColumnDiff, k as ColumnInfo, l as ColumnRef, m as CommentInfo, C as Connection, n as ConnectionContextOptions, o as ConnectionMigrator, p as CustomTypesInfo, D as DataLossError, q as DataLossWarning, r as DeleteAST, s as Dialect, t as DiffResult, E as EmbedDef, u as EmbedTransform, v as ExplainOptions, F as FiltersResult, w as ForeignKeyDiff, x as ForeignKeyInfo, y as FunctionInfo, H as HeadersResult, I as IConnectionConfig, z as IndexDiff, G as IndexInfo, J as InsertAST, K as IntrospectOptions, L as JoinDef, M as JoinMap, N as Meta, O as MigrationError, P as OrderEntry, Q as PlanResult, R as PlanStep, S as PlanStepType, U as PreferToken, X as PrimaryKeyInfo, Y as Qb, Z as QbDelete, _ as QbInsert, $ as QbSelect, a0 as QbUpdate, a1 as QueryAST, a2 as QueryParamsResult, a3 as RelationNotFoundError, a4 as RouteResult, a5 as RpcAST, a6 as RpcResult, a7 as SchemaDiffResult, a8 as SelectEntry, a9 as SelectResult, aa as TableDiff, ab as TableInfo, ac as TextSearchValue, ad as TransformsResult, ae as TranslatorConfig, af as TriggerInfo, ag as UniqueConstraintInfo, ah as UpdateAST, ai as UpsertAST, aj as UpsertResult, ak as ViewInfo, al as ViewOptionsMetadata, am as WhereValue, an as isRef } from './Connection-Cm9fpZU3.js';
13
+ import { a as CacheDriver, b as CacheSetOptions, W as Where, c as IntrospectResult, M as MigrateScope, A as AnyAST, V as VarsContext, T as TransactionOptions$1, C as Connection$1 } from './Connection-D9UUTsjg.js';
14
+ export { d as AST, e as ASTType, f as AggregateFunction, B as BaseAST, g as BodyResult, h as CheckConstraintInfo, i as ColumnDef, j as ColumnDiff, k as ColumnInfo, l as ColumnRef, m as CommentInfo, n as ConnectionContextOptions, o as ConnectionMigrator, p as CustomTypesInfo, D as DataLossError, q as DataLossWarning, r as DeleteAST, s as Dialect, t as DiffResult, E as EmbedDef, u as EmbedTransform, v as ExplainOptions, F as FiltersResult, w as ForeignKeyDiff, x as ForeignKeyInfo, y as FunctionInfo, H as HeadersResult, I as IConnectionConfig, z as IndexDiff, G as IndexInfo, J as InsertAST, K as IntrospectOptions, L as JoinDef, N as JoinMap, O as Meta, P as MigrationError, Q as OrderEntry, R as PlanResult, S as PlanStep, U as PlanStepType, X as PreferToken, Y as PrimaryKeyInfo, Z as Qb, _ as QbDelete, $ as QbInsert, a0 as QbSelect, a1 as QbUpdate, a2 as QueryAST, a3 as QueryParamsResult, a4 as RelationNotFoundError, a5 as RouteResult, a6 as RpcAST, a7 as RpcResult, a8 as SchemaDiffResult, a9 as SelectEntry, aa as SelectResult, ab as TableDiff, ac as TableInfo, ad as TextSearchValue, ae as TransformsResult, af as TranslatorConfig, ag as TriggerInfo, ah as UniqueConstraintInfo, ai as UpdateAST, aj as UpsertAST, ak as UpsertResult, al as ViewInfo, am as ViewOptionsMetadata, an as WhereValue, ao as isRef } from './Connection-D9UUTsjg.js';
15
15
  import { ParseResult } from 'libpg-query';
16
16
  import { DeparserOptions } from 'pgsql-deparser';
17
17
  import 'jsonv-ts';
@@ -2161,6 +2161,9 @@ declare function createServer(app: App, options?: ServerOptions): hono_hono_base
2161
2161
  delete: never;
2162
2162
  } | undefined;
2163
2163
  } | undefined;
2164
+ system?: {
2165
+ schemaReconciliation?: "additive" | "full" | undefined;
2166
+ } | undefined;
2164
2167
  } | undefined;
2165
2168
  rls?: {
2166
2169
  tables: string[];
@@ -2361,14 +2364,25 @@ interface IAppConfig extends DefaultSchema {
2361
2364
  defaults?: boolean;
2362
2365
  server?: ServerOptions;
2363
2366
  drivers?: PartialAppDrivers;
2367
+ system?: SystemOptions;
2364
2368
  };
2365
2369
  }
2370
+ interface SystemOptions {
2371
+ /**
2372
+ * How `ensureSystemSchema()` reconciles system schemas against config:
2373
+ * `"additive"` (default) only creates missing tables/columns; `"full"` also
2374
+ * drops system tables removed from an enabled module's schema (data-loss
2375
+ * steps require `force`).
2376
+ */
2377
+ schemaReconciliation?: "additive" | "full";
2378
+ }
2366
2379
  interface DefaultAppConfig extends IAppConfig {
2367
2380
  connection: Connection;
2368
2381
  options?: {
2369
2382
  defaults?: true;
2370
2383
  server?: ServerOptions;
2371
2384
  drivers?: PartialAppDrivers;
2385
+ system?: SystemOptions;
2372
2386
  };
2373
2387
  }
2374
2388
  declare class App<Config extends IAppConfig = DefaultAppConfig, Conn = Config extends IAppConfig ? Config["connection"] extends Connection ? Config["connection"] : Config["connection"] extends Promise<Connection> ? Awaited<Config["connection"]> : Connection : never> {
@@ -2387,6 +2401,20 @@ declare class App<Config extends IAppConfig = DefaultAppConfig, Conn = Config ex
2387
2401
  * Initialize the app. This is called automatically on first request.
2388
2402
  */
2389
2403
  init(): Promise<this>;
2404
+ /**
2405
+ * Provision the enabled system schemas (auth / storage / migration-history)
2406
+ * on the connected database with NO filesystem access — the runtime entry
2407
+ * point for non-CLI consumers (e.g. a lite-platform Durable Object) and the
2408
+ * shared provisioning path for the CLI (LITE-291). Reconciles ONLY the system
2409
+ * schemas, so user-land tables are never touched. The reconciliation mode
2410
+ * comes from `options.system.schemaReconciliation` (default `"additive"`).
2411
+ *
2412
+ * @param opts.force allow data-loss drops in `"full"` mode (else throws
2413
+ * `DataLossError`).
2414
+ */
2415
+ ensureSystemSchema(opts?: {
2416
+ force?: boolean;
2417
+ }): Promise<void>;
2390
2418
  isValidConfig(config: Schema | DefaultSchema | IAppConfig): boolean;
2391
2419
  getClient<SchemaName extends string = "public">(options?: SupabaseClientOptions<SchemaName>): _supabase_supabase_js.SupabaseClient<any, "public", SchemaName, Omit<any, "__InternalSupabase">[SchemaName] extends {
2392
2420
  Tables: Record<string, {
@@ -2601,14 +2629,14 @@ declare class SqliteMigrator implements ConnectionMigrator {
2601
2629
  translationResult?: SqlitePostgresTranslationResult;
2602
2630
  constructor(conn: SqliteConnection, desiredSchema: string, options?: SqliteMigratorOptions);
2603
2631
  getDesiredSchema(): Promise<string>;
2604
- diff(): Promise<SchemaDiffResult>;
2632
+ diff(scope?: MigrateScope): Promise<SchemaDiffResult>;
2605
2633
  safeSortPlanSteps(steps: PlanStep[]): PlanStep[];
2606
2634
  migratePlan(planResult: PlanResult, opts?: {
2607
2635
  force?: boolean;
2608
2636
  }): Promise<void>;
2609
2637
  migrate(opts?: {
2610
2638
  force?: boolean;
2611
- }): Promise<SchemaDiffResult>;
2639
+ } & MigrateScope): Promise<SchemaDiffResult>;
2612
2640
  }
2613
2641
 
2614
2642
  interface ISqliteConnectionConfig extends IConnectionConfig {
@@ -2790,6 +2818,57 @@ declare class CloudConnection<DB = any> extends SqliteConnection<never, DB> {
2790
2818
  }
2791
2819
  declare function cloud<DB = any>(config: ICloudConnectionConfig): CloudConnection<DB>;
2792
2820
 
2821
+ interface MigrationHistoryRow {
2822
+ version: string;
2823
+ name: string | null;
2824
+ statements: string[];
2825
+ /**
2826
+ * mgmt-API superset columns (LITE-291). Optional so the CLI path, which only
2827
+ * cares about version/name/statements, is unaffected. `idempotency_key` is
2828
+ * backed by a unique index — see `recordVersionSql`'s upsert.
2829
+ */
2830
+ created_by?: string | null;
2831
+ idempotency_key?: string | null;
2832
+ rollback?: string[] | null;
2833
+ }
2834
+ /**
2835
+ * Driver-split history table layout, matching the parity rule in `app/AGENTS.md`:
2836
+ *
2837
+ * - `pg`: real postgres / pglite — `supabase_migrations.schema_migrations`
2838
+ * and `supabase_migrations.seed_files`, byte-compatible with the Supabase
2839
+ * CLI (`~/supabase/cli/pkg/migration/history.go:14-28`).
2840
+ * - `pg-flat`: sqlite-postgres — the same Postgres-shaped DDL, but storage
2841
+ * names are flattened (`"supabase_migrations.schema_migrations"`) because
2842
+ * sqlite has no real schemas. From the user's perspective the SQL written
2843
+ * in migration files is still pg DDL — translation handles the rest.
2844
+ * - `sqlite`: bare sqlite driver — flat `migrations` + `seed_files` tables.
2845
+ */
2846
+ type HistoryVariant = "pg" | "pg-flat" | "sqlite";
2847
+ declare function historyVariant(connection: Connection$1): HistoryVariant;
2848
+ /**
2849
+ * Idempotent raw-pg DDL for the migration-history system schema, parallel to
2850
+ * `getAuthSchemaSql` / `getStorageSchemaSql`. Fed into the system-schema module
2851
+ * registry (see `db/system-schema.ts`); the pg-flat execution path runs it
2852
+ * through `connection.translateDdl` before exec'ing, so storage flattens.
2853
+ */
2854
+ declare function getMigrationHistorySchemaSql(variant: HistoryVariant): string;
2855
+ /**
2856
+ * Idempotently provision the history table. The migration-history tables are
2857
+ * excluded from introspection (so the declarative diff never drops them), which
2858
+ * means the schema-scoped migrator can't create them — this is the direct path
2859
+ * (`App.ensureSystemSchema` calls it, LITE-291). Translation-free (native DDL
2860
+ * per variant) so it runs in workerd. Order matters: create tables, upgrade
2861
+ * columns on any pre-existing table, THEN create the unique index (which
2862
+ * references `idempotency_key`).
2863
+ */
2864
+ declare function ensureHistoryTable(connection: Connection$1): Promise<void>;
2865
+ declare function appliedVersions(connection: Connection$1): Promise<string[]>;
2866
+ declare function recordVersion(connection: Connection$1, row: MigrationHistoryRow): Promise<void>;
2867
+ declare function removeVersion(connection: Connection$1, version: string): Promise<void>;
2868
+ declare function listHistory(connection: Connection$1): Promise<MigrationHistoryRow[]>;
2869
+ declare function getVersion(connection: Connection$1, version: string): Promise<MigrationHistoryRow | null>;
2870
+ declare function removeVersionsGte(connection: Connection$1, version: string): Promise<void>;
2871
+
2793
2872
  type Primitive = string | number | boolean;
2794
2873
  declare function isPrimitive(value: any): value is Primitive;
2795
2874
  type BooleanLike = boolean | 0 | 1;
@@ -2933,4 +3012,4 @@ declare function isExperimentalEnabled(name: ExperimentalFeature): boolean;
2933
3012
  declare function setExperimental(name: ExperimentalFeature, enabled: boolean): void;
2934
3013
  declare function listEnabledExperimentals(): ExperimentalFeature[];
2935
3014
 
2936
- export { AnyAST, App, type AppDrivers, AwsSesEmailDriver, type AwsSesEmailDriverOptions, type BooleanLike, CacheDriver, CacheSetOptions, CloudConnection, CloudflareKvCacheDriver, type CloudflareKvCacheDriverOptions, type DefaultAppConfig, type EmailDriver, type EmailMessage, type ExperimentalFeature, type HonoContext, type IAppConfig, type ICloudConnectionConfig, type ISqliteConnectionConfig, InMemoryEmailDriver, type InMemoryEmailDriverOptions, InMemoryLruCacheDriver, type InMemoryLruCacheDriverOptions, IntrospectResult, InvalidPostgresToSQLiteTranslation, type MatchPattern, type MaybePromise, NoopEmailDriver, type NoopEmailDriverOptions, NoopSmsDriver, type NoopSmsDriverOptions, type PartialAppDrivers, type PersistedDeparseInfo, Policy, type PolicyCommand, type PolicyData, type PolicyRole, type Primitive, type RedisCacheClient, RedisCacheDriver, type RedisCacheDriverOptions, ResendEmailDriver, type ResendEmailDriverOptions, SUPABASE_AUTH_HELPERS_SQL, Schema, SendmailEmailDriver, type SendmailEmailDriverOptions, type ServerOptions, type SmsDriver, type SmsMessage, SqliteConnection, type SqlitePostgresDeparseInfo, type SqlitePostgresTranslationResult, type StoredEmailMessage, TransactionOptions$1 as TransactionOptions, UnableToCreateRuntimeConnection, VarsContext, Where, checkPasswordStrength, cleanSql, cloud, createAppDrivers, ensureVar, filterSearchParams, formatSendmailMessage, fuzzyMatch, getAuthSchemaSql, getPath, getStatementsArray, getStorageSchemaSql, invariant, isBooleanLike, isBun, isEmail, isEqual, isExperimentalEnabled, isNode, isObject, isPlainObject, isPrimitive, isString, jsonStringify, listEnabledExperimentals, measureTime, mergeObject, mergeObjectWith, normalizeDefault, normalizeSql, normalizeString, normalizeType, objectDiff, omit, params, parseBigInt, patternMatch, pick, pipe, pipeEach, quote, randomString, replacePlaceholders, requireAuth, resolveAuth, setExperimental, setPath, slugify, snakeToPascalWithSpaces, splitSqlStatements, studioRouteHandler, threw, threwAsync, translatePostgresDdl, truncate, trySync, ucFirst, ucFirstAll, uuid };
3015
+ export { AnyAST, App, type AppDrivers, AwsSesEmailDriver, type AwsSesEmailDriverOptions, type BooleanLike, CacheDriver, CacheSetOptions, CloudConnection, CloudflareKvCacheDriver, type CloudflareKvCacheDriverOptions, Connection$1 as Connection, type DefaultAppConfig, type EmailDriver, type EmailMessage, type ExperimentalFeature, type HistoryVariant, type HonoContext, type IAppConfig, type ICloudConnectionConfig, type ISqliteConnectionConfig, InMemoryEmailDriver, type InMemoryEmailDriverOptions, InMemoryLruCacheDriver, type InMemoryLruCacheDriverOptions, IntrospectResult, InvalidPostgresToSQLiteTranslation, type MatchPattern, type MaybePromise, MigrateScope, type MigrationHistoryRow, NoopEmailDriver, type NoopEmailDriverOptions, NoopSmsDriver, type NoopSmsDriverOptions, type PartialAppDrivers, type PersistedDeparseInfo, Policy, type PolicyCommand, type PolicyData, type PolicyRole, type Primitive, type RedisCacheClient, RedisCacheDriver, type RedisCacheDriverOptions, ResendEmailDriver, type ResendEmailDriverOptions, SUPABASE_AUTH_HELPERS_SQL, Schema, SendmailEmailDriver, type SendmailEmailDriverOptions, type ServerOptions, type SmsDriver, type SmsMessage, SqliteConnection, type SqlitePostgresDeparseInfo, type SqlitePostgresTranslationResult, type StoredEmailMessage, TransactionOptions$1 as TransactionOptions, UnableToCreateRuntimeConnection, VarsContext, Where, appliedVersions, checkPasswordStrength, cleanSql, cloud, createAppDrivers, ensureHistoryTable, ensureVar, filterSearchParams, formatSendmailMessage, fuzzyMatch, getAuthSchemaSql, getMigrationHistorySchemaSql, getPath, getStatementsArray, getStorageSchemaSql, getVersion, historyVariant, invariant, isBooleanLike, isBun, isEmail, isEqual, isExperimentalEnabled, isNode, isObject, isPlainObject, isPrimitive, isString, jsonStringify, listEnabledExperimentals, listHistory, measureTime, mergeObject, mergeObjectWith, normalizeDefault, normalizeSql, normalizeString, normalizeType, objectDiff, omit, params, parseBigInt, patternMatch, pick, pipe, pipeEach, quote, randomString, recordVersion, removeVersion, removeVersionsGte, replacePlaceholders, requireAuth, resolveAuth, setExperimental, setPath, slugify, snakeToPascalWithSpaces, splitSqlStatements, studioRouteHandler, threw, threwAsync, translatePostgresDdl, truncate, trySync, ucFirst, ucFirstAll, uuid };