prostgles-types 4.0.310 → 4.0.312

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/JSONBSchemaValidation/getJSONBSchemaTSTypes.d.ts.map +1 -1
  2. package/dist/JSONBSchemaValidation/getJSONBSchemaTSTypes.js +2 -1
  3. package/dist/JSONBSchemaValidation/getJSONBSchemaTSTypes.js.map +1 -1
  4. package/dist/auditTable.d.ts +32 -0
  5. package/dist/auditTable.d.ts.map +1 -0
  6. package/dist/auditTable.js +33 -0
  7. package/dist/auditTable.js.map +1 -0
  8. package/dist/auth.d.ts +8 -0
  9. package/dist/auth.d.ts.map +1 -1
  10. package/dist/fileTable.d.ts +53 -0
  11. package/dist/fileTable.d.ts.map +1 -0
  12. package/dist/fileTable.js +39 -0
  13. package/dist/fileTable.js.map +1 -0
  14. package/dist/index.d.ts +4 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +4 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/index_umd.js +1 -1
  19. package/dist/jobControl.d.ts +2 -1
  20. package/dist/jobControl.d.ts.map +1 -1
  21. package/dist/jobTable.d.ts +149 -0
  22. package/dist/jobTable.d.ts.map +1 -0
  23. package/dist/jobTable.js +70 -0
  24. package/dist/jobTable.js.map +1 -0
  25. package/dist/tableRowFromColumnDefinitions.d.ts +79 -0
  26. package/dist/tableRowFromColumnDefinitions.d.ts.map +1 -0
  27. package/dist/tableRowFromColumnDefinitions.js +3 -0
  28. package/dist/tableRowFromColumnDefinitions.js.map +1 -0
  29. package/lib/JSONBSchemaValidation/getJSONBSchemaTSTypes.ts +2 -1
  30. package/lib/auditTable.ts +38 -0
  31. package/lib/auth.ts +11 -0
  32. package/lib/fileTable.ts +62 -0
  33. package/lib/index.ts +4 -0
  34. package/lib/jobControl.ts +3 -2
  35. package/lib/jobTable.ts +95 -0
  36. package/lib/tableRowFromColumnDefinitions.ts +220 -0
  37. package/package.json +1 -1
