@supabase/sql-to-rest
Version:
[](https://github.com/supabase-community/sql-to-rest/actions?query=branch%3Amain) [](https://www
14 lines • 30.5 kB
JavaScript
;var Re=Object.create;var J=Object.defineProperty,Ae=Object.defineProperties,$e=Object.getOwnPropertyDescriptor,be=Object.getOwnPropertyDescriptors,Ne=Object.getOwnPropertyNames,P=Object.getOwnPropertySymbols,Le=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty,se=Object.prototype.propertyIsEnumerable;var ie=(e,t,r)=>t in e?J(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,$=(e,t)=>{for(var r in t||(t={}))Y.call(t,r)&&ie(e,r,t[r]);if(P)for(var r of P(t))se.call(t,r)&&ie(e,r,t[r]);return e},b=(e,t)=>Ae(e,be(t));var le=(e,t)=>{var r={};for(var n in e)Y.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&P)for(var n of P(e))t.indexOf(n)<0&&se.call(e,n)&&(r[n]=e[n]);return r};var Oe=(e,t)=>{for(var r in t)J(e,r,{get:t[r],enumerable:!0})},ue=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ne(t))!Y.call(e,a)&&a!==r&&J(e,a,{get:()=>t[a],enumerable:!(n=$e(t,a))||n.enumerable});return e};var X=(e,t,r)=>(r=e!=null?Re(Le(e)):{},ue(t||!e||!e.__esModule?J(r,"default",{value:e,enumerable:!0}):r,e)),Fe=e=>ue(J({},"__esModule",{value:!0}),e);var _=(e,t,r)=>new Promise((n,a)=>{var i=s=>{try{u(r.next(s))}catch(f){a(f)}},o=s=>{try{u(r.throw(s))}catch(f){a(f)}},u=s=>s.done?n(s.value):Promise.resolve(s.value).then(i,o);u((r=r.apply(e,t)).next())});var bt={};Oe(bt,{ParsingError:()=>q,RenderError:()=>E,UnimplementedError:()=>C,UnsupportedError:()=>l,everyTarget:()=>I,flattenTargets:()=>G,formatCurl:()=>_t,formatHttp:()=>St,getParsingErrorHint:()=>M,processSql:()=>Ve,renderHttp:()=>xt,renderSupabaseJs:()=>Rt,sentenceCase:()=>me,someFilter:()=>z,someTarget:()=>R,supportedAggregateFunctions:()=>k});module.exports=Fe(bt);var q=class extends Error{constructor(r,n){super(me(r));this.hint=n;this.name="ParsingError"}},C=class extends Error{constructor(){super(...arguments);this.name="UnimplementedError"}},l=class extends Error{constructor(r,n){super(r);this.hint=n;this.name="UnsupportedError"}},E=class extends Error{constructor(r,n){super(r);this.renderer=n;this.name="RenderError"}};function me(e){return e[0].toUpperCase()+e.slice(1)}function M(e){switch(e){case'syntax error at or near "from"':return"Did you leave a trailing comma in the select target list?";case'syntax error at or near "where"':return"Do you have an incomplete join in the FROM clause?";default:}}var he=require("libpg-query");function v(e,t){if(e.A_Expr.name.length>1)throw new l("Only one operator name supported per expression");let[r]=e.A_Expr.name,n=r.String.sval;if(!["->","->>"].includes(n))throw new l("Invalid JSON operator");let a,i,o;if("A_Const"in e.A_Expr.lexpr){if("fval"in e.A_Expr.lexpr.A_Const)throw new l("Invalid JSON path");i=N(e.A_Expr.lexpr)}else if("A_Expr"in e.A_Expr.lexpr){let{column:u}=v(e.A_Expr.lexpr,t);i=u}else if("ColumnRef"in e.A_Expr.lexpr)i=w(e.A_Expr.lexpr.ColumnRef.fields,t);else throw new l("Invalid JSON path");if("A_Const"in e.A_Expr.rexpr){if("fval"in e.A_Expr.rexpr.A_Const)throw new l("Invalid JSON path");o=N(e.A_Expr.rexpr)}else if("TypeCast"in e.A_Expr.rexpr)if(a=Q(e.A_Expr.rexpr.TypeCast.typeName.names),"A_Const"in e.A_Expr.rexpr.TypeCast.arg)if("sval"in e.A_Expr.rexpr.TypeCast.arg.A_Const)o=e.A_Expr.rexpr.TypeCast.arg.A_Const.sval.sval;else throw new l("Invalid JSON path");else throw new l("Invalid JSON path");else throw new l("Invalid JSON path");return{type:"column-target",column:`${i}${n}${o}`,cast:a}}function w(e,t,r="dot"){let n=e.map(u=>{if("String"in u)return u.String.sval;if("A_Star"in u)return"*";{let[s]=Object.keys(u);throw new l(`Unsupported internal type '${s}' for data type names`)}}),[a]=n.slice(-2,-1),[i]=n.slice(-1),o=t.joined.find(u=>{var s;return((s=u.alias)!=null?s:u.relation)===a});if(!a||a===t.primary.reference)return i;if(o){let u=o.flatten?o.relation:a;if(r==="dot")return[u,i].join(".");if(r==="parenthesis")return`${u}(${i})`;throw new Error(`Unknown render syntax '${r}'`)}else{let u=[a,i].join(".");throw new l(`Found foreign column '${u}' without a join to that relation`,"Did you forget to join that relation or alias it to something else?")}}function Q(e){let[t,...r]=e;if(t.String.sval==="pg_catalog"&&r.length===1){let[n]=r;switch(n.String.sval){case"int2":return"smallint";case"int4":return"int";case"int8":return"bigint";case"float8":return"float";default:return n.String.sval}}else{if(r.length>0)throw new l("Casts can only reference data types by their unqualified name (not schema-qualified)");return t.String.sval}}function N(e){var t;if("sval"in e.A_Const)return e.A_Const.sval.sval;if("ival"in e.A_Const)return(t=e.A_Const.ival.ival)!=null?t:0;if("fval"in e.A_Const)return parseFloat(e.A_Const.fval.fval);throw new l("Constant values must be a string, integer, or float")}function G(e){return e.flatMap(t=>{let{type:r}=t;if(r==="column-target"||r==="aggregate-target")return t;if(r==="embedded-target")return[t,...G(t.targets)];throw new l(`Unknown target type '${r}'`)})}function z(e,t){let{type:r}=e;if(r==="column")return t(e);if(r==="logical")return e.values.some(n=>z(n,t));throw new l(`Unknown filter type '${r}'`)}function I(e,t,r){return e.every(n=>{let{type:a}=n;if(a==="column-target"||a==="aggregate-target")return t(n,r);if(a==="embedded-target")return I(n.targets,t,n);throw new l(`Unknown target type '${a}'`)})}function R(e,t,r){return e.some(n=>{let{type:a}=n;if(a==="column-target"||a==="aggregate-target")return t(n,r);if(a==="embedded-target")return R(n.targets,t,n);throw new l(`Unknown target type '${a}'`)})}function fe(e,t,r){var a;let n=(a=e.map(i=>w(i.ColumnRef.fields,r)))!=null?a:[];if(!n.every(i=>R(t,(o,u)=>"column"in o?(u?[u.alias&&!u.flatten?u.alias:u.relation,o.column]:[o.column]).join(".")===i:!1)))throw new l("Every group by column must also exist as a select target");if(R(t,i=>i.type==="aggregate-target")&&!I(t,(i,o)=>{if(i.type==="aggregate-target")return!0;let s=(o?[o.alias&&!o.flatten?o.alias:o.relation,i.column]:[i.column]).join(".");return n.some(f=>s===f)}))throw new l("Every non-aggregate select target must also exist in a group by clause");if(n.length>0&&!R(t,i=>i.type==="aggregate-target"))throw new l("There must be at least one aggregate function in the select target list when using group by")}function K(e,t){if("A_Expr"in e){let r;if(e.A_Expr.name.length>1)throw new l("Only one operator name supported per expression");let n=e.A_Expr.kind,[a]=e.A_Expr.name,i=a.String.sval.toLowerCase(),o=je(n,i);if("A_Expr"in e.A_Expr.lexpr)try{r=v(e.A_Expr.lexpr,t).column}catch(u){throw new l("Left side of WHERE clause must be a column")}else if("ColumnRef"in e.A_Expr.lexpr){let{fields:u}=e.A_Expr.lexpr.ColumnRef;r=w(u,t)}else{if("TypeCast"in e.A_Expr.lexpr)throw new l("Casting is not supported in the WHERE clause");if("FuncCall"in e.A_Expr.lexpr){let u=w(e.A_Expr.lexpr.FuncCall.funcname,t);if(o==="fts")if(u==="to_tsvector"){if(!e.A_Expr.lexpr.FuncCall.args||e.A_Expr.lexpr.FuncCall.args.length!==1)throw new l(`${u} requires 1 column argument`);let[s]=e.A_Expr.lexpr.FuncCall.args;if("A_Expr"in s)try{r=v(s,t).column}catch(f){throw new l(`${u} requires a column argument`)}else if("ColumnRef"in s){let{fields:f}=s.ColumnRef;r=w(f,t)}else throw"TypeCast"in s?new l("Casting is not supported in the WHERE clause"):new l(`${u} requires a column argument`)}else throw new l("Only 'to_tsvector' function allowed on left side of text search operator");else throw new l("Left side of WHERE clause must be a column")}else throw new l("Left side of WHERE clause must be a column")}if(o==="eq"||o==="neq"||o==="gt"||o==="gte"||o==="lt"||o==="lte"){if(!("A_Const"in e.A_Expr.rexpr))throw new l(`Right side of WHERE clause '${i}' expression must be a constant`,"Did you forget to wrap your value in single quotes?");let u=N(e.A_Expr.rexpr);return{type:"column",column:r,operator:o,negate:!1,value:u}}else if(o==="between"||o==="between symmetric"||o==="not between"||o==="not between symmetric"){if(!("List"in e.A_Expr.rexpr)||e.A_Expr.rexpr.List.items.length!==2)throw new l(`Right side of WHERE clause '${i}' expression must contain two constants`);let[u,s]=e.A_Expr.rexpr.List.items.map(h=>N(h));if(o.includes("symmetric")){if(typeof u!="number"||typeof s!="number")throw new l("BETWEEN SYMMETRIC is only supported with number values");if(u>s){let h=s;s=u,u=h}}let f={type:"column",column:r,operator:"gte",negate:!1,value:u},m={type:"column",column:r,operator:"lte",negate:!1,value:s};return{type:"logical",operator:"and",negate:o.includes("not"),values:[f,m]}}else if(o==="like"||o==="ilike"||o==="match"||o==="imatch"){if(!("A_Const"in e.A_Expr.rexpr)||!("sval"in e.A_Expr.rexpr.A_Const))throw new l(`Right side of WHERE clause '${o}' expression must be a string constant`);let u=e.A_Expr.rexpr.A_Const.sval.sval;return{type:"column",column:r,operator:o,negate:!1,value:u}}else if(o==="in"){if(!("List"in e.A_Expr.rexpr)||!e.A_Expr.rexpr.List.items.every(s=>"A_Const"in s))throw new l(`Right side of WHERE clause '${o}' expression must be a list of constants`);let u=e.A_Expr.rexpr.List.items.map(s=>N(s));return{type:"column",column:r,operator:o,negate:!1,value:u}}else if(o==="fts"){let u=["to_tsquery","plainto_tsquery","phraseto_tsquery","websearch_to_tsquery"];if(!("FuncCall"in e.A_Expr.rexpr))throw new l(`Right side of WHERE clause '${i}' expression must be one of these functions: ${u.join(", ")}`);let s=w(e.A_Expr.rexpr.FuncCall.funcname,t);if(!u.includes(s))throw new l(`Right side of WHERE clause '${i}' expression must be one of these functions: ${u.join(", ")}`);if(!e.A_Expr.rexpr.FuncCall.args||e.A_Expr.rexpr.FuncCall.args.length===0||e.A_Expr.rexpr.FuncCall.args.length>2)throw new l(`${s} requires 1 or 2 arguments`);let f=e.A_Expr.rexpr.FuncCall.args.map(A=>{if(!("A_Const"in A)||!("sval"in A.A_Const))throw new l(`${s} only accepts text arguments`);return A.A_Const.sval.sval}),[m]=f.slice(-2,-1),[h]=f.slice(-1),x=Je(s);return{type:"column",column:r,operator:x,config:m,value:h,negate:!1}}else throw new l(`Unsupported operator '${i}'`)}else if("NullTest"in e){let{fields:r}=e.NullTest.arg.ColumnRef,n=w(r,t),a=e.NullTest.nulltesttype==="IS_NOT_NULL";return{type:"column",column:n,operator:"is",negate:a,value:null}}else if("BoolExpr"in e){let r;if(e.BoolExpr.boolop==="AND_EXPR")r="and";else if(e.BoolExpr.boolop==="OR_EXPR")r="or";else if(e.BoolExpr.boolop==="NOT_EXPR")r="not";else throw new l(`Unknown boolop '${e.BoolExpr.boolop}'`);let n=e.BoolExpr.args.map(a=>K(a,t));if(r==="not"){if(n.length>1)throw new l(`NOT expressions must have only 1 child, but received ${n.length} children`);let[a]=n;return a.negate=!0,a}return{type:"logical",operator:r,negate:!1,values:n}}else throw new l("The WHERE clause must contain an expression")}function je(e,t){switch(e){case"AEXPR_OP":switch(t){case"=":return"eq";case"<>":return"neq";case">":return"gt";case">=":return"gte";case"<":return"lt";case"<=":return"lte";case"~":return"match";case"~*":return"imatch";case"@@":return"fts";default:throw new l(`Unsupported operator '${t}'`)}case"AEXPR_BETWEEN":case"AEXPR_BETWEEN_SYM":case"AEXPR_NOT_BETWEEN":case"AEXPR_NOT_BETWEEN_SYM":switch(t){case"between":return"between";case"between symmetric":return"between symmetric";case"not between":return"not between";case"not between symmetric":return"not between symmetric";default:throw new l(`Unsupported operator '${t}'`)}case"AEXPR_LIKE":switch(t){case"~~":return"like";default:throw new l(`Unsupported operator '${t}'`)}case"AEXPR_ILIKE":switch(t){case"~~*":return"ilike";default:throw new l(`Unsupported operator '${t}'`)}case"AEXPR_IN":switch(t){case"=":return"in";default:throw new l(`Unsupported operator '${t}'`)}}}function Je(e){switch(e){case"to_tsquery":return"fts";case"plainto_tsquery":return"plfts";case"phraseto_tsquery":return"phfts";case"websearch_to_tsquery":return"wfts";default:throw new l(`Function '${e}' not supported for full-text search`)}}function pe(e){let t,r;if(e.SelectStmt.limitCount){if(!("ival"in e.SelectStmt.limitCount.A_Const))throw new l("Limit count must be an integer");t=e.SelectStmt.limitCount.A_Const.ival.ival}if(e.SelectStmt.limitOffset){if(!("ival"in e.SelectStmt.limitOffset.A_Const))throw new l("Limit offset must be an integer");r=e.SelectStmt.limitOffset.A_Const.ival.ival}if(!(t===void 0&&r===void 0))return{count:t,offset:r}}function ce(e,t){return e.map(r=>{let n;if("A_Expr"in r.SortBy.node)try{n=v(r.SortBy.node,t).column}catch(o){throw new l("ORDER BY clause must reference a column")}else if("ColumnRef"in r.SortBy.node){let{fields:o}=r.SortBy.node.ColumnRef;n=w(o,t,"parenthesis")}else throw"TypeCast"in r.SortBy.node?new l("Casting is not supported in the ORDER BY clause"):new l("ORDER BY clause must reference a column");let a=qe(r.SortBy.sortby_dir),i=Ie(r.SortBy.sortby_nulls);return{column:n,direction:a,nulls:i}})}function qe(e){switch(e){case"SORTBY_ASC":return"asc";case"SORTBY_DESC":return"desc";case"SORTBY_DEFAULT":return;default:throw new l(`Unknown sort by direction '${e}'`)}}function Ie(e){switch(e){case"SORTBY_NULLS_FIRST":return"first";case"SORTBY_NULLS_LAST":return"last";case"SORTBY_NULLS_DEFAULT":return;default:throw new l(`Unknown sort by nulls '${e}'`)}}var k=["avg","count","max","min","sum"];function ge(e){var s,f;if(!e.SelectStmt.fromClause)throw new l("The query must have a from clause");if(e.SelectStmt.fromClause.length>1)throw new l("Only one FROM source is supported");if(e.SelectStmt.withClause)throw new l("CTEs are not supported");if(e.SelectStmt.distinctClause)throw new l("SELECT DISTINCT is not supported");if(e.SelectStmt.havingClause)throw new l("The HAVING clause is not supported");let[t]=e.SelectStmt.fromClause,r=de(t),n=r.primary.name,a=Ue(e.SelectStmt.targetList,r);fe((s=e.SelectStmt.groupClause)!=null?s:[],a,r);let i=e.SelectStmt.whereClause?K(e.SelectStmt.whereClause,r):void 0,o=ce((f=e.SelectStmt.sortClause)!=null?f:[],r),u=pe(e);return{type:"select",from:n,targets:a,filter:i,sorts:o,limit:u}}function de(e){var t,r,n;if("RangeVar"in e)return{primary:{name:e.RangeVar.relname,alias:(t=e.RangeVar.alias)==null?void 0:t.aliasname,get reference(){var a;return(a=this.alias)!=null?a:this.name}},joined:[]};if("JoinExpr"in e){let a=Pe(e.JoinExpr.jointype),{primary:i,joined:o}=de(e.JoinExpr.larg),u=(r=e.JoinExpr.rarg.RangeVar.alias)==null?void 0:r.aliasname,s=u!=null?u:e.JoinExpr.rarg.RangeVar.relname,f=[i.reference,...o.map(y=>{var ae;return(ae=y.alias)!=null?ae:y.relation}),s];if(!("A_Expr"in e.JoinExpr.quals))throw new l("Join qualifier must be an expression comparing columns");let m,h,x=e.JoinExpr.quals.A_Expr;if(!("ColumnRef"in x.lexpr))throw new l("Left side of join qualifier must be a column");if(!x.lexpr.ColumnRef.fields.every(y=>"String"in y))throw new l("Left side column of join qualifier must contain String fields");let A=x.lexpr.ColumnRef.fields.map(y=>y.String.sval),[F]=A.slice(-2,-1),[re]=A.slice(-1);if(!F)m=i.reference;else if(f.includes(F))m=F;else if(F===s)m=s;else throw new l(`Left side of join qualifier references a different relation (${F}) than the join (${f.join(", ")})`);if(!("ColumnRef"in x.rexpr))throw new l("Right side of join qualifier must be a column");if(!x.rexpr.ColumnRef.fields.every(y=>"String"in y))throw new l("Right side column of join qualifier must contain String fields");let ne=x.rexpr.ColumnRef.fields.map(y=>y.String.sval),[j]=ne.slice(-2,-1),[oe]=ne.slice(-1);if(!j)h=i.reference;else if(f.includes(j))h=j;else if(j===s)h=s;else throw new l(`Right side of join qualifier references a different relation (${j}) than the join (${f.join(", ")})`);if(h===m)throw new l("Join qualifier cannot compare columns from same relation");if(h!==s&&m!==s)throw new l("Join qualifier must reference a column from the joined table");let[Ce]=x.name;if(Ce.String.sval!=="=")throw new l("Join qualifier operator must be '='");let V,W;h===s?(V={relation:m,column:re},W={relation:h,column:oe}):(W={relation:m,column:re},V={relation:h,column:oe});let ve={type:"embedded-target",relation:e.JoinExpr.rarg.RangeVar.relname,alias:(n=e.JoinExpr.rarg.RangeVar.alias)==null?void 0:n.aliasname,joinType:a,targets:[],flatten:!0,joinedColumns:{left:V,right:W}};return{primary:i,joined:[...o,ve]}}else{let[a]=Object.keys(e);throw new l(`Unsupported FROM clause type '${a}'`)}}function Ue(e,t){let n=e.map(i=>{let o=Z(i.ResTarget.val,t);return o.alias=i.ResTarget.name,o}).filter(i=>{if(i.type==="aggregate-target"&&!("column"in i))return!0;let o=i.column.split("."),[u]=o.slice(-2,-1),[s]=o.slice(-1);if(!u)return!0;if(u){let f=t.joined.find(m=>(m.alias&&!m.flatten?m.alias:m.relation)===u);if(!f)throw new l(`Found foreign column '${i.column}' in target list without a join to that relation`,"Did you forget to join that relation or alias it to something else?");return i.column=s,f.targets.push(i),!1}return!0}),a=t.joined.reduce((i,o)=>{if(o.joinedColumns.left.relation===t.primary.reference)return[...i,o];let u=t.joined.find(s=>{var f;return((f=s.alias)!=null?f:s.relation)===o.joinedColumns.left.relation});if(!u)throw new l(`Something went wrong, could not find parent embedded target for nested embedded target '${o.relation}'`);return u.targets.push(o),i},[]);return[...n,...a]}function Z(e,t){if("TypeCast"in e)return ke(e,t);if("ColumnRef"in e)return He(e,t);if("A_Expr"in e)return Be(e,t);if("FuncCall"in e)return De(e,t);throw new l("Only columns, JSON fields, and aggregates are supported as query targets")}function Pe(e){switch(e){case"JOIN_INNER":return"inner";case"JOIN_LEFT":return"left";default:throw new l(`Unsupported join type '${e}'`)}}function ke(e,t){let r=Q(e.TypeCast.typeName.names);if("A_Const"in e.TypeCast.arg)throw new l("Only columns, JSON fields, and aggregates are supported as query targets");let n=Z(e.TypeCast.arg,t),{type:a}=n;if(a==="aggregate-target")return b($({},n),{outputCast:r});if(a==="column-target")return b($({},n),{cast:r});throw new l(`Cannot process target with type '${a}'`)}function He(e,t){return{type:"column-target",column:w(e.ColumnRef.fields,t)}}function Be(e,t){try{return v(e,t)}catch(r){let n=r instanceof Error&&r.message==="Invalid JSON path"?"Did you forget to quote a JSON path?":void 0;throw new l("Expressions not supported as targets",n)}}function De(e,t){let r=w(e.FuncCall.funcname,t);if(!k.includes(r))throw new l(`Only the following aggregate functions are supported: ${JSON.stringify(k)}`);if(r==="count"&&!e.FuncCall.args&&e.FuncCall.agg_star)return{type:"aggregate-target",functionName:r};if(!e.FuncCall.args)throw new l(`Aggregate function '${r}' requires a column argument`);if(e.FuncCall.args&&e.FuncCall.args.length>1)throw new l("Aggregate functions only accept one argument");let[n]=e.FuncCall.args,a=Z(n,t);if(a.type==="aggregate-target")throw new l("Aggregate functions cannot contain another function");let u=a,{cast:i}=u,o=le(u,["cast"]);return b($({},o),{type:"aggregate-target",functionName:r,inputCast:i})}function Ve(e){return _(this,null,function*(){try{let t=yield(0,he.parseQuery)(e);if(t.stmts.length===0)throw new l("Expected a statement, but received none");if(t.stmts.length>1)throw new l("Expected a single statement, but received multiple");let[r]=t.stmts.map(n=>We(n));return r}catch(t){if(t instanceof Error&&"cursorPosition"in t){let r=M(t.message),n=new q(t.message,r);throw Object.assign(n,t),n}else throw t}})}function We({stmt:e}){if("SelectStmt"in e)return ge(e);if("InsertStmt"in e)throw new C("Insert statements are not yet implemented by the translator");if("UpdateStmt"in e)throw new C("Update statements are not yet implemented by the translator");if("DeleteStmt"in e)throw new C("Delete statements are not yet implemented by the translator");if("ExplainStmt"in e)throw new C("Explain statements are not yet implemented by the translator");{let[t]=Object.keys(e),r=t.replace(/Stmt$/,"");throw new l(`${r} statements are not supported`)}}var Ye=function(){function e(t,r){for(var n=0;n<r.length;n++){var a=r[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(t,a.key,a)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),Xe=Me(["",""],["",""]);function Me(e,t){return Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))}function Qe(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var Ge=function(){function e(){for(var t=this,r=arguments.length,n=Array(r),a=0;a<r;a++)n[a]=arguments[a];return Qe(this,e),this.tag=function(i){for(var o=arguments.length,u=Array(o>1?o-1:0),s=1;s<o;s++)u[s-1]=arguments[s];return typeof i=="function"?t.interimTag.bind(t,i):typeof i=="string"?t.transformEndResult(i):(i=i.map(t.transformString.bind(t)),t.transformEndResult(i.reduce(t.processSubstitutions.bind(t,u))))},n.length>0&&Array.isArray(n[0])&&(n=n[0]),this.transformers=n.map(function(i){return typeof i=="function"?i():i}),this.tag}return Ye(e,[{key:"interimTag",value:function(r,n){for(var a=arguments.length,i=Array(a>2?a-2:0),o=2;o<a;o++)i[o-2]=arguments[o];return this.tag(Xe,r.apply(void 0,[n].concat(i)))}},{key:"processSubstitutions",value:function(r,n,a){var i=this.transformSubstitution(r.shift(),n);return"".concat(n,i,a)}},{key:"transformString",value:function(r){var n=function(i,o){return o.onString?o.onString(i):i};return this.transformers.reduce(n,r)}},{key:"transformSubstitution",value:function(r,n){var a=function(o,u){return u.onSubstitution?u.onSubstitution(o,n):o};return this.transformers.reduce(a,r)}},{key:"transformEndResult",value:function(r){var n=function(i,o){return o.onEndResult?o.onEndResult(i):i};return this.transformers.reduce(n,r)}}]),e}(),p=Ge;var ze=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"";return{onEndResult:function(n){if(t==="")return n.trim();if(t=t.toLowerCase(),t==="start"||t==="left")return n.replace(/^\s*/,"");if(t==="end"||t==="right")return n.replace(/\s*$/,"");throw new Error("Side not supported: "+t)}}},c=ze;function Ke(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}else return Array.from(e)}var Ze=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"initial";return{onEndResult:function(n){if(t==="initial"){var a=n.match(/^[^\S\n]*(?=\S)/gm),i=a&&Math.min.apply(Math,Ke(a.map(function(u){return u.length})));if(i){var o=new RegExp("^.{"+i+"}","gm");return n.replace(o,"")}return n}if(t==="all")return n.replace(/^[^\S\n]+/gm,"");throw new Error("Unknown type: "+t)}}},d=Ze;var et=function(t,r){return{onEndResult:function(a){if(t==null||r==null)throw new Error("replaceResultTransformer requires at least 2 arguments.");return a.replace(t,r)}}},T=et;var tt=function(t,r){return{onSubstitution:function(a,i){if(t==null||r==null)throw new Error("replaceSubstitutionTransformer requires at least 2 arguments.");return a==null?a:a.toString().replace(t,r)}}},S=tt;var nt={separator:"",conjunction:"",serial:!1},ot=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:nt;return{onSubstitution:function(n,a){if(Array.isArray(n)){var i=n.length,o=t.separator,u=t.conjunction,s=t.serial,f=a.match(/(\n?[^\S\n]+)$/);if(f?n=n.join(o+f[1]):n=n.join(o+" "),u&&i>1){var m=n.lastIndexOf(o);n=n.slice(0,m)+(s?o:"")+" "+u+n.slice(m+1)}}return n}}},g=ot;var at=function(t){return{onSubstitution:function(n,a){if(t!=null&&typeof t=="string")typeof n=="string"&&n.includes(t)&&(n=n.split(t));else throw new Error("You need to specify a string character to split by.");return n}}},L=at;var we=function(t){return t!=null&&!Number.isNaN(t)&&typeof t!="boolean"},it=function(){return{onSubstitution:function(r){return Array.isArray(r)?r.filter(we):we(r)?r:""}}},H=it;var Ir=new p(g({separator:","}),d,c);var Wr=new p(g({separator:",",conjunction:"and"}),d,c);var Zr=new p(g({separator:",",conjunction:"or"}),d,c);var mn=new p(L(`
`),H,g,d,c);var Cn=new p(L(`
`),g,d,c,S(/&/g,"&"),S(/</g,"<"),S(/>/g,">"),S(/"/g,"""),S(/'/g,"'"),S(/`/g,"`"));var Ln=new p(T(/(?:\n(?:\s*))+/g," "),c);var Un=new p(T(/(?:\n\s*)/g,""),c);var Yn=new p(g({separator:","}),T(/(?:\s+)/g," "),c);var eo=new p(g({separator:",",conjunction:"or"}),T(/(?:\s+)/g," "),c);var lo=new p(g({separator:",",conjunction:"and"}),T(/(?:\s+)/g," "),c);var wo=new p(g,d,c);var vo=new p(g,T(/(?:\s+)/g," "),c);var Tt=new p(d,c),B=Tt;var Uo=new p(d("all"),c);function O(e,t){let r=t?" ".repeat(t.initialIndent):"",n=t?`
`:"";return e.map(a=>{if(a.type==="column-target"){let{column:i,alias:o,cast:u}=a,s=i;return o&&o!==i&&(s=`${o}:${s}`),u&&(s=`${s}::${u}`),s=`${r}${s}`,s}else if(a.type==="aggregate-target"&&!("column"in a)){let{functionName:i,alias:o,outputCast:u}=a,s=`${i}()`;return o&&(s=`${o}:${s}`),u&&(s=`${s}::${u}`),s=`${r}${s}`,s}else if(a.type==="aggregate-target"){let{column:i,alias:o,functionName:u,inputCast:s,outputCast:f}=a,m=i;return o&&o!==i&&(m=`${o}:${m}`),s&&(m=`${m}::${s}`),m=`${m}.${u}()`,f&&(m=`${m}::${f}`),m=`${r}${m}`,m}else if(a.type==="embedded-target"){let{relation:i,alias:o,joinType:u,targets:s,flatten:f}=a,m=i;return u==="inner"&&(m=`${m}!inner`),o&&o!==i&&!f&&(m=`${o}:${m}`),f&&(m=`...${m}`),s.length>0?m=`${r}${m}(${n}${O(s,t?b($({},t),{initialIndent:t.initialIndent+t.indent}):void 0)}${n}${r})`:m=`${r}${m}()`,m}}).join(","+n)}function ee(e,t=!0,r=","){let{type:n}=e,a=e.negate?"not.":"";if(n==="column")if(e.operator==="like"||e.operator==="ilike"){let i=t?e.value.replaceAll("%","*"):e.value;return[e.column,`${a}${e.operator}.${i}`]}else if(e.operator==="in"){let i=e.value.map(o=>o.toString().includes(",")?`"${o}"`:o).join(",");return[e.column,`${a}${e.operator}.(${i})`]}else if(e.operator==="fts"||e.operator==="plfts"||e.operator==="phfts"||e.operator==="wfts"){let i=e.config?`(${e.config})`:"";return[e.column,`${a}${e.operator}${i}.${e.value}`]}else return[e.column,`${a}${e.operator}.${e.value}`];else{if(n==="logical")return[`${a}${e.operator}`,`(${e.values.map(i=>D(i,t,r)).join(r)})`];throw new Error(`Unknown filter type '${n}'`)}}function D(e,t=!0,r=","){let[n,a]=ee(e,t,r),{type:i}=e;if(i==="column")return`${n}.${a}`;if(i==="logical")return`${n}${a}`;throw new Error(`Unknown filter type '${i}'`)}var Te=["*","(",")",",",":","!",">","-","[","]"];function ye(e,t=Te){return xe(e.toString(),t)}function te(e,t=Te){return xe(encodeURIComponent(e),t)}function xe(e,t){let r=e;for(let n of t){let a=n.charCodeAt(0).toString(16).toUpperCase();r=r.replaceAll(`%${a}`,n)}return r}function xt(e){return _(this,null,function*(){switch(e.type){case"select":return Et(e);default:throw new E(`Unsupported statement type '${e.type}'`,"http")}})}function Et(e){return _(this,null,function*(){let{from:t,targets:r,filter:n,sorts:a,limit:i}=e,o=new URLSearchParams;if(r.length>0){let[s]=r;(s.type!=="column-target"||s.column!=="*"||r.length!==1)&&o.set("select",O(r))}if(n&&Ee(o,n),a){let s=[];for(let f of a){let m=f.column;f.direction&&(m+=`.${f.direction}`),f.nulls&&(m+=`.nulls${f.nulls}`),s.push(m)}s.length>0&&o.set("order",s.join(","))}i&&(i.count!==void 0&&o.set("limit",i.count.toString()),i.offset!==void 0&&o.set("offset",i.offset.toString()));let u=`/${t}`;return{method:"GET",path:u,params:o,get fullPath(){return Array.from(o).length>0?`${u}?${ye(o)}`:u}}})}function Ee(e,t){let{type:r}=t;if(r==="logical"&&t.operator==="and"&&!t.negate)for(let n of t.values)Ee(e,n);else{let[n,a]=ee(t);e.append(n,a)}}function St(e,t){let{method:r,fullPath:n}=t,a=new URL(e);return B`
${r} ${a.pathname}${n} HTTP/1.1
Host: ${a.host}
`}function _t(e,t){let{method:r,path:n,params:a}=t,i=[],o=new URL(e),u=(o.origin+o.pathname).replace(/\/+$/,""),s=a.size>0?"-G ":"";if(r==="GET"){i.push(`curl ${s}${u}${n}`);for(let[f,m]of a)i.push(` -d "${te(f)}=${te(m)}"`)}return i.join(` \\
`)}var Ct=X(require("prettier/plugins/babel")),vt=X(require("prettier/plugins/estree")),Se=X(require("prettier/standalone"));function Rt(e){return _(this,null,function*(){switch(e.type){case"select":return At(e);default:throw new E(`Unsupported statement type '${e.type}'`,"supabase-js")}})}function At(e){return _(this,null,function*(){let{from:t,targets:r,filter:n,sorts:a,limit:i}=e,o=["const { data, error } = await supabase",`.from('${t}')`];if(r.length>0){let[s]=r;s.type==="column-target"&&s.column==="*"&&r.length===1?o.push(".select()"):r.length>1?o.push(`.select(
\`
${O(r,{initialIndent:4,indent:2})}
\`
)`):o.push(`.select(${JSON.stringify(O(r))})`)}if(n&&_e(o,n),a)for(let s of a)if(!s.direction&&!s.nulls)o.push(`.order(${JSON.stringify(s.column)})`);else{let f={ascending:s.direction?s.direction==="asc":void 0,nullsFirst:s.nulls?s.nulls==="first":void 0};o.push(`.order(${JSON.stringify(s.column)}, ${JSON.stringify(f)})`)}if(i)if(i.count!==void 0&&i.offset===void 0)o.push(`.limit(${i.count})`);else{if(i.count===void 0&&i.offset!==void 0)throw new E("supabase-js doesn't support an offset without a limit","supabase-js");i.count!==void 0&&i.offset!==void 0&&o.push(`.range(${i.offset}, ${i.offset+i.count})`)}return{code:(yield Se.format(o.join(`
`),{parser:"babel",plugins:[Ct,vt],printWidth:40,semi:!1,singleQuote:!0,trailingComma:"all"})).trim()}})}function _e(e,t){let{type:r}=t;if(t.negate){if(t.type==="column")if(t.operator==="fts"||t.operator==="plfts"||t.operator==="phfts"||t.operator==="wfts"){let n=t.config?`(${t.config})`:"";e.push(`.not(${JSON.stringify(t.column)}, ${JSON.stringify(`${t.operator}${n}`)}, ${JSON.stringify(t.value)})`)}else e.push(`.not(${JSON.stringify(t.column)}, ${JSON.stringify(t.operator)}, ${JSON.stringify(t.value)})`);else t.type==="logical"&&e.push(`.or(${JSON.stringify(D(t,!1,", "))})`);return}if(r==="column")if(t.operator==="fts"||t.operator==="plfts"||t.operator==="phfts"||t.operator==="wfts"){let n=t.operator!=="fts"||t.config!==void 0?`, ${JSON.stringify({type:$t(t.operator),config:t.config})}`:"";e.push(`.textSearch(${JSON.stringify(t.column)}, ${JSON.stringify(t.value)}${n})`)}else e.push(`.${t.operator}(${JSON.stringify(t.column)}, ${JSON.stringify(t.value)})`);else if(r==="logical")if(t.operator==="and")for(let n of t.values)_e(e,n);else t.operator==="or"&&e.push(`.or(${JSON.stringify(t.values.map(n=>D(n,!1,", ")).join(", "))})`);else throw new E(`Unknown filter type '${r}'`,"supabase-js")}function $t(e){switch(e){case"plfts":return"plain";case"phfts":return"phrase";case"wfts":return"websearch";default:return}}0&&(module.exports={ParsingError,RenderError,UnimplementedError,UnsupportedError,everyTarget,flattenTargets,formatCurl,formatHttp,getParsingErrorHint,processSql,renderHttp,renderSupabaseJs,sentenceCase,someFilter,someTarget,supportedAggregateFunctions});
//# sourceMappingURL=index.js.map