@svgrid/enterprise 3.1.61 → 3.1.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  <script lang="ts">
2
- import{untrack}from"svelte";import{SvSwitchButton,announce}from"@svgrid/grid";import FilterPanel from"./viewbar/FilterPanel.svelte";import AutomationTrigger from"./AutomationTrigger.svelte";import AutomationActionEditor from"./AutomationAction.svelte";import{primaryOf,rowIdOf}from"./base-tables";import{actionLabel,tableFields,triggerText}from"./automations.svelte";import{actionChoices,actionKey,newAction,newAutomation,newTrigger}from"./automation-edit";import{automationDrafter}from"./automation-drafter";import{bm,bmCount}from"./messages.svelte";let{tables,onChange,runner,serverRuns,onServer=false,runOnServer,records,webhookUrl,scriptsInPage=false,height="100%"}=$props();const snapshot=list=>JSON.parse(JSON.stringify(list));let lists=$state(Object.fromEntries(tables.map(t=>[t.id,snapshot(t.automations??[])])));const tableOf=id=>tables.find(t=>t.id===id);const entries=$derived(tables.flatMap(t=>(lists[t.id]??[]).map(a=>({table:t,a}))));let picked=$state(entries[0]?{table:entries[0].table.id,id:entries[0].a.id}:null);const current=$derived(entries.find(e=>e.table.id===picked?.table&&e.a.id===picked?.id)??null);let part=$state("trigger");let tab=$state("edit");let inserting=$state(null);const side=a=>onServer?"server":a.runOn??"browser";const ACTIONS=$derived(actionChoices());function save(tableId,next){lists={...lists,[tableId]:next};onChange(tableId,snapshot(next))}function patch(change){const c=current;if(!c)return;save(c.table.id,(lists[c.table.id]??[]).map(a=>a.id===c.a.id?{...a,...change}:a))}function pick(tableId,id){picked={table:tableId,id};part="trigger";tab="edit";inserting=null;tryError=""}function create(){const t=current?.table??tables[0];if(!t)return;const a=newAutomation(t);save(t.id,[...lists[t.id]??[],a]);pick(t.id,a.id)}const drafter=automationDrafter();let offer=$state(false);$effect(()=>{if(!drafter)return;if(!drafter.available){offer=true;return}Promise.resolve().then(()=>drafter.available()).then(yes=>offer=!!yes,()=>offer=false)});let describeText=$state("");let describing=$state(false);let describeError=$state("");let describeQuestion=$state("");let drafted=$state(null);async function draftIt(){const text=describeText.trim();if(!drafter||!text||describing)return;describing=true;describeError="";describeQuestion="";try{const answer=await drafter.draft(text,"");const t=(answer.tableId?tableOf(answer.tableId):null)??current?.table??tables[0];if(answer.automation&&t){const a={...answer.automation,id:newAutomation(t).id,enabled:false};if(onServer)a.runOn="server";save(t.id,[...lists[t.id]??[],a]);pick(t.id,a.id);drafted={key:t.id+"/"+a.id,words:answer.words??""};announce(bm("extras.drafted"))}else{describeQuestion=answer.question||bm("extras.describeAgain")}}catch(e){describeError=e instanceof Error?e.message:String(e)}finally{describing=false}}let deleting=$state(false);function remove(){const c=current;if(!c)return;save(c.table.id,(lists[c.table.id]??[]).filter(a=>a.id!==c.a.id));deleting=false;const next=entries.find(e=>!(e.table.id===c.table.id&&e.a.id===c.a.id));picked=next?{table:next.table.id,id:next.a.id}:null;part="trigger"}function moveTo(tableId){const c=current;const to=tableOf(tableId);if(!c||!to||to.id===c.table.id)return;const actions=c.a.actions.map(x=>{if(x.type==="updateRecord")return{...x,values:{}};if(x.type==="createRecord")return{type:"createRecord",table:x.table,values:x.table===c.table.id?{}:x.values};if(x.type==="highlight")return{...x,fields:[]};if(x.type==="if")return{...x,condition:void 0,then:[],else:[]};if(x.type==="ai")return{...x,field:void 0};return x});const type=c.a.trigger.type;const moved={...c.a,trigger:newTrigger(type,to),condition:void 0,actions};save(c.table.id,(lists[c.table.id]??[]).filter(a=>a.id!==c.a.id));save(to.id,[...lists[to.id]??[],moved]);picked={table:to.id,id:moved.id}}const EMPTY={kind:"fieldFilter",conjunction:"and",conditions:[]};function standIn(t){const cols=[...tableFields(t).values()];return{internalColumns:cols.map(c=>({...c.def,id:c.id})),allColumns:cols.map(c=>({id:c.id})),hiddenColumns:{}}}const ctrl=$derived(current?standIn(current.table):null);function setCondition(f){patch({condition:f.conditions.length?f:void 0})}function setAction(i,next){const c=current;if(!c)return;const actions=[...c.a.actions];if(next)actions[i]=next;else actions.splice(i,1);patch({actions});if(!next)part=actions.length?Math.min(i,actions.length-1):"trigger"}function insert(at,value){const c=current;if(!c||!value)return;const actions=[...c.a.actions];actions.splice(at,0,newAction(value,c.table));patch({actions});inserting=null;part=at}function moveAction(i,dir){const c=current;if(!c)return;const actions=[...c.a.actions];const j=i+dir;if(j<0||j>=actions.length)return;[actions[i],actions[j]]=[actions[j],actions[i]];patch({actions});part=j;announce(bm("extras.stepMoved",{from:i+1,to:j+1}))}function summary(t,x){switch(x.type){case"updateRecord":{const names=Object.keys(x.values).map(id=>tableFields(t).get(id)?.header??id);return names.length?bm("extras.summarySet",{fields:names.join(", ")}):bm("extras.summaryNothing")}case"createRecord":return bm("extras.summaryCreate",{table:tableOf(x.table)?.name??x.table});case"notify":return x.message;case"highlight":return bm("extras.summaryColor");case"webhook":return`${x.method??"POST"} ${x.url}`;case"email":return x.to?bm("extras.summaryEmail",{to:x.to}):bm("extras.summaryNoTo");case"chat":return x.text||bm("extras.summaryNoText");case"textMessage":return x.to?bm(x.channel==="viber"?"extras.summaryViber":"extras.summarySms",{to:x.to}):bm("extras.summaryNoPhone");case"repeat":return bm("extras.summaryRepeat",{table:tableOf(x.table)?.name??x.table,steps:bmCount("extras.stepCount",(x.actions??[]).length)});case"if":return bm("extras.summaryIf",{then:bmCount("extras.stepCount",(x.then??[]).length),otherwise:bmCount("extras.stepCount",(x.else??[]).length)});case"ai":return x.prompt||bm("extras.summaryNoText");case"script":return bm("extras.summaryScript",{lines:x.code.split("\n").filter(l=>l.trim()&&!l.trim().startsWith("//")).length});default:return""}}const whenText=(t,a)=>triggerText(t,a.trigger.type==="recordMatches"?a:{...a,condition:void 0});const ICONS={trigger:"M13 2 4 14h7l-1 8 9-12h-7l1-8z",condition:"M3 5h18l-7 8v6l-4 2v-8L3 5z",updateRecord:"M4 20h4L19 9l-4-4L4 16v4zM14 6l4 4",createRecord:"M4 4h16v16H4zM12 8v8M8 12h8",notify:"M6 16V11a6 6 0 0 1 12 0v5l2 2H4l2-2zM10 21h4",highlight:"M12 3s6 7 6 11a6 6 0 0 1-12 0c0-4 6-11 6-11z",webhook:"M10 14a4 4 0 0 0 5.66 0l3-3a4 4 0 0 0-5.66-5.66l-1 1M14 10a4 4 0 0 0-5.66 0l-3 3a4 4 0 0 0 5.66 5.66l1-1",email:"M3 6h18v12H3zM3 7l9 6 9-6",run:"M7 4v16l13-8z",chat:"M4 5h16v11H9l-5 4V5z",textMessage:"M7 2h10a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1zM11 18h2",repeat:"M17 2l3 3-3 3M4 11V9a4 4 0 0 1 4-4h12M7 22l-3-3 3-3M20 13v2a4 4 0 0 1-4 4H4",if:"M6 3v6a4 4 0 0 0 4 4h8M15 10l3 3-3 3M6 13v8",ai:"M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z",script:"M8 7l-5 5 5 5M16 7l5 5-5 5"};let tryRecord=$state("");let tryError=$state("");let testRows=$state.raw([]);const testTable=$derived(current?.table.id??"");$effect(()=>{const id=testTable;untrack(()=>{const t=tableOf(id);tryRecord="";testRows=[];if(!t)return;const take=rows=>{if(testTable!==id)return;testRows=rows;if(!tryRecord&&rows[0])tryRecord=rowIdOf(t,rows[0])};if(records)void records(t.id).then(take,()=>take([]));else if(t.source?.server&&runner)void runner.firstRecords(t.id,200).then(take);else take((t.data??[]).filter(Boolean).slice(0,200))})});const testChoices=$derived(current?testRows.map(r=>({id:rowIdOf(current.table,r),name:String(r[primaryOf(current.table)]??"")||bm("extras.noName")})):[]);const canTest=$derived(!!current&&(side(current.a)==="server"&&!!runOnServer||side(current.a)!=="server"&&!!runner));function test(){const c=current;if(!c)return;const a=JSON.parse(JSON.stringify(c.a));tryError="";if(side(a)==="server"&&runOnServer){runOnServer(a,c.table.id,tryRecord||null).then(()=>showRuns(),e=>{tryError=e instanceof Error?e.message:String(e);showRuns()});return}if(runner){void runner.runNow(a,c.table.id,tryRecord||null);showRuns()}}let fromServer=$state.raw([]);let serverError=$state("");let onlyThis=$state(true);function showRuns(){tab="runs";if(!serverRuns)return;serverRuns().then(r=>{fromServer=r;serverError=""},e=>serverError=e instanceof Error?e.message:String(e))}const allRuns=$derived([...(runner?.runs??[]).map(r=>({...r,side:"browser"})),...fromServer.map(r=>({...r,side:"server"}))].sort((x,y)=>y.at-x.at));const shownRuns=$derived(onlyThis&&current?allRuns.filter(r=>r.automationId===current.a.id):allRuns);const time=at=>new Date(at).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"});
2
+ import{untrack}from"svelte";import{SvSwitchButton,announce}from"@svgrid/grid";import FilterPanel from"./viewbar/FilterPanel.svelte";import AutomationTrigger from"./AutomationTrigger.svelte";import AutomationActionEditor from"./AutomationAction.svelte";import{primaryOf,rowIdOf}from"./base-tables";import{actionLabel,tableFields,triggerText}from"./automations.svelte";import{actionChoices,actionKey,newAction,newAutomation,newTrigger}from"./automation-edit";import{automationDrafter}from"./automation-drafter";import{bm,bmCount}from"./messages.svelte";let{tables,onChange,runner,serverRuns,onServer=false,runOnServer,records,webhookUrl,scriptsInPage=false,height="100%"}=$props();const snapshot=list=>JSON.parse(JSON.stringify(list));let lists=$state(Object.fromEntries(tables.map(t=>[t.id,snapshot(t.automations??[])])));const tableOf=id=>tables.find(t=>t.id===id);const entries=$derived(tables.flatMap(t=>(lists[t.id]??[]).map(a=>({table:t,a}))));let picked=$state(entries[0]?{table:entries[0].table.id,id:entries[0].a.id}:null);const current=$derived(entries.find(e=>e.table.id===picked?.table&&e.a.id===picked?.id)??null);let part=$state("trigger");let tab=$state("edit");let inserting=$state(null);const side=a=>onServer?"server":a.runOn??"browser";const ACTIONS=$derived(actionChoices());function save(tableId,next){lists={...lists,[tableId]:next};onChange(tableId,snapshot(next))}function patch(change){const c=current;if(!c)return;save(c.table.id,(lists[c.table.id]??[]).map(a=>a.id===c.a.id?{...a,...change}:a))}function pick(tableId,id){picked={table:tableId,id};part="trigger";tab="edit";inserting=null;tryError=""}function create(){const t=current?.table??tables[0];if(!t)return;const a=newAutomation(t);save(t.id,[...lists[t.id]??[],a]);pick(t.id,a.id)}const drafter=automationDrafter();let offer=$state(false);$effect(()=>{if(!drafter)return;if(!drafter.available){offer=true;return}Promise.resolve().then(()=>drafter.available()).then(yes=>offer=!!yes,()=>offer=false)});let describeText=$state("");let describing=$state(false);let describeError=$state("");let describeQuestion=$state("");let drafted=$state(null);async function draftIt(){const text=describeText.trim();if(!drafter||!text||describing)return;describing=true;describeError="";describeQuestion="";try{const answer=await drafter.draft(text,"");const t=(answer.tableId?tableOf(answer.tableId):null)??current?.table??tables[0];if(answer.automation&&t){const a={...answer.automation,id:newAutomation(t).id,enabled:false};if(onServer)a.runOn="server";save(t.id,[...lists[t.id]??[],a]);pick(t.id,a.id);drafted={key:t.id+"/"+a.id,words:answer.words??""};announce(bm("extras.drafted"))}else{describeQuestion=answer.question||bm("extras.describeAgain")}}catch(e){describeError=e instanceof Error?e.message:String(e)}finally{describing=false}}function duplicate(){const c=current;if(!c)return;const copy={...structuredClone($state.snapshot(c.a)),id:newAutomation(c.table).id,name:bm("extras.copyOf",{name:c.a.name||bm("extras.untitled")}),enabled:false};if(copy.trigger.type==="webhookReceived")copy.trigger=newTrigger("webhookReceived",c.table);const list=lists[c.table.id]??[];const at=list.findIndex(a=>a.id===c.a.id);save(c.table.id,[...list.slice(0,at+1),copy,...list.slice(at+1)]);pick(c.table.id,copy.id);announce(bm("extras.duplicated"))}let deleting=$state(false);function remove(){const c=current;if(!c)return;save(c.table.id,(lists[c.table.id]??[]).filter(a=>a.id!==c.a.id));deleting=false;const next=entries.find(e=>!(e.table.id===c.table.id&&e.a.id===c.a.id));picked=next?{table:next.table.id,id:next.a.id}:null;part="trigger"}function moveTo(tableId){const c=current;const to=tableOf(tableId);if(!c||!to||to.id===c.table.id)return;const actions=c.a.actions.map(x=>{if(x.type==="updateRecord")return{...x,values:{}};if(x.type==="createRecord")return{type:"createRecord",table:x.table,values:x.table===c.table.id?{}:x.values};if(x.type==="highlight")return{...x,fields:[]};if(x.type==="if")return{...x,condition:void 0,then:[],else:[]};if(x.type==="ai")return{...x,field:void 0};return x});const type=c.a.trigger.type;const moved={...c.a,trigger:newTrigger(type,to),condition:void 0,actions};save(c.table.id,(lists[c.table.id]??[]).filter(a=>a.id!==c.a.id));save(to.id,[...lists[to.id]??[],moved]);picked={table:to.id,id:moved.id}}const EMPTY={kind:"fieldFilter",conjunction:"and",conditions:[]};function standIn(t){const cols=[...tableFields(t).values()];return{internalColumns:cols.map(c=>({...c.def,id:c.id})),allColumns:cols.map(c=>({id:c.id})),hiddenColumns:{}}}const ctrl=$derived(current?standIn(current.table):null);function setCondition(f){patch({condition:f.conditions.length?f:void 0})}function setAction(i,next){const c=current;if(!c)return;const actions=[...c.a.actions];if(next)actions[i]=next;else actions.splice(i,1);patch({actions});if(!next)part=actions.length?Math.min(i,actions.length-1):"trigger"}function insert(at,value){const c=current;if(!c||!value)return;const actions=[...c.a.actions];actions.splice(at,0,newAction(value,c.table));patch({actions});inserting=null;part=at}function moveAction(i,dir){const c=current;if(!c)return;const actions=[...c.a.actions];const j=i+dir;if(j<0||j>=actions.length)return;[actions[i],actions[j]]=[actions[j],actions[i]];patch({actions});part=j;announce(bm("extras.stepMoved",{from:i+1,to:j+1}))}function summary(t,x){switch(x.type){case"updateRecord":{const names=Object.keys(x.values).map(id=>tableFields(t).get(id)?.header??id);return names.length?bm("extras.summarySet",{fields:names.join(", ")}):bm("extras.summaryNothing")}case"createRecord":return bm("extras.summaryCreate",{table:tableOf(x.table)?.name??x.table});case"deleteRecord":return bm("extras.summaryDelete");case"notify":return x.message;case"highlight":return bm("extras.summaryColor");case"webhook":return`${x.method??"POST"} ${x.url}`;case"email":return x.to?bm("extras.summaryEmail",{to:x.to}):bm("extras.summaryNoTo");case"chat":return x.text||bm("extras.summaryNoText");case"textMessage":return x.to?bm(x.channel==="viber"?"extras.summaryViber":"extras.summarySms",{to:x.to}):bm("extras.summaryNoPhone");case"repeat":return bm("extras.summaryRepeat",{table:tableOf(x.table)?.name??x.table,steps:bmCount("extras.stepCount",(x.actions??[]).length)});case"if":return bm("extras.summaryIf",{then:bmCount("extras.stepCount",(x.then??[]).length),otherwise:bmCount("extras.stepCount",(x.else??[]).length)});case"ai":return x.prompt||bm("extras.summaryNoText");case"script":return bm("extras.summaryScript",{lines:x.code.split("\n").filter(l=>l.trim()&&!l.trim().startsWith("//")).length});default:return""}}const whenText=(t,a)=>triggerText(t,a.trigger.type==="recordMatches"?a:{...a,condition:void 0});const ICONS={trigger:"M13 2 4 14h7l-1 8 9-12h-7l1-8z",condition:"M3 5h18l-7 8v6l-4 2v-8L3 5z",updateRecord:"M4 20h4L19 9l-4-4L4 16v4zM14 6l4 4",createRecord:"M4 4h16v16H4zM12 8v8M8 12h8",notify:"M6 16V11a6 6 0 0 1 12 0v5l2 2H4l2-2zM10 21h4",highlight:"M12 3s6 7 6 11a6 6 0 0 1-12 0c0-4 6-11 6-11z",webhook:"M10 14a4 4 0 0 0 5.66 0l3-3a4 4 0 0 0-5.66-5.66l-1 1M14 10a4 4 0 0 0-5.66 0l-3 3a4 4 0 0 0 5.66 5.66l1-1",email:"M3 6h18v12H3zM3 7l9 6 9-6",run:"M7 4v16l13-8z",chat:"M4 5h16v11H9l-5 4V5z",textMessage:"M7 2h10a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1zM11 18h2",repeat:"M17 2l3 3-3 3M4 11V9a4 4 0 0 1 4-4h12M7 22l-3-3 3-3M20 13v2a4 4 0 0 1-4 4H4",if:"M6 3v6a4 4 0 0 0 4 4h8M15 10l3 3-3 3M6 13v8",ai:"M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z",script:"M8 7l-5 5 5 5M16 7l5 5-5 5"};let tryRecord=$state("");let tryError=$state("");let testRows=$state.raw([]);const testTable=$derived(current?.table.id??"");$effect(()=>{const id=testTable;untrack(()=>{const t=tableOf(id);tryRecord="";testRows=[];if(!t)return;const take=rows=>{if(testTable!==id)return;testRows=rows;if(!tryRecord&&rows[0])tryRecord=rowIdOf(t,rows[0])};if(records)void records(t.id).then(take,()=>take([]));else if(t.source?.server&&runner)void runner.firstRecords(t.id,200).then(take);else take((t.data??[]).filter(Boolean).slice(0,200))})});const testChoices=$derived(current?testRows.map(r=>({id:rowIdOf(current.table,r),name:String(r[primaryOf(current.table)]??"")||bm("extras.noName")})):[]);const canTest=$derived(!!current&&(side(current.a)==="server"&&!!runOnServer||side(current.a)!=="server"&&!!runner));function test(){const c=current;if(!c)return;const a=JSON.parse(JSON.stringify(c.a));tryError="";if(side(a)==="server"&&runOnServer){runOnServer(a,c.table.id,tryRecord||null).then(()=>showRuns(),e=>{tryError=e instanceof Error?e.message:String(e);showRuns()});return}if(runner){void runner.runNow(a,c.table.id,tryRecord||null);showRuns()}}let fromServer=$state.raw([]);let serverError=$state("");let onlyThis=$state(true);function showRuns(){tab="runs";if(!serverRuns)return;serverRuns().then(r=>{fromServer=r;serverError=""},e=>serverError=e instanceof Error?e.message:String(e))}const allRuns=$derived([...(runner?.runs??[]).map(r=>({...r,side:"browser"})),...fromServer.map(r=>({...r,side:"server"}))].sort((x,y)=>y.at-x.at));const shownRuns=$derived(onlyThis&&current?allRuns.filter(r=>r.automationId===current.a.id):allRuns);const time=at=>new Date(at).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"});
3
3
  </script>
4
4
 