package/dist/index_umd.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(Object(this||window),()=>(()=>{"use strict";var e={994(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.DATA_TYPES=t.PrimitiveArrayTypes=t.PrimitiveTypes=t.PrimitiveTypesObj=void 0;const i=n(472);t.PrimitiveTypesObj={boolean:1,number:1,integer:1,string:1,Date:1,time:1,timestamp:1,Uint8Array:1,Blob:1,FileLike:1,any:1,unknown:1},t.PrimitiveTypes=(0,i.getKeys)(t.PrimitiveTypesObj),t.PrimitiveArrayTypes=t.PrimitiveTypes.map(e=>`${e}[]`),t.DATA_TYPES=[...t.PrimitiveTypes,...t.PrimitiveArrayTypes]},897(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.assertJSONBObjectAgainstSchema=t.validateJSONBObjectAgainstSchema=t.getJSONBSchemaValidationErrorAsync=t.getJSONBSchemaValidationError=t.getJSONBObjectSchemaValidationError=t.getFieldTypeObj=void 0;const i=n(472),r=n(441),o=n(704),s=e=>null==e||["number","string","boolean"].includes(typeof e),a=e=>{if(!(0,i.isObject)(e))return!1;const t=(0,o.safeGetKeys)(e);return!!t.length&&t.every(t=>s((0,o.safeGetProperty)(e,t)))};t.getFieldTypeObj=e=>"string"==typeof e?{type:e}:e;const l=e=>e instanceof Blob||"undefined"!=typeof Buffer&&e instanceof Buffer||"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer,c={string:e=>"string"==typeof e,number:e=>"number"==typeof e&&Number.isFinite(e),integer:e=>"number"==typeof e&&Number.isInteger(e),boolean:e=>"boolean"==typeof e,time:e=>"string"==typeof e,timestamp:e=>"string"==typeof e,any:e=>"function"!=typeof e&&"symbol"!=typeof e,unknown:e=>"function"!=typeof e&&"symbol"!=typeof e,Date:e=>"string"==typeof e,Uint8Array:l,Blob:l,FileLike:(e,t)=>{if("FileLike"!==t.type)throw new Error("FileLike type must have type 'FileLike'");const n=(0,i.isObject)(e)&&"string"==typeof e.name&&"string"==typeof e.type&&l(e.data);if(n&&t.mimeTypes&&!Object.keys(t.mimeTypes).some(t=>e.type===t))throw new Error(`Invalid FileLike type. Expected one of: ${Object.keys(t.mimeTypes).join(", ")}`);return n}},p=(0,i.getKeys)(c),u=(e,n,l=[],m,f)=>{const y=`${l.join(".")} is of invalid type. Expecting ${d(n).replaceAll("\n","")}`,g=(0,t.getFieldTypeObj)(n),{type:h,allowedValues:b,nullable:v,optional:O}=g;if(v&&null===e)return;if(O&&void 0===e)return;if(b){if("string"!=typeof h)throw new Error("allowedValues is only supported for primitive types");const t=h.endsWith("[]"),n=t&&Array.isArray(e)?e:[e],r=b.map(e=>(0,i.isObject)(e)?e.value:e);for(const[e,i]of n.entries())if(!r.includes(i))return`${t?`${l.join(".")}[${e}]`:l.join(".")} is of invalid type. Expecting ${r.map(e=>"string"==typeof e?JSON.stringify(e):String(e)).join(" | ")} But got ${JSON.stringify(i)}`}if(h){if((0,i.isObject)(h)){if(!(0,i.isObject)(e))return y;for(const t of(0,o.safeGetKeys)(h)){const n=(0,o.safeGetProperty)(h,t);if(!((0,i.isObject)(n)&&n.optional||(0,o.safeHasOwn)(e,t)))return`${[...l,t].join(".")} is missing but required`;const r=u((0,o.safeGetProperty)(e,t),n,[...l,t],m,f);if(void 0!==r)return r}if(!m?.allowExtraProperties){const t=(0,o.safeGetKeys)(e),n=(0,o.safeGetKeys)(h),i=t.filter(e=>!n.includes(e));if(i.length)return`${l.join(".")} has extra properties: ${i.join(", ")}`}return}if(h.includes("Lookup")){if(!f)throw new Error("Lookup types are not supported for validation");const t=h.endsWith("[]");if(t!==Array.isArray(e))return y;const n=h.replace("[]","");return(t?e:[e]).every(e=>"RowLookup"===n?a(e):"ValueLookup"===n?s(e):"TableLookup"===n?"string"==typeof e:(0,i.isObject)(e)&&"string"==typeof(0,o.safeGetProperty)(e,"table")&&"string"==typeof(0,o.safeGetProperty)(e,"column")&&(0,o.safeGetKeys)(e).every(e=>"table"===e||"column"===e))?void f.push({schema:g,value:e,path:l}):y}const{validator:t}=((e,t)=>{const n=(e=>{if("string"==typeof e&&e.endsWith("[]")){const t=e.slice(0,-2);if(!(0,r.includes)(p,t))throw new Error(`Invalid array field type ${e}`);return t}})(e);if(n){const e=c[n];return{isArray:!0,validator:n=>Array.isArray(n)&&n.every(n=>e(n,t))}}const i=c[e];if(!i)throw new Error(`Unknown field type ${e}`);return{isArray:!1,validator:i}})(h,g);return t(e,g)?void 0:y}if(g.tuple){const t=g.tuple;if(!Array.isArray(e))return y+`[${t.map(e=>d(e)).join(", ")}]`;if(e.length!==t.length)return`${l.length?l.join("."):"value"} is of invalid tuple length. Expecting ${t.length} elements but got ${e.length}`;for(let n=0;n<t.length;n++){const i=u(e[n],t[n],[...l,`${n}`],m,f);if(void 0!==i)return i}return}if(g.enum){const t=[];return g.nullable&&t.push(null),g.optional&&t.push(void 0),g.enum.includes(e)?void 0:y}const _=g.arrayOf??(g.arrayOfType?{type:g.arrayOfType}:void 0);if(_){if(!Array.isArray(e))return y+" an array";const t=e.map((e,t)=>u(e,_,[...l,`${t}`],m,f)).filter(i.isDefined)[0];return void 0!==t?`${y}. Error at index ${l.length>0?l.join(".")+".":""}\n\n${t}`:void 0}const S=g.oneOf??g.oneOfType?.map(e=>({type:e}));if(S){if(!S.length)return y+"to not be empty";let t;if(S.find(n=>{const i=f?.length,r=u(e,n,l,m,f);return void 0!==r&&void 0!==i&&(f.length=i),t??(t=r),void 0===r}))return;return y}if(g.record){const{keysEnum:t,partial:n,values:r}=g.record;if(!(0,i.isObject)(e))return y+"object";if(n&&(0,i.isEmpty)(e))return;const s=(0,i.getKeys)(e),a=n?void 0:t?.find(e=>!s.includes(e));if(void 0!==a)return`${y} to have key ${a}`;const c=t&&s.filter(e=>!t.includes(e));if(c?.length)return`${y} has extra keys: ${c}`;if(r)for(const t of(0,o.safeGetKeys)(e)){const n=(0,o.safeGetProperty)(e,t),i=u(n,r,[...l,t],m,f);if(void 0!==i)return`${i}`}return}return`Could not validate field type. Some logic might be missing: ${JSON.stringify(g)}`},d=e=>{const n=(0,t.getFieldTypeObj)(e),{type:r,nullable:o,optional:s,record:a}=n,l=n.oneOf??n.oneOfType?.map(e=>({type:e})),c=[];if(o&&c.push("null"),s&&c.push("undefined"),"string"==typeof r)c.push(r);else if(r&&(0,i.isObject)(r)){const e=[];Object.entries(r).forEach(([t,n])=>{e.push(`${t}: ${d(n)}`)}),c.push(`{ ${e.join("; ")} }`)}if(n.enum?.forEach(e=>{null===e?c.push("null"):void 0===e?c.push("undefined"):"string"==typeof e?c.push(JSON.stringify(e)):c.push(e)}),l?.forEach(e=>{const t=d(e);c.push(t)}),a){const{keysEnum:e,partial:t,values:n}=a,i=t?"?":"",r=n?d(n):"any";e?c.push(`{ [${e.join(" | ")}]${i}: ${r} }`):c.push(`{ [key: string]${i}: ${r} }`)}return c.join(" | ")};t.getJSONBObjectSchemaValidationError=(e,t,n="input",r=!1,o)=>{if(void 0===t&&!r)return{error:`Expecting ${n} to be defined`};if(!(0,i.isObject)(t))return{error:`Expecting ${n} to be an object`};const s=u(t,{type:e},[],o);return s?{error:s}:{data:t}},t.getJSONBSchemaValidationError=(e,t,n)=>{const i=u(t,e,void 0,n);return i?{error:i}:{data:t}};const m=(e,t)=>[...e,...void 0===t?[]:[String(t)]].join(".")||"value",f=async(e,t)=>{const{schema:n,path:i}=e,r=n.type.endsWith("[]"),o=r?e.value:[e.value];for(const[e,l]of o.entries()){const o=m(i,r?e:void 0);if("TableLookup"===n.type||"TableLookup[]"===n.type){if(!t.has(l))return`${o} references an unknown table ${JSON.stringify(l)}`;continue}if("ColumnLookup"===n.type||"ColumnLookup[]"===n.type){const e=l;if(n.filter?.table&&e.table!==n.filter.table)return`${o} references a column that does not match the lookup filter`;const i=t.get(e.table);if(!i)return`${o} references an unknown table ${JSON.stringify(e.table)}`;if("function"!=typeof i.getColumns)throw new Error(`Cannot validate ColumnLookup: table ${JSON.stringify(e.table)} does not expose getColumns`);const r=(await i.getColumns()).find(({name:t})=>t===e.column);if(!r||n.filter?.tsDataType&&r.tsDataType!==n.filter.tsDataType||n.filter?.udt_name&&r.udt_name!==n.filter.udt_name)return`${o} references an unknown or disallowed column ${JSON.stringify(`${e.table}.${e.column}`)}`;continue}const c=n,p=t.get(c.table);if(!p)throw new Error(`Cannot validate ${c.type}: table ${JSON.stringify(c.table)} does not expose findOne`);const u="RowLookup"===c.type||"RowLookup[]"===c.type;if(u&&!a(l)||!u&&!s(l))return`${o} contains a non-primitive lookup value`;const d=u?l:{[c.column]:l},f=c.filter?{$and:[c.filter,d]}:d;if(!await(p?.findOne?.(f)))return`${o} does not reference an existing row in ${JSON.stringify(c.table)}`}};t.getJSONBSchemaValidationErrorAsync=async(e,t,n,i)=>{const r=[],o=u(t,e,void 0,i,r);if(o)return{error:o};for(const e of r){const t=await f(e,n);if(t)return{error:t}}return{data:t}},t.validateJSONBObjectAgainstSchema=(e,n,i,r=!1)=>{const{error:o}=(0,t.getJSONBObjectSchemaValidationError)(e,n,i,r);return void 0===o},t.assertJSONBObjectAgainstSchema=(e,n,i,r=!1)=>{const{error:o}=(0,t.getJSONBObjectSchemaValidationError)(e,n,i,r);if(o)throw new Error(o)}},699(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.getJSONSchemaObject=void 0,t.getJSONBSchemaAsJSONSchema=function(e,n,i){return(0,t.getJSONSchemaObject)(i,{id:`${e}.${n}`})};const i=n(472),r=n(704),o=e=>{if(!e)return;const t=e.endsWith("[]")?e.slice(0,-2):e;return{type:"integer"===t?"integer":"boolean"===t?"boolean":"number"===t?"number":"any"===t||"unknown"===t||t.endsWith("Lookup")||"Uint8Array"===t||"Blob"===t||"FileLike"===t?void 0:"string",isArray:e.endsWith("[]")}};t.getJSONSchemaObject=(e,n)=>{const{type:s,arrayOf:a,arrayOfType:l,description:c,nullable:p,oneOf:u,oneOfType:d,title:m,record:f,tuple:y,...g}="string"==typeof e?{type:e}:e;let h={};const b={...(g.enum||g.allowedValues?.length&&("string"!=typeof s||!s.endsWith("[]")))&&{enum:g.allowedValues?.slice(0)??g.enum.slice(0)},...!!c&&{description:c},...!!m&&{title:m}};if(g.enum?.length){const e=typeof g.enum[0];b.type="number"===e?"number":"boolean"===e?"boolean":"string"}if("string"==typeof s||a||l){if(s&&"string"!=typeof s)throw"Not expected";h=a||l||s?.endsWith("[]")?{type:"array",items:a||l?(0,t.getJSONSchemaObject)(a||{type:l}):s?.startsWith("any")?{type:void 0}:{type:o(s)?.type,...g.allowedValues&&{enum:g.allowedValues.slice(0)}}}:{type:o(s)?.type}}else if((0,i.isObject)(s))h={type:"object",required:(0,r.safeGetKeys)(s).filter(e=>{const t=s[e];return"string"==typeof t||!t.optional}),properties:(0,i.getObjectEntries)(s).reduce((e,[n,i])=>({...e,[n]:(0,t.getJSONSchemaObject)(i)}),{})};else if(y)h={type:"array",items:y.map(e=>(0,t.getJSONSchemaObject)(e)),additionalItems:!1,minItems:y.length,maxItems:y.length};else if(u||d){const e=u||d.map(e=>({type:e}));h={oneOf:e.map(e=>(0,t.getJSONSchemaObject)(e))}}else f&&(h={type:"object",...f.values&&!f.keysEnum&&{additionalProperties:(0,t.getJSONSchemaObject)(f.values)},...f.keysEnum&&{properties:f.keysEnum.reduce((e,n)=>({...e,[n]:f.values?(0,t.getJSONSchemaObject)(f.values):{type:{}}}),{})}});if(p){const e={type:"null"};h.oneOf?h.oneOf.push(e):h.enum&&!h.enum.includes(null)?h.enum.push(null):h={oneOf:[h,e]}}return{...n?{$id:n?.id,$schema:"https://json-schema.org/draft/2020-12/schema"}:void 0,...b,...h}}},394(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.getJSONBTSTypes=void 0,t.getJSONBSchemaTSTypes=function(e,n,i="",r){return(0,t.getJSONBTSTypes)(r,{...e,nullable:n.nullable},void 0,i)};const i=n(806),r=n(897),o=e=>null===e?"null":void 0===e?"undefined":"string"==typeof e?JSON.stringify(e):String(e);t.getJSONBTSTypes=(e,n,a=!1,l="",c=0)=>{const p=(0,r.getFieldTypeObj)(n),u=p.nullable?"null | ":"";if("string"==typeof p.type&&p.type.includes("Lookup"))return((e,t)=>{const n=t.nullable?"null | ":"",r=t.type.endsWith("[]")?"[]":"";if("TableLookup"===t.type||"TableLookup[]"===t.type)return`${n}string${r}`;if("ColumnLookup"===t.type||"ColumnLookup[]"===t.type)return`${n}{ "table": string; "column": string; }${r}`;const o=t,s=e.find(e=>e.name===o.table)?.columns;if("ValueLookup"===t.type||"ValueLookup[]"===t.type){const e=t,o=s?.find(t=>t.name===e.column)?.udt_name;return`${n}${(0,i.postgresToTsType)(o??"text")}${r}`}return`${n}${s?`{ ${s.map(e=>`${JSON.stringify(e.name)}: ${e.is_nullable?"null | ":""} ${(0,i.postgresToTsType)(e.udt_name)}; `).join(" ")} }`:"any"}${r}`})(e,p);if("string"==typeof p.type){const e=p.type.replace("integer","number").replace("time","string").replace("timestamp","string").replace("FileLike","{ name: string; type: string; data: Blob; }").replace("Date","string");if(p.allowedValues){const e=p.type.endsWith("[]")?"[]":"";return u+` (${p.allowedValues.map(e=>JSON.stringify((0,i.isObject)(e)?e.value:e)).join(" | ")})${e}`}return u+e}if((0,i.isObject)(p.type)){const n=e=>e.trim().endsWith(";")?e:e.trim()+";",{type:o}=p,l=a?" ":" ";let d=` {${l}`+(0,i.getObjectEntries)(o).map(([i,o])=>{const a=(0,r.getFieldTypeObj)(o),p=s(i)?i:JSON.stringify(i);return`${l}${p}${a.optional?"?":""}: `+n((0,t.getJSONBTSTypes)(e,a,!0,void 0,c+1))}).join(" ")+`${l}}`;return a||(d=n(d)),a&&(d=d.split("\n").join("")),u+d}if(p.enum)return u+p.enum.map(e=>o(e)).join(" | ");if(p.tuple)return`${u}[${p.tuple.map(n=>(0,t.getJSONBTSTypes)(e,n,!0,void 0,c+1)).join(", ")}]`;if(p.oneOf||p.oneOfType){const n=p.oneOf||p.oneOfType.map(e=>({type:e}));return(p.nullable?`\n${l} | null`:"")+n.map(n=>`\n${l} | `+(0,t.getJSONBTSTypes)(e,n,!0,void 0,c+1)).join("")}if(p.arrayOf||p.arrayOfType){const n=p.arrayOf||{type:p.arrayOfType};return`${p.nullable?"null | ":""} ( ${(0,t.getJSONBTSTypes)(e,n,!0,void 0,c+1)} )[]`}if(p.record){const{keysEnum:n,values:i,partial:r}=p.record,s=e=>r?`Partial<Record<${e}>>`:`Record<${e}>`;return`${p.nullable?"null |":""} ${s(`${n?.map(e=>o(e)).join(" | ")??"string"}, ${i?(0,t.getJSONBTSTypes)(e,i,!0,void 0,c+1):"any"}`)}`}throw"Unexpected getSchemaTSTypes: "+JSON.stringify({fieldType:p},null,2)};const s=e=>/^[A-Za-z$_][A-Za-z0-9$_]*$/.test(e)},704(e,t){t.safeGetKeys=t.safeGetProperty=t.safeHasOwn=void 0;const n=["__proto__","constructor","prototype"];t.safeHasOwn=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),t.safeGetProperty=(e,t)=>{if(n.includes(t)){const n=Object.getOwnPropertyDescriptor(e,t);return n?.value}return e[t]},t.safeGetKeys=e=>{const i=Object.keys(e);for(const r of n)(0,t.safeHasOwn)(e,r)&&!i.includes(r)&&i.push(r);return i}},502(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.WAL=void 0;const i=n(806);t.WAL=class{constructor(e){if(this.changed={},this.sending={},this.sentHistory={},this.callbacks=[],this.sort=(e,t)=>{const{orderBy:n}=this.options;return n&&e&&t&&n.map(n=>{if(!(n.fieldName in e)||!(n.fieldName in t))throw"Replication error: \n some orderBy fields missing from data";let i=n.asc?e[n.fieldName]:t[n.fieldName],r=n.asc?t[n.fieldName]:e[n.fieldName],o=+i-+r,s=i<r?-1:i==r?0:1;return"number"===n.tsDataType&&Number.isFinite(o)?o:s}).find(e=>e)||0},this.isInHistory=e=>{if(!e)throw"Provide item";const t=e[this.options.synced_field];if(!Number.isFinite(+t))throw"Provided item Synced field value is missing/invalid ";const n=this.sentHistory[this.getIdStr(e)],i=n?.[this.options.synced_field];if(n){if(!Number.isFinite(+i))throw"Provided historic item Synced field value is missing/invalid";if(+i===+t)return!0}return!1},this.addData=e=>((0,i.isEmpty)(this.changed)&&this.options.onSendStart&&this.options.onSendStart(),e.forEach(e=>{var t;const{initial:n,current:i,delta:r}={...e};if(!i)throw"Expecting { current: object, initial?: object }";const o=this.getIdStr(i);this.changed??(this.changed={}),(t=this.changed)[o]??(t[o]={initial:n,current:i,delta:r}),this.changed[o].current={...this.changed[o].current,...i},this.changed[o].delta={...this.changed[o].delta,...r}}),this.sendItems()),this.getPendingItems=()=>[...Object.values(this.sending),...Object.values(this.changed)],this.isOnSending=!1,this.isSendingTimeout=void 0,this.willDeleteHistory=void 0,this.sendItems=async()=>{const{DEBUG_MODE:e,onSend:t,onSendEnd:n,batch_size:r,throttle:o,historyAgeSeconds:s=2}=this.options;if(this.isSendingTimeout||this.sending&&!(0,i.isEmpty)(this.sending))return;if(!this.changed||(0,i.isEmpty)(this.changed))return;let a,l=[],c=[],p={};Object.keys(this.changed).sort((e,t)=>this.sort(this.changed[e].current,this.changed[t].current)).slice(0,r).map(e=>{let t={...this.changed[e]};this.sending[e]={...t},c.push({...t}),p[e]={...t.current},delete this.changed[e]}),l=c.map(e=>{let t={};return Object.keys(e.current).map(n=>{const r=e.initial?.[n],o=e.current[n];![this.options.synced_field,...this.options.id_fields].includes(n)&&(0,i.isEqual)(r,o)||(t[n]=o)}),t}),e&&console.log(this.options.id," SENDING lr->",l[l.length-1]),this.isSendingTimeout||(this.isSendingTimeout=setTimeout(()=>{this.isSendingTimeout=void 0,(0,i.isEmpty)(this.changed)||this.sendItems()},o)),this.isOnSending=!0;try{await t(l,c),s&&(this.sentHistory={...this.sentHistory,...p},this.willDeleteHistory||(this.willDeleteHistory=setTimeout(()=>{this.willDeleteHistory=void 0,this.sentHistory={}},1e3*s)))}catch(e){a=e,console.error("WAL onSend failed:",e,l,c)}if(this.isOnSending=!1,this.callbacks.length){const e=Object.keys(this.sending);this.callbacks.forEach((t,n)=>{t.idStrs=t.idStrs.filter(t=>e.includes(t)),t.idStrs.length||t.cb(a)}),this.callbacks=this.callbacks.filter(e=>e.idStrs.length)}this.sending={},e&&console.log(this.options.id," SENT lr->",l[l.length-1]),(0,i.isEmpty)(this.changed)?n&&n(l,c,a):this.sendItems()},this.options={...e},!this.options.orderBy){const{synced_field:t,id_fields:n}=e;this.options.orderBy=[t,...n.sort()].map(e=>({fieldName:e,tsDataType:e===t?"number":"string",asc:!0}))}}isSending(){const e=this.isOnSending||!((0,i.isEmpty)(this.sending)&&(0,i.isEmpty)(this.changed));return this.options.DEBUG_MODE&&console.log(this.options.id," CHECKING isSending ->",e),e}getIdStr(e){return this.options.id_fields.sort().map(t=>String(e[t])).join(".")}getIdObj(e){let t={};return this.options.id_fields.sort().map(n=>{t[n]=e[n]}),t}getDeltaObj(e){let t={};return Object.keys(e).map(n=>{this.options.id_fields.includes(n)||(t[n]=e[n])}),t}}},618(e,t){Object.defineProperty(t,"__esModule",{value:!0})},356(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.authContract=void 0;const i=n(749),r={username:"string",password:{type:"string",optional:!0}};t.authContract={login:{request:{type:{...r,remember_me:{type:"boolean",optional:!0},totp_token:{type:"string",optional:!0},totp_recovery_code:{type:"string",optional:!0}}},response:{oneOf:[i.authResponseSchemas.authSuccess,i.authResponseSchemas.passwordLoginFailure,i.authResponseSchemas.magicLinkAuthSuccess,i.authResponseSchemas.magicLinkAuthFailure,i.authResponseSchemas.oauthRegisterFailure,i.authResponseSchemas.codeVerificationFailure]}},register:{request:{type:{...r,invitationToken:{type:"string",optional:!0},totpTokenConfirmation:{type:"string",optional:!0}}},response:{oneOf:[i.authResponseSchemas.passwordRegisterSuccess,i.authResponseSchemas.passwordRegisterFailure]}},magicLinkOrOTP:{request:{oneOfType:[{id:"string",returnToken:{type:"boolean",optional:!0}},{email:"string",code:"string",returnToken:{type:"boolean",optional:!0}}]},response:{oneOf:[i.authResponseSchemas.authSuccess,i.authResponseSchemas.emailConfirmationSuccess,i.authResponseSchemas.magicLinkAuthFailure,i.authResponseSchemas.codeVerificationFailure,i.authResponseSchemas.invalidEmail]}},logout:{request:{type:{}},response:{oneOf:[i.authResponseSchemas.authSuccess,i.authResponseSchemas.commonFailure]}}}},749(e,t){t.authResponseSchemas=void 0;const n={type:"string",optional:!0},i={success:{enum:[!0]},message:n},r={success:{enum:[!1]},message:n},o=["server-error","rate-limit-exceeded","something-went-wrong"],s=[...o,"no-match","inactive-account"];t.authResponseSchemas={authSuccess:{type:{...i,code:{enum:[void 0],optional:!0},token:{type:"string",optional:!0}}},commonFailure:{type:{...r,code:{enum:o}}},authFailure:{type:{...r,code:{enum:s}}},magicLinkAuthSuccess:{type:{...i,code:{enum:["email-verification-code-sent","magic-link-sent"]}}},magicLinkAuthFailure:{type:{...r,code:{enum:[...s,"expired-magic-link","invalid-magic-link","used-magic-link"]}}},oauthRegisterFailure:{type:{...r,code:{enum:[...o,"provider-issue"]}}},passwordLoginFailure:{type:{...r,code:{enum:[...s,"totp-token-missing","invalid-username","username-missing","invalid-email","password-missing","invalid-password","is-from-OAuth","is-from-magic-link","invalid-totp-recovery-code","invalid-totp-code","email-not-confirmed"]}}},passwordRegisterFailure:{type:{...r,code:{enum:[...o,"weak-password","user-already-registered","username-missing","password-missing","invalid-email-confirmation-code","expired-email-confirmation-code","inactive-account"]}}},passwordRegisterSuccess:{type:{...i,code:{enum:["email-verification-code-sent","already-registered-but-did-not-confirm-email","email-verified"]}}},codeVerificationFailure:{type:{...r,code:{enum:[...s,"invalid-otp-code","expired-otp-code"]}}},emailConfirmationSuccess:{type:{...i,code:{enum:["email-verified"]}}},invalidEmail:{type:{...r,code:{enum:["invalid-email"]}}}}},521(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.CONTENT_TYPE_TO_EXT=void 0,t.CONTENT_TYPE_TO_EXT={"text/html":["html","htm","shtml"],"text/css":["css"],"text/csv":["csv"],"text/tsv":["tsv"],"text/tab-separated-values":["tsv"],"text/xml":["xml"],"text/mathml":["mml"],"text/plain":["txt","text","log"],"text/markdown":["md","markdown","qmd","rmd"],"text/x-markdown":["md","markdown"],"text/asciidoc":["adoc","asciidoc","asc"],"text/x-asciidoc":["adoc","asciidoc","asc"],"text/x-tex":["tex"],"text/x-latex":["tex","latex"],"text/rtf":["rtf"],"text/vtt":["vtt"],"text/calendar":["ics","ifb"],"text/vcard":["vcf","vcard"],"text/javascript":["js","mjs","cjs"],"text/yaml":["yaml","yml"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/x-component":["htc"],"image/gif":["gif"],"image/jpeg":["jpeg","jpg"],"image/png":["png"],"image/tiff":["tif","tiff"],"image/bmp":["bmp"],"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"],"image/vnd.wap.wbmp":["wbmp"],"image/x-icon":["ico"],"image/vnd.microsoft.icon":["ico"],"image/x-jng":["jng"],"image/x-ms-bmp":["bmp"],"image/svg+xml":["svg"],"image/webp":["webp"],"application/sql":["sql"],"application/json":["json"],"application/xml":["xml","xsl","xsd","nxml","xbrl","dclg"],"application/yaml":["yaml","yml"],"application/geo+json":["geojson"],"application/javascript":["js","mjs","cjs"],"application/x-javascript":["js"],"application/atom+xml":["atom"],"application/rss+xml":["rss"],"application/java-archive":["jar","war","ear"],"application/mac-binhex40":["hqx"],"application/msword":["doc","docx","dot"],"application/x-msword":["doc","dot"],"application/pdf":["pdf"],"application/postscript":["ps","eps","ai"],"application/rtf":["rtf"],"application/x-rtf":["rtf"],"application/epub+zip":["epub"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.keynote":["key"],"application/x-iwork-pages-sffpages":["pages"],"application/x-iwork-numbers-sffnumbers":["numbers"],"application/x-iwork-keynote-sffkey":["key"],"application/vnd.box.boxnote":["boxnote"],"application/vnd.ibm.modcap":["afp"],"application/x-afp":["afp"],"application/x-ebcdic":["ebc","ebcdic"],"application/vnd.ms-excel":["xls","xlsx","xlt"],"application/x-msexcel":["xls","xlt"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-powerpoint":["ppt","pptx","pot","pps"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-outlook":["msg"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/x-7z-compressed":["7z"],"application/gzip":["gz","tgz"],"application/x-tar":["tar"],"application/x-bzip2":["bz2","tbz2"],"application/x-xz":["xz"],"application/zstd":["zst"],"application/vnd.rar":["rar"],"application/x-cocoa":["cco"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-makeself":["run"],"application/x-perl":["pl","pm"],"application/x-pilot":["prc","pdb"],"application/x-rar-compressed":["rar"],"application/x-redhat-package-manager":["rpm"],"application/x-sea":["sea"],"application/x-shockwave-flash":["swf"],"application/x-stuffit":["sit"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-latex":["latex"],"application/x-mimearchive":["mhtml","mht"],"application/x-x509-ca-cert":["der","pem","crt"],"application/x-xpinstall":["xpi"],"application/xhtml+xml":["xhtml"],"application/zip":["zip","dclx"],"application/octet-stream":["bin","exe","dll","deb","dmg","eot","iso","img","msi","msp","msm"],"audio/midi":["mid","midi","kar"],"audio/mpeg":["mp3"],"audio/mp3":["mp3"],"audio/mp4":["m4a","mp4a","m4b"],"audio/m4a":["m4a"],"audio/x-m4a":["m4a"],"audio/aac":["aac","adts"],"audio/wav":["wav"],"audio/x-wav":["wav"],"audio/vnd.wave":["wav"],"audio/flac":["flac"],"audio/x-flac":["flac"],"audio/ogg":["ogg","oga","opus","spx"],"audio/webm":["weba"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-realaudio":["ra"],"video/3gpp":["3gpp","3gp"],"video/mpeg":["mpeg","mpg"],"video/quicktime":["mov"],"video/x-flv":["flv"],"video/x-mng":["mng"],"video/x-ms-asf":["asx","asf"],"video/x-ms-wmv":["wmv"],"video/x-msvideo":["avi"],"video/avi":["avi"],"video/x-matroska":["mkv"],"video/mp4":["m4v","mp4"],"video/webm":["webm"],"video/ogg":["ogv"],"message/rfc822":["eml","mime","mht","mhtml"],"multipart/related":["mhtml","mht"]}},209(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.COMPLEX_FILTER_KEY=t.ComplexFilterComparisonKeys=t.EXISTS_KEYS=t.GeomFilter_Funcs=t.GeomFilterKeys=t.ArrayFilterOperands=t.TextFilter_FullTextSearchFilterKeys=t.TextFilterFTSKeys=t.TextFilterKeys=t.JsonbFilterKeys=t.JsonbOperands=t.BetweenFilterKeys=t.CompareInFilterKeys=t.CompareFilterKeys=void 0;const i=n(472);t.CompareFilterKeys=["=","<>",">","<",">=","<=","$eq","$ne","$gt","$gte","$lt","$lte","$isDistinctFrom","$isNotDistinctFrom"],t.CompareInFilterKeys=["$in","$nin"],t.BetweenFilterKeys=["$between","$notBetween"],t.JsonbOperands={"@>":{Operator:"@>","Right Operand Type":"jsonb",Description:"Does the left JSON value contain the right JSON path/value entries at the top level?",Example:'\'{"a":1, "b":2}\'::jsonb @> \'{"b":2}\'::jsonb'},"<@":{Operator:"<@","Right Operand Type":"jsonb",Description:"Are the left JSON path/value entries contained at the top level within the right JSON value?",Example:'\'{"b":2}\'::jsonb <@ \'{"a":1, "b":2}\'::jsonb'},"?":{Operator:"?","Right Operand Type":"text",Description:"Does the string exist as a top-level key within the JSON value?",Example:"'{\"a\":1, \"b\":2}'::jsonb ? 'b'"},"?|":{Operator:"?|","Right Operand Type":"text[]",Description:"Do any of these array strings exist as top-level keys?",Example:"'{\"a\":1, \"b\":2, \"c\":3}'::jsonb ?| array['b', 'c']"},"?&":{Operator:"?&","Right Operand Type":"text[]",Description:"Do all of these array strings exist as top-level keys?",Example:"'[\"a\", \"b\"]'::jsonb ?& array['a', 'b']"},"||":{Operator:"||","Right Operand Type":"jsonb",Description:"Concatenate two jsonb values into a new jsonb value",Example:'\'["a", "b"]\'::jsonb || \'["c", "d"]\'::jsonb'},"-":{Operator:"-","Right Operand Type":"integer",Description:"Delete the array element with specified index (Negative integers count from the end). Throws an error if top level container is not an array.",Example:'\'["a", "b"]\'::jsonb - 1'},"#-":{Operator:"#-","Right Operand Type":"text[]",Description:"Delete the field or element with specified path (for JSON arrays, negative integers count from the end)",Example:"'[\"a\", {\"b\":1}]'::jsonb #- '{1,b}'"},"@?":{Operator:"@?","Right Operand Type":"jsonpath",Description:"Does JSON path return any item for the specified JSON value?",Example:"'{\"a\":[1,2,3,4,5]}'::jsonb @? '$.a[*] ? (@ > 2)'"},"@@":{Operator:"@@","Right Operand Type":"jsonpath",Description:"Returns the result of JSON path predicate check for the specified JSON value. Only the first item of the result is taken into account. If the result is not Boolean, then null is returned.",Example:"'{\"a\":[1,2,3,4,5]}'::jsonb @@ '$.a[*] > 2'"}},t.JsonbFilterKeys=(0,i.getKeys)(t.JsonbOperands),t.TextFilterKeys=["$ilike","$like","$nilike","$nlike"],t.TextFilterFTSKeys=["@@","@>","<@","$contains","$containedBy"],t.TextFilter_FullTextSearchFilterKeys=["to_tsquery","plainto_tsquery","phraseto_tsquery","websearch_to_tsquery"],t.ArrayFilterOperands=["@>","<@","=","$eq","$contains","$containedBy","&&","$overlaps"],t.GeomFilterKeys=["~","~=","@","|&>","|>>",">>","=","<<|","<<","&>","&<|","&<","&&&","&&"],t.GeomFilter_Funcs=["ST_MakeEnvelope","st_makeenvelope","ST_MakePolygon","st_makepolygon"],t.EXISTS_KEYS=["$exists","$notExists","$existsJoined","$notExistsJoined"],t.ComplexFilterComparisonKeys=[...t.TextFilterKeys,...t.JsonbFilterKeys,...t.CompareFilterKeys,...t.BetweenFilterKeys,...t.CompareInFilterKeys],t.COMPLEX_FILTER_KEY="$filter"},391(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.getActionFunctions=void 0,t.getActionFunctions=(e,t)=>Object.entries(e).flatMap(([e,n])=>Object.entries(n.input??{}).flatMap(([n,i])=>"string"==typeof i||"RowLookup"!==i.type&&"ValueLookup"!==i.type||i.table!==t.name||"ValueLookup"===i.type&&!t.columns.some(e=>e.name===i.column&&e.select)?[]:[{methodName:e,argName:n,lookup:i}]))},806(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.ABORTABLE_METHODS=t.CONTENT_TYPE_TO_EXT=t.getPossibleNestedInsert=t.SQL_COMMAND_TABLE_METHODS=t.CHANNELS=t.CHANNEL_PREFIX=t.ROW_ACTIONS_COLUMN=t.JOIN_PARAMS=t.JOIN_KEYS=t.getAllowedTableMethods=t.postgresToTsType=t.TS_PG_Types=t._PG_bytes=t._PG_geometric=t._PG_postgis=t._PG_interval=t._PG_date=t._PG_bool=t._PG_json=t._PG_numbers=t._PG_numbers_str=t._PG_numbers_num=t._PG_strings=void 0;const o=n(472),s=n(441);t._PG_strings=["bpchar","char","varchar","text","citext","uuid","time","timetz","interval","name","cidr","inet","macaddr","macaddr8","int4range","int8range","numrange","tsvector"],t._PG_numbers_num=["int2","int4","float4","float8","oid"],t._PG_numbers_str=["int8","numeric","money"],t._PG_numbers=[...t._PG_numbers_num,...t._PG_numbers_str],t._PG_json=["json","jsonb"],t._PG_bool=["bool"],t._PG_date=["date","timestamp","timestamptz"],t._PG_interval=["interval"],t._PG_postgis=["geometry","geography"],t._PG_geometric=["point","line","lseg","box","path","polygon","circle"],t._PG_bytes=["bytea"];const a={Uint8Array:t._PG_bytes,string:[...t._PG_strings,...t._PG_numbers_str,...t._PG_date,...t._PG_geometric,...t._PG_postgis,"lseg"],number:t._PG_numbers_num,boolean:t._PG_bool,any:[...t._PG_json,...t._PG_interval]};t.TS_PG_Types={...a,"number[]":a.number.map(e=>`_${e}`),"boolean[]":a.boolean.map(e=>`_${e}`),"string[]":a.string.map(e=>`_${e}`),"any[]":a.any.map(e=>`_${e}`)},t.postgresToTsType=e=>(0,o.getKeys)(t.TS_PG_Types).find(n=>(0,s.includes)(t.TS_PG_Types[n],e))??"any",t.getAllowedTableMethods=({publishInfo:e})=>{let n=[...e.select||e.insert||e.delete||e.update?t.SQL_COMMAND_TABLE_METHODS.schema:[],...t.SQL_COMMAND_TABLE_METHODS.select.filter(t=>{if(!e.select)return!1;const n="subscribeOne"===t?"subscribe":t;return!Object.keys(e.select.disabledMethods??{}).includes(n)&&("sync"!==t||void 0!==e.select.syncConfig)}),...t.SQL_COMMAND_TABLE_METHODS.update.filter(t=>e.update&&!Object.keys(e.update.disabledMethods??{}).includes(t)),...e.insert?t.SQL_COMMAND_TABLE_METHODS.insert:[],...e.delete?t.SQL_COMMAND_TABLE_METHODS.delete:[]];const i=new Map;return Object.values(t.SQL_COMMAND_TABLE_METHODS).forEach(e=>{e.forEach(e=>{i.set(e,(i.get(e)??0)+1)})}),i.forEach((e,t)=>{n.filter(e=>e===t).length!==e&&i.delete(t)}),Array.from(i.keys())},t.JOIN_KEYS=["$innerJoin","$leftJoin"],t.JOIN_PARAMS=["select","filter","offset","limit","orderBy","having"],t.ROW_ACTIONS_COLUMN="$prostgles_actions",t.CHANNEL_PREFIX="_psqlWS_.",t.CHANNELS={SCHEMA_CHANGED:t.CHANNEL_PREFIX+"schema-changed",SCHEMA:t.CHANNEL_PREFIX+"schema",DEFAULT:t.CHANNEL_PREFIX,SQL:`${t.CHANNEL_PREFIX}sql`,SQL_STREAM:`${t.CHANNEL_PREFIX}sql-stream`,METHOD:`${t.CHANNEL_PREFIX}method`,NOTICE_EV:`${t.CHANNEL_PREFIX}notice`,LISTEN_EV:`${t.CHANNEL_PREFIX}listen`,REGISTER:`${t.CHANNEL_PREFIX}register`,LOGIN:`${t.CHANNEL_PREFIX}login`,LOGOUT:`${t.CHANNEL_PREFIX}logout`,AUTH_GUARD:`${t.CHANNEL_PREFIX}authguard`,CONNECTION:`${t.CHANNEL_PREFIX}connection`,_preffix:t.CHANNEL_PREFIX},t.SQL_COMMAND_TABLE_METHODS={schema:["getColumns","getInfo"],insert:["insert","insertMany","upsert"],update:["update","upsert","updateBatch"],select:["findOne","find","count","size","subscribe","subscribeOne","sync"],delete:["delete","remove"]},t.getPossibleNestedInsert=(e,t,n=!0)=>{const i=(e.references??[]).map(e=>{const{ftable:n,fcols:i}=e,r=t.find(e=>e.name===n);if(!r)return;const o=r.columns.filter(e=>i.includes(e.name));return o.length?{ref:e,fcolsInfo:o}:void 0}).filter(o.isDefined),[r,...s]=i??[];if(!s.length)return r?.ref;const[a,...l]=i.filter(e=>e.fcolsInfo.some(e=>e.is_pkey));if(!l.length)return a?.ref;if(!n)throw["Cannot do a nested insert on column that references multiple tables.","Expecting only one reference to a single primary key fcol"].join("\n")},r(n(618),t),r(n(356),t),r(n(4),t);var l=n(521);Object.defineProperty(t,"CONTENT_TYPE_TO_EXT",{enumerable:!0,get:function(){return l.CONTENT_TYPE_TO_EXT}}),r(n(209),t),r(n(319),t),r(n(699),t),r(n(394),t),r(n(994),t),r(n(897),t),r(n(164),t),r(n(472),t),r(n(502),t),r(n(778),t),r(n(784),t),r(n(391),t),t.ABORTABLE_METHODS=["find","findOne","count","size"]},319(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.leftJoin=t.innerJoin=t.parsedJoinPathSchema=t.defineJoin=void 0;const i=n(472);t.defineJoin=e=>e,t.parsedJoinPathSchema={type:{table:"string",on:{oneOf:[{type:"string"},{arrayOf:{record:{values:"string"}}}]},params:{record:{values:"unknown"},optional:!0},reversed:{type:"boolean",optional:!0}}};const r=(e="$leftJoin")=>(t,n,r,o={})=>({[e]:o.path??t,filter:n,...(0,i.omitKeys)(o,["path","select"]),select:r});t.innerJoin=r("$innerJoin"),t.leftJoin=r("$leftJoin")},666(e,t){function n(e,t){var n=e[0],i=e[1],l=e[2],c=e[3];n=r(n,i,l,c,t[0],7,-680876936),c=r(c,n,i,l,t[1],12,-389564586),l=r(l,c,n,i,t[2],17,606105819),i=r(i,l,c,n,t[3],22,-1044525330),n=r(n,i,l,c,t[4],7,-176418897),c=r(c,n,i,l,t[5],12,1200080426),l=r(l,c,n,i,t[6],17,-1473231341),i=r(i,l,c,n,t[7],22,-45705983),n=r(n,i,l,c,t[8],7,1770035416),c=r(c,n,i,l,t[9],12,-1958414417),l=r(l,c,n,i,t[10],17,-42063),i=r(i,l,c,n,t[11],22,-1990404162),n=r(n,i,l,c,t[12],7,1804603682),c=r(c,n,i,l,t[13],12,-40341101),l=r(l,c,n,i,t[14],17,-1502002290),n=o(n,i=r(i,l,c,n,t[15],22,1236535329),l,c,t[1],5,-165796510),c=o(c,n,i,l,t[6],9,-1069501632),l=o(l,c,n,i,t[11],14,643717713),i=o(i,l,c,n,t[0],20,-373897302),n=o(n,i,l,c,t[5],5,-701558691),c=o(c,n,i,l,t[10],9,38016083),l=o(l,c,n,i,t[15],14,-660478335),i=o(i,l,c,n,t[4],20,-405537848),n=o(n,i,l,c,t[9],5,568446438),c=o(c,n,i,l,t[14],9,-1019803690),l=o(l,c,n,i,t[3],14,-187363961),i=o(i,l,c,n,t[8],20,1163531501),n=o(n,i,l,c,t[13],5,-1444681467),c=o(c,n,i,l,t[2],9,-51403784),l=o(l,c,n,i,t[7],14,1735328473),n=s(n,i=o(i,l,c,n,t[12],20,-1926607734),l,c,t[5],4,-378558),c=s(c,n,i,l,t[8],11,-2022574463),l=s(l,c,n,i,t[11],16,1839030562),i=s(i,l,c,n,t[14],23,-35309556),n=s(n,i,l,c,t[1],4,-1530992060),c=s(c,n,i,l,t[4],11,1272893353),l=s(l,c,n,i,t[7],16,-155497632),i=s(i,l,c,n,t[10],23,-1094730640),n=s(n,i,l,c,t[13],4,681279174),c=s(c,n,i,l,t[0],11,-358537222),l=s(l,c,n,i,t[3],16,-722521979),i=s(i,l,c,n,t[6],23,76029189),n=s(n,i,l,c,t[9],4,-640364487),c=s(c,n,i,l,t[12],11,-421815835),l=s(l,c,n,i,t[15],16,530742520),n=a(n,i=s(i,l,c,n,t[2],23,-995338651),l,c,t[0],6,-198630844),c=a(c,n,i,l,t[7],10,1126891415),l=a(l,c,n,i,t[14],15,-1416354905),i=a(i,l,c,n,t[5],21,-57434055),n=a(n,i,l,c,t[12],6,1700485571),c=a(c,n,i,l,t[3],10,-1894986606),l=a(l,c,n,i,t[10],15,-1051523),i=a(i,l,c,n,t[1],21,-2054922799),n=a(n,i,l,c,t[8],6,1873313359),c=a(c,n,i,l,t[15],10,-30611744),l=a(l,c,n,i,t[6],15,-1560198380),i=a(i,l,c,n,t[13],21,1309151649),n=a(n,i,l,c,t[4],6,-145523070),c=a(c,n,i,l,t[11],10,-1120210379),l=a(l,c,n,i,t[2],15,718787259),i=a(i,l,c,n,t[9],21,-343485551),e[0]=d(n,e[0]),e[1]=d(i,e[1]),e[2]=d(l,e[2]),e[3]=d(c,e[3])}function i(e,t,n,i,r,o){return t=d(d(t,e),d(i,o)),d(t<<r|t>>>32-r,n)}function r(e,t,n,r,o,s,a){return i(t&n|~t&r,e,t,o,s,a)}function o(e,t,n,r,o,s,a){return i(t&r|n&~r,e,t,o,s,a)}function s(e,t,n,r,o,s,a){return i(t^n^r,e,t,o,s,a)}function a(e,t,n,r,o,s,a){return i(n^(t|~r),e,t,o,s,a)}function l(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}t.md5=u;var c="0123456789abcdef".split("");function p(e){for(var t="",n=0;n<4;n++)t+=c[e>>8*n+4&15]+c[e>>8*n&15];return t}function u(e){return function(e){for(var t=0;t<e.length;t++)e[t]=p(e[t]);return e.join("")}(function(e){var t,i=e.length,r=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=e.length;t+=64)n(r,l(e.substring(t-64,t)));e=e.substring(t-64);var o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t<e.length;t++)o[t>>2]|=e.charCodeAt(t)<<(t%4<<3);if(o[t>>2]|=128<<(t%4<<3),t>55)for(n(r,o),t=0;t<16;t++)o[t]=0;return o[14]=8*i,n(r,o),r}(e))}function d(e,t){return e+t&4294967295}u("hello")},784(e,t){Object.defineProperty(t,"__esModule",{value:!0})},164(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.ReplicationProtocol=t.getSyncChannelName=void 0;const i=n(806);var r;t.getSyncChannelName=({tableName:e,filter:t={},select:n="*"})=>[i.CHANNEL_PREFIX,e,"sync",(0,i.stableStringify)(t),"string"==typeof n?n:(0,i.stableStringify)(n)].join("."),function(e){e.CreateSchema={name:"Create",source:"client",request:{type:{tableName:"string",command:{enum:["sync"]},param1:{record:{values:"unknown"}},param2:{type:{select:"unknown"}}}},response:{type:{id_fields:"string[]",synced_field:"string",channelName:"string",data:"any[]",isSynced:"boolean"}}};const t={state:{enum:["syncing"]},c_fr:{optional:!0,record:{values:"unknown"}},c_lr:{optional:!0,record:{values:"unknown"}},c_count:"number"},n={state:{enum:["syncing-data"]},c_fr:{record:{values:"unknown"}},c_lr:{record:{values:"unknown"}},c_count:"number",data:{arrayOf:{record:{values:"unknown"}}}},r={from_synced:{oneOf:["string","number",{enum:[void 0]}]},to_synced:{oneOf:["string","number",{enum:[void 0]}]}};e.ServerSyncRequest={name:"ServerSyncRequest",source:"server",request:{type:{...r,end_offset:{oneOf:["number",{enum:[null]}]}}},response:{oneOfType:[t,n,{state:{enum:["error"]},err:"unknown"}]}},e.ClientSyncRequest={name:"ClientSyncRequest",source:"client",request:{oneOfType:[t,n]},response:{oneOfType:[{success:{enum:[!0]}},{success:{enum:[!1]},err:"unknown"}]}},e.PullRequest={name:"PullRequest",source:"server",request:{type:{...r,offset:{oneOf:["number",{enum:[void 0]}]},limit:{oneOf:["number",{enum:[void 0]}]}}},response:{oneOfType:[{success:{enum:[!0]},data:{arrayOf:{record:{values:"unknown"}}}},{success:{enum:[!1]},err:"unknown"}]}},e.UpdateRequest={name:"UpdateRequest",source:"server",request:{oneOfType:[{state:{enum:["error"]},err:"unknown"},{state:{enum:["synced"]},isSynced:"boolean"},{state:{enum:["syncing"]},data:{arrayOf:{record:{values:"unknown"}}}}]},response:{oneOfType:[{success:{enum:[!0]}},{success:{enum:[!1]},err:"unknown"}]}};const o={ClientSyncRequest:e.ClientSyncRequest,ServerSyncRequest:e.ServerSyncRequest,PullRequest:e.PullRequest,UpdateRequest:e.UpdateRequest},s=Object.values(o),a=(e,t,n,r)=>(t.removeAllListeners(e),t.on(e,async(e,t)=>{const{type:o,request:a}=(0,i.isObject)(e)?e:{};if("string"!=typeof o||!a)return void t("Unexpected data");const l=s.find(e=>e.name===o&&e.source!==n);if(!l)return void t("Invalid data.type");if(l.source===n)return void t("Invalid schema.source");if("server"===n){const e=(0,i.getJSONBSchemaValidationError)(l.request,a);if(void 0!==e.error)return console.error("Invalid request from client",e.error,a),void t(e.error)}const c=l.name;try{t(await(0,i.withTimeout)(Promise.resolve(r[c](a)),1e4))}catch(e){t((0,i.getSerialisableError)(e))}}),(0,i.fromEntries)((0,i.getEntries)(o).map(([r,o])=>{if(o.source===n)return[r,r=>(0,i.createPromiseWithTimeout)((s,a)=>{t.emit(e,{type:o.name,request:r},e=>{if("server"===n){const t=(0,i.getJSONBSchemaValidationError)(o.response,e);if(void 0!==t.error)return console.error("Invalid response from client for "+o.name,t.error,e),void a(t.error)}s(e)})},1e4)]}).filter(i.isDefined)));e.getServerHandlers=(e,t,n)=>a(e,t,"server",n),e.getClientHandlers=(e,t,n)=>a(e,t,"client",n)}(r||(t.ReplicationProtocol=r={}))},4(e,t){Object.defineProperty(t,"__esModule",{value:!0})},472(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.fromEntries=t.getEntries=t.createPromiseWithTimeout=t.withTimeout=t.getProperty=t.getSerialisableError=t.safeStringify=t.extractTypeUtil=t.reverseParsedPath=t.reverseJoinOn=t.tryCatch=t.getObjectEntries=t.isNotEmpty=t.pickKeys=void 0,t.asName=function(e){if(null==e||!e.toString||!e.toString())throw"Expecting a non empty string";return`"${e.toString().replace(/"/g,'""')}"`},t.omitKeys=r,t.filter=o,t.find=function(e,t){return o(e,t)[0]},t.stableStringify=function(e,t={}){t||(t={}),"function"==typeof t&&(t={cmp:t});var n,i="boolean"==typeof t.cycles&&t.cycles,r=t.cmp&&(n=t.cmp,function(e){return function(t,i){var r={key:t,value:e[t]},o={key:i,value:e[i]};return n(r,o)}}),o=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var n,s;if(Array.isArray(t)){for(s="[",n=0;n<t.length;n++)n&&(s+=","),s+=e(t[n])||"null";return s+"]"}if(null===t)return"null";if(-1!==o.indexOf(t)){if(i)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var a=o.push(t)-1,l=Object.keys(t).sort(r&&r(t));for(s="",n=0;n<l.length;n++){var c=l[n],p=e(t[c]);p&&(s&&(s+=","),s+=JSON.stringify(c)+":"+p)}return o.splice(a,1),"{"+s+"}"}}(e)},t.getTextPatch=function(e,t){if(!(e&&t&&e.trim().length&&t.trim().length))return t;if(e===t)return{from:0,to:0,text:"",md5:(0,i.md5)(t)};function n(n=1){let i=n<1?-1:0,r=!1;for(;!r&&Math.abs(i)<=t.length;){const o=n<1?[i]:[0,i];e.slice(...o)!==t.slice(...o)?r=!0:i+=1*Math.sign(n)}return i}let r=n()-1,o=e.length+n(-1)+1,s=t.length+n(-1)+1;return{from:r,to:o,text:t.slice(r,s),md5:(0,i.md5)(t)}},t.unpatchText=function(e,t){if(!t||"string"==typeof t)return t;const{from:n,to:r,text:o,md5:s}=t;if(null===o||null===e)return o;let a=e.slice(0,n)+o+e.slice(r);if(s&&(0,i.md5)(a)!==s)throw"Patch text error: Could not match md5 hash: (original/result) \n"+e+"\n"+a;return a},t.isEmpty=s,t.get=function(e,t){let n=t,i=e;return e?("string"==typeof n&&(n=n.split(".")),n.reduce((e,t)=>e&&e[t]?e[t]:void 0,i)):e},t.isObject=function(e){return Boolean(e&&"object"==typeof e&&!Array.isArray(e))},t.isDefined=function(e){return null!=e},t.getKeys=a;const i=n(666);function r(e,n){return(0,t.pickKeys)(e,a(e).filter(e=>!n.includes(e)))}function o(e,t){return e.filter(e=>Object.entries(t).every(([t,n])=>e[t]===n))}function s(e){for(var t in e)return!1;return!0}function a(e){return Object.keys(e)}t.pickKeys=(e,t=[],n=!0)=>{if(!t.length)return{};if(e&&t.length){let i={};return t.forEach(t=>{n&&void 0===e[t]||(i[t]=e[t])}),i}return e},t.isNotEmpty=e=>!s(e),t.getObjectEntries=e=>Object.entries(e),t.tryCatch=async e=>{const t=Date.now();try{return{...await e(),duration:Date.now()-t}}catch(e){return{error:e,hasError:!0,duration:Date.now()-t}}},t.reverseJoinOn=e=>e.map(e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e]))),t.reverseParsedPath=(e,n)=>(e??[]).map(({table:i,on:r,params:o,reversed:s},a)=>{const l=e[a-1]?.table??n;return"string"==typeof r?{table:l,on:r,...o&&{params:o},...i===l&&{reversed:!s}}:{table:l,on:(0,t.reverseJoinOn)(r)}}).reverse(),t.extractTypeUtil=(e,t)=>{if(Object.entries(t).every(([t,n])=>e[t]===n))return e},t.safeStringify=e=>{const t=new WeakSet;return JSON.stringify(e,(e,n)=>{if("object"==typeof n&&null!==n){if(t.has(n))return"[Circular]";t.add(n)}return n})},t.getSerialisableError=(e,n=!1)=>{if(null==e)return e;if("string"==typeof e||"boolean"==typeof e||"bigint"==typeof e||void 0===e||"number"==typeof e)return e?.toString();if(e instanceof DOMException)return{name:e.name,message:e.message,code:e.code,...n?{stack:e.stack}:{}};if(e instanceof Error){const i=Object.getOwnPropertyNames(e).reduce((t,n)=>({...t,[n]:e[n]}),{}),o=JSON.parse((0,t.safeStringify)(i));return n?o:r(o,["stack"])}return Array.isArray(e)?e.map(e=>(0,t.getSerialisableError)(e,n)):e},t.getProperty=(e,t)=>{if(Object.keys(e).includes(t))return e[t]},t.withTimeout=(e,t)=>{const n=new Promise((e,n)=>setTimeout(()=>n(new Error(`Timed out after ${t}ms`)),t));return Promise.race([e,n])},t.createPromiseWithTimeout=(e,t)=>{const n=new Promise((e,n)=>setTimeout(()=>n(new Error(`Timed out after ${t}ms`)),t)),i=new Promise(e);return Promise.race([i,n])},t.getEntries=e=>Object.entries(e),t.fromEntries=e=>Object.fromEntries(e)},441(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.includes=function(e,t){return e.some(e=>e===t)}},778(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),r(n(102),t),r(n(436),t),r(n(441),t)},102(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.isEqual=void 0,t.isEqual=(e,t,i="trace")=>n(e,t,void 0,i);const n=(e,t,i=new WeakMap,r)=>{if(e===t)return!0;if(typeof e!=typeof t)return!1;if(null===e||null===t)return!1;if("object"!=typeof e||"object"!=typeof t)return e!=e&&t!=t;let o=i.get(e);if(o?.has(t)){if("quiet"!==r&&console.trace("Circular reference detected in isEqual",e,t),"error"===r)throw new Error("Circular reference detected in isEqual");return"return-true"===r}if(o||(o=new WeakSet,i.set(e,o)),o.add(t),e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof RegExp&&t instanceof RegExp)return e.source===t.source&&e.flags===t.flags;const s=Array.isArray(e),a=Array.isArray(t);if(s&&a){if(e.length!==t.length)return!1;for(let o=0;o<e.length;o++)if(!n(e[o],t[o],i,r))return!1;return!0}if(s!==a)return!1;if(ArrayBuffer.isView(e)&&ArrayBuffer.isView(t)){if(e.byteLength!==t.byteLength)return!1;const n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),i=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);for(let e=0;e<n.length;e++)if(n[e]!==i[e])return!1;return!0}if(e instanceof ArrayBuffer&&t instanceof ArrayBuffer){if(e.byteLength!==t.byteLength)return!1;const n=new Uint8Array(e),i=new Uint8Array(t);for(let e=0;e<n.length;e++)if(n[e]!==i[e])return!1;return!0}const l=Object.keys(e);if(l.length!==Object.keys(t).length)return!1;for(const o of l){if(!(o in t))return!1;{const s=e[o],a=t[o];if(!n(s,a,i,r))return!1}}return!0}},436(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.tryCatchV2=void 0,t.tryCatchV2=e=>{const t=Date.now();try{const n=e();return n instanceof Promise?new Promise(async(e,i)=>{e({...await n.then(e=>({data:e})).catch(e=>({error:e,hasError:!0})),duration:Date.now()-t})}):{data:n,duration:Date.now()-t}}catch(e){return{error:e,hasError:!0,duration:Date.now()-t}}}}};const t={};return function n(i){const r=t[i];if(void 0!==r)return r.exports;const o=t[i]={exports:{}};return e[i].call(o.exports,o,o.exports,n),o.exports}(806)})());
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(Object(this||window),()=>(()=>{"use strict";var e={994(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.DATA_TYPES=t.PrimitiveArrayTypes=t.PrimitiveTypes=t.PrimitiveTypesObj=void 0;const i=n(472);t.PrimitiveTypesObj={boolean:1,number:1,integer:1,string:1,Date:1,time:1,timestamp:1,Uint8Array:1,Blob:1,FileLike:1,any:1,unknown:1},t.PrimitiveTypes=(0,i.getKeys)(t.PrimitiveTypesObj),t.PrimitiveArrayTypes=t.PrimitiveTypes.map(e=>`${e}[]`),t.DATA_TYPES=[...t.PrimitiveTypes,...t.PrimitiveArrayTypes]},897(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.assertJSONBObjectAgainstSchema=t.validateJSONBObjectAgainstSchema=t.getJSONBSchemaValidationErrorAsync=t.getJSONBSchemaValidationError=t.getJSONBObjectSchemaValidationError=t.getFieldTypeObj=void 0;const i=n(472),r=n(441),o=n(704),s=e=>null==e||["number","string","boolean"].includes(typeof e),a=e=>{if(!(0,i.isObject)(e))return!1;const t=(0,o.safeGetKeys)(e);return!!t.length&&t.every(t=>s((0,o.safeGetProperty)(e,t)))};t.getFieldTypeObj=e=>"string"==typeof e?{type:e}:e;const l=e=>e instanceof Blob||"undefined"!=typeof Buffer&&e instanceof Buffer||"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer,c={string:e=>"string"==typeof e,number:e=>"number"==typeof e&&Number.isFinite(e),integer:e=>"number"==typeof e&&Number.isInteger(e),boolean:e=>"boolean"==typeof e,time:e=>"string"==typeof e,timestamp:e=>"string"==typeof e,any:e=>"function"!=typeof e&&"symbol"!=typeof e,unknown:e=>"function"!=typeof e&&"symbol"!=typeof e,Date:e=>"string"==typeof e,Uint8Array:l,Blob:l,FileLike:(e,t)=>{if("FileLike"!==t.type)throw new Error("FileLike type must have type 'FileLike'");const n=(0,i.isObject)(e)&&"string"==typeof e.name&&"string"==typeof e.type&&l(e.data);if(n&&t.mimeTypes&&!Object.keys(t.mimeTypes).some(t=>e.type===t))throw new Error(`Invalid FileLike type. Expected one of: ${Object.keys(t.mimeTypes).join(", ")}`);return n}},p=(0,i.getKeys)(c),u=(e,n,l=[],m,f)=>{const y=`${l.join(".")} is of invalid type. Expecting ${d(n).replaceAll("\n","")}`,g=(0,t.getFieldTypeObj)(n),{type:h,allowedValues:b,nullable:O,optional:_}=g;if(O&&null===e)return;if(_&&void 0===e)return;if(b){if("string"!=typeof h)throw new Error("allowedValues is only supported for primitive types");const t=h.endsWith("[]"),n=t&&Array.isArray(e)?e:[e],r=b.map(e=>(0,i.isObject)(e)?e.value:e);for(const[e,i]of n.entries())if(!r.includes(i))return`${t?`${l.join(".")}[${e}]`:l.join(".")} is of invalid type. Expecting ${r.map(e=>"string"==typeof e?JSON.stringify(e):String(e)).join(" | ")} But got ${JSON.stringify(i)}`}if(h){if((0,i.isObject)(h)){if(!(0,i.isObject)(e))return y;for(const t of(0,o.safeGetKeys)(h)){const n=(0,o.safeGetProperty)(h,t);if(!((0,i.isObject)(n)&&n.optional||(0,o.safeHasOwn)(e,t)))return`${[...l,t].join(".")} is missing but required`;const r=u((0,o.safeGetProperty)(e,t),n,[...l,t],m,f);if(void 0!==r)return r}if(!m?.allowExtraProperties){const t=(0,o.safeGetKeys)(e),n=(0,o.safeGetKeys)(h),i=t.filter(e=>!n.includes(e));if(i.length)return`${l.join(".")} has extra properties: ${i.join(", ")}`}return}if(h.includes("Lookup")){if(!f)throw new Error("Lookup types are not supported for validation");const t=h.endsWith("[]");if(t!==Array.isArray(e))return y;const n=h.replace("[]","");return(t?e:[e]).every(e=>"RowLookup"===n?a(e):"ValueLookup"===n?s(e):"TableLookup"===n?"string"==typeof e:(0,i.isObject)(e)&&"string"==typeof(0,o.safeGetProperty)(e,"table")&&"string"==typeof(0,o.safeGetProperty)(e,"column")&&(0,o.safeGetKeys)(e).every(e=>"table"===e||"column"===e))?void f.push({schema:g,value:e,path:l}):y}const{validator:t}=((e,t)=>{const n=(e=>{if("string"==typeof e&&e.endsWith("[]")){const t=e.slice(0,-2);if(!(0,r.includes)(p,t))throw new Error(`Invalid array field type ${e}`);return t}})(e);if(n){const e=c[n];return{isArray:!0,validator:n=>Array.isArray(n)&&n.every(n=>e(n,t))}}const i=c[e];if(!i)throw new Error(`Unknown field type ${e}`);return{isArray:!1,validator:i}})(h,g);return t(e,g)?void 0:y}if(g.tuple){const t=g.tuple;if(!Array.isArray(e))return y+`[${t.map(e=>d(e)).join(", ")}]`;if(e.length!==t.length)return`${l.length?l.join("."):"value"} is of invalid tuple length. Expecting ${t.length} elements but got ${e.length}`;for(let n=0;n<t.length;n++){const i=u(e[n],t[n],[...l,`${n}`],m,f);if(void 0!==i)return i}return}if(g.enum){const t=[];return g.nullable&&t.push(null),g.optional&&t.push(void 0),g.enum.includes(e)?void 0:y}const v=g.arrayOf??(g.arrayOfType?{type:g.arrayOfType}:void 0);if(v){if(!Array.isArray(e))return y+" an array";const t=e.map((e,t)=>u(e,v,[...l,`${t}`],m,f)).filter(i.isDefined)[0];return void 0!==t?`${y}. Error at index ${l.length>0?l.join(".")+".":""}\n\n${t}`:void 0}const T=g.oneOf??g.oneOfType?.map(e=>({type:e}));if(T){if(!T.length)return y+"to not be empty";let t;if(T.find(n=>{const i=f?.length,r=u(e,n,l,m,f);return void 0!==r&&void 0!==i&&(f.length=i),t??(t=r),void 0===r}))return;return y}if(g.record){const{keysEnum:t,partial:n,values:r}=g.record;if(!(0,i.isObject)(e))return y+"object";if(n&&(0,i.isEmpty)(e))return;const s=(0,i.getKeys)(e),a=n?void 0:t?.find(e=>!s.includes(e));if(void 0!==a)return`${y} to have key ${a}`;const c=t&&s.filter(e=>!t.includes(e));if(c?.length)return`${y} has extra keys: ${c}`;if(r)for(const t of(0,o.safeGetKeys)(e)){const n=(0,o.safeGetProperty)(e,t),i=u(n,r,[...l,t],m,f);if(void 0!==i)return`${i}`}return}return`Could not validate field type. Some logic might be missing: ${JSON.stringify(g)}`},d=e=>{const n=(0,t.getFieldTypeObj)(e),{type:r,nullable:o,optional:s,record:a}=n,l=n.oneOf??n.oneOfType?.map(e=>({type:e})),c=[];if(o&&c.push("null"),s&&c.push("undefined"),"string"==typeof r)c.push(r);else if(r&&(0,i.isObject)(r)){const e=[];Object.entries(r).forEach(([t,n])=>{e.push(`${t}: ${d(n)}`)}),c.push(`{ ${e.join("; ")} }`)}if(n.enum?.forEach(e=>{null===e?c.push("null"):void 0===e?c.push("undefined"):"string"==typeof e?c.push(JSON.stringify(e)):c.push(e)}),l?.forEach(e=>{const t=d(e);c.push(t)}),a){const{keysEnum:e,partial:t,values:n}=a,i=t?"?":"",r=n?d(n):"any";e?c.push(`{ [${e.join(" | ")}]${i}: ${r} }`):c.push(`{ [key: string]${i}: ${r} }`)}return c.join(" | ")};t.getJSONBObjectSchemaValidationError=(e,t,n="input",r=!1,o)=>{if(void 0===t&&!r)return{error:`Expecting ${n} to be defined`};if(!(0,i.isObject)(t))return{error:`Expecting ${n} to be an object`};const s=u(t,{type:e},[],o);return s?{error:s}:{data:t}},t.getJSONBSchemaValidationError=(e,t,n)=>{const i=u(t,e,void 0,n);return i?{error:i}:{data:t}};const m=(e,t)=>[...e,...void 0===t?[]:[String(t)]].join(".")||"value",f=async(e,t)=>{const{schema:n,path:i}=e,r=n.type.endsWith("[]"),o=r?e.value:[e.value];for(const[e,l]of o.entries()){const o=m(i,r?e:void 0);if("TableLookup"===n.type||"TableLookup[]"===n.type){if(!t.has(l))return`${o} references an unknown table ${JSON.stringify(l)}`;continue}if("ColumnLookup"===n.type||"ColumnLookup[]"===n.type){const e=l;if(n.filter?.table&&e.table!==n.filter.table)return`${o} references a column that does not match the lookup filter`;const i=t.get(e.table);if(!i)return`${o} references an unknown table ${JSON.stringify(e.table)}`;if("function"!=typeof i.getColumns)throw new Error(`Cannot validate ColumnLookup: table ${JSON.stringify(e.table)} does not expose getColumns`);const r=(await i.getColumns()).find(({name:t})=>t===e.column);if(!r||n.filter?.tsDataType&&r.tsDataType!==n.filter.tsDataType||n.filter?.udt_name&&r.udt_name!==n.filter.udt_name)return`${o} references an unknown or disallowed column ${JSON.stringify(`${e.table}.${e.column}`)}`;continue}const c=n,p=t.get(c.table);if(!p)throw new Error(`Cannot validate ${c.type}: table ${JSON.stringify(c.table)} does not expose findOne`);const u="RowLookup"===c.type||"RowLookup[]"===c.type;if(u&&!a(l)||!u&&!s(l))return`${o} contains a non-primitive lookup value`;const d=u?l:{[c.column]:l},f=c.filter?{$and:[c.filter,d]}:d;if(!await(p?.findOne?.(f)))return`${o} does not reference an existing row in ${JSON.stringify(c.table)}`}};t.getJSONBSchemaValidationErrorAsync=async(e,t,n,i)=>{const r=[],o=u(t,e,void 0,i,r);if(o)return{error:o};for(const e of r){const t=await f(e,n);if(t)return{error:t}}return{data:t}},t.validateJSONBObjectAgainstSchema=(e,n,i,r=!1)=>{const{error:o}=(0,t.getJSONBObjectSchemaValidationError)(e,n,i,r);return void 0===o},t.assertJSONBObjectAgainstSchema=(e,n,i,r=!1)=>{const{error:o}=(0,t.getJSONBObjectSchemaValidationError)(e,n,i,r);if(o)throw new Error(o)}},699(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.getJSONSchemaObject=void 0,t.getJSONBSchemaAsJSONSchema=function(e,n,i){return(0,t.getJSONSchemaObject)(i,{id:`${e}.${n}`})};const i=n(472),r=n(704),o=e=>{if(!e)return;const t=e.endsWith("[]")?e.slice(0,-2):e;return{type:"integer"===t?"integer":"boolean"===t?"boolean":"number"===t?"number":"any"===t||"unknown"===t||t.endsWith("Lookup")||"Uint8Array"===t||"Blob"===t||"FileLike"===t?void 0:"string",isArray:e.endsWith("[]")}};t.getJSONSchemaObject=(e,n)=>{const{type:s,arrayOf:a,arrayOfType:l,description:c,nullable:p,oneOf:u,oneOfType:d,title:m,record:f,tuple:y,...g}="string"==typeof e?{type:e}:e;let h={};const b={...(g.enum||g.allowedValues?.length&&("string"!=typeof s||!s.endsWith("[]")))&&{enum:g.allowedValues?.slice(0)??g.enum.slice(0)},...!!c&&{description:c},...!!m&&{title:m}};if(g.enum?.length){const e=typeof g.enum[0];b.type="number"===e?"number":"boolean"===e?"boolean":"string"}if("string"==typeof s||a||l){if(s&&"string"!=typeof s)throw"Not expected";h=a||l||s?.endsWith("[]")?{type:"array",items:a||l?(0,t.getJSONSchemaObject)(a||{type:l}):s?.startsWith("any")?{type:void 0}:{type:o(s)?.type,...g.allowedValues&&{enum:g.allowedValues.slice(0)}}}:{type:o(s)?.type}}else if((0,i.isObject)(s))h={type:"object",required:(0,r.safeGetKeys)(s).filter(e=>{const t=s[e];return"string"==typeof t||!t.optional}),properties:(0,i.getObjectEntries)(s).reduce((e,[n,i])=>({...e,[n]:(0,t.getJSONSchemaObject)(i)}),{})};else if(y)h={type:"array",items:y.map(e=>(0,t.getJSONSchemaObject)(e)),additionalItems:!1,minItems:y.length,maxItems:y.length};else if(u||d){const e=u||d.map(e=>({type:e}));h={oneOf:e.map(e=>(0,t.getJSONSchemaObject)(e))}}else f&&(h={type:"object",...f.values&&!f.keysEnum&&{additionalProperties:(0,t.getJSONSchemaObject)(f.values)},...f.keysEnum&&{properties:f.keysEnum.reduce((e,n)=>({...e,[n]:f.values?(0,t.getJSONSchemaObject)(f.values):{type:{}}}),{})}});if(p){const e={type:"null"};h.oneOf?h.oneOf.push(e):h.enum&&!h.enum.includes(null)?h.enum.push(null):h={oneOf:[h,e]}}return{...n?{$id:n?.id,$schema:"https://json-schema.org/draft/2020-12/schema"}:void 0,...b,...h}}},394(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.getJSONBTSTypes=void 0,t.getJSONBSchemaTSTypes=function(e,n,i="",r){return(0,t.getJSONBTSTypes)(r,{...e,nullable:n.nullable},void 0,i)};const i=n(806),r=n(897),o=e=>null===e?"null":void 0===e?"undefined":"string"==typeof e?JSON.stringify(e):String(e);t.getJSONBTSTypes=(e,n,a=!1,l="",c=0)=>{const p=(0,r.getFieldTypeObj)(n),u=p.nullable?"null | ":"";if("string"==typeof p.type&&p.type.includes("Lookup"))return((e,t)=>{const n=t.nullable?"null | ":"",r=t.type.endsWith("[]")?"[]":"";if("TableLookup"===t.type||"TableLookup[]"===t.type)return`${n}string${r}`;if("ColumnLookup"===t.type||"ColumnLookup[]"===t.type)return`${n}{ "table": string; "column": string; }${r}`;const o=t,s=e.find(e=>e.name===o.table)?.columns;if("ValueLookup"===t.type||"ValueLookup[]"===t.type){const e=t,o=s?.find(t=>t.name===e.column)?.udt_name;return`${n}${(0,i.postgresToTsType)(o??"text")}${r}`}return`${n}${s?`{ ${s.map(e=>`${JSON.stringify(e.name)}?: ${e.is_nullable?"null | ":""} ${(0,i.postgresToTsType)(e.udt_name)}; `).join(" ")} }`:"any"}${r}`})(e,p);if("string"==typeof p.type){const e=p.type.replace("integer","number").replace("time","string").replace("timestamp","string").replace("FileLike","{ name: string; type: string; data: Blob; }").replace("Date","string");if(p.allowedValues){const e=p.type.endsWith("[]")?"[]":"";return u+` (${p.allowedValues.map(e=>JSON.stringify((0,i.isObject)(e)?e.value:e)).join(" | ")})${e}`}return u+e}if((0,i.isObject)(p.type)){const n=e=>e.trim().endsWith(";")?e:e.trim()+";",{type:o}=p,l=a?" ":" ";let d=` {${l}`+(0,i.getObjectEntries)(o).map(([i,o])=>{const a=(0,r.getFieldTypeObj)(o),p=s(i)?i:JSON.stringify(i);return`${l}${p}${a.optional?"?":""}: `+n((0,t.getJSONBTSTypes)(e,a,!0,void 0,c+1))}).join(" ")+`${l}}`;return a||(d=n(d)),a&&(d=d.split("\n").join("")),u+d}if(p.enum)return u+p.enum.map(e=>o(e)).join(" | ");if(p.tuple)return`${u}[${p.tuple.map(n=>(0,t.getJSONBTSTypes)(e,n,!0,void 0,c+1)).join(", ")}]`;if(p.oneOf||p.oneOfType){const n=p.oneOf||p.oneOfType.map(e=>({type:e}));return(p.nullable?`\n${l} | null`:"")+n.map(n=>`\n${l} | `+(0,t.getJSONBTSTypes)(e,n,!0,void 0,c+1)).join("")}if(p.arrayOf||p.arrayOfType){const n=p.arrayOf||{type:p.arrayOfType};return`${p.nullable?"null | ":""} ( ${(0,t.getJSONBTSTypes)(e,n,!0,void 0,c+1)} )[]`}if(p.record){const{keysEnum:n,values:i,partial:r}=p.record,s=e=>r?`Partial<Record<${e}>>`:`Record<${e}>`;return`${p.nullable?"null |":""} ${s(`${n?.map(e=>o(e)).join(" | ")??"string"}, ${i?(0,t.getJSONBTSTypes)(e,i,!0,void 0,c+1):"any"}`)}`}throw"Unexpected getSchemaTSTypes: "+JSON.stringify({fieldType:p},null,2)};const s=e=>/^[A-Za-z$_][A-Za-z0-9$_]*$/.test(e)},704(e,t){t.safeGetKeys=t.safeGetProperty=t.safeHasOwn=void 0;const n=["__proto__","constructor","prototype"];t.safeHasOwn=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),t.safeGetProperty=(e,t)=>{if(n.includes(t)){const n=Object.getOwnPropertyDescriptor(e,t);return n?.value}return e[t]},t.safeGetKeys=e=>{const i=Object.keys(e);for(const r of n)(0,t.safeHasOwn)(e,r)&&!i.includes(r)&&i.push(r);return i}},502(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.WAL=void 0;const i=n(806);t.WAL=class{constructor(e){if(this.changed={},this.sending={},this.sentHistory={},this.callbacks=[],this.sort=(e,t)=>{const{orderBy:n}=this.options;return n&&e&&t&&n.map(n=>{if(!(n.fieldName in e)||!(n.fieldName in t))throw"Replication error: \n some orderBy fields missing from data";let i=n.asc?e[n.fieldName]:t[n.fieldName],r=n.asc?t[n.fieldName]:e[n.fieldName],o=+i-+r,s=i<r?-1:i==r?0:1;return"number"===n.tsDataType&&Number.isFinite(o)?o:s}).find(e=>e)||0},this.isInHistory=e=>{if(!e)throw"Provide item";const t=e[this.options.synced_field];if(!Number.isFinite(+t))throw"Provided item Synced field value is missing/invalid ";const n=this.sentHistory[this.getIdStr(e)],i=n?.[this.options.synced_field];if(n){if(!Number.isFinite(+i))throw"Provided historic item Synced field value is missing/invalid";if(+i===+t)return!0}return!1},this.addData=e=>((0,i.isEmpty)(this.changed)&&this.options.onSendStart&&this.options.onSendStart(),e.forEach(e=>{var t;const{initial:n,current:i,delta:r}={...e};if(!i)throw"Expecting { current: object, initial?: object }";const o=this.getIdStr(i);this.changed??(this.changed={}),(t=this.changed)[o]??(t[o]={initial:n,current:i,delta:r}),this.changed[o].current={...this.changed[o].current,...i},this.changed[o].delta={...this.changed[o].delta,...r}}),this.sendItems()),this.getPendingItems=()=>[...Object.values(this.sending),...Object.values(this.changed)],this.isOnSending=!1,this.isSendingTimeout=void 0,this.willDeleteHistory=void 0,this.sendItems=async()=>{const{DEBUG_MODE:e,onSend:t,onSendEnd:n,batch_size:r,throttle:o,historyAgeSeconds:s=2}=this.options;if(this.isSendingTimeout||this.sending&&!(0,i.isEmpty)(this.sending))return;if(!this.changed||(0,i.isEmpty)(this.changed))return;let a,l=[],c=[],p={};Object.keys(this.changed).sort((e,t)=>this.sort(this.changed[e].current,this.changed[t].current)).slice(0,r).map(e=>{let t={...this.changed[e]};this.sending[e]={...t},c.push({...t}),p[e]={...t.current},delete this.changed[e]}),l=c.map(e=>{let t={};return Object.keys(e.current).map(n=>{const r=e.initial?.[n],o=e.current[n];![this.options.synced_field,...this.options.id_fields].includes(n)&&(0,i.isEqual)(r,o)||(t[n]=o)}),t}),e&&console.log(this.options.id," SENDING lr->",l[l.length-1]),this.isSendingTimeout||(this.isSendingTimeout=setTimeout(()=>{this.isSendingTimeout=void 0,(0,i.isEmpty)(this.changed)||this.sendItems()},o)),this.isOnSending=!0;try{await t(l,c),s&&(this.sentHistory={...this.sentHistory,...p},this.willDeleteHistory||(this.willDeleteHistory=setTimeout(()=>{this.willDeleteHistory=void 0,this.sentHistory={}},1e3*s)))}catch(e){a=e,console.error("WAL onSend failed:",e,l,c)}if(this.isOnSending=!1,this.callbacks.length){const e=Object.keys(this.sending);this.callbacks.forEach((t,n)=>{t.idStrs=t.idStrs.filter(t=>e.includes(t)),t.idStrs.length||t.cb(a)}),this.callbacks=this.callbacks.filter(e=>e.idStrs.length)}this.sending={},e&&console.log(this.options.id," SENT lr->",l[l.length-1]),(0,i.isEmpty)(this.changed)?n&&n(l,c,a):this.sendItems()},this.options={...e},!this.options.orderBy){const{synced_field:t,id_fields:n}=e;this.options.orderBy=[t,...n.sort()].map(e=>({fieldName:e,tsDataType:e===t?"number":"string",asc:!0}))}}isSending(){const e=this.isOnSending||!((0,i.isEmpty)(this.sending)&&(0,i.isEmpty)(this.changed));return this.options.DEBUG_MODE&&console.log(this.options.id," CHECKING isSending ->",e),e}getIdStr(e){return this.options.id_fields.sort().map(t=>String(e[t])).join(".")}getIdObj(e){let t={};return this.options.id_fields.sort().map(n=>{t[n]=e[n]}),t}getDeltaObj(e){let t={};return Object.keys(e).map(n=>{this.options.id_fields.includes(n)||(t[n]=e[n])}),t}}},509(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.AUDIT_TABLE_COLUMNS=t.AUDIT_TABLE_COLUMN_NAMES=t.AUDIT_TABLE_COLUMN_DEFINITIONS=void 0,t.AUDIT_TABLE_COLUMN_DEFINITIONS={id:"BIGSERIAL PRIMARY KEY",created_at:"TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()",schema_name:"TEXT NOT NULL",table_name:"TEXT NOT NULL",operation:{enum:["INSERT","UPDATE","DELETE"]},old_id:"JSONB",new_id:"JSONB",old_row:"JSONB",new_row:"JSONB",actor:"JSONB",db_context:{jsonbSchema:{type:{transaction_id:"string",transaction_started_at:"string",statement_started_at:"string",current_role:"string",session_user:"string",application_name:"string"}}}},t.AUDIT_TABLE_COLUMN_NAMES=Object.fromEntries(Object.keys(t.AUDIT_TABLE_COLUMN_DEFINITIONS).map(e=>[e,e])),t.AUDIT_TABLE_COLUMNS=Object.values(t.AUDIT_TABLE_COLUMN_NAMES)},618(e,t){Object.defineProperty(t,"__esModule",{value:!0})},356(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.authContract=void 0;const i=n(749),r={username:"string",password:{type:"string",optional:!0}};t.authContract={login:{request:{type:{...r,remember_me:{type:"boolean",optional:!0},totp_token:{type:"string",optional:!0},totp_recovery_code:{type:"string",optional:!0}}},response:{oneOf:[i.authResponseSchemas.authSuccess,i.authResponseSchemas.passwordLoginFailure,i.authResponseSchemas.magicLinkAuthSuccess,i.authResponseSchemas.magicLinkAuthFailure,i.authResponseSchemas.oauthRegisterFailure,i.authResponseSchemas.codeVerificationFailure]}},register:{request:{type:{...r,invitationToken:{type:"string",optional:!0},totpTokenConfirmation:{type:"string",optional:!0}}},response:{oneOf:[i.authResponseSchemas.passwordRegisterSuccess,i.authResponseSchemas.passwordRegisterFailure]}},magicLinkOrOTP:{request:{oneOfType:[{id:"string",returnToken:{type:"boolean",optional:!0}},{email:"string",code:"string",returnToken:{type:"boolean",optional:!0}}]},response:{oneOf:[i.authResponseSchemas.authSuccess,i.authResponseSchemas.emailConfirmationSuccess,i.authResponseSchemas.magicLinkAuthFailure,i.authResponseSchemas.codeVerificationFailure,i.authResponseSchemas.invalidEmail]}},logout:{request:{type:{}},response:{oneOf:[i.authResponseSchemas.authSuccess,i.authResponseSchemas.commonFailure]}}}},749(e,t){t.authResponseSchemas=void 0;const n={type:"string",optional:!0},i={success:{enum:[!0]},message:n},r={success:{enum:[!1]},message:n},o=["server-error","rate-limit-exceeded","something-went-wrong"],s=[...o,"no-match","inactive-account"];t.authResponseSchemas={authSuccess:{type:{...i,code:{enum:[void 0],optional:!0},token:{type:"string",optional:!0}}},commonFailure:{type:{...r,code:{enum:o}}},authFailure:{type:{...r,code:{enum:s}}},magicLinkAuthSuccess:{type:{...i,code:{enum:["email-verification-code-sent","magic-link-sent"]}}},magicLinkAuthFailure:{type:{...r,code:{enum:[...s,"expired-magic-link","invalid-magic-link","used-magic-link"]}}},oauthRegisterFailure:{type:{...r,code:{enum:[...o,"provider-issue"]}}},passwordLoginFailure:{type:{...r,code:{enum:[...s,"totp-token-missing","invalid-username","username-missing","invalid-email","password-missing","invalid-password","is-from-OAuth","is-from-magic-link","invalid-totp-recovery-code","invalid-totp-code","email-not-confirmed"]}}},passwordRegisterFailure:{type:{...r,code:{enum:[...o,"weak-password","user-already-registered","username-missing","password-missing","invalid-email-confirmation-code","expired-email-confirmation-code","inactive-account"]}}},passwordRegisterSuccess:{type:{...i,code:{enum:["email-verification-code-sent","already-registered-but-did-not-confirm-email","email-verified"]}}},codeVerificationFailure:{type:{...r,code:{enum:[...s,"invalid-otp-code","expired-otp-code"]}}},emailConfirmationSuccess:{type:{...i,code:{enum:["email-verified"]}}},invalidEmail:{type:{...r,code:{enum:["invalid-email"]}}}}},184(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.FILE_VERSION_TABLE_COLUMN_DEFINITIONS=t.FILE_TABLE_VERSION_COLUMN_DEFINITIONS=t.FILE_TABLE_COLUMN_DEFINITIONS=void 0;const i=n(472);t.FILE_TABLE_COLUMN_DEFINITIONS={id:"UUID PRIMARY KEY DEFAULT gen_random_uuid()",storage_key:"UUID UNIQUE",extension:"TEXT NOT NULL DEFAULT ''",content_type:"TEXT NOT NULL DEFAULT ''",content_length:"BIGINT NOT NULL DEFAULT 0",etag:"TEXT NOT NULL DEFAULT ''",original_name:"TEXT NOT NULL",original_last_modified:"TIMESTAMPTZ",description:"TEXT",url:"TEXT NOT NULL DEFAULT ''",cloud_url:"TEXT",local_file_path:"TEXT",signed_url:"TEXT",signed_url_expires:"BIGINT",added:"TIMESTAMP NOT NULL DEFAULT NOW()",updated:"TIMESTAMP NOT NULL DEFAULT NOW()",deleted:"TIMESTAMPTZ",deleted_from_storage:"TIMESTAMPTZ",data:"BYTEA NOT NULL CHECK (data = decode('01', 'hex'))"},t.FILE_TABLE_VERSION_COLUMN_DEFINITIONS={version:"INTEGER NOT NULL DEFAULT 1"},t.FILE_VERSION_TABLE_COLUMN_DEFINITIONS={...(0,i.omitKeys)(t.FILE_TABLE_COLUMN_DEFINITIONS,["data"]),storage_key:"UUID NOT NULL",file_id:"UUID NOT NULL",version:"INTEGER NOT NULL",created:"TIMESTAMP NOT NULL DEFAULT NOW()"}},521(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.CONTENT_TYPE_TO_EXT=void 0,t.CONTENT_TYPE_TO_EXT={"text/html":["html","htm","shtml"],"text/css":["css"],"text/csv":["csv"],"text/tsv":["tsv"],"text/tab-separated-values":["tsv"],"text/xml":["xml"],"text/mathml":["mml"],"text/plain":["txt","text","log"],"text/markdown":["md","markdown","qmd","rmd"],"text/x-markdown":["md","markdown"],"text/asciidoc":["adoc","asciidoc","asc"],"text/x-asciidoc":["adoc","asciidoc","asc"],"text/x-tex":["tex"],"text/x-latex":["tex","latex"],"text/rtf":["rtf"],"text/vtt":["vtt"],"text/calendar":["ics","ifb"],"text/vcard":["vcf","vcard"],"text/javascript":["js","mjs","cjs"],"text/yaml":["yaml","yml"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/x-component":["htc"],"image/gif":["gif"],"image/jpeg":["jpeg","jpg"],"image/png":["png"],"image/tiff":["tif","tiff"],"image/bmp":["bmp"],"image/avif":["avif"],"image/heic":["heic"],"image/heif":["heif"],"image/vnd.wap.wbmp":["wbmp"],"image/x-icon":["ico"],"image/vnd.microsoft.icon":["ico"],"image/x-jng":["jng"],"image/x-ms-bmp":["bmp"],"image/svg+xml":["svg"],"image/webp":["webp"],"application/sql":["sql"],"application/json":["json"],"application/xml":["xml","xsl","xsd","nxml","xbrl","dclg"],"application/yaml":["yaml","yml"],"application/geo+json":["geojson"],"application/javascript":["js","mjs","cjs"],"application/x-javascript":["js"],"application/atom+xml":["atom"],"application/rss+xml":["rss"],"application/java-archive":["jar","war","ear"],"application/mac-binhex40":["hqx"],"application/msword":["doc","docx","dot"],"application/x-msword":["doc","dot"],"application/pdf":["pdf"],"application/postscript":["ps","eps","ai"],"application/rtf":["rtf"],"application/x-rtf":["rtf"],"application/epub+zip":["epub"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.keynote":["key"],"application/x-iwork-pages-sffpages":["pages"],"application/x-iwork-numbers-sffnumbers":["numbers"],"application/x-iwork-keynote-sffkey":["key"],"application/vnd.box.boxnote":["boxnote"],"application/vnd.ibm.modcap":["afp"],"application/x-afp":["afp"],"application/x-ebcdic":["ebc","ebcdic"],"application/vnd.ms-excel":["xls","xlsx","xlt"],"application/x-msexcel":["xls","xlt"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-powerpoint":["ppt","pptx","pot","pps"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-outlook":["msg"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/x-7z-compressed":["7z"],"application/gzip":["gz","tgz"],"application/x-tar":["tar"],"application/x-bzip2":["bz2","tbz2"],"application/x-xz":["xz"],"application/zstd":["zst"],"application/vnd.rar":["rar"],"application/x-cocoa":["cco"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-makeself":["run"],"application/x-perl":["pl","pm"],"application/x-pilot":["prc","pdb"],"application/x-rar-compressed":["rar"],"application/x-redhat-package-manager":["rpm"],"application/x-sea":["sea"],"application/x-shockwave-flash":["swf"],"application/x-stuffit":["sit"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-latex":["latex"],"application/x-mimearchive":["mhtml","mht"],"application/x-x509-ca-cert":["der","pem","crt"],"application/x-xpinstall":["xpi"],"application/xhtml+xml":["xhtml"],"application/zip":["zip","dclx"],"application/octet-stream":["bin","exe","dll","deb","dmg","eot","iso","img","msi","msp","msm"],"audio/midi":["mid","midi","kar"],"audio/mpeg":["mp3"],"audio/mp3":["mp3"],"audio/mp4":["m4a","mp4a","m4b"],"audio/m4a":["m4a"],"audio/x-m4a":["m4a"],"audio/aac":["aac","adts"],"audio/wav":["wav"],"audio/x-wav":["wav"],"audio/vnd.wave":["wav"],"audio/flac":["flac"],"audio/x-flac":["flac"],"audio/ogg":["ogg","oga","opus","spx"],"audio/webm":["weba"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-realaudio":["ra"],"video/3gpp":["3gpp","3gp"],"video/mpeg":["mpeg","mpg"],"video/quicktime":["mov"],"video/x-flv":["flv"],"video/x-mng":["mng"],"video/x-ms-asf":["asx","asf"],"video/x-ms-wmv":["wmv"],"video/x-msvideo":["avi"],"video/avi":["avi"],"video/x-matroska":["mkv"],"video/mp4":["m4v","mp4"],"video/webm":["webm"],"video/ogg":["ogv"],"message/rfc822":["eml","mime","mht","mhtml"],"multipart/related":["mhtml","mht"]}},209(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.COMPLEX_FILTER_KEY=t.ComplexFilterComparisonKeys=t.EXISTS_KEYS=t.GeomFilter_Funcs=t.GeomFilterKeys=t.ArrayFilterOperands=t.TextFilter_FullTextSearchFilterKeys=t.TextFilterFTSKeys=t.TextFilterKeys=t.JsonbFilterKeys=t.JsonbOperands=t.BetweenFilterKeys=t.CompareInFilterKeys=t.CompareFilterKeys=void 0;const i=n(472);t.CompareFilterKeys=["=","<>",">","<",">=","<=","$eq","$ne","$gt","$gte","$lt","$lte","$isDistinctFrom","$isNotDistinctFrom"],t.CompareInFilterKeys=["$in","$nin"],t.BetweenFilterKeys=["$between","$notBetween"],t.JsonbOperands={"@>":{Operator:"@>","Right Operand Type":"jsonb",Description:"Does the left JSON value contain the right JSON path/value entries at the top level?",Example:'\'{"a":1, "b":2}\'::jsonb @> \'{"b":2}\'::jsonb'},"<@":{Operator:"<@","Right Operand Type":"jsonb",Description:"Are the left JSON path/value entries contained at the top level within the right JSON value?",Example:'\'{"b":2}\'::jsonb <@ \'{"a":1, "b":2}\'::jsonb'},"?":{Operator:"?","Right Operand Type":"text",Description:"Does the string exist as a top-level key within the JSON value?",Example:"'{\"a\":1, \"b\":2}'::jsonb ? 'b'"},"?|":{Operator:"?|","Right Operand Type":"text[]",Description:"Do any of these array strings exist as top-level keys?",Example:"'{\"a\":1, \"b\":2, \"c\":3}'::jsonb ?| array['b', 'c']"},"?&":{Operator:"?&","Right Operand Type":"text[]",Description:"Do all of these array strings exist as top-level keys?",Example:"'[\"a\", \"b\"]'::jsonb ?& array['a', 'b']"},"||":{Operator:"||","Right Operand Type":"jsonb",Description:"Concatenate two jsonb values into a new jsonb value",Example:'\'["a", "b"]\'::jsonb || \'["c", "d"]\'::jsonb'},"-":{Operator:"-","Right Operand Type":"integer",Description:"Delete the array element with specified index (Negative integers count from the end). Throws an error if top level container is not an array.",Example:'\'["a", "b"]\'::jsonb - 1'},"#-":{Operator:"#-","Right Operand Type":"text[]",Description:"Delete the field or element with specified path (for JSON arrays, negative integers count from the end)",Example:"'[\"a\", {\"b\":1}]'::jsonb #- '{1,b}'"},"@?":{Operator:"@?","Right Operand Type":"jsonpath",Description:"Does JSON path return any item for the specified JSON value?",Example:"'{\"a\":[1,2,3,4,5]}'::jsonb @? '$.a[*] ? (@ > 2)'"},"@@":{Operator:"@@","Right Operand Type":"jsonpath",Description:"Returns the result of JSON path predicate check for the specified JSON value. Only the first item of the result is taken into account. If the result is not Boolean, then null is returned.",Example:"'{\"a\":[1,2,3,4,5]}'::jsonb @@ '$.a[*] > 2'"}},t.JsonbFilterKeys=(0,i.getKeys)(t.JsonbOperands),t.TextFilterKeys=["$ilike","$like","$nilike","$nlike"],t.TextFilterFTSKeys=["@@","@>","<@","$contains","$containedBy"],t.TextFilter_FullTextSearchFilterKeys=["to_tsquery","plainto_tsquery","phraseto_tsquery","websearch_to_tsquery"],t.ArrayFilterOperands=["@>","<@","=","$eq","$contains","$containedBy","&&","$overlaps"],t.GeomFilterKeys=["~","~=","@","|&>","|>>",">>","=","<<|","<<","&>","&<|","&<","&&&","&&"],t.GeomFilter_Funcs=["ST_MakeEnvelope","st_makeenvelope","ST_MakePolygon","st_makepolygon"],t.EXISTS_KEYS=["$exists","$notExists","$existsJoined","$notExistsJoined"],t.ComplexFilterComparisonKeys=[...t.TextFilterKeys,...t.JsonbFilterKeys,...t.CompareFilterKeys,...t.BetweenFilterKeys,...t.CompareInFilterKeys],t.COMPLEX_FILTER_KEY="$filter"},391(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.getActionFunctions=void 0,t.getActionFunctions=(e,t)=>Object.entries(e).flatMap(([e,n])=>Object.entries(n.input??{}).flatMap(([n,i])=>"string"==typeof i||"RowLookup"!==i.type&&"ValueLookup"!==i.type||i.table!==t.name||"ValueLookup"===i.type&&!t.columns.some(e=>e.name===i.column&&e.select)?[]:[{methodName:e,argName:n,lookup:i}]))},806(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.ABORTABLE_METHODS=t.CONTENT_TYPE_TO_EXT=t.getPossibleNestedInsert=t.SQL_COMMAND_TABLE_METHODS=t.CHANNELS=t.CHANNEL_PREFIX=t.ROW_ACTIONS_COLUMN=t.JOIN_PARAMS=t.JOIN_KEYS=t.getAllowedTableMethods=t.postgresToTsType=t.TS_PG_Types=t._PG_bytes=t._PG_geometric=t._PG_postgis=t._PG_interval=t._PG_date=t._PG_bool=t._PG_json=t._PG_numbers=t._PG_numbers_str=t._PG_numbers_num=t._PG_strings=void 0;const o=n(472),s=n(441);t._PG_strings=["bpchar","char","varchar","text","citext","uuid","time","timetz","interval","name","cidr","inet","macaddr","macaddr8","int4range","int8range","numrange","tsvector"],t._PG_numbers_num=["int2","int4","float4","float8","oid"],t._PG_numbers_str=["int8","numeric","money"],t._PG_numbers=[...t._PG_numbers_num,...t._PG_numbers_str],t._PG_json=["json","jsonb"],t._PG_bool=["bool"],t._PG_date=["date","timestamp","timestamptz"],t._PG_interval=["interval"],t._PG_postgis=["geometry","geography"],t._PG_geometric=["point","line","lseg","box","path","polygon","circle"],t._PG_bytes=["bytea"];const a={Uint8Array:t._PG_bytes,string:[...t._PG_strings,...t._PG_numbers_str,...t._PG_date,...t._PG_geometric,...t._PG_postgis,"lseg"],number:t._PG_numbers_num,boolean:t._PG_bool,any:[...t._PG_json,...t._PG_interval]};t.TS_PG_Types={...a,"number[]":a.number.map(e=>`_${e}`),"boolean[]":a.boolean.map(e=>`_${e}`),"string[]":a.string.map(e=>`_${e}`),"any[]":a.any.map(e=>`_${e}`)},t.postgresToTsType=e=>(0,o.getKeys)(t.TS_PG_Types).find(n=>(0,s.includes)(t.TS_PG_Types[n],e))??"any",t.getAllowedTableMethods=({publishInfo:e})=>{let n=[...e.select||e.insert||e.delete||e.update?t.SQL_COMMAND_TABLE_METHODS.schema:[],...t.SQL_COMMAND_TABLE_METHODS.select.filter(t=>{if(!e.select)return!1;const n="subscribeOne"===t?"subscribe":t;return!Object.keys(e.select.disabledMethods??{}).includes(n)&&("sync"!==t||void 0!==e.select.syncConfig)}),...t.SQL_COMMAND_TABLE_METHODS.update.filter(t=>e.update&&!Object.keys(e.update.disabledMethods??{}).includes(t)),...e.insert?t.SQL_COMMAND_TABLE_METHODS.insert:[],...e.delete?t.SQL_COMMAND_TABLE_METHODS.delete:[]];const i=new Map;return Object.values(t.SQL_COMMAND_TABLE_METHODS).forEach(e=>{e.forEach(e=>{i.set(e,(i.get(e)??0)+1)})}),i.forEach((e,t)=>{n.filter(e=>e===t).length!==e&&i.delete(t)}),Array.from(i.keys())},t.JOIN_KEYS=["$innerJoin","$leftJoin"],t.JOIN_PARAMS=["select","filter","offset","limit","orderBy","having"],t.ROW_ACTIONS_COLUMN="$prostgles_actions",t.CHANNEL_PREFIX="_psqlWS_.",t.CHANNELS={SCHEMA_CHANGED:t.CHANNEL_PREFIX+"schema-changed",SCHEMA:t.CHANNEL_PREFIX+"schema",DEFAULT:t.CHANNEL_PREFIX,SQL:`${t.CHANNEL_PREFIX}sql`,SQL_STREAM:`${t.CHANNEL_PREFIX}sql-stream`,METHOD:`${t.CHANNEL_PREFIX}method`,NOTICE_EV:`${t.CHANNEL_PREFIX}notice`,LISTEN_EV:`${t.CHANNEL_PREFIX}listen`,REGISTER:`${t.CHANNEL_PREFIX}register`,LOGIN:`${t.CHANNEL_PREFIX}login`,LOGOUT:`${t.CHANNEL_PREFIX}logout`,AUTH_GUARD:`${t.CHANNEL_PREFIX}authguard`,CONNECTION:`${t.CHANNEL_PREFIX}connection`,_preffix:t.CHANNEL_PREFIX},t.SQL_COMMAND_TABLE_METHODS={schema:["getColumns","getInfo"],insert:["insert","insertMany","upsert"],update:["update","upsert","updateBatch"],select:["findOne","find","count","size","subscribe","subscribeOne","sync"],delete:["delete","remove"]},t.getPossibleNestedInsert=(e,t,n=!0)=>{const i=(e.references??[]).map(e=>{const{ftable:n,fcols:i}=e,r=t.find(e=>e.name===n);if(!r)return;const o=r.columns.filter(e=>i.includes(e.name));return o.length?{ref:e,fcolsInfo:o}:void 0}).filter(o.isDefined),[r,...s]=i??[];if(!s.length)return r?.ref;const[a,...l]=i.filter(e=>e.fcolsInfo.some(e=>e.is_pkey));if(!l.length)return a?.ref;if(!n)throw["Cannot do a nested insert on column that references multiple tables.","Expecting only one reference to a single primary key fcol"].join("\n")},r(n(618),t),r(n(356),t),r(n(4),t),r(n(509),t),r(n(381),t),r(n(390),t);var l=n(521);Object.defineProperty(t,"CONTENT_TYPE_TO_EXT",{enumerable:!0,get:function(){return l.CONTENT_TYPE_TO_EXT}}),r(n(184),t),r(n(209),t),r(n(319),t),r(n(699),t),r(n(394),t),r(n(994),t),r(n(897),t),r(n(164),t),r(n(472),t),r(n(502),t),r(n(778),t),r(n(784),t),r(n(391),t),t.ABORTABLE_METHODS=["find","findOne","count","size"]},381(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.jobTableSchema=void 0;const n={target_table:{},user_id:{},occurrence:{},checkpoint:{},progress_message:{},progress_numeric:{},backoff:{enum:["fixed","exponential"]},reason:{enum:["trigger","rerun"]}};t.jobTableSchema={columns:{id:"UUID PRIMARY KEY",job_name:"TEXT NOT NULL",target_table:"TEXT",target_row_pkey:"JSONB NOT NULL",params:"JSONB NOT NULL",user_id:"TEXT",occurrence:"TIMESTAMPTZ",reason:"TEXT NOT NULL DEFAULT 'trigger'",status:"TEXT NOT NULL DEFAULT 'pending'",attempts:"INTEGER NOT NULL DEFAULT 0",max_attempts:"INTEGER NOT NULL",delay_ms:"DOUBLE PRECISION NOT NULL",backoff:"TEXT NOT NULL",cancel_requested:"BOOLEAN NOT NULL DEFAULT FALSE",checkpoint:"JSONB",has_checkpoint:"BOOLEAN NOT NULL DEFAULT FALSE",progress_message:"TEXT",progress_numeric:{nullable:!0,jsonbSchema:{type:{done:"number",total:"number"}}},error:"JSONB",run_at:"TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()",lease_token:"UUID",locked_until:"TIMESTAMPTZ",created_at:"TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()",finished_at:"TIMESTAMPTZ"},check:{$or:[{...n,status:"pending",error:{}},{...n,status:"running",error:{},lease_token:{$ne:null},locked_until:{$ne:null}},{...n,status:"succeeded",finished_at:{$ne:null}},{...n,status:"failed",error:{$ne:null},finished_at:{$ne:null}},{...n,status:"cancelled",error:{},finished_at:{$ne:null}}]}}},319(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.leftJoin=t.innerJoin=t.parsedJoinPathSchema=t.defineJoin=void 0;const i=n(472);t.defineJoin=e=>e,t.parsedJoinPathSchema={type:{table:"string",on:{oneOf:[{type:"string"},{arrayOf:{record:{values:"string"}}}]},params:{record:{values:"unknown"},optional:!0},reversed:{type:"boolean",optional:!0}}};const r=(e="$leftJoin")=>(t,n,r,o={})=>({[e]:o.path??t,filter:n,...(0,i.omitKeys)(o,["path","select"]),select:r});t.innerJoin=r("$innerJoin"),t.leftJoin=r("$leftJoin")},666(e,t){function n(e,t){var n=e[0],i=e[1],l=e[2],c=e[3];n=r(n,i,l,c,t[0],7,-680876936),c=r(c,n,i,l,t[1],12,-389564586),l=r(l,c,n,i,t[2],17,606105819),i=r(i,l,c,n,t[3],22,-1044525330),n=r(n,i,l,c,t[4],7,-176418897),c=r(c,n,i,l,t[5],12,1200080426),l=r(l,c,n,i,t[6],17,-1473231341),i=r(i,l,c,n,t[7],22,-45705983),n=r(n,i,l,c,t[8],7,1770035416),c=r(c,n,i,l,t[9],12,-1958414417),l=r(l,c,n,i,t[10],17,-42063),i=r(i,l,c,n,t[11],22,-1990404162),n=r(n,i,l,c,t[12],7,1804603682),c=r(c,n,i,l,t[13],12,-40341101),l=r(l,c,n,i,t[14],17,-1502002290),n=o(n,i=r(i,l,c,n,t[15],22,1236535329),l,c,t[1],5,-165796510),c=o(c,n,i,l,t[6],9,-1069501632),l=o(l,c,n,i,t[11],14,643717713),i=o(i,l,c,n,t[0],20,-373897302),n=o(n,i,l,c,t[5],5,-701558691),c=o(c,n,i,l,t[10],9,38016083),l=o(l,c,n,i,t[15],14,-660478335),i=o(i,l,c,n,t[4],20,-405537848),n=o(n,i,l,c,t[9],5,568446438),c=o(c,n,i,l,t[14],9,-1019803690),l=o(l,c,n,i,t[3],14,-187363961),i=o(i,l,c,n,t[8],20,1163531501),n=o(n,i,l,c,t[13],5,-1444681467),c=o(c,n,i,l,t[2],9,-51403784),l=o(l,c,n,i,t[7],14,1735328473),n=s(n,i=o(i,l,c,n,t[12],20,-1926607734),l,c,t[5],4,-378558),c=s(c,n,i,l,t[8],11,-2022574463),l=s(l,c,n,i,t[11],16,1839030562),i=s(i,l,c,n,t[14],23,-35309556),n=s(n,i,l,c,t[1],4,-1530992060),c=s(c,n,i,l,t[4],11,1272893353),l=s(l,c,n,i,t[7],16,-155497632),i=s(i,l,c,n,t[10],23,-1094730640),n=s(n,i,l,c,t[13],4,681279174),c=s(c,n,i,l,t[0],11,-358537222),l=s(l,c,n,i,t[3],16,-722521979),i=s(i,l,c,n,t[6],23,76029189),n=s(n,i,l,c,t[9],4,-640364487),c=s(c,n,i,l,t[12],11,-421815835),l=s(l,c,n,i,t[15],16,530742520),n=a(n,i=s(i,l,c,n,t[2],23,-995338651),l,c,t[0],6,-198630844),c=a(c,n,i,l,t[7],10,1126891415),l=a(l,c,n,i,t[14],15,-1416354905),i=a(i,l,c,n,t[5],21,-57434055),n=a(n,i,l,c,t[12],6,1700485571),c=a(c,n,i,l,t[3],10,-1894986606),l=a(l,c,n,i,t[10],15,-1051523),i=a(i,l,c,n,t[1],21,-2054922799),n=a(n,i,l,c,t[8],6,1873313359),c=a(c,n,i,l,t[15],10,-30611744),l=a(l,c,n,i,t[6],15,-1560198380),i=a(i,l,c,n,t[13],21,1309151649),n=a(n,i,l,c,t[4],6,-145523070),c=a(c,n,i,l,t[11],10,-1120210379),l=a(l,c,n,i,t[2],15,718787259),i=a(i,l,c,n,t[9],21,-343485551),e[0]=d(n,e[0]),e[1]=d(i,e[1]),e[2]=d(l,e[2]),e[3]=d(c,e[3])}function i(e,t,n,i,r,o){return t=d(d(t,e),d(i,o)),d(t<<r|t>>>32-r,n)}function r(e,t,n,r,o,s,a){return i(t&n|~t&r,e,t,o,s,a)}function o(e,t,n,r,o,s,a){return i(t&r|n&~r,e,t,o,s,a)}function s(e,t,n,r,o,s,a){return i(t^n^r,e,t,o,s,a)}function a(e,t,n,r,o,s,a){return i(n^(t|~r),e,t,o,s,a)}function l(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}t.md5=u;var c="0123456789abcdef".split("");function p(e){for(var t="",n=0;n<4;n++)t+=c[e>>8*n+4&15]+c[e>>8*n&15];return t}function u(e){return function(e){for(var t=0;t<e.length;t++)e[t]=p(e[t]);return e.join("")}(function(e){var t,i=e.length,r=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=e.length;t+=64)n(r,l(e.substring(t-64,t)));e=e.substring(t-64);var o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t<e.length;t++)o[t>>2]|=e.charCodeAt(t)<<(t%4<<3);if(o[t>>2]|=128<<(t%4<<3),t>55)for(n(r,o),t=0;t<16;t++)o[t]=0;return o[14]=8*i,n(r,o),r}(e))}function d(e,t){return e+t&4294967295}u("hello")},784(e,t){Object.defineProperty(t,"__esModule",{value:!0})},164(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.ReplicationProtocol=t.getSyncChannelName=void 0;const i=n(806);var r;t.getSyncChannelName=({tableName:e,filter:t={},select:n="*"})=>[i.CHANNEL_PREFIX,e,"sync",(0,i.stableStringify)(t),"string"==typeof n?n:(0,i.stableStringify)(n)].join("."),function(e){e.CreateSchema={name:"Create",source:"client",request:{type:{tableName:"string",command:{enum:["sync"]},param1:{record:{values:"unknown"}},param2:{type:{select:"unknown"}}}},response:{type:{id_fields:"string[]",synced_field:"string",channelName:"string",data:"any[]",isSynced:"boolean"}}};const t={state:{enum:["syncing"]},c_fr:{optional:!0,record:{values:"unknown"}},c_lr:{optional:!0,record:{values:"unknown"}},c_count:"number"},n={state:{enum:["syncing-data"]},c_fr:{record:{values:"unknown"}},c_lr:{record:{values:"unknown"}},c_count:"number",data:{arrayOf:{record:{values:"unknown"}}}},r={from_synced:{oneOf:["string","number",{enum:[void 0]}]},to_synced:{oneOf:["string","number",{enum:[void 0]}]}};e.ServerSyncRequest={name:"ServerSyncRequest",source:"server",request:{type:{...r,end_offset:{oneOf:["number",{enum:[null]}]}}},response:{oneOfType:[t,n,{state:{enum:["error"]},err:"unknown"}]}},e.ClientSyncRequest={name:"ClientSyncRequest",source:"client",request:{oneOfType:[t,n]},response:{oneOfType:[{success:{enum:[!0]}},{success:{enum:[!1]},err:"unknown"}]}},e.PullRequest={name:"PullRequest",source:"server",request:{type:{...r,offset:{oneOf:["number",{enum:[void 0]}]},limit:{oneOf:["number",{enum:[void 0]}]}}},response:{oneOfType:[{success:{enum:[!0]},data:{arrayOf:{record:{values:"unknown"}}}},{success:{enum:[!1]},err:"unknown"}]}},e.UpdateRequest={name:"UpdateRequest",source:"server",request:{oneOfType:[{state:{enum:["error"]},err:"unknown"},{state:{enum:["synced"]},isSynced:"boolean"},{state:{enum:["syncing"]},data:{arrayOf:{record:{values:"unknown"}}}}]},response:{oneOfType:[{success:{enum:[!0]}},{success:{enum:[!1]},err:"unknown"}]}};const o={ClientSyncRequest:e.ClientSyncRequest,ServerSyncRequest:e.ServerSyncRequest,PullRequest:e.PullRequest,UpdateRequest:e.UpdateRequest},s=Object.values(o),a=(e,t,n,r)=>(t.removeAllListeners(e),t.on(e,async(e,t)=>{const{type:o,request:a}=(0,i.isObject)(e)?e:{};if("string"!=typeof o||!a)return void t("Unexpected data");const l=s.find(e=>e.name===o&&e.source!==n);if(!l)return void t("Invalid data.type");if(l.source===n)return void t("Invalid schema.source");if("server"===n){const e=(0,i.getJSONBSchemaValidationError)(l.request,a);if(void 0!==e.error)return console.error("Invalid request from client",e.error,a),void t(e.error)}const c=l.name;try{t(await(0,i.withTimeout)(Promise.resolve(r[c](a)),1e4))}catch(e){t((0,i.getSerialisableError)(e))}}),(0,i.fromEntries)((0,i.getEntries)(o).map(([r,o])=>{if(o.source===n)return[r,r=>(0,i.createPromiseWithTimeout)((s,a)=>{t.emit(e,{type:o.name,request:r},e=>{if("server"===n){const t=(0,i.getJSONBSchemaValidationError)(o.response,e);if(void 0!==t.error)return console.error("Invalid response from client for "+o.name,t.error,e),void a(t.error)}s(e)})},1e4)]}).filter(i.isDefined)));e.getServerHandlers=(e,t,n)=>a(e,t,"server",n),e.getClientHandlers=(e,t,n)=>a(e,t,"client",n)}(r||(t.ReplicationProtocol=r={}))},4(e,t){Object.defineProperty(t,"__esModule",{value:!0})},390(e,t){Object.defineProperty(t,"__esModule",{value:!0})},472(e,t,n){Object.defineProperty(t,"__esModule",{value:!0}),t.fromEntries=t.getEntries=t.createPromiseWithTimeout=t.withTimeout=t.getProperty=t.getSerialisableError=t.safeStringify=t.extractTypeUtil=t.reverseParsedPath=t.reverseJoinOn=t.tryCatch=t.getObjectEntries=t.isNotEmpty=t.pickKeys=void 0,t.asName=function(e){if(null==e||!e.toString||!e.toString())throw"Expecting a non empty string";return`"${e.toString().replace(/"/g,'""')}"`},t.omitKeys=r,t.filter=o,t.find=function(e,t){return o(e,t)[0]},t.stableStringify=function(e,t={}){t||(t={}),"function"==typeof t&&(t={cmp:t});var n,i="boolean"==typeof t.cycles&&t.cycles,r=t.cmp&&(n=t.cmp,function(e){return function(t,i){var r={key:t,value:e[t]},o={key:i,value:e[i]};return n(r,o)}}),o=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var n,s;if(Array.isArray(t)){for(s="[",n=0;n<t.length;n++)n&&(s+=","),s+=e(t[n])||"null";return s+"]"}if(null===t)return"null";if(-1!==o.indexOf(t)){if(i)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var a=o.push(t)-1,l=Object.keys(t).sort(r&&r(t));for(s="",n=0;n<l.length;n++){var c=l[n],p=e(t[c]);p&&(s&&(s+=","),s+=JSON.stringify(c)+":"+p)}return o.splice(a,1),"{"+s+"}"}}(e)},t.getTextPatch=function(e,t){if(!(e&&t&&e.trim().length&&t.trim().length))return t;if(e===t)return{from:0,to:0,text:"",md5:(0,i.md5)(t)};function n(n=1){let i=n<1?-1:0,r=!1;for(;!r&&Math.abs(i)<=t.length;){const o=n<1?[i]:[0,i];e.slice(...o)!==t.slice(...o)?r=!0:i+=1*Math.sign(n)}return i}let r=n()-1,o=e.length+n(-1)+1,s=t.length+n(-1)+1;return{from:r,to:o,text:t.slice(r,s),md5:(0,i.md5)(t)}},t.unpatchText=function(e,t){if(!t||"string"==typeof t)return t;const{from:n,to:r,text:o,md5:s}=t;if(null===o||null===e)return o;let a=e.slice(0,n)+o+e.slice(r);if(s&&(0,i.md5)(a)!==s)throw"Patch text error: Could not match md5 hash: (original/result) \n"+e+"\n"+a;return a},t.isEmpty=s,t.get=function(e,t){let n=t,i=e;return e?("string"==typeof n&&(n=n.split(".")),n.reduce((e,t)=>e&&e[t]?e[t]:void 0,i)):e},t.isObject=function(e){return Boolean(e&&"object"==typeof e&&!Array.isArray(e))},t.isDefined=function(e){return null!=e},t.getKeys=a;const i=n(666);function r(e,n){return(0,t.pickKeys)(e,a(e).filter(e=>!n.includes(e)))}function o(e,t){return e.filter(e=>Object.entries(t).every(([t,n])=>e[t]===n))}function s(e){for(var t in e)return!1;return!0}function a(e){return Object.keys(e)}t.pickKeys=(e,t=[],n=!0)=>{if(!t.length)return{};if(e&&t.length){let i={};return t.forEach(t=>{n&&void 0===e[t]||(i[t]=e[t])}),i}return e},t.isNotEmpty=e=>!s(e),t.getObjectEntries=e=>Object.entries(e),t.tryCatch=async e=>{const t=Date.now();try{return{...await e(),duration:Date.now()-t}}catch(e){return{error:e,hasError:!0,duration:Date.now()-t}}},t.reverseJoinOn=e=>e.map(e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e]))),t.reverseParsedPath=(e,n)=>(e??[]).map(({table:i,on:r,params:o,reversed:s},a)=>{const l=e[a-1]?.table??n;return"string"==typeof r?{table:l,on:r,...o&&{params:o},...i===l&&{reversed:!s}}:{table:l,on:(0,t.reverseJoinOn)(r)}}).reverse(),t.extractTypeUtil=(e,t)=>{if(Object.entries(t).every(([t,n])=>e[t]===n))return e},t.safeStringify=e=>{const t=new WeakSet;return JSON.stringify(e,(e,n)=>{if("object"==typeof n&&null!==n){if(t.has(n))return"[Circular]";t.add(n)}return n})},t.getSerialisableError=(e,n=!1)=>{if(null==e)return e;if("string"==typeof e||"boolean"==typeof e||"bigint"==typeof e||void 0===e||"number"==typeof e)return e?.toString();if(e instanceof DOMException)return{name:e.name,message:e.message,code:e.code,...n?{stack:e.stack}:{}};if(e instanceof Error){const i=Object.getOwnPropertyNames(e).reduce((t,n)=>({...t,[n]:e[n]}),{}),o=JSON.parse((0,t.safeStringify)(i));return n?o:r(o,["stack"])}return Array.isArray(e)?e.map(e=>(0,t.getSerialisableError)(e,n)):e},t.getProperty=(e,t)=>{if(Object.keys(e).includes(t))return e[t]},t.withTimeout=(e,t)=>{const n=new Promise((e,n)=>setTimeout(()=>n(new Error(`Timed out after ${t}ms`)),t));return Promise.race([e,n])},t.createPromiseWithTimeout=(e,t)=>{const n=new Promise((e,n)=>setTimeout(()=>n(new Error(`Timed out after ${t}ms`)),t)),i=new Promise(e);return Promise.race([i,n])},t.getEntries=e=>Object.entries(e),t.fromEntries=e=>Object.fromEntries(e)},441(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.includes=function(e,t){return e.some(e=>e===t)}},778(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),r(n(102),t),r(n(436),t),r(n(441),t)},102(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.isEqual=void 0,t.isEqual=(e,t,i="trace")=>n(e,t,void 0,i);const n=(e,t,i=new WeakMap,r)=>{if(e===t)return!0;if(typeof e!=typeof t)return!1;if(null===e||null===t)return!1;if("object"!=typeof e||"object"!=typeof t)return e!=e&&t!=t;let o=i.get(e);if(o?.has(t)){if("quiet"!==r&&console.trace("Circular reference detected in isEqual",e,t),"error"===r)throw new Error("Circular reference detected in isEqual");return"return-true"===r}if(o||(o=new WeakSet,i.set(e,o)),o.add(t),e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e instanceof RegExp&&t instanceof RegExp)return e.source===t.source&&e.flags===t.flags;const s=Array.isArray(e),a=Array.isArray(t);if(s&&a){if(e.length!==t.length)return!1;for(let o=0;o<e.length;o++)if(!n(e[o],t[o],i,r))return!1;return!0}if(s!==a)return!1;if(ArrayBuffer.isView(e)&&ArrayBuffer.isView(t)){if(e.byteLength!==t.byteLength)return!1;const n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),i=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);for(let e=0;e<n.length;e++)if(n[e]!==i[e])return!1;return!0}if(e instanceof ArrayBuffer&&t instanceof ArrayBuffer){if(e.byteLength!==t.byteLength)return!1;const n=new Uint8Array(e),i=new Uint8Array(t);for(let e=0;e<n.length;e++)if(n[e]!==i[e])return!1;return!0}const l=Object.keys(e);if(l.length!==Object.keys(t).length)return!1;for(const o of l){if(!(o in t))return!1;{const s=e[o],a=t[o];if(!n(s,a,i,r))return!1}}return!0}},436(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.tryCatchV2=void 0,t.tryCatchV2=e=>{const t=Date.now();try{const n=e();return n instanceof Promise?new Promise(async(e,i)=>{e({...await n.then(e=>({data:e})).catch(e=>({error:e,hasError:!0})),duration:Date.now()-t})}):{data:n,duration:Date.now()-t}}catch(e){return{error:e,hasError:!0,duration:Date.now()-t}}}}};const t={};return function n(i){const r=t[i];if(void 0!==r)return r.exports;const o=t[i]={exports:{}};return e[i].call(o.exports,o,o.exports,n),o.exports}(806)})());
@@ -1,4 +1,5 @@
1
- export type JobStatus = "pending" | "running" | "succeeded" | "failed" | "cancelled";
1
+ import type { JobRecord } from "./jobTable";
2
+ export type JobStatus = JobRecord["status"];
2
3
  /** Start new work or retry failed/cancelled work; rerun succeeded work; cancel pending/running work. */
3
4
  export type JobControlOperation = "startOrRetry" | "rerun" | "cancel";
4
5
  export type JobControlFunctionMetadata = {
@@ -1 +1 @@
1
- {"version":3,"file":"jobControl.d.ts","sourceRoot":"","sources":["../lib/jobControl.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,SAAS,GACnB,SAAS,GAAG,SAAS,GAAG,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;AAE/D,wGAAwG;AACxG,MAAM,MAAM,mBAAmB,GAAG,cAAc,GAAG,OAAO,GAAG,QAAQ,CAAC;AAEtE,MAAM,MAAM,0BAA0B,GAAG;IACvC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,KAAK,CAAC;IACd,SAAS,EAAE,mBAAmB,CAAC;CAChC,CAAC;AAEF,sFAAsF;AACtF,MAAM,MAAM,iBAAiB,GAAG,0BAA0B,GAAG;IAC3D,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,eAAe,EAAE,SAAS,SAAS,EAAE,CAAC;CACvC,CAAC"}
1
+ {"version":3,"file":"jobControl.d.ts","sourceRoot":"","sources":["../lib/jobControl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE5C,MAAM,MAAM,SAAS,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;AAE5C,wGAAwG;AACxG,MAAM,MAAM,mBAAmB,GAAG,cAAc,GAAG,OAAO,GAAG,QAAQ,CAAC;AAEtE,MAAM,MAAM,0BAA0B,GAAG;IACvC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,KAAK,CAAC;IACd,SAAS,EAAE,mBAAmB,CAAC;CAChC,CAAC;AAEF,sFAAsF;AACtF,MAAM,MAAM,iBAAiB,GAAG,0BAA0B,GAAG;IAC3D,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,eAAe,EAAE,SAAS,SAAS,EAAE,CAAC;CACvC,CAAC"}
@@ -0,0 +1,149 @@
1
+ import type { TableInsertRowFromTableConfig, TableRowFromTableConfig } from "./tableRowFromColumnDefinitions";
2
+ export declare const jobTableSchema: {
3
+ readonly columns: {
4
+ readonly id: "UUID PRIMARY KEY";
5
+ readonly job_name: "TEXT NOT NULL";
6
+ readonly target_table: "TEXT";
7
+ readonly target_row_pkey: "JSONB NOT NULL";
8
+ readonly params: "JSONB NOT NULL";
9
+ readonly user_id: "TEXT";
10
+ /**
11
+ * Scheduled cron time, rounded to a minute (five fields) or second (six fields).
12
+ * Together with job_name, prevents duplicate scheduling across workers and restarts.
13
+ * Null for row-triggered jobs and manual reruns.
14
+ */
15
+ readonly occurrence: "TIMESTAMPTZ";
16
+ readonly reason: "TEXT NOT NULL DEFAULT 'trigger'";
17
+ readonly status: "TEXT NOT NULL DEFAULT 'pending'";
18
+ readonly attempts: "INTEGER NOT NULL DEFAULT 0";
19
+ readonly max_attempts: "INTEGER NOT NULL";
20
+ readonly delay_ms: "DOUBLE PRECISION NOT NULL";
21
+ readonly backoff: "TEXT NOT NULL";
22
+ readonly cancel_requested: "BOOLEAN NOT NULL DEFAULT FALSE";
23
+ readonly checkpoint: "JSONB";
24
+ readonly has_checkpoint: "BOOLEAN NOT NULL DEFAULT FALSE";
25
+ readonly progress_message: "TEXT";
26
+ readonly progress_numeric: {
27
+ readonly nullable: true;
28
+ readonly jsonbSchema: {
29
+ readonly type: {
30
+ readonly done: "number";
31
+ readonly total: "number";
32
+ };
33
+ };
34
+ };
35
+ readonly error: "JSONB";
36
+ readonly run_at: "TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()";
37
+ readonly lease_token: "UUID";
38
+ readonly locked_until: "TIMESTAMPTZ";
39
+ readonly created_at: "TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()";
40
+ readonly finished_at: "TIMESTAMPTZ";
41
+ };
42
+ readonly check: {
43
+ readonly $or: readonly [{
44
+ readonly status: "pending";
45
+ readonly error: {};
46
+ readonly target_table: {};
47
+ readonly user_id: {};
48
+ readonly occurrence: {};
49
+ readonly checkpoint: {};
50
+ readonly progress_message: {};
51
+ readonly progress_numeric: {};
52
+ readonly backoff: {
53
+ readonly enum: readonly ["fixed", "exponential"];
54
+ };
55
+ readonly reason: {
56
+ readonly enum: readonly ["trigger", "rerun"];
57
+ };
58
+ }, {
59
+ readonly status: "running";
60
+ readonly error: {};
61
+ readonly lease_token: {
62
+ readonly $ne: null;
63
+ };
64
+ readonly locked_until: {
65
+ readonly $ne: null;
66
+ };
67
+ readonly target_table: {};
68
+ readonly user_id: {};
69
+ readonly occurrence: {};
70
+ readonly checkpoint: {};
71
+ readonly progress_message: {};
72
+ readonly progress_numeric: {};
73
+ readonly backoff: {
74
+ readonly enum: readonly ["fixed", "exponential"];
75
+ };
76
+ readonly reason: {
77
+ readonly enum: readonly ["trigger", "rerun"];
78
+ };
79
+ }, {
80
+ readonly status: "succeeded";
81
+ readonly finished_at: {
82
+ readonly $ne: null;
83
+ };
84
+ readonly target_table: {};
85
+ readonly user_id: {};
86
+ readonly occurrence: {};
87
+ readonly checkpoint: {};
88
+ readonly progress_message: {};
89
+ readonly progress_numeric: {};
90
+ readonly backoff: {
91
+ readonly enum: readonly ["fixed", "exponential"];
92
+ };
93
+ readonly reason: {
94
+ readonly enum: readonly ["trigger", "rerun"];
95
+ };
96
+ }, {
97
+ readonly status: "failed";
98
+ readonly error: {
99
+ readonly $ne: null;
100
+ };
101
+ readonly finished_at: {
102
+ readonly $ne: null;
103
+ };
104
+ readonly target_table: {};
105
+ readonly user_id: {};
106
+ readonly occurrence: {};
107
+ readonly checkpoint: {};
108
+ readonly progress_message: {};
109
+ readonly progress_numeric: {};
110
+ readonly backoff: {
111
+ readonly enum: readonly ["fixed", "exponential"];
112
+ };
113
+ readonly reason: {
114
+ readonly enum: readonly ["trigger", "rerun"];
115
+ };
116
+ }, {
117
+ readonly status: "cancelled";
118
+ readonly error: {};
119
+ readonly finished_at: {
120
+ readonly $ne: null;
121
+ };
122
+ readonly target_table: {};
123
+ readonly user_id: {};
124
+ readonly occurrence: {};
125
+ readonly checkpoint: {};
126
+ readonly progress_message: {};
127
+ readonly progress_numeric: {};
128
+ readonly backoff: {
129
+ readonly enum: readonly ["fixed", "exponential"];
130
+ };
131
+ readonly reason: {
132
+ readonly enum: readonly ["trigger", "rerun"];
133
+ };
134
+ }];
135
+ };
136
+ };
137
+ export type JobValue = null | string | number | boolean | readonly JobValue[] | {
138
+ readonly [key: string]: JobValue;
139
+ };
140
+ type JobValues = {
141
+ target_row_pkey: Record<string, JobValue>;
142
+ params: Record<string, JobValue>;
143
+ checkpoint: JobValue | null;
144
+ error: JobValue;
145
+ };
146
+ export type JobRecord = TableRowFromTableConfig<typeof jobTableSchema, JobValues>;
147
+ export type JobInsertRecord = TableInsertRowFromTableConfig<typeof jobTableSchema, JobValues>;
148
+ export {};
149
+ //# sourceMappingURL=jobTable.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jobTable.d.ts","sourceRoot":"","sources":["../lib/jobTable.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,6BAA6B,EAC7B,uBAAuB,EACxB,MAAM,iCAAiC,CAAC;AAazC,eAAO,MAAM,cAAc;;;;;;;;QAQvB;;;;WAIG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CgC,CAAC;AAExC,MAAM,MAAM,QAAQ,GAChB,IAAI,GACJ,MAAM,GACN,MAAM,GACN,OAAO,GACP,SAAS,QAAQ,EAAE,GACnB;IAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,GAAG,QAAQ,CAAA;CAAE,CAAC;AACzC,KAAK,SAAS,GAAG;IACf,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAC1C,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACjC,UAAU,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC5B,KAAK,EAAE,QAAQ,CAAC;CACjB,CAAC;AACF,MAAM,MAAM,SAAS,GAAG,uBAAuB,CAC7C,OAAO,cAAc,EACrB,SAAS,CACV,CAAC;AACF,MAAM,MAAM,eAAe,GAAG,6BAA6B,CACzD,OAAO,cAAc,EACrB,SAAS,CACV,CAAC"}
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.jobTableSchema = void 0;
4
+ const shared = {
5
+ target_table: {},
6
+ user_id: {},
7
+ occurrence: {},
8
+ checkpoint: {},
9
+ progress_message: {},
10
+ progress_numeric: {},
11
+ backoff: { enum: ["fixed", "exponential"] },
12
+ reason: { enum: ["trigger", "rerun"] },
13
+ };
14
+ exports.jobTableSchema = {
15
+ columns: {
16
+ id: "UUID PRIMARY KEY",
17
+ job_name: "TEXT NOT NULL",
18
+ target_table: "TEXT",
19
+ target_row_pkey: "JSONB NOT NULL",
20
+ params: "JSONB NOT NULL",
21
+ user_id: "TEXT",
22
+ /**
23
+ * Scheduled cron time, rounded to a minute (five fields) or second (six fields).
24
+ * Together with job_name, prevents duplicate scheduling across workers and restarts.
25
+ * Null for row-triggered jobs and manual reruns.
26
+ */
27
+ occurrence: "TIMESTAMPTZ",
28
+ reason: "TEXT NOT NULL DEFAULT 'trigger'",
29
+ status: "TEXT NOT NULL DEFAULT 'pending'",
30
+ attempts: "INTEGER NOT NULL DEFAULT 0",
31
+ max_attempts: "INTEGER NOT NULL",
32
+ delay_ms: "DOUBLE PRECISION NOT NULL",
33
+ backoff: "TEXT NOT NULL",
34
+ cancel_requested: "BOOLEAN NOT NULL DEFAULT FALSE",
35
+ checkpoint: "JSONB",
36
+ has_checkpoint: "BOOLEAN NOT NULL DEFAULT FALSE",
37
+ progress_message: "TEXT",
38
+ progress_numeric: {
39
+ nullable: true,
40
+ jsonbSchema: { type: { done: "number", total: "number" } },
41
+ },
42
+ error: "JSONB",
43
+ run_at: "TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()",
44
+ lease_token: "UUID",
45
+ locked_until: "TIMESTAMPTZ",
46
+ created_at: "TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()",
47
+ finished_at: "TIMESTAMPTZ",
48
+ },
49
+ check: {
50
+ $or: [
51
+ { ...shared, status: "pending", error: {} },
52
+ {
53
+ ...shared,
54
+ status: "running",
55
+ error: {},
56
+ lease_token: { $ne: null },
57
+ locked_until: { $ne: null },
58
+ },
59
+ { ...shared, status: "succeeded", finished_at: { $ne: null } },
60
+ {
61
+ ...shared,
62
+ status: "failed",
63
+ error: { $ne: null },
64
+ finished_at: { $ne: null },
65
+ },
66
+ { ...shared, status: "cancelled", error: {}, finished_at: { $ne: null } },
67
+ ],
68
+ },
69
+ };
70
+ //# sourceMappingURL=jobTable.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jobTable.js","sourceRoot":"","sources":["../lib/jobTable.ts"],"names":[],"mappings":";;;AAMA,MAAM,MAAM,GAAG;IACb,YAAY,EAAE,EAAE;IAChB,OAAO,EAAE,EAAE;IACX,UAAU,EAAE,EAAE;IACd,UAAU,EAAE,EAAE;IACd,gBAAgB,EAAE,EAAE;IACpB,gBAAgB,EAAE,EAAE;IACpB,OAAO,EAAE,EAAE,IAAI,EAAE,CAAC,OAAO,EAAE,aAAa,CAAC,EAAE;IAC3C,MAAM,EAAE,EAAE,IAAI,EAAE,CAAC,SAAS,EAAE,OAAO,CAAC,EAAE;CAC9B,CAAC;AAEE,QAAA,cAAc,GAAG;IAC5B,OAAO,EAAE;QACP,EAAE,EAAE,kBAAkB;QACtB,QAAQ,EAAE,eAAe;QACzB,YAAY,EAAE,MAAM;QACpB,eAAe,EAAE,gBAAgB;QACjC,MAAM,EAAE,gBAAgB;QACxB,OAAO,EAAE,MAAM;QACf;;;;WAIG;QACH,UAAU,EAAE,aAAa;QACzB,MAAM,EAAE,iCAAiC;QACzC,MAAM,EAAE,iCAAiC;QACzC,QAAQ,EAAE,4BAA4B;QACtC,YAAY,EAAE,kBAAkB;QAChC,QAAQ,EAAE,2BAA2B;QACrC,OAAO,EAAE,eAAe;QACxB,gBAAgB,EAAE,gCAAgC;QAClD,UAAU,EAAE,OAAO;QACnB,cAAc,EAAE,gCAAgC;QAChD,gBAAgB,EAAE,MAAM;QACxB,gBAAgB,EAAE;YAChB,QAAQ,EAAE,IAAI;YACd,WAAW,EAAE,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE;SAC3D;QACD,KAAK,EAAE,OAAO;QACd,MAAM,EAAE,gDAAgD;QACxD,WAAW,EAAE,MAAM;QACnB,YAAY,EAAE,aAAa;QAC3B,UAAU,EAAE,gDAAgD;QAC5D,WAAW,EAAE,aAAa;KAC3B;IACD,KAAK,EAAE;QACL,GAAG,EAAE;YACH,EAAE,GAAG,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,EAAE;YAC3C;gBACE,GAAG,MAAM;gBACT,MAAM,EAAE,SAAS;gBACjB,KAAK,EAAE,EAAE;gBACT,WAAW,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE;gBAC1B,YAAY,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE;aAC5B;YACD,EAAE,GAAG,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,WAAW,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;YAC9D;gBACE,GAAG,MAAM;gBACT,MAAM,EAAE,QAAQ;gBAChB,KAAK,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE;gBACpB,WAAW,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE;aAC3B;YACD,EAAE,GAAG,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,KAAK,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;SAC1E;KACF;CACoC,CAAC"}
@@ -0,0 +1,79 @@
1
+ import type { JSONB } from "./JSONBSchemaValidation/JSONBSchema";
2
+ export type TableCheckValue = string | number | boolean | null;
3
+ export type TableCheckBranch = Record<string, TableCheckValue | {
4
+ enum: readonly TableCheckValue[];
5
+ } | {
6
+ $ne: null;
7
+ } | Record<string, never>>;
8
+ export type TableCheck = {
9
+ $or: readonly TableCheckBranch[];
10
+ };
11
+ export type ManagedTableColumnDefinition = string | {
12
+ enum: readonly (string | number)[];
13
+ nullable?: boolean;
14
+ } | {
15
+ jsonbSchema: JSONB.JSONBSchema;
16
+ nullable?: boolean;
17
+ };
18
+ export type ManagedTableSchema = {
19
+ columns: Record<string, ManagedTableColumnDefinition>;
20
+ check?: TableCheck;
21
+ };
22
+ /** Row types for the column definitions used by managed tables. */
23
+ export type TableRowFromColumnDefinitions<T extends Record<string, ManagedTableColumnDefinition>, Binary = ArrayBuffer | Uint8Array> = InsertRow<{
24
+ [K in keyof T]: T[K] extends string ? NormalizeSQL<Uppercase<T[K]>> : T[K];
25
+ }, Binary>;
26
+ /** Selected managed rows, narrowed by the same CHECK branches as the generated schema. */
27
+ export type TableRowFromTableConfig<T extends ManagedTableSchema, ValueTypes extends Partial<Record<keyof T["columns"], unknown>> = {}, Binary = ArrayBuffer | Uint8Array> = CheckedRow<{
28
+ [K in keyof T["columns"]]: K extends keyof ValueTypes ? ValueTypes[K] : TableRowFromColumnDefinitions<T["columns"], Binary> extends infer Row ? K extends keyof Row ? Required<Row>[K] : never : never;
29
+ }, T extends ({
30
+ check: {
31
+ $or: readonly (infer Branch extends TableCheckBranch)[];
32
+ };
33
+ }) ? Branch : undefined>;
34
+ /** Insert rows may omit nullable columns and columns supplied by database defaults. */
35
+ export type TableInsertRowFromTableConfig<T extends ManagedTableSchema, ValueTypes extends Partial<Record<keyof T["columns"], unknown>> = {}, Binary = ArrayBuffer | Uint8Array> = CheckedInsertRow<TableRowFromTableConfig<T, ValueTypes, Binary>, GeneratedColumnNames<{
36
+ [K in keyof T["columns"]]: T["columns"][K] extends string ? NormalizeSQL<Uppercase<T["columns"][K]>> : T["columns"][K];
37
+ }>>;
38
+ type CheckedInsertRow<Row, Defaults> = Row extends unknown ? Omit<Row, OptionalInsertKeys<Row, Defaults>> & Partial<Pick<Row, OptionalInsertKeys<Row, Defaults>>> : never;
39
+ type OptionalInsertKeys<Row, Defaults> = {
40
+ [K in keyof Row]: K extends Defaults ? K : null extends Row[K] ? K : never;
41
+ }[keyof Row];
42
+ type CheckedRow<Row, Branch> = Branch extends TableCheckBranch ? {
43
+ [K in keyof Row]: K extends keyof Branch ? Branch[K] extends {
44
+ $ne: null;
45
+ } ? NonNullable<Row[K]> : Branch[K] extends {
46
+ enum: readonly (infer V)[];
47
+ } ? V : Branch[K] extends Record<string, never> ? Row[K] : Branch[K] : null extends Row[K] ? null : Row[K];
48
+ } : Row;
49
+ type InsertRow<T extends Record<string, ManagedTableColumnDefinition>, Binary> = Omit<TableRow<T, Binary>, GeneratedColumnNames<T>> & Partial<Pick<TableRow<T, Binary>, GeneratedColumnNames<T>>>;
50
+ type TableRow<T extends Record<string, ManagedTableColumnDefinition>, Binary> = {
51
+ [K in keyof T]: T[K] extends ({
52
+ jsonbSchema: infer S extends JSONB.JSONBSchema;
53
+ }) ? JSONB.GetType<S> | (T[K] extends {
54
+ nullable: true;
55
+ } ? null : never) : T[K] extends {
56
+ enum: readonly (infer V)[];
57
+ } ? V | (T[K] extends {
58
+ nullable: true;
59
+ } ? null : never) : ColumnValue<T[K], Binary> | (T[K] extends string ? ColumnIsRequired<T[K]> extends true ? never : null : never);
60
+ };
61
+ type ColumnIsRequired<T extends string> = ReadType<T>[0] extends SerialType ? true : ` ${Unquoted<T>} ` extends (`${string} NOT NULL ${string}` | `${string} PRIMARY KEY ${string}` | `${string} GENERATED ${string} AS IDENTITY ${string}`) ? true : false;
62
+ type GeneratedColumnNames<T extends Record<string, ManagedTableColumnDefinition>> = {
63
+ [K in keyof T]: T[K] extends string ? ReadType<T[K]>[0] extends SerialType ? K : ` ${Unquoted<T[K]>} ` extends (`${string} DEFAULT ${string}` | `${string} GENERATED ${string}`) ? K : never : never;
64
+ }[keyof T];
65
+ type SerialType = "SMALLSERIAL" | "SERIAL2" | "SERIAL" | "SERIAL4" | "BIGSERIAL" | "SERIAL8";
66
+ type ColumnValue<T, Binary> = T extends string ? T extends `DOUBLE PRECISION${infer Rest}` ? ColumnValue<`FLOAT8${Rest}`, Binary> : ReadType<T> extends ([
67
+ infer Name extends string,
68
+ infer Rest extends string
69
+ ]) ? ArrayValue<ScalarValue<Name, Binary>, Trim<Rest>> : never : never;
70
+ type ScalarValue<T, Binary> = T extends "BYTEA" ? Binary : T extends "JSON" | "JSONB" ? Record<string, unknown> : T extends "BOOL" | "BOOLEAN" ? boolean : T extends ("SMALLINT" | "INT2" | "INT" | "INTEGER" | "INT4" | "SMALLSERIAL" | "SERIAL2" | "SERIAL" | "SERIAL4" | "REAL" | "FLOAT" | "FLOAT4" | "FLOAT8") ? number : T extends ("BIGINT" | "INT8" | "BIGSERIAL" | "SERIAL8" | "NUMERIC" | "DECIMAL" | "DEC") ? string | number : string;
71
+ /** Only consume modifiers/array dimensions immediately following the type. */
72
+ type ArrayValue<Value, Rest extends string> = Rest extends `(${string})${infer Tail}` ? ArrayValue<Value, Trim<Tail>> : Rest extends `[${string}]${infer Tail}` ? ArrayValue<(Value | null)[], Trim<Tail>> : Rest extends "ARRAY" | `ARRAY ${string}` | `ARRAY[${string}` ? Rest extends `ARRAY${infer Tail}` ? Trim<Tail> extends `[${string}` ? ArrayValue<Value, Trim<Tail>> : (Value | null)[] : never : Value;
73
+ type ReadType<T extends string, Name extends string = ""> = T extends `${" " | "(" | "["}${string}` ? [Name, T] : T extends `${infer Char}${infer Rest}` ? ReadType<Rest, `${Name}${Char}`> : [Name, ""];
74
+ type Trim<T extends string> = T extends ` ${infer Rest}` ? Trim<Rest> : T extends `${infer Rest} ` ? Trim<Rest> : T;
75
+ type NormalizeSQL<T extends string> = T extends `${infer Start}\n${infer End}` ? NormalizeSQL<`${Start} ${End}`> : T extends `${infer Start}\r${infer End}` ? NormalizeSQL<`${Start} ${End}`> : T extends `${infer Start}\t${infer End}` ? NormalizeSQL<`${Start} ${End}`> : T extends `${infer Start} ${infer End}` ? NormalizeSQL<`${Start} ${End}`> : Trim<T>;
76
+ /** Quoted values and identifiers do not declare defaults or constraints. */
77
+ type Unquoted<T extends string> = T extends `${infer Start}'${string}'${infer End}` ? Unquoted<`${Start}${End}`> : T extends `${infer Start}"${string}"${infer End}` ? Unquoted<`${Start}${End}`> : T;
78
+ export {};
79
+ //# sourceMappingURL=tableRowFromColumnDefinitions.d.ts.map