@svgrid/enterprise 3.1.74 → 3.1.75

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.
@@ -1538,7 +1538,7 @@ ${F}
1538
1538
  @keyframes st-home-spin { to { transform: rotate(360deg); } }
1539
1539
  </style>
1540
1540
  `}}function $S(t){for(let a of t)gs(a);let r=new Map(t.map(a=>[a.name,a])),n=t.map(a=>{let l=Pse(a,r);return{schema:jse(a,l),infos:l}});return{entries:n,seed:Use(n)}}function ID(t,r={}){let{entries:n,seed:a}=$S(t),{file:l,needs:i}=sde(n,a,r.sources,r.supabaseConn,r.serverMemory),o=[Vse(n),l];(i.supabase||r.supabaseAuth)&&!i.supabaseUrl&&(r.supabaseConn?.url||r.supabaseConn?.key)&&(i.supabaseUrl=r.supabaseConn.url,i.supabaseKey=r.supabaseConn.key),(i.supabase||r.supabaseAuth)&&o.push(dde(i));for(let s of i.sqlRoutes)o.push(Qse(s.schema,s.table,s.dialect,{access:r.accessEnabled,audit:r.auditEnabled,screenIds:r.screensByEntity?.get(s.schema.name)??[],triggers:r.triggers?.[s.schema.name],dbSchema:s.dbSchema,tenantField:r.tenantField&&r.tenantScoped?.(s.schema.name)!==!1?r.tenantField:void 0}));if(i.memoryRoutes.length){o.push(tde(i.memoryRoutes));for(let s of i.memoryRoutes)o.push(ede(s.schema,{access:r.accessEnabled,audit:r.auditEnabled,screenIds:r.screensByEntity?.get(s.schema.name)??[],triggers:r.triggers?.[s.schema.name],tenantField:r.tenantField&&r.tenantScoped?.(s.schema.name)!==!1?r.tenantField:void 0}))}return{files:o,prepared:n.map(s=>s.schema)}}function ude(t){if(t.length===0)throw Error("emitStudioApp: no schemas to emit");let{files:r,prepared:n}=ID(t),a=n.map(i=>{let o=Ua(i);return{href:`/${o.route}`,label:o.label}}),l={path:"src/custom.css",description:"Your custom styles (imported after app.css so it overrides).",userOwned:!0,contents:`/* Your custom styles. Imported after app.css, so these rules override the defaults. */
1541
- `};return[...r,...n.map(i=>cde(i)),ED(a),RD(a),l]}var pde="3.1.74",gde="3.0.43",ml=(t,r)=>t.some(n=>n.config.kind===r),DD=t=>`activeTab_${t.replace(/[^a-zA-Z0-9_$]/g,"_")}`,ev=(t,r)=>`${t}-${r}`,ND=t=>`accOpen_${t.replace(/[^a-zA-Z0-9_$]/g,"_")}`,tv=(t,r)=>`${t}-s${r}`,rv=t=>`md_${t.replace(/[^a-zA-Z0-9]/g,"_")}_rows`;function fde(t){switch(t.type){case"number":{let r=t.decimals;return r==null?"{ type: 'number' }":`{ type: 'number', options: { minimumFractionDigits: ${r}, maximumFractionDigits: ${r} } }`}case"currency":return`{ type: 'currency', currency: ${Qr(t.currency||"USD")} }`;case"percent":{let r=["type: 'percent'"];return t.valueIsPercentPoints&&r.push("valueIsPercentPoints: true"),t.decimals!=null&&r.push(`options: { minimumFractionDigits: ${t.decimals}, maximumFractionDigits: ${t.decimals} }`),`{ ${r.join(", ")} }`}case"date":case"datetime":return t.pattern?`{ type: '${t.type}', pattern: ${Qr(t.pattern)} }`:`{ type: '${t.type}' }`}}function hde(t,r,n,a){if(r.config.kind!=="grid")return`schemaToColumns(${t})`;let l=r.config,i=r.id.replace(/-/g,"_"),o=l.columns.filter(y=>y.show),s=new Set(o.map(y=>y.field)),c=new Set,d=o.map(y=>{let w=a?.get(y.field);return{c:y,col:w&&!s.has(w)?w:y.field}}).filter(y=>!c.has(y.col)&&!!c.add(y.col)),p=l.editing==="inline"?"":", editable: false";if(d.length===0)return p?`schemaToColumns(${t}).map((c) => ({ ...c${p} }))`:`schemaToColumns(${t})`;let u=d.map(y=>`'${y.col}'`),f=d.map(({c:y,col:w})=>{let v=[];return y.header&&v.push(`header: ${JSON.stringify(y.header)}`),y.width!=null&&v.push(`width: ${y.width}`),y.align&&v.push(`align: '${y.align}'`),y.aggregate&&v.push(`aggregate: '${y.aggregate}'`),l.treeData&&y.field===l.treeData.labelField&&n?v.push(`cell: (ctx: CellContext<${n}>) => renderSnippet(treeCell_${i}, { value: ctx.getValue(), row: ctx.row.original })`):y.cellType&&n?v.push(`cell: (ctx: CellContext<${n}>) => renderSnippet(${jD(i,y.field)}, { value: ctx.getValue() })`):y.format&&v.push(`format: ${fde(y.format)}`),v.length?`'${w}': { ${v.join(", ")} }`:null}).filter(y=>!!y),b=f.length?` const ov: Record<string, Partial<(typeof all)[number]>> = { ${f.join(", ")} };`:"",h=f.length?", ...(ov[String(c.field)] ?? {})":"",S=`[${u.join(", ")}].map((f) => all.find((c) => c.field === f)).filter((c): c is (typeof all)[number] => !!c)`;return`(() => { const all = schemaToColumns(${t});${b} return ${p||h?`${S}.map((c) => ({ ...c${p}${h} }))`:S} })()`}function ic(t,r){let n=[`grid-column: span ${foe(t)}`,"min-width: 0"];r&&n.push(r);let a=moe(t.style);return a&&n.push(a),`style="${n.join("; ")}"`}var mde=t=>t&&t.replace(/[^#a-zA-Z0-9(),.%\s_-]/g,"").slice(0,40)||"var(--sg-accent)";function Lu(t,r){let n=[r,goe(t)].filter(Boolean).join(" ");return n?` class="${n}"`:""}function n1(t){let r=cS(t.className);return r?` ${r}`:""}function vde(t){let r=If(t);if(r==="grid"){let n=Roe(t),a=n.maxWidth?` max-width: ${n.maxWidth}px; margin-inline: auto;`:"";return` .st-screen { grid-template-columns: repeat(12, 1fr); gap: ${n.rowGap}px ${n.colGap}px; align-items: ${n.align};${a} }
1541
+ `};return[...r,...n.map(i=>cde(i)),ED(a),RD(a),l]}var pde="3.1.75",gde="3.0.43",ml=(t,r)=>t.some(n=>n.config.kind===r),DD=t=>`activeTab_${t.replace(/[^a-zA-Z0-9_$]/g,"_")}`,ev=(t,r)=>`${t}-${r}`,ND=t=>`accOpen_${t.replace(/[^a-zA-Z0-9_$]/g,"_")}`,tv=(t,r)=>`${t}-s${r}`,rv=t=>`md_${t.replace(/[^a-zA-Z0-9]/g,"_")}_rows`;function fde(t){switch(t.type){case"number":{let r=t.decimals;return r==null?"{ type: 'number' }":`{ type: 'number', options: { minimumFractionDigits: ${r}, maximumFractionDigits: ${r} } }`}case"currency":return`{ type: 'currency', currency: ${Qr(t.currency||"USD")} }`;case"percent":{let r=["type: 'percent'"];return t.valueIsPercentPoints&&r.push("valueIsPercentPoints: true"),t.decimals!=null&&r.push(`options: { minimumFractionDigits: ${t.decimals}, maximumFractionDigits: ${t.decimals} }`),`{ ${r.join(", ")} }`}case"date":case"datetime":return t.pattern?`{ type: '${t.type}', pattern: ${Qr(t.pattern)} }`:`{ type: '${t.type}' }`}}function hde(t,r,n,a){if(r.config.kind!=="grid")return`schemaToColumns(${t})`;let l=r.config,i=r.id.replace(/-/g,"_"),o=l.columns.filter(y=>y.show),s=new Set(o.map(y=>y.field)),c=new Set,d=o.map(y=>{let w=a?.get(y.field);return{c:y,col:w&&!s.has(w)?w:y.field}}).filter(y=>!c.has(y.col)&&!!c.add(y.col)),p=l.editing==="inline"?"":", editable: false";if(d.length===0)return p?`schemaToColumns(${t}).map((c) => ({ ...c${p} }))`:`schemaToColumns(${t})`;let u=d.map(y=>`'${y.col}'`),f=d.map(({c:y,col:w})=>{let v=[];return y.header&&v.push(`header: ${JSON.stringify(y.header)}`),y.width!=null&&v.push(`width: ${y.width}`),y.align&&v.push(`align: '${y.align}'`),y.aggregate&&v.push(`aggregate: '${y.aggregate}'`),l.treeData&&y.field===l.treeData.labelField&&n?v.push(`cell: (ctx: CellContext<${n}>) => renderSnippet(treeCell_${i}, { value: ctx.getValue(), row: ctx.row.original })`):y.cellType&&n?v.push(`cell: (ctx: CellContext<${n}>) => renderSnippet(${jD(i,y.field)}, { value: ctx.getValue() })`):y.format&&v.push(`format: ${fde(y.format)}`),v.length?`'${w}': { ${v.join(", ")} }`:null}).filter(y=>!!y),b=f.length?` const ov: Record<string, Partial<(typeof all)[number]>> = { ${f.join(", ")} };`:"",h=f.length?", ...(ov[String(c.field)] ?? {})":"",S=`[${u.join(", ")}].map((f) => all.find((c) => c.field === f)).filter((c): c is (typeof all)[number] => !!c)`;return`(() => { const all = schemaToColumns(${t});${b} return ${p||h?`${S}.map((c) => ({ ...c${p}${h} }))`:S} })()`}function ic(t,r){let n=[`grid-column: span ${foe(t)}`,"min-width: 0"];r&&n.push(r);let a=moe(t.style);return a&&n.push(a),`style="${n.join("; ")}"`}var mde=t=>t&&t.replace(/[^#a-zA-Z0-9(),.%\s_-]/g,"").slice(0,40)||"var(--sg-accent)";function Lu(t,r){let n=[r,goe(t)].filter(Boolean).join(" ");return n?` class="${n}"`:""}function n1(t){let r=cS(t.className);return r?` ${r}`:""}function vde(t){let r=If(t);if(r==="grid"){let n=Roe(t),a=n.maxWidth?` max-width: ${n.maxWidth}px; margin-inline: auto;`:"";return` .st-screen { grid-template-columns: repeat(12, 1fr); gap: ${n.rowGap}px ${n.colGap}px; align-items: ${n.align};${a} }
1542
1542
  @media (max-width: ${n.mobileBreakpoint}px) { .st-screen { grid-template-columns: 1fr; gap: 12px; } }
1543
1543
  `}if(r==="stack"){let n=Ioe(t),a=n.maxWidth?` max-width: ${n.maxWidth}px;${n.align==="center"?" margin-inline: auto;":""}`:"",l=n.minHeight?`
1544
1544
  .st-stack > * { min-height: ${n.minHeight}px; }`:"",i=n.dividers?`