5
5
  {#snippet mark(kind: string)}
@@ -207,6 +207,7 @@ import{untrack}from"svelte";import{SvSwitchButton,announce}from"@svgrid/grid";im
207
207
  <button type="button" class="sv-bap-danger" onclick={remove}>{bm('extras.delete')}</button>
208
208
  <button type="button" class="sv-fvb-text-btn" onclick={() => (deleting = false)}>{bm('extras.keep')}</button>
209
209
  {:else}
210
+ <button type="button" class="sv-fvb-text-btn" onclick={duplicate}>{bm('extras.duplicateAutomation')}</button>
210
211
  <button type="button" class="sv-bap-danger" onclick={() => (deleting = true)}>{bm('extras.deleteAutomation')}</button>
211
212
  {/if}
212
213
  </div>
@@ -1 +1 @@
1
- import{FORMULA_FUNCTIONS as _,columnResolver as j,formulaError as G}from"./formula.js";import{aiPromptError as W}from"./ai-prompt.js";import{OPTION_COLORS as z}from"./palette.js";const H=["blue","cyan","teal","green","yellow","orange","red","pink","purple","gray"],K={Light2:0,Light1:1,Bright:2,Dark1:3};export function airtableColor(t){const i=/^(blue|cyan|teal|green|yellow|orange|red|pink|purple|gray)(Light2|Light1|Bright|Dark1)?$/.exec(String(t??""));if(i)return z[K[i[2]??"Bright"]*10+H.indexOf(i[1])]?.value}const X=new Set(["local","friendly","us","european","iso"]),J=new Set(["h:mm","h:mm:ss","h:mm:ss.S","h:mm:ss.SS","h:mm:ss.SSS"]),U=new Set(["check","star","heart","thumbsUp","flag","dot"]),V={grid:"grid",kanban:"kanban",calendar:"calendar",gallery:"gallery",form:"form",timeline:"timeline",gantt:"gantt"},v=new Set(["SUM","AVERAGE","MIN","MAX","COUNT","COUNTA","COUNTALL","ARRAYJOIN","ARRAYUNIQUE","CONCATENATE","AND","OR"]),$=new Set(["number","currency","percent","duration","rating"]),Z=new Set(["formula","rollup","multipleLookupValues","count","button"]);function w(t,i){const e={time:i},l=t?.dateFormat?.name;return X.has(l)&&(e.dateFormat=l),i&&((t?.timeFormat?.name==="24hour"||t?.timeFormat?.name==="12hour")&&(e.timeFormat=t.timeFormat.name),t?.timeZone==="utc"&&(e.gmt=!0)),e}function Q(t,i){const e=t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"field";let l=e;for(let o=2;i.has(l);o++)l=`${e}_${o}`;return i.add(l),l}function B(t,i,e){let l="",o=0,T=0;const I=n=>{l+=i(t.slice(T,n))};for(;o<t.length;){const n=t[o];if(n==='"'||n==="'"){I(o);let r=o+1;for(;r<t.length&&t[r]!==n;)r+=t[r]==="\\"?2:1;l+=t.slice(o,r+1),o=T=r+1}else if(n==="{"){I(o);const r=t.indexOf("}",o);if(r<0){T=o;break}l+=`{${e(t.slice(o+1,r))}}`,o=T=r+1}else o++}return l+i(t.slice(T))}function q(t){let i="",e=0;for(;e<t.length;){const l=t[e];if(l!=='"'&&l!=="'"){i+=l,e++;continue}let o=e+1;for(;o<t.length&&t[o]!==l;)o+=t[o]==="\\"?2:1;i+=l+" ".repeat(Math.max(0,Math.min(o,t.length)-e-1))+(o<t.length?l:""),e=o+1}return i}function ee(t){const i=[...t.fields],e=[],l=n=>{const r=n.trim();return i.find(s=>s.id===r)?.id??i.find(s=>s.name===r)?.id},o=n=>{let r=n;for(let s=2;i.some(f=>f.name===r);s++)r=`${n} ${s}`;return r},T=(n,r)=>Array.isArray(n)&&n.length===r.length&&r.every(s=>n.includes(s)),I=(n,r)=>{const s=n===null?i.find(u=>u.type==="createdTime"):i.find(u=>u.type==="lastModifiedTime"&&(n.length?T(u.options?.referencedFieldIds,n):!u.options?.referencedFieldIds?.length));if(s)return s.id;const f=n===null?"Created":n.length?`${n.map(u=>i.find(a=>a.id===u).name).join(" and ")} modified`:"Last modified",h={id:n===null?"fldSvCreated":`fldSvModified${n.join("")}`,name:o(f),type:n===null?"createdTime":"lastModifiedTime",options:{...n?.length?{referencedFieldIds:n}:{},result:{type:"dateTime"}}};return i.push(h),e.push({field:h,usedBy:r}),h.id};for(const[n,r]of i.entries()){if(r.type!=="formula"||typeof r.options?.formula!="string")continue;const s=r.options.formula,f=q(s),h=[];for(const a of f.matchAll(/\bCREATED_TIME\s*\(\s*\)/gi))h.push([a.index,a.index+a[0].length,`{${I(null,r.name)}}`]);for(const a of f.matchAll(/\bLAST_MODIFIED_TIME\s*\(\s*((?:\{[^}]*\}\s*,?\s*)*)\)/gi)){const y=[...a[1].matchAll(/\{([^}]*)\}/g)].map(g=>l(g[1]));y.some(g=>!g)||h.push([a.index,a.index+a[0].length,`{${I(y,r.name)}}`])}if(!h.length)continue;let u=s;for(const[a,y,g]of h.sort((N,C)=>C[0]-N[0]))u=u.slice(0,a)+g+u.slice(y);i[n]={...r,options:{...r.options,formula:u}}}return{table:e.length||i.some((n,r)=>n!==t.fields[r])?{...t,fields:i}:t,added:e}}export function formulaFunctionsUsed(t){const i=new Set;return B(t,e=>{for(const l of e.matchAll(/([A-Za-z_][A-Za-z0-9_]*)\s*\(/g))i.add(l[1].toUpperCase());return e},e=>e),[...i]}function te(t,i){return B(t,e=>e,e=>i.get(e.trim())??e)}function ie(t,i){const e=t.options??{},l=i.keys.get(i.table.id),o=(n,r)=>i.report.push({kind:n,table:i.table.name,name:t.name,message:r}),T=n=>{const r=l.get(String(n));return r||o("link","The link field it reads is not in the table."),r},I=(n,r)=>{const s=i.table.fields.find(f=>f.id===n);return i.keys.get(String(s?.options?.linkedTableId))?.get(String(r))};switch(t.type){case"singleLineText":return{fieldType:"text"};case"multilineText":return{fieldType:"longText"};case"richText":return{fieldType:"longText",fieldProps:{richText:!0}};case"email":return{fieldType:"email"};case"url":return{fieldType:"url"};case"phoneNumber":return{fieldType:"phone"};case"number":{const n=Number(e.precision??0);return{fieldType:"number",fieldProps:n>0?{format:"decimal",precision:n}:{format:"integer",precision:0}}}case"currency":return{fieldType:"number",fieldProps:{format:"currency",precision:Number(e.precision??2),symbol:e.symbol??"$"}};case"percent":return{fieldType:"number",fieldProps:{format:"percent",precision:Number(e.precision??0)}};case"rating":{const n=airtableColor(e.color);return{fieldType:"rating",fieldProps:{max:Number(e.max??5),...U.has(e.icon)&&e.icon!=="check"?{icon:e.icon}:{},...n?{color:n}:{}}}}case"duration":return{fieldType:"duration",fieldProps:J.has(e.durationFormat)?{durationFormat:e.durationFormat}:{}};case"checkbox":{const n=airtableColor(e.color),r=e.icon==="xCheckbox"?"x":U.has(e.icon)?e.icon:void 0;return{fieldType:"checkbox",fieldProps:{...r?{icon:r}:{},...n?{color:n}:{}}}}case"singleSelect":case"multipleSelects":{const n=(Array.isArray(e.choices)?e.choices:[]).map(r=>{const s=airtableColor(r.color);return{value:String(r.name),...s?{color:s}:{}}});return{fieldType:t.type==="singleSelect"?"singleSelect":"multiSelect",fieldProps:{options:n}}}case"date":return{fieldType:"date",fieldProps:w(e,!1)};case"dateTime":return{fieldType:"date",fieldProps:w(e,!0)};case"singleCollaborator":return{fieldType:"user",fieldProps:{multiple:!1}};case"multipleCollaborators":return{fieldType:"user",fieldProps:{multiple:!0}};case"multipleRecordLinks":{const n=String(e.linkedTableId??"");i.tableIds.has(n)||o("link","It links to a table that was not imported; the record ids stay, the cells show none of them.");const r=e.inverseLinkFieldId?i.keys.get(n)?.get(String(e.inverseLinkFieldId)):void 0,s=typeof e.viewIdForRecordSelection=="string"&&e.viewIdForRecordSelection?{pickFrom:e.viewIdForRecordSelection}:{};return{fieldType:"link",fieldProps:{table:n,multiple:e.prefersSingleRecordLink!==!0,...r&&n!==i.table.id&&i.tableIds.has(n)?{inverse:r}:{},...s}}}case"multipleAttachments":return{fieldType:"attachment"};case"barcode":return{fieldType:"barcode"};case"autoNumber":return{fieldType:"autoNumber"};case"button":return o("setting","The API does not say what the button does: set its URL (fieldProps.url, with {Field name} for values) or fieldProps.onClick."),{fieldType:"button",fieldProps:{label:String(e.label??t.name)}};case"createdTime":return{fieldType:"createdTime",fieldProps:w(e.result?.options,e.result?.type!=="date")};case"lastModifiedTime":case"lastModifiedBy":{const n=(Array.isArray(e.referencedFieldIds)?e.referencedFieldIds:[]).map(s=>l.get(s)).filter(Boolean),r=n.length?{watch:"specific",watchFields:n}:{watch:"all"};return t.type==="lastModifiedTime"?{fieldType:"lastModifiedTime",fieldProps:{...r,...w(e.result?.options,e.result?.type!=="date")}}:{fieldType:"lastModifiedBy",fieldProps:r}}case"createdBy":return{fieldType:"createdBy"};case"aiText":{const n=new Map(i.table.fields.map(u=>[u.id,u.name])),s=(Array.isArray(e.prompt)?e.prompt:typeof e.prompt=="string"?[e.prompt]:[]).map(u=>{if(typeof u=="string")return u;const a=u?.field?.fieldId;return a!=null?`{${n.get(String(a))??String(a)}}`:""}).join(""),f=i.table.fields.filter(u=>u.id!==t.id).map(u=>({field:l.get(u.id),header:u.name})),h=W(s,f,[t.name]);return s.trim()?h?o("setting",`${h}: fix the prompt in the field editor. The generated values come over as they are.`):o("setting","The generated values come over as they are. New ones come from the AI provider your app sets with setAIProvider()."):o("setting","The API gave no prompt: write one in the field editor. The generated values come over as they are."),{fieldType:"ai",fieldProps:{prompt:s,output:"text",auto:!0}}}case"formula":{const n=new Map(i.table.fields.map(f=>[f.id,f.name])),r=te(String(e.formula??""),n),s=formulaFunctionsUsed(r).filter(f=>!_.includes(f));if(s.length)o("formula",`Uses ${s.join(", ")}, which Base formulas do not have: the cells show #ERROR until that part is rewritten.`);else{const f=i.table.fields.filter(u=>u.id!==t.id).map(u=>({field:l.get(u.id),header:u.name})),h=G(r,j(f,[t.name]));h&&o("formula",`${h}: the cells show #ERROR.`)}return{fieldType:"formula",fieldProps:{formula:r,...ne(e.result)}}}case"rollup":{const n=T(e.recordLinkFieldId),r=I(e.recordLinkFieldId,e.fieldIdInLinkedTable),s=/^\s*([A-Za-z_]+)\s*\(\s*values\s*\)\s*$/i.exec(String(e.formula??""))?.[1]?.toUpperCase(),f=s&&v.has(s)?s:$.has(e.result?.type)?"SUM":"ARRAYJOIN";s?v.has(s)||o("formula",`The rollup's ${s}(values) has no Base aggregation; it is set to ${f}.`):o("setting",`The schema does not include the rollup's aggregation; it is set to ${f}. Change it in the field editor if the base used another.`);const h=e.result?.options?.precision;return{fieldType:"rollup",fieldProps:{linkField:n,field:r,aggregation:f,...h!=null&&$.has(e.result?.type)?{precision:Number(h)}:{}}}}case"multipleLookupValues":return{fieldType:"lookup",fieldProps:{linkField:T(e.recordLinkFieldId),field:I(e.recordLinkFieldId,e.fieldIdInLinkedTable)}};case"count":return{fieldType:"count",fieldProps:{linkField:T(e.recordLinkFieldId)}};default:return null}}function ne(t){const i=t?.options??{},e=i.precision!=null?{precision:Number(i.precision)}:{};switch(t?.type){case"number":return{result:"number",...e};case"currency":return{result:"currency",...e,...i.symbol?{symbol:i.symbol}:{}};case"percent":return{result:"percent",...e};case"date":return{result:"date",...w(i,!1)};case"dateTime":return{result:"date",...w(i,!0)};default:return{result:"auto"}}}const F=t=>Array.isArray(t)?t:t==null?[]:[t];function re(t){const i=t.thumbnails?.large?.url??t.thumbnails?.small?.url;return{id:String(t.id??t.url),url:String(t.url??""),name:String(t.filename??t.name??""),type:String(t.type??""),...typeof t.size=="number"?{size:t.size}:{},...typeof t.width=="number"?{width:t.width}:{},...typeof t.height=="number"?{height:t.height}:{},...i?{thumbnailUrl:String(i)}:{}}}function M(t){if(t==null)return"";if(Array.isArray(t))return t.map(M).join(", ");if(typeof t=="object"){const i=t;return"value"in i?M(i.value):"name"in i?String(i.name):"text"in i?String(i.text):JSON.stringify(t)}return String(t)}export function baseFromAirtable(t,i={},e={}){const l=[];for(const a of Array.isArray(t?.tables)?t.tables:[])if(!a||!Array.isArray(a.fields))throw Object.assign(new Error(`baseFromAirtable: a table in this file has no list of fields. Pass the JSON of Airtable's "Get base schema" call.`),{code:"bad-airtable-schema"});const o=(Array.isArray(t?.tables)?t.tables:[]).map(ee),T=o.map(a=>a.table),I=e.tables?.length?e.tables.map(a=>T.find(y=>y.id===a||y.name===a)).filter(a=>!!a):T,n=new Set(I.map(a=>a.id)),r=new Map;for(const a of T){const y=new Set(["id"]);r.set(a.id,new Map(a.fields.map(g=>[g.id,Q(g.name,y)])))}const s=new Map,f=e.userId??(a=>a.id),h=a=>{if(a==null||typeof a!="object")return a==null?null:String(a);const y=a,g=f(y);return s.has(g)||s.set(g,{id:g,name:y.name??y.email??g,...y.email?{email:y.email}:{}}),g};return{tables:I.map(a=>{const y={table:a,keys:r,tableIds:n,report:l};for(const{field:d,usedBy:c}of o.find(b=>b.table===a)?.added??[]){const b=(d.options?.referencedFieldIds??[]).map(m=>a.fields.find(A=>A.id===m).name),p=m=>l.push({kind:"field",table:a.name,name:d.name,message:`Added for ${c}, ${m}`});d.type==="createdTime"?p("which reads CREATED_TIME(): a Base record keeps that time in a Created time field. It holds each record's createdTime from the API."):b.length?p(`which reads when ${b.join(" and ")} last changed: a Last modified time field that watches ${b.length>1?"them":"it"}. The API does not say when a field last changed, so it is empty until the next edit.`):p("which reads LAST_MODIFIED_TIME(): a Last modified time field. The API does not say when a record last changed, so it is empty until the next edit.")}const g=r.get(a.id),N=a.primaryFieldId??a.fields[0]?.id,P=[...a.fields].sort((d,c)=>+(c.id===N)-+(d.id===N)).map(d=>{let c=ie(d,y);return c||(l.push({kind:"field",table:a.name,name:d.name,message:`Base has no "${d.type}" field: it is a text field, with each value as text.`}),c={fieldType:"text"}),{f:d,key:g.get(d.id),fieldType:c.fieldType,fieldProps:c.fieldProps,known:c.fieldType!=="text"||d.type==="singleLineText"}}),S=P.map(({f:d,key:c,fieldType:b,fieldProps:p})=>({id:c,field:c,header:d.name,fieldType:b,...p&&Object.keys(p).length?{fieldProps:p}:{},...d.description?{description:d.description}:{}})),k=i[a.id]??i[a.name],Y=(Array.isArray(k)?k:k?.records??[]).map(d=>{const c={id:d.id};for(const{f:b,key:p,fieldType:m,fieldProps:A,known:O}of P){if(Z.has(b.type))continue;let E=d.fields?.[b.name]??d.fields?.[b.id];b.type==="createdTime"&&E==null&&(E=d.createdTime),E!==void 0&&(O?m==="user"||m==="createdBy"||m==="lastModifiedBy"?c[p]=A?.multiple?F(E).map(h).filter(R=>R!=null):h(Array.isArray(E)?E[0]:E):m==="attachment"?c[p]=F(E).filter(R=>R&&typeof R=="object").map(R=>re(R)):m==="link"?c[p]=F(E).map(R=>String(R&&typeof R=="object"?R.id:R)):m==="ai"?c[p]=E&&typeof E=="object"?E.value??null:E:c[p]=E:c[p]=M(E))}return c}),x=d=>S.find(d)?.field,D=[];for(const d of a.views??[]){const c=V[d.type],b=m=>l.push({kind:"view",table:a.name,name:d.name,message:m});if(!c){b(`Base has no "${d.type}" view; it was left out.`);continue}const p={id:d.id,name:d.name,type:c};if(c==="kanban"){const m=x(A=>A.fieldType==="singleSelect"||A.fieldType==="user"&&!A.fieldProps?.multiple);if(!m){b("A Kanban view needs a single select or a single user field; the table has none.");continue}p.stackBy=m,l.push({kind:"setting",table:a.name,name:d.name,message:`The API does not say which field the board stacks by; it uses ${S.find(A=>A.field===m).header}.`})}else if(c==="calendar"||c==="timeline"||c==="gantt"){const m=S.filter(A=>A.fieldType==="date").map(A=>String(A.field));if(!m.length){b(`A ${c==="calendar"?"calendar":c==="gantt"?"Gantt":"timeline"} needs a date field; the table has none.`);continue}p.dateField=m[0],c!=="calendar"&&m[1]&&(p.endField=m[1]),l.push({kind:"setting",table:a.name,name:d.name,message:`The API does not say which dates the view uses; it uses ${[p.dateField,p.endField].filter(Boolean).map(A=>S.find(O=>O.field===A).header).join(" to ")}.`}),c==="timeline"&&l.push({kind:"setting",table:a.name,name:d.name,message:"The API does not say which field the swimlanes are; pick it under Customize timeline, Lanes by."})}else if(c==="gallery"){const m=x(A=>A.fieldType==="attachment");m&&(p.coverField=m)}D.push(p)}return D.length||D.push({id:"grid",name:"Grid view",type:"grid"}),{id:a.id,name:a.name,primaryField:g.get(N??"")??String(S[0]?.field??""),columns:S,data:Y,views:D}}),users:[...s.values()],report:l}}const L="JavaScript regular expressions, not RE2.",ae=[["CONCATENATE","Text"],["LEFT","Text"],["RIGHT","Text"],["MID","Text","The count may be left out for the rest of the text."],["LEN","Text"],["FIND","Text","Case matters; 0 when the text is not there."],["SEARCH","Text","Case matters; empty when the text is not there."],["SUBSTITUTE","Text"],["REPLACE","Text"],["TRIM","Text"],["UPPER","Text"],["LOWER","Text"],["REPT","Text","At most 1,000 repeats.",!0],["T","Text"],["ENCODE_URL_COMPONENT","Text"],["REGEX_MATCH","Text",`${L} A leading (?i) works; other inline flags do not.`,!0],["REGEX_EXTRACT","Text",`${L} Empty when nothing matches.`,!0],["REGEX_REPLACE","Text",`${L} Replaces every match; the new text names a group by its number after a dollar sign, as JavaScript's replace does.`,!0],["IF","Logical"],["SWITCH","Logical",'Compares as text, so 1 matches "1".',!0],["AND","Logical"],["OR","Logical"],["NOT","Logical"],["XOR","Logical"],["TRUE","Logical","With or without the parentheses."],["FALSE","Logical","With or without the parentheses."],["BLANK","Logical"],["ERROR","Logical","The cell shows #ERROR."],["ISERROR","Logical","Division by zero is empty in Base, not an error, so ISERROR(1 / 0) is false.",!0],["ABS","Numeric"],["AVERAGE","Numeric"],["CEILING","Numeric"],["COUNT","Numeric"],["COUNTA","Numeric"],["COUNTALL","Numeric"],["EVEN","Numeric"],["EXP","Numeric"],["FLOOR","Numeric"],["INT","Numeric"],["LOG","Numeric","Base 10 unless a base is given."],["MAX","Numeric"],["MIN","Numeric"],["MOD","Numeric"],["ODD","Numeric"],["POWER","Numeric"],["ROUND","Numeric","Halves round toward positive: ROUND(-2.5) is -2."],["ROUNDDOWN","Numeric","Toward zero."],["ROUNDUP","Numeric","Away from zero."],["SQRT","Numeric"],["SUM","Numeric"],["VALUE","Numeric",'Skips characters that are not part of a number: VALUE("1,200.50 USD") is 1200.5.'],["DATEADD","Date",'The units Airtable names, except that "M" is minutes here: write "months".',!0],["DATESTR","Date"],["DATETIME_DIFF","Date",'Units as in DATEADD: "M" is minutes, write "months".',!0],["DATETIME_FORMAT","Date","moment.js tokens (YYYY, MMMM, Do, HH, A, Z, L, LL and the rest); week-of-year tokens are not read.",!0],["DATETIME_PARSE","Date","Reads the tokens DATETIME_FORMAT writes, with the separators as written. Text without a zone is local time.",!0],["DAY","Date"],["HOUR","Date"],["IS_AFTER","Date"],["IS_BEFORE","Date"],["IS_SAME","Date"],["MINUTE","Date"],["MONTH","Date"],["NOW","Date"],["SECOND","Date"],["SET_LOCALE","Date","Changes the month and weekday names DATETIME_FORMAT writes; ordinals (Do) stay English.",!0],["SET_TIMEZONE","Date","Changes what DATETIME_FORMAT writes. An unknown zone leaves the cell empty.",!0],["TIMESTR","Date"],["TONOW","Date","Calendar days from the date to today, signed.",!0],["FROMNOW","Date","Calendar days from today to the date, signed.",!0],["TODAY","Date"],["WEEKDAY","Date",'0 for Sunday; "Monday" as the second argument makes Monday 0.'],["WEEKNUM","Date",'Weeks start on Sunday, or on Monday with "Monday".'],["WORKDAY","Date",'Holidays as text ("2026-12-25, 2026-12-26") or a list of dates.'],["WORKDAY_DIFF","Date","Both days count. Holidays as in WORKDAY."],["YEAR","Date"],["ARRAYCOMPACT","Array"],["ARRAYFLATTEN","Array"],["ARRAYJOIN","Array"],["ARRAYUNIQUE","Array"],["ARRAYSLICE","Array"],["RECORD_ID","Record","The record's id; after baseFromAirtable, the Airtable record id."],["CREATED_TIME","Record","A Base record keeps that time in a Created time field. baseFromAirtable rewrites CREATED_TIME() to read the table's, and adds one when the table has none."],["LAST_MODIFIED_TIME","Record","A Base record keeps that time in a Last modified time field. baseFromAirtable rewrites LAST_MODIFIED_TIME() to read one that watches every field, and LAST_MODIFIED_TIME({Field}) one that watches that field, and adds it when the table has none."]];export function airtableFormulaSupport(){return ae.map(([t,i,e="",l])=>{const T=_.includes(t)?l?"different":"supported":"unsupported";return{name:t,group:i,status:T,note:e}})}
1
+ import{FORMULA_FUNCTIONS as _,columnResolver as W,formulaError as j}from"./formula.js";import{aiPromptError as G}from"./ai-prompt.js";import{OPTION_COLORS as z}from"./palette.js";const H=["blue","cyan","teal","green","yellow","orange","red","pink","purple","gray"],K={Light2:0,Light1:1,Bright:2,Dark1:3};export function airtableColor(t){const i=/^(blue|cyan|teal|green|yellow|orange|red|pink|purple|gray)(Light2|Light1|Bright|Dark1)?$/.exec(String(t??""));if(i)return z[K[i[2]??"Bright"]*10+H.indexOf(i[1])]?.value}const X=new Set(["local","friendly","us","european","iso"]),J=new Set(["h:mm","h:mm:ss","h:mm:ss.S","h:mm:ss.SS","h:mm:ss.SSS"]),U=new Set(["check","star","heart","thumbsUp","flag","dot"]),V={grid:"grid",kanban:"kanban",calendar:"calendar",gallery:"gallery",form:"form",timeline:"timeline",gantt:"gantt"},v=new Set(["SUM","AVERAGE","MIN","MAX","COUNT","COUNTA","COUNTALL","ARRAYJOIN","ARRAYUNIQUE","CONCATENATE","AND","OR"]),$=new Set(["number","currency","percent","duration","rating"]),Z=new Set(["formula","rollup","multipleLookupValues","count","button"]);function w(t,i){const e={time:i},l=t?.dateFormat?.name;return X.has(l)&&(e.dateFormat=l),i&&((t?.timeFormat?.name==="24hour"||t?.timeFormat?.name==="12hour")&&(e.timeFormat=t.timeFormat.name),t?.timeZone==="utc"&&(e.gmt=!0)),e}function Q(t,i){const e=t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"field";let l=e;for(let o=2;i.has(l);o++)l=`${e}_${o}`;return i.add(l),l}function B(t,i,e){let l="",o=0,T=0;const I=r=>{l+=i(t.slice(T,r))};for(;o<t.length;){const r=t[o];if(r==='"'||r==="'"){I(o);let n=o+1;for(;n<t.length&&t[n]!==r;)n+=t[n]==="\\"?2:1;l+=t.slice(o,n+1),o=T=n+1}else if(r==="{"){I(o);const n=t.indexOf("}",o);if(n<0){T=o;break}l+=`{${e(t.slice(o+1,n))}}`,o=T=n+1}else o++}return l+i(t.slice(T))}function q(t){let i="",e=0;for(;e<t.length;){const l=t[e];if(l!=='"'&&l!=="'"){i+=l,e++;continue}let o=e+1;for(;o<t.length&&t[o]!==l;)o+=t[o]==="\\"?2:1;i+=l+" ".repeat(Math.max(0,Math.min(o,t.length)-e-1))+(o<t.length?l:""),e=o+1}return i}function ee(t){const i=[...t.fields],e=[],l=r=>{const n=r.trim();return i.find(s=>s.id===n)?.id??i.find(s=>s.name===n)?.id},o=r=>{let n=r;for(let s=2;i.some(f=>f.name===n);s++)n=`${r} ${s}`;return n},T=(r,n)=>Array.isArray(r)&&r.length===n.length&&n.every(s=>r.includes(s)),I=(r,n)=>{const s=r===null?i.find(u=>u.type==="createdTime"):i.find(u=>u.type==="lastModifiedTime"&&(r.length?T(u.options?.referencedFieldIds,r):!u.options?.referencedFieldIds?.length));if(s)return s.id;const f=r===null?"Created":r.length?`${r.map(u=>i.find(a=>a.id===u).name).join(" and ")} modified`:"Last modified",h={id:r===null?"fldSvCreated":`fldSvModified${r.join("")}`,name:o(f),type:r===null?"createdTime":"lastModifiedTime",options:{...r?.length?{referencedFieldIds:r}:{},result:{type:"dateTime"}}};return i.push(h),e.push({field:h,usedBy:n}),h.id};for(const[r,n]of i.entries()){if(n.type!=="formula"||typeof n.options?.formula!="string")continue;const s=n.options.formula,f=q(s),h=[];for(const a of f.matchAll(/\bCREATED_TIME\s*\(\s*\)/gi))h.push([a.index,a.index+a[0].length,`{${I(null,n.name)}}`]);for(const a of f.matchAll(/\bLAST_MODIFIED_TIME\s*\(\s*((?:\{[^}]*\}\s*,?\s*)*)\)/gi)){const y=[...a[1].matchAll(/\{([^}]*)\}/g)].map(g=>l(g[1]));y.some(g=>!g)||h.push([a.index,a.index+a[0].length,`{${I(y,n.name)}}`])}if(!h.length)continue;let u=s;for(const[a,y,g]of h.sort((N,C)=>C[0]-N[0]))u=u.slice(0,a)+g+u.slice(y);i[r]={...n,options:{...n.options,formula:u}}}return{table:e.length||i.some((r,n)=>r!==t.fields[n])?{...t,fields:i}:t,added:e}}export function formulaFunctionsUsed(t){const i=new Set;return B(t,e=>{for(const l of e.matchAll(/([A-Za-z_][A-Za-z0-9_]*)\s*\(/g))i.add(l[1].toUpperCase());return e},e=>e),[...i]}function te(t,i){return B(t,e=>e,e=>i.get(e.trim())??e)}function ie(t,i){const e=t.options??{},l=i.keys.get(i.table.id),o=(r,n)=>i.report.push({kind:r,table:i.table.name,name:t.name,message:n}),T=r=>{const n=l.get(String(r));return n||o("link","The link field it reads is not in the table."),n},I=(r,n)=>{const s=i.table.fields.find(f=>f.id===r);return i.keys.get(String(s?.options?.linkedTableId))?.get(String(n))};switch(t.type){case"singleLineText":return{fieldType:"text"};case"multilineText":return{fieldType:"longText"};case"richText":return{fieldType:"longText",fieldProps:{richText:!0}};case"email":return{fieldType:"email"};case"url":return{fieldType:"url"};case"phoneNumber":return{fieldType:"phone"};case"number":{const r=Number(e.precision??0);return{fieldType:"number",fieldProps:r>0?{format:"decimal",precision:r}:{format:"integer",precision:0}}}case"currency":return{fieldType:"number",fieldProps:{format:"currency",precision:Number(e.precision??2),symbol:e.symbol??"$"}};case"percent":return{fieldType:"number",fieldProps:{format:"percent",precision:Number(e.precision??0)}};case"rating":{const r=airtableColor(e.color);return{fieldType:"rating",fieldProps:{max:Number(e.max??5),...U.has(e.icon)&&e.icon!=="check"?{icon:e.icon}:{},...r?{color:r}:{}}}}case"duration":return{fieldType:"duration",fieldProps:J.has(e.durationFormat)?{durationFormat:e.durationFormat}:{}};case"checkbox":{const r=airtableColor(e.color),n=e.icon==="xCheckbox"?"x":U.has(e.icon)?e.icon:void 0;return{fieldType:"checkbox",fieldProps:{...n?{icon:n}:{},...r?{color:r}:{}}}}case"singleSelect":case"multipleSelects":{const r=(Array.isArray(e.choices)?e.choices:[]).map(n=>{const s=airtableColor(n.color);return{value:String(n.name),...s?{color:s}:{}}});return{fieldType:t.type==="singleSelect"?"singleSelect":"multiSelect",fieldProps:{options:r}}}case"date":return{fieldType:"date",fieldProps:w(e,!1)};case"dateTime":return{fieldType:"date",fieldProps:w(e,!0)};case"singleCollaborator":return{fieldType:"user",fieldProps:{multiple:!1}};case"multipleCollaborators":return{fieldType:"user",fieldProps:{multiple:!0}};case"multipleRecordLinks":{const r=String(e.linkedTableId??"");i.tableIds.has(r)||o("link","It links to a table that was not imported; the record ids stay, the cells show none of them.");const n=e.inverseLinkFieldId?i.keys.get(r)?.get(String(e.inverseLinkFieldId)):void 0,s=typeof e.viewIdForRecordSelection=="string"&&e.viewIdForRecordSelection?{pickFrom:e.viewIdForRecordSelection}:{};return{fieldType:"link",fieldProps:{table:r,multiple:e.prefersSingleRecordLink!==!0,...n&&r!==i.table.id&&i.tableIds.has(r)?{inverse:n}:{},...s}}}case"multipleAttachments":return{fieldType:"attachment"};case"barcode":return{fieldType:"barcode"};case"autoNumber":return{fieldType:"autoNumber"};case"button":return o("setting","The API does not say what the button does: set its URL (fieldProps.url, with {Field name} for values) or fieldProps.onClick."),{fieldType:"button",fieldProps:{label:String(e.label??t.name)}};case"createdTime":return{fieldType:"createdTime",fieldProps:w(e.result?.options,e.result?.type!=="date")};case"lastModifiedTime":case"lastModifiedBy":{const r=(Array.isArray(e.referencedFieldIds)?e.referencedFieldIds:[]).map(s=>l.get(s)).filter(Boolean),n=r.length?{watch:"specific",watchFields:r}:{watch:"all"};return t.type==="lastModifiedTime"?{fieldType:"lastModifiedTime",fieldProps:{...n,...w(e.result?.options,e.result?.type!=="date")}}:{fieldType:"lastModifiedBy",fieldProps:n}}case"createdBy":return{fieldType:"createdBy"};case"aiText":{const r=new Map(i.table.fields.map(u=>[u.id,u.name])),s=(Array.isArray(e.prompt)?e.prompt:typeof e.prompt=="string"?[e.prompt]:[]).map(u=>{if(typeof u=="string")return u;const a=u?.field?.fieldId;return a!=null?`{${r.get(String(a))??String(a)}}`:""}).join(""),f=i.table.fields.filter(u=>u.id!==t.id).map(u=>({field:l.get(u.id),header:u.name})),h=G(s,f,[t.name]);return s.trim()?h?o("setting",`${h}: fix the prompt in the field editor. The generated values come over as they are.`):o("setting","The generated values come over as they are. New ones come from the AI provider your app sets with setAIProvider()."):o("setting","The API gave no prompt: write one in the field editor. The generated values come over as they are."),{fieldType:"ai",fieldProps:{prompt:s,output:"text",auto:!0}}}case"formula":{const r=new Map(i.table.fields.map(f=>[f.id,f.name])),n=te(String(e.formula??""),r),s=formulaFunctionsUsed(n).filter(f=>!_.includes(f));if(s.length)o("formula",`Uses ${s.join(", ")}, which Base formulas do not have: the cells show #ERROR until that part is rewritten.`);else{const f=i.table.fields.filter(u=>u.id!==t.id).map(u=>({field:l.get(u.id),header:u.name})),h=j(n,W(f,[t.name]));h&&o("formula",`${h}: the cells show #ERROR.`)}return{fieldType:"formula",fieldProps:{formula:n,...re(e.result)}}}case"rollup":{const r=T(e.recordLinkFieldId),n=I(e.recordLinkFieldId,e.fieldIdInLinkedTable),s=/^\s*([A-Za-z_]+)\s*\(\s*values\s*\)\s*$/i.exec(String(e.formula??""))?.[1]?.toUpperCase(),f=s&&v.has(s)?s:$.has(e.result?.type)?"SUM":"ARRAYJOIN";s?v.has(s)||o("formula",`The rollup's ${s}(values) has no Base aggregation; it is set to ${f}.`):o("setting",`The schema does not include the rollup's aggregation; it is set to ${f}. Change it in the field editor if the base used another.`);const h=e.result?.options?.precision;return{fieldType:"rollup",fieldProps:{linkField:r,field:n,aggregation:f,...h!=null&&$.has(e.result?.type)?{precision:Number(h)}:{}}}}case"multipleLookupValues":return{fieldType:"lookup",fieldProps:{linkField:T(e.recordLinkFieldId),field:I(e.recordLinkFieldId,e.fieldIdInLinkedTable)}};case"count":return{fieldType:"count",fieldProps:{linkField:T(e.recordLinkFieldId)}};default:return null}}function re(t){const i=t?.options??{},e=i.precision!=null?{precision:Number(i.precision)}:{};switch(t?.type){case"number":return{result:"number",...e};case"currency":return{result:"currency",...e,...i.symbol?{symbol:i.symbol}:{}};case"percent":return{result:"percent",...e};case"date":return{result:"date",...w(i,!1)};case"dateTime":return{result:"date",...w(i,!0)};default:return{result:"auto"}}}const F=t=>Array.isArray(t)?t:t==null?[]:[t];function ne(t){const i=t.thumbnails?.large?.url??t.thumbnails?.small?.url;return{id:String(t.id??t.url),url:String(t.url??""),name:String(t.filename??t.name??""),type:String(t.type??""),...typeof t.size=="number"?{size:t.size}:{},...typeof t.width=="number"?{width:t.width}:{},...typeof t.height=="number"?{height:t.height}:{},...i?{thumbnailUrl:String(i)}:{}}}function M(t){if(t==null)return"";if(Array.isArray(t))return t.map(M).join(", ");if(typeof t=="object"){const i=t;return"value"in i?M(i.value):"name"in i?String(i.name):"text"in i?String(i.text):JSON.stringify(t)}return String(t)}export function baseFromAirtable(t,i={},e={}){const l=[];for(const a of Array.isArray(t?.tables)?t.tables:[])if(!a||!Array.isArray(a.fields))throw Object.assign(new Error(`baseFromAirtable: a table in this file has no list of fields. Pass the JSON of Airtable's "Get base schema" call.`),{code:"bad-airtable-schema"});const o=(Array.isArray(t?.tables)?t.tables:[]).map(ee),T=o.map(a=>a.table),I=e.tables?.length?e.tables.map(a=>T.find(y=>y.id===a||y.name===a)).filter(a=>!!a):T,r=new Set(I.map(a=>a.id)),n=new Map;for(const a of T){const y=new Set(["id"]);n.set(a.id,new Map(a.fields.map(g=>[g.id,Q(g.name,y)])))}const s=new Map,f=e.userId??(a=>a.id),h=a=>{if(a==null||typeof a!="object")return a==null?null:String(a);const y=a,g=f(y);return s.has(g)||s.set(g,{id:g,name:y.name??y.email??g,...y.email?{email:y.email}:{}}),g};return{tables:I.map(a=>{const y={table:a,keys:n,tableIds:r,report:l};for(const{field:d,usedBy:c}of o.find(b=>b.table===a)?.added??[]){const b=(d.options?.referencedFieldIds??[]).map(m=>a.fields.find(A=>A.id===m).name),p=m=>l.push({kind:"field",table:a.name,name:d.name,message:`Added for ${c}, ${m}`});d.type==="createdTime"?p("which reads CREATED_TIME(): a Base record keeps that time in a Created time field. It holds each record's createdTime from the API."):b.length?p(`which reads when ${b.join(" and ")} last changed: a Last modified time field that watches ${b.length>1?"them":"it"}. The API does not say when a field last changed, so it is empty until the next edit.`):p("which reads LAST_MODIFIED_TIME(): a Last modified time field. The API does not say when a record last changed, so it is empty until the next edit.")}const g=n.get(a.id),N=a.primaryFieldId??a.fields[0]?.id,P=[...a.fields].sort((d,c)=>+(c.id===N)-+(d.id===N)).map(d=>{let c=ie(d,y);return c||(l.push({kind:"field",table:a.name,name:d.name,message:`Base has no "${d.type}" field: it is a text field, with each value as text.`}),c={fieldType:"text"}),{f:d,key:g.get(d.id),fieldType:c.fieldType,fieldProps:c.fieldProps,known:c.fieldType!=="text"||d.type==="singleLineText"}}),S=P.map(({f:d,key:c,fieldType:b,fieldProps:p})=>({id:c,field:c,header:d.name,fieldType:b,...p&&Object.keys(p).length?{fieldProps:p}:{},...d.description?{description:d.description}:{}})),O=i[a.id]??i[a.name],Y=(Array.isArray(O)?O:O?.records??[]).map(d=>{const c={id:d.id};for(const{f:b,key:p,fieldType:m,fieldProps:A,known:k}of P){if(Z.has(b.type))continue;let E=d.fields?.[b.name]??d.fields?.[b.id];b.type==="createdTime"&&E==null&&(E=d.createdTime),E!==void 0&&(k?m==="user"||m==="createdBy"||m==="lastModifiedBy"?c[p]=A?.multiple?F(E).map(h).filter(R=>R!=null):h(Array.isArray(E)?E[0]:E):m==="attachment"?c[p]=F(E).filter(R=>R&&typeof R=="object").map(R=>ne(R)):m==="link"?c[p]=F(E).map(R=>String(R&&typeof R=="object"?R.id:R)):m==="ai"?c[p]=E&&typeof E=="object"?E.value??null:E:c[p]=E:c[p]=M(E))}return c}),x=d=>S.find(d)?.field,D=[];for(const d of a.views??[]){const c=V[d.type],b=m=>l.push({kind:"view",table:a.name,name:d.name,message:m});if(!c){b(`Base has no "${d.type}" view; it was left out.`);continue}const p={id:d.id,name:d.name,type:c};if(c==="kanban"){const m=x(A=>A.fieldType==="singleSelect"||A.fieldType==="user"&&!A.fieldProps?.multiple);if(!m){b("A Kanban view needs a single select or a single user field; the table has none.");continue}p.stackBy=m,l.push({kind:"setting",table:a.name,name:d.name,message:`The API does not say which field the board stacks by; it uses ${S.find(A=>A.field===m).header}.`})}else if(c==="calendar"||c==="timeline"||c==="gantt"){const m=S.filter(A=>A.fieldType==="date").map(A=>String(A.field));if(!m.length){b(`A ${c==="calendar"?"calendar":c==="gantt"?"Gantt":"timeline"} needs a date field; the table has none.`);continue}p.dateField=m[0],c!=="calendar"&&m[1]&&(p.endField=m[1]),l.push({kind:"setting",table:a.name,name:d.name,message:`The API does not say which dates the view uses; it uses ${[p.dateField,p.endField].filter(Boolean).map(A=>S.find(k=>k.field===A).header).join(" to ")}.`}),c==="timeline"&&l.push({kind:"setting",table:a.name,name:d.name,message:"The API does not say which field the swimlanes are; pick it under Customize timeline, Lanes by."})}else if(c==="gallery"){const m=x(A=>A.fieldType==="attachment");m&&(p.coverField=m)}D.push(p)}return D.length||D.push({id:"grid",name:"Grid view",type:"grid"}),{id:a.id,name:a.name,primaryField:g.get(N??"")??String(S[0]?.field??""),columns:S,data:Y,views:D}}),users:[...s.values()],report:l}}const L="JavaScript regular expressions, not RE2.",ae=[["CONCATENATE","Text"],["LEFT","Text"],["RIGHT","Text"],["MID","Text","The count may be left out for the rest of the text."],["LEN","Text"],["FIND","Text","Case matters; 0 when the text is not there."],["SEARCH","Text","Case matters; empty when the text is not there."],["SUBSTITUTE","Text"],["REPLACE","Text"],["TRIM","Text"],["UPPER","Text"],["LOWER","Text"],["REPT","Text","At most 1,000 repeats.",!0],["T","Text"],["ENCODE_URL_COMPONENT","Text"],["REGEX_MATCH","Text",`${L} A leading (?i) works; other inline flags do not.`,!0],["REGEX_EXTRACT","Text",`${L} Empty when nothing matches.`,!0],["REGEX_REPLACE","Text",`${L} Replaces every match; the new text names a group by its number after a dollar sign, as JavaScript's replace does.`,!0],["IF","Logical"],["SWITCH","Logical",'Compares as text, so 1 matches "1".',!0],["AND","Logical"],["OR","Logical"],["NOT","Logical"],["XOR","Logical"],["TRUE","Logical","With or without the parentheses."],["FALSE","Logical","With or without the parentheses."],["BLANK","Logical"],["ERROR","Logical","The cell shows #ERROR."],["ISERROR","Logical","Division by zero is empty in Base, not an error, so ISERROR(1 / 0) is false.",!0],["ABS","Numeric"],["AVERAGE","Numeric"],["CEILING","Numeric"],["COUNT","Numeric"],["COUNTA","Numeric"],["COUNTALL","Numeric"],["EVEN","Numeric"],["EXP","Numeric"],["FLOOR","Numeric"],["INT","Numeric"],["LOG","Numeric","Base 10 unless a base is given."],["MAX","Numeric"],["MIN","Numeric"],["MOD","Numeric"],["ODD","Numeric"],["POWER","Numeric"],["ROUND","Numeric","Halves round toward positive: ROUND(-2.5) is -2."],["ROUNDDOWN","Numeric","Toward zero."],["ROUNDUP","Numeric","Away from zero."],["SQRT","Numeric"],["SUM","Numeric"],["VALUE","Numeric",'Skips characters that are not part of a number: VALUE("1,200.50 USD") is 1200.5.'],["DATEADD","Date",'The units Airtable names, except that "M" is minutes here: write "months".',!0],["DATESTR","Date"],["DATETIME_DIFF","Date",'Units as in DATEADD: "M" is minutes, write "months".',!0],["DATETIME_FORMAT","Date","moment.js tokens (YYYY, MMMM, Do, HH, A, Z, L, LL and the rest); week-of-year tokens are not read.",!0],["DATETIME_PARSE","Date","Reads the tokens DATETIME_FORMAT writes, with the separators as written. Text without a zone is local time.",!0],["DAY","Date"],["HOUR","Date"],["IS_AFTER","Date"],["IS_BEFORE","Date"],["IS_SAME","Date"],["MINUTE","Date"],["MONTH","Date"],["NOW","Date"],["SECOND","Date"],["SET_LOCALE","Date","Changes the month and weekday names DATETIME_FORMAT writes; ordinals (Do) stay English.",!0],["SET_TIMEZONE","Date","Changes what DATETIME_FORMAT writes. An unknown zone leaves the cell empty.",!0],["TIMESTR","Date"],["TONOW","Date","Calendar days from the date to today, signed.",!0],["FROMNOW","Date","Calendar days from today to the date, signed.",!0],["TODAY","Date"],["WEEKDAY","Date",'0 for Sunday; "Monday" as the second argument makes Monday 0.'],["WEEKNUM","Date",'Weeks start on Sunday, or on Monday with "Monday".'],["WORKDAY","Date",'Holidays as text ("2026-12-25, 2026-12-26") or a list of dates.'],["WORKDAY_DIFF","Date","Both days count. Holidays as in WORKDAY."],["YEAR","Date"],["ARRAYCOMPACT","Array"],["ARRAYFLATTEN","Array"],["ARRAYJOIN","Array"],["ARRAYUNIQUE","Array"],["ARRAYSLICE","Array"],["RECORD_ID","Record","The record's id; after baseFromAirtable, the Airtable record id."],["CREATED_TIME","Record","When the record was made: the row's created_at (from a server) or createdTime. baseFromAirtable still rewrites CREATED_TIME() to read a Created time field, and adds one when the table has none, so Airtable's times come over."],["LAST_MODIFIED_TIME","Record","When the record last changed: the row's updated_at or lastModifiedTime; field arguments are read as the whole record's. baseFromAirtable rewrites LAST_MODIFIED_TIME() to read a Last modified time field that watches every field, and LAST_MODIFIED_TIME({Field}) one that watches that field, and adds it when the table has none.",!0]];export function airtableFormulaSupport(){return ae.map(([t,i,e="",l])=>{const T=_.includes(t)?l?"different":"supported":"unsupported";return{name:t,group:i,status:T,note:e}})}
@@ -1,4 +1,4 @@
1
- import{CRON_PRESETS as i}from"../scheduling.js";import{primaryOf as s}from"./base-tables.js";import{listAutomationActions as n,tableFields as c}from"./automations.svelte.js";import{bm as t}from"./messages.svelte.js";export const COMPUTED_TYPES=new Set(["formula","lookup","rollup","count","button","autoNumber","createdTime","lastModifiedTime","createdBy","lastModifiedBy"]),fieldsOf=e=>e?[...c(e).values()]:[],writableFields=e=>fieldsOf(e).filter(r=>!COMPUTED_TYPES.has(String(r.fieldType??""))),TRIGGER_CHOICES=[{value:"recordCreated",key:"extras.triggerCreated"},{value:"recordUpdated",key:"extras.triggerUpdated"},{value:"recordMatches",key:"extras.triggerMatches"},{value:"formSubmitted",key:"extras.triggerForm"},{value:"button",key:"extras.triggerButton"},{value:"scheduled",key:"extras.triggerScheduled"},{value:"webhookReceived",key:"extras.triggerWebhook"}];export function newWebhookToken(){const e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),[...e].map(r=>r.toString(16).padStart(2,"0")).join("")}export function newTrigger(e,r){switch(e){case"recordUpdated":return{type:e,fields:[]};case"formSubmitted":return{type:e};case"button":return{type:e,field:fieldsOf(r).find(a=>a.fieldType==="button")?.id??""};case"scheduled":return{type:e,cron:i[3].cron};case"webhookReceived":return{type:e,token:newWebhookToken()};default:return{type:e}}}export function actionChoices(e=0){const r=[{value:"updateRecord",label:t("extras.doUpdateRecord")},{value:"createRecord",label:t("extras.doCreateRecord")},{value:"repeat",label:t("extras.doRepeat")},{value:"if",label:t("extras.doIf")},{value:"notify",label:t("extras.actionNotify")},{value:"highlight",label:t("extras.doHighlight")},{value:"email",label:t("extras.actionEmail")},{value:"chat",label:t("extras.doChat")},{value:"textMessage",label:t("extras.doText")},{value:"webhook",label:t("extras.actionWebhook")},{value:"ai",label:t("extras.doAi")},{value:"script",label:t("extras.doScript")},...n().map(a=>({value:`run:${a.id}`,label:a.label}))];return e?r.filter(a=>a.value!=="script"&&a.value!=="highlight"&&(e<2||a.value!=="if"&&a.value!=="repeat")):r}export function newAction(e,r){if(e.startsWith("run:"))return{type:"run",action:e.slice(4)};switch(e){case"updateRecord":return{type:"updateRecord",values:{}};case"createRecord":return{type:"createRecord",table:r.id,values:{}};case"highlight":return{type:"highlight",background:"#fee2e2",color:"#991b1b"};case"webhook":return{type:"webhook",url:"https://",body:""};case"email":return{type:"email",to:"",subject:"",body:""};case"chat":return{type:"chat",service:"slack",url:"https://hooks.slack.com/services/",text:""};case"textMessage":return{type:"textMessage",channel:"sms",to:"",text:""};case"repeat":return{type:"repeat",table:r.id,limit:100,actions:[]};case"if":return{type:"if",then:[],else:[]};case"ai":return{type:"ai",prompt:""};case"script":return{type:"script",code:SCRIPT_START};default:return{type:"notify",message:"",severity:"info"}}}export const SCRIPT_START=`// The record that set it off: input.config() has its fields by name.
1
+ import{CRON_PRESETS as i}from"../scheduling.js";import{primaryOf as s}from"./base-tables.js";import{listAutomationActions as n,tableFields as c,viewFilterOf as l}from"./automations.svelte.js";import{bm as r}from"./messages.svelte.js";export const COMPUTED_TYPES=new Set(["formula","lookup","rollup","count","button","autoNumber","createdTime","lastModifiedTime","createdBy","lastModifiedBy"]),fieldsOf=e=>e?[...c(e).values()]:[],writableFields=e=>fieldsOf(e).filter(t=>!COMPUTED_TYPES.has(String(t.fieldType??""))),TRIGGER_CHOICES=[{value:"recordCreated",key:"extras.triggerCreated"},{value:"recordUpdated",key:"extras.triggerUpdated"},{value:"recordMatches",key:"extras.triggerMatches"},{value:"recordEntersView",key:"extras.triggerEntersView"},{value:"formSubmitted",key:"extras.triggerForm"},{value:"button",key:"extras.triggerButton"},{value:"scheduled",key:"extras.triggerScheduled"},{value:"webhookReceived",key:"extras.triggerWebhook"}];export function newWebhookToken(){const e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),[...e].map(t=>t.toString(16).padStart(2,"0")).join("")}export function newTrigger(e,t){switch(e){case"recordUpdated":return{type:e,fields:[]};case"formSubmitted":return{type:e};case"button":return{type:e,field:fieldsOf(t).find(a=>a.fieldType==="button")?.id??""};case"scheduled":return{type:e,cron:i[3].cron};case"webhookReceived":return{type:e,token:newWebhookToken()};case"recordEntersView":return{type:e,view:(t.views??[]).find(a=>a.type!=="form"&&l(t,a.id))?.id??""};default:return{type:e}}}export function actionChoices(e=0){const t=[{value:"updateRecord",label:r("extras.doUpdateRecord")},{value:"createRecord",label:r("extras.doCreateRecord")},{value:"deleteRecord",label:r("extras.doDeleteRecord")},{value:"repeat",label:r("extras.doRepeat")},{value:"if",label:r("extras.doIf")},{value:"notify",label:r("extras.actionNotify")},{value:"highlight",label:r("extras.doHighlight")},{value:"email",label:r("extras.actionEmail")},{value:"chat",label:r("extras.doChat")},{value:"textMessage",label:r("extras.doText")},{value:"webhook",label:r("extras.actionWebhook")},{value:"ai",label:r("extras.doAi")},{value:"script",label:r("extras.doScript")},...n().map(a=>({value:`run:${a.id}`,label:a.label}))];return e?t.filter(a=>a.value!=="script"&&a.value!=="highlight"&&(e<2||a.value!=="if"&&a.value!=="repeat")):t}export function newAction(e,t){if(e.startsWith("run:"))return{type:"run",action:e.slice(4)};switch(e){case"updateRecord":return{type:"updateRecord",values:{}};case"createRecord":return{type:"createRecord",table:t.id,values:{}};case"deleteRecord":return{type:"deleteRecord"};case"highlight":return{type:"highlight",background:"#fee2e2",color:"#991b1b"};case"webhook":return{type:"webhook",url:"https://",body:""};case"email":return{type:"email",to:"",subject:"",body:""};case"chat":return{type:"chat",service:"slack",url:"https://hooks.slack.com/services/",text:""};case"textMessage":return{type:"textMessage",channel:"sms",to:"",text:""};case"repeat":return{type:"repeat",table:t.id,limit:100,actions:[]};case"if":return{type:"if",then:[],else:[]};case"ai":return{type:"ai",prompt:""};case"script":return{type:"script",code:SCRIPT_START};default:return{type:"notify",message:"",severity:"info"}}}export const SCRIPT_START=`// The record that set it off: input.config() has its fields by name.
2
2
  const config = input.config()
3
3
  console.log('Record', config.recordId)
4
4
 
@@ -9,4 +9,4 @@ console.log('Record', config.recordId)
9
9
 
10
10
  // Hand values to the next steps as {script.name}:
11
11
  // output.set('name', 'value')
12
- `,actionKey=e=>e.type==="run"?`run:${e.action}`:e.type;export function newAutomation(e){const r=fieldsOf(e),a=r.find(o=>o.id===s(e))??r[0];return{id:`auto-${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,name:t("extras.newAutomation"),enabled:!0,trigger:{type:"recordCreated"},actions:[{type:"notify",message:t("extras.newRecordMessage",{field:a?.header??t("extras.nameFallback")})}]}}
12
+ `,actionKey=e=>e.type==="run"?`run:${e.action}`:e.type;export function newAutomation(e){const t=fieldsOf(e),a=t.find(o=>o.id===s(e))??t[0];return{id:`auto-${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,name:r("extras.newAutomation"),enabled:!0,trigger:{type:"recordCreated"},actions:[{type:"notify",message:r("extras.newRecordMessage",{field:a?.header??r("extras.nameFallback")})}]}}
@@ -1 +1 @@
1
- import{cronMatches as ue}from"../scheduling.js";import{primaryOf as L,rowIdOf as m,syncAllInverses as le}from"./base-tables.js";import{newRecordId as de}from"./field-ops.js";import{registerLinkedTable as he}from"./sources.svelte.js";import{MAX_DEPTH as Z,REPEAT_MOST as pe,actionLabel as me,automationsFor as we,triggerValues as ge,webhookValues as ye,fieldValueFrom as I,fillTokens as ee,matches as V,outbound as N,runAppAction as be,tableFields as M}from"./automations.svelte.js";import{callWebhook as ke,sendChat as ve,sendEmailAction as Se,sendTextAction as Ee}from"./automation-outbound.js";import{checkedFetch as $e}from"./automation-address.js";let Oe=0;const Te=1e4,_=(w,A)=>JSON.stringify(w??null)===JSON.stringify(A??null);export function createAutomationServer(w){const A=w.now??(()=>new Date),q=w.keepRuns??200;let S=w.tables.map(e=>({...e,data:[]})),F=null,j=!1;const R=new Map,te=(e,n)=>{const t=R.get(e)??new Set;R.set(e,t),t.add(n),t.size>Te&&t.delete(t.values().next().value)},D=(e,n)=>!!R.get(e)?.delete(n),J=new WeakSet;let B=Promise.resolve();const P=[],z=new Map,K=e=>typeof w.secrets=="function"?w.secrets(e):w.secrets?.[e],Q=w.allowInternalWebhooks?null:e=>$e(e,w.resolveHost,w.fetch),y=e=>S.find(n=>n.id===e),T=e=>{if(!e.source)throw new Error(`Table ${e.name} has no source`);return e.source};function $(e,n){S=S.map(t=>t.id===e?{...t,data:n(t.data)}:t);for(const t of S)S=le(S,t.id)}function O(){return F??(F=(async()=>{for(const e of S){const n=await T(e).load({whole:!0});$(e.id,()=>n)}for(const e of S){const n=e.id;he({id:n,name:e.name,rows:()=>y(n)?.data??[],getRowId:t=>m(y(n)??e,t),primaryField:L(e),fields:e.columns.filter(t=>t.field).map(t=>({field:String(t.field),header:String(t.header??t.field),fieldType:t.fieldType,fieldProps:t.fieldProps}))})}j=!0})().catch(e=>{throw F=null,e})),F}function C(e,n,t){const i=[];for(const r of M(e).values())_(n[r.field],t[r.field])||i.push(r.id);return i}async function U(e,n,t={}){await O();const i=y(e);if(!i)throw new Error(`No table "${e}"`);const r=l=>l?t.db===!1?l:T(i).toPage(l):null,s=r(n.after),c=r(n.before);if(!s){const l=String(c?.id??"");return $(e,h=>h.filter(u=>m(i,u)!==l)),te(e,l),[]}const a=String(s.id),o=i.data.find(l=>m(i,l)===a),g={...o??{},...s},d=!!o&&!C(i,o,g).length;if(o&&(d||t.first)){if(!t.first)return[];d||$(e,v=>v.map(G=>G===o?g:G));const l=y(e).data.find(v=>m(i,v)===a)??g;if(t.first.created)return E({type:"created",table:e,record:l});const h=t.first.values?r(t.first.values):{},u=[...M(i).values()].filter(v=>v.field in h).map(v=>v.id),k=Object.fromEntries(Object.keys(h).map(v=>[v,void 0]));return u.length?E({type:"updated",table:e,record:l,before:{...l,...k},fields:u}):[]}const p=c?{...o??{},...c}:o;$(e,l=>o?l.map(h=>h===o?g:h):[...l,g]);const f=y(e).data.find(l=>m(i,l)===a);if(!p)return D(e,a)?[]:E({type:"created",table:e,record:f});const b=C(i,p,f);return b.length?E({type:"updated",table:e,record:f,before:p,fields:b}):[]}async function W(e){await O();const n=y(e);if(!n)throw new Error(`No table "${e}"`);const t=await T(n).load({whole:!0}),i=new Map(n.data.map(s=>[m(n,s),s]));$(e,()=>t);const r=[];for(const s of y(e).data){const c=i.get(m(n,s));if(!c)D(e,m(n,s))||r.push(...await E({type:"created",table:e,record:s}));else{const a=C(n,c,s);a.length&&r.push(...await E({type:"updated",table:e,record:s,before:c,fields:a}))}}return r}function ne(e,n){const t=async r=>{if(r.action==="purge"){r.id!=null&&R.get(e)?.delete(String(r.id));return}const s=r.event&&typeof r.event=="object"?r.event:null;!j&&s&&J.add(s);const c=!j||!!s&&J.has(s);if(r.action==="delete"){await U(e,{before:{id:r.id},after:null},{db:!1});return}if(r.action==="restore"){await O(),r.id!=null&&await re(e,String(r.id));return}if(!r.result){await W(e);return}await U(e,{after:r.result},c?{first:{created:r.action==="create",...r.values?{values:r.values}:{}}}:{})};return Object.assign(async r=>{try{n&&await n(r)}finally{await t(r)}},{before:()=>O()})}async function re(e,n){const t=y(e);if(!t)return;D(e,n);const i=T(t),s=(i.read?await i.read([n]):(await i.load({whole:!0})).filter(c=>m(t,c)===n))[0];s&&$(e,c=>[...c.filter(a=>m(t,a)!==n),s])}async function ie(e,n,t){await O();const i=await X(e,n);return i?E({type:"form",table:e,record:i,view:t}):[]}async function oe(e,n,t){await O();const i=await X(e,n);return i?E({type:"button",table:e,record:i,field:t}):[]}async function X(e,n){const t=y(e);if(!t)return null;let i=t.data.find(r=>m(t,r)===n);return i||(await W(e),i=y(e).data.find(r=>m(t,r)===n)),i??null}async function ae(e,n){await O();const t=[];if(!e)return t;for(const i of S)for(const r of i.automations??[])!r.enabled||r.runOn!=="server"||r.trigger.type!=="webhookReceived"||r.trigger.token!==e||t.push(await x(r,i.id,null,0,ye(n)));return t}async function se(e=A()){await O();const n=`${e.getFullYear()}-${e.getMonth()}-${e.getDate()} ${e.getHours()}:${e.getMinutes()}`,t=[];for(const i of S)for(const r of i.automations??[]){if(!r.enabled||r.runOn!=="server"||r.trigger.type!=="scheduled")continue;const s=`${i.id}:${r.id}`;if(!(z.get(s)===n||!ue(r.trigger.cron,e)))if(z.set(s,n),!r.condition)t.push(await x(r,i.id,null,0));else for(const c of y(i.id).data)V(i,r.condition,c)&&t.push(await x(r,i.id,m(i,c),0))}return t}async function E(e){const n=y(e.table);if(!n)return[];const t="depth"in e?e.depth??0:0,i=[];for(const r of we(n,e,"server"))i.push(await x(r,n.id,m(n,e.record),t));return i}function x(e,n,t,i,r=new Map){const s=B.then(()=>ce(e,n,t,i,r));return B=s.catch(()=>{}),s}async function ce(e,n,t,i,r){const s=y(n),c=t==null?null:s.data.find(o=>m(s,o)===t)??null,a={id:++Oe,automationId:e.id,name:e.name,table:s.name,record:c?String(c[L(s)]??t):null,at:A().getTime(),status:"ok",steps:[]};if(i>=Z)a.status="stopped",a.steps.push({action:"Stopped",detail:`Automations set each other off ${Z} times in a row; this one did not run, so they cannot loop.`});else{const o=[];await H(e,e.actions,n,t,i,o,a,r),Y(a);for(const g of o)g();return a}return Y(a),a}function Y(e){P.unshift(e),P.length>q&&(P.length=q),w.onRun?.(e)}async function H(e,n,t,i,r,s,c,a){for(const o of n)try{const g=y(t),d=i==null?null:g.data.find(f=>m(g,f)===i)??null;if(o.type==="if"){const f=d?V(g,o.condition,d):!o.condition?.conditions?.length;if(c.steps.push({action:"If",detail:f?"It matched: the Then steps ran":"It did not match: the Otherwise steps ran"}),!await H(e,(f?o.then:o.else)??[],t,i,r,s,c,a))return!1;continue}if(o.type==="repeat"){const f=y(o.table);if(!f)throw new Error(`No table "${o.table}"`);const b=Math.max(1,Math.min(pe,o.limit??100)),l=f.data.filter(u=>V(f,o.condition,u)).slice(0,b).map(u=>m(f,u));c.steps.push({action:"Find records",detail:`${l.length} in ${f.name}`});const h=ge(g,d,a);h.set("found",String(l.length));for(const u of l)if(!await H(e,o.actions??[],f.id,u,r,s,c,h))return!1;continue}const p=await fe(e,o,t,i,r,s,a);p&&c.steps.push(p)}catch(g){return c.status="error",c.steps.push({action:me(o),detail:"",error:g instanceof Error?g.message:String(g)}),!1}return!0}async function fe(e,n,t,i,r,s,c){const a=y(t),o=i==null?null:a.data.find(d=>m(a,d)===i)??null,g={tables:S,from:a,record:o,now:A(),values:c};switch(n.type){case"notify":{const d=ee(a,o,n.message,c);return w.notify?.({message:d,severity:n.severity??"info",automation:e.name,table:a.name,record:o}),{action:"Notice",detail:d}}case"highlight":return null;case"updateRecord":{if(!o||i==null)return{action:"Update record",detail:"No record to update"};const d=M(a),p={};for(const[u,k]of Object.entries(n.values)){const v=d.get(u);v&&(p[v.field]=I(a,v.def,k,g))}const f={...o,...p},b=Object.keys(p).filter(u=>!_(o[u],f[u]));if(!b.length)return{action:"Update record",detail:"Already set"};const l={};for(const u of b)l[u]=f[u];await T(a).update(i,l,o),$(t,u=>u.map(k=>k===o?f:k));const h=b.map(u=>[...d.values()].find(k=>k.field===u)?.id??u);return s.push(()=>E({type:"updated",table:t,record:y(t).data.find(u=>m(a,u)===i),before:o,fields:h,depth:r+1})),{action:"Update record",detail:b.map(u=>`${[...d.values()].find(k=>k.field===u)?.header??u}: ${String(f[u]??"")}`).join(", ")}}case"createRecord":{const d=y(n.table);if(!d)throw new Error(`No table "${n.table}"`);const p=M(d),f={id:de()};for(const[h,u]of Object.entries(n.values)){const k=p.get(h);k&&(f[k.field]=I(d,k.def,u,g))}if(n.linkField&&o){const h=p.get(n.linkField);h&&(f[h.field]=[m(a,o)])}const b=await T(d).insert(f),l={...f,id:String(b.id??f.id)};return $(d.id,h=>[...h,l]),s.push(()=>E({type:"created",table:d.id,record:l,depth:r+1})),{action:"Create record",detail:`${String(l[L(d)]??"")||"a record"} in ${d.name}`}}case"run":return be(e,n,a,o);case"webhook":return{action:"Webhook",detail:await ke(n,N(e,a,o,{secret:K,fetch:w.fetch,...Q?{checkUrl:Q}:{}},c))};case"email":return{action:"Email",detail:await Se(n,N(e,a,o,{},c),w.sendEmail)};case"textMessage":return{action:"Text message",detail:await Ee(n,N(e,a,o,{},c),w.sendText)};case"chat":return{action:"Message",detail:await ve(n,N(e,a,o,{secret:K,fetch:w.fetch},c))};case"ai":{if(!w.ai)throw new Error("No AI model here: give createAutomationServer an ai");const d=ee(a,o,n.prompt,c).trim();if(!d)throw new Error("The prompt is empty");const p=String(await w.ai(d)).trim();c.set("ai",p);const f=n.field?M(a).get(n.field):void 0;if(f&&o&&i!=null&&!_(o[f.field],p)){await T(a).update(i,{[f.field]:p},o);const b={...o,[f.field]:p};$(t,l=>l.map(h=>h===o?b:h)),s.push(()=>E({type:"updated",table:t,record:b,before:o,fields:[f.id],depth:r+1}))}return{action:"AI",detail:p.length>160?p.slice(0,157)+"...":p}}case"script":throw new Error("A script runs in a browser, in the page of the person who made the change: set Runs in to The browser.");default:return null}}return{prime:O,recordChanged:U,tableChanged:W,audit:ne,formSubmitted:ie,buttonPressed:oe,webhookReceived:ae,tick:se,get runs(){return P},settled:()=>B.then(()=>{}),get tables(){return S}}}
1
+ import{cronMatches as le}from"../scheduling.js";import{primaryOf as x,rowIdOf as m,syncAllInverses as ue}from"./base-tables.js";import{newRecordId as de}from"./field-ops.js";import{registerLinkedTable as he}from"./sources.svelte.js";import{MAX_DEPTH as Z,REPEAT_MOST as pe,actionLabel as me,automationsFor as we,triggerValues as ge,webhookValues as ye,fieldValueFrom as I,fillTokens as ee,matches as V,outbound as j,runAppAction as be,tableFields as M}from"./automations.svelte.js";import{callWebhook as ke,sendChat as ve,sendEmailAction as Se,sendTextAction as Ee}from"./automation-outbound.js";import{checkedFetch as $e}from"./automation-address.js";let Oe=0;const Te=1e4,_=(w,A)=>JSON.stringify(w??null)===JSON.stringify(A??null);export function createAutomationServer(w){const A=w.now??(()=>new Date),q=w.keepRuns??200;let S=w.tables.map(e=>({...e,data:[]})),R=null,D=!1;const F=new Map,te=(e,n)=>{const t=F.get(e)??new Set;F.set(e,t),t.add(n),t.size>Te&&t.delete(t.values().next().value)},B=(e,n)=>!!F.get(e)?.delete(n),J=new WeakSet;let C=Promise.resolve();const N=[],z=new Map,K=e=>typeof w.secrets=="function"?w.secrets(e):w.secrets?.[e],Q=w.allowInternalWebhooks?null:e=>$e(e,w.resolveHost,w.fetch),y=e=>S.find(n=>n.id===e),T=e=>{if(!e.source)throw new Error(`Table ${e.name} has no source`);return e.source};function $(e,n){S=S.map(t=>t.id===e?{...t,data:n(t.data)}:t);for(const t of S)S=ue(S,t.id)}function O(){return R??(R=(async()=>{for(const e of S){const n=await T(e).load({whole:!0});$(e.id,()=>n)}for(const e of S){const n=e.id;he({id:n,name:e.name,rows:()=>y(n)?.data??[],getRowId:t=>m(y(n)??e,t),primaryField:x(e),fields:e.columns.filter(t=>t.field).map(t=>({field:String(t.field),header:String(t.header??t.field),fieldType:t.fieldType,fieldProps:t.fieldProps}))})}D=!0})().catch(e=>{throw R=null,e})),R}function U(e,n,t){const i=[];for(const r of M(e).values())_(n[r.field],t[r.field])||i.push(r.id);return i}async function W(e,n,t={}){await O();const i=y(e);if(!i)throw new Error(`No table "${e}"`);const r=u=>u?t.db===!1?u:T(i).toPage(u):null,s=r(n.after),c=r(n.before);if(!s){const u=String(c?.id??"");return $(e,p=>p.filter(l=>m(i,l)!==u)),te(e,u),[]}const a=String(s.id),o=i.data.find(u=>m(i,u)===a),g={...o??{},...s},d=!!o&&!U(i,o,g).length;if(o&&(d||t.first)){if(!t.first)return[];d||$(e,v=>v.map(G=>G===o?g:G));const u=y(e).data.find(v=>m(i,v)===a)??g;if(t.first.created)return E({type:"created",table:e,record:u});const p=t.first.values?r(t.first.values):{},l=[...M(i).values()].filter(v=>v.field in p).map(v=>v.id),k=Object.fromEntries(Object.keys(p).map(v=>[v,void 0]));return l.length?E({type:"updated",table:e,record:u,before:{...u,...k},fields:l}):[]}const h=c?{...o??{},...c}:o;$(e,u=>o?u.map(p=>p===o?g:p):[...u,g]);const f=y(e).data.find(u=>m(i,u)===a);if(!h)return B(e,a)?[]:E({type:"created",table:e,record:f});const b=U(i,h,f);return b.length?E({type:"updated",table:e,record:f,before:h,fields:b}):[]}async function H(e){await O();const n=y(e);if(!n)throw new Error(`No table "${e}"`);const t=await T(n).load({whole:!0}),i=new Map(n.data.map(s=>[m(n,s),s]));$(e,()=>t);const r=[];for(const s of y(e).data){const c=i.get(m(n,s));if(!c)B(e,m(n,s))||r.push(...await E({type:"created",table:e,record:s}));else{const a=U(n,c,s);a.length&&r.push(...await E({type:"updated",table:e,record:s,before:c,fields:a}))}}return r}function ne(e,n){const t=async r=>{if(r.action==="purge"){r.id!=null&&F.get(e)?.delete(String(r.id));return}const s=r.event&&typeof r.event=="object"?r.event:null;!D&&s&&J.add(s);const c=!D||!!s&&J.has(s);if(r.action==="delete"){await W(e,{before:{id:r.id},after:null},{db:!1});return}if(r.action==="restore"){await O(),r.id!=null&&await re(e,String(r.id));return}if(!r.result){await H(e);return}await W(e,{after:r.result},c?{first:{created:r.action==="create",...r.values?{values:r.values}:{}}}:{})};return Object.assign(async r=>{try{n&&await n(r)}finally{await t(r)}},{before:()=>O()})}async function re(e,n){const t=y(e);if(!t)return;B(e,n);const i=T(t),s=(i.read?await i.read([n]):(await i.load({whole:!0})).filter(c=>m(t,c)===n))[0];s&&$(e,c=>[...c.filter(a=>m(t,a)!==n),s])}async function ie(e,n,t){await O();const i=await X(e,n);return i?E({type:"form",table:e,record:i,view:t}):[]}async function oe(e,n,t){await O();const i=await X(e,n);return i?E({type:"button",table:e,record:i,field:t}):[]}async function X(e,n){const t=y(e);if(!t)return null;let i=t.data.find(r=>m(t,r)===n);return i||(await H(e),i=y(e).data.find(r=>m(t,r)===n)),i??null}async function ae(e,n){await O();const t=[];if(!e)return t;for(const i of S)for(const r of i.automations??[])!r.enabled||r.runOn!=="server"||r.trigger.type!=="webhookReceived"||r.trigger.token!==e||t.push(await P(r,i.id,null,0,ye(n)));return t}async function se(e=A()){await O();const n=`${e.getFullYear()}-${e.getMonth()}-${e.getDate()} ${e.getHours()}:${e.getMinutes()}`,t=[];for(const i of S)for(const r of i.automations??[]){if(!r.enabled||r.runOn!=="server"||r.trigger.type!=="scheduled")continue;const s=`${i.id}:${r.id}`;if(!(z.get(s)===n||!le(r.trigger.cron,e)))if(z.set(s,n),!r.condition)t.push(await P(r,i.id,null,0));else for(const c of y(i.id).data)V(i,r.condition,c)&&t.push(await P(r,i.id,m(i,c),0))}return t}async function E(e){const n=y(e.table);if(!n)return[];const t="depth"in e?e.depth??0:0,i=[];for(const r of we(n,e,"server"))i.push(await P(r,n.id,m(n,e.record),t));return i}function P(e,n,t,i,r=new Map){const s=C.then(()=>ce(e,n,t,i,r));return C=s.catch(()=>{}),s}async function ce(e,n,t,i,r){const s=y(n),c=t==null?null:s.data.find(o=>m(s,o)===t)??null,a={id:++Oe,automationId:e.id,name:e.name,table:s.name,record:c?String(c[x(s)]??t):null,at:A().getTime(),status:"ok",steps:[]};if(i>=Z)a.status="stopped",a.steps.push({action:"Stopped",detail:`Automations set each other off ${Z} times in a row; this one did not run, so they cannot loop.`});else{const o=[];await L(e,e.actions,n,t,i,o,a,r),Y(a);for(const g of o)g();return a}return Y(a),a}function Y(e){N.unshift(e),N.length>q&&(N.length=q),w.onRun?.(e)}async function L(e,n,t,i,r,s,c,a){for(const o of n)try{const g=y(t),d=i==null?null:g.data.find(f=>m(g,f)===i)??null;if(o.type==="if"){const f=d?V(g,o.condition,d):!o.condition?.conditions?.length;if(c.steps.push({action:"If",detail:f?"It matched: the Then steps ran":"It did not match: the Otherwise steps ran"}),!await L(e,(f?o.then:o.else)??[],t,i,r,s,c,a))return!1;continue}if(o.type==="repeat"){const f=y(o.table);if(!f)throw new Error(`No table "${o.table}"`);const b=Math.max(1,Math.min(pe,o.limit??100)),u=f.data.filter(l=>V(f,o.condition,l)).slice(0,b).map(l=>m(f,l));c.steps.push({action:"Find records",detail:`${u.length} in ${f.name}`});const p=ge(g,d,a);p.set("found",String(u.length));for(const l of u)if(!await L(e,o.actions??[],f.id,l,r,s,c,p))return!1;continue}const h=await fe(e,o,t,i,r,s,a);h&&c.steps.push(h)}catch(g){return c.status="error",c.steps.push({action:me(o),detail:"",error:g instanceof Error?g.message:String(g)}),!1}return!0}async function fe(e,n,t,i,r,s,c){const a=y(t),o=i==null?null:a.data.find(d=>m(a,d)===i)??null,g={tables:S,from:a,record:o,now:A(),values:c};switch(n.type){case"notify":{const d=ee(a,o,n.message,c);return w.notify?.({message:d,severity:n.severity??"info",automation:e.name,table:a.name,record:o}),{action:"Notice",detail:d}}case"highlight":return null;case"updateRecord":{if(!o||i==null)return{action:"Update record",detail:"No record to update"};const d=M(a),h={};for(const[l,k]of Object.entries(n.values)){const v=d.get(l);v&&(h[v.field]=I(a,v.def,k,g))}const f={...o,...h},b=Object.keys(h).filter(l=>!_(o[l],f[l]));if(!b.length)return{action:"Update record",detail:"Already set"};const u={};for(const l of b)u[l]=f[l];await T(a).update(i,u,o),$(t,l=>l.map(k=>k===o?f:k));const p=b.map(l=>[...d.values()].find(k=>k.field===l)?.id??l);return s.push(()=>E({type:"updated",table:t,record:y(t).data.find(l=>m(a,l)===i),before:o,fields:p,depth:r+1})),{action:"Update record",detail:b.map(l=>`${[...d.values()].find(k=>k.field===l)?.header??l}: ${String(f[l]??"")}`).join(", ")}}case"deleteRecord":return!o||i==null?{action:"Delete record",detail:"No record to delete"}:(await T(a).remove(i,o),$(t,d=>d.filter(h=>h!==o)),{action:"Delete record",detail:String(o[x(a)]??"")||"a record"});case"createRecord":{const d=y(n.table);if(!d)throw new Error(`No table "${n.table}"`);const h=M(d),f={id:de()};for(const[p,l]of Object.entries(n.values)){const k=h.get(p);k&&(f[k.field]=I(d,k.def,l,g))}if(n.linkField&&o){const p=h.get(n.linkField);p&&(f[p.field]=[m(a,o)])}const b=await T(d).insert(f),u={...f,id:String(b.id??f.id)};return $(d.id,p=>[...p,u]),s.push(()=>E({type:"created",table:d.id,record:u,depth:r+1})),{action:"Create record",detail:`${String(u[x(d)]??"")||"a record"} in ${d.name}`}}case"run":return be(e,n,a,o);case"webhook":return{action:"Webhook",detail:await ke(n,j(e,a,o,{secret:K,fetch:w.fetch,...Q?{checkUrl:Q}:{}},c))};case"email":return{action:"Email",detail:await Se(n,j(e,a,o,{},c),w.sendEmail)};case"textMessage":return{action:"Text message",detail:await Ee(n,j(e,a,o,{},c),w.sendText)};case"chat":return{action:"Message",detail:await ve(n,j(e,a,o,{secret:K,fetch:w.fetch},c))};case"ai":{if(!w.ai)throw new Error("No AI model here: give createAutomationServer an ai");const d=ee(a,o,n.prompt,c).trim();if(!d)throw new Error("The prompt is empty");const h=String(await w.ai(d)).trim();c.set("ai",h);const f=n.field?M(a).get(n.field):void 0;if(f&&o&&i!=null&&!_(o[f.field],h)){await T(a).update(i,{[f.field]:h},o);const b={...o,[f.field]:h};$(t,u=>u.map(p=>p===o?b:p)),s.push(()=>E({type:"updated",table:t,record:b,before:o,fields:[f.id],depth:r+1}))}return{action:"AI",detail:h.length>160?h.slice(0,157)+"...":h}}case"script":throw new Error("A script runs in a browser, in the page of the person who made the change: set Runs in to The browser.");default:return null}}return{prime:O,recordChanged:W,tableChanged:H,audit:ne,formSubmitted:ie,buttonPressed:oe,webhookReceived:ae,tick:se,get runs(){return N},settled:()=>C.then(()=>{}),get tables(){return S}}}
@@ -19,6 +19,15 @@ export type AutomationTrigger =
19
19
  | {
20
20
  type: 'recordMatches';
21
21
  }