@@ -76332,7 +76332,7 @@ ${st}
76332
76332
  .st-home a { color: var(--sg-accent, #6366f1); font-weight: 600; }
76333
76333
  @keyframes st-home-spin { to { transform: rotate(360deg); } }
76334
76334
  </style>
76335
- `}}function s2e(a){for(let p of a)G4(p);let i=new Map(a.map(p=>[p.name,p])),l=a.map(p=>{let f=kpr(p,i);return{schema:Ppr(p,f),infos:f}});return{entries:l,seed:Cpr(l)}}function rur(a,i={}){let{entries:l,seed:p}=s2e(a),{file:f,needs:g}=Ypr(l,p,i.sources,i.supabaseConn,i.serverMemory),_=[Opr(l),f];(g.supabase||i.supabaseAuth)&&!g.supabaseUrl&&(i.supabaseConn?.url||i.supabaseConn?.key)&&(g.supabaseUrl=i.supabaseConn.url,g.supabaseKey=i.supabaseConn.key),(g.supabase||i.supabaseAuth)&&_.push(Zpr(g));for(let S of g.sqlRoutes)_.push(Upr(S.schema,S.table,S.dialect,{access:i.accessEnabled,audit:i.auditEnabled,screenIds:i.screensByEntity?.get(S.schema.name)??[],triggers:i.triggers?.[S.schema.name],dbSchema:S.dbSchema,tenantField:i.tenantField&&i.tenantScoped?.(S.schema.name)!==!1?i.tenantField:void 0}));if(g.memoryRoutes.length){_.push(Hpr(g.memoryRoutes));for(let S of g.memoryRoutes)_.push(Vpr(S.schema,{access:i.accessEnabled,audit:i.auditEnabled,screenIds:i.screensByEntity?.get(S.schema.name)??[],triggers:i.triggers?.[S.schema.name],tenantField:i.tenantField&&i.tenantScoped?.(S.schema.name)!==!1?i.tenantField:void 0}))}return{files:_,prepared:l.map(S=>S.schema)}}var nur="3.1.74",our="3.0.43",sb=(a,i)=>a.some(l=>l.config.kind===i),qit=a=>`activeTab_${a.replace(/[^a-zA-Z0-9_$]/g,"_")}`,XZ=(a,i)=>`${a}-${i}`,Kit=a=>`accOpen_${a.replace(/[^a-zA-Z0-9_$]/g,"_")}`,JZ=(a,i)=>`${a}-s${i}`,YZ=a=>`md_${a.replace(/[^a-zA-Z0-9]/g,"_")}_rows`;function aur(a){switch(a.type){case"number":{let i=a.decimals;return i==null?"{ type: 'number' }":`{ type: 'number', options: { minimumFractionDigits: ${i}, maximumFractionDigits: ${i} } }`}case"currency":return`{ type: 'currency', currency: ${cu(a.currency||"USD")} }`;case"percent":{let i=["type: 'percent'"];return a.valueIsPercentPoints&&i.push("valueIsPercentPoints: true"),a.decimals!=null&&i.push(`options: { minimumFractionDigits: ${a.decimals}, maximumFractionDigits: ${a.decimals} }`),`{ ${i.join(", ")} }`}case"date":case"datetime":return a.pattern?`{ type: '${a.type}', pattern: ${cu(a.pattern)} }`:`{ type: '${a.type}' }`}}function iur(a,i,l,p){if(i.config.kind!=="grid")return`schemaToColumns(${a})`;let f=i.config,g=i.id.replace(/-/g,"_"),_=f.columns.filter(be=>be.show),S=new Set(_.map(be=>be.field)),A=new Set,k=_.map(be=>{let Be=p?.get(be.field);return{c:be,col:Be&&!S.has(Be)?Be:be.field}}).filter(be=>!A.has(be.col)&&!!A.add(be.col)),L=f.editing==="inline"?"":", editable: false";if(k.length===0)return L?`schemaToColumns(${a}).map((c) => ({ ...c${L} }))`:`schemaToColumns(${a})`;let F=k.map(be=>`'${be.col}'`),ee=k.map(({c:be,col:Be})=>{let Ue=[];return be.header&&Ue.push(`header: ${JSON.stringify(be.header)}`),be.width!=null&&Ue.push(`width: ${be.width}`),be.align&&Ue.push(`align: '${be.align}'`),be.aggregate&&Ue.push(`aggregate: '${be.aggregate}'`),f.treeData&&be.field===f.treeData.labelField&&l?Ue.push(`cell: (ctx: CellContext<${l}>) => renderSnippet(treeCell_${g}, { value: ctx.getValue(), row: ctx.row.original })`):be.cellType&&l?Ue.push(`cell: (ctx: CellContext<${l}>) => renderSnippet(${est(g,be.field)}, { value: ctx.getValue() })`):be.format&&Ue.push(`format: ${aur(be.format)}`),Ue.length?`'${Be}': { ${Ue.join(", ")} }`:null}).filter(be=>!!be),J=ee.length?` const ov: Record<string, Partial<(typeof all)[number]>> = { ${ee.join(", ")} };`:"",te=ee.length?", ...(ov[String(c.field)] ?? {})":"",Ie=`[${F.join(", ")}].map((f) => all.find((c) => c.field === f)).filter((c): c is (typeof all)[number] => !!c)`;return`(() => { const all = schemaToColumns(${a});${J} return ${L||te?`${Ie}.map((c) => ({ ...c${L}${te} }))`:Ie} })()`}function eW(a,i){let l=[`grid-column: span ${yM(a)}`,"min-width: 0"];i&&l.push(i);let p=vit(a.style);return p&&l.push(p),`style="${l.join("; ")}"`}var sur=a=>a&&a.replace(/[^#a-zA-Z0-9(),.%\s_-]/g,"").slice(0,40)||"var(--sg-accent)";function z8(a,i){let l=[i,LH(a)].filter(Boolean).join(" ");return l?` class="${l}"`:""}function ofe(a){let i=WZ(a.className);return i?` ${i}`:""}function lur(a){let i=iR(a);if(i==="grid"){let l=qDe(a),p=l.maxWidth?` max-width: ${l.maxWidth}px; margin-inline: auto;`:"";return` .st-screen { grid-template-columns: repeat(12, 1fr); gap: ${l.rowGap}px ${l.colGap}px; align-items: ${l.align};${p} }
76335
+ `}}function s2e(a){for(let p of a)G4(p);let i=new Map(a.map(p=>[p.name,p])),l=a.map(p=>{let f=kpr(p,i);return{schema:Ppr(p,f),infos:f}});return{entries:l,seed:Cpr(l)}}function rur(a,i={}){let{entries:l,seed:p}=s2e(a),{file:f,needs:g}=Ypr(l,p,i.sources,i.supabaseConn,i.serverMemory),_=[Opr(l),f];(g.supabase||i.supabaseAuth)&&!g.supabaseUrl&&(i.supabaseConn?.url||i.supabaseConn?.key)&&(g.supabaseUrl=i.supabaseConn.url,g.supabaseKey=i.supabaseConn.key),(g.supabase||i.supabaseAuth)&&_.push(Zpr(g));for(let S of g.sqlRoutes)_.push(Upr(S.schema,S.table,S.dialect,{access:i.accessEnabled,audit:i.auditEnabled,screenIds:i.screensByEntity?.get(S.schema.name)??[],triggers:i.triggers?.[S.schema.name],dbSchema:S.dbSchema,tenantField:i.tenantField&&i.tenantScoped?.(S.schema.name)!==!1?i.tenantField:void 0}));if(g.memoryRoutes.length){_.push(Hpr(g.memoryRoutes));for(let S of g.memoryRoutes)_.push(Vpr(S.schema,{access:i.accessEnabled,audit:i.auditEnabled,screenIds:i.screensByEntity?.get(S.schema.name)??[],triggers:i.triggers?.[S.schema.name],tenantField:i.tenantField&&i.tenantScoped?.(S.schema.name)!==!1?i.tenantField:void 0}))}return{files:_,prepared:l.map(S=>S.schema)}}var nur="3.1.75",our="3.0.43",sb=(a,i)=>a.some(l=>l.config.kind===i),qit=a=>`activeTab_${a.replace(/[^a-zA-Z0-9_$]/g,"_")}`,XZ=(a,i)=>`${a}-${i}`,Kit=a=>`accOpen_${a.replace(/[^a-zA-Z0-9_$]/g,"_")}`,JZ=(a,i)=>`${a}-s${i}`,YZ=a=>`md_${a.replace(/[^a-zA-Z0-9]/g,"_")}_rows`;function aur(a){switch(a.type){case"number":{let i=a.decimals;return i==null?"{ type: 'number' }":`{ type: 'number', options: { minimumFractionDigits: ${i}, maximumFractionDigits: ${i} } }`}case"currency":return`{ type: 'currency', currency: ${cu(a.currency||"USD")} }`;case"percent":{let i=["type: 'percent'"];return a.valueIsPercentPoints&&i.push("valueIsPercentPoints: true"),a.decimals!=null&&i.push(`options: { minimumFractionDigits: ${a.decimals}, maximumFractionDigits: ${a.decimals} }`),`{ ${i.join(", ")} }`}case"date":case"datetime":return a.pattern?`{ type: '${a.type}', pattern: ${cu(a.pattern)} }`:`{ type: '${a.type}' }`}}function iur(a,i,l,p){if(i.config.kind!=="grid")return`schemaToColumns(${a})`;let f=i.config,g=i.id.replace(/-/g,"_"),_=f.columns.filter(be=>be.show),S=new Set(_.map(be=>be.field)),A=new Set,k=_.map(be=>{let Be=p?.get(be.field);return{c:be,col:Be&&!S.has(Be)?Be:be.field}}).filter(be=>!A.has(be.col)&&!!A.add(be.col)),L=f.editing==="inline"?"":", editable: false";if(k.length===0)return L?`schemaToColumns(${a}).map((c) => ({ ...c${L} }))`:`schemaToColumns(${a})`;let F=k.map(be=>`'${be.col}'`),ee=k.map(({c:be,col:Be})=>{let Ue=[];return be.header&&Ue.push(`header: ${JSON.stringify(be.header)}`),be.width!=null&&Ue.push(`width: ${be.width}`),be.align&&Ue.push(`align: '${be.align}'`),be.aggregate&&Ue.push(`aggregate: '${be.aggregate}'`),f.treeData&&be.field===f.treeData.labelField&&l?Ue.push(`cell: (ctx: CellContext<${l}>) => renderSnippet(treeCell_${g}, { value: ctx.getValue(), row: ctx.row.original })`):be.cellType&&l?Ue.push(`cell: (ctx: CellContext<${l}>) => renderSnippet(${est(g,be.field)}, { value: ctx.getValue() })`):be.format&&Ue.push(`format: ${aur(be.format)}`),Ue.length?`'${Be}': { ${Ue.join(", ")} }`:null}).filter(be=>!!be),J=ee.length?` const ov: Record<string, Partial<(typeof all)[number]>> = { ${ee.join(", ")} };`:"",te=ee.length?", ...(ov[String(c.field)] ?? {})":"",Ie=`[${F.join(", ")}].map((f) => all.find((c) => c.field === f)).filter((c): c is (typeof all)[number] => !!c)`;return`(() => { const all = schemaToColumns(${a});${J} return ${L||te?`${Ie}.map((c) => ({ ...c${L}${te} }))`:Ie} })()`}function eW(a,i){let l=[`grid-column: span ${yM(a)}`,"min-width: 0"];i&&l.push(i);let p=vit(a.style);return p&&l.push(p),`style="${l.join("; ")}"`}var sur=a=>a&&a.replace(/[^#a-zA-Z0-9(),.%\s_-]/g,"").slice(0,40)||"var(--sg-accent)";function z8(a,i){let l=[i,LH(a)].filter(Boolean).join(" ");return l?` class="${l}"`:""}function ofe(a){let i=WZ(a.className);return i?` ${i}`:""}function lur(a){let i=iR(a);if(i==="grid"){let l=qDe(a),p=l.maxWidth?` max-width: ${l.maxWidth}px; margin-inline: auto;`:"";return` .st-screen { grid-template-columns: repeat(12, 1fr); gap: ${l.rowGap}px ${l.colGap}px; align-items: ${l.align};${p} }
76336
76336
  @media (max-width: ${l.mobileBreakpoint}px) { .st-screen { grid-template-columns: 1fr; gap: 12px; } }
76337
76337
  `}if(i==="stack"){let l=que(a),p=l.maxWidth?` max-width: ${l.maxWidth}px;${l.align==="center"?" margin-inline: auto;":""}`:"",f=l.minHeight?`
76338
76338
  .st-stack > * { min-height: ${l.minHeight}px; }`:"",g=l.dividers?`
@@ -4,7 +4,7 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>SvGrid Studio - Designer</title>
7
- <script type="module" crossorigin src="./assets/index-C2M7tfqh.js"></script>
7
+ <script type="module" crossorigin src="./assets/index-BOF2h-Nd.js"></script>
8
8
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-Dd_uD5pT.js">
9
9
  <link rel="modulepreload" crossorigin href="./assets/index-client-CwjHmKgT.js">
10
10
  <link rel="modulepreload" crossorigin href="./assets/disclose-version-xihTtKlq.js">
@@ -170,7 +170,8 @@ import{safeColor}from"./palette";import{primaryOf}from"./base-tables";import{get
170
170
  {#each writableFields(table).filter((c) => TEXT_TYPES.has(String(c.fieldType ?? 'text'))) as c (c.id)}<option value={c.id}>{c.header}</option>{/each}
171
171
  </select>
172
172
  </div>
173
- <p class="sv-baac-hint">{bm('extras.aiHint')}</p>
173
+ <label class="sv-baac-row sv-baac-whole"><input type="checkbox" checked={!!action.base} onchange={(e) => onChange({ ...action, base: e.currentTarget.checked || undefined })} /> {bm('extras.aiBase')}</label>
174
+ <p class="sv-baac-hint">{bm('extras.aiHint')}{action.base ? ' ' + bm('extras.aiBaseHint') : ''}</p>
174
175
  {:else if action.type === 'script'}
175
176
  {#if serverSide && !scriptsInPage}<p class="sv-baac-hint sv-baac-bad">{bm('extras.scriptNeedsBrowser')}</p>{/if}
176
177
  <textarea class="sv-fvb-input sv-baac-text sv-baac-mono sv-baac-code" aria-label={bm('extras.scriptCode')} rows="14" spellcheck="false" value={action.code} onchange={(e) => onChange({ ...action, code: e.currentTarget.value })}></textarea>
@@ -128,7 +128,8 @@ export type AutomationAction =
128
128
  | {
129
129
  type: 'ai';
130
130
  prompt: string;
131
- field?: string;
131
+ field?: string; /** The server sends every table's records with the prompt. */
132
+ base?: boolean;
132
133
  }
133
134
  /**
134
135
  * Run JavaScript in a sandbox in the browser (automation-script.ts):
@@ -194,6 +195,13 @@ export declare function tableFields(t: BaseTable): Map<string, FieldColumn>;
194
195
  export type RunValues = Map<string, string>;
195
196
  /** `{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. */
196
197
  export declare function fillTokens(t: BaseTable, record: Row | null, template: string, values?: RunValues): string;
198
+ /**
199
+ * Every table's records as text, for an AI step sent the whole base: a heading
200
+ * per table, then a line per record ("- Name | Field: value | ..."), names for
201
+ * links and options. Past `most` characters each table keeps a fair share (what
202
+ * a small table leaves goes to the bigger ones) and says how many it shows. Files, buttons and empty values are left out.
203
+ */
204
+ export declare function baseText(tables: ReadonlyArray<BaseTable>, most?: number): string;
197
205
  /** The filter of a table's view, when it has one a record can be tested against. */
198
206
  export declare function viewFilterOf(t: BaseTable, viewId: string | undefined): FieldFilter | null;
199
207
  /** Whether a record matches a condition (no condition matches every record). */
@@ -1 +1,6 @@
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
+ 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 baseText(tables,most=6e4){const SKIP=new Set(["attachment","button","richText","createdBy","lastModifiedBy"]);const parts=tables.slice(0,20).map(t=>{const fields=[...tableFields(t).values()].filter(c=>!SKIP.has(String(c.fieldType??"text")));const lines=[];for(const r of t.data??[]){const cells=[];for(const c of fields){let v=fieldText(c,r);if(!v||c.fieldType==="checkbox"&&v==="false")continue;v=(v.length>300?v.slice(0,297)+"...":v).replace(/\s+/g," ");cells.push(c.field===t.primaryField?v:`${c.header}: ${v}`)}if(cells.length)lines.push("- "+cells.join(" | "))}return{name:t.name,lines}});const sizes=parts.map((p,i)=>({i,size:p.lines.reduce((n,line)=>n+line.length+1,0)})).sort((a,b)=>a.size-b.size);const budget=[];let left=most;sizes.forEach(({i,size},k)=>{budget[i]=Math.min(size,Math.floor(left/Math.max(1,sizes.length-k)));left-=budget[i]});return parts.map((p,i)=>{const kept=[];let size=0;for(const line of p.lines){if(size+line.length+1>budget[i])break;kept.push(line);size+=line.length+1}const left2=p.lines.length-kept.length;return`## ${p.name} (${p.lines.length} records${left2>0?`, the first ${kept.length} shown`:""})
2
+ ${kept.join("\n")}`}).join("\n\n")}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"));let prompt=fillTokens(t,rec,action.prompt,values).trim();if(!prompt)throw new Error(bm("extras.aiNoPrompt"));if(action.base)prompt+=`
3
+
4
+ Today is ${ctx.now.toDateString()}. The base now:
5
+
6
+ ${baseText(options.getTables()??[])}`;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
- import{fillFieldColumn as O}from"./registry.svelte.js";import Ae from"./RatingCell.svelte";import N from"./LinkCell.svelte";import Ve from"./AttachmentCell.svelte";import Fe from"./CheckboxCell.svelte";import re from"./PercentCell.svelte";import B from"./UserCell.svelte";import Ie from"./ButtonCell.svelte";import Le from"./BarcodeCell.svelte";import Oe from"./LinkedRecordsCell.svelte";import Ne from"./RichTextCell.svelte";import Be from"./RichHtmlCell.svelte";import{richPlain as A}from"./rich-html.js";import{toRichHtml as Re}from"./rich-html-write.js";import le from"./SelectCell.svelte";import Ee from"./ChecklistCell.svelte";import He from"./ColorCell.svelte";import{attachmentsText as Ue,parseAttachments as _e}from"./attachments.js";import{dateEditTokens as ze,dateFromParts as R,exactNumber as We,formatCurrency as ie,formatDate as E,formatDuration as ne,formatNumber as H,formatPercent as oe,numberFieldShape as ae,numberFromText as Ge,numberKind as je,parseDateText as $e,parseDuration as V,toNumber as U}from"./format.js";import{BRIGHT as se,CHECKBOX_ICONS as xe,RATING_ICONS as Ke}from"./palette.js";import{COMPUTED_TYPES as Ye,ROLLUPS as _,fieldNameMap as Xe}from"./rollups.js";import{sparklineValues as z,voteCount as ue,voteIds as Ze}from"./vote.js";import qe from"./VoteCell.svelte";import Je from"./TimerCell.svelte";import{timerSeconds as F,timerTotal as Qe}from"./timer.js";import et from"./SparklineCell.svelte";import{compileFormula as tt,isoDate as rt,selfReferenceError as lt}from"./formula.js";import{findFieldUser as ce,getCurrentUser as de,getFieldUsers as W,getLinkedTable as T,idOf as it,linkedRows as G,listLinkedTables as nt,liveLink as ot,recordsNaming as at,resolveLinkId as st,resolveLinkIds as ut}from"./sources.svelte.js";import{splitNames as j}from"./name-list.js";import{linkedFields as ct}from"./linked-fields.js";import{AI_FIELD_TYPE as dt}from"./ai-field.svelte.js";import{CHECKLIST_GROUPS as pe,checklistGroup as pt,checklistSortValue as ft,checklistText as mt,parseChecklist as gt,toChecklist as ht}from"./checklist.js";import{colorSortValue as bt,parseColor as $}from"./color-value.js";import{formatTimeOfDay as yt,parseTimeOfDay as fe,timeSeconds as kt}from"./time-of-day.js";import{bm as l}from"./messages.svelte.js";import{BUTTON_ACTIONS as Tt,buttonAction as b,fillButtonTokens as wt,isLinkTemplate as vt}from"./button.js";import{recordActionsFor as me}from"./record-actions.js";const St=new Set(["user","createdBy","lastModifiedBy"]);function Mt(e){const t=String(e.field??e.id),r=o=>o.length===1?o[0]:o;if(St.has(String(e.fieldType)))return o=>{const n=o?.[t];return n==null||n===""?n:r((Array.isArray(n)?n:[n]).map(a=>ce(a)?.name??a))};if(e.fieldType!=="link")return null;const i=e.fieldProps?.table;return o=>{const n=o?.[t],a=T(i);if(!a||n==null||n==="")return n;const p=x(a,a.primaryField),d=new Map(G(a,n).map(f=>[it(a,f),p(f)]));return r((Array.isArray(n)?n:[n]).map(f=>d.get(String(f))??f))}}const ge=new WeakMap;let M=0;function x(e,t){const r=n=>n?.[t];if(!e?.fields?.length)return r;let i=ge.get(e.fields);if(i||ge.set(e.fields,i=new Map),!i.has(t)){const n=ct(e).find(p=>p.def.field===t),a=n?.def.fieldType==="timer"?p=>F(p?.[t]):null;i.set(t,a??n?.def.fieldFn??null)}const o=i.get(t);return o?n=>{if(M>3)return r(n);M+=1;try{return o(n)}finally{M-=1}}:r}const s={text:"M4 6h16M4 12h10M4 18h7",longText:"M4 6h16M4 10h16M4 14h16M4 18h10",richText:"M6 4h7a4 4 0 0 1 0 8H6zM6 12h8a4 4 0 0 1 0 8H6zM6 4v16",vote:"M12 19V5M5 12l7-7 7 7",sparkline:"M3 17l5-6 4 4 8-9",number:"M9 4 7 20M17 4l-2 16M4 9h16M3 15h16",currency:"M12 3v18M16 7.5C16 5.6 14.2 4.5 12 4.5S8 5.6 8 7.5s1.8 2.7 4 3.5 4 1.6 4 3.5-1.8 3-4 3-4-1.1-4-3",percent:"M19 5 5 19M7 7h.01M17 17h.01",date:"M4 6h16v14H4zM4 10h16M8 3v4M16 3v4",duration:"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zM12 8v4l3 2",timer:"M12 7a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM12 10v4l2.5 1.5M9.5 2.5h5M12 2.5V5",checkbox:"M4 4h16v16H4zM8 12l3 3 5-6",singleSelect:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM8 11l4 4 4-4",multiSelect:"M3 7h11M3 12h11M3 17h11M17 6l2 2 3-3M17 16l2 2 3-3",rating:"M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3 6.5 20.2l1-6.2L3 9.6l6.2-.9z",url:"M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1",email:"M3 6h18v12H3zM3 7l9 6 9-6",phone:"M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2",attachment:"M20 11.5 12.3 19a5 5 0 0 1-7.1-7.1l7.8-7.8a3.3 3.3 0 0 1 4.7 4.7L9.9 16.6a1.7 1.7 0 0 1-2.4-2.4l7.1-7",user:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0",createdTime:"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zM12 8v4h4",modifiedTime:"M4 12a8 8 0 1 0 2.3-5.7M4 4v4h4M12 8v4l3 2",createdBy:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 11-7.5M19 15v6M16 18h6",modifiedBy:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 11-7.5M16 21l5-5-2-2-5 5v2z",autoNumber:"M5 7h3v10M11 9a2 2 0 1 1 4 0c0 2-4 3-4 6h4M18 7h2v10",barcode:"M4 5v14M7 5v14M10 5v14M13 5v14M15 5v14M18 5v14M20 5v14",button:"M4 7h16v10H4zM9 12h6",formula:"M7 20c2 0 2.5-2 3-5l2-10c.5-2 1.5-2 3-2M8 9h7",link:"M9 7H6a5 5 0 0 0 0 10h3M15 7h3a5 5 0 0 1 0 10h-3M8 12h8",lookup:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4M8 11h6",rollup:"M6 4h12L12 12l6 8H6",count:"M5 5h14v14H5zM9 9v6M12 9v6M15 9v6",checklist:"M3.5 6l1.5 1.5L7.5 5M3.5 12l1.5 1.5 2.5-2.5M3.5 18l1.5 1.5 2.5-2.5M11 6h9M11 12h9M11 18h9",color:"M12 3a9 9 0 1 0 0 18c1 0 1.6-.7 1.6-1.6 0-1-.8-1.4-.8-2.3 0-1 .8-1.7 1.8-1.7H17a4 4 0 0 0 4-4C21 6.6 17 3 12 3zM7.5 12h.01M9.5 7.5h.01M14.5 7.5h.01",timeOfDay:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 7v5l-3 2M12 3v2M21 12h-2M12 21v-2M3 12h2"},u=(e,t)=>({value:e,get label(){return l(t)}}),Ct={link:"fields.buttonActionLink",automation:"fields.buttonActionAutomation",update:"fields.buttonActionUpdate",template:"fields.buttonActionTemplate",recordAction:"fields.buttonActionRecordAction",copy:"fields.buttonActionCopy",duplicate:"fields.buttonActionDuplicate",delete:"fields.buttonActionDelete",open:"fields.buttonActionOpen"};function Pt(e){const t=!!e.ctrl?.props?.baseButton,r=b(e.props),i=o=>o===r||o==="link"||o==="copy"?!0:t?o==="template"?(e.ctrl?.props?.baseRecordTemplates?.()??[]).length>0:o==="recordAction"?me(e.ctrl?.props?.baseTableId).length>0:!0:!1;return Tt.filter(i).map(o=>u(o,Ct[o]))}const he=e=>e?{visible:e}:{},Dt={key:"separators",get label(){return l("fields.propSeparators")},kind:"choice",choices:[u("local","fields.choiceLocal"),{value:"comma-period",label:"1,000,000.00"},{value:"period-comma",label:"1.000.000,00"},{value:"space-comma",label:"1 000 000,00"},{value:"space-period",label:"1 000 000.00"}]},At={key:"showThousands",get label(){return l("fields.propShowThousands")},kind:"checkbox"},Vt=e=>({key:"abbreviation",get label(){return l("fields.propAbbreviation")},kind:"choice",choices:[u("none","fields.choiceNone"),u("thousand","fields.choiceThousand"),u("million","fields.choiceMillion"),u("billion","fields.choiceBillion")],...he(e)}),Ft={key:"allowNegative",get label(){return l("fields.propAllowNegative")},kind:"checkbox"},w={key:"default",get label(){return l("fields.propDefault")},kind:"default",get hint(){return l("fields.propDefaultHint")}},K=(e,t)=>Array.from({length:t-e+1},(r,i)=>{const o=e+i;return{value:String(o),label:o===0?"1":`1.${"0".repeat(o)}`}}),Y=(e,t)=>({key:"precision",get label(){return l("fields.propPrecision")},kind:"choice",choices:e,visible:t}),It=[u("local","fields.choiceLocal"),u("friendly","fields.choiceFriendly"),u("us","fields.choiceUs"),u("european","fields.choiceEuropean"),u("iso","fields.choiceIso")],I=e=>({key:"dateFormat",get label(){return l("fields.propDateFormat")},kind:"choice",choices:It,...he(e)}),be=[u("12hour","fields.choice12Hour"),u("24hour","fields.choice24Hour")],X=[{key:"time",get label(){return l("fields.propIncludeTime")},kind:"checkbox"},{key:"timeFormat",get label(){return l("fields.propTimeFormat")},kind:"segmented",choices:be,visible:e=>!!e.time},{key:"gmt",get label(){return l("fields.propGmt")},kind:"checkbox",visible:e=>!!e.time},{key:"showTimeZone",get label(){return l("fields.propShowTimeZone")},kind:"checkbox",visible:e=>!!e.time}],Lt=e=>e.columns.filter(t=>t.fieldType==="link").map(t=>({value:String(t.id??t.field),label:String(t.header??t.field)})),Z={key:"linkField",get label(){return l("fields.propLinkField")},kind:"choice",choices:Lt,get hint(){return l("fields.propLinkFieldHint")}},Ot=e=>{const t=e.columns.find(o=>String(o.id??o.field)===e.props.linkField),r=T(t?.fieldProps?.table);return r?(r.fields??[{field:r.primaryField,header:r.primaryField}]).map(o=>({value:o.field,label:o.header})):[]},ye={key:"field",get label(){return l("fields.propLinkedField")},kind:"choice",choices:Ot,visible:e=>!!e.linkField},C={key:"color",get label(){return l("fields.propColor")},kind:"color",palette:se},ke={key:"options",get label(){return l("fields.propOptions")},kind:"options"},Te=(e,t=0)=>{const r=Number(e.precision);return Number.isInteger(r)&&r>=0&&r<=8?r:t},Nt=e=>({precision:e.format==="integer"?0:Te(e,e.format==="decimal"?1:0),separators:e.separators,showThousands:e.showThousands!==!1,abbreviation:e.abbreviation}),Bt=(e,t)=>r=>{const i=typeof r.rawInput=="string"?r.rawInput:r.newValue;if(typeof i=="number"||i==null)return i;if(String(i).trim()==="")return null;const o=Ge(String(i),e,t);return o??r.oldValue},Rt=(e,t)=>t.allowNegative===!1&&!e.validate?{rejectInvalid:!0,validate:r=>Number(r.value)<0?l("fields.negativeNotAllowed"):null}:{},Et=(e,t)=>{const r={precision:ae(e,t).places,separators:t.separators,showThousands:t.showThousands!==!1,abbreviation:e==="percent"?void 0:t.abbreviation};return i=>{const o=We(i.value);return o==null?"":e==="currency"?ie(o,{...r,symbol:t.symbol,symbolPosition:t.symbolPosition}):e==="percent"?oe(o,{...r,points:t.points}):H(o,r)}},q=(e,t,r)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldNumber",align:e.align??(r==="percent"&&t.showBar?"left":"right"),...Rt(e,t),valueParser:e.valueParser??Bt(r,t),formatter:e.formatter??Et(r,t),sortValue:e.sortValue??U}),P=e=>Array.isArray(e.options)?e.options.map(t=>({value:t.value,label:t.label??String(t.value),...t.color?{color:t.color}:{}})):[],we=(e,t)=>{const r=new Map;for(const n of P(e))r.set(String(n.value).toLowerCase(),n.value),r.set(String(n.label).toLowerCase(),n.value);const i=n=>r.get(n.toLowerCase()),o=r.size===0;return n=>{if(typeof n.rawInput!="string")return n.newValue;const a=t?j(n.rawInput):n.rawInput.split(/\n/).map(d=>d.trim()).filter(Boolean);if(o)return t?[...new Set(a)]:a[0]??null;const p=a.map(i).filter(d=>d!==void 0);return a.length&&!p.length?n.oldValue:t?[...new Set(p)]:a.length?i(a[0])===void 0?n.oldValue:i(a[0]):null}},ve=e=>{const t=new Map(P(e).map(r=>[String(r.value),r.label]));return r=>(Array.isArray(r.value)?r.value:r.value==null||r.value===""?[]:[r.value]).map(i=>t.get(String(i))??String(i)).join(", ")},Ht=e=>{const t=new Map(P(e).map((r,i)=>[String(r.value),i]));return r=>r==null||r===""?null:t.get(String(r))??t.size},Se=Xe,y=e=>({editable:e.editable??!1}),J=e=>t=>E(t.value,e),D=e=>e.oldValue!=null&&typeof e.oldValue!="string"&&String(e.oldValue)===e.newValue?e.oldValue:e.newValue,Ut=e=>t=>{const r=typeof t.rawInput=="string"?t.rawInput:t.newValue;if(r==null||typeof r=="string"&&r.trim()==="")return null;if(r instanceof Date)return e.time?r.toISOString():R({y:r.getFullYear(),mo:r.getMonth()+1,d:r.getDate(),time:null},e);const i=String(r).trim();if(/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2})?/.test(i)){if(!e.time)return i.slice(0,10);if(i.length>10&&i[10]==="T")return i}const o=$e(i,e);return o?R(o,e,t.oldValue):t.oldValue},Q=e=>(Array.isArray(e)?e:e==null||e===""?[]:[e]).map(t=>ce(t)?.name??String(t)).join(", "),Me=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=W(),i=a=>{const p=a.toLowerCase();return r.find(f=>f.id.toLowerCase()===p||f.name.toLowerCase()===p||f.email?.toLowerCase()===p)?.id??(r.length?void 0:a)},o=e?j(t.rawInput):t.rawInput.split(/\n/).map(a=>a.trim()).filter(Boolean),n=o.map(i).filter(a=>a!==void 0);return o.length&&!n.length?t.oldValue:e?[...new Set(n)]:o.length?n[0]:null},_t=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=T(e.table);if(!r)return t.newValue;const i=j(t.rawInput),o=ut(r,i);if(r.records&&r.resolveNames&&t.data&&t.columnId){const n=i.filter(a=>st(r,a)==null);n.length&&r.resolveNames({row:t.data,columnId:t.columnId,multiple:e.multiple!==!1},n,o)}return i.length&&!o.length?t.oldValue:e.multiple===!1?o.slice(0,1):o},zt=e=>typeof e.rawInput=="string"?e.rawInput.trim()?gt(e.rawInput):null:Array.isArray(e.newValue)?ht(e.newValue):e.newValue??null,Wt=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=t.rawInput.trim();if(!r)return null;const i=Number(r);return Number.isInteger(i)&&i>=0&&i<=Number(e.max??5)?i:t.oldValue},Gt=e=>{const t=typeof e.rawInput=="string"?e.rawInput:e.newValue;return t==null||String(t).trim()===""?null:$(t)??e.oldValue},jt=e=>t=>{const r=typeof t.rawInput=="string"?t.rawInput:t.newValue;return r==null||typeof r=="string"&&r.trim()===""?null:fe(r,{seconds:!!e.showSeconds})??t.oldValue};function ee(e,t){if(e==null)return"";if(Array.isArray(e))return e.map(r=>ee(r,t)).join(", ");if(e instanceof Date)return E(e,t);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(t.result==="currency"||t.result==="percent"||t.result==="number"){const r=t.result,i={...Nt(t),precision:ae(r,{precision:t.precision}).places};return r==="currency"?ie(e,{...i,symbol:t.symbol}):r==="percent"?oe(e,i):H(e,i)}return String(Math.round(e*1e10)/1e10)}if(t.result==="date"){const r=rt(String(e));if(r)return E(r,t)}return String(e)}const te=(e,t)=>{const r=t.columns.find(n=>String(n.id??n.field)===e.linkField);if(!r)return null;const i=r.fieldProps?.table,o=r.fieldProps?.inverse;return{key:String(r.field??r.id),get table(){return T(i)},rowsOf(n){const a=T(i),p=String(r.field??r.id);return a&&o&&!a.records&&n?.[p]===void 0?at(a,o,String(n?.id??"")):G(a,n?.[p])},get stored(){const n=T(i)?.records;return n&&o&&n.stores(o)?{records:n,field:o}:null}}},$t={SUM:"sum",AVERAGE:"avg",MIN:"min",MAX:"max",COUNT:"count"},Ce=new WeakMap;function Pe(e,t,r){const i=e?.table?.fields;if(!i)return;let o=Ce.get(i);o||Ce.set(i,o=new Map);const n=`${String(t)}|${r??""}`;if(o.has(n))return o.get(n);const a=i.find(d=>d.field===String(t)),p=a?.fieldType?O({field:a.field,fieldType:a.fieldType,fieldProps:{...a.fieldProps,...r==null?{}:{precision:r}}}).formatter:void 0;return o.set(n,p),p}const L=()=>new Date().toISOString(),xt=new Intl.Collator(void 0,{sensitivity:"base",numeric:!0}),Kt=(e,t)=>{const r=i=>i?pe.indexOf(i):pe.length;return r(e)-r(t)},De=[{key:"watch",get label(){return l("fields.propWatch")},kind:"segmented",choices:[u("all","fields.choiceAllFields"),u("specific","fields.choiceSpecificFields")]},{key:"watchFields",get label(){return l("fields.propWatchFields")},kind:"columns",visible:e=>e.watch==="specific"}];export const BUILTIN_FIELD_TYPES=[{id:"text",get label(){return l("fields.typeText")},get description(){return l("fields.typeTextDescription")},icon:s.text,group:"basic",properties:[w],fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D})},{id:"longText",get label(){return l("fields.typeLongText")},get description(){return l("fields.typeLongTextDescription")},icon:s.longText,group:"basic",width:260,properties:[{key:"richText",get label(){return l("fields.propMarkdown")},kind:"checkbox",get hint(){return l("fields.propMarkdownHint")}}],fill:e=>({...e,editorType:e.editorType??"fieldLongText",valueParser:e.valueParser??D}),cell:Ne,hasCell:e=>!!e.richText},{id:"richText",get label(){return l("fields.typeRichText")},get description(){return l("fields.typeRichTextDescription")},icon:s.richText,group:"basic",width:280,defaults:{toolbar:"standard"},properties:[{key:"toolbar",get label(){return l("fields.propToolbar")},kind:"segmented",choices:[u("standard","fields.choiceStandard"),u("full","fields.choiceFull")],get hint(){return l("fields.propToolbarHint")}}],fill:e=>({...e,editorType:e.editorType??"fieldRichText",formatter:e.formatter??(t=>A(t.value)),sortComparator:e.sortComparator??((t,r)=>xt.compare(A(t),A(r))),valueParser:e.valueParser??(t=>Re(t.newValue))}),cell:Be},{id:"attachment",get label(){return l("fields.typeAttachment")},get description(){return l("fields.typeAttachmentDescription")},icon:s.attachment,group:"basic",width:180,defaults:{maxFiles:20},properties:[{key:"accept",get label(){return l("fields.propAccept")},kind:"text",get placeholder(){return l("fields.propAcceptPlaceholder")}},{key:"maxFiles",get label(){return l("fields.propMaxFiles")},kind:"number",min:1,max:100}],fill:(e,t)=>({...e,editorType:e.editorType??"attachment",formatter:e.formatter??(r=>Ue(r.value)),valueParser:e.valueParser??(r=>_e(r.newValue,t))}),cell:Ve},{id:"checkbox",get label(){return l("fields.typeCheckbox")},get description(){return l("fields.typeCheckboxDescription")},icon:s.checkbox,group:"basic",width:90,defaults:{icon:"check",color:"#20c933"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"icon",icons:xe},C,w],fill:e=>({...e,editorType:e.editorType??"checkbox",align:e.align??"center",toggleOnSecondClick:e.toggleOnSecondClick??!0}),cell:Fe},{id:"singleSelect",get label(){return l("fields.typeSingleSelect")},get description(){return l("fields.typeSingleSelectDescription")},icon:s.singleSelect,group:"basic",width:140,defaults:{options:[]},properties:[ke,w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",editorOptions:e.editorOptions??P(t),formatter:e.formatter??ve(t),valueParser:e.valueParser??we(t,!1),sortValue:e.sortValue??Ht(t)}),cell:le},{id:"multiSelect",get label(){return l("fields.typeMultiSelect")},get description(){return l("fields.typeMultiSelectDescription")},icon:s.multiSelect,group:"basic",width:200,defaults:{options:[]},properties:[ke,w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",editorMultiple:e.editorMultiple??!0,editorOptions:e.editorOptions??P(t),formatter:e.formatter??ve(t),valueParser:e.valueParser??we(t,!0)}),cell:le},{id:"user",get label(){return l("fields.typeUser")},get description(){return l("fields.typeUserDescription")},icon:s.user,group:"basic",width:170,properties:[{key:"multiple",get label(){return l("fields.propMultipleUsers")},kind:"checkbox"},w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",valueParser:e.valueParser??Me(!!t.multiple),editorMultiple:e.editorMultiple??!!t.multiple,editorOptions:e.editorOptions??W().map(r=>({value:r.id,label:r.name})),formatter:e.formatter??(r=>Q(r.value))}),cell:B},{id:"date",get label(){return l("fields.typeDate")},get description(){return l("fields.typeDateDescription")},icon:s.date,group:"basic",width:150,defaults:{dateFormat:"local",timeFormat:"12hour"},properties:[I(),...X,{key:"defaultToday",get label(){return l("fields.propDefaultToday")},kind:"checkbox"}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??(t.time?"date":"dateString"),editorType:e.editorType??"fieldDate",editorFormatString:e.editorFormatString??ze(t),formatter:e.formatter??J(t),valueParser:e.valueParser??Ut(t)}),newRowValue:({props:e})=>{if(!e.defaultToday)return;if(e.time)return L();const t=new Date;return R({y:t.getFullYear(),mo:t.getMonth()+1,d:t.getDate(),time:null},{})}},{id:"phone",get label(){return l("fields.typePhone")},get description(){return l("fields.typePhoneDescription")},icon:s.phone,group:"basic",fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D}),cell:N},{id:"email",get label(){return l("fields.typeEmail")},get description(){return l("fields.typeEmailDescription")},icon:s.email,group:"basic",width:200,fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D}),cell:N},{id:"url",get label(){return l("fields.typeUrl")},get description(){return l("fields.typeUrlDescription")},icon:s.url,group:"basic",width:200,fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D}),cell:N},{id:"barcode",get label(){return l("fields.typeBarcode")},get description(){return l("fields.typeBarcodeDescription")},icon:s.barcode,group:"basic",width:160,fill:e=>({...e,editorType:e.editorType??"text",formatter:e.formatter??(t=>t.value&&typeof t.value=="object"?String(t.value.text??""):String(t.value??""))}),cell:Le},{id:"button",get label(){return l("fields.typeButton")},get description(){return l("fields.typeButtonDescription")},icon:s.button,group:"basic",width:120,defaults:{label:"Open",color:"#2d7ff9",action:"link"},properties:[{key:"label",get label(){return l("fields.propButtonLabel")},kind:"text",get placeholder(){return l("fields.propButtonLabelPlaceholder")}},{key:"color",get label(){return l("fields.propButtonStyle")},kind:"color",palette:se},{key:"action",get label(){return l("fields.propButtonAction")},kind:"choice",choices:Pt},{key:"url",get label(){return l("fields.propButtonUrl")},kind:"text",get placeholder(){return l("fields.propButtonUrlPlaceholder")},get hint(){return l("fields.propButtonUrlHint")},visible:e=>b(e)==="link"},{key:"values",get label(){return l("fields.propButtonValues")},kind:"recordValues",get hint(){return l("fields.propButtonValuesHint")},visible:e=>b(e)==="update"},{key:"template",get label(){return l("fields.propButtonTemplate")},kind:"choice",get hint(){return l("fields.propButtonTemplateHint")},visible:e=>b(e)==="template",choices:e=>(e.ctrl?.props?.baseRecordTemplates?.()??[]).map(t=>({value:t.id,label:t.name}))},{key:"recordAction",get label(){return l("fields.propButtonRecordAction")},kind:"choice",visible:e=>b(e)==="recordAction",choices:e=>me(e.ctrl?.props?.baseTableId).map(t=>({value:t.id,label:t.label}))},{key:"copy",get label(){return l("fields.propButtonCopy")},kind:"text",get placeholder(){return l("fields.propButtonCopyPlaceholder")},get hint(){return l("fields.propButtonCopyHint")},visible:e=>b(e)==="copy"},{key:"doneLabel",get label(){return l("fields.propButtonDoneLabel")},kind:"text",get placeholder(){return l("fields.propButtonDoneLabelPlaceholder")},get hint(){return l("fields.propButtonDoneLabelHint")},visible:e=>b(e)==="update"||b(e)==="template"},{key:"when",get label(){return l("fields.propButtonWhen")},kind:"filter",get hint(){return l("fields.propButtonWhenHint")}},{key:"who",get label(){return l("fields.propButtonWho")},kind:"people",get everyone(){return l("fields.buttonWhoEveryone")},get only(){return l("fields.whoOnly")},get hint(){return l("fields.propButtonWhoHint")}},{key:"ask",get label(){return l("fields.propButtonAsk")},kind:"checkbox",visible:e=>b(e)!=="delete"},{key:"askText",get label(){return l("fields.propButtonAskText")},kind:"text",get placeholder(){return l("fields.buttonAskDefault")},visible:e=>!!e.ask&&b(e)!=="delete"}],fill:(e,t,r)=>{const i=Se(r.columns),o=(d,f,h)=>{if(!d.trim())return null;if(!f)return m=>m?wt(d,m,i,h):"";const c=O({id:`${String(e.id??e.field)}__button`,field:`__button_${String(e.field??e.id)}`,fieldType:"formula",fieldProps:{formula:d}},r.columns).fieldFn;return m=>{if(!c||!m)return"";const g=c(m);return g==="#ERROR"?"":ee(g,{})}},n=String(t.url??""),a=String(t.copy??""),p=a.trim().startsWith("=");return{...e,...y(e),sortable:e.sortable??!1,__fieldNames:i,__buttonLink:o(n,!!n.trim()&&!vt(n),!0),__buttonCopy:o(p?a.trim().slice(1):a,p,!1)}},cell:Ie},{id:"checklist",get label(){return l("fields.typeChecklist")},get description(){return l("fields.typeChecklistDescription")},icon:s.checklist,group:"basic",width:150,fill:e=>({...e,editorType:e.editorType??"fieldChecklist",formatter:e.formatter??(t=>mt(t.value)),valueParser:e.valueParser??zt,sortValue:e.sortValue??ft,groupValue:e.groupValue??pt,groupOrder:e.groupOrder??Kt}),cell:Ee},{id:"color",get label(){return l("fields.typeColor")},get description(){return l("fields.typeColorDescription")},icon:s.color,group:"basic",width:130,properties:[w],fill:e=>({...e,editorType:e.editorType??"fieldColor",formatter:e.formatter??(t=>$(t.value)??String(t.value??"")),valueParser:e.valueParser??Gt,sortValue:e.sortValue??bt}),newRowValue:({props:e})=>e.default==null||e.default===""?void 0:$(e.default),cell:He},{id:"number",get label(){return l("fields.typeNumber")},get description(){return l("fields.typeNumberDescription")},icon:s.number,group:"number",width:120,defaults:{format:"decimal",precision:1,separators:"local",showThousands:!0,abbreviation:"none",allowNegative:!0,symbol:"$",symbolPosition:"before",showBar:!1,points:!1,step:1},properties:[{key:"format",get label(){return l("fields.propFormat")},kind:"segmented",choices:[u("integer","fields.choiceInteger"),u("decimal","fields.choiceDecimal"),u("currency","fields.choiceCurrency"),u("percent","fields.choicePercent")],alsoSets:e=>({precision:e==="decimal"?1:e==="currency"?2:0})},{key:"symbol",get label(){return l("fields.propCurrencySymbol")},kind:"text",placeholder:"$, €, £, ¥, CHF, kr",visible:e=>e.format==="currency"},{key:"symbolPosition",get label(){return l("fields.propSymbolPosition")},kind:"segmented",visible:e=>e.format==="currency",choices:[u("before","fields.choiceBefore"),u("after","fields.choiceAfter")]},Y(K(0,8),e=>e.format!=="integer"),{key:"step",get label(){return l("fields.propStep")},kind:"number",min:0,get hint(){return l("fields.propStepHint")}},Dt,At,Vt(e=>e.format!=="percent"),Ft,{key:"showBar",get label(){return l("fields.propShowBar")},kind:"checkbox",visible:e=>e.format==="percent"},{key:"points",get label(){return l("fields.propPoints")},kind:"checkbox",visible:e=>e.format==="percent"},w],fill:(e,t)=>q(e,t,je("number",t)),cell:re,hasCell:e=>e.format==="percent"&&!!e.showBar},{id:"currency",get label(){return l("fields.typeCurrency")},get description(){return l("fields.typeCurrencyDescription")},icon:s.currency,group:"number",width:120,defaults:{symbol:"$",symbolPosition:"before",precision:2,separators:"local",showThousands:!0,abbreviation:"none",allowNegative:!0},editAs:{type:"number",props:{format:"currency"}},fill:(e,t)=>q(e,t,"currency")},{id:"percent",get label(){return l("fields.typePercent")},get description(){return l("fields.typePercentDescription")},icon:s.percent,group:"number",width:110,defaults:{precision:0,separators:"local",showThousands:!0,allowNegative:!0,points:!1},editAs:{type:"number",props:{format:"percent"}},fill:(e,t)=>q(e,t,"percent"),cell:re,hasCell:e=>!!e.showBar},{id:"duration",get label(){return l("fields.typeDuration")},get description(){return l("fields.typeDurationDescription")},icon:s.duration,group:"number",width:110,defaults:{durationFormat:"h:mm"},properties:[{key:"durationFormat",get label(){return l("fields.propDurationFormat")},kind:"choice",choices:[{value:"h:mm",label:"h:mm"},{value:"h:mm:ss",label:"h:mm:ss"},{value:"h:mm:ss.S",label:"h:mm:ss.S"},{value:"h:mm:ss.SS",label:"h:mm:ss.SS"},{value:"h:mm:ss.SSS",label:"h:mm:ss.SSS"}]}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldNumber",formatter:e.formatter??(r=>{const i=U(r.value);return i==null?"":ne(i,t.durationFormat)}),valueParser:e.valueParser??(r=>typeof r.rawInput=="string"?r.rawInput.trim()?V(r.rawInput)??r.oldValue:null:typeof r.newValue=="number"?r.newValue:V(r.newValue))})},{id:"timeOfDay",get label(){return l("fields.typeTimeOfDay")},get description(){return l("fields.typeTimeOfDayDescription")},icon:s.timeOfDay,group:"number",width:120,defaults:{timeFormat:"12hour",showSeconds:!1},properties:[{key:"timeFormat",get label(){return l("fields.propTimeFormat")},kind:"segmented",choices:be},{key:"showSeconds",get label(){return l("fields.propShowSeconds")},kind:"checkbox"},w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldTime",formatter:e.formatter??(r=>yt(r.value,t)),valueParser:e.valueParser??jt(t),sortValue:e.sortValue??kt}),newRowValue:({props:e})=>e.default==null||e.default===""?void 0:fe(e.default,{seconds:!!e.showSeconds})},{id:"rating",get label(){return l("fields.typeRating")},get description(){return l("fields.typeRatingDescription")},icon:s.rating,group:"number",width:130,defaults:{max:5,icon:"star",color:"#fcb400"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"icon",icons:Ke},C,{key:"max",get label(){return l("fields.propMaximum")},kind:"choice",choices:Array.from({length:10},(e,t)=>({value:String(t+1),label:String(t+1)}))}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",align:e.align??"left",editorType:e.editorType??"fieldRating",valueParser:e.valueParser??Wt(t)}),cell:Ae},{id:"timer",get label(){return l("fields.typeTimer")},get description(){return l("fields.typeTimerDescription")},icon:s.timer,group:"number",width:130,defaults:{durationFormat:"h:mm:ss"},properties:[{key:"durationFormat",get label(){return l("fields.propDurationFormat")},kind:"choice",choices:[{value:"h:mm",label:"h:mm"},{value:"h:mm:ss",label:"h:mm:ss"}]},C],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldTimer",align:e.align??"left",sortValue:e.sortValue??(r=>F(r)),formatter:e.formatter??(r=>{const i=F(r.value);return i==null?"":ne(i,t.durationFormat??"h:mm:ss")}),valueParser:e.valueParser??(r=>typeof r.rawInput=="string"?r.rawInput.trim()?V(r.rawInput)??r.oldValue:null:r.newValue==null||r.newValue===""?null:typeof r.newValue=="number"||typeof r.newValue=="object"&&Qe(r.newValue)!=null?r.newValue:V(r.newValue))}),cell:Je},{id:"vote",get label(){return l("fields.typeVote")},get description(){return l("fields.typeVoteDescription")},icon:s.vote,group:"basic",width:100,defaults:{icon:"up"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"segmented",choices:[u("up","fields.choiceArrow"),u("thumb","fields.choiceThumb"),u("heart","fields.choiceHeart")]},C],fill:e=>({...e,editorType:e.editorType??"fieldVote",editorOptions:e.editorOptions??W().map(t=>({value:t.id,label:t.name})),align:e.align??"left",sortValue:e.sortValue??(t=>ue(t)),formatter:e.formatter??(t=>String(ue(t.value))),valueParser:e.valueParser??(t=>Ze(Me(!0)(t)))}),newRowValue:()=>[],cell:qe},{id:"sparkline",get label(){return l("fields.typeSparkline")},get description(){return l("fields.typeSparklineDescription")},icon:s.sparkline,group:"number",width:160,defaults:{chart:"line"},properties:[{key:"chart",get label(){return l("fields.propChart")},kind:"segmented",choices:[u("line","fields.choiceLine"),u("area","fields.choiceArea"),u("bar","fields.choiceColumns")]},C,{key:"showLast",get label(){return l("fields.propShowLast")},kind:"checkbox"}],fill:e=>({...e,formatter:e.formatter??(t=>z(t.value).join(", ")),valueParser:e.valueParser??(t=>{const r=z(t.newValue);return r.length?r:null}),sortValue:e.sortValue??(t=>z(t).at(-1)??null)}),cell:et},{id:"formula",get label(){return l("fields.typeFormula")},get description(){return l("fields.typeFormulaDescription")},icon:s.formula,group:"computed",width:160,defaults:{formula:"",result:"auto"},properties:[{key:"formula",get label(){return l("fields.propFormula")},kind:"formula"},{key:"result",get label(){return l("fields.propResult")},kind:"choice",choices:[u("auto","fields.choiceAsComputed"),u("number","fields.choiceNumber"),u("currency","fields.choiceCurrency"),u("percent","fields.choicePercent"),u("date","fields.choiceDate")]},Y(K(0,8),e=>["number","currency","percent"].includes(e.result)),{key:"symbol",get label(){return l("fields.propCurrencySymbol")},kind:"text",placeholder:"$",visible:e=>e.result==="currency"},I(e=>e.result==="date")],fill:(e,t,r)=>{const i=Se(r.columns),o=String(t.formula??""),n=String(e.field??e.id),a=new Set([n.toLowerCase(),typeof e.header=="string"?e.header.trim().toLowerCase():""].filter(Boolean)),p=c=>{const m=c.trim().toLowerCase(),g=i[m]??null;if(g===n||g==null&&a.has(m))throw lt(c);return g};let d=null;try{d=o.trim()?tt(o,p).fn:()=>null}catch{d=null}let f=null;const h=()=>{if(f)return f;f=new Map;for(const c of r.columns){if(c.fieldType==="richText"){const k=String(c.field??c.id);f.set(k,S=>A(S?.[k]));continue}if(c.fieldType==="timer"){const k=String(c.field??c.id);f.set(k,S=>F(S?.[k]));continue}const m=Mt(c);if(m){f.set(String(c.field??c.id),m);continue}if(!Ye.has(String(c.fieldType))||String(c.field??c.id)===n)continue;const g=O(c,r.columns);typeof g.fieldFn=="function"&&f.set(String(c.field??c.id),g.fieldFn)}return f},v=c=>{const m=h();return!m.size||!c?c:new Proxy(c,{get:(g,k)=>{const S=typeof k=="string"?m.get(k):void 0;if(!S||M>3)return g[k];M+=1;try{return S(g)}finally{M-=1}}})};return{...e,...y(e),fieldFn:c=>d?d(v(c)):"#ERROR",align:e.align??(["number","currency","percent"].includes(t.result)?"right":void 0),formatter:e.formatter??(c=>ee(c.value,t))}}},{id:"createdTime",get label(){return l("fields.typeCreatedTime")},get description(){return l("fields.typeCreatedTimeDescription")},icon:s.createdTime,group:"computed",width:170,defaults:{dateFormat:"local",time:!0,timeFormat:"12hour"},properties:[I(),...X],fill:(e,t)=>({...e,...y(e),formatter:e.formatter??J(t)}),newRowValue:()=>L(),onCreate:({rows:e})=>e.map(()=>L())},{id:"lastModifiedTime",get label(){return l("fields.typeLastModifiedTime")},get description(){return l("fields.typeLastModifiedTimeDescription")},icon:s.modifiedTime,group:"computed",width:170,defaults:{dateFormat:"local",time:!0,timeFormat:"12hour",watch:"all"},properties:[...De,I(),...X],fill:(e,t)=>({...e,...y(e),formatter:e.formatter??J(t)}),newRowValue:()=>L()},{id:"createdBy",get label(){return l("fields.typeCreatedBy")},get description(){return l("fields.typeCreatedByDescription")},icon:s.createdBy,group:"computed",width:160,fill:e=>({...e,...y(e),formatter:e.formatter??(t=>Q(t.value))}),newRowValue:()=>de()?.id??null,cell:B},{id:"lastModifiedBy",get label(){return l("fields.typeLastModifiedBy")},get description(){return l("fields.typeLastModifiedByDescription")},icon:s.modifiedBy,group:"computed",width:160,defaults:{watch:"all"},properties:De,fill:e=>({...e,...y(e),formatter:e.formatter??(t=>Q(t.value))}),newRowValue:()=>de()?.id??null,cell:B},{id:"autoNumber",get label(){return l("fields.typeAutoNumber")},get description(){return l("fields.typeAutoNumberDescription")},icon:s.autoNumber,group:"computed",width:100,fill:e=>({...e,...y(e),cellDataType:e.cellDataType??"number"}),newRowValue:({rows:e,field:t})=>e.reduce((r,i)=>Math.max(r,Number(i?.[t])||0),0)+1,onCreate:({rows:e})=>e.map((t,r)=>r+1)},{id:"link",get label(){return l("fields.typeLink")},get description(){return l("fields.typeLinkDescription")},icon:s.link,group:"relation",width:200,defaults:{multiple:!0},properties:[{key:"table",get label(){return l("fields.propTable")},kind:"choice",choices:()=>nt().map(e=>({value:e.id,label:e.name})),get hint(){return l("fields.propTableHint")},alsoSets:()=>({pickFrom:""})},{key:"multiple",get label(){return l("fields.propMultipleRecords")},kind:"checkbox"},{key:"pickFrom",get label(){return l("fields.propPickFrom")},kind:"choice",choices:e=>[{value:"",label:l("fields.pickFromAll")},...(T(e.props.table)?.views?.()??[]).filter(t=>!t.personal&&t.type!=="form").map(t=>({value:t.id,label:t.name}))],visible:e=>!!e.table,get hint(){return l("fields.propPickFromHint")}}],fill:(e,t)=>({...e,editorType:e.editorType??"fieldLink",formatter:e.formatter??(r=>{const i=T(t.table);return G(i,r.value).map(o=>String(o[i.primaryField]??"")).join(", ")}),valueParser:e.valueParser??_t(t),groupValue:e.groupValue??(r=>ot(t.table,r)),groupCopies:!0}),cell:Oe},{id:"lookup",get label(){return l("fields.typeLookup")},get description(){return l("fields.typeLookupDescription")},icon:s.lookup,group:"relation",width:180,properties:[Z,ye],fill:(e,t,r)=>{const i=te(t,r),o=n=>{const a=Pe(i,t.field);return String(a?a({value:n})??"":n)};return{...e,...y(e),fieldSource:()=>i?.table?.fields?.find(n=>n.field===String(t.field)),fieldFn:n=>{if(!i)return[];const a=x(i.table,String(t.field)),p=i.stored;return p?p.records.allLinkedTo(p.field,String(n?.id??"")).map(a):i.rowsOf(n).map(a)},formatter:e.formatter??(n=>Array.isArray(n.value)?n.value.filter(a=>a!=null&&a!=="").map(o).join(", "):n.value==null?"":o(n.value))}}},{id:"rollup",get label(){return l("fields.typeRollup")},get description(){return l("fields.typeRollupDescription")},icon:s.rollup,group:"relation",width:140,defaults:{aggregation:"SUM"},properties:[Z,ye,{key:"aggregation",get label(){return l("fields.propAggregation")},kind:"choice",choices:Object.keys(_).map(e=>({value:e,label:e}))},Y(K(0,8),e=>["SUM","AVERAGE","MIN","MAX"].includes(e.aggregation))],fill:(e,t,r)=>{const i=te(t,r),o=_[String(t.aggregation)]??_.SUM,n=["SUM","AVERAGE","MIN","MAX","COUNT","COUNTA","COUNTALL"].includes(String(t.aggregation)),a=["SUM","AVERAGE","MIN","MAX"].includes(String(t.aggregation)),p=d=>{const f=a?Pe(i,t.field,t.precision):void 0;return f?String(f({value:d})??""):H(d,{precision:Te(t,0)})};return{...e,...y(e),...n?{cellDataType:e.cellDataType??"number"}:{},align:e.align??(n?"right":void 0),fieldSource:()=>i?.table?.fields?.find(d=>d.field===String(t.field)),fieldFn:d=>{if(!i)return null;const f=x(i.table,String(t.field)),h=i.stored;if(h){const v=String(d?.id??""),c=$t[String(t.aggregation)];return c?h.records.total(h.field,v,String(t.field),c)??null:t.aggregation==="COUNTA"||t.aggregation==="COUNTALL"?h.records.total(h.field,v)??null:o(h.records.allLinkedTo(h.field,v).map(f))}return o(i.rowsOf(d).map(f))},formatter:e.formatter??(d=>{const f=n?U(d.value):typeof d.value=="number"?d.value:null;return f==null?String(d.value??""):p(f)})}}},{id:"count",get label(){return l("fields.typeCount")},get description(){return l("fields.typeCountDescription")},icon:s.count,group:"relation",width:90,properties:[Z],fill:(e,t,r)=>{const i=te(t,r);return{...e,...y(e),cellDataType:e.cellDataType??"number",formatter:o=>o.value==null?"":Number(o.value).toLocaleString(),fieldFn:o=>{if(!i)return 0;const n=i.stored;return n?n.records.total(n.field,String(o?.id??""))??null:i.rowsOf(o).length}}}},dt];
1
+ import{fillFieldColumn as O}from"./registry.svelte.js";import Ve from"./RatingCell.svelte";import N from"./LinkCell.svelte";import Fe from"./AttachmentCell.svelte";import Ie from"./CheckboxCell.svelte";import le from"./PercentCell.svelte";import B from"./UserCell.svelte";import Le from"./ButtonCell.svelte";import Oe from"./BarcodeCell.svelte";import Ne from"./LinkedRecordsCell.svelte";import Be from"./RichTextCell.svelte";import Re from"./RichHtmlCell.svelte";import{richPlain as A}from"./rich-html.js";import{toRichHtml as Ee}from"./rich-html-write.js";import ie from"./SelectCell.svelte";import He from"./ChecklistCell.svelte";import Ue from"./ColorCell.svelte";import{attachmentsText as _e,parseAttachments as ze}from"./attachments.js";import{dateEditTokens as We,dateFromParts as R,exactNumber as Ge,formatCurrency as ne,formatDate as E,formatDuration as oe,formatNumber as H,formatPercent as ae,numberFieldShape as se,numberFromText as je,numberKind as $e,parseDateText as xe,parseDuration as V,toNumber as U}from"./format.js";import{BRIGHT as ue,CHECKBOX_ICONS as Ke,RATING_ICONS as Xe}from"./palette.js";import{COMPUTED_TYPES as ce,ROLLUPS as _,fieldNameMap as Ye}from"./rollups.js";import{sparklineValues as z,voteCount as de,voteIds as Ze}from"./vote.js";import qe from"./VoteCell.svelte";import Je from"./TimerCell.svelte";import{timerSeconds as F,timerTotal as Qe}from"./timer.js";import et from"./SparklineCell.svelte";import{compileFormula as tt,isoDate as rt,selfReferenceError as lt}from"./formula.js";import{findFieldUser as pe,getCurrentUser as fe,getFieldUsers as W,getLinkedTable as T,idOf as it,linkedRows as G,listLinkedTables as nt,liveLink as ot,recordsNaming as at,resolveLinkId as st,resolveLinkIds as ut}from"./sources.svelte.js";import{splitNames as j}from"./name-list.js";import{linkedFields as ct}from"./linked-fields.js";import{AI_FIELD_TYPE as dt}from"./ai-field.svelte.js";import{CHECKLIST_GROUPS as me,checklistGroup as pt,checklistSortValue as ft,checklistText as mt,parseChecklist as gt,toChecklist as ht}from"./checklist.js";import{colorSortValue as bt,parseColor as $}from"./color-value.js";import{formatTimeOfDay as yt,parseTimeOfDay as ge,timeSeconds as kt}from"./time-of-day.js";import{bm as l}from"./messages.svelte.js";import{BUTTON_ACTIONS as Tt,buttonAction as b,fillButtonTokens as vt,isLinkTemplate as wt}from"./button.js";import{recordActionsFor as he}from"./record-actions.js";const St=new Set(["user","createdBy","lastModifiedBy"]);function Mt(e){const t=String(e.field??e.id),r=o=>o.length===1?o[0]:o;if(St.has(String(e.fieldType)))return o=>{const n=o?.[t];return n==null||n===""?n:r((Array.isArray(n)?n:[n]).map(a=>pe(a)?.name??a))};if(e.fieldType!=="link")return null;const i=e.fieldProps?.table;return o=>{const n=o?.[t],a=T(i);if(!a||n==null||n==="")return n;const d=x(a,a.primaryField),g=new Map(G(a,n).map(m=>[it(a,m),d(m)]));return r((Array.isArray(n)?n:[n]).map(m=>g.get(String(m))??m))}}const be=new WeakMap;let w=0;function x(e,t){const r=n=>n?.[t];if(!e?.fields?.length)return r;let i=be.get(e.fields);if(i||be.set(e.fields,i=new Map),!i.has(t)){const n=ct(e).find(d=>d.def.field===t),a=n?.def.fieldType==="timer"?d=>F(d?.[t]):null;i.set(t,a??n?.def.fieldFn??null)}const o=i.get(t);return o?n=>{if(w>3)return r(n);w+=1;try{return o(n)}finally{w-=1}}:r}const u={text:"M4 6h16M4 12h10M4 18h7",longText:"M4 6h16M4 10h16M4 14h16M4 18h10",richText:"M6 4h7a4 4 0 0 1 0 8H6zM6 12h8a4 4 0 0 1 0 8H6zM6 4v16",vote:"M12 19V5M5 12l7-7 7 7",sparkline:"M3 17l5-6 4 4 8-9",number:"M9 4 7 20M17 4l-2 16M4 9h16M3 15h16",currency:"M12 3v18M16 7.5C16 5.6 14.2 4.5 12 4.5S8 5.6 8 7.5s1.8 2.7 4 3.5 4 1.6 4 3.5-1.8 3-4 3-4-1.1-4-3",percent:"M19 5 5 19M7 7h.01M17 17h.01",date:"M4 6h16v14H4zM4 10h16M8 3v4M16 3v4",duration:"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zM12 8v4l3 2",timer:"M12 7a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM12 10v4l2.5 1.5M9.5 2.5h5M12 2.5V5",checkbox:"M4 4h16v16H4zM8 12l3 3 5-6",singleSelect:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM8 11l4 4 4-4",multiSelect:"M3 7h11M3 12h11M3 17h11M17 6l2 2 3-3M17 16l2 2 3-3",rating:"M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3 6.5 20.2l1-6.2L3 9.6l6.2-.9z",url:"M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1",email:"M3 6h18v12H3zM3 7l9 6 9-6",phone:"M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2",attachment:"M20 11.5 12.3 19a5 5 0 0 1-7.1-7.1l7.8-7.8a3.3 3.3 0 0 1 4.7 4.7L9.9 16.6a1.7 1.7 0 0 1-2.4-2.4l7.1-7",user:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0",createdTime:"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zM12 8v4h4",modifiedTime:"M4 12a8 8 0 1 0 2.3-5.7M4 4v4h4M12 8v4l3 2",createdBy:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 11-7.5M19 15v6M16 18h6",modifiedBy:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 11-7.5M16 21l5-5-2-2-5 5v2z",autoNumber:"M5 7h3v10M11 9a2 2 0 1 1 4 0c0 2-4 3-4 6h4M18 7h2v10",barcode:"M4 5v14M7 5v14M10 5v14M13 5v14M15 5v14M18 5v14M20 5v14",button:"M4 7h16v10H4zM9 12h6",formula:"M7 20c2 0 2.5-2 3-5l2-10c.5-2 1.5-2 3-2M8 9h7",link:"M9 7H6a5 5 0 0 0 0 10h3M15 7h3a5 5 0 0 1 0 10h-3M8 12h8",lookup:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4M8 11h6",rollup:"M6 4h12L12 12l6 8H6",count:"M5 5h14v14H5zM9 9v6M12 9v6M15 9v6",checklist:"M3.5 6l1.5 1.5L7.5 5M3.5 12l1.5 1.5 2.5-2.5M3.5 18l1.5 1.5 2.5-2.5M11 6h9M11 12h9M11 18h9",color:"M12 3a9 9 0 1 0 0 18c1 0 1.6-.7 1.6-1.6 0-1-.8-1.4-.8-2.3 0-1 .8-1.7 1.8-1.7H17a4 4 0 0 0 4-4C21 6.6 17 3 12 3zM7.5 12h.01M9.5 7.5h.01M14.5 7.5h.01",timeOfDay:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 7v5l-3 2M12 3v2M21 12h-2M12 21v-2M3 12h2"},c=(e,t)=>({value:e,get label(){return l(t)}}),Ct={link:"fields.buttonActionLink",automation:"fields.buttonActionAutomation",update:"fields.buttonActionUpdate",template:"fields.buttonActionTemplate",recordAction:"fields.buttonActionRecordAction",copy:"fields.buttonActionCopy",duplicate:"fields.buttonActionDuplicate",delete:"fields.buttonActionDelete",open:"fields.buttonActionOpen"};function Dt(e){const t=!!e.ctrl?.props?.baseButton,r=b(e.props),i=o=>o===r||o==="link"||o==="copy"?!0:t?o==="template"?(e.ctrl?.props?.baseRecordTemplates?.()??[]).length>0:o==="recordAction"?he(e.ctrl?.props?.baseTableId).length>0:!0:!1;return Tt.filter(i).map(o=>c(o,Ct[o]))}const ye=e=>e?{visible:e}:{},Pt={key:"separators",get label(){return l("fields.propSeparators")},kind:"choice",choices:[c("local","fields.choiceLocal"),{value:"comma-period",label:"1,000,000.00"},{value:"period-comma",label:"1.000.000,00"},{value:"space-comma",label:"1 000 000,00"},{value:"space-period",label:"1 000 000.00"}]},At={key:"showThousands",get label(){return l("fields.propShowThousands")},kind:"checkbox"},Vt=e=>({key:"abbreviation",get label(){return l("fields.propAbbreviation")},kind:"choice",choices:[c("none","fields.choiceNone"),c("thousand","fields.choiceThousand"),c("million","fields.choiceMillion"),c("billion","fields.choiceBillion")],...ye(e)}),Ft={key:"allowNegative",get label(){return l("fields.propAllowNegative")},kind:"checkbox"},v={key:"default",get label(){return l("fields.propDefault")},kind:"default",get hint(){return l("fields.propDefaultHint")}},K=(e,t)=>Array.from({length:t-e+1},(r,i)=>{const o=e+i;return{value:String(o),label:o===0?"1":`1.${"0".repeat(o)}`}}),X=(e,t)=>({key:"precision",get label(){return l("fields.propPrecision")},kind:"choice",choices:e,visible:t}),It=[c("local","fields.choiceLocal"),c("friendly","fields.choiceFriendly"),c("us","fields.choiceUs"),c("european","fields.choiceEuropean"),c("iso","fields.choiceIso")],I=e=>({key:"dateFormat",get label(){return l("fields.propDateFormat")},kind:"choice",choices:It,...ye(e)}),ke=[c("12hour","fields.choice12Hour"),c("24hour","fields.choice24Hour")],Y=[{key:"time",get label(){return l("fields.propIncludeTime")},kind:"checkbox"},{key:"timeFormat",get label(){return l("fields.propTimeFormat")},kind:"segmented",choices:ke,visible:e=>!!e.time},{key:"gmt",get label(){return l("fields.propGmt")},kind:"checkbox",visible:e=>!!e.time},{key:"showTimeZone",get label(){return l("fields.propShowTimeZone")},kind:"checkbox",visible:e=>!!e.time}],Lt=e=>e.columns.filter(t=>t.fieldType==="link").map(t=>({value:String(t.id??t.field),label:String(t.header??t.field)})),Z={key:"linkField",get label(){return l("fields.propLinkField")},kind:"choice",choices:Lt,get hint(){return l("fields.propLinkFieldHint")}},Ot=e=>{const t=e.columns.find(o=>String(o.id??o.field)===e.props.linkField),r=T(t?.fieldProps?.table);return r?(r.fields??[{field:r.primaryField,header:r.primaryField}]).map(o=>({value:o.field,label:o.header})):[]},Te={key:"field",get label(){return l("fields.propLinkedField")},kind:"choice",choices:Ot,visible:e=>!!e.linkField},M={key:"color",get label(){return l("fields.propColor")},kind:"color",palette:ue},ve={key:"options",get label(){return l("fields.propOptions")},kind:"options"},we=(e,t=0)=>{const r=Number(e.precision);return Number.isInteger(r)&&r>=0&&r<=8?r:t},Nt=e=>({precision:e.format==="integer"?0:we(e,e.format==="decimal"?1:0),separators:e.separators,showThousands:e.showThousands!==!1,abbreviation:e.abbreviation}),Bt=(e,t)=>r=>{const i=typeof r.rawInput=="string"?r.rawInput:r.newValue;if(typeof i=="number"||i==null)return i;if(String(i).trim()==="")return null;const o=je(String(i),e,t);return o??r.oldValue},Rt=(e,t)=>t.allowNegative===!1&&!e.validate?{rejectInvalid:!0,validate:r=>Number(r.value)<0?l("fields.negativeNotAllowed"):null}:{},Et=(e,t)=>{const r={precision:se(e,t).places,separators:t.separators,showThousands:t.showThousands!==!1,abbreviation:e==="percent"?void 0:t.abbreviation};return i=>{const o=Ge(i.value);return o==null?"":e==="currency"?ne(o,{...r,symbol:t.symbol,symbolPosition:t.symbolPosition}):e==="percent"?ae(o,{...r,points:t.points}):H(o,r)}},q=(e,t,r)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldNumber",align:e.align??(r==="percent"&&t.showBar?"left":"right"),...Rt(e,t),valueParser:e.valueParser??Bt(r,t),formatter:e.formatter??Et(r,t),sortValue:e.sortValue??U}),C=e=>Array.isArray(e.options)?e.options.map(t=>({value:t.value,label:t.label??String(t.value),...t.color?{color:t.color}:{}})):[],Se=(e,t)=>{const r=new Map;for(const n of C(e))r.set(String(n.value).toLowerCase(),n.value),r.set(String(n.label).toLowerCase(),n.value);const i=n=>r.get(n.toLowerCase()),o=r.size===0;return n=>{if(typeof n.rawInput!="string")return n.newValue;const a=t?j(n.rawInput):n.rawInput.split(/\n/).map(g=>g.trim()).filter(Boolean);if(o)return t?[...new Set(a)]:a[0]??null;const d=a.map(i).filter(g=>g!==void 0);return a.length&&!d.length?n.oldValue:t?[...new Set(d)]:a.length?i(a[0])===void 0?n.oldValue:i(a[0]):null}},Me=e=>{const t=new Map(C(e).map(r=>[String(r.value),r.label]));return r=>(Array.isArray(r.value)?r.value:r.value==null||r.value===""?[]:[r.value]).map(i=>t.get(String(i))??String(i)).join(", ")},Ht=e=>{const t=new Map(C(e).map((r,i)=>[String(r.value),i]));return r=>r==null||r===""?null:t.get(String(r))??t.size},Ce=Ye,y=e=>({editable:e.editable??!1}),J=e=>t=>E(t.value,e),D=e=>e.oldValue!=null&&typeof e.oldValue!="string"&&String(e.oldValue)===e.newValue?e.oldValue:e.newValue,Ut=e=>t=>{const r=typeof t.rawInput=="string"?t.rawInput:t.newValue;if(r==null||typeof r=="string"&&r.trim()==="")return null;if(r instanceof Date)return e.time?r.toISOString():R({y:r.getFullYear(),mo:r.getMonth()+1,d:r.getDate(),time:null},e);const i=String(r).trim();if(/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2})?/.test(i)){if(!e.time)return i.slice(0,10);if(i.length>10&&i[10]==="T")return i}const o=xe(i,e);return o?R(o,e,t.oldValue):t.oldValue},Q=e=>(Array.isArray(e)?e:e==null||e===""?[]:[e]).map(t=>pe(t)?.name??String(t)).join(", "),De=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=W(),i=a=>{const d=a.toLowerCase();return r.find(m=>m.id.toLowerCase()===d||m.name.toLowerCase()===d||m.email?.toLowerCase()===d)?.id??(r.length?void 0:a)},o=e?j(t.rawInput):t.rawInput.split(/\n/).map(a=>a.trim()).filter(Boolean),n=o.map(i).filter(a=>a!==void 0);return o.length&&!n.length?t.oldValue:e?[...new Set(n)]:o.length?n[0]:null},_t=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=T(e.table);if(!r)return t.newValue;const i=j(t.rawInput),o=ut(r,i);if(r.records&&r.resolveNames&&t.data&&t.columnId){const n=i.filter(a=>st(r,a)==null);n.length&&r.resolveNames({row:t.data,columnId:t.columnId,multiple:e.multiple!==!1},n,o)}return i.length&&!o.length?t.oldValue:e.multiple===!1?o.slice(0,1):o},zt=e=>typeof e.rawInput=="string"?e.rawInput.trim()?gt(e.rawInput):null:Array.isArray(e.newValue)?ht(e.newValue):e.newValue??null,Wt=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=t.rawInput.trim();if(!r)return null;const i=Number(r);return Number.isInteger(i)&&i>=0&&i<=Number(e.max??5)?i:t.oldValue},Gt=e=>{const t=typeof e.rawInput=="string"?e.rawInput:e.newValue;return t==null||String(t).trim()===""?null:$(t)??e.oldValue},jt=e=>t=>{const r=typeof t.rawInput=="string"?t.rawInput:t.newValue;return r==null||typeof r=="string"&&r.trim()===""?null:ge(r,{seconds:!!e.showSeconds})??t.oldValue};function ee(e,t){if(e==null)return"";if(Array.isArray(e))return e.map(r=>ee(r,t)).join(", ");if(e instanceof Date)return E(e,t);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(t.result==="currency"||t.result==="percent"||t.result==="number"){const r=t.result,i={...Nt(t),precision:se(r,{precision:t.precision}).places};return r==="currency"?ne(e,{...i,symbol:t.symbol}):r==="percent"?ae(e,i):H(e,i)}return String(Math.round(e*1e10)/1e10)}if(t.result==="date"){const r=rt(String(e));if(r)return E(r,t)}return String(e)}const te=(e,t)=>{const r=t.columns.find(n=>String(n.id??n.field)===e.linkField);if(!r)return null;const i=r.fieldProps?.table,o=r.fieldProps?.inverse;return{key:String(r.field??r.id),get table(){return T(i)},rowsOf(n){const a=T(i),d=String(r.field??r.id);return a&&o&&!a.records&&n?.[d]===void 0?at(a,o,String(n?.id??"")):G(a,n?.[d])},get stored(){const n=T(i)?.records;return n&&o&&n.stores(o)?{records:n,field:o}:null}}},$t={SUM:"sum",AVERAGE:"avg",MIN:"min",MAX:"max",COUNT:"count"},Pe=new WeakMap;function re(e,t,r){const i=e?.table?.fields;if(!i)return;let o=Pe.get(i);o||Pe.set(i,o=new Map);const n=`${String(t)}|${r??""}`;if(o.has(n))return o.get(n);const a=i.find(g=>g.field===String(t)),d=a?.fieldType?O({field:a.field,fieldType:a.fieldType,fieldProps:{...a.fieldProps,...r==null?{}:{precision:r}}}).formatter:void 0;return o.set(n,d),d}const L=()=>new Date().toISOString(),xt=new Intl.Collator(void 0,{sensitivity:"base",numeric:!0}),Kt=(e,t)=>{const r=i=>i?me.indexOf(i):me.length;return r(e)-r(t)},Ae=[{key:"watch",get label(){return l("fields.propWatch")},kind:"segmented",choices:[c("all","fields.choiceAllFields"),c("specific","fields.choiceSpecificFields")]},{key:"watchFields",get label(){return l("fields.propWatchFields")},kind:"columns",visible:e=>e.watch==="specific"}];export const BUILTIN_FIELD_TYPES=[{id:"text",get label(){return l("fields.typeText")},get description(){return l("fields.typeTextDescription")},icon:u.text,group:"basic",properties:[v],fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D})},{id:"longText",get label(){return l("fields.typeLongText")},get description(){return l("fields.typeLongTextDescription")},icon:u.longText,group:"basic",width:260,properties:[{key:"richText",get label(){return l("fields.propMarkdown")},kind:"checkbox",get hint(){return l("fields.propMarkdownHint")}}],fill:e=>({...e,editorType:e.editorType??"fieldLongText",valueParser:e.valueParser??D}),cell:Be,hasCell:e=>!!e.richText},{id:"richText",get label(){return l("fields.typeRichText")},get description(){return l("fields.typeRichTextDescription")},icon:u.richText,group:"basic",width:280,defaults:{toolbar:"standard"},properties:[{key:"toolbar",get label(){return l("fields.propToolbar")},kind:"segmented",choices:[c("standard","fields.choiceStandard"),c("full","fields.choiceFull")],get hint(){return l("fields.propToolbarHint")}}],fill:e=>({...e,editorType:e.editorType??"fieldRichText",formatter:e.formatter??(t=>A(t.value)),sortComparator:e.sortComparator??((t,r)=>xt.compare(A(t),A(r))),valueParser:e.valueParser??(t=>Ee(t.newValue))}),cell:Re},{id:"attachment",get label(){return l("fields.typeAttachment")},get description(){return l("fields.typeAttachmentDescription")},icon:u.attachment,group:"basic",width:180,defaults:{maxFiles:20},properties:[{key:"accept",get label(){return l("fields.propAccept")},kind:"text",get placeholder(){return l("fields.propAcceptPlaceholder")}},{key:"maxFiles",get label(){return l("fields.propMaxFiles")},kind:"number",min:1,max:100}],fill:(e,t)=>({...e,editorType:e.editorType??"attachment",formatter:e.formatter??(r=>_e(r.value)),valueParser:e.valueParser??(r=>ze(r.newValue,t))}),cell:Fe},{id:"checkbox",get label(){return l("fields.typeCheckbox")},get description(){return l("fields.typeCheckboxDescription")},icon:u.checkbox,group:"basic",width:90,defaults:{icon:"check",color:"#20c933"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"icon",icons:Ke},M,v],fill:e=>({...e,editorType:e.editorType??"checkbox",align:e.align??"center",toggleOnSecondClick:e.toggleOnSecondClick??!0}),cell:Ie},{id:"singleSelect",get label(){return l("fields.typeSingleSelect")},get description(){return l("fields.typeSingleSelectDescription")},icon:u.singleSelect,group:"basic",width:140,defaults:{options:[]},properties:[ve,v],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",editorOptions:e.editorOptions??C(t),formatter:e.formatter??Me(t),valueParser:e.valueParser??Se(t,!1),sortValue:e.sortValue??Ht(t)}),cell:ie},{id:"multiSelect",get label(){return l("fields.typeMultiSelect")},get description(){return l("fields.typeMultiSelectDescription")},icon:u.multiSelect,group:"basic",width:200,defaults:{options:[]},properties:[ve,v],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",editorMultiple:e.editorMultiple??!0,editorOptions:e.editorOptions??C(t),formatter:e.formatter??Me(t),valueParser:e.valueParser??Se(t,!0)}),cell:ie},{id:"user",get label(){return l("fields.typeUser")},get description(){return l("fields.typeUserDescription")},icon:u.user,group:"basic",width:170,properties:[{key:"multiple",get label(){return l("fields.propMultipleUsers")},kind:"checkbox"},v],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",valueParser:e.valueParser??De(!!t.multiple),editorMultiple:e.editorMultiple??!!t.multiple,editorOptions:e.editorOptions??W().map(r=>({value:r.id,label:r.name})),formatter:e.formatter??(r=>Q(r.value))}),cell:B},{id:"date",get label(){return l("fields.typeDate")},get description(){return l("fields.typeDateDescription")},icon:u.date,group:"basic",width:150,defaults:{dateFormat:"local",timeFormat:"12hour"},properties:[I(),...Y,{key:"defaultToday",get label(){return l("fields.propDefaultToday")},kind:"checkbox"}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??(t.time?"date":"dateString"),editorType:e.editorType??"fieldDate",editorFormatString:e.editorFormatString??We(t),formatter:e.formatter??J(t),valueParser:e.valueParser??Ut(t)}),newRowValue:({props:e})=>{if(!e.defaultToday)return;if(e.time)return L();const t=new Date;return R({y:t.getFullYear(),mo:t.getMonth()+1,d:t.getDate(),time:null},{})}},{id:"phone",get label(){return l("fields.typePhone")},get description(){return l("fields.typePhoneDescription")},icon:u.phone,group:"basic",fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D}),cell:N},{id:"email",get label(){return l("fields.typeEmail")},get description(){return l("fields.typeEmailDescription")},icon:u.email,group:"basic",width:200,fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D}),cell:N},{id:"url",get label(){return l("fields.typeUrl")},get description(){return l("fields.typeUrlDescription")},icon:u.url,group:"basic",width:200,fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D}),cell:N},{id:"barcode",get label(){return l("fields.typeBarcode")},get description(){return l("fields.typeBarcodeDescription")},icon:u.barcode,group:"basic",width:160,fill:e=>({...e,editorType:e.editorType??"text",formatter:e.formatter??(t=>t.value&&typeof t.value=="object"?String(t.value.text??""):String(t.value??""))}),cell:Oe},{id:"button",get label(){return l("fields.typeButton")},get description(){return l("fields.typeButtonDescription")},icon:u.button,group:"basic",width:120,defaults:{label:"Open",color:"#2d7ff9",action:"link"},properties:[{key:"label",get label(){return l("fields.propButtonLabel")},kind:"text",get placeholder(){return l("fields.propButtonLabelPlaceholder")}},{key:"color",get label(){return l("fields.propButtonStyle")},kind:"color",palette:ue},{key:"action",get label(){return l("fields.propButtonAction")},kind:"choice",choices:Dt},{key:"url",get label(){return l("fields.propButtonUrl")},kind:"text",get placeholder(){return l("fields.propButtonUrlPlaceholder")},get hint(){return l("fields.propButtonUrlHint")},visible:e=>b(e)==="link"},{key:"values",get label(){return l("fields.propButtonValues")},kind:"recordValues",get hint(){return l("fields.propButtonValuesHint")},visible:e=>b(e)==="update"},{key:"template",get label(){return l("fields.propButtonTemplate")},kind:"choice",get hint(){return l("fields.propButtonTemplateHint")},visible:e=>b(e)==="template",choices:e=>(e.ctrl?.props?.baseRecordTemplates?.()??[]).map(t=>({value:t.id,label:t.name}))},{key:"recordAction",get label(){return l("fields.propButtonRecordAction")},kind:"choice",visible:e=>b(e)==="recordAction",choices:e=>he(e.ctrl?.props?.baseTableId).map(t=>({value:t.id,label:t.label}))},{key:"copy",get label(){return l("fields.propButtonCopy")},kind:"text",get placeholder(){return l("fields.propButtonCopyPlaceholder")},get hint(){return l("fields.propButtonCopyHint")},visible:e=>b(e)==="copy"},{key:"doneLabel",get label(){return l("fields.propButtonDoneLabel")},kind:"text",get placeholder(){return l("fields.propButtonDoneLabelPlaceholder")},get hint(){return l("fields.propButtonDoneLabelHint")},visible:e=>b(e)==="update"||b(e)==="template"},{key:"when",get label(){return l("fields.propButtonWhen")},kind:"filter",get hint(){return l("fields.propButtonWhenHint")}},{key:"who",get label(){return l("fields.propButtonWho")},kind:"people",get everyone(){return l("fields.buttonWhoEveryone")},get only(){return l("fields.whoOnly")},get hint(){return l("fields.propButtonWhoHint")}},{key:"ask",get label(){return l("fields.propButtonAsk")},kind:"checkbox",visible:e=>b(e)!=="delete"},{key:"askText",get label(){return l("fields.propButtonAskText")},kind:"text",get placeholder(){return l("fields.buttonAskDefault")},visible:e=>!!e.ask&&b(e)!=="delete"}],fill:(e,t,r)=>{const i=Ce(r.columns),o=(g,m,S)=>{if(!g.trim())return null;if(!m)return p=>p?vt(g,p,i,S):"";const s=O({id:`${String(e.id??e.field)}__button`,field:`__button_${String(e.field??e.id)}`,fieldType:"formula",fieldProps:{formula:g}},r.columns).fieldFn;return p=>{if(!s||!p)return"";const f=s(p);return f==="#ERROR"?"":ee(f,{})}},n=String(t.url??""),a=String(t.copy??""),d=a.trim().startsWith("=");return{...e,...y(e),sortable:e.sortable??!1,__fieldNames:i,__buttonLink:o(n,!!n.trim()&&!wt(n),!0),__buttonCopy:o(d?a.trim().slice(1):a,d,!1)}},cell:Le},{id:"checklist",get label(){return l("fields.typeChecklist")},get description(){return l("fields.typeChecklistDescription")},icon:u.checklist,group:"basic",width:150,fill:e=>({...e,editorType:e.editorType??"fieldChecklist",formatter:e.formatter??(t=>mt(t.value)),valueParser:e.valueParser??zt,sortValue:e.sortValue??ft,groupValue:e.groupValue??pt,groupOrder:e.groupOrder??Kt}),cell:He},{id:"color",get label(){return l("fields.typeColor")},get description(){return l("fields.typeColorDescription")},icon:u.color,group:"basic",width:130,properties:[v],fill:e=>({...e,editorType:e.editorType??"fieldColor",formatter:e.formatter??(t=>$(t.value)??String(t.value??"")),valueParser:e.valueParser??Gt,sortValue:e.sortValue??bt}),newRowValue:({props:e})=>e.default==null||e.default===""?void 0:$(e.default),cell:Ue},{id:"number",get label(){return l("fields.typeNumber")},get description(){return l("fields.typeNumberDescription")},icon:u.number,group:"number",width:120,defaults:{format:"decimal",precision:1,separators:"local",showThousands:!0,abbreviation:"none",allowNegative:!0,symbol:"$",symbolPosition:"before",showBar:!1,points:!1,step:1},properties:[{key:"format",get label(){return l("fields.propFormat")},kind:"segmented",choices:[c("integer","fields.choiceInteger"),c("decimal","fields.choiceDecimal"),c("currency","fields.choiceCurrency"),c("percent","fields.choicePercent")],alsoSets:e=>({precision:e==="decimal"?1:e==="currency"?2:0})},{key:"symbol",get label(){return l("fields.propCurrencySymbol")},kind:"text",placeholder:"$, €, £, ¥, CHF, kr",visible:e=>e.format==="currency"},{key:"symbolPosition",get label(){return l("fields.propSymbolPosition")},kind:"segmented",visible:e=>e.format==="currency",choices:[c("before","fields.choiceBefore"),c("after","fields.choiceAfter")]},X(K(0,8),e=>e.format!=="integer"),{key:"step",get label(){return l("fields.propStep")},kind:"number",min:0,get hint(){return l("fields.propStepHint")}},Pt,At,Vt(e=>e.format!=="percent"),Ft,{key:"showBar",get label(){return l("fields.propShowBar")},kind:"checkbox",visible:e=>e.format==="percent"},{key:"points",get label(){return l("fields.propPoints")},kind:"checkbox",visible:e=>e.format==="percent"},v],fill:(e,t)=>q(e,t,$e("number",t)),cell:le,hasCell:e=>e.format==="percent"&&!!e.showBar},{id:"currency",get label(){return l("fields.typeCurrency")},get description(){return l("fields.typeCurrencyDescription")},icon:u.currency,group:"number",width:120,defaults:{symbol:"$",symbolPosition:"before",precision:2,separators:"local",showThousands:!0,abbreviation:"none",allowNegative:!0},editAs:{type:"number",props:{format:"currency"}},fill:(e,t)=>q(e,t,"currency")},{id:"percent",get label(){return l("fields.typePercent")},get description(){return l("fields.typePercentDescription")},icon:u.percent,group:"number",width:110,defaults:{precision:0,separators:"local",showThousands:!0,allowNegative:!0,points:!1},editAs:{type:"number",props:{format:"percent"}},fill:(e,t)=>q(e,t,"percent"),cell:le,hasCell:e=>!!e.showBar},{id:"duration",get label(){return l("fields.typeDuration")},get description(){return l("fields.typeDurationDescription")},icon:u.duration,group:"number",width:110,defaults:{durationFormat:"h:mm"},properties:[{key:"durationFormat",get label(){return l("fields.propDurationFormat")},kind:"choice",choices:[{value:"h:mm",label:"h:mm"},{value:"h:mm:ss",label:"h:mm:ss"},{value:"h:mm:ss.S",label:"h:mm:ss.S"},{value:"h:mm:ss.SS",label:"h:mm:ss.SS"},{value:"h:mm:ss.SSS",label:"h:mm:ss.SSS"}]}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldNumber",formatter:e.formatter??(r=>{const i=U(r.value);return i==null?"":oe(i,t.durationFormat)}),valueParser:e.valueParser??(r=>typeof r.rawInput=="string"?r.rawInput.trim()?V(r.rawInput)??r.oldValue:null:typeof r.newValue=="number"?r.newValue:V(r.newValue))})},{id:"timeOfDay",get label(){return l("fields.typeTimeOfDay")},get description(){return l("fields.typeTimeOfDayDescription")},icon:u.timeOfDay,group:"number",width:120,defaults:{timeFormat:"12hour",showSeconds:!1},properties:[{key:"timeFormat",get label(){return l("fields.propTimeFormat")},kind:"segmented",choices:ke},{key:"showSeconds",get label(){return l("fields.propShowSeconds")},kind:"checkbox"},v],fill:(e,t)=>({...e,editorType:e.editorType??"fieldTime",formatter:e.formatter??(r=>yt(r.value,t)),valueParser:e.valueParser??jt(t),sortValue:e.sortValue??kt}),newRowValue:({props:e})=>e.default==null||e.default===""?void 0:ge(e.default,{seconds:!!e.showSeconds})},{id:"rating",get label(){return l("fields.typeRating")},get description(){return l("fields.typeRatingDescription")},icon:u.rating,group:"number",width:130,defaults:{max:5,icon:"star",color:"#fcb400"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"icon",icons:Xe},M,{key:"max",get label(){return l("fields.propMaximum")},kind:"choice",choices:Array.from({length:10},(e,t)=>({value:String(t+1),label:String(t+1)}))}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",align:e.align??"left",editorType:e.editorType??"fieldRating",valueParser:e.valueParser??Wt(t)}),cell:Ve},{id:"timer",get label(){return l("fields.typeTimer")},get description(){return l("fields.typeTimerDescription")},icon:u.timer,group:"number",width:130,defaults:{durationFormat:"h:mm:ss"},properties:[{key:"durationFormat",get label(){return l("fields.propDurationFormat")},kind:"choice",choices:[{value:"h:mm",label:"h:mm"},{value:"h:mm:ss",label:"h:mm:ss"}]},M],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldTimer",align:e.align??"left",sortValue:e.sortValue??(r=>F(r)),formatter:e.formatter??(r=>{const i=F(r.value);return i==null?"":oe(i,t.durationFormat??"h:mm:ss")}),valueParser:e.valueParser??(r=>typeof r.rawInput=="string"?r.rawInput.trim()?V(r.rawInput)??r.oldValue:null:r.newValue==null||r.newValue===""?null:typeof r.newValue=="number"||typeof r.newValue=="object"&&Qe(r.newValue)!=null?r.newValue:V(r.newValue))}),cell:Je},{id:"vote",get label(){return l("fields.typeVote")},get description(){return l("fields.typeVoteDescription")},icon:u.vote,group:"basic",width:100,defaults:{icon:"up"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"segmented",choices:[c("up","fields.choiceArrow"),c("thumb","fields.choiceThumb"),c("heart","fields.choiceHeart")]},M],fill:e=>({...e,editorType:e.editorType??"fieldVote",editorOptions:e.editorOptions??W().map(t=>({value:t.id,label:t.name})),align:e.align??"left",sortValue:e.sortValue??(t=>de(t)),formatter:e.formatter??(t=>String(de(t.value))),valueParser:e.valueParser??(t=>Ze(De(!0)(t)))}),newRowValue:()=>[],cell:qe},{id:"sparkline",get label(){return l("fields.typeSparkline")},get description(){return l("fields.typeSparklineDescription")},icon:u.sparkline,group:"number",width:160,defaults:{chart:"line"},properties:[{key:"chart",get label(){return l("fields.propChart")},kind:"segmented",choices:[c("line","fields.choiceLine"),c("area","fields.choiceArea"),c("bar","fields.choiceColumns")]},M,{key:"showLast",get label(){return l("fields.propShowLast")},kind:"checkbox"}],fill:e=>({...e,formatter:e.formatter??(t=>z(t.value).join(", ")),valueParser:e.valueParser??(t=>{const r=z(t.newValue);return r.length?r:null}),sortValue:e.sortValue??(t=>z(t).at(-1)??null)}),cell:et},{id:"formula",get label(){return l("fields.typeFormula")},get description(){return l("fields.typeFormulaDescription")},icon:u.formula,group:"computed",width:160,defaults:{formula:"",result:"auto"},properties:[{key:"formula",get label(){return l("fields.propFormula")},kind:"formula"},{key:"result",get label(){return l("fields.propResult")},kind:"choice",choices:[c("auto","fields.choiceAsComputed"),c("number","fields.choiceNumber"),c("currency","fields.choiceCurrency"),c("percent","fields.choicePercent"),c("date","fields.choiceDate")]},X(K(0,8),e=>["number","currency","percent"].includes(e.result)),{key:"symbol",get label(){return l("fields.propCurrencySymbol")},kind:"text",placeholder:"$",visible:e=>e.result==="currency"},I(e=>e.result==="date")],fill:(e,t,r)=>{const i=Ce(r.columns),o=String(t.formula??""),n=String(e.field??e.id),a=new Set([n.toLowerCase(),typeof e.header=="string"?e.header.trim().toLowerCase():""].filter(Boolean)),d=s=>{const p=s.trim().toLowerCase(),f=i[p]??null;if(f===n||f==null&&a.has(p))throw lt(s);return f};let g=null;try{g=o.trim()?tt(o,d).fn:()=>null}catch{g=null}let m=null;const S=()=>{if(m)return m;m=new Map;for(const s of r.columns){if(s.fieldType==="richText"){const h=String(s.field??s.id);m.set(h,k=>A(k?.[h]));continue}if(s.fieldType==="timer"){const h=String(s.field??s.id);m.set(h,k=>F(k?.[h]));continue}const p=Mt(s);if(p){m.set(String(s.field??s.id),p);continue}if(!ce.has(String(s.fieldType))||String(s.field??s.id)===n)continue;const f=O(s,r.columns);typeof f.fieldFn=="function"&&m.set(String(s.field??s.id),f.fieldFn)}return m},P=s=>{const p=S();return!p.size||!s?s:new Proxy(s,{get:(f,h)=>{const k=typeof h=="string"?p.get(h):void 0;if(!k||w>3)return f[h];w+=1;try{return k(f)}finally{w-=1}}})};return{...e,...y(e),fieldFn:s=>g?g(P(s)):"#ERROR",align:e.align??(["number","currency","percent"].includes(t.result)?"right":void 0),formatter:e.formatter??(s=>ee(s.value,t))}}},{id:"createdTime",get label(){return l("fields.typeCreatedTime")},get description(){return l("fields.typeCreatedTimeDescription")},icon:u.createdTime,group:"computed",width:170,defaults:{dateFormat:"local",time:!0,timeFormat:"12hour"},properties:[I(),...Y],fill:(e,t)=>({...e,...y(e),formatter:e.formatter??J(t)}),newRowValue:()=>L(),onCreate:({rows:e})=>e.map(()=>L())},{id:"lastModifiedTime",get label(){return l("fields.typeLastModifiedTime")},get description(){return l("fields.typeLastModifiedTimeDescription")},icon:u.modifiedTime,group:"computed",width:170,defaults:{dateFormat:"local",time:!0,timeFormat:"12hour",watch:"all"},properties:[...Ae,I(),...Y],fill:(e,t)=>({...e,...y(e),formatter:e.formatter??J(t)}),newRowValue:()=>L()},{id:"createdBy",get label(){return l("fields.typeCreatedBy")},get description(){return l("fields.typeCreatedByDescription")},icon:u.createdBy,group:"computed",width:160,fill:e=>({...e,...y(e),formatter:e.formatter??(t=>Q(t.value))}),newRowValue:()=>fe()?.id??null,cell:B},{id:"lastModifiedBy",get label(){return l("fields.typeLastModifiedBy")},get description(){return l("fields.typeLastModifiedByDescription")},icon:u.modifiedBy,group:"computed",width:160,defaults:{watch:"all"},properties:Ae,fill:e=>({...e,...y(e),formatter:e.formatter??(t=>Q(t.value))}),newRowValue:()=>fe()?.id??null,cell:B},{id:"autoNumber",get label(){return l("fields.typeAutoNumber")},get description(){return l("fields.typeAutoNumberDescription")},icon:u.autoNumber,group:"computed",width:100,fill:e=>({...e,...y(e),cellDataType:e.cellDataType??"number"}),newRowValue:({rows:e,field:t})=>e.reduce((r,i)=>Math.max(r,Number(i?.[t])||0),0)+1,onCreate:({rows:e})=>e.map((t,r)=>r+1)},{id:"link",get label(){return l("fields.typeLink")},get description(){return l("fields.typeLinkDescription")},icon:u.link,group:"relation",width:200,defaults:{multiple:!0},properties:[{key:"table",get label(){return l("fields.propTable")},kind:"choice",choices:()=>nt().map(e=>({value:e.id,label:e.name})),get hint(){return l("fields.propTableHint")},alsoSets:()=>({pickFrom:""})},{key:"multiple",get label(){return l("fields.propMultipleRecords")},kind:"checkbox"},{key:"pickFrom",get label(){return l("fields.propPickFrom")},kind:"choice",choices:e=>[{value:"",label:l("fields.pickFromAll")},...(T(e.props.table)?.views?.()??[]).filter(t=>!t.personal&&t.type!=="form").map(t=>({value:t.id,label:t.name}))],visible:e=>!!e.table,get hint(){return l("fields.propPickFromHint")}}],fill:(e,t)=>({...e,editorType:e.editorType??"fieldLink",formatter:e.formatter??(r=>{const i=T(t.table);return G(i,r.value).map(o=>String(o[i.primaryField]??"")).join(", ")}),valueParser:e.valueParser??_t(t),groupValue:e.groupValue??(r=>ot(t.table,r)),groupCopies:!0}),cell:Ne},{id:"lookup",get label(){return l("fields.typeLookup")},get description(){return l("fields.typeLookupDescription")},icon:u.lookup,group:"relation",width:180,properties:[Z,Te],fill:(e,t,r)=>{const i=te(t,r),o=n=>{const a=re(i,t.field);return String(a?a({value:n})??"":n)};return{...e,...y(e),fieldSource:()=>i?.table?.fields?.find(n=>n.field===String(t.field)),fieldFn:n=>{if(!i)return[];const a=x(i.table,String(t.field)),d=i.stored;return d?d.records.allLinkedTo(d.field,String(n?.id??"")).map(a):i.rowsOf(n).map(a)},formatter:e.formatter??(n=>Array.isArray(n.value)?n.value.filter(a=>a!=null&&a!=="").map(o).join(", "):n.value==null?"":o(n.value))}}},{id:"rollup",get label(){return l("fields.typeRollup")},get description(){return l("fields.typeRollupDescription")},icon:u.rollup,group:"relation",width:140,defaults:{aggregation:"SUM"},properties:[Z,Te,{key:"aggregation",get label(){return l("fields.propAggregation")},kind:"choice",choices:Object.keys(_).map(e=>({value:e,label:e}))},X(K(0,8),e=>["SUM","AVERAGE","MIN","MAX"].includes(e.aggregation))],fill:(e,t,r)=>{const i=te(t,r),o=_[String(t.aggregation)]??_.SUM,n=String(i?.table?.fields?.find(s=>s.field===String(t.field))?.fieldType??""),a=["MIN","MAX"].includes(String(t.aggregation))&&["date","createdTime","lastModifiedTime"].includes(n),d=!a&&!ce.has(n),g=!a&&["SUM","AVERAGE","MIN","MAX","COUNT","COUNTA","COUNTALL"].includes(String(t.aggregation)),m=["SUM","AVERAGE","MIN","MAX"].includes(String(t.aggregation)),S=s=>{const p=m?re(i,t.field,t.precision):void 0;return p?String(p({value:s})??""):H(s,{precision:we(t,0)})},P=s=>{const p=re(i,t.field),f=s instanceof Date?s.toISOString():s;return String(p?p({value:f})??"":f??"")};return{...e,...y(e),...g?{cellDataType:e.cellDataType??"number"}:{},...a?{cellDataType:e.cellDataType??"dateString"}:{},align:e.align??(g?"right":void 0),fieldSource:()=>i?.table?.fields?.find(s=>s.field===String(t.field)),fieldFn:s=>{if(!i)return null;const p=x(i.table,String(t.field)),f=i.stored;if(f&&!d)return o(f.records.allLinkedTo(f.field,String(s?.id??"")).map(p));if(f){const h=String(s?.id??""),k=$t[String(t.aggregation)];return k?f.records.total(f.field,h,String(t.field),k)??null:t.aggregation==="COUNTA"||t.aggregation==="COUNTALL"?f.records.total(f.field,h)??null:o(f.records.allLinkedTo(f.field,h).map(p))}return o(i.rowsOf(s).map(p))},formatter:e.formatter??(s=>{if(a)return s.value==null||s.value===""?"":P(s.value);const p=g?U(s.value):typeof s.value=="number"?s.value:null;return p==null?String(s.value??""):S(p)})}}},{id:"count",get label(){return l("fields.typeCount")},get description(){return l("fields.typeCountDescription")},icon:u.count,group:"relation",width:90,properties:[Z],fill:(e,t,r)=>{const i=te(t,r);return{...e,...y(e),cellDataType:e.cellDataType??"number",formatter:o=>o.value==null?"":Number(o.value).toLocaleString(),fieldFn:o=>{if(!i)return 0;const n=i.stored;return n?n.records.total(n.field,String(o?.id??""))??null:i.rowsOf(o).length}}}},dt];
@@ -303,6 +303,8 @@ export declare const EXTRAS_MESSAGES: {
303
303
  readonly 'extras.aiInto': "Put the answer in";
304
304
  readonly 'extras.aiNowhere': "No field (use {ai} in the next steps)";
305
305
  readonly 'extras.aiHint': "Name fields in braces. The answer is {ai} in the next steps.";
306
+ readonly 'extras.aiBase': "Send it the whole base";
307
+ readonly 'extras.aiBaseHint': "The records of every table go with the prompt, for a letter about all of it (\"What should I do this week?\").";
306
308
  readonly 'extras.scriptCode': "Script";
307
309
  readonly 'extras.scriptNeedsBrowser': "A script runs in the browser: set Runs in to The browser.";
308
310
  readonly 'extras.scriptHint': "JavaScript, as in Airtable: input.config() has the record's fields by name; base.getTable('Name') reads and changes a table (selectRecordsAsync, updateRecordAsync, createRecordAsync, deleteRecordAsync); output.set('name', value) is {script.name} in the next steps; fetch() calls https addresses that allow it. It runs in a sandbox for up to 30 seconds.";
@@ -1 +1 @@
1
- export const EXTRAS_MESSAGES={"extras.whenCreated":"When a record is created","extras.whenCreatedWhere":"When a record is created, where {condition}","extras.whenRecordChanges":"When a record changes","extras.whenRecordChangesWhere":"When a record changes, where {condition}","extras.whenFieldsChange":"When {fields} changes","extras.whenFieldsChangeWhere":"When {fields} changes, where {condition}","extras.fieldsOr":" or ","extras.whenMatches":"When a record matches: {condition}","extras.noConditionYet":"no condition yet","extras.whenForm":"When a form is sent","extras.whenFormWhere":"When a form is sent, where {condition}","extras.whenPressed":"When {field} is pressed","extras.onSchedule":"{cron}","extras.onScheduleWhere":"{cron}, for records where {condition}","extras.cronOther":"On a schedule ({cron})","extras.cronEveryMinute":"Every minute","extras.cronEveryMinutes":"Every {n} minutes","extras.cronHourly":"Every hour, on the hour","extras.cronHourlyAt":"Every hour at {minute} past","extras.cronDaily":"Every day at {time}","extras.cronWeekdays":"Every weekday at {time}","extras.cronWeekly0":"Every Sunday at {time}","extras.cronWeekly1":"Every Monday at {time}","extras.cronWeekly2":"Every Tuesday at {time}","extras.cronWeekly3":"Every Wednesday at {time}","extras.cronWeekly4":"Every Thursday at {time}","extras.cronWeekly5":"Every Friday at {time}","extras.cronWeekly6":"Every Saturday at {time}","extras.cronDays":"Every {days} at {time}","extras.cronDay0":"Sunday","extras.cronDay1":"Monday","extras.cronDay2":"Tuesday","extras.cronDay3":"Wednesday","extras.cronDay4":"Thursday","extras.cronDay5":"Friday","extras.cronDay6":"Saturday","extras.cronMonthly":"Day {day} of every month at {time}","extras.actionUpdateRecord":"Update record","extras.actionCreateRecord":"Create record","extras.actionNotify":"Show a notice","extras.actionHighlight":"Color the record","extras.actionWebhook":"Call a webhook","extras.actionEmail":"Send an email","extras.stepStopped":"Stopped","extras.stepLoop":"Automations set each other off {max} times in a row; this one did not run, so they cannot loop.","extras.stepNotice":"Notice","extras.stepWebhook":"Webhook","extras.stepEmail":"Email","extras.stepNotRun":"Not run","extras.stepNoMatch":"The record does not match the condition","extras.stepDone":"Done","extras.noRecordToUpdate":"No record to update","extras.alreadySet":"Already set","extras.noTable":'No table "{table}"',"extras.noAction":'No action "{action}" is registered',"extras.aRecord":"a record","extras.createdIn":"{name} in {table}","extras.saidValue":"{field}: {value}","extras.saidChecked":"{field}: checked","extras.saidUnchecked":"{field}: unchecked","extras.saidEmpty":"empty","extras.title":"Automations in {table}","extras.listLabel":"Automations","extras.untitled":"Untitled","extras.switchOn":"{name} on","extras.noAutomations":"No automations yet. An automation does something when a record is added, changes or matches a condition.","extras.addAutomation":"+ New automation","extras.describeLabel":"Describe what should happen","extras.describePlaceholder":"For example: every Monday at 8:00, e-mail me the tasks that are not done","extras.describeButton":"Draft it","extras.describing":"Drafting...","extras.describeAgain":"Say a little more about what should happen, then try again.","extras.drafted":"Drafted from your words and switched off. Check each part, then switch it on.","extras.newAutomation":"New automation","extras.newRecordMessage":"New record: {{field}}","extras.nameFallback":"Name","extras.runs":"Runs","extras.clearRuns":"Clear this page's runs","extras.serverRunsFailed":"The server's runs did not load: {message}","extras.statusDone":"Done","extras.statusFailed":"Failed","extras.statusStopped":"Stopped","extras.runOn":"on {record}","extras.runIn":"in {table}","extras.serverTag":"Server","extras.noRuns":"Nothing has run yet. Runs show here with what each action did.","extras.name":"Name","extras.runsIn":"Runs in","extras.runsInBrowser":"This browser","extras.runsInServer":"The server","extras.serverHint":"Your server runs it (createAutomationServer): it hears changes from the database, whoever made them, reads secrets and sends email.","extras.browserHint":"It runs in the browser of the person who makes the change, right away.","extras.when":"When","extras.trigger":"Trigger","extras.triggerCreated":"A record is created","extras.triggerUpdated":"A record changes","extras.triggerMatches":"A record matches a condition","extras.triggerForm":"A form is sent","extras.triggerButton":"A button is pressed","extras.triggerScheduled":"At a scheduled time","extras.watchSome":"Only when one of these fields changes:","extras.watchAny":"Any field. Pick fields to watch only those:","extras.form":"Form","extras.anyForm":"Any form of this table","extras.buttonField":"Button field","extras.addButtonFirst":"Add a Button field to the table first.","extras.schedule":"Schedule","extras.customSchedule":"Custom","extras.cronExpression":"Cron expression","extras.scheduleHint":"Runs while the base is open in a browser. With a condition, it runs once for each record that matches at that time.","extras.condition":"Condition","extras.onlyWhere":"Only for records where","extras.startsToMatch":"Runs when a record starts to match","extras.addMatchCondition":"Add the condition a record has to start matching.","extras.everyRecord":"Every record. Add a condition to narrow it.","extras.do":"Do","extras.action":"Action","extras.doUpdateRecord":"Update the record","extras.doCreateRecord":"Create a record","extras.doHighlight":"Color the record while it matches","extras.moveUp":"Move up","extras.moveDown":"Move down","extras.moveStepUp":"Move step {step} up","extras.moveStepDown":"Move step {step} down","extras.removeStep":"Remove step {step}","extras.stepMoved":"Step {from} is now step {to}.","extras.removeAction":"Remove action","extras.message":"Message","extras.notifyPlaceholder":"{{field}} needs a look","extras.kind":"Kind","extras.severityInfo":"Info","extras.severitySuccess":"Success","extras.severityWarning":"Warning","extras.severityError":"Error","extras.notifyHint":"Name a field in braces for its value: {fields}.","extras.notifyTo":"Also send it to the notifications of:","extras.notifyToField":"The people in {field}","extras.highlightNeedsCondition":"Colors records while they match the condition above; add one.","extras.fill":"Fill","extras.text":"Text","extras.sample":"Sample","extras.wholeRow":"Whole row","extras.in":"In","extras.table":"Table","extras.linkBack":"Link it back","extras.linkField":"Link field","extras.noLink":"No link","extras.through":"through {field}","extras.valueOf":"{field} value","extras.valuePlaceholder":"a value, or {Field}","extras.numberPlaceholder":"0, or 100% for a percent","extras.linkPlaceholder":"a record name, or {record}","extras.userPlaceholder":"a name","extras.doNotSet":"Do not set {field}","extras.remove":"Remove","extras.setField":"Set a field","extras.addSetField":"+ Set a field","extras.runsApp":"Runs {action}, an action the app registered.","extras.method":"Method","extras.url":"URL","extras.headers":"Headers","extras.body":"Body","extras.webhookHintServer":"Empty body: the record as JSON. {secret} is read on the server only.","extras.webhookHintBrowser":"Empty body: the record as JSON. {secret} is read on the server only; set Runs in to The server to use one.","extras.emailNeedsServer":"Email is sent by the server: set Runs in to The server.","extras.to":"To","extras.toPlaceholder":"team@example.com, {Owner email}","extras.subject":"Subject","extras.emailText":"Email text","extras.addAction":"Add an action","extras.addActionOption":"+ Add an action","extras.deleteIt":"Delete it?","extras.delete":"Delete","extras.keep":"Keep","extras.deleteAutomation":"Delete automation","extras.triggerEntersView":"A record enters a view","extras.view":"View","extras.pickView":"Pick a view","extras.aView":"a view","extras.entersViewHint":"Runs once when a record starts to show in this view, through its filter, as the view has it then. It runs again only after the record has left the view.","extras.addViewFilterFirst":"First give a view of this table a filter: this trigger runs when a record starts to show in it.","extras.whenEntersView":"When a record enters {view}","extras.whenEntersViewWhere":"When a record enters {view}, where {condition}","extras.doDeleteRecord":"Delete the record","extras.actionDeleteRecord":"Delete record","extras.deleteRecordHint":"Deletes the record that started the automation (inside Find records, each record found). It goes to the trash, where it can be restored for 30 days.","extras.noRecordToDelete":"No record to delete","extras.deletedRecord":"Deleted {name}","extras.cannotDeleteHere":"This table cannot delete records from an automation.","extras.summaryDelete":"Deletes the record","extras.duplicateAutomation":"Duplicate","extras.copyOf":"{name} copy","extras.duplicated":"Copied. The copy is off until you turn it on.","extras.runsOnServer":"Runs on your server when its trigger happens.","extras.tryRecord":"Record to try it on","extras.noRecord":"No record","extras.runNow":"Run now","extras.pickAutomation":"Pick an automation, or add one.","extras.noName":"(no name)","extras.noRecordValue":"(no record)","extras.pageLabel":"Automations of the base","extras.createAutomation":"+ Create automation","extras.runHistory":"Run history","extras.pageEmpty":"No automations yet. An automation does something on its own: when a record is added or changes, a form is sent, a button is pressed or at a time you set.","extras.pickOne":"Pick an automation on the left, or create one.","extras.triggerCard":"Trigger","extras.whenIn":"{when}, in {table}","extras.conditionCard":"Only for records where","extras.conditionEvery":"Every record","extras.conditionCount.one":"{count} condition","extras.conditionCount.other":"{count} conditions","extras.addCondition":"+ Add a condition","extras.actionCard":"Action {n}","extras.insertAction":"Add an action here","extras.addActionPage":"+ Add an action","extras.flowLabel":"What {name} does","extras.summarySet":"Set {fields}","extras.summaryNothing":"No fields set yet","extras.summaryCreate":"A new record in {table}","extras.summaryEmail":"To {to}","extras.summaryNoTo":"No address yet","extras.summaryColor":"While it matches","extras.tableOfTrigger":"Table","extras.tableMoveHint":"Its trigger, condition and fields are for this table: a new table starts them again.","extras.settingsOf":"Settings","extras.testOn":"Test on","extras.test":"Test","extras.testRuns":"Its runs show in the run history.","extras.allRunsOf":"Runs of {name}","extras.allRuns":"All runs","extras.showAllRuns":"Show every automation's runs","extras.whenWebhook":"When a webhook is received","extras.triggerWebhook":"A webhook is received","extras.webhookAddress":"Webhook address","extras.webhookNoUrl":"This automation listens for the token {token}: give it to your server runner (webhookReceived).","extras.webhookHint":"Send a POST with a JSON body to this address. Its values are {webhook.name} in the steps ({webhook.order.id} inside objects). Anyone with the address can start the automation: keep it secret.","extras.newAddress":"Make a new address","extras.copy":"Copy","extras.copied":"Copied","extras.actionChat":"Send a message","extras.actionRepeat":"Find records","extras.actionIf":"If","extras.actionAi":"Ask AI","extras.actionScript":"Run a script","extras.doChat":"Send a Slack, Teams or Google Chat message","extras.doRepeat":"Find records and, for each, do","extras.doIf":"If a condition holds, do","extras.doAi":"Ask AI","extras.doScript":"Run a script","extras.stepChat":"Message","extras.stepIf":"If","extras.stepIfThen":"It matched: the Then steps ran","extras.stepIfElse":"It did not match: the Otherwise steps ran","extras.stepFound":"Find records","extras.foundIn":"{count} in {table}","extras.stepAi":"AI","extras.stepScript":"Script","extras.noAi":"No AI model is set up here.","extras.aiNoPrompt":"The prompt is empty.","extras.scriptFailed":"The script failed.","extras.noField":"No field named {field}.","extras.noRecordId":"No record {id}.","extras.stepKind":"{list}, step {n}","extras.addStep":"+ Add a step","extras.addStepTo":"Add a step to {list}","extras.chatApp":"Chat app","extras.chatUrl":"Webhook address","extras.chatHintSlack":"In Slack: Apps, Incoming Webhooks, Add to a channel; paste the address it gives here.","extras.chatHintTeams":`In Teams: the channel's Workflows, "Post to a channel when a webhook request is received"; paste the address it gives here.`,"extras.chatHintGoogle":"In Google Chat: the space's Apps and integrations, Webhooks, Add webhook; paste the address it gives here.","extras.actionText":"Send a text message","extras.doText":"Send a text message (SMS or Viber)","extras.stepText":"Text message","extras.textNeedsServer":"Text messages are sent by the server: set Runs in to The server.","extras.textBy":"Send by","extras.textSms":"SMS","extras.textViber":"Viber (SMS if not on Viber)","extras.textTo":"To","extras.textToPlaceholder":"+359 88 123 4567, {Phone}","extras.textMessage":"Message","extras.textHint":"Phone numbers with their country code, or a phone field in braces; several apart with commas. The text names fields in braces.","extras.summarySms":"SMS to {to}","extras.summaryViber":"Viber to {to}","extras.summaryNoPhone":"No phone yet","extras.ifHint":"When the record matches this condition the Then steps run, otherwise the Otherwise steps.","extras.ifAlways":"No condition: Then always runs","extras.then":"Then","extras.otherwise":"Otherwise","extras.findIn":"Find in","extras.whichRecords":"Records where","extras.atMost":"At most","extras.forEach":"For each record found","extras.repeatHint":"In these steps {Field} is the found record's field, {trigger.Field} the field of the record that set the automation off, and {found} how many were found.","extras.aiPrompt":"Prompt","extras.aiPlaceholder":"Write a two-line summary of {{field}} for a weekly report.","extras.aiInto":"Put the answer in","extras.aiNowhere":"No field (use {ai} in the next steps)","extras.aiHint":"Name fields in braces. The answer is {ai} in the next steps.","extras.scriptCode":"Script","extras.scriptNeedsBrowser":"A script runs in the browser: set Runs in to The browser.","extras.scriptHint":"JavaScript, as in Airtable: input.config() has the record's fields by name; base.getTable('Name') reads and changes a table (selectRecordsAsync, updateRecordAsync, createRecordAsync, deleteRecordAsync); output.set('name', value) is {script.name} in the next steps; fetch() calls https addresses that allow it. It runs in a sandbox for up to 30 seconds.","extras.scriptInPageHint":"It runs in the page of the person who made the change, with what they may do. A run with no one's page behind it (a schedule, a webhook, a change through the API) stops at this step and says so.","extras.summaryNoText":"Nothing written yet","extras.stepCount.one":"{count} step","extras.stepCount.other":"{count} steps","extras.summaryRepeat":"{steps} for each record in {table}","extras.summaryIf":"Then {then}; otherwise {otherwise}","extras.summaryScript":"{lines} lines"};
1
+ export const EXTRAS_MESSAGES={"extras.whenCreated":"When a record is created","extras.whenCreatedWhere":"When a record is created, where {condition}","extras.whenRecordChanges":"When a record changes","extras.whenRecordChangesWhere":"When a record changes, where {condition}","extras.whenFieldsChange":"When {fields} changes","extras.whenFieldsChangeWhere":"When {fields} changes, where {condition}","extras.fieldsOr":" or ","extras.whenMatches":"When a record matches: {condition}","extras.noConditionYet":"no condition yet","extras.whenForm":"When a form is sent","extras.whenFormWhere":"When a form is sent, where {condition}","extras.whenPressed":"When {field} is pressed","extras.onSchedule":"{cron}","extras.onScheduleWhere":"{cron}, for records where {condition}","extras.cronOther":"On a schedule ({cron})","extras.cronEveryMinute":"Every minute","extras.cronEveryMinutes":"Every {n} minutes","extras.cronHourly":"Every hour, on the hour","extras.cronHourlyAt":"Every hour at {minute} past","extras.cronDaily":"Every day at {time}","extras.cronWeekdays":"Every weekday at {time}","extras.cronWeekly0":"Every Sunday at {time}","extras.cronWeekly1":"Every Monday at {time}","extras.cronWeekly2":"Every Tuesday at {time}","extras.cronWeekly3":"Every Wednesday at {time}","extras.cronWeekly4":"Every Thursday at {time}","extras.cronWeekly5":"Every Friday at {time}","extras.cronWeekly6":"Every Saturday at {time}","extras.cronDays":"Every {days} at {time}","extras.cronDay0":"Sunday","extras.cronDay1":"Monday","extras.cronDay2":"Tuesday","extras.cronDay3":"Wednesday","extras.cronDay4":"Thursday","extras.cronDay5":"Friday","extras.cronDay6":"Saturday","extras.cronMonthly":"Day {day} of every month at {time}","extras.actionUpdateRecord":"Update record","extras.actionCreateRecord":"Create record","extras.actionNotify":"Show a notice","extras.actionHighlight":"Color the record","extras.actionWebhook":"Call a webhook","extras.actionEmail":"Send an email","extras.stepStopped":"Stopped","extras.stepLoop":"Automations set each other off {max} times in a row; this one did not run, so they cannot loop.","extras.stepNotice":"Notice","extras.stepWebhook":"Webhook","extras.stepEmail":"Email","extras.stepNotRun":"Not run","extras.stepNoMatch":"The record does not match the condition","extras.stepDone":"Done","extras.noRecordToUpdate":"No record to update","extras.alreadySet":"Already set","extras.noTable":'No table "{table}"',"extras.noAction":'No action "{action}" is registered',"extras.aRecord":"a record","extras.createdIn":"{name} in {table}","extras.saidValue":"{field}: {value}","extras.saidChecked":"{field}: checked","extras.saidUnchecked":"{field}: unchecked","extras.saidEmpty":"empty","extras.title":"Automations in {table}","extras.listLabel":"Automations","extras.untitled":"Untitled","extras.switchOn":"{name} on","extras.noAutomations":"No automations yet. An automation does something when a record is added, changes or matches a condition.","extras.addAutomation":"+ New automation","extras.describeLabel":"Describe what should happen","extras.describePlaceholder":"For example: every Monday at 8:00, e-mail me the tasks that are not done","extras.describeButton":"Draft it","extras.describing":"Drafting...","extras.describeAgain":"Say a little more about what should happen, then try again.","extras.drafted":"Drafted from your words and switched off. Check each part, then switch it on.","extras.newAutomation":"New automation","extras.newRecordMessage":"New record: {{field}}","extras.nameFallback":"Name","extras.runs":"Runs","extras.clearRuns":"Clear this page's runs","extras.serverRunsFailed":"The server's runs did not load: {message}","extras.statusDone":"Done","extras.statusFailed":"Failed","extras.statusStopped":"Stopped","extras.runOn":"on {record}","extras.runIn":"in {table}","extras.serverTag":"Server","extras.noRuns":"Nothing has run yet. Runs show here with what each action did.","extras.name":"Name","extras.runsIn":"Runs in","extras.runsInBrowser":"This browser","extras.runsInServer":"The server","extras.serverHint":"Your server runs it (createAutomationServer): it hears changes from the database, whoever made them, reads secrets and sends email.","extras.browserHint":"It runs in the browser of the person who makes the change, right away.","extras.when":"When","extras.trigger":"Trigger","extras.triggerCreated":"A record is created","extras.triggerUpdated":"A record changes","extras.triggerMatches":"A record matches a condition","extras.triggerForm":"A form is sent","extras.triggerButton":"A button is pressed","extras.triggerScheduled":"At a scheduled time","extras.watchSome":"Only when one of these fields changes:","extras.watchAny":"Any field. Pick fields to watch only those:","extras.form":"Form","extras.anyForm":"Any form of this table","extras.buttonField":"Button field","extras.addButtonFirst":"Add a Button field to the table first.","extras.schedule":"Schedule","extras.customSchedule":"Custom","extras.cronExpression":"Cron expression","extras.scheduleHint":"Runs while the base is open in a browser. With a condition, it runs once for each record that matches at that time.","extras.condition":"Condition","extras.onlyWhere":"Only for records where","extras.startsToMatch":"Runs when a record starts to match","extras.addMatchCondition":"Add the condition a record has to start matching.","extras.everyRecord":"Every record. Add a condition to narrow it.","extras.do":"Do","extras.action":"Action","extras.doUpdateRecord":"Update the record","extras.doCreateRecord":"Create a record","extras.doHighlight":"Color the record while it matches","extras.moveUp":"Move up","extras.moveDown":"Move down","extras.moveStepUp":"Move step {step} up","extras.moveStepDown":"Move step {step} down","extras.removeStep":"Remove step {step}","extras.stepMoved":"Step {from} is now step {to}.","extras.removeAction":"Remove action","extras.message":"Message","extras.notifyPlaceholder":"{{field}} needs a look","extras.kind":"Kind","extras.severityInfo":"Info","extras.severitySuccess":"Success","extras.severityWarning":"Warning","extras.severityError":"Error","extras.notifyHint":"Name a field in braces for its value: {fields}.","extras.notifyTo":"Also send it to the notifications of:","extras.notifyToField":"The people in {field}","extras.highlightNeedsCondition":"Colors records while they match the condition above; add one.","extras.fill":"Fill","extras.text":"Text","extras.sample":"Sample","extras.wholeRow":"Whole row","extras.in":"In","extras.table":"Table","extras.linkBack":"Link it back","extras.linkField":"Link field","extras.noLink":"No link","extras.through":"through {field}","extras.valueOf":"{field} value","extras.valuePlaceholder":"a value, or {Field}","extras.numberPlaceholder":"0, or 100% for a percent","extras.linkPlaceholder":"a record name, or {record}","extras.userPlaceholder":"a name","extras.doNotSet":"Do not set {field}","extras.remove":"Remove","extras.setField":"Set a field","extras.addSetField":"+ Set a field","extras.runsApp":"Runs {action}, an action the app registered.","extras.method":"Method","extras.url":"URL","extras.headers":"Headers","extras.body":"Body","extras.webhookHintServer":"Empty body: the record as JSON. {secret} is read on the server only.","extras.webhookHintBrowser":"Empty body: the record as JSON. {secret} is read on the server only; set Runs in to The server to use one.","extras.emailNeedsServer":"Email is sent by the server: set Runs in to The server.","extras.to":"To","extras.toPlaceholder":"team@example.com, {Owner email}","extras.subject":"Subject","extras.emailText":"Email text","extras.addAction":"Add an action","extras.addActionOption":"+ Add an action","extras.deleteIt":"Delete it?","extras.delete":"Delete","extras.keep":"Keep","extras.deleteAutomation":"Delete automation","extras.triggerEntersView":"A record enters a view","extras.view":"View","extras.pickView":"Pick a view","extras.aView":"a view","extras.entersViewHint":"Runs once when a record starts to show in this view, through its filter, as the view has it then. It runs again only after the record has left the view.","extras.addViewFilterFirst":"First give a view of this table a filter: this trigger runs when a record starts to show in it.","extras.whenEntersView":"When a record enters {view}","extras.whenEntersViewWhere":"When a record enters {view}, where {condition}","extras.doDeleteRecord":"Delete the record","extras.actionDeleteRecord":"Delete record","extras.deleteRecordHint":"Deletes the record that started the automation (inside Find records, each record found). It goes to the trash, where it can be restored for 30 days.","extras.noRecordToDelete":"No record to delete","extras.deletedRecord":"Deleted {name}","extras.cannotDeleteHere":"This table cannot delete records from an automation.","extras.summaryDelete":"Deletes the record","extras.duplicateAutomation":"Duplicate","extras.copyOf":"{name} copy","extras.duplicated":"Copied. The copy is off until you turn it on.","extras.runsOnServer":"Runs on your server when its trigger happens.","extras.tryRecord":"Record to try it on","extras.noRecord":"No record","extras.runNow":"Run now","extras.pickAutomation":"Pick an automation, or add one.","extras.noName":"(no name)","extras.noRecordValue":"(no record)","extras.pageLabel":"Automations of the base","extras.createAutomation":"+ Create automation","extras.runHistory":"Run history","extras.pageEmpty":"No automations yet. An automation does something on its own: when a record is added or changes, a form is sent, a button is pressed or at a time you set.","extras.pickOne":"Pick an automation on the left, or create one.","extras.triggerCard":"Trigger","extras.whenIn":"{when}, in {table}","extras.conditionCard":"Only for records where","extras.conditionEvery":"Every record","extras.conditionCount.one":"{count} condition","extras.conditionCount.other":"{count} conditions","extras.addCondition":"+ Add a condition","extras.actionCard":"Action {n}","extras.insertAction":"Add an action here","extras.addActionPage":"+ Add an action","extras.flowLabel":"What {name} does","extras.summarySet":"Set {fields}","extras.summaryNothing":"No fields set yet","extras.summaryCreate":"A new record in {table}","extras.summaryEmail":"To {to}","extras.summaryNoTo":"No address yet","extras.summaryColor":"While it matches","extras.tableOfTrigger":"Table","extras.tableMoveHint":"Its trigger, condition and fields are for this table: a new table starts them again.","extras.settingsOf":"Settings","extras.testOn":"Test on","extras.test":"Test","extras.testRuns":"Its runs show in the run history.","extras.allRunsOf":"Runs of {name}","extras.allRuns":"All runs","extras.showAllRuns":"Show every automation's runs","extras.whenWebhook":"When a webhook is received","extras.triggerWebhook":"A webhook is received","extras.webhookAddress":"Webhook address","extras.webhookNoUrl":"This automation listens for the token {token}: give it to your server runner (webhookReceived).","extras.webhookHint":"Send a POST with a JSON body to this address. Its values are {webhook.name} in the steps ({webhook.order.id} inside objects). Anyone with the address can start the automation: keep it secret.","extras.newAddress":"Make a new address","extras.copy":"Copy","extras.copied":"Copied","extras.actionChat":"Send a message","extras.actionRepeat":"Find records","extras.actionIf":"If","extras.actionAi":"Ask AI","extras.actionScript":"Run a script","extras.doChat":"Send a Slack, Teams or Google Chat message","extras.doRepeat":"Find records and, for each, do","extras.doIf":"If a condition holds, do","extras.doAi":"Ask AI","extras.doScript":"Run a script","extras.stepChat":"Message","extras.stepIf":"If","extras.stepIfThen":"It matched: the Then steps ran","extras.stepIfElse":"It did not match: the Otherwise steps ran","extras.stepFound":"Find records","extras.foundIn":"{count} in {table}","extras.stepAi":"AI","extras.stepScript":"Script","extras.noAi":"No AI model is set up here.","extras.aiNoPrompt":"The prompt is empty.","extras.scriptFailed":"The script failed.","extras.noField":"No field named {field}.","extras.noRecordId":"No record {id}.","extras.stepKind":"{list}, step {n}","extras.addStep":"+ Add a step","extras.addStepTo":"Add a step to {list}","extras.chatApp":"Chat app","extras.chatUrl":"Webhook address","extras.chatHintSlack":"In Slack: Apps, Incoming Webhooks, Add to a channel; paste the address it gives here.","extras.chatHintTeams":`In Teams: the channel's Workflows, "Post to a channel when a webhook request is received"; paste the address it gives here.`,"extras.chatHintGoogle":"In Google Chat: the space's Apps and integrations, Webhooks, Add webhook; paste the address it gives here.","extras.actionText":"Send a text message","extras.doText":"Send a text message (SMS or Viber)","extras.stepText":"Text message","extras.textNeedsServer":"Text messages are sent by the server: set Runs in to The server.","extras.textBy":"Send by","extras.textSms":"SMS","extras.textViber":"Viber (SMS if not on Viber)","extras.textTo":"To","extras.textToPlaceholder":"+359 88 123 4567, {Phone}","extras.textMessage":"Message","extras.textHint":"Phone numbers with their country code, or a phone field in braces; several apart with commas. The text names fields in braces.","extras.summarySms":"SMS to {to}","extras.summaryViber":"Viber to {to}","extras.summaryNoPhone":"No phone yet","extras.ifHint":"When the record matches this condition the Then steps run, otherwise the Otherwise steps.","extras.ifAlways":"No condition: Then always runs","extras.then":"Then","extras.otherwise":"Otherwise","extras.findIn":"Find in","extras.whichRecords":"Records where","extras.atMost":"At most","extras.forEach":"For each record found","extras.repeatHint":"In these steps {Field} is the found record's field, {trigger.Field} the field of the record that set the automation off, and {found} how many were found.","extras.aiPrompt":"Prompt","extras.aiPlaceholder":"Write a two-line summary of {{field}} for a weekly report.","extras.aiInto":"Put the answer in","extras.aiNowhere":"No field (use {ai} in the next steps)","extras.aiHint":"Name fields in braces. The answer is {ai} in the next steps.","extras.aiBase":"Send it the whole base","extras.aiBaseHint":'The records of every table go with the prompt, for a letter about all of it ("What should I do this week?").',"extras.scriptCode":"Script","extras.scriptNeedsBrowser":"A script runs in the browser: set Runs in to The browser.","extras.scriptHint":"JavaScript, as in Airtable: input.config() has the record's fields by name; base.getTable('Name') reads and changes a table (selectRecordsAsync, updateRecordAsync, createRecordAsync, deleteRecordAsync); output.set('name', value) is {script.name} in the next steps; fetch() calls https addresses that allow it. It runs in a sandbox for up to 30 seconds.","extras.scriptInPageHint":"It runs in the page of the person who made the change, with what they may do. A run with no one's page behind it (a schedule, a webhook, a change through the API) stops at this step and says so.","extras.summaryNoText":"Nothing written yet","extras.stepCount.one":"{count} step","extras.stepCount.other":"{count} steps","extras.summaryRepeat":"{steps} for each record in {table}","extras.summaryIf":"Then {then}; otherwise {otherwise}","extras.summaryScript":"{lines} lines"};
@@ -452,6 +452,8 @@ export declare const BASE_MESSAGES: {
452
452
  readonly 'extras.aiInto': "Put the answer in";
453
453
  readonly 'extras.aiNowhere': "No field (use {ai} in the next steps)";
454
454
  readonly 'extras.aiHint': "Name fields in braces. The answer is {ai} in the next steps.";
455
+ readonly 'extras.aiBase': "Send it the whole base";
456
+ readonly 'extras.aiBaseHint': "The records of every table go with the prompt, for a letter about all of it (\"What should I do this week?\").";
455
457
  readonly 'extras.scriptCode': "Script";
456
458
  readonly 'extras.scriptNeedsBrowser': "A script runs in the browser: set Runs in to The browser.";
457
459
  readonly 'extras.scriptHint': "JavaScript, as in Airtable: input.config() has the record's fields by name; base.getTable('Name') reads and changes a table (selectRecordsAsync, updateRecordAsync, createRecordAsync, deleteRecordAsync); output.set('name', value) is {script.name} in the next steps; fetch() calls https addresses that allow it. It runs in a sandbox for up to 30 seconds.";