22
+ /**
23
+ * A record starts showing in a view: it matches the view's filter now and
24
+ * did not before the change (or it was just made). The filter is read as
25
+ * the view has it when the record changes, so the trigger follows the view.
26
+ */
27
+ | {
28
+ type: 'recordEntersView';
29
+ view: string;
30
+ }
22
31
  /** A form view sends a record; with `view`, only that form. */
23
32
  | {
24
33
  type: 'formSubmitted';
@@ -49,6 +58,10 @@ export type AutomationAction =
49
58
  type: 'updateRecord';
50
59
  values: Record<string, unknown>;
51
60
  }
61
+ /** Delete the record that set it off (in "Find records", the found one): to the base's trash where it has one. */
62
+ | {
63
+ type: 'deleteRecord';
64
+ }
52
65
  /** Add a record to a table; `linkField` there links it to the record that set it off. */
53
66
  | {
54
67
  type: 'createRecord';
@@ -181,6 +194,8 @@ export declare function tableFields(t: BaseTable): Map<string, FieldColumn>;
181
194
  export type RunValues = Map<string, string>;
182
195
  /** `{Field name}` tokens of a template, filled from a record (and the run's `values`). A run with no record says so: the token is not for reading. */
183
196
  export declare function fillTokens(t: BaseTable, record: Row | null, template: string, values?: RunValues): string;
197
+ /** The filter of a table's view, when it has one a record can be tested against. */
198
+ export declare function viewFilterOf(t: BaseTable, viewId: string | undefined): FieldFilter | null;
184
199
  /** Whether a record matches a condition (no condition matches every record). */
185
200
  export declare function matches(t: BaseTable, condition: FieldFilter | undefined, record: Row): boolean;
186
201
  /** What a value written in an action becomes in a field of `t`. */
@@ -242,6 +257,8 @@ export type AutomationRunnerOptions = {
242
257
  read(tableId: string, id: string): Promise<Row | null>;
243
258
  byName(tableId: string, name: string): Promise<string | null>;
244
259
  update(tableId: string, id: string, patch: Row, before: Row): Promise<void>;
260
+ /** Take a record out of a table read from a server ("Delete record"). */
261
+ remove?(tableId: string, id: string, before: Row): Promise<void>;
245
262
  each(tableId: string, condition: unknown, run: (row: Row) => Promise<void>): Promise<void>;
246
263
  first(tableId: string, count: number): Promise<Row[]>;
247
264
  };
@@ -1 +1 @@
1
- import{toast}from"@svgrid/grid";import{createScheduler}from"../scheduling.js";import{colId,primaryOf,rowIdOf,syncAllInverses}from"./base-tables.js";import{compileFieldFilter,describeFieldFilter}from"./filter-model.js";import{fieldPropsOf,fillFieldColumn}from"./registry.svelte.js";import{noteChange}from"./activity.svelte.js";import{getCurrentUser,getFieldUsers}from"./sources.svelte.js";import{newRecordId}from"./field-ops.js";import{fieldText,fieldValue,linkNames}from"./base-alerts.js";import{callWebhook,sendChat,sendEmailAction,sendTextAction}from"./automation-outbound.js";import{runScript}from"./automation-script.js";import{bm}from"./messages.svelte.js";import{cronWords}from"./cron-words.js";const appActions=new Map;export function registerAutomationAction(id,action){appActions.set(id,action)}export function listAutomationActions(){return[...appActions].map(([id,a])=>({id,label:a.label}))}const readers=new WeakMap;export function tableFields(t){const hit=readers.get(t.columns);if(hit)return hit;const all=t.columns.map(d=>({...d,id:colId(d)}));const map=new Map;for(const d of t.columns){if(d.field==null)continue;const def=fillFieldColumn(d,all);map.set(colId(d),{id:colId(d),field:String(d.field),header:String(d.header??d.field),fieldType:d.fieldType,def,visible:true})}readers.set(t.columns,map);return map}const byName=(t,name)=>{const lower=name.trim().toLowerCase();for(const c of tableFields(t).values()){if(c.header.trim().toLowerCase()===lower||c.field.toLowerCase()===lower||c.id.toLowerCase()===lower)return c}return void 0};export function fillTokens(t,record,template,values){return template.replace(/\{([^{}\n]+)\}/g,(m,name)=>{const given=values?.get(name.trim().toLowerCase());if(given!==void 0)return given;const c=byName(t,name);return!c?m:record?fieldText(c,record):bm("extras.noRecordValue")})}export function matches(t,condition,record){if(!condition)return true;const fields=tableFields(t);const test=compileFieldFilter(condition,(row,id)=>{const c=fields.get(id);return c?fieldValue(c,row):row[id]},linkNames);return test?test(record):true}function stampModifiedTime(t,row,changedIds,at){for(const d of t.columns){if(d.fieldType!=="lastModifiedTime"||d.field==null||changedIds.includes(colId(d)))continue;const p=fieldPropsOf(d);if(p.watch==="specific"&&!changedIds.some(id=>(p.watchFields??[]).includes(id)))continue;row[String(d.field)]=at.toISOString()}}const DAY=864e5;const isoDay=d=>`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,"0")}-${String(d.getDate()).padStart(2,"0")}`;export function fieldValueFrom(t,def,spec,ctx){const type=def.fieldType;if(typeof spec!=="string")return spec;const raw=spec.includes("{record}")?spec:fillTokens(ctx.from,ctx.record,spec,ctx.values);const text=raw.trim();if(text==="")return type==="checkbox"?false:type==="multiSelect"||type==="link"||type==="attachment"?[]:null;switch(type){case"checkbox":return/^(true|yes|1|checked|on)$/i.test(text);case"number":case"rating":case"duration":case"currency":case"percent":{const n=Number(text.replace(/[^0-9.+-eE]/g,""));return Number.isFinite(n)?text.endsWith("%")?n/100:n:null}case"multiSelect":return text.split(/\s*,\s*/).filter(Boolean);case"user":{const found=getFieldUsers().find(u=>u.id===text||u.name.toLocaleLowerCase()===text.toLocaleLowerCase());return found?found.id:text}case"date":{const m=/^(today|now)\s*(?:([+-])\s*(\d+))?$/i.exec(text);if(!m)return text;const shift=m[2]?(m[2]==="-"?-1:1)*Number(m[3])*DAY:0;const at=new Date(ctx.now.getTime()+shift);return m[1].toLowerCase()==="now"||def.fieldProps?.time?at.toISOString():isoDay(at)}case"link":{const target=ctx.tables.find(x=>x.id===def.fieldProps?.table);const out=[];for(const part of text.split(/\s*,\s*/)){if(part==="{record}"){if(ctx.record&&ctx.from.id===target?.id)out.push(rowIdOf(ctx.from,ctx.record));continue}const name=fillTokens(ctx.from,ctx.record,part,ctx.values).toLocaleLowerCase();const named=ctx.named?.get(name);if(named){out.push(named);continue}const hit=target?.data.find(r=>String(r?.[primaryOf(target)]??"").toLocaleLowerCase()===name);if(hit&&target)out.push(rowIdOf(target,hit))}return def.fieldProps?.multiple===false?out.slice(0,1):out}default:return raw}}export const MAX_DEPTH=4;export function pressedValues(){const me=getCurrentUser();const out=new Map;out.set("pressed.name",me?.name??"");out.set("pressed.email",me?.email??"");out.set("pressed.id",me?.id??"");return out}export const REPEAT_MOST=1e3;const SCRIPT_ROWS=5e3;const READ_AS_TEXT=new Set(["checkbox","number","rating","duration","currency","percent","multiSelect","user","date","link"]);export function scriptRecord(t,r){const values={};const texts={};let name="";for(const c of tableFields(t).values()){let v=r[c.field]??null;try{v=JSON.parse(JSON.stringify(v))}catch{v=null}values[c.header]=v;texts[c.header]=fieldText(c,r);if(c.field===primaryOf(t))name=texts[c.header]}return{id:rowIdOf(t,r),name,values,texts}}export function scriptInput(t,rec,values){const out={};if(rec){out.recordId=rowIdOf(t,rec);for(const c of tableFields(t).values())out[c.header]=fieldText(c,rec)}for(const[k,v]of values)out[k]=v;return out}export function webhookValues(body){const out=new Map;const walk=(v,path,depth)=>{if(out.size>=200)return;if(v!==null&&typeof v==="object"&&depth<5){for(const[k,x]of Object.entries(v).slice(0,100))walk(x,`${path}.${k.toLowerCase()}`,depth+1);if(path!=="webhook")out.set(path,JSON.stringify(v));return}out.set(path,v==null?"":typeof v==="string"?v:JSON.stringify(v))};walk(body,"webhook",0);out.set("webhook",typeof body==="string"?body:JSON.stringify(body??null));return out}export function triggerValues(t,rec,values){const out=new Map(values);if(rec)for(const c of tableFields(t).values())out.set(`trigger.${c.header.trim().toLowerCase()}`,fieldText(c,rec));return out}export function allActions(list){const out=[];for(const x of list){out.push(x);if(x.type==="if")out.push(...allActions(x.then??[]),...allActions(x.else??[]));if(x.type==="repeat")out.push(...allActions(x.actions??[]))}return out}const SHOW_BACKLOG=20;const CARRY_MOST=5e3;const FREE_EVERY=4096;let runSeq=0;export function createAutomationRunner(options){const now=options.now??(()=>new Date);let runs=$state.raw([]);let scheduler=null;let chain=Promise.resolve();let waiting=[];let head=0;let draining=false;let burst={done:0,total:0,at:0,told:0};let backlog=$state.raw(null);let measured=null;const record=run=>runs=[run,...runs].slice(0,100);const automationsOf=t=>(t.automations??[]).filter(a=>a.enabled&&a.runOn!=="server");const tableOf=id=>options.getTables()?.find(t=>t.id===id);const carried=new Map;const carriedFor=new Map;const carry=(key,row)=>{carried.set(key,row);carriedFor.set(key,(carriedFor.get(key)??0)+1)};const letGo=key=>{const left=(carriedFor.get(key)??1)-1;if(left>0)return void carriedFor.set(key,left);carriedFor.delete(key);carried.delete(key)};const recordNow=async(t,id)=>{const own=tableOf(t.id)??t;if(!own.source?.server)return own.data.find(r=>r&&rowIdOf(own,r)===id)??null;return carried.get(`${t.id}:${id}`)??await options.server?.read(t.id,id)??null};async function namesIn(target,values,ctx){const named=new Map;const fields=tableFields(target);for(const[id,spec]of Object.entries(values)){const def=fields.get(id)?.def;if(def?.fieldType!=="link"||typeof spec!=="string")continue;const to=(options.getTables()??[]).find(x=>x.id===def.fieldProps?.table);if(!to?.source?.server)continue;for(const part of spec.split(/\s*,\s*/)){const name=fillTokens(ctx.from,ctx.record,part);const hit=part==="{record}"?null:await options.server?.byName(to.id,name);if(hit)named.set(name.toLocaleLowerCase(),hit)}}return named}const setOff=(t,e)=>automationsFor(t,e,"browser");function handle(e){const t=tableOf(e.table);if(!t)return chain;const list=setOff(t,e);const depth="depth"in e?e.depth??0:0;const recordId=rowIdOf(t,e.record);for(const a of list){if(t.source?.server&&waiting.length-head<CARRY_MOST)carry(`${t.id}:${recordId}`,e.record);if(!draining&&head===waiting.length)burst={done:0,total:0,at:Date.now(),told:0};burst.total+=1;waiting.push({a,tableId:t.id,recordId,depth})}return list.length?drain():chain}function tell(){const clock=Date.now();if(burst.total<SHOW_BACKLOG||clock-burst.told<250)return;burst.told=clock;const seconds=(clock-burst.at)/1e3;if(burst.done>=SHOW_BACKLOG&&seconds>0)measured=burst.done/seconds;backlog={done:burst.done,total:burst.total,perSecond:burst.done>=SHOW_BACKLOG?measured:null}}function endBurst(left){const shown=backlog!=null||burst.total>=SHOW_BACKLOG;backlog=null;if(shown)options.onBurstEnd?.({done:burst.total-left,total:burst.total,left})}function drain(){if(draining)return chain;draining=true;tell();chain=chain.then(async()=>{let breath=Date.now();for(;;){if(head>=waiting.length){if(burst.total<SHOW_BACKLOG)break;await new Promise(r=>setTimeout(r,200));if(head>=waiting.length)break;continue}if(Date.now()-breath>40){await new Promise(r=>setTimeout(r));breath=Date.now();continue}const w=waiting[head];head+=1;if(head>=FREE_EVERY){waiting=waiting.slice(head);head=0}try{await runOne(w.a,w.tableId,w.recordId,w.depth)}catch(e){record({id:++runSeq,automationId:w.a.id,name:w.a.name,table:tableOf(w.tableId)?.name??w.tableId,record:w.recordId,at:now().getTime(),status:"error",steps:[{action:w.a.name,detail:"",error:e instanceof Error?e.message:String(e)}]})}if(w.recordId!=null)letGo(`${w.tableId}:${w.recordId}`);burst.done+=1;tell()}waiting=[];head=0;draining=false;endBurst(0)});return chain}function stopRuns(){const left=waiting.length-head;if(!left)return 0;for(let i=head;i<waiting.length;i++){const w=waiting[i];if(w.recordId!=null)letGo(`${w.tableId}:${w.recordId}`)}waiting=[];head=0;endBurst(left);burst={done:0,total:0,at:Date.now(),told:0};return left}async function runOne(a,tableId,recordId,depth){const t=tableOf(tableId);if(!t)return;const rec=recordId==null?null:await recordNow(t,recordId);const run={id:++runSeq,automationId:a.id,name:a.name,table:t.name,record:rec?String(rec[primaryOf(t)]??recordId):null,at:now().getTime(),status:"ok",steps:[]};if(depth>=MAX_DEPTH){run.status="stopped";run.steps.push({action:bm("extras.stepStopped"),detail:bm("extras.stepLoop",{max:MAX_DEPTH})});record(run);return}await runList(a,a.actions,tableId,recordId,depth,run,a.trigger.type==="button"?pressedValues():new Map);record(run)}async function runList(a,list,tableId,recordId,depth,run,values){for(const action of list){try{if(action.type==="if"){const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;const yes=!!t&&(rec?matches(t,action.condition,rec):!action.condition?.conditions?.length);run.steps.push({action:bm("extras.stepIf"),detail:bm(yes?"extras.stepIfThen":"extras.stepIfElse")});if(!await runList(a,(yes?action.then:action.else)??[],tableId,recordId,depth,run,values))return false;continue}if(action.type==="repeat"){if(!await runRepeat(a,action,tableId,recordId,depth,run,values))return false;continue}const step=await act(a,action,tableId,recordId,depth,values);if(step)run.steps.push(step)}catch(e){run.status="error";run.steps.push({action:actionLabel(action),detail:"",error:e instanceof Error?e.message:String(e)});return false}}return true}async function runRepeat(a,action,tableId,recordId,depth,run,values){const target=tableOf(action.table);if(!target)throw new Error(bm("extras.noTable",{table:action.table}));const most=Math.max(1,Math.min(REPEAT_MOST,action.limit??100));const ids=[];if(target.source?.server){await options.server?.each(target.id,action.condition,async r=>{if(ids.length>=most)return;const id=rowIdOf(target,r);carry(`${target.id}:${id}`,r);ids.push(id)})}else{for(const r of target.data){if(ids.length>=most)break;if(r&&matches(target,action.condition,r))ids.push(rowIdOf(target,r))}}run.steps.push({action:bm("extras.stepFound"),detail:bm("extras.foundIn",{count:ids.length,table:target.name})});const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;const inner=t?triggerValues(t,rec,values):new Map(values);inner.set("found",String(ids.length));try{for(const id of ids)if(!await runList(a,action.actions??[],target.id,id,depth,run,inner))return false}finally{if(target.source?.server)for(const id of ids)letGo(`${target.id}:${id}`)}return true}async function writeRecord(a,t,recordId,rec,patch,depth,at){const fields=tableFields(t);const before={...rec};const after={...rec,...patch};const changed=Object.keys(patch).filter(f=>JSON.stringify(before[f]??null)!==JSON.stringify(after[f]??null));if(!changed.length)return{changed,after};const changedIds=changed.map(f=>[...fields.values()].find(c=>c.field===f)?.id??f);stampModifiedTime(t,after,changedIds,at);if(t.source?.server){carried.set(`${t.id}:${recordId}`,after);await options.server?.update(t.id,recordId,Object.fromEntries(Object.keys(after).filter(k=>after[k]!==before[k]).map(k=>[k,after[k]])),before)}else{const tables=options.getTables()??[];let next=tables.map(x=>x.id===t.id?{...x,data:x.data.map(r=>r&&rowIdOf(t,r)===recordId?after:r)}:x);next=syncAllInverses(next,t.id);options.apply(next,depth+1,t.id)}changed.forEach((f,i)=>noteChange({base:options.scope,tableId:t.id},recordId,changedIds[i],after[f],a.name));void handle({type:"updated",table:t.id,record:after,before,fields:changedIds,depth:depth+1});return{changed,after}}function addRecord(target,row,depth){const tables=options.getTables()??[];let next=tables.map(x=>x.id===target.id?{...x,data:[...x.data,row]}:x);next=syncAllInverses(next,target.id);options.apply(next,depth+1,target.id);void handle({type:"created",table:target.id,record:row,depth:depth+1})}function pageBridge(a,depth){const named=name=>{const t=(options.getTables()??[]).find(x=>x.name.trim().toLowerCase()===name.trim().toLowerCase());if(!t)throw new Error(bm("extras.noTable",{table:name}));return t};const rowsOf=async t=>{if(!t.source?.server)return t.data.filter(Boolean);const out=[];await options.server?.each(t.id,void 0,async r=>{if(out.length<SCRIPT_ROWS)out.push(r)});return out};const patchOf=(t,given)=>{const patch={};for(const[name,v]of Object.entries(given??{})){const c=byName(t,name);if(!c)throw new Error(bm("extras.noField",{field:name}));const type=String(c.fieldType??"");const text=typeof v==="string"?v:v&&typeof v==="object"&&!Array.isArray(v)&&"name"in v?String(v.name):null;patch[c.field]=text!==null&&READ_AS_TEXT.has(type)?fieldValueFrom(t,c.def,text.replace(/[{}]/g,""),{tables:options.getTables()??[],from:t,record:null,now:now()}):v}return patch};return{tables:()=>(options.getTables()??[]).map(t=>t.name),select:async name=>{const t=named(name);return(await rowsOf(t)).map(r=>scriptRecord(t,r))},update:async(name,id,given)=>{const t=named(name);const rec=await recordNow(t,id);if(!rec)throw new Error(bm("extras.noRecordId",{id}));await writeRecord(a,t,id,rec,patchOf(t,given),depth,now())},create:async(name,given)=>{const t=named(name);const row={id:newRecordId(),...patchOf(t,given)};addRecord(t,row,depth);return String(row.id)},remove:async(name,id)=>{const t=named(name);const tables=options.getTables()??[];options.apply(tables.map(x=>x.id===t.id?{...x,data:x.data.filter(r=>!r||rowIdOf(t,r)!==id)}:x),depth+1,t.id)}}}async function act(a,action,tableId,recordId,depth,values){const tables=options.getTables()??[];const t=tables.find(x=>x.id===tableId);const rec=recordId==null?null:await recordNow(t,recordId);const ctx={tables,from:t,record:rec,now:now(),values};switch(action.type){case"notify":{const message=fillTokens(t,rec,action.message,values);const sev=action.severity??"info";toast[sev](message);return{action:bm("extras.stepNotice"),detail:message}}case"highlight":return null;case"updateRecord":{if(!rec||recordId==null)return{action:bm("extras.actionUpdateRecord"),detail:bm("extras.noRecordToUpdate")};const fields=tableFields(t);const patch={};ctx.named=await namesIn(t,action.values,ctx);for(const[id,spec]of Object.entries(action.values)){const c=fields.get(id);if(c)patch[c.field]=fieldValueFrom(t,c.def,spec,ctx)}const{changed,after}=await writeRecord(a,t,recordId,rec,patch,depth,ctx.now);if(!changed.length)return{action:bm("extras.actionUpdateRecord"),detail:bm("extras.alreadySet")};return{action:bm("extras.actionUpdateRecord"),detail:changed.map(f=>said([...fields.values()].find(c=>c.field===f),f,after)).join(", ")}}case"createRecord":{const target=tables.find(x=>x.id===action.table);if(!target)throw new Error(bm("extras.noTable",{table:action.table}));const fields=tableFields(target);const row={id:newRecordId()};ctx.named=await namesIn(target,action.values,ctx);for(const[id,spec]of Object.entries(action.values)){const c=fields.get(id);if(c)row[c.field]=fieldValueFrom(target,c.def,spec,ctx)}if(action.linkField&&rec){const c=fields.get(action.linkField);if(c)row[c.field]=[rowIdOf(t,rec)]}addRecord(target,row,depth);const name=String(row[primaryOf(target)]??"")||bm("extras.aRecord");return{action:bm("extras.actionCreateRecord"),detail:bm("extras.createdIn",{name,table:target.name})}}case"run":return runAppAction(a,action,t,rec);case"webhook":return{action:bm("extras.stepWebhook"),detail:await callWebhook(action,outbound(a,t,rec,{},values))};case"email":return{action:bm("extras.stepEmail"),detail:await sendEmailAction(action,outbound(a,t,rec,{},values),void 0)};case"chat":return{action:bm("extras.stepChat"),detail:await sendChat(action,outbound(a,t,rec,{},values))};case"textMessage":return{action:bm("extras.stepText"),detail:await sendTextAction(action,outbound(a,t,rec,{},values),void 0)};case"ai":{if(!options.ai)throw new Error(bm("extras.noAi"));const prompt=fillTokens(t,rec,action.prompt,values).trim();if(!prompt)throw new Error(bm("extras.aiNoPrompt"));const answer=String(await options.ai(prompt)).trim();values.set("ai",answer);const c=action.field?tableFields(t).get(action.field):void 0;if(c&&rec&&recordId!=null)await writeRecord(a,t,recordId,rec,{[c.field]:answer},depth,ctx.now);return{action:bm("extras.stepAi"),detail:answer.length>160?answer.slice(0,157)+"...":answer}}case"script":{const result=await runScript(action.code,{input:scriptInput(t,rec,values),bridge:pageBridge(a,depth)});for(const[k,v]of Object.entries(result.output))values.set(`script.${k.toLowerCase()}`,typeof v==="string"?v:JSON.stringify(v));if(!result.ok)throw new Error(result.error??bm("extras.scriptFailed"));return{action:bm("extras.stepScript"),detail:result.logs.slice(-3).join(" | ")||bm("extras.stepDone")}}default:return null}}function schedule(){scheduler?.stop();scheduler=null;const list=options.getTables()??[];const due=[];for(const t of list)for(const a of automationsOf(t))if(a.trigger.type==="scheduled")due.push({id:`${t.id}:${a.id}`,cron:a.trigger.cron,table:t.id,automation:a});if(!due.length)return;scheduler=createScheduler({schedules:due,now,onFire:s=>void runScheduled(s.id)});scheduler.start()}function runScheduled(key){const[tableId,automationId]=key.split(":");const t=tableOf(tableId);const a=t?.automations?.find(x=>x.id===automationId);if(!t||!a)return chain;if(!a.condition)chain=chain.then(()=>runOne(a,t.id,null,0));else if(t.source?.server){chain=chain.then(()=>options.server?.each(t.id,a.condition,async r=>{const key2=`${t.id}:${rowIdOf(t,r)}`;carry(key2,r);await runOne(a,t.id,rowIdOf(t,r),0);letGo(key2)}))}else for(const r of t.data)if(r&&matches(t,a.condition,r))chain=chain.then(()=>runOne(a,t.id,rowIdOf(t,r),0));return chain}return{handle,stopRuns,get backlog(){return backlog},get waiting(){return waiting.length-head},get perSecond(){return measured},schedule,runScheduled,firstRecords:async(tableId,count)=>await options.server?.first(tableId,count)??[],runNow:(a,tableId,recordId)=>chain=chain.then(async()=>{const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;if(t&&rec&&a.condition&&!matches(t,a.condition,rec)){record({id:++runSeq,automationId:a.id,name:a.name,table:t.name,record:String(rec[primaryOf(t)]??recordId),at:now().getTime(),status:"stopped",steps:[{action:bm("extras.stepNotRun"),detail:bm("extras.stepNoMatch")}]});return}return runOne(a,tableId,recordId,0)}),get runs(){return runs},clearRuns:()=>runs=[],settled:()=>chain,stop:()=>scheduler?.stop()}}function said(c,field,record){if(!c)return bm("extras.saidValue",{field,value:String(record[field]??"")});if(c.fieldType==="checkbox")return bm(record[c.field]?"extras.saidChecked":"extras.saidUnchecked",{field:c.header});return bm("extras.saidValue",{field:c.header,value:fieldText(c,record)||bm("extras.saidEmpty")})}export function automationsFor(t,e,side){return(t.automations??[]).filter(a=>{if(!a.enabled||a.runOn==="server"!==(side==="server"))return false;const tr=a.trigger;switch(tr.type){case"recordCreated":return e.type==="created"&&matches(t,a.condition,e.record);case"recordUpdated":return e.type==="updated"&&(!tr.fields?.length||tr.fields.some(f=>e.fields.includes(f)))&&matches(t,a.condition,e.record);case"recordMatches":if(!a.condition)return false;if(e.type==="created")return matches(t,a.condition,e.record);if(e.type==="updated")return matches(t,a.condition,e.record)&&!matches(t,a.condition,e.before);return false;case"formSubmitted":return e.type==="form"&&(!tr.view||tr.view===e.view)&&matches(t,a.condition,e.record);case"button":return e.type==="button"&&e.field===tr.field&&matches(t,a.condition,e.record);default:return false}})}export function outbound(a,t,rec,extra={},values){return{automation:a.name,table:t.name,record:rec,fill:template=>fillTokens(t,rec,template,values),fields:()=>{const out={};if(rec)for(const c of tableFields(t).values())out[c.header]=c.fieldType==="checkbox"?String(!!rec[c.field]):fieldText(c,rec);return out},...extra}}export async function runAppAction(a,action,t,rec){const app=appActions.get(action.action);if(!app)throw new Error(bm("extras.noAction",{action:action.action}));const out=await app.run({automation:a,table:t,record:rec,text:name=>fillTokens(t,rec,`{${name}}`),options:action.options??{}});return{action:app.label,detail:typeof out==="string"?out:bm("extras.stepDone")}}export function actionLabel(a){switch(a.type){case"updateRecord":return bm("extras.actionUpdateRecord");case"createRecord":return bm("extras.actionCreateRecord");case"notify":return bm("extras.actionNotify");case"highlight":return bm("extras.actionHighlight");case"run":return appActions.get(a.action)?.label??a.action;case"webhook":return bm("extras.actionWebhook");case"email":return bm("extras.actionEmail");case"chat":return bm("extras.actionChat");case"textMessage":return bm("extras.actionText");case"repeat":return bm("extras.actionRepeat");case"if":return bm("extras.actionIf");case"ai":return bm("extras.actionAi");case"script":return bm("extras.actionScript")}}export function triggerText(t,a){const name=id=>t?tableFields(t).get(id)?.header??id:id;const cond=a.condition?describeFieldFilter(a.condition,name):"";const where=cond&&cond!=="every record";const tr=a.trigger;switch(tr.type){case"recordCreated":return where?bm("extras.whenCreatedWhere",{condition:cond}):bm("extras.whenCreated");case"recordUpdated":{if(!tr.fields?.length)return where?bm("extras.whenRecordChangesWhere",{condition:cond}):bm("extras.whenRecordChanges");const fields=tr.fields.map(name).join(bm("extras.fieldsOr"));return where?bm("extras.whenFieldsChangeWhere",{fields,condition:cond}):bm("extras.whenFieldsChange",{fields})}case"recordMatches":return bm("extras.whenMatches",{condition:cond||bm("extras.noConditionYet")});case"formSubmitted":return where?bm("extras.whenFormWhere",{condition:cond}):bm("extras.whenForm");case"button":return bm("extras.whenPressed",{field:name(tr.field)});case"scheduled":return where?bm("extras.onScheduleWhere",{cron:cronWords(tr.cron),condition:cond}):bm("extras.onSchedule",{cron:cronWords(tr.cron)});case"webhookReceived":return bm("extras.whenWebhook")}}
1
+ import{toast}from"@svgrid/grid";import{createScheduler}from"../scheduling.js";import{colId,primaryOf,rowIdOf,syncAllInverses}from"./base-tables.js";import{compileFieldFilter,describeFieldFilter}from"./filter-model.js";import{fieldPropsOf,fillFieldColumn}from"./registry.svelte.js";import{noteChange}from"./activity.svelte.js";import{getCurrentUser,getFieldUsers}from"./sources.svelte.js";import{newRecordId}from"./field-ops.js";import{fieldText,fieldValue,linkNames}from"./base-alerts.js";import{callWebhook,sendChat,sendEmailAction,sendTextAction}from"./automation-outbound.js";import{runScript}from"./automation-script.js";import{bm}from"./messages.svelte.js";import{cronWords}from"./cron-words.js";const appActions=new Map;export function registerAutomationAction(id,action){appActions.set(id,action)}export function listAutomationActions(){return[...appActions].map(([id,a])=>({id,label:a.label}))}const readers=new WeakMap;export function tableFields(t){const hit=readers.get(t.columns);if(hit)return hit;const all=t.columns.map(d=>({...d,id:colId(d)}));const map=new Map;for(const d of t.columns){if(d.field==null)continue;const def=fillFieldColumn(d,all);map.set(colId(d),{id:colId(d),field:String(d.field),header:String(d.header??d.field),fieldType:d.fieldType,def,visible:true})}readers.set(t.columns,map);return map}const byName=(t,name)=>{const lower=name.trim().toLowerCase();for(const c of tableFields(t).values()){if(c.header.trim().toLowerCase()===lower||c.field.toLowerCase()===lower||c.id.toLowerCase()===lower)return c}return void 0};export function fillTokens(t,record,template,values){return template.replace(/\{([^{}\n]+)\}/g,(m,name)=>{const given=values?.get(name.trim().toLowerCase());if(given!==void 0)return given;const c=byName(t,name);return!c?m:record?fieldText(c,record):bm("extras.noRecordValue")})}export function viewFilterOf(t,viewId){const v=(t.views??[]).find(x=>x.id===viewId);const f=v?.state?.advancedFilter;return f&&typeof f==="object"&&f.kind==="fieldFilter"?f:null}export function matches(t,condition,record){if(!condition)return true;const fields=tableFields(t);const test=compileFieldFilter(condition,(row,id)=>{const c=fields.get(id);return c?fieldValue(c,row):row[id]},linkNames);return test?test(record):true}function stampModifiedTime(t,row,changedIds,at){for(const d of t.columns){if(d.fieldType!=="lastModifiedTime"||d.field==null||changedIds.includes(colId(d)))continue;const p=fieldPropsOf(d);if(p.watch==="specific"&&!changedIds.some(id=>(p.watchFields??[]).includes(id)))continue;row[String(d.field)]=at.toISOString()}}const DAY=864e5;const isoDay=d=>`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,"0")}-${String(d.getDate()).padStart(2,"0")}`;export function fieldValueFrom(t,def,spec,ctx){const type=def.fieldType;if(typeof spec!=="string")return spec;const raw=spec.includes("{record}")?spec:fillTokens(ctx.from,ctx.record,spec,ctx.values);const text=raw.trim();if(text==="")return type==="checkbox"?false:type==="multiSelect"||type==="link"||type==="attachment"?[]:null;switch(type){case"checkbox":return/^(true|yes|1|checked|on)$/i.test(text);case"number":case"rating":case"duration":case"currency":case"percent":{const n=Number(text.replace(/[^0-9.+-eE]/g,""));return Number.isFinite(n)?text.endsWith("%")?n/100:n:null}case"multiSelect":return text.split(/\s*,\s*/).filter(Boolean);case"user":{const found=getFieldUsers().find(u=>u.id===text||u.name.toLocaleLowerCase()===text.toLocaleLowerCase());return found?found.id:text}case"date":{const m=/^(today|now)\s*(?:([+-])\s*(\d+))?$/i.exec(text);if(!m)return text;const shift=m[2]?(m[2]==="-"?-1:1)*Number(m[3])*DAY:0;const at=new Date(ctx.now.getTime()+shift);return m[1].toLowerCase()==="now"||def.fieldProps?.time?at.toISOString():isoDay(at)}case"link":{const target=ctx.tables.find(x=>x.id===def.fieldProps?.table);const out=[];for(const part of text.split(/\s*,\s*/)){if(part==="{record}"){if(ctx.record&&ctx.from.id===target?.id)out.push(rowIdOf(ctx.from,ctx.record));continue}const name=fillTokens(ctx.from,ctx.record,part,ctx.values).toLocaleLowerCase();const named=ctx.named?.get(name);if(named){out.push(named);continue}const hit=target?.data.find(r=>String(r?.[primaryOf(target)]??"").toLocaleLowerCase()===name);if(hit&&target)out.push(rowIdOf(target,hit))}return def.fieldProps?.multiple===false?out.slice(0,1):out}default:return raw}}export const MAX_DEPTH=4;export function pressedValues(){const me=getCurrentUser();const out=new Map;out.set("pressed.name",me?.name??"");out.set("pressed.email",me?.email??"");out.set("pressed.id",me?.id??"");return out}export const REPEAT_MOST=1e3;const SCRIPT_ROWS=5e3;const READ_AS_TEXT=new Set(["checkbox","number","rating","duration","currency","percent","multiSelect","user","date","link"]);export function scriptRecord(t,r){const values={};const texts={};let name="";for(const c of tableFields(t).values()){let v=r[c.field]??null;try{v=JSON.parse(JSON.stringify(v))}catch{v=null}values[c.header]=v;texts[c.header]=fieldText(c,r);if(c.field===primaryOf(t))name=texts[c.header]}return{id:rowIdOf(t,r),name,values,texts}}export function scriptInput(t,rec,values){const out={};if(rec){out.recordId=rowIdOf(t,rec);for(const c of tableFields(t).values())out[c.header]=fieldText(c,rec)}for(const[k,v]of values)out[k]=v;return out}export function webhookValues(body){const out=new Map;const walk=(v,path,depth)=>{if(out.size>=200)return;if(v!==null&&typeof v==="object"&&depth<5){for(const[k,x]of Object.entries(v).slice(0,100))walk(x,`${path}.${k.toLowerCase()}`,depth+1);if(path!=="webhook")out.set(path,JSON.stringify(v));return}out.set(path,v==null?"":typeof v==="string"?v:JSON.stringify(v))};walk(body,"webhook",0);out.set("webhook",typeof body==="string"?body:JSON.stringify(body??null));return out}export function triggerValues(t,rec,values){const out=new Map(values);if(rec)for(const c of tableFields(t).values())out.set(`trigger.${c.header.trim().toLowerCase()}`,fieldText(c,rec));return out}export function allActions(list){const out=[];for(const x of list){out.push(x);if(x.type==="if")out.push(...allActions(x.then??[]),...allActions(x.else??[]));if(x.type==="repeat")out.push(...allActions(x.actions??[]))}return out}const SHOW_BACKLOG=20;const CARRY_MOST=5e3;const FREE_EVERY=4096;let runSeq=0;export function createAutomationRunner(options){const now=options.now??(()=>new Date);let runs=$state.raw([]);let scheduler=null;let chain=Promise.resolve();let waiting=[];let head=0;let draining=false;let burst={done:0,total:0,at:0,told:0};let backlog=$state.raw(null);let measured=null;const record=run=>runs=[run,...runs].slice(0,100);const automationsOf=t=>(t.automations??[]).filter(a=>a.enabled&&a.runOn!=="server");const tableOf=id=>options.getTables()?.find(t=>t.id===id);const carried=new Map;const carriedFor=new Map;const carry=(key,row)=>{carried.set(key,row);carriedFor.set(key,(carriedFor.get(key)??0)+1)};const letGo=key=>{const left=(carriedFor.get(key)??1)-1;if(left>0)return void carriedFor.set(key,left);carriedFor.delete(key);carried.delete(key)};const recordNow=async(t,id)=>{const own=tableOf(t.id)??t;if(!own.source?.server)return own.data.find(r=>r&&rowIdOf(own,r)===id)??null;return carried.get(`${t.id}:${id}`)??await options.server?.read(t.id,id)??null};async function namesIn(target,values,ctx){const named=new Map;const fields=tableFields(target);for(const[id,spec]of Object.entries(values)){const def=fields.get(id)?.def;if(def?.fieldType!=="link"||typeof spec!=="string")continue;const to=(options.getTables()??[]).find(x=>x.id===def.fieldProps?.table);if(!to?.source?.server)continue;for(const part of spec.split(/\s*,\s*/)){const name=fillTokens(ctx.from,ctx.record,part);const hit=part==="{record}"?null:await options.server?.byName(to.id,name);if(hit)named.set(name.toLocaleLowerCase(),hit)}}return named}const setOff=(t,e)=>automationsFor(t,e,"browser");function handle(e){const t=tableOf(e.table);if(!t)return chain;const list=setOff(t,e);const depth="depth"in e?e.depth??0:0;const recordId=rowIdOf(t,e.record);for(const a of list){if(t.source?.server&&waiting.length-head<CARRY_MOST)carry(`${t.id}:${recordId}`,e.record);if(!draining&&head===waiting.length)burst={done:0,total:0,at:Date.now(),told:0};burst.total+=1;waiting.push({a,tableId:t.id,recordId,depth})}return list.length?drain():chain}function tell(){const clock=Date.now();if(burst.total<SHOW_BACKLOG||clock-burst.told<250)return;burst.told=clock;const seconds=(clock-burst.at)/1e3;if(burst.done>=SHOW_BACKLOG&&seconds>0)measured=burst.done/seconds;backlog={done:burst.done,total:burst.total,perSecond:burst.done>=SHOW_BACKLOG?measured:null}}function endBurst(left){const shown=backlog!=null||burst.total>=SHOW_BACKLOG;backlog=null;if(shown)options.onBurstEnd?.({done:burst.total-left,total:burst.total,left})}function drain(){if(draining)return chain;draining=true;tell();chain=chain.then(async()=>{let breath=Date.now();for(;;){if(head>=waiting.length){if(burst.total<SHOW_BACKLOG)break;await new Promise(r=>setTimeout(r,200));if(head>=waiting.length)break;continue}if(Date.now()-breath>40){await new Promise(r=>setTimeout(r));breath=Date.now();continue}const w=waiting[head];head+=1;if(head>=FREE_EVERY){waiting=waiting.slice(head);head=0}try{await runOne(w.a,w.tableId,w.recordId,w.depth)}catch(e){record({id:++runSeq,automationId:w.a.id,name:w.a.name,table:tableOf(w.tableId)?.name??w.tableId,record:w.recordId,at:now().getTime(),status:"error",steps:[{action:w.a.name,detail:"",error:e instanceof Error?e.message:String(e)}]})}if(w.recordId!=null)letGo(`${w.tableId}:${w.recordId}`);burst.done+=1;tell()}waiting=[];head=0;draining=false;endBurst(0)});return chain}function stopRuns(){const left=waiting.length-head;if(!left)return 0;for(let i=head;i<waiting.length;i++){const w=waiting[i];if(w.recordId!=null)letGo(`${w.tableId}:${w.recordId}`)}waiting=[];head=0;endBurst(left);burst={done:0,total:0,at:Date.now(),told:0};return left}async function runOne(a,tableId,recordId,depth){const t=tableOf(tableId);if(!t)return;const rec=recordId==null?null:await recordNow(t,recordId);const run={id:++runSeq,automationId:a.id,name:a.name,table:t.name,record:rec?String(rec[primaryOf(t)]??recordId):null,at:now().getTime(),status:"ok",steps:[]};if(depth>=MAX_DEPTH){run.status="stopped";run.steps.push({action:bm("extras.stepStopped"),detail:bm("extras.stepLoop",{max:MAX_DEPTH})});record(run);return}await runList(a,a.actions,tableId,recordId,depth,run,a.trigger.type==="button"?pressedValues():new Map);record(run)}async function runList(a,list,tableId,recordId,depth,run,values){for(const action of list){try{if(action.type==="if"){const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;const yes=!!t&&(rec?matches(t,action.condition,rec):!action.condition?.conditions?.length);run.steps.push({action:bm("extras.stepIf"),detail:bm(yes?"extras.stepIfThen":"extras.stepIfElse")});if(!await runList(a,(yes?action.then:action.else)??[],tableId,recordId,depth,run,values))return false;continue}if(action.type==="repeat"){if(!await runRepeat(a,action,tableId,recordId,depth,run,values))return false;continue}const step=await act(a,action,tableId,recordId,depth,values);if(step)run.steps.push(step)}catch(e){run.status="error";run.steps.push({action:actionLabel(action),detail:"",error:e instanceof Error?e.message:String(e)});return false}}return true}async function runRepeat(a,action,tableId,recordId,depth,run,values){const target=tableOf(action.table);if(!target)throw new Error(bm("extras.noTable",{table:action.table}));const most=Math.max(1,Math.min(REPEAT_MOST,action.limit??100));const ids=[];if(target.source?.server){await options.server?.each(target.id,action.condition,async r=>{if(ids.length>=most)return;const id=rowIdOf(target,r);carry(`${target.id}:${id}`,r);ids.push(id)})}else{for(const r of target.data){if(ids.length>=most)break;if(r&&matches(target,action.condition,r))ids.push(rowIdOf(target,r))}}run.steps.push({action:bm("extras.stepFound"),detail:bm("extras.foundIn",{count:ids.length,table:target.name})});const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;const inner=t?triggerValues(t,rec,values):new Map(values);inner.set("found",String(ids.length));try{for(const id of ids)if(!await runList(a,action.actions??[],target.id,id,depth,run,inner))return false}finally{if(target.source?.server)for(const id of ids)letGo(`${target.id}:${id}`)}return true}async function writeRecord(a,t,recordId,rec,patch,depth,at){const fields=tableFields(t);const before={...rec};const after={...rec,...patch};const changed=Object.keys(patch).filter(f=>JSON.stringify(before[f]??null)!==JSON.stringify(after[f]??null));if(!changed.length)return{changed,after};const changedIds=changed.map(f=>[...fields.values()].find(c=>c.field===f)?.id??f);stampModifiedTime(t,after,changedIds,at);if(t.source?.server){carried.set(`${t.id}:${recordId}`,after);await options.server?.update(t.id,recordId,Object.fromEntries(Object.keys(after).filter(k=>after[k]!==before[k]).map(k=>[k,after[k]])),before)}else{const tables=options.getTables()??[];let next=tables.map(x=>x.id===t.id?{...x,data:x.data.map(r=>r&&rowIdOf(t,r)===recordId?after:r)}:x);next=syncAllInverses(next,t.id);options.apply(next,depth+1,t.id)}changed.forEach((f,i)=>noteChange({base:options.scope,tableId:t.id},recordId,changedIds[i],after[f],a.name));void handle({type:"updated",table:t.id,record:after,before,fields:changedIds,depth:depth+1});return{changed,after}}function addRecord(target,row,depth){const tables=options.getTables()??[];let next=tables.map(x=>x.id===target.id?{...x,data:[...x.data,row]}:x);next=syncAllInverses(next,target.id);options.apply(next,depth+1,target.id);void handle({type:"created",table:target.id,record:row,depth:depth+1})}function pageBridge(a,depth){const named=name=>{const t=(options.getTables()??[]).find(x=>x.name.trim().toLowerCase()===name.trim().toLowerCase());if(!t)throw new Error(bm("extras.noTable",{table:name}));return t};const rowsOf=async t=>{if(!t.source?.server)return t.data.filter(Boolean);const out=[];await options.server?.each(t.id,void 0,async r=>{if(out.length<SCRIPT_ROWS)out.push(r)});return out};const patchOf=(t,given)=>{const patch={};for(const[name,v]of Object.entries(given??{})){const c=byName(t,name);if(!c)throw new Error(bm("extras.noField",{field:name}));const type=String(c.fieldType??"");const text=typeof v==="string"?v:v&&typeof v==="object"&&!Array.isArray(v)&&"name"in v?String(v.name):null;patch[c.field]=text!==null&&READ_AS_TEXT.has(type)?fieldValueFrom(t,c.def,text.replace(/[{}]/g,""),{tables:options.getTables()??[],from:t,record:null,now:now()}):v}return patch};return{tables:()=>(options.getTables()??[]).map(t=>t.name),select:async name=>{const t=named(name);return(await rowsOf(t)).map(r=>scriptRecord(t,r))},update:async(name,id,given)=>{const t=named(name);const rec=await recordNow(t,id);if(!rec)throw new Error(bm("extras.noRecordId",{id}));await writeRecord(a,t,id,rec,patchOf(t,given),depth,now())},create:async(name,given)=>{const t=named(name);const row={id:newRecordId(),...patchOf(t,given)};addRecord(t,row,depth);return String(row.id)},remove:async(name,id)=>{const t=named(name);const tables=options.getTables()??[];options.apply(tables.map(x=>x.id===t.id?{...x,data:x.data.filter(r=>!r||rowIdOf(t,r)!==id)}:x),depth+1,t.id)}}}async function act(a,action,tableId,recordId,depth,values){const tables=options.getTables()??[];const t=tables.find(x=>x.id===tableId);const rec=recordId==null?null:await recordNow(t,recordId);const ctx={tables,from:t,record:rec,now:now(),values};switch(action.type){case"notify":{const message=fillTokens(t,rec,action.message,values);const sev=action.severity??"info";toast[sev](message);return{action:bm("extras.stepNotice"),detail:message}}case"highlight":return null;case"updateRecord":{if(!rec||recordId==null)return{action:bm("extras.actionUpdateRecord"),detail:bm("extras.noRecordToUpdate")};const fields=tableFields(t);const patch={};ctx.named=await namesIn(t,action.values,ctx);for(const[id,spec]of Object.entries(action.values)){const c=fields.get(id);if(c)patch[c.field]=fieldValueFrom(t,c.def,spec,ctx)}const{changed,after}=await writeRecord(a,t,recordId,rec,patch,depth,ctx.now);if(!changed.length)return{action:bm("extras.actionUpdateRecord"),detail:bm("extras.alreadySet")};return{action:bm("extras.actionUpdateRecord"),detail:changed.map(f=>said([...fields.values()].find(c=>c.field===f),f,after)).join(", ")}}case"deleteRecord":{if(!rec||recordId==null)return{action:bm("extras.actionDeleteRecord"),detail:bm("extras.noRecordToDelete")};const name=String(rec[primaryOf(t)]??"")||bm("extras.aRecord");if(t.source?.server){if(!options.server?.remove)throw new Error(bm("extras.cannotDeleteHere"));await options.server.remove(t.id,recordId,rec)}else{let next=(options.getTables()??[]).map(x=>x.id===t.id?{...x,data:x.data.filter(r=>!r||rowIdOf(t,r)!==recordId)}:x);next=syncAllInverses(next,t.id);options.apply(next,depth+1,t.id)}return{action:bm("extras.actionDeleteRecord"),detail:bm("extras.deletedRecord",{name})}}case"createRecord":{const target=tables.find(x=>x.id===action.table);if(!target)throw new Error(bm("extras.noTable",{table:action.table}));const fields=tableFields(target);const row={id:newRecordId()};ctx.named=await namesIn(target,action.values,ctx);for(const[id,spec]of Object.entries(action.values)){const c=fields.get(id);if(c)row[c.field]=fieldValueFrom(target,c.def,spec,ctx)}if(action.linkField&&rec){const c=fields.get(action.linkField);if(c)row[c.field]=[rowIdOf(t,rec)]}addRecord(target,row,depth);const name=String(row[primaryOf(target)]??"")||bm("extras.aRecord");return{action:bm("extras.actionCreateRecord"),detail:bm("extras.createdIn",{name,table:target.name})}}case"run":return runAppAction(a,action,t,rec);case"webhook":return{action:bm("extras.stepWebhook"),detail:await callWebhook(action,outbound(a,t,rec,{},values))};case"email":return{action:bm("extras.stepEmail"),detail:await sendEmailAction(action,outbound(a,t,rec,{},values),void 0)};case"chat":return{action:bm("extras.stepChat"),detail:await sendChat(action,outbound(a,t,rec,{},values))};case"textMessage":return{action:bm("extras.stepText"),detail:await sendTextAction(action,outbound(a,t,rec,{},values),void 0)};case"ai":{if(!options.ai)throw new Error(bm("extras.noAi"));const prompt=fillTokens(t,rec,action.prompt,values).trim();if(!prompt)throw new Error(bm("extras.aiNoPrompt"));const answer=String(await options.ai(prompt)).trim();values.set("ai",answer);const c=action.field?tableFields(t).get(action.field):void 0;if(c&&rec&&recordId!=null)await writeRecord(a,t,recordId,rec,{[c.field]:answer},depth,ctx.now);return{action:bm("extras.stepAi"),detail:answer.length>160?answer.slice(0,157)+"...":answer}}case"script":{const result=await runScript(action.code,{input:scriptInput(t,rec,values),bridge:pageBridge(a,depth)});for(const[k,v]of Object.entries(result.output))values.set(`script.${k.toLowerCase()}`,typeof v==="string"?v:JSON.stringify(v));if(!result.ok)throw new Error(result.error??bm("extras.scriptFailed"));return{action:bm("extras.stepScript"),detail:result.logs.slice(-3).join(" | ")||bm("extras.stepDone")}}default:return null}}function schedule(){scheduler?.stop();scheduler=null;const list=options.getTables()??[];const due=[];for(const t of list)for(const a of automationsOf(t))if(a.trigger.type==="scheduled")due.push({id:`${t.id}:${a.id}`,cron:a.trigger.cron,table:t.id,automation:a});if(!due.length)return;scheduler=createScheduler({schedules:due,now,onFire:s=>void runScheduled(s.id)});scheduler.start()}function runScheduled(key){const[tableId,automationId]=key.split(":");const t=tableOf(tableId);const a=t?.automations?.find(x=>x.id===automationId);if(!t||!a)return chain;if(!a.condition)chain=chain.then(()=>runOne(a,t.id,null,0));else if(t.source?.server){chain=chain.then(()=>options.server?.each(t.id,a.condition,async r=>{const key2=`${t.id}:${rowIdOf(t,r)}`;carry(key2,r);await runOne(a,t.id,rowIdOf(t,r),0);letGo(key2)}))}else for(const r of t.data)if(r&&matches(t,a.condition,r))chain=chain.then(()=>runOne(a,t.id,rowIdOf(t,r),0));return chain}return{handle,stopRuns,get backlog(){return backlog},get waiting(){return waiting.length-head},get perSecond(){return measured},schedule,runScheduled,firstRecords:async(tableId,count)=>await options.server?.first(tableId,count)??[],runNow:(a,tableId,recordId)=>chain=chain.then(async()=>{const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;if(t&&rec&&a.condition&&!matches(t,a.condition,rec)){record({id:++runSeq,automationId:a.id,name:a.name,table:t.name,record:String(rec[primaryOf(t)]??recordId),at:now().getTime(),status:"stopped",steps:[{action:bm("extras.stepNotRun"),detail:bm("extras.stepNoMatch")}]});return}return runOne(a,tableId,recordId,0)}),get runs(){return runs},clearRuns:()=>runs=[],settled:()=>chain,stop:()=>scheduler?.stop()}}function said(c,field,record){if(!c)return bm("extras.saidValue",{field,value:String(record[field]??"")});if(c.fieldType==="checkbox")return bm(record[c.field]?"extras.saidChecked":"extras.saidUnchecked",{field:c.header});return bm("extras.saidValue",{field:c.header,value:fieldText(c,record)||bm("extras.saidEmpty")})}export function automationsFor(t,e,side){return(t.automations??[]).filter(a=>{if(!a.enabled||a.runOn==="server"!==(side==="server"))return false;const tr=a.trigger;switch(tr.type){case"recordCreated":return e.type==="created"&&matches(t,a.condition,e.record);case"recordUpdated":return e.type==="updated"&&(!tr.fields?.length||tr.fields.some(f=>e.fields.includes(f)))&&matches(t,a.condition,e.record);case"recordMatches":if(!a.condition)return false;if(e.type==="created")return matches(t,a.condition,e.record);if(e.type==="updated")return matches(t,a.condition,e.record)&&!matches(t,a.condition,e.before);return false;case"recordEntersView":{const f=viewFilterOf(t,tr.view);if(!f)return false;if(e.type==="created")return matches(t,f,e.record)&&matches(t,a.condition,e.record);if(e.type==="updated")return matches(t,f,e.record)&&!matches(t,f,e.before)&&matches(t,a.condition,e.record);return false}case"formSubmitted":return e.type==="form"&&(!tr.view||tr.view===e.view)&&matches(t,a.condition,e.record);case"button":return e.type==="button"&&e.field===tr.field&&matches(t,a.condition,e.record);default:return false}})}export function outbound(a,t,rec,extra={},values){return{automation:a.name,table:t.name,record:rec,fill:template=>fillTokens(t,rec,template,values),fields:()=>{const out={};if(rec)for(const c of tableFields(t).values())out[c.header]=c.fieldType==="checkbox"?String(!!rec[c.field]):fieldText(c,rec);return out},...extra}}export async function runAppAction(a,action,t,rec){const app=appActions.get(action.action);if(!app)throw new Error(bm("extras.noAction",{action:action.action}));const out=await app.run({automation:a,table:t,record:rec,text:name=>fillTokens(t,rec,`{${name}}`),options:action.options??{}});return{action:app.label,detail:typeof out==="string"?out:bm("extras.stepDone")}}export function actionLabel(a){switch(a.type){case"updateRecord":return bm("extras.actionUpdateRecord");case"deleteRecord":return bm("extras.actionDeleteRecord");case"createRecord":return bm("extras.actionCreateRecord");case"notify":return bm("extras.actionNotify");case"highlight":return bm("extras.actionHighlight");case"run":return appActions.get(a.action)?.label??a.action;case"webhook":return bm("extras.actionWebhook");case"email":return bm("extras.actionEmail");case"chat":return bm("extras.actionChat");case"textMessage":return bm("extras.actionText");case"repeat":return bm("extras.actionRepeat");case"if":return bm("extras.actionIf");case"ai":return bm("extras.actionAi");case"script":return bm("extras.actionScript")}}export function triggerText(t,a){const name=id=>t?tableFields(t).get(id)?.header??id:id;const cond=a.condition?describeFieldFilter(a.condition,name):"";const where=cond&&cond!=="every record";const tr=a.trigger;switch(tr.type){case"recordCreated":return where?bm("extras.whenCreatedWhere",{condition:cond}):bm("extras.whenCreated");case"recordUpdated":{if(!tr.fields?.length)return where?bm("extras.whenRecordChangesWhere",{condition:cond}):bm("extras.whenRecordChanges");const fields=tr.fields.map(name).join(bm("extras.fieldsOr"));return where?bm("extras.whenFieldsChangeWhere",{fields,condition:cond}):bm("extras.whenFieldsChange",{fields})}case"recordMatches":return bm("extras.whenMatches",{condition:cond||bm("extras.noConditionYet")});case"recordEntersView":{const view=(t?.views??[]).find(v=>v.id===tr.view)?.name??bm("extras.aView");return where?bm("extras.whenEntersViewWhere",{view,condition:cond}):bm("extras.whenEntersView",{view})}case"formSubmitted":return where?bm("extras.whenFormWhere",{condition:cond}):bm("extras.whenForm");case"button":return bm("extras.whenPressed",{field:name(tr.field)});case"scheduled":return where?bm("extras.onScheduleWhere",{cron:cronWords(tr.cron),condition:cond}):bm("extras.onSchedule",{cron:cronWords(tr.cron)});case"webhookReceived":return bm("extras.whenWebhook")}}
@@ -1 +1 @@
1
- export const FORMULA_DOCS={IF:{syntax:"IF(condition, value if true, [value if false])",summary:"One value when the condition is true, another when it is not (empty if left out).",example:'IF({Qty} > 10, "Bulk", "Small")',group:"logic"},AND:{syntax:"AND(condition1, [condition2, ...])",summary:"True when every condition is true.",example:'AND({Paid}, {Status} = "Shipped")',group:"logic"},OR:{syntax:"OR(condition1, [condition2, ...])",summary:"True when at least one condition is true.",example:'OR({Status} = "Late", {Status} = "Lost")',group:"logic"},NOT:{syntax:"NOT(condition)",summary:"True when the condition is false or empty, false when it is true.",example:"NOT({Paid})",group:"logic"},XOR:{syntax:"XOR(condition1, [condition2, ...])",summary:"True when an odd number of the conditions are true.",example:"XOR({Paid}, {Refunded})",group:"logic"},TRUE:{syntax:"TRUE()",summary:"The value true. You can also write TRUE without the brackets.",example:"IF({Qty} > 0, TRUE(), FALSE())",group:"logic"},FALSE:{syntax:"FALSE()",summary:"The value false. You can also write FALSE without the brackets.",example:'IF({Status} = "Cancelled", FALSE(), TRUE())',group:"logic"},BLANK:{syntax:"BLANK()",summary:"An empty value, for leaving the cell empty.",example:"IF({Qty} = 0, BLANK(), {Qty} * {Unit price})",group:"logic"},ERROR:{syntax:"ERROR()",summary:"Makes the cell show #ERROR, to flag a record that needs a look.",example:"IF({Qty} < 0, ERROR(), {Qty})",group:"logic"},ISERROR:{syntax:"ISERROR(value)",summary:"True when the value is an error, such as ERROR() or a number that cannot be worked out.",example:"IF(ISERROR({Discount}), 0, {Discount})",group:"logic"},SWITCH:{syntax:"SWITCH(value, match1, result1, [match2, result2, ...], [default])",summary:"The result next to the first match for the value, or the default when none match.",example:'SWITCH({Status}, "New", 1, "Paid", 2, "Shipped", 3, 0)',group:"logic"},RECORD_ID:{syntax:"RECORD_ID()",summary:"The id of this record, as text.",example:'"https://example.com/orders/" & RECORD_ID()',group:"records"},CONCATENATE:{syntax:"CONCATENATE(text1, [text2, ...])",summary:"All the values joined into one text, in order. The & sign does the same.",example:'CONCATENATE({First name}, " ", {Last name})',group:"text"},LEN:{syntax:"LEN(text)",summary:"The number of characters in the text.",example:"LEN({Phone})",group:"text"},UPPER:{syntax:"UPPER(text)",summary:"The text in capital letters.",example:"UPPER({Country code})",group:"text"},LOWER:{syntax:"LOWER(text)",summary:"The text in small letters.",example:"LOWER({Email})",group:"text"},TRIM:{syntax:"TRIM(text)",summary:"The text without spaces at the start and the end.",example:"TRIM({Client})",group:"text"},LEFT:{syntax:"LEFT(text, [count])",summary:"The first characters of the text; one character if no count is given.",example:"LEFT({Postcode}, 2)",group:"text"},RIGHT:{syntax:"RIGHT(text, [count])",summary:"The last characters of the text; one character if no count is given.",example:"RIGHT({Phone}, 4)",group:"text"},MID:{syntax:"MID(text, start, [count])",summary:"Characters from a position (1 is the first); the rest of the text if no count.",example:"MID({Invoice no}, 5, 3)",group:"text"},FIND:{syntax:"FIND(text to find, text, [start])",summary:"Where the text is found (1 is the first character), or 0 if not. Case matters.",example:'FIND("@", {Email})',group:"text"},SEARCH:{syntax:"SEARCH(text to find, text, [start])",summary:"Where the text is found (1 is the first character), or empty if not. Case matters.",example:'SEARCH("urgent", {Notes})',group:"text"},SUBSTITUTE:{syntax:"SUBSTITUTE(text, old text, new text, [which one])",summary:"The text with the old text swapped for the new; only the nth one if you give n.",example:'SUBSTITUTE({Phone}, " ", "")',group:"text"},REPLACE:{syntax:"REPLACE(text, start, count, new text)",summary:"The text with count characters from the start position swapped for the new text.",example:'REPLACE({Card number}, 1, 12, "************")',group:"text"},ENCODE_URL_COMPONENT:{syntax:"ENCODE_URL_COMPONENT(text)",summary:"The text made safe to put in a web address.",example:'"https://maps.google.com/?q=" & ENCODE_URL_COMPONENT({Address})',group:"text"},REGEX_MATCH:{syntax:"REGEX_MATCH(text, pattern)",summary:"True when the text fits the pattern (a regular expression).",example:'REGEX_MATCH({Email}, "^[^@ ]+@[^@ ]+[.][a-z]+$")',group:"text"},REGEX_EXTRACT:{syntax:"REGEX_EXTRACT(text, pattern)",summary:"The first part of the text that fits the pattern, or empty if none does.",example:'REGEX_EXTRACT({Notes}, "[0-9]+")',group:"text"},REGEX_REPLACE:{syntax:"REGEX_REPLACE(text, pattern, new text)",summary:"The text with every part that fits the pattern swapped for the new text.",example:'REGEX_REPLACE({Phone}, "[^0-9]", "")',group:"text"},REPT:{syntax:"REPT(text, times)",summary:"The text repeated a number of times (at most 1,000).",example:'REPT("*", {Rating})',group:"text"},T:{syntax:"T(value)",summary:"The value if it is text, otherwise empty text.",example:"T({Notes})",group:"text"},VALUE:{syntax:"VALUE(text)",summary:"The number in the text, ignoring signs like $ and spaces; empty if there is none.",example:"VALUE({Price text}) * {Qty}",group:"text"},ARRAYJOIN:{syntax:"ARRAYJOIN(list, [separator])",summary:'The items of a list joined into one text, with ", " between them unless you say.',example:'ARRAYJOIN({Tags}, " / ")',group:"text"},ARRAYCOMPACT:{syntax:"ARRAYCOMPACT(list)",summary:"The list without its empty items.",example:"ARRAYCOMPACT({Phone numbers})",group:"lists"},ARRAYFLATTEN:{syntax:"ARRAYFLATTEN(list1, [list2, ...])",summary:"One flat list of all the items, with lists inside lists opened up.",example:"ARRAYFLATTEN({Tags}, {Categories})",group:"lists"},ARRAYUNIQUE:{syntax:"ARRAYUNIQUE(list)",summary:"The list with each item only once.",example:"ARRAYUNIQUE({Order cities})",group:"lists"},ARRAYSLICE:{syntax:"ARRAYSLICE(list, start, [end])",summary:"The items from start to end (1 is the first; a negative number counts from the end).",example:"ARRAYSLICE({Tags}, 1, 3)",group:"lists"},SUM:{syntax:"SUM(number1, [number2, ...])",summary:"All the numbers added up.",example:"SUM({Subtotal}, {Shipping}, {Tax})",group:"numbers"},AVERAGE:{syntax:"AVERAGE(number1, [number2, ...])",summary:"The average of the numbers, leaving out empty ones.",example:"AVERAGE({Q1 sales}, {Q2 sales}, {Q3 sales})",group:"numbers"},MAX:{syntax:"MAX(number1, [number2, ...])",summary:"The largest of the numbers.",example:"MAX({Quote A}, {Quote B})",group:"numbers"},MIN:{syntax:"MIN(number1, [number2, ...])",summary:"The smallest of the numbers.",example:"MIN({Stock}, {Qty})",group:"numbers"},COUNT:{syntax:"COUNT(value1, [value2, ...])",summary:"How many of the values are numbers.",example:"COUNT({Mon hours}, {Tue hours}, {Wed hours})",group:"numbers"},COUNTA:{syntax:"COUNTA(value1, [value2, ...])",summary:"How many of the values are not empty.",example:"COUNTA({Phone}, {Email}, {Address})",group:"numbers"},COUNTALL:{syntax:"COUNTALL(value1, [value2, ...])",summary:"How many values there are, empty ones included.",example:"COUNTALL({Attendees})",group:"numbers"},ROUND:{syntax:"ROUND(number, [decimals])",summary:"The number rounded to that many decimal places (none if left out).",example:"ROUND({Qty} * {Unit price}, 2)",group:"numbers"},ROUNDUP:{syntax:"ROUNDUP(number, [decimals])",summary:"The number rounded away from zero to that many decimal places.",example:"ROUNDUP({Hours worked}, 0)",group:"numbers"},ROUNDDOWN:{syntax:"ROUNDDOWN(number, [decimals])",summary:"The number rounded toward zero to that many decimal places.",example:"ROUNDDOWN({Total} * 0.1, 2)",group:"numbers"},INT:{syntax:"INT(number)",summary:"The number rounded down to a whole number.",example:"INT({Hours worked})",group:"numbers"},ABS:{syntax:"ABS(number)",summary:"The number without its minus sign.",example:"ABS({Balance})",group:"numbers"},MOD:{syntax:"MOD(number, divisor)",summary:"What is left after dividing; it takes the sign of the first number.",example:"MOD({Qty}, 12)",group:"numbers"},POWER:{syntax:"POWER(number, power)",summary:"The number raised to the power.",example:"{Deposit} * POWER(1 + {Rate}, {Years})",group:"numbers"},SQRT:{syntax:"SQRT(number)",summary:"The square root of the number.",example:"SQRT({Floor area})",group:"numbers"},EXP:{syntax:"EXP(number)",summary:"The number e (about 2.718) raised to the power you give.",example:"{Deposit} * EXP({Rate} * {Years})",group:"numbers"},LOG:{syntax:"LOG(number, [base])",summary:"The logarithm of the number, in base 10 unless you give another base.",example:"LOG({Visitors}, 10)",group:"numbers"},EVEN:{syntax:"EVEN(number)",summary:"The number rounded away from zero to the next even whole number.",example:"EVEN({Guests})",group:"numbers"},ODD:{syntax:"ODD(number)",summary:"The number rounded away from zero to the next odd whole number.",example:"ODD({Team size})",group:"numbers"},CEILING:{syntax:"CEILING(number, [multiple])",summary:"The number rounded up to a multiple (1 if left out): CEILING(7, 5) is 10.",example:"CEILING({Qty}, 6)",group:"numbers"},FLOOR:{syntax:"FLOOR(number, [multiple])",summary:"The number rounded down to a multiple (1 if left out): FLOOR(7, 5) is 5.",example:"FLOOR({Price}, 0.5)",group:"numbers"},DISTANCE:{syntax:"DISTANCE(place, place)",summary:'Metres between two places given as coordinates ("42.6977, 23.3219"), as a phone saves them.',example:"DISTANCE({Where the phone was}, '42.6977, 23.3219')",group:"numbers"},TODAY:{syntax:"TODAY()",summary:"Today's date, at midnight.",example:'DATETIME_DIFF({Due date}, TODAY(), "days")',group:"dates"},NOW:{syntax:"NOW()",summary:"The date and time right now.",example:'DATETIME_DIFF(NOW(), {Created}, "hours")',group:"dates"},YEAR:{syntax:"YEAR(date)",summary:"The year of a date, such as 2026.",example:"YEAR({Invoice date})",group:"dates"},MONTH:{syntax:"MONTH(date)",summary:"The month of a date, from 1 (January) to 12 (December).",example:"MONTH({Invoice date})",group:"dates"},DAY:{syntax:"DAY(date)",summary:"The day of the month of a date, from 1 to 31.",example:"DAY({Due date})",group:"dates"},HOUR:{syntax:"HOUR(date)",summary:"The hour of a date and time, from 0 to 23.",example:"HOUR({Appointment})",group:"dates"},MINUTE:{syntax:"MINUTE(date)",summary:"The minute of a date and time, from 0 to 59.",example:"MINUTE({Appointment})",group:"dates"},SECOND:{syntax:"SECOND(date)",summary:"The second of a date and time, from 0 to 59.",example:"SECOND({Logged at})",group:"dates"},WEEKDAY:{syntax:"WEEKDAY(date, [first day])",summary:'The day of the week, 0 for Sunday to 6; with "Monday" as first day, 0 is Monday.',example:'WEEKDAY({Delivery date}, "Monday")',group:"dates"},WEEKNUM:{syntax:"WEEKNUM(date, [first day])",summary:'The week of the year (week 1 holds January 1); weeks start Sunday, or "Monday".',example:'WEEKNUM({Order date}, "Monday")',group:"dates"},DATEADD:{syntax:"DATEADD(date, count, [unit])",summary:"The date moved on by a number of days, weeks, months, years... (days if no unit).",example:'DATEADD({Invoice date}, 30, "days")',group:"dates"},DATETIME_DIFF:{syntax:"DATETIME_DIFF(date1, date2, [unit])",summary:"The time between two dates: the first minus the second, in days or another unit.",example:'DATETIME_DIFF({Due date}, TODAY(), "days")',group:"dates"},IS_BEFORE:{syntax:"IS_BEFORE(date1, date2)",summary:"True when the first date is before the second.",example:"IS_BEFORE({Due date}, TODAY())",group:"dates"},IS_AFTER:{syntax:"IS_AFTER(date1, date2)",summary:"True when the first date is after the second.",example:"IS_AFTER({Delivered on}, {Due date})",group:"dates"},IS_SAME:{syntax:"IS_SAME(date1, date2, [unit])",summary:"True when two dates are the same moment, or the same day, month, year... by unit.",example:'IS_SAME({Order date}, TODAY(), "month")',group:"dates"},DATESTR:{syntax:"DATESTR(date)",summary:"The date as text, year first: 2026-12-04.",example:"DATESTR({Due date})",group:"dates"},TIMESTR:{syntax:"TIMESTR(date)",summary:"The time of a date as text, in 24 hours: 14:30:00.",example:"TIMESTR({Appointment})",group:"dates"},DATETIME_FORMAT:{syntax:"DATETIME_FORMAT(date, [format])",summary:'The date as text in the format you write, such as "DD/MM/YYYY" or "MMMM D".',example:'DATETIME_FORMAT({Due date}, "DD/MM/YYYY")',group:"dates"},DATETIME_PARSE:{syntax:"DATETIME_PARSE(text, [format])",summary:"The date written in the text, read with the format if you give one.",example:'DATETIME_PARSE({Date text}, "DD.MM.YYYY")',group:"dates"},SET_LOCALE:{syntax:"SET_LOCALE(date, locale)",summary:'The date, set to show month and day names in a language, such as "fr" or "de".',example:'DATETIME_FORMAT(SET_LOCALE({Due date}, "fr"), "D MMMM YYYY")',group:"dates"},SET_TIMEZONE:{syntax:"SET_TIMEZONE(date, time zone)",summary:'The date, set to show the clock of a time zone, such as "Europe/London".',example:'DATETIME_FORMAT(SET_TIMEZONE({Appointment}, "Europe/London"), "HH:mm")',group:"dates"},TONOW:{syntax:"TONOW(date)",summary:"The number of days from the date to today.",example:"TONOW({Last contacted})",group:"dates"},FROMNOW:{syntax:"FROMNOW(date)",summary:"The number of days from today to the date.",example:"FROMNOW({Due date})",group:"dates"},WORKDAY:{syntax:"WORKDAY(start date, days, [holidays])",summary:"The date that many working days on, skipping weekends and the holidays.",example:'WORKDAY({Order date}, 5, "2026-12-25, 2026-12-26")',group:"dates"},WORKDAY_DIFF:{syntax:"WORKDAY_DIFF(start date, end date, [holidays])",summary:"The working days from start to end, both days counted, skipping the holidays.",example:'WORKDAY_DIFF({Start date}, {End date}, "2026-12-25")',group:"dates"}};export function syntaxArgs(e){const t=e.indexOf("("),a=e.lastIndexOf(")");return t<0||a<=t?[]:e.slice(t+1,a).replace(/[[\]]/g,"").split(",").map(s=>s.replace(/\.{3}|…/g,"").trim()).filter(Boolean)}
1
+ export const FORMULA_DOCS={IF:{syntax:"IF(condition, value if true, [value if false])",summary:"One value when the condition is true, another when it is not (empty if left out).",example:'IF({Qty} > 10, "Bulk", "Small")',group:"logic"},AND:{syntax:"AND(condition1, [condition2, ...])",summary:"True when every condition is true.",example:'AND({Paid}, {Status} = "Shipped")',group:"logic"},OR:{syntax:"OR(condition1, [condition2, ...])",summary:"True when at least one condition is true.",example:'OR({Status} = "Late", {Status} = "Lost")',group:"logic"},NOT:{syntax:"NOT(condition)",summary:"True when the condition is false or empty, false when it is true.",example:"NOT({Paid})",group:"logic"},XOR:{syntax:"XOR(condition1, [condition2, ...])",summary:"True when an odd number of the conditions are true.",example:"XOR({Paid}, {Refunded})",group:"logic"},TRUE:{syntax:"TRUE()",summary:"The value true. You can also write TRUE without the brackets.",example:"IF({Qty} > 0, TRUE(), FALSE())",group:"logic"},FALSE:{syntax:"FALSE()",summary:"The value false. You can also write FALSE without the brackets.",example:'IF({Status} = "Cancelled", FALSE(), TRUE())',group:"logic"},BLANK:{syntax:"BLANK()",summary:"An empty value, for leaving the cell empty.",example:"IF({Qty} = 0, BLANK(), {Qty} * {Unit price})",group:"logic"},ERROR:{syntax:"ERROR()",summary:"Makes the cell show #ERROR, to flag a record that needs a look.",example:"IF({Qty} < 0, ERROR(), {Qty})",group:"logic"},ISERROR:{syntax:"ISERROR(value)",summary:"True when the value is an error, such as ERROR() or a number that cannot be worked out.",example:"IF(ISERROR({Discount}), 0, {Discount})",group:"logic"},SWITCH:{syntax:"SWITCH(value, match1, result1, [match2, result2, ...], [default])",summary:"The result next to the first match for the value, or the default when none match.",example:'SWITCH({Status}, "New", 1, "Paid", 2, "Shipped", 3, 0)',group:"logic"},RECORD_ID:{syntax:"RECORD_ID()",summary:"The id of this record, as text.",example:'"https://example.com/orders/" & RECORD_ID()',group:"records"},CREATED_TIME:{syntax:"CREATED_TIME()",summary:"When this record was made.",example:'DATETIME_DIFF(NOW(), CREATED_TIME(), "days")',group:"records"},LAST_MODIFIED_TIME:{syntax:"LAST_MODIFIED_TIME()",summary:"When this record was last changed.",example:'IF(DATETIME_DIFF(NOW(), LAST_MODIFIED_TIME(), "days") > 14, "Stale")',group:"records"},CONCATENATE:{syntax:"CONCATENATE(text1, [text2, ...])",summary:"All the values joined into one text, in order. The & sign does the same.",example:'CONCATENATE({First name}, " ", {Last name})',group:"text"},LEN:{syntax:"LEN(text)",summary:"The number of characters in the text.",example:"LEN({Phone})",group:"text"},UPPER:{syntax:"UPPER(text)",summary:"The text in capital letters.",example:"UPPER({Country code})",group:"text"},LOWER:{syntax:"LOWER(text)",summary:"The text in small letters.",example:"LOWER({Email})",group:"text"},TRIM:{syntax:"TRIM(text)",summary:"The text without spaces at the start and the end.",example:"TRIM({Client})",group:"text"},LEFT:{syntax:"LEFT(text, [count])",summary:"The first characters of the text; one character if no count is given.",example:"LEFT({Postcode}, 2)",group:"text"},RIGHT:{syntax:"RIGHT(text, [count])",summary:"The last characters of the text; one character if no count is given.",example:"RIGHT({Phone}, 4)",group:"text"},MID:{syntax:"MID(text, start, [count])",summary:"Characters from a position (1 is the first); the rest of the text if no count.",example:"MID({Invoice no}, 5, 3)",group:"text"},FIND:{syntax:"FIND(text to find, text, [start])",summary:"Where the text is found (1 is the first character), or 0 if not. Case matters.",example:'FIND("@", {Email})',group:"text"},SEARCH:{syntax:"SEARCH(text to find, text, [start])",summary:"Where the text is found (1 is the first character), or empty if not. Case matters.",example:'SEARCH("urgent", {Notes})',group:"text"},SUBSTITUTE:{syntax:"SUBSTITUTE(text, old text, new text, [which one])",summary:"The text with the old text swapped for the new; only the nth one if you give n.",example:'SUBSTITUTE({Phone}, " ", "")',group:"text"},REPLACE:{syntax:"REPLACE(text, start, count, new text)",summary:"The text with count characters from the start position swapped for the new text.",example:'REPLACE({Card number}, 1, 12, "************")',group:"text"},ENCODE_URL_COMPONENT:{syntax:"ENCODE_URL_COMPONENT(text)",summary:"The text made safe to put in a web address.",example:'"https://maps.google.com/?q=" & ENCODE_URL_COMPONENT({Address})',group:"text"},REGEX_MATCH:{syntax:"REGEX_MATCH(text, pattern)",summary:"True when the text fits the pattern (a regular expression).",example:'REGEX_MATCH({Email}, "^[^@ ]+@[^@ ]+[.][a-z]+$")',group:"text"},REGEX_EXTRACT:{syntax:"REGEX_EXTRACT(text, pattern)",summary:"The first part of the text that fits the pattern, or empty if none does.",example:'REGEX_EXTRACT({Notes}, "[0-9]+")',group:"text"},REGEX_REPLACE:{syntax:"REGEX_REPLACE(text, pattern, new text)",summary:"The text with every part that fits the pattern swapped for the new text.",example:'REGEX_REPLACE({Phone}, "[^0-9]", "")',group:"text"},REPT:{syntax:"REPT(text, times)",summary:"The text repeated a number of times (at most 1,000).",example:'REPT("*", {Rating})',group:"text"},T:{syntax:"T(value)",summary:"The value if it is text, otherwise empty text.",example:"T({Notes})",group:"text"},VALUE:{syntax:"VALUE(text)",summary:"The number in the text, ignoring signs like $ and spaces; empty if there is none.",example:"VALUE({Price text}) * {Qty}",group:"text"},ARRAYJOIN:{syntax:"ARRAYJOIN(list, [separator])",summary:'The items of a list joined into one text, with ", " between them unless you say.',example:'ARRAYJOIN({Tags}, " / ")',group:"text"},ARRAYCOMPACT:{syntax:"ARRAYCOMPACT(list)",summary:"The list without its empty items.",example:"ARRAYCOMPACT({Phone numbers})",group:"lists"},ARRAYFLATTEN:{syntax:"ARRAYFLATTEN(list1, [list2, ...])",summary:"One flat list of all the items, with lists inside lists opened up.",example:"ARRAYFLATTEN({Tags}, {Categories})",group:"lists"},ARRAYUNIQUE:{syntax:"ARRAYUNIQUE(list)",summary:"The list with each item only once.",example:"ARRAYUNIQUE({Order cities})",group:"lists"},ARRAYSLICE:{syntax:"ARRAYSLICE(list, start, [end])",summary:"The items from start to end (1 is the first; a negative number counts from the end).",example:"ARRAYSLICE({Tags}, 1, 3)",group:"lists"},SUM:{syntax:"SUM(number1, [number2, ...])",summary:"All the numbers added up.",example:"SUM({Subtotal}, {Shipping}, {Tax})",group:"numbers"},AVERAGE:{syntax:"AVERAGE(number1, [number2, ...])",summary:"The average of the numbers, leaving out empty ones.",example:"AVERAGE({Q1 sales}, {Q2 sales}, {Q3 sales})",group:"numbers"},MAX:{syntax:"MAX(number1, [number2, ...])",summary:"The largest of the numbers.",example:"MAX({Quote A}, {Quote B})",group:"numbers"},MIN:{syntax:"MIN(number1, [number2, ...])",summary:"The smallest of the numbers.",example:"MIN({Stock}, {Qty})",group:"numbers"},COUNT:{syntax:"COUNT(value1, [value2, ...])",summary:"How many of the values are numbers.",example:"COUNT({Mon hours}, {Tue hours}, {Wed hours})",group:"numbers"},COUNTA:{syntax:"COUNTA(value1, [value2, ...])",summary:"How many of the values are not empty.",example:"COUNTA({Phone}, {Email}, {Address})",group:"numbers"},COUNTALL:{syntax:"COUNTALL(value1, [value2, ...])",summary:"How many values there are, empty ones included.",example:"COUNTALL({Attendees})",group:"numbers"},ROUND:{syntax:"ROUND(number, [decimals])",summary:"The number rounded to that many decimal places (none if left out).",example:"ROUND({Qty} * {Unit price}, 2)",group:"numbers"},ROUNDUP:{syntax:"ROUNDUP(number, [decimals])",summary:"The number rounded away from zero to that many decimal places.",example:"ROUNDUP({Hours worked}, 0)",group:"numbers"},ROUNDDOWN:{syntax:"ROUNDDOWN(number, [decimals])",summary:"The number rounded toward zero to that many decimal places.",example:"ROUNDDOWN({Total} * 0.1, 2)",group:"numbers"},INT:{syntax:"INT(number)",summary:"The number rounded down to a whole number.",example:"INT({Hours worked})",group:"numbers"},ABS:{syntax:"ABS(number)",summary:"The number without its minus sign.",example:"ABS({Balance})",group:"numbers"},MOD:{syntax:"MOD(number, divisor)",summary:"What is left after dividing; it takes the sign of the first number.",example:"MOD({Qty}, 12)",group:"numbers"},POWER:{syntax:"POWER(number, power)",summary:"The number raised to the power.",example:"{Deposit} * POWER(1 + {Rate}, {Years})",group:"numbers"},SQRT:{syntax:"SQRT(number)",summary:"The square root of the number.",example:"SQRT({Floor area})",group:"numbers"},EXP:{syntax:"EXP(number)",summary:"The number e (about 2.718) raised to the power you give.",example:"{Deposit} * EXP({Rate} * {Years})",group:"numbers"},LOG:{syntax:"LOG(number, [base])",summary:"The logarithm of the number, in base 10 unless you give another base.",example:"LOG({Visitors}, 10)",group:"numbers"},EVEN:{syntax:"EVEN(number)",summary:"The number rounded away from zero to the next even whole number.",example:"EVEN({Guests})",group:"numbers"},ODD:{syntax:"ODD(number)",summary:"The number rounded away from zero to the next odd whole number.",example:"ODD({Team size})",group:"numbers"},CEILING:{syntax:"CEILING(number, [multiple])",summary:"The number rounded up to a multiple (1 if left out): CEILING(7, 5) is 10.",example:"CEILING({Qty}, 6)",group:"numbers"},FLOOR:{syntax:"FLOOR(number, [multiple])",summary:"The number rounded down to a multiple (1 if left out): FLOOR(7, 5) is 5.",example:"FLOOR({Price}, 0.5)",group:"numbers"},DISTANCE:{syntax:"DISTANCE(place, place)",summary:'Metres between two places given as coordinates ("42.6977, 23.3219"), as a phone saves them.',example:"DISTANCE({Where the phone was}, '42.6977, 23.3219')",group:"numbers"},TODAY:{syntax:"TODAY()",summary:"Today's date, at midnight.",example:'DATETIME_DIFF({Due date}, TODAY(), "days")',group:"dates"},NOW:{syntax:"NOW()",summary:"The date and time right now.",example:'DATETIME_DIFF(NOW(), {Created}, "hours")',group:"dates"},YEAR:{syntax:"YEAR(date)",summary:"The year of a date, such as 2026.",example:"YEAR({Invoice date})",group:"dates"},MONTH:{syntax:"MONTH(date)",summary:"The month of a date, from 1 (January) to 12 (December).",example:"MONTH({Invoice date})",group:"dates"},DAY:{syntax:"DAY(date)",summary:"The day of the month of a date, from 1 to 31.",example:"DAY({Due date})",group:"dates"},HOUR:{syntax:"HOUR(date)",summary:"The hour of a date and time, from 0 to 23.",example:"HOUR({Appointment})",group:"dates"},MINUTE:{syntax:"MINUTE(date)",summary:"The minute of a date and time, from 0 to 59.",example:"MINUTE({Appointment})",group:"dates"},SECOND:{syntax:"SECOND(date)",summary:"The second of a date and time, from 0 to 59.",example:"SECOND({Logged at})",group:"dates"},WEEKDAY:{syntax:"WEEKDAY(date, [first day])",summary:'The day of the week, 0 for Sunday to 6; with "Monday" as first day, 0 is Monday.',example:'WEEKDAY({Delivery date}, "Monday")',group:"dates"},WEEKNUM:{syntax:"WEEKNUM(date, [first day])",summary:'The week of the year (week 1 holds January 1); weeks start Sunday, or "Monday".',example:'WEEKNUM({Order date}, "Monday")',group:"dates"},DATEADD:{syntax:"DATEADD(date, count, [unit])",summary:"The date moved on by a number of days, weeks, months, years... (days if no unit).",example:'DATEADD({Invoice date}, 30, "days")',group:"dates"},DATETIME_DIFF:{syntax:"DATETIME_DIFF(date1, date2, [unit])",summary:"The time between two dates: the first minus the second, in days or another unit.",example:'DATETIME_DIFF({Due date}, TODAY(), "days")',group:"dates"},IS_BEFORE:{syntax:"IS_BEFORE(date1, date2)",summary:"True when the first date is before the second.",example:"IS_BEFORE({Due date}, TODAY())",group:"dates"},IS_AFTER:{syntax:"IS_AFTER(date1, date2)",summary:"True when the first date is after the second.",example:"IS_AFTER({Delivered on}, {Due date})",group:"dates"},IS_SAME:{syntax:"IS_SAME(date1, date2, [unit])",summary:"True when two dates are the same moment, or the same day, month, year... by unit.",example:'IS_SAME({Order date}, TODAY(), "month")',group:"dates"},DATESTR:{syntax:"DATESTR(date)",summary:"The date as text, year first: 2026-12-04.",example:"DATESTR({Due date})",group:"dates"},TIMESTR:{syntax:"TIMESTR(date)",summary:"The time of a date as text, in 24 hours: 14:30:00.",example:"TIMESTR({Appointment})",group:"dates"},DATETIME_FORMAT:{syntax:"DATETIME_FORMAT(date, [format])",summary:'The date as text in the format you write, such as "DD/MM/YYYY" or "MMMM D".',example:'DATETIME_FORMAT({Due date}, "DD/MM/YYYY")',group:"dates"},DATETIME_PARSE:{syntax:"DATETIME_PARSE(text, [format])",summary:"The date written in the text, read with the format if you give one.",example:'DATETIME_PARSE({Date text}, "DD.MM.YYYY")',group:"dates"},SET_LOCALE:{syntax:"SET_LOCALE(date, locale)",summary:'The date, set to show month and day names in a language, such as "fr" or "de".',example:'DATETIME_FORMAT(SET_LOCALE({Due date}, "fr"), "D MMMM YYYY")',group:"dates"},SET_TIMEZONE:{syntax:"SET_TIMEZONE(date, time zone)",summary:'The date, set to show the clock of a time zone, such as "Europe/London".',example:'DATETIME_FORMAT(SET_TIMEZONE({Appointment}, "Europe/London"), "HH:mm")',group:"dates"},TONOW:{syntax:"TONOW(date)",summary:"The number of days from the date to today.",example:"TONOW({Last contacted})",group:"dates"},FROMNOW:{syntax:"FROMNOW(date)",summary:"The number of days from today to the date.",example:"FROMNOW({Due date})",group:"dates"},WORKDAY:{syntax:"WORKDAY(start date, days, [holidays])",summary:"The date that many working days on, skipping weekends and the holidays.",example:'WORKDAY({Order date}, 5, "2026-12-25, 2026-12-26")',group:"dates"},WORKDAY_DIFF:{syntax:"WORKDAY_DIFF(start date, end date, [holidays])",summary:"The working days from start to end, both days counted, skipping the holidays.",example:'WORKDAY_DIFF({Start date}, {End date}, "2026-12-25")',group:"dates"}};export function syntaxArgs(e){const t=e.indexOf("("),a=e.lastIndexOf(")");return t<0||a<=t?[]:e.slice(t+1,a).replace(/[[\]]/g,"").split(",").map(s=>s.replace(/\.{3}|…/g,"").trim()).filter(Boolean)}