@objectstack/console 9.6.0 → 9.8.0
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.
- package/dist/assets/{AdapterProvider-o2n9dY2j.js → AdapterProvider-CGofnJBf.js} +1 -1
- package/dist/assets/{AiPendingActionsPage-DGAL-HJ9.js → AiPendingActionsPage-CaJCvm5D.js} +1 -1
- package/dist/assets/{ApiConsolePage-DNuInlzy.js → ApiConsolePage-DGCgQ6RS.js} +1 -1
- package/dist/assets/{AppDocsIndex-DtACBq8P.js → AppDocsIndex-B_hZ36LW.js} +1 -1
- package/dist/assets/{AppManagementPage-BSgP2T9T.js → AppManagementPage-DN-u3YQP.js} +1 -1
- package/dist/assets/ApprovalsInboxPage-BbvtY-xj.js +1 -0
- package/dist/assets/{AuditLogPage-B_gxba-u.js → AuditLogPage-ffz9xeHl.js} +1 -1
- package/dist/assets/{ComponentNavView-BSV-rPCq.js → ComponentNavView-B6LSKpd-.js} +1 -1
- package/dist/assets/ConsoleFloatingChatbot-CsiQ_KDu.js +1 -0
- package/dist/assets/DashboardView-CsknMwAh.js +1 -0
- package/dist/assets/{DashboardWidgetInspector-CNmycNmj.js → DashboardWidgetInspector-DSLIsQS9.js} +1 -1
- package/dist/assets/{DeveloperHubPage-YvUkG7Lt.js → DeveloperHubPage-DZyjalsK.js} +1 -1
- package/dist/assets/{ExpressionProvider-Cuv0RaiR.js → ExpressionProvider-wi1dJ2tN.js} +1 -1
- package/dist/assets/FlowRunsPage-DcT6ntvZ.js +1 -0
- package/dist/assets/{IntegrationsPage-C8k36Ie_.js → IntegrationsPage-Dfl35fAT.js} +2 -2
- package/dist/assets/{InterfaceListPage-DTHEyaKG.js → InterfaceListPage-DAJiEE0k.js} +1 -1
- package/dist/assets/{ManagedByBadge-B60ZX6y9.js → ManagedByBadge-BAL_PuGz.js} +1 -1
- package/dist/assets/MarketplaceAccessDenied-BBUl4uOo.js +1 -0
- package/dist/assets/MarketplaceInstalledPage-CaN54GxZ.js +1 -0
- package/dist/assets/MarketplacePackagePage-SKgqOj7g.js +4 -0
- package/dist/assets/MarketplacePage-CoigR7d_.js +1 -0
- package/dist/assets/{MetadataInspector-zJtxyFau.js → MetadataInspector-BGWYqUse.js} +1 -1
- package/dist/assets/{MetadataProvider-BagIop6q.js → MetadataProvider-_6IU7cWK.js} +1 -1
- package/dist/assets/PageView-CxOhEFic.js +1 -0
- package/dist/assets/{ProfilePage-0yyBZHjT.js → ProfilePage-C11r_2xN.js} +1 -1
- package/dist/assets/PublicFormsPage-N0Wofan4.js +1 -0
- package/dist/assets/RecordDetailView-Bh6I2k3c.js +1 -0
- package/dist/assets/{RecordFormPage-DqFdHPz8.js → RecordFormPage-1zrrumdr.js} +1 -1
- package/dist/assets/ReportDefaultInspector--SQsifZI.js +1 -0
- package/dist/assets/{ReportView-Cx-qFxJZ.js → ReportView-q3jNGyaI.js} +1 -1
- package/dist/assets/{RuntimeDraftBar-Be6SQ4g6.js → RuntimeDraftBar-DaYAgW5v.js} +1 -1
- package/dist/assets/{SearchResultsPage-DkQMPMlE.js → SearchResultsPage-BRnB7VD4.js} +1 -1
- package/dist/assets/{SettingsHub-el09ZPJP.js → SettingsHub-CUCcntU9.js} +1 -1
- package/dist/assets/{SettingsView-BiYeb1nb.js → SettingsView-DRjJrXF9.js} +1 -1
- package/dist/assets/{SystemHubPage-QSk3FL5a.js → SystemHubPage-_i5E_SOC.js} +1 -1
- package/dist/assets/{data-adapter-BtpuYbBh.js → data-adapter-CzKUUIgi.js} +1 -1
- package/dist/assets/{framework-ZJouI0cJ.js → framework-DLckRGJs.js} +3 -3
- package/dist/assets/{highlighted-body-OFNGDK62-DfdyR_41.js → highlighted-body-OFNGDK62-JYK0hMjr.js} +1 -1
- package/dist/assets/index-DGuFGryh.css +2 -0
- package/dist/assets/index-JrHkY-wh.js +4 -0
- package/dist/assets/marketplaceApi-CucX7DD9.js +1 -0
- package/dist/assets/{mergeServerFields-DPrTk8u4.js → mergeServerFields-CM4cY1zR.js} +4 -4
- package/dist/assets/mermaid-GHXKKRXX-Bg8PoWKD.js +1 -0
- package/dist/assets/metadata-admin-B5WWi7HS.js +19 -0
- package/dist/assets/{plugin-calendar-CwYuZf8c.js → plugin-calendar-DCCbdIpj.js} +1 -1
- package/dist/assets/{plugin-charts-DhlEvpuy.js → plugin-charts-Do3qrshN.js} +2 -2
- package/dist/assets/plugin-chatbot-DF5LNhQ2.js +120 -0
- package/dist/assets/plugin-dashboard-BQ3awX8y.js +5 -0
- package/dist/assets/plugin-form-FmgnWzcl.js +1 -0
- package/dist/assets/plugin-gantt-CWw13thv.js +23 -0
- package/dist/assets/plugin-grid-Cd-2qFJP.js +6 -0
- package/dist/assets/plugin-kanban-CYKs5Fuv.js +1 -0
- package/dist/assets/{plugin-map-Cz9tJHoZ.js → plugin-map-DuGG00x5.js} +1 -1
- package/dist/assets/{plugin-markdown-_H-xFg2t.js → plugin-markdown-Du1ajwhj.js} +3 -2
- package/dist/assets/plugin-report-D0COS83c.js +59 -0
- package/dist/assets/{plugin-timeline-DjngAdR-.js → plugin-timeline-BBYlrrgQ.js} +1 -1
- package/dist/assets/plugin-view-BhoDHK4P.js +1 -0
- package/dist/assets/plugins-views-gs7PYt1Y.js +4 -0
- package/dist/assets/{resolveActionParams-ergReBd1.js → resolveActionParams-DjRjW-gD.js} +3 -3
- package/dist/assets/{skeletons-BRDBm95C.js → skeletons-Cdt8ttDk.js} +1 -1
- package/dist/assets/{src-B5JRlZgC.js → src-BPf-hjw2.js} +1 -1
- package/dist/assets/{types-fX7qb4I3.js → types-DjNzBgbB.js} +1 -1
- package/dist/assets/ui-components-B2CBE2Rs.js +42 -0
- package/dist/assets/{ui-layout-CswtJjnW.js → ui-layout-D19iPz4K.js} +1 -1
- package/dist/assets/{useActionModal-d8GNl1HP.js → useActionModal-BKaoxO40.js} +1 -1
- package/dist/index.html +4 -4
- package/package.json +1 -1
- package/dist/assets/ApprovalsInboxPage-jrTqrLxX.js +0 -1
- package/dist/assets/ConsoleFloatingChatbot-B1xDv7X-.js +0 -1
- package/dist/assets/DashboardView-BNUhTJ8Y.js +0 -1
- package/dist/assets/FlowRunsPage-DdjGSDw1.js +0 -1
- package/dist/assets/MarketplaceInstalledPage-DJN3P4aw.js +0 -1
- package/dist/assets/MarketplacePackagePage-BUrsYfA7.js +0 -4
- package/dist/assets/MarketplacePage-q23E8dYU.js +0 -1
- package/dist/assets/PageView-M09zUJqv.js +0 -1
- package/dist/assets/PublicFormsPage-BPEDFiNo.js +0 -1
- package/dist/assets/RecordDetailView-cj45YVH-.js +0 -1
- package/dist/assets/ReportDefaultInspector-D5dIioUJ.js +0 -1
- package/dist/assets/index-B99f8h8i.js +0 -4
- package/dist/assets/index-BXu9hpEZ.css +0 -2
- package/dist/assets/marketplaceApi-DCvJ2C6u.js +0 -1
- package/dist/assets/mermaid-GHXKKRXX-BF-AoOMn.js +0 -1
- package/dist/assets/metadata-admin-DT8BohcC.js +0 -19
- package/dist/assets/plugin-chatbot-CJsfoGAD.js +0 -120
- package/dist/assets/plugin-dashboard-CGRjBe2V.js +0 -5
- package/dist/assets/plugin-form-C5yl9byI.js +0 -1
- package/dist/assets/plugin-gantt-C5hIQDHF.js +0 -23
- package/dist/assets/plugin-grid-2QHjCxCx.js +0 -6
- package/dist/assets/plugin-kanban-LtqKit9T.js +0 -1
- package/dist/assets/plugin-report-DA6bVPuW.js +0 -59
- package/dist/assets/plugin-view-BUsWmCh-.js +0 -1
- package/dist/assets/plugins-views-yfd0iHKg.js +0 -4
- package/dist/assets/runtime-config-BeHVOPm3.js +0 -1
- package/dist/assets/ui-components-Bs-DxYrW.js +0 -42
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ui-components-BL3SEdAz.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{o as e,r as t}from"./rolldown-runtime-CMxvf4Kt.js";import{_ as n,f as r,m as i,t as a,u as o}from"./vendor-react-DR370ovB.js";import{f as s}from"./infrastructure-CJNwTVno.js";import{T as c,r as l,w as u}from"./framework-ZJouI0cJ.js";import{H as d,R as f,Sr as p,Yi as m,hr as h,ja as g,js as _,z as v}from"./ui-components-Bs-DxYrW.js";import"./AdapterProvider-o2n9dY2j.js";import"./MetadataProvider-BagIop6q.js";import{r as y}from"./ExpressionProvider-Cuv0RaiR.js";import{C as b,r as x}from"./mergeServerFields-DPrTk8u4.js";import{n as S,r as C,t as w}from"./MetadataInspector-zJtxyFau.js";import{t as T}from"./ReportDefaultInspector-D5dIioUJ.js";import{r as E,t as D}from"./RuntimeDraftBar-Be6SQ4g6.js";var O=e(n(),1),k=a();function A({open:e,onClose:t,config:n,onSave:r,onFieldChange:i,name:a,metadataClient:o,onAfterChange:s}){let{t:c}=l(),u=(0,O.useMemo)(()=>x(),[]),[d,f]=(0,O.useState)(!1),m=(0,O.useMemo)(()=>({...n??{}}),[n]),[g,_]=(0,O.useState)(m),v=(0,O.useRef)(g),y=(0,O.useRef)(m);y.current!==m&&(y.current=m,v.current=m,_(m),f(!1));let b=(0,O.useCallback)(e=>{let t={...v.current,...e};if(v.current=t,_(t),f(!0),i)for(let[n,r]of Object.entries(e))i(n,r,t)},[i]),S=(0,O.useCallback)(()=>{r(v.current),f(!1),t()},[r,t]),C=(0,O.useCallback)(e=>{let t={...e};v.current=t,_(t),f(!1)},[]),w=(0,O.useCallback)(()=>{t()},[t]);return e?(0,k.jsxs)(`aside`,{className:`hidden sm:flex w-[440px] shrink-0 flex-col border-l bg-background h-full`,"data-testid":`report-config-panel`,role:`complementary`,"aria-label":c(`report.editor.title`,{defaultValue:`Edit report`}),children:[(0,k.jsxs)(`div`,{className:`flex items-center justify-between gap-2 border-b px-4 py-2.5 shrink-0`,children:[(0,k.jsx)(`div`,{className:`text-sm font-medium truncate`,children:c(`report.editor.title`,{defaultValue:`Edit report`})}),(0,k.jsx)(h,{variant:`ghost`,size:`sm`,onClick:t,className:`h-7 w-7 p-0`,"aria-label":c(`common.close`,{defaultValue:`Close`}),"data-testid":`report-config-close`,children:(0,k.jsx)(p,{className:`h-4 w-4`})})]}),(0,k.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:(0,k.jsx)(T,{type:`report`,name:typeof g.name==`string`?g.name:``,draft:g,readOnly:!1,locale:u,onPatch:b})}),(0,k.jsxs)(`div`,{"data-testid":`report-config-footer`,className:`flex items-center justify-end gap-2 border-t px-4 py-2.5 shrink-0`,children:[(0,k.jsx)(D,{type:`report`,name:a,metadataClient:o,dirty:d,onResume:C,onAfterChange:s}),(0,k.jsx)(h,{variant:`ghost`,size:`sm`,onClick:w,"data-testid":`report-config-discard`,children:c(`common.cancel`,{defaultValue:`Cancel`})}),(0,k.jsx)(h,{size:`sm`,onClick:S,"data-testid":`report-config-save`,children:c(`common.save`,{defaultValue:`Save`})})]})]}):null}var j=t({ReportView:()=>P}),M=(0,O.lazy)(()=>i(()=>import(`./plugin-report-DA6bVPuW.js`).then(e=>e.t).then(e=>({default:e.ReportViewer})),__vite__mapDeps([0]),import.meta.url)),N=(0,O.lazy)(()=>i(()=>import(`./plugin-report-DA6bVPuW.js`).then(e=>e.t).then(e=>({default:e.ReportRenderer})),__vite__mapDeps([0]),import.meta.url)),ee=[{value:`month`,label:`Month`,type:`text`},{value:`revenue`,label:`Revenue`,type:`number`},{value:`count`,label:`Count`,type:`number`},{value:`region`,label:`Region`,type:`text`},{value:`product`,label:`Product`,type:`text`},{value:`source`,label:`Lead Source`,type:`text`},{value:`stage`,label:`Stage`,type:`text`},{value:`amount`,label:`Amount`,type:`number`}];function P({dataSource:e}){let{t}=l(),{appName:n,reportName:i}=r(),a=o(),{showDebug:p}=S();u();let h=b(),{user:x}=s(),T=x?.role===`admin`,[D,j]=(0,O.useState)(!1),[P,F]=(0,O.useState)(0),{reports:I,objects:L,loading:R,refresh:z}=c(),{app:B}=y(),V=C(I,i,B?._packageId),[H,U]=(0,O.useState)(V),[W,G]=(0,O.useState)(null),[K,q]=(0,O.useState)([]),[J,Y]=(0,O.useState)(!1),X=(0,O.useCallback)(e=>{if(!e||!L?.length)return;let t=L.find(t=>t.name===e);if(!t?.fields)return;let n=t.fields;return Array.isArray(n)?n.map(e=>typeof e==`string`?{value:e,label:e,type:`text`}:{value:e.name,label:e.label||e.name,type:e.type||`text`}):Object.entries(n).map(([e,t])=>({value:e,label:t.label||e,type:t.type||`text`}))},[L]),te=(0,O.useCallback)(async({dataset:e,groupKey:t})=>{try{let r=await h.get(`dataset`,e),i=typeof r?.object==`string`?r.object:void 0;if(!i)return;let o=Array.isArray(r?.dimensions)?r.dimensions:[],s=new Map(o.filter(e=>e?.name).map(e=>[e.name,e])),c=L?.find(e=>e.name===i)?.fields,l=e=>{if(Array.isArray(c))return c.find(t=>t?.name===e);if(c&&typeof c==`object`)return c[e]},u=new URLSearchParams;for(let[e,n]of Object.entries(t)){if(n==null)continue;let t=s.get(e);if(t?.dateGranularity)continue;let r=t?.field||e,i=l(r);if(i?.type===`lookup`||i?.type===`master_detail`)continue;let a=n;if(Array.isArray(i?.options)){let e=i.options.find(e=>e?.label===n||e?.value===n);e&&e.value!=null&&(a=e.value)}u.set(`filter[${r}]`,String(a))}let d=u.toString();a(`${n?`/apps/${n}`:``}/${i}${d?`?${d}`:``}`)}catch(e){console.warn(`ReportView: drill navigation failed`,e)}},[h,a,n,L]),ne=(0,O.useMemo)(()=>{let e=W||H;return X(e?.objectName||e?.dataSource?.object||e?.dataSource?.resource)??ee},[W,H,X]),Z=(0,O.useCallback)(async e=>{try{h&&(await E(`report`,i,e,{metadataClient:h}),z().catch(()=>{}))}catch(e){console.warn(`[ReportView] Auto-save failed:`,e)}},[h,i,z]),re=(0,O.useCallback)(()=>{G(H),j(!0),F(e=>e+1)},[H]),ie=(0,O.useCallback)(()=>{j(!1)},[]),ae=(0,O.useMemo)(()=>W||H,[P]),oe=(0,O.useCallback)(e=>{G(e),Z(e),F(e=>e+1)},[Z]),se=(0,O.useCallback)((e,t)=>{G(n=>({...n,[e]:t}))},[]);(0,O.useEffect)(()=>{U(V)},[V]),(0,O.useEffect)(()=>{D||G(null)},[V]);let Q=W||H,ce=(0,O.useMemo)(()=>JSON.stringify(Q?.filters),[Q?.filters]),le=(0,O.useMemo)(()=>JSON.stringify(Q?.dataSource),[Q?.dataSource]),ue=(0,O.useMemo)(()=>JSON.stringify(Q?.data),[Q?.data]);if((0,O.useEffect)(()=>{if(!Q||!e){q([]);return}if(Q.data&&Array.isArray(Q.data)){q(Q.data);return}if(Q.dataSource){(async()=>{Y(!0);try{let t=Q.dataSource.object||Q.dataSource.resource;if(!t){console.warn(`ReportView: dataSource missing object/resource property`),q([]);return}q((await e.find(t,{$filter:Q.dataSource.filter,$orderby:Q.dataSource.sort,$top:Q.dataSource.limit})).data||[])}catch(e){console.error(`ReportView: Failed to load data from dataSource`,e),q([])}finally{Y(!1)}})();return}if(Q.objectName){(async()=>{Y(!0);try{q((await e.find(Q.objectName,{$filter:Q.filters,$orderby:Q.sort,$top:Q.limit||100})).data||[])}catch(e){console.error(`ReportView: Failed to load data from objectName`,e),q([])}finally{Y(!1)}})();return}q([])},[Q?.objectName,Q?.limit,ce,le,ue,e]),R)return(0,k.jsx)(`div`,{className:`h-full flex items-center justify-center p-8`,children:(0,k.jsx)(g,{className:`h-8 w-8 animate-spin text-muted-foreground`})});if(!V||!H)return!R&&!V?(0,k.jsx)(`div`,{className:`h-full flex items-center justify-center p-8`,children:(0,k.jsxs)(f,{children:[(0,k.jsx)(`div`,{className:`mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted`,children:(0,k.jsx)(_,{className:`h-6 w-6 text-muted-foreground`})}),(0,k.jsx)(d,{children:t(`empty.reportNotFound`)}),(0,k.jsx)(v,{children:t(`empty.reportNotFoundDescription`,{name:i})})]})}):(0,k.jsx)(`div`,{className:`h-full flex items-center justify-center p-8`,children:(0,k.jsx)(g,{className:`h-8 w-8 animate-spin text-muted-foreground`})});let de=e=>{let t={...e};!t.title&&t.label&&(t.title=t.label);let n=t.objectName||t.dataSource?.object||t.dataSource?.resource,r=n?L?.find(e=>e.name===n):null,i=Array.isArray(r?.fields)?r.fields:r?.fields?Object.entries(r.fields).map(([e,t])=>({name:e,...t})):[],a={};for(let e of i)e&&e.name&&(a[e.name]=e);let o=e=>{let t=e.name||e.field,n=t?a[t]:void 0;if(!n)return e;let r={...e};if(r.type===void 0&&n.type!==void 0&&(r.type=n.type),r.options===void 0&&Array.isArray(n.options)&&(r.options=n.options),r.referenceTo===void 0){let e=n.referenceTo||n.reference?.to||n.target;e&&(r.referenceTo=e)}return r.label===void 0&&n.label&&(r.label=n.label),r};if(!t.fields&&Array.isArray(t.columns)?t.fields=t.columns.map(e=>{let t=o(e);return{name:t.field||t.name,label:t.label,type:t.type,options:t.options,referenceTo:t.referenceTo,format:t.format,renderAs:t.renderAs,colorMap:t.colorMap,...t.aggregate?{aggregation:t.aggregate,showInSummary:!0}:{}}}):Array.isArray(t.fields)&&(t.fields=t.fields.map(o)),t.fields&&Array.isArray(t.fields)&&t.fields.length>0){let n=t.fields.some(e=>e.showInSummary||e.aggregation),r=t.type||t.reportType||`tabular`,i=[];(r===`summary`||n)&&i.push({type:`summary`,title:`Key Metrics`}),i.push({type:`table`,title:`Details`,columns:t.fields.map(e=>({name:e.name,label:e.label,type:e.type,options:e.options,referenceTo:e.referenceTo,format:e.format,renderAs:e.renderAs,colorMap:e.colorMap}))});let a=t.chart||t.chartConfig,o=a?.type||a?.chartType;if(o){let e=a.xAxis||a.xAxisField,t=a.yAxis||a.yAxisFields?.[0];i.push({type:`chart`,title:`Chart`,chart:{type:`chart`,chartType:o,xAxisField:e,yAxisFields:t?[t]:a.yAxisFields}})}if(Array.isArray(e.sections)){let t=e.sections.filter(e=>e.type===`chart`&&!o);i.push(...t)}t.sections=i}else t.sections||=[];return t},$=W||H,fe=!!($&&(typeof $.dataset==`string`||$.type===`joined`&&Array.isArray($.blocks)&&$.blocks.some(e=>typeof e?.dataset==`string`)))||!!($&&$.objectName&&($.type===`matrix`||$.type===`joined`||$.type===`summary`||$.type===`tabular`||$.type===void 0||Array.isArray($.groupingsAcross)&&$.groupingsAcross.length>0||Array.isArray($.columns))),pe={type:`report-viewer`,report:de($),data:K,showToolbar:!0,allowExport:!0,loading:J};return(0,k.jsxs)(`div`,{className:`flex flex-col h-full overflow-hidden bg-background`,children:[(0,k.jsxs)(`div`,{className:`flex flex-col sm:flex-row justify-between sm:items-center gap-3 sm:gap-4 p-4 sm:p-6 border-b shrink-0`,children:[(0,k.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,k.jsx)(`h1`,{className:`text-lg sm:text-xl md:text-2xl font-bold tracking-tight truncate`,children:$.title||$.label||`Report Viewer`}),$.description&&(0,k.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1 line-clamp-2`,children:$.description})]}),(0,k.jsx)(`div`,{className:`shrink-0 flex items-center gap-1.5`,children:T&&(0,k.jsxs)(`button`,{type:`button`,onClick:re,className:`inline-flex items-center gap-1.5 rounded-md border border-input bg-background px-2.5 py-1.5 text-xs font-medium text-muted-foreground shadow-sm hover:bg-accent hover:text-accent-foreground`,"data-testid":`report-edit-button`,children:[(0,k.jsx)(m,{className:`h-3.5 w-3.5`}),t(`common.edit`)]})})]}),(0,k.jsxs)(`div`,{className:`flex-1 overflow-hidden flex flex-col sm:flex-row relative`,children:[(0,k.jsx)(`div`,{className:`flex-1 min-w-0 overflow-auto p-4 sm:p-6 lg:p-8 bg-muted/5`,children:(0,k.jsx)(`div`,{className:`w-full shadow-sm border rounded-lg sm:rounded-xl bg-background overflow-hidden min-h-150`,children:(0,k.jsx)(O.Suspense,{fallback:(0,k.jsx)(`div`,{className:`p-8 text-sm text-muted-foreground`,children:t(`common.loading`,{defaultValue:`Loading…`})}),children:fe?(0,k.jsx)(`div`,{className:`p-4 sm:p-6`,children:(0,k.jsx)(N,{schema:$,dataSource:e,rows:K,onDrill:te})}):(0,k.jsx)(M,{schema:pe})})})}),(0,k.jsx)(A,{open:D&&T,onClose:ie,config:ae,onSave:oe,onFieldChange:se,availableFields:ne,getFieldsForObject:X,name:i,metadataClient:h,onAfterChange:()=>z().catch(()=>{})}),(0,k.jsx)(w,{open:p,sections:[{title:`Report Configuration`,data:$}]})]})]})}export{j as t};
|
|
2
|
+
import{o as e,r as t}from"./rolldown-runtime-CMxvf4Kt.js";import{_ as n,f as r,m as i,t as a,u as o}from"./vendor-react-DR370ovB.js";import{f as s}from"./infrastructure-CJNwTVno.js";import{T as c,r as l,w as u}from"./framework-DLckRGJs.js";import{H as d,Ma as f,Ns as p,R as m,Sr as h,Xi as g,hr as _,z as v}from"./ui-components-B2CBE2Rs.js";import"./AdapterProvider-CGofnJBf.js";import"./MetadataProvider-_6IU7cWK.js";import{r as y}from"./ExpressionProvider-wi1dJ2tN.js";import{C as b,r as x}from"./mergeServerFields-CM4cY1zR.js";import{n as S,r as C,t as w}from"./MetadataInspector-BGWYqUse.js";import{t as T}from"./ReportDefaultInspector--SQsifZI.js";import{r as E,t as D}from"./RuntimeDraftBar-DaYAgW5v.js";var O=e(n(),1),k=a();function A({open:e,onClose:t,config:n,onSave:r,onFieldChange:i,name:a,metadataClient:o,onAfterChange:s}){let{t:c}=l(),u=(0,O.useMemo)(()=>x(),[]),[d,f]=(0,O.useState)(!1),p=(0,O.useMemo)(()=>({...n??{}}),[n]),[m,g]=(0,O.useState)(p),v=(0,O.useRef)(m),y=(0,O.useRef)(p);y.current!==p&&(y.current=p,v.current=p,g(p),f(!1));let b=(0,O.useCallback)(e=>{let t={...v.current,...e};if(v.current=t,g(t),f(!0),i)for(let[n,r]of Object.entries(e))i(n,r,t)},[i]),S=(0,O.useCallback)(()=>{r(v.current),f(!1),t()},[r,t]),C=(0,O.useCallback)(e=>{let t={...e};v.current=t,g(t),f(!1)},[]),w=(0,O.useCallback)(()=>{t()},[t]);return e?(0,k.jsxs)(`aside`,{className:`hidden sm:flex w-[440px] shrink-0 flex-col border-l bg-background h-full`,"data-testid":`report-config-panel`,role:`complementary`,"aria-label":c(`report.editor.title`,{defaultValue:`Edit report`}),children:[(0,k.jsxs)(`div`,{className:`flex items-center justify-between gap-2 border-b px-4 py-2.5 shrink-0`,children:[(0,k.jsx)(`div`,{className:`text-sm font-medium truncate`,children:c(`report.editor.title`,{defaultValue:`Edit report`})}),(0,k.jsx)(_,{variant:`ghost`,size:`sm`,onClick:t,className:`h-7 w-7 p-0`,"aria-label":c(`common.close`,{defaultValue:`Close`}),"data-testid":`report-config-close`,children:(0,k.jsx)(h,{className:`h-4 w-4`})})]}),(0,k.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto`,children:(0,k.jsx)(T,{type:`report`,name:typeof m.name==`string`?m.name:``,draft:m,readOnly:!1,locale:u,onPatch:b})}),(0,k.jsxs)(`div`,{"data-testid":`report-config-footer`,className:`flex items-center justify-end gap-2 border-t px-4 py-2.5 shrink-0`,children:[(0,k.jsx)(D,{type:`report`,name:a,metadataClient:o,dirty:d,onResume:C,onAfterChange:s}),(0,k.jsx)(_,{variant:`ghost`,size:`sm`,onClick:w,"data-testid":`report-config-discard`,children:c(`common.cancel`,{defaultValue:`Cancel`})}),(0,k.jsx)(_,{size:`sm`,onClick:S,"data-testid":`report-config-save`,children:c(`common.save`,{defaultValue:`Save`})})]})]}):null}var j=t({ReportView:()=>P}),M=(0,O.lazy)(()=>i(()=>import(`./plugin-report-D0COS83c.js`).then(e=>e.t).then(e=>({default:e.ReportViewer})),__vite__mapDeps([0]),import.meta.url)),N=(0,O.lazy)(()=>i(()=>import(`./plugin-report-D0COS83c.js`).then(e=>e.t).then(e=>({default:e.ReportRenderer})),__vite__mapDeps([0]),import.meta.url)),ee=[{value:`month`,label:`Month`,type:`text`},{value:`revenue`,label:`Revenue`,type:`number`},{value:`count`,label:`Count`,type:`number`},{value:`region`,label:`Region`,type:`text`},{value:`product`,label:`Product`,type:`text`},{value:`source`,label:`Lead Source`,type:`text`},{value:`stage`,label:`Stage`,type:`text`},{value:`amount`,label:`Amount`,type:`number`}];function P({dataSource:e}){let{t}=l(),{appName:n,reportName:i}=r(),a=o(),{showDebug:h}=S();u();let _=b(),{user:x}=s(),T=x?.role===`admin`,[D,j]=(0,O.useState)(!1),[P,F]=(0,O.useState)(0),{reports:I,objects:L,loading:R,refresh:z}=c(),{app:B}=y(),V=C(I,i,B?._packageId),[H,U]=(0,O.useState)(V),[W,G]=(0,O.useState)(null),[K,q]=(0,O.useState)([]),[J,Y]=(0,O.useState)(!1),X=(0,O.useCallback)(e=>{if(!e||!L?.length)return;let t=L.find(t=>t.name===e);if(!t?.fields)return;let n=t.fields;return Array.isArray(n)?n.map(e=>typeof e==`string`?{value:e,label:e,type:`text`}:{value:e.name,label:e.label||e.name,type:e.type||`text`}):Object.entries(n).map(([e,t])=>({value:e,label:t.label||e,type:t.type||`text`}))},[L]),te=(0,O.useCallback)(async({dataset:e,groupKey:t})=>{try{let r=await _.get(`dataset`,e),i=typeof r?.object==`string`?r.object:void 0;if(!i)return;let o=Array.isArray(r?.dimensions)?r.dimensions:[],s=new Map(o.filter(e=>e?.name).map(e=>[e.name,e])),c=L?.find(e=>e.name===i)?.fields,l=e=>{if(Array.isArray(c))return c.find(t=>t?.name===e);if(c&&typeof c==`object`)return c[e]},u=new URLSearchParams;for(let[e,n]of Object.entries(t)){if(n==null)continue;let t=s.get(e);if(t?.dateGranularity)continue;let r=t?.field||e,i=l(r);if(i?.type===`lookup`||i?.type===`master_detail`)continue;let a=n;if(Array.isArray(i?.options)){let e=i.options.find(e=>e?.label===n||e?.value===n);e&&e.value!=null&&(a=e.value)}u.set(`filter[${r}]`,String(a))}let d=u.toString();a(`${n?`/apps/${n}`:``}/${i}${d?`?${d}`:``}`)}catch(e){console.warn(`ReportView: drill navigation failed`,e)}},[_,a,n,L]),ne=(0,O.useMemo)(()=>{let e=W||H;return X(e?.objectName||e?.dataSource?.object||e?.dataSource?.resource)??ee},[W,H,X]),Z=(0,O.useCallback)(async e=>{try{_&&(await E(`report`,i,e,{metadataClient:_}),z().catch(()=>{}))}catch(e){console.warn(`[ReportView] Auto-save failed:`,e)}},[_,i,z]),re=(0,O.useCallback)(()=>{G(H),j(!0),F(e=>e+1)},[H]),ie=(0,O.useCallback)(()=>{j(!1)},[]),ae=(0,O.useMemo)(()=>W||H,[P]),oe=(0,O.useCallback)(e=>{G(e),Z(e),F(e=>e+1)},[Z]),se=(0,O.useCallback)((e,t)=>{G(n=>({...n,[e]:t}))},[]);(0,O.useEffect)(()=>{U(V)},[V]),(0,O.useEffect)(()=>{D||G(null)},[V]);let Q=W||H,ce=(0,O.useMemo)(()=>JSON.stringify(Q?.filters),[Q?.filters]),le=(0,O.useMemo)(()=>JSON.stringify(Q?.dataSource),[Q?.dataSource]),ue=(0,O.useMemo)(()=>JSON.stringify(Q?.data),[Q?.data]);if((0,O.useEffect)(()=>{if(!Q||!e){q([]);return}if(Q.data&&Array.isArray(Q.data)){q(Q.data);return}if(Q.dataSource){(async()=>{Y(!0);try{let t=Q.dataSource.object||Q.dataSource.resource;if(!t){console.warn(`ReportView: dataSource missing object/resource property`),q([]);return}q((await e.find(t,{$filter:Q.dataSource.filter,$orderby:Q.dataSource.sort,$top:Q.dataSource.limit})).data||[])}catch(e){console.error(`ReportView: Failed to load data from dataSource`,e),q([])}finally{Y(!1)}})();return}if(Q.objectName){(async()=>{Y(!0);try{q((await e.find(Q.objectName,{$filter:Q.filters,$orderby:Q.sort,$top:Q.limit||100})).data||[])}catch(e){console.error(`ReportView: Failed to load data from objectName`,e),q([])}finally{Y(!1)}})();return}q([])},[Q?.objectName,Q?.limit,ce,le,ue,e]),R)return(0,k.jsx)(`div`,{className:`h-full flex items-center justify-center p-8`,children:(0,k.jsx)(f,{className:`h-8 w-8 animate-spin text-muted-foreground`})});if(!V||!H)return!R&&!V?(0,k.jsx)(`div`,{className:`h-full flex items-center justify-center p-8`,children:(0,k.jsxs)(m,{children:[(0,k.jsx)(`div`,{className:`mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted`,children:(0,k.jsx)(p,{className:`h-6 w-6 text-muted-foreground`})}),(0,k.jsx)(d,{children:t(`empty.reportNotFound`)}),(0,k.jsx)(v,{children:t(`empty.reportNotFoundDescription`,{name:i})})]})}):(0,k.jsx)(`div`,{className:`h-full flex items-center justify-center p-8`,children:(0,k.jsx)(f,{className:`h-8 w-8 animate-spin text-muted-foreground`})});let de=e=>{let t={...e};!t.title&&t.label&&(t.title=t.label);let n=t.objectName||t.dataSource?.object||t.dataSource?.resource,r=n?L?.find(e=>e.name===n):null,i=Array.isArray(r?.fields)?r.fields:r?.fields?Object.entries(r.fields).map(([e,t])=>({name:e,...t})):[],a={};for(let e of i)e&&e.name&&(a[e.name]=e);let o=e=>{let t=e.name||e.field,n=t?a[t]:void 0;if(!n)return e;let r={...e};if(r.type===void 0&&n.type!==void 0&&(r.type=n.type),r.options===void 0&&Array.isArray(n.options)&&(r.options=n.options),r.referenceTo===void 0){let e=n.referenceTo||n.reference?.to||n.target;e&&(r.referenceTo=e)}return r.label===void 0&&n.label&&(r.label=n.label),r};if(!t.fields&&Array.isArray(t.columns)?t.fields=t.columns.map(e=>{let t=o(e);return{name:t.field||t.name,label:t.label,type:t.type,options:t.options,referenceTo:t.referenceTo,format:t.format,renderAs:t.renderAs,colorMap:t.colorMap,...t.aggregate?{aggregation:t.aggregate,showInSummary:!0}:{}}}):Array.isArray(t.fields)&&(t.fields=t.fields.map(o)),t.fields&&Array.isArray(t.fields)&&t.fields.length>0){let n=t.fields.some(e=>e.showInSummary||e.aggregation),r=t.type||t.reportType||`tabular`,i=[];(r===`summary`||n)&&i.push({type:`summary`,title:`Key Metrics`}),i.push({type:`table`,title:`Details`,columns:t.fields.map(e=>({name:e.name,label:e.label,type:e.type,options:e.options,referenceTo:e.referenceTo,format:e.format,renderAs:e.renderAs,colorMap:e.colorMap}))});let a=t.chart||t.chartConfig,o=a?.type||a?.chartType;if(o){let e=a.xAxis||a.xAxisField,t=a.yAxis||a.yAxisFields?.[0];i.push({type:`chart`,title:`Chart`,chart:{type:`chart`,chartType:o,xAxisField:e,yAxisFields:t?[t]:a.yAxisFields}})}if(Array.isArray(e.sections)){let t=e.sections.filter(e=>e.type===`chart`&&!o);i.push(...t)}t.sections=i}else t.sections||=[];return t},$=W||H,fe=!!($&&(typeof $.dataset==`string`||$.type===`joined`&&Array.isArray($.blocks)&&$.blocks.some(e=>typeof e?.dataset==`string`)))||!!($&&$.objectName&&($.type===`matrix`||$.type===`joined`||$.type===`summary`||$.type===`tabular`||$.type===void 0||Array.isArray($.groupingsAcross)&&$.groupingsAcross.length>0||Array.isArray($.columns))),pe={type:`report-viewer`,report:de($),data:K,showToolbar:!0,allowExport:!0,loading:J};return(0,k.jsxs)(`div`,{className:`flex flex-col h-full overflow-hidden bg-background`,children:[(0,k.jsxs)(`div`,{className:`flex flex-col sm:flex-row justify-between sm:items-center gap-3 sm:gap-4 p-4 sm:p-6 border-b shrink-0`,children:[(0,k.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,k.jsx)(`h1`,{className:`text-lg sm:text-xl md:text-2xl font-bold tracking-tight truncate`,children:$.title||$.label||`Report Viewer`}),$.description&&(0,k.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1 line-clamp-2`,children:$.description})]}),(0,k.jsx)(`div`,{className:`shrink-0 flex items-center gap-1.5`,children:T&&(0,k.jsxs)(`button`,{type:`button`,onClick:re,className:`inline-flex items-center gap-1.5 rounded-md border border-input bg-background px-2.5 py-1.5 text-xs font-medium text-muted-foreground shadow-sm hover:bg-accent hover:text-accent-foreground`,"data-testid":`report-edit-button`,children:[(0,k.jsx)(g,{className:`h-3.5 w-3.5`}),t(`common.edit`)]})})]}),(0,k.jsxs)(`div`,{className:`flex-1 overflow-hidden flex flex-col sm:flex-row relative`,children:[(0,k.jsx)(`div`,{className:`flex-1 min-w-0 overflow-auto p-4 sm:p-6 lg:p-8 bg-muted/5`,children:(0,k.jsx)(`div`,{className:`w-full shadow-sm border rounded-lg sm:rounded-xl bg-background overflow-hidden min-h-150`,children:(0,k.jsx)(O.Suspense,{fallback:(0,k.jsx)(`div`,{className:`p-8 text-sm text-muted-foreground`,children:t(`common.loading`,{defaultValue:`Loading…`})}),children:fe?(0,k.jsx)(`div`,{className:`p-4 sm:p-6`,children:(0,k.jsx)(N,{schema:$,dataSource:e,rows:K,onDrill:te})}):(0,k.jsx)(M,{schema:pe})})})}),(0,k.jsx)(A,{open:D&&T,onClose:ie,config:ae,onSave:oe,onFieldChange:se,availableFields:ne,getFieldsForObject:X,name:i,metadataClient:_,onAfterChange:()=>z().catch(()=>{})}),(0,k.jsx)(w,{open:h,sections:[{title:`Report Configuration`,data:$}]})]})]})}export{j as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as e}from"./rolldown-runtime-CMxvf4Kt.js";import{_ as t,t as n}from"./vendor-react-DR370ovB.js";import{Ir as r,
|
|
1
|
+
import{o as e}from"./rolldown-runtime-CMxvf4Kt.js";import{_ as t,t as n}from"./vendor-react-DR370ovB.js";import{Ir as r,Ma as i,hr as a,xi as o}from"./ui-components-B2CBE2Rs.js";import{a as s,i as c,r as l}from"./mergeServerFields-CM4cY1zR.js";var u=e(t(),1);function d(e){if(!e||typeof e!=`object`)return null;let t=e;if(`item`in t){let e=t.item;return!e||typeof e!=`object`?null:Object.keys(e).length>0?e:null}return Object.keys(t).length>0?t:null}async function f(e,t,n,r){await r.metadataClient.save(e,t,n,{mode:`draft`})}async function p(e,t,n,r){return await r.metadataClient.save(e,t,n,{mode:`draft`}),t}async function m(e,t,n){return d(await n.metadataClient.get(e,t,{state:`draft`}))}async function h(e,t,n){await n.metadataClient.reset(e,t,{state:`draft`})}async function g(e,t,n){await n.metadataClient.publish(e,t)}var _=n();function v({type:e,name:t,metadataClient:n,dirty:d,onResume:f,onAfterChange:p,savedSignal:v}){let y=l(),[b,x]=(0,u.useState)(!1),[S,C]=(0,u.useState)(!1),w=(0,u.useRef)(null),T=(0,u.useCallback)(async()=>{if(!t||!n){x(!1);return}let r;try{r=await m(e,t,{metadataClient:n})}catch{x(!1);return}if(x(!!r),r&&f&&w.current!==t){w.current=t;try{f(r)}catch(e){console.error(`[RuntimeDraftBar] Resume draft failed:`,e)}}},[e,t,n,f]);(0,u.useEffect)(()=>{T()},[T]);let E=(0,u.useRef)(v);(0,u.useEffect)(()=>{v!==E.current&&(E.current=v,v&&x(!0))},[v]);let D=(0,u.useCallback)(async()=>{if(t){C(!0);try{await g(e,t,{metadataClient:n}),x(!1),p?.()}catch(e){console.error(`[RuntimeDraftBar] Publish failed:`,e)}finally{C(!1)}}},[e,t,n,p]),O=(0,u.useCallback)(async()=>{if(t&&!(typeof confirm==`function`&&!confirm(s(`engine.edit.discardDraftConfirm`,y,{type:e,name:t})))){C(!0);try{await h(e,t,{metadataClient:n}),x(!1),p?.()}catch(e){console.error(`[RuntimeDraftBar] Discard draft failed:`,e)}finally{C(!1)}}},[e,t,n,p,y]);return b?(0,_.jsxs)(`div`,{className:`mr-auto flex items-center gap-2`,"data-testid":`runtime-draft-bar`,children:[(0,_.jsxs)(`span`,{className:`text-xs text-amber-700 dark:text-amber-400`,title:c(`engine.edit.draftPending`,y),"data-testid":`runtime-draft-indicator`,children:[`● `,c(`engine.edit.draftPending`,y)]}),(0,_.jsx)(a,{variant:`ghost`,size:`sm`,onClick:O,disabled:S,className:`h-7 w-7 p-0 text-muted-foreground`,title:c(`engine.edit.discardDraft`,y),"aria-label":c(`engine.edit.discardDraft`,y),"data-testid":`runtime-draft-discard`,children:(0,_.jsx)(r,{className:`h-3.5 w-3.5`})}),(0,_.jsx)(a,{size:`sm`,onClick:D,disabled:S||d,className:`h-7 px-2 bg-emerald-600 hover:bg-emerald-700 text-emerald-50`,title:c(d?`engine.edit.publishBlockedDirty`:`engine.edit.publish`,y),"data-testid":`runtime-draft-publish`,children:S?(0,_.jsx)(i,{className:`h-3.5 w-3.5 animate-spin`}):(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(o,{className:`h-3.5 w-3.5 mr-1`}),c(`engine.edit.publish`,y)]})})]}):null}export{p as n,f as r,v as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as e,r as t}from"./rolldown-runtime-CMxvf4Kt.js";import{_ as n,f as r,p as i,r as a,t as o}from"./vendor-react-DR370ovB.js";import{f as s}from"./infrastructure-CJNwTVno.js";import{T as c,r as l}from"./framework-
|
|
1
|
+
import{o as e,r as t}from"./rolldown-runtime-CMxvf4Kt.js";import{_ as n,f as r,p as i,r as a,t as o}from"./vendor-react-DR370ovB.js";import{f as s}from"./infrastructure-CJNwTVno.js";import{T as c,r as l}from"./framework-DLckRGJs.js";import{$n as u,Co as d,Ha as f,Jn as p,Ns as m,Si as h,Wo as g,ac as _,nn as v,qn as y}from"./ui-components-B2CBE2Rs.js";import"./MetadataProvider-_6IU7cWK.js";import{n as b}from"./ui-layout-D19iPz4K.js";import{n as x}from"./appRoute-D5vwtoc_.js";var S=t({SearchResultsPage:()=>O}),C=e(n(),1),w=o();function T(e){let t=[];for(let n of e)n.type===`group`&&n.children?t.push(...T(n.children)):t.push(n);return t}var E={object:g,dashboard:f,page:d,report:m},D={object:`bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200`,dashboard:`bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200`,page:`bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200`,report:`bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200`};function O(){let{t:e}=l(),{appName:t}=r(),[n,o]=i(),[d,f]=(0,C.useState)(n.get(`q`)||``),{apps:m}=c(),S=m||[],O=x(S,t)||S[0],k=`/apps/${t}`,{user:A}=s(),j=(0,C.useMemo)(()=>{if(!O)return[];let e=T(O.navigation||[]),t={currentUserId:A?.id??null};return e.map(e=>{let{href:n}=b(e,k,t);return{id:e.id,label:e.label||e.objectName||e.dashboardName||e.pageName||e.reportName||``,href:n,type:e.type,description:e.description}}).filter(e=>e.href!==`#`)},[O,k,A?.id]),M=(0,C.useMemo)(()=>{if(!d.trim())return j;let e=d.toLowerCase();return j.filter(t=>t.label.toLowerCase().includes(e)||t.type.toLowerCase().includes(e)||t.description&&t.description.toLowerCase().includes(e))},[j,d]),N=e=>{f(e),o(e?{q:e}:{})},P=(0,C.useMemo)(()=>{let e={};for(let t of M)(e[t.type]||=[]).push(t);return e},[M]);return(0,w.jsxs)(`div`,{className:`flex flex-col gap-6 p-4 sm:p-6 max-w-4xl mx-auto`,children:[(0,w.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,w.jsxs)(a,{to:k,className:`flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors`,children:[(0,w.jsx)(_,{className:`h-4 w-4`}),e(`search.back`)]}),(0,w.jsx)(`h1`,{className:`text-xl font-semibold`,children:e(`search.title`)})]}),(0,w.jsxs)(`div`,{className:`relative`,children:[(0,w.jsx)(`label`,{htmlFor:`search-results-input`,className:`sr-only`,children:e(`search.placeholder`)}),(0,w.jsx)(h,{className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground`,"aria-hidden":`true`}),(0,w.jsx)(v,{id:`search-results-input`,value:d,onChange:e=>N(e.target.value),placeholder:e(`search.placeholder`),className:`pl-10 h-11 text-base`,autoFocus:!0})]}),(0,w.jsx)(`div`,{className:`text-sm text-muted-foreground`,children:d.trim()?e(M.length===1?`search.resultsCount`:`search.resultsCountPlural`,{count:M.length,query:d}):e(`search.itemsAvailable`,{count:j.length})}),M.length===0?(0,w.jsxs)(`div`,{className:`flex flex-col items-center justify-center py-12 text-center`,children:[(0,w.jsx)(h,{className:`h-12 w-12 text-muted-foreground/30 mb-4`}),(0,w.jsx)(`p`,{className:`text-lg font-medium text-muted-foreground`,children:e(`search.noResults`)}),(0,w.jsx)(`p`,{className:`text-sm text-muted-foreground/80 mt-1`,children:e(`search.noResultsHint`)})]}):(0,w.jsx)(`div`,{className:`space-y-6`,children:Object.entries(P).map(([t,n])=>{let r=E[t]||g,i=`search.type${t.charAt(0).toUpperCase()}${t.slice(1)}s`;return`${t.charAt(0).toUpperCase()}${t.slice(1)}`,(0,w.jsxs)(`div`,{children:[(0,w.jsxs)(`h2`,{className:`text-sm font-medium text-muted-foreground mb-2 flex items-center gap-1.5`,children:[(0,w.jsx)(r,{className:`h-4 w-4`}),e(i),(0,w.jsx)(u,{variant:`secondary`,className:`ml-1 text-xs`,children:n.length})]}),(0,w.jsx)(`div`,{className:`grid gap-2`,children:n.map(t=>{let n=E[t.type]||g,r=`search.badge${t.type.charAt(0).toUpperCase()}${t.type.slice(1)}`;return(0,w.jsx)(a,{to:t.href,className:`rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2`,children:(0,w.jsx)(y,{className:`hover:bg-accent/50 transition-colors cursor-pointer`,children:(0,w.jsxs)(p,{className:`flex items-center gap-3 p-3`,children:[(0,w.jsx)(`div`,{className:`flex h-8 w-8 items-center justify-center rounded ${D[t.type]||``}`,children:(0,w.jsx)(n,{className:`h-4 w-4`})}),(0,w.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,w.jsx)(`p`,{className:`text-sm font-medium truncate`,children:t.label}),t.description&&(0,w.jsx)(`p`,{className:`text-xs text-muted-foreground truncate`,children:t.description})]}),(0,w.jsx)(u,{variant:`outline`,className:`text-xs shrink-0`,children:e(r)})]})})},t.id)})})]},t)})})]})}export{S as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as e}from"./rolldown-runtime-CMxvf4Kt.js";import{_ as t,t as n,u as r}from"./vendor-react-DR370ovB.js";import{$n as i,Jn as a,Mt as o,Xn as s,Yn as c,Zn as l,bi as u,qn as d}from"./ui-components-
|
|
1
|
+
import{o as e}from"./rolldown-runtime-CMxvf4Kt.js";import{_ as t,t as n,u as r}from"./vendor-react-DR370ovB.js";import{$n as i,Jn as a,Mt as o,Xn as s,Yn as c,Zn as l,bi as u,qn as d}from"./ui-components-B2CBE2Rs.js";import{o as f,r as p,t as m}from"./types-DjNzBgbB.js";var h=e(t(),1),g=n();function _(){let e=r(),[t,n]=(0,h.useState)(null),[_,v]=(0,h.useState)(null);(0,h.useEffect)(()=>{p().then(e=>n(e.manifests??[])).catch(e=>v(e?.message??`Failed to load settings`))},[]);let y=(0,h.useMemo)(()=>{if(!t)return null;let e=new Map;for(let n of[...t].sort((e,t)=>(e.order??999)-(t.order??999))){let t=n.category??`Other`,r=e.get(t)??[];r.push(n),e.set(t,r)}return e},[t]);return(0,g.jsxs)(`div`,{className:`p-6 max-w-6xl mx-auto`,children:[(0,g.jsxs)(`div`,{className:`flex items-center gap-3 mb-6`,children:[(0,g.jsx)(u,{className:`h-7 w-7 text-muted-foreground`}),(0,g.jsxs)(`div`,{children:[(0,g.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:`Settings`}),(0,g.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`Configure your workspace, integrations, and feature flags.`})]})]}),_?(0,g.jsx)(d,{children:(0,g.jsx)(a,{className:`py-8 text-center text-sm text-destructive`,children:_})}):null,t?t.length===0?(0,g.jsx)(d,{children:(0,g.jsx)(a,{className:`py-12 text-center text-sm text-muted-foreground`,children:`No settings registered. Plugins can register settings manifests via the SettingsService.`})}):Array.from(y??[]).map(([t,n])=>(0,g.jsxs)(`section`,{className:`mb-8`,children:[(0,g.jsx)(`h2`,{className:`text-sm font-semibold tracking-wide uppercase text-muted-foreground mb-3`,children:t}),(0,g.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4`,children:n.map(t=>(0,g.jsxs)(d,{className:`cursor-pointer hover:border-primary/50 hover:shadow-sm transition-all`,onClick:()=>e(`/system/settings/${t.namespace}`),children:[(0,g.jsxs)(s,{className:`pb-3`,children:[(0,g.jsxs)(`div`,{className:`flex items-start justify-between`,children:[(0,g.jsx)(t.icon?f(t.icon):u,{className:`h-6 w-6 text-muted-foreground`}),t.beta?(0,g.jsx)(i,{variant:`secondary`,className:`text-[10px]`,children:`Beta`}):null]}),(0,g.jsx)(l,{className:`text-base mt-2`,children:m(t.label)}),t.description?(0,g.jsx)(c,{className:`text-xs`,children:t.description}):null]}),(0,g.jsx)(a,{className:`pt-0`,children:(0,g.jsxs)(`div`,{className:`text-[11px] text-muted-foreground`,children:[t.specifiers.length,` setting`,t.specifiers.length===1?``:`s`]})})]},t.namespace))})]},t)):(0,g.jsxs)(`div`,{className:`space-y-4`,children:[(0,g.jsx)(o,{className:`h-6 w-32`}),(0,g.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4`,children:Array.from({length:3}).map((e,t)=>(0,g.jsx)(o,{className:`h-32 w-full`},t))})]})]})}export{_ as SettingsHub};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as e}from"./rolldown-runtime-CMxvf4Kt.js";import{_ as t,f as n,t as r,u as i}from"./vendor-react-DR370ovB.js";import{r as a}from"./framework-ZJouI0cJ.js";import{$n as o,Aa as s,Bt as c,Ht as l,Jn as u,Kn as d,Mt as f,Ut as p,Vt as m,Wt as h,Xt as g,Zt as _,ar as v,ft as y,hr as b,ir as x,ja as S,ki as C,nn as w,on as T,pt as E,qa as D,qn as O,rc as k,rr as A,tt as j,xs as M,zt as N}from"./ui-components-Bs-DxYrW.js";import{r as P}from"./vendor-ui-utils-rQOI1gAo.js";import{a as F,i as I,n as L,o as R,t as z}from"./types-fX7qb4I3.js";var B=e(t(),1),V=r();function H({reason:e,className:t}){return(0,V.jsxs)(o,{variant:`outline`,className:`gap-1 border-amber-300 bg-amber-50 text-amber-900 ${t??``}`,title:e??`Pinned by environment variable — cannot be edited from the UI.`,children:[(0,V.jsx)(s,{className:`h-3 w-3`}),`Locked by env`]})}function U({resolved:e,labels:t}){let n=e.cascadeChain;if(!n||n.length===0)return null;let r=n.find(e=>e.effective)??n[n.length-1],i=n.find(e=>e!==r&&e.value!==null&&e.value!==void 0),a=e=>t?.sourceLabel?.(e)??e;return r.scope!=="default"&&r.scope!==`user`&&r.scope!==`tenant`?(0,V.jsxs)(o,{variant:`outline`,className:`text-blue-700 border-blue-300 text-[10px]`,children:[`Inherited from `,a(r.scope)]}):i?(0,V.jsxs)(o,{variant:`outline`,className:`text-amber-700 border-amber-300 text-[10px]`,children:[`Overrides `,a(i.scope)]}):null}function W({spec:e,resolved:t,labelText:n,labels:r}){return(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsxs)(T,{className:`text-sm font-medium`,children:[n,e.required?(0,V.jsx)(`span`,{className:`ml-0.5 text-destructive`,children:`*`}):null]}),e.deprecated?(0,V.jsxs)(o,{variant:`outline`,className:`text-amber-700 border-amber-300`,children:[`Deprecated`,e.replacedBy?` → ${e.replacedBy}`:``]}):null,t?.locked?(0,V.jsx)(H,{reason:t.lockedReason}):null,t&&!t.locked?(0,V.jsx)(U,{resolved:t,labels:r}):null,t?.source&&t.source!=="default"&&!t.locked?(0,V.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:r?.sourceLabel?.(t.source)??t.source}):null]})}function G({description:e}){return e?(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:e}):null}function K(e){let{spec:t,resolved:n,value:r,onChange:i,onAction:a,locked:o,saving:s,labels:u}=e,f=(0,B.useId)(),S=!!(o||s),C=z(t.label),O=t.key&&u?u.fieldLabel(t.key,C):C,k=t.key&&u?u.fieldHelp(t.key,t.description):t.description;if(t.type===`group`){let e=t.id&&u?u.groupTitle(t.id,C):C,n=t.id&&u?u.groupDescription(t.id,t.description):t.description;return(0,V.jsxs)(`div`,{className:`pt-6 pb-2`,children:[(0,V.jsx)(`h3`,{className:`text-sm font-semibold tracking-tight text-foreground/90`,children:e}),n?(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:n}):null,(0,V.jsx)(N,{className:`mt-3`})]})}if(t.type===`info_banner`)return(0,V.jsxs)(A,{variant:t.bannerSeverity===`error`?`destructive`:`default`,className:`my-2`,children:[(0,V.jsx)(D,{className:`h-4 w-4`}),(0,V.jsx)(v,{children:C}),t.bannerText?(0,V.jsx)(x,{children:t.bannerText}):null]});if(t.type===`child_pane`)return(0,V.jsxs)(`a`,{href:`#/settings/${t.childNamespace}`,className:`flex items-center justify-between rounded-md border border-border bg-card px-4 py-3 hover:bg-accent transition-colors`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`div`,{className:`text-sm font-medium`,children:C}),t.description?(0,V.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:t.description}):null]}),(0,V.jsx)(M,{className:`h-4 w-4 text-muted-foreground`})]});if(t.type===`title_value`)return(0,V.jsxs)(`div`,{className:`flex items-center justify-between py-2`,children:[(0,V.jsx)(W,{spec:t,resolved:n,labelText:O,labels:u}),(0,V.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:String(r??`—`)})]});if(t.type===`action_button`){let e=t.icon?R(t.icon):null,n=t.id??t.key??`test`,r=u?u.actionLabel(n,C):C;return(0,V.jsxs)(`div`,{className:`flex items-center justify-between py-3`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`div`,{className:`text-sm font-medium`,children:r}),t.description?(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:t.description}):null]}),(0,V.jsxs)(b,{size:`sm`,variant:`secondary`,onClick:a,disabled:s,children:[e?(0,V.jsx)(e,{className:`h-4 w-4 mr-1.5`}):null,r]})]})}let P=e=>(0,V.jsxs)(`div`,{className:`space-y-1.5 py-2`,children:[(0,V.jsx)(W,{spec:t,resolved:n,labelText:O,labels:u}),e,(0,V.jsx)(G,{description:k})]}),F=e=>{let n=typeof e.label==`string`?e.label:e.label?.defaultValue??String(e.value);return!t.key||!u?n:u.optionLabel(t.key,String(e.value),n)};switch(t.type){case`text`:case`email`:case`url`:case`phone`:return P((0,V.jsx)(w,{id:f,type:t.type===`email`?`email`:t.type===`url`?`url`:`text`,value:r??``,minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,disabled:S,onChange:e=>i(e.target.value)}));case`password`:return P((0,V.jsx)(w,{id:f,type:`password`,autoComplete:`new-password`,placeholder:r?`••••••••`:``,disabled:S,onChange:e=>i(e.target.value)}));case`textarea`:return P((0,V.jsx)(j,{id:f,rows:t.rows??4,value:r??``,minLength:t.minLength,maxLength:t.maxLength,disabled:S,onChange:e=>i(e.target.value)}));case`number`:return P((0,V.jsx)(w,{id:f,type:`number`,value:r,min:t.min,max:t.max,step:t.step,disabled:S,onChange:e=>i(e.target.value===``?null:Number(e.target.value))}));case`toggle`:return(0,V.jsxs)(`div`,{className:`flex items-center justify-between py-3`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(W,{spec:t,resolved:n,labelText:O,labels:u}),(0,V.jsx)(G,{description:k})]}),(0,V.jsx)(y,{id:f,checked:!!r,disabled:S,onCheckedChange:e=>i(e)})]});case`select`:return P((0,V.jsxs)(c,{value:r==null?void 0:String(r),onValueChange:e=>i(e),disabled:S,children:[(0,V.jsx)(p,{id:f,children:(0,V.jsx)(h,{placeholder:`Select…`})}),(0,V.jsx)(m,{children:t.options?.map(e=>(0,V.jsx)(l,{value:String(e.value),children:F(e)},String(e.value)))})]}));case`radio`:return P((0,V.jsx)(g,{value:r==null?void 0:String(r),onValueChange:e=>i(e),disabled:S,children:t.options?.map(e=>(0,V.jsxs)(`div`,{className:`flex items-center space-x-2`,children:[(0,V.jsx)(_,{value:String(e.value),id:`${f}-${e.value}`}),(0,V.jsx)(T,{htmlFor:`${f}-${e.value}`,className:`text-sm font-normal`,children:F(e)})]},String(e.value)))}));case`multiselect`:{let e=Array.isArray(r)?r:[];return P((0,V.jsx)(`div`,{className:`grid grid-cols-2 gap-2`,children:t.options?.map(t=>{let n=String(t.value);return(0,V.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,V.jsx)(d,{checked:e.map(String).includes(n),disabled:S,onCheckedChange:t=>{let r=new Set(e.map(String));t?r.add(n):r.delete(n),i(Array.from(r))}}),F(t)]},n)})}))}case`slider`:return P((0,V.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,V.jsx)(E,{value:[Number(r??t.min??0)],min:t.min??0,max:t.max??100,step:t.step??1,disabled:S,onValueChange:e=>i(e[0]),className:`flex-1`}),(0,V.jsx)(`span`,{className:`text-sm tabular-nums w-12 text-right`,children:String(r??t.min??0)})]}));case`color`:return P((0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsx)(w,{id:f,type:`color`,value:r??`#000000`,disabled:S,onChange:e=>i(e.target.value),className:`w-16 h-9 p-1`}),(0,V.jsx)(w,{value:r??``,disabled:S,onChange:e=>i(e.target.value),className:`flex-1 font-mono text-sm`})]}));case`json`:return P((0,V.jsx)(j,{id:f,rows:t.rows??6,className:`font-mono text-xs`,value:typeof r==`string`?r:JSON.stringify(r??null,null,2),disabled:S,onChange:e=>i(e.target.value)}));default:return P((0,V.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`Unsupported specifier type: `,t.type]}))}}var q=new Set([`common`,`validation`,`errors`,`system`,`auth`]);function J(e){let{t,i18n:n}=a();return(0,B.useMemo)(()=>{let r=()=>{if(!n||typeof n.getResourceBundle!=`function`)return[];let e=n.language||`en`,t=n.getResourceBundle(e,`translation`);return t?Object.keys(t).filter(e=>!q.has(e)&&t[e]&&typeof t[e]==`object`&&t[e].settings):[]},i=(n,i)=>{if(!e)return i;try{let i=r();for(let r of i){let i=`${r}.settings.${e}.${n}`,a=t(i,{defaultValue:``});if(a&&a!==i&&a!==``)return a}}catch{}return i},a=(e,r)=>{try{if(!n||typeof n.getResourceBundle!=`function`)return r;let i=n.language||`en`,a=n.getResourceBundle(i,`translation`);if(!a)return r;for(let n of Object.keys(a)){if(q.has(n))continue;let r=a[n];if(!r||typeof r!=`object`||!(`settingsCommon`in r))continue;let i=`${n}.settingsCommon.${e}`,o=t(i,{defaultValue:``});if(o&&o!==i&&o!==``)return o}}catch{}return r},o={env:`Env`,global:`Global`,tenant:`Tenant`,user:`User`,default:`Default`};return{title:e=>i(`title`,e)??e,description:e=>i(`description`,e),groupTitle:(e,t)=>i(`groups.${e}.title`,t)??t,groupDescription:(e,t)=>i(`groups.${e}.description`,t),fieldLabel:(e,t)=>i(`keys.${e}.label`,t)??t,fieldHelp:(e,t)=>i(`keys.${e}.help`,t),fieldPlaceholder:(e,t)=>i(`keys.${e}.placeholder`,t),optionLabel:(e,t,n)=>i(`keys.${e}.options.${t}`,n)??n,actionLabel:(e,t)=>i(`actions.${e}.label`,t)??t,actionConfirm:(e,t)=>i(`actions.${e}.confirmText`,t),actionSuccess:(e,t)=>i(`actions.${e}.successMessage`,t),sourceLabel:e=>a(`sourceLabels.${e}`,o[e]??e)}},[e,t,n,n?.language])}function Y(e,t){if(!e)return!0;let n=e.trim().match(/^\$\{(.+)\}$/);if(!n)return!0;try{return!!Function(`data`,`with (data) { return (${n[1]}); }`)(t)}catch{return!0}}function X(){let e=n(),t=i(),r=e.namespace??``,[a,s]=(0,B.useState)(null),[c,l]=(0,B.useState)(!0),[d,p]=(0,B.useState)(!1),[m,h]=(0,B.useState)(null),[g,_]=(0,B.useState)({}),v=(0,B.useCallback)(async()=>{l(!0),h(null);try{s(await L(r)),_({})}catch(e){h(e?.message??`Failed to load settings`)}finally{l(!1)}},[r]);(0,B.useEffect)(()=>{r&&v()},[r,v]);let y=(0,B.useMemo)(()=>{let e={};if(!a)return e;for(let[t,n]of Object.entries(a.values))e[t]=n.value;return{...e,...g}},[a,g]),x=(0,B.useMemo)(()=>Object.keys(g),[g]),w=J(r);if(!r)return(0,V.jsx)(`div`,{className:`p-6 text-muted-foreground`,children:`No namespace selected.`});if(c)return(0,V.jsxs)(`div`,{className:`p-6 space-y-3 max-w-3xl`,children:[(0,V.jsx)(f,{className:`h-8 w-1/3`}),(0,V.jsx)(f,{className:`h-4 w-2/3`}),(0,V.jsx)(f,{className:`h-32 w-full`}),(0,V.jsx)(f,{className:`h-32 w-full`})]});if(m)return(0,V.jsxs)(`div`,{className:`p-6 max-w-3xl`,children:[(0,V.jsxs)(b,{variant:`ghost`,size:`sm`,onClick:()=>t(-1),children:[(0,V.jsx)(k,{className:`h-4 w-4 mr-1`}),` Back`]}),(0,V.jsx)(O,{className:`mt-3`,children:(0,V.jsx)(u,{className:`py-8 text-center text-sm text-destructive`,children:m})})]});if(!a)return null;let{manifest:T,values:E}=a,D=T.icon?R(T.icon):null,A=w.title(z(T.label)),j=w.description(T.description),M=async()=>{if(x.length!==0){p(!0);try{let e=await F(r,g);s({...a,values:{...E,...e.values}}),_({}),P.success(`Settings saved`)}catch(e){e?.payload?.error?.code===`SETTINGS_LOCKED`?P.error(`Locked by environment: ${e.payload.error.key}`):P.error(e?.message??`Save failed`)}finally{p(!1)}}},N=async e=>{p(!0);try{let t=await I(r,e,g);t.ok?P.success(t.message??`Action succeeded`):P.error(t.message??`Action failed`)}catch(e){P.error(e?.message??`Action failed`)}finally{p(!1)}};return(0,V.jsxs)(`div`,{className:`p-6 max-w-3xl mx-auto pb-32`,children:[(0,V.jsxs)(b,{variant:`ghost`,size:`sm`,onClick:()=>t(`/system/settings`),children:[(0,V.jsx)(k,{className:`h-4 w-4 mr-1`}),` All settings`]}),(0,V.jsxs)(`div`,{className:`mt-3 flex items-start gap-3`,children:[D?(0,V.jsx)(D,{className:`h-7 w-7 mt-0.5 text-muted-foreground`}):null,(0,V.jsxs)(`div`,{className:`flex-1`,children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:A}),T.beta?(0,V.jsx)(o,{variant:`secondary`,children:`Beta`}):null]}),j?(0,V.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:j}):null]})]}),T.helpText?(0,V.jsx)(`p`,{className:`text-sm text-muted-foreground mt-4 whitespace-pre-wrap`,children:T.helpText}):null,(0,V.jsx)(`div`,{className:`mt-6 divide-y`,children:T.specifiers.filter(e=>Y(e.visible,y)).map((e,t)=>{let n=e.key,r=n?E[n]:void 0;return(0,V.jsx)(K,{spec:e,resolved:r,value:n?n in g?g[n]:r?.value:void 0,onChange:e=>n&&_(t=>({...t,[n]:e})),onAction:e.type===`action_button`?()=>N(e.id??n??`test`):void 0,locked:r?.locked,saving:d,labels:w},(n??`_layout_${t}`)+t)})}),x.length>0?(0,V.jsx)(`div`,{className:`fixed bottom-0 inset-x-0 bg-background/95 backdrop-blur border-t shadow-lg z-40`,children:(0,V.jsxs)(`div`,{className:`max-w-3xl mx-auto px-6 py-3 flex items-center justify-between`,children:[(0,V.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[x.length,` unsaved change`,x.length>1?`s`:``]}),(0,V.jsxs)(`div`,{className:`flex gap-2`,children:[(0,V.jsxs)(b,{variant:`ghost`,size:`sm`,onClick:()=>_({}),disabled:d,children:[(0,V.jsx)(C,{className:`h-4 w-4 mr-1`}),` Discard`]}),(0,V.jsxs)(b,{onClick:M,disabled:d,children:[d?(0,V.jsx)(S,{className:`h-4 w-4 mr-1 animate-spin`}):null,`Save changes`]})]})]})}):null]})}export{X as SettingsView};
|
|
1
|
+
import{o as e}from"./rolldown-runtime-CMxvf4Kt.js";import{_ as t,f as n,t as r,u as i}from"./vendor-react-DR370ovB.js";import{r as a}from"./framework-DLckRGJs.js";import{$n as o,Ai as s,Bt as c,Cs as l,Ht as u,Ja as d,Jn as f,Kn as p,Ma as m,Mt as h,Ut as g,Vt as _,Wt as v,Xt as y,Zt as b,ac as x,ar as S,ft as C,hr as w,ir as T,ja as E,nn as D,on as O,pt as k,qn as A,rr as j,tt as M,zt as N}from"./ui-components-B2CBE2Rs.js";import{r as P}from"./vendor-ui-utils-rQOI1gAo.js";import{a as F,i as I,n as L,o as R,t as z}from"./types-DjNzBgbB.js";var B=e(t(),1),V=r();function H({reason:e,className:t}){return(0,V.jsxs)(o,{variant:`outline`,className:`gap-1 border-amber-300 bg-amber-50 text-amber-900 ${t??``}`,title:e??`Pinned by environment variable — cannot be edited from the UI.`,children:[(0,V.jsx)(E,{className:`h-3 w-3`}),`Locked by env`]})}function U({resolved:e,labels:t}){let n=e.cascadeChain;if(!n||n.length===0)return null;let r=n.find(e=>e.effective)??n[n.length-1],i=n.find(e=>e!==r&&e.value!==null&&e.value!==void 0),a=e=>t?.sourceLabel?.(e)??e;return r.scope!=="default"&&r.scope!==`user`&&r.scope!==`tenant`?(0,V.jsxs)(o,{variant:`outline`,className:`text-blue-700 border-blue-300 text-[10px]`,children:[`Inherited from `,a(r.scope)]}):i?(0,V.jsxs)(o,{variant:`outline`,className:`text-amber-700 border-amber-300 text-[10px]`,children:[`Overrides `,a(i.scope)]}):null}function W({spec:e,resolved:t,labelText:n,labels:r}){return(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsxs)(O,{className:`text-sm font-medium`,children:[n,e.required?(0,V.jsx)(`span`,{className:`ml-0.5 text-destructive`,children:`*`}):null]}),e.deprecated?(0,V.jsxs)(o,{variant:`outline`,className:`text-amber-700 border-amber-300`,children:[`Deprecated`,e.replacedBy?` → ${e.replacedBy}`:``]}):null,t?.locked?(0,V.jsx)(H,{reason:t.lockedReason}):null,t&&!t.locked?(0,V.jsx)(U,{resolved:t,labels:r}):null,t?.source&&t.source!=="default"&&!t.locked?(0,V.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:r?.sourceLabel?.(t.source)??t.source}):null]})}function G({description:e}){return e?(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:e}):null}function K(e){let{spec:t,resolved:n,value:r,onChange:i,onAction:a,locked:o,saving:s,labels:f}=e,m=(0,B.useId)(),h=!!(o||s),x=z(t.label),E=t.key&&f?f.fieldLabel(t.key,x):x,A=t.key&&f?f.fieldHelp(t.key,t.description):t.description;if(t.type===`group`){let e=t.id&&f?f.groupTitle(t.id,x):x,n=t.id&&f?f.groupDescription(t.id,t.description):t.description;return(0,V.jsxs)(`div`,{className:`pt-6 pb-2`,children:[(0,V.jsx)(`h3`,{className:`text-sm font-semibold tracking-tight text-foreground/90`,children:e}),n?(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:n}):null,(0,V.jsx)(N,{className:`mt-3`})]})}if(t.type===`info_banner`)return(0,V.jsxs)(j,{variant:t.bannerSeverity===`error`?`destructive`:`default`,className:`my-2`,children:[(0,V.jsx)(d,{className:`h-4 w-4`}),(0,V.jsx)(S,{children:x}),t.bannerText?(0,V.jsx)(T,{children:t.bannerText}):null]});if(t.type===`child_pane`)return(0,V.jsxs)(`a`,{href:`#/settings/${t.childNamespace}`,className:`flex items-center justify-between rounded-md border border-border bg-card px-4 py-3 hover:bg-accent transition-colors`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`div`,{className:`text-sm font-medium`,children:x}),t.description?(0,V.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:t.description}):null]}),(0,V.jsx)(l,{className:`h-4 w-4 text-muted-foreground`})]});if(t.type===`title_value`)return(0,V.jsxs)(`div`,{className:`flex items-center justify-between py-2`,children:[(0,V.jsx)(W,{spec:t,resolved:n,labelText:E,labels:f}),(0,V.jsx)(`span`,{className:`text-sm text-muted-foreground`,children:String(r??`—`)})]});if(t.type===`action_button`){let e=t.icon?R(t.icon):null,n=t.id??t.key??`test`,r=f?f.actionLabel(n,x):x;return(0,V.jsxs)(`div`,{className:`flex items-center justify-between py-3`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`div`,{className:`text-sm font-medium`,children:r}),t.description?(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground mt-1`,children:t.description}):null]}),(0,V.jsxs)(w,{size:`sm`,variant:`secondary`,onClick:a,disabled:s,children:[e?(0,V.jsx)(e,{className:`h-4 w-4 mr-1.5`}):null,r]})]})}let P=e=>(0,V.jsxs)(`div`,{className:`space-y-1.5 py-2`,children:[(0,V.jsx)(W,{spec:t,resolved:n,labelText:E,labels:f}),e,(0,V.jsx)(G,{description:A})]}),F=e=>{let n=typeof e.label==`string`?e.label:e.label?.defaultValue??String(e.value);return!t.key||!f?n:f.optionLabel(t.key,String(e.value),n)};switch(t.type){case`text`:case`email`:case`url`:case`phone`:return P((0,V.jsx)(D,{id:m,type:t.type===`email`?`email`:t.type===`url`?`url`:`text`,value:r??``,minLength:t.minLength,maxLength:t.maxLength,pattern:t.pattern,disabled:h,onChange:e=>i(e.target.value)}));case`password`:return P((0,V.jsx)(D,{id:m,type:`password`,autoComplete:`new-password`,placeholder:r?`••••••••`:``,disabled:h,onChange:e=>i(e.target.value)}));case`textarea`:return P((0,V.jsx)(M,{id:m,rows:t.rows??4,value:r??``,minLength:t.minLength,maxLength:t.maxLength,disabled:h,onChange:e=>i(e.target.value)}));case`number`:return P((0,V.jsx)(D,{id:m,type:`number`,value:r,min:t.min,max:t.max,step:t.step,disabled:h,onChange:e=>i(e.target.value===``?null:Number(e.target.value))}));case`toggle`:return(0,V.jsxs)(`div`,{className:`flex items-center justify-between py-3`,children:[(0,V.jsxs)(`div`,{children:[(0,V.jsx)(W,{spec:t,resolved:n,labelText:E,labels:f}),(0,V.jsx)(G,{description:A})]}),(0,V.jsx)(C,{id:m,checked:!!r,disabled:h,onCheckedChange:e=>i(e)})]});case`select`:return P((0,V.jsxs)(c,{value:r==null?void 0:String(r),onValueChange:e=>i(e),disabled:h,children:[(0,V.jsx)(g,{id:m,children:(0,V.jsx)(v,{placeholder:`Select…`})}),(0,V.jsx)(_,{children:t.options?.map(e=>(0,V.jsx)(u,{value:String(e.value),children:F(e)},String(e.value)))})]}));case`radio`:return P((0,V.jsx)(y,{value:r==null?void 0:String(r),onValueChange:e=>i(e),disabled:h,children:t.options?.map(e=>(0,V.jsxs)(`div`,{className:`flex items-center space-x-2`,children:[(0,V.jsx)(b,{value:String(e.value),id:`${m}-${e.value}`}),(0,V.jsx)(O,{htmlFor:`${m}-${e.value}`,className:`text-sm font-normal`,children:F(e)})]},String(e.value)))}));case`multiselect`:{let e=Array.isArray(r)?r:[];return P((0,V.jsx)(`div`,{className:`grid grid-cols-2 gap-2`,children:t.options?.map(t=>{let n=String(t.value);return(0,V.jsxs)(`label`,{className:`flex items-center gap-2 text-sm`,children:[(0,V.jsx)(p,{checked:e.map(String).includes(n),disabled:h,onCheckedChange:t=>{let r=new Set(e.map(String));t?r.add(n):r.delete(n),i(Array.from(r))}}),F(t)]},n)})}))}case`slider`:return P((0,V.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,V.jsx)(k,{value:[Number(r??t.min??0)],min:t.min??0,max:t.max??100,step:t.step??1,disabled:h,onValueChange:e=>i(e[0]),className:`flex-1`}),(0,V.jsx)(`span`,{className:`text-sm tabular-nums w-12 text-right`,children:String(r??t.min??0)})]}));case`color`:return P((0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsx)(D,{id:m,type:`color`,value:r??`#000000`,disabled:h,onChange:e=>i(e.target.value),className:`w-16 h-9 p-1`}),(0,V.jsx)(D,{value:r??``,disabled:h,onChange:e=>i(e.target.value),className:`flex-1 font-mono text-sm`})]}));case`json`:return P((0,V.jsx)(M,{id:m,rows:t.rows??6,className:`font-mono text-xs`,value:typeof r==`string`?r:JSON.stringify(r??null,null,2),disabled:h,onChange:e=>i(e.target.value)}));default:return P((0,V.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[`Unsupported specifier type: `,t.type]}))}}var q=new Set([`common`,`validation`,`errors`,`system`,`auth`]);function J(e){let{t,i18n:n}=a();return(0,B.useMemo)(()=>{let r=()=>{if(!n||typeof n.getResourceBundle!=`function`)return[];let e=n.language||`en`,t=n.getResourceBundle(e,`translation`);return t?Object.keys(t).filter(e=>!q.has(e)&&t[e]&&typeof t[e]==`object`&&t[e].settings):[]},i=(n,i)=>{if(!e)return i;try{let i=r();for(let r of i){let i=`${r}.settings.${e}.${n}`,a=t(i,{defaultValue:``});if(a&&a!==i&&a!==``)return a}}catch{}return i},a=(e,r)=>{try{if(!n||typeof n.getResourceBundle!=`function`)return r;let i=n.language||`en`,a=n.getResourceBundle(i,`translation`);if(!a)return r;for(let n of Object.keys(a)){if(q.has(n))continue;let r=a[n];if(!r||typeof r!=`object`||!(`settingsCommon`in r))continue;let i=`${n}.settingsCommon.${e}`,o=t(i,{defaultValue:``});if(o&&o!==i&&o!==``)return o}}catch{}return r},o={env:`Env`,global:`Global`,tenant:`Tenant`,user:`User`,default:`Default`};return{title:e=>i(`title`,e)??e,description:e=>i(`description`,e),groupTitle:(e,t)=>i(`groups.${e}.title`,t)??t,groupDescription:(e,t)=>i(`groups.${e}.description`,t),fieldLabel:(e,t)=>i(`keys.${e}.label`,t)??t,fieldHelp:(e,t)=>i(`keys.${e}.help`,t),fieldPlaceholder:(e,t)=>i(`keys.${e}.placeholder`,t),optionLabel:(e,t,n)=>i(`keys.${e}.options.${t}`,n)??n,actionLabel:(e,t)=>i(`actions.${e}.label`,t)??t,actionConfirm:(e,t)=>i(`actions.${e}.confirmText`,t),actionSuccess:(e,t)=>i(`actions.${e}.successMessage`,t),sourceLabel:e=>a(`sourceLabels.${e}`,o[e]??e)}},[e,t,n,n?.language])}function Y(e,t){if(!e)return!0;let n=e.trim().match(/^\$\{(.+)\}$/);if(!n)return!0;try{return!!Function(`data`,`with (data) { return (${n[1]}); }`)(t)}catch{return!0}}function X(){let e=n(),t=i(),r=e.namespace??``,[a,c]=(0,B.useState)(null),[l,u]=(0,B.useState)(!0),[d,p]=(0,B.useState)(!1),[g,_]=(0,B.useState)(null),[v,y]=(0,B.useState)({}),b=(0,B.useCallback)(async()=>{u(!0),_(null);try{c(await L(r)),y({})}catch(e){_(e?.message??`Failed to load settings`)}finally{u(!1)}},[r]);(0,B.useEffect)(()=>{r&&b()},[r,b]);let S=(0,B.useMemo)(()=>{let e={};if(!a)return e;for(let[t,n]of Object.entries(a.values))e[t]=n.value;return{...e,...v}},[a,v]),C=(0,B.useMemo)(()=>Object.keys(v),[v]),T=J(r);if(!r)return(0,V.jsx)(`div`,{className:`p-6 text-muted-foreground`,children:`No namespace selected.`});if(l)return(0,V.jsxs)(`div`,{className:`p-6 space-y-3 max-w-3xl`,children:[(0,V.jsx)(h,{className:`h-8 w-1/3`}),(0,V.jsx)(h,{className:`h-4 w-2/3`}),(0,V.jsx)(h,{className:`h-32 w-full`}),(0,V.jsx)(h,{className:`h-32 w-full`})]});if(g)return(0,V.jsxs)(`div`,{className:`p-6 max-w-3xl`,children:[(0,V.jsxs)(w,{variant:`ghost`,size:`sm`,onClick:()=>t(-1),children:[(0,V.jsx)(x,{className:`h-4 w-4 mr-1`}),` Back`]}),(0,V.jsx)(A,{className:`mt-3`,children:(0,V.jsx)(f,{className:`py-8 text-center text-sm text-destructive`,children:g})})]});if(!a)return null;let{manifest:E,values:D}=a,O=E.icon?R(E.icon):null,k=T.title(z(E.label)),j=T.description(E.description),M=async()=>{if(C.length!==0){p(!0);try{let e=await F(r,v);c({...a,values:{...D,...e.values}}),y({}),P.success(`Settings saved`)}catch(e){e?.payload?.error?.code===`SETTINGS_LOCKED`?P.error(`Locked by environment: ${e.payload.error.key}`):P.error(e?.message??`Save failed`)}finally{p(!1)}}},N=async e=>{p(!0);try{let t=await I(r,e,v);t.ok?P.success(t.message??`Action succeeded`):P.error(t.message??`Action failed`)}catch(e){P.error(e?.message??`Action failed`)}finally{p(!1)}};return(0,V.jsxs)(`div`,{className:`p-6 max-w-3xl mx-auto pb-32`,children:[(0,V.jsxs)(w,{variant:`ghost`,size:`sm`,onClick:()=>t(`/system/settings`),children:[(0,V.jsx)(x,{className:`h-4 w-4 mr-1`}),` All settings`]}),(0,V.jsxs)(`div`,{className:`mt-3 flex items-start gap-3`,children:[O?(0,V.jsx)(O,{className:`h-7 w-7 mt-0.5 text-muted-foreground`}):null,(0,V.jsxs)(`div`,{className:`flex-1`,children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:k}),E.beta?(0,V.jsx)(o,{variant:`secondary`,children:`Beta`}):null]}),j?(0,V.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:j}):null]})]}),E.helpText?(0,V.jsx)(`p`,{className:`text-sm text-muted-foreground mt-4 whitespace-pre-wrap`,children:E.helpText}):null,(0,V.jsx)(`div`,{className:`mt-6 divide-y`,children:E.specifiers.filter(e=>Y(e.visible,S)).map((e,t)=>{let n=e.key,r=n?D[n]:void 0;return(0,V.jsx)(K,{spec:e,resolved:r,value:n?n in v?v[n]:r?.value:void 0,onChange:e=>n&&y(t=>({...t,[n]:e})),onAction:e.type===`action_button`?()=>N(e.id??n??`test`):void 0,locked:r?.locked,saving:d,labels:T},(n??`_layout_${t}`)+t)})}),C.length>0?(0,V.jsx)(`div`,{className:`fixed bottom-0 inset-x-0 bg-background/95 backdrop-blur border-t shadow-lg z-40`,children:(0,V.jsxs)(`div`,{className:`max-w-3xl mx-auto px-6 py-3 flex items-center justify-between`,children:[(0,V.jsxs)(`div`,{className:`text-sm text-muted-foreground`,children:[C.length,` unsaved change`,C.length>1?`s`:``]}),(0,V.jsxs)(`div`,{className:`flex gap-2`,children:[(0,V.jsxs)(w,{variant:`ghost`,size:`sm`,onClick:()=>y({}),disabled:d,children:[(0,V.jsx)(s,{className:`h-4 w-4 mr-1`}),` Discard`]}),(0,V.jsxs)(w,{onClick:M,disabled:d,children:[d?(0,V.jsx)(m,{className:`h-4 w-4 mr-1 animate-spin`}):null,`Save changes`]})]})]})}):null]})}export{X as SettingsView};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as e}from"./rolldown-runtime-CMxvf4Kt.js";import{_ as t,f as n,t as r,u as i}from"./vendor-react-DR370ovB.js";import{d as a}from"./infrastructure-CJNwTVno.js";import{w as o}from"./framework-
|
|
1
|
+
import{o as e}from"./rolldown-runtime-CMxvf4Kt.js";import{_ as t,f as n,t as r,u as i}from"./vendor-react-DR370ovB.js";import{d as a}from"./infrastructure-CJNwTVno.js";import{w as o}from"./framework-DLckRGJs.js";import{$n as s,Ar as c,Ci as l,Ga as u,Jn as d,Jr as f,Ma as p,Rs as m,Wo as h,Ws as g,Xn as _,Yn as v,Zn as y,bi as b,ei as x,jr as S,mi as C,qn as w,za as T}from"./ui-components-B2CBE2Rs.js";import"./index-JrHkY-wh.js";var E=e(t(),1),D=r();function O(){let e=i(),{appName:t}=n(),r=t?`/apps/${t}`:``,O=o(),k=a(),[A,j]=(0,E.useState)({users:null,orgs:null,roles:null,permissions:null,auditLogs:null}),[M,N]=(0,E.useState)(!0),P=(0,E.useCallback)(async()=>{if(O){N(!0);try{let[e,t,n,r,i]=await Promise.all([O.find(`sys_user`).catch(()=>({data:[]})),O.find(`sys_org`).catch(()=>({data:[]})),O.find(`sys_role`).catch(()=>({data:[]})),O.find(`sys_permission`).catch(()=>({data:[]})),O.find(`sys_audit_log`).catch(()=>({data:[]}))]);j({users:e.data?.length??0,orgs:t.data?.length??0,roles:n.data?.length??0,permissions:r.data?.length??0,auditLogs:i.data?.length??0})}catch{}finally{N(!1)}}},[O]);(0,E.useEffect)(()=>{P()},[P]);let F=[{title:`Applications`,description:`Manage all configured applications`,icon:T,href:`${r}/system/apps`,countLabel:``,count:null},{title:`Metadata`,description:`Browse and edit every metadata type the platform exposes`,icon:h,href:`${r}/component/metadata/directory`,countLabel:``,count:null}],I=[{title:`Users`,description:`Manage system users and accounts`,icon:c,href:`${r}/system/users`,countLabel:`users`,count:A.users},{title:`Organizations`,description:`Manage organizations and teams`,icon:m,href:`${r}/system/organizations`,countLabel:`organizations`,count:A.orgs},{title:`Roles`,description:`Configure roles and access levels`,icon:C,href:`${r}/system/roles`,countLabel:`roles`,count:A.roles},{title:`Permissions`,description:`Manage permission rules and assignments`,icon:u,href:`${r}/system/permissions`,countLabel:`permissions`,count:A.permissions},{title:`Audit Log`,description:`View system activity and changes`,icon:l,href:`${r}/system/audit-log`,countLabel:`entries`,count:A.auditLogs},{title:`AI Approvals`,description:`Review actions AI agents propose before they execute`,icon:g,href:`${r}/system/ai-approvals`,countLabel:``,count:null},{title:`App Marketplace`,description:`Browse and install approved apps from the ObjectStack catalog`,icon:x,href:`${r}/system/marketplace`,countLabel:``,count:null,adminOnly:!0},{title:`Settings`,description:`Configure mail, branding, feature flags, and more`,icon:b,href:`${r}/system/settings`,countLabel:``,count:null},{title:`Developer`,description:`API console, flow runs, and public form management`,icon:f,href:`${r}/developer`,countLabel:``,count:null},{title:`Profile`,description:`View and edit your account settings`,icon:S,href:`${r}/system/profile`,countLabel:``,count:null}],L=[...F,...I].filter(e=>!e.adminOnly||k);return(0,D.jsxs)(`div`,{className:`flex flex-col gap-6 p-4 sm:p-6`,children:[(0,D.jsxs)(`div`,{className:`min-w-0`,children:[(0,D.jsx)(`h1`,{className:`text-xl sm:text-2xl font-bold tracking-tight`,children:`System Settings`}),(0,D.jsx)(`p`,{className:`text-sm text-muted-foreground mt-1`,children:`Manage applications, users, roles, permissions, and system configuration`})]}),M&&(0,D.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-muted-foreground`,role:`status`,"aria-live":`polite`,children:[(0,D.jsx)(p,{className:`h-4 w-4 animate-spin`,"aria-hidden":`true`}),`Loading statistics...`]}),(0,D.jsx)(`div`,{className:`grid gap-4 sm:grid-cols-2 lg:grid-cols-3`,children:L.map(t=>{let n=t.icon;return(0,D.jsxs)(w,{className:`cursor-pointer transition-colors hover:bg-accent/50`,onClick:()=>e(t.href),"data-testid":`hub-card-${t.title.toLowerCase().replace(/\s+/g,`-`)}`,role:`link`,tabIndex:0,"aria-label":`${t.title}: ${t.description}`,onKeyDown:n=>{(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),e(t.href))},children:[(0,D.jsxs)(_,{className:`flex flex-row items-center gap-3 pb-2`,children:[(0,D.jsx)(`div`,{className:`flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary`,children:(0,D.jsx)(n,{className:`h-5 w-5`})}),(0,D.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,D.jsx)(y,{className:`text-base`,children:t.title}),(0,D.jsx)(v,{className:`text-xs`,children:t.description})]})]}),(0,D.jsx)(d,{className:`pt-0`,children:t.count!==null&&(0,D.jsxs)(s,{variant:`secondary`,children:[t.count,` `,t.countLabel]})})]},t.title)})})]})}export{O as SystemHubPage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mt as e}from"./framework-ZJouI0cJ.js";import{s as t}from"./vendor-objectstack-BNd856rx.js";var n=class{cache;inflight;maxSize;ttl;stats;constructor(e={}){this.cache=new Map,this.inflight=new Map,this.maxSize=e.maxSize||100,this.ttl=e.ttl||300*1e3,this.stats={hits:0,misses:0,evictions:0,coalesced:0}}async get(e,t){let n=Date.now(),r=this.cache.get(e);if(r){if(n-r.timestamp<this.ttl)return r.accessCount++,r.lastAccessed=n,this.stats.hits++,this.cache.delete(e),this.cache.set(e,r),r.data;this.cache.delete(e)}let i=this.inflight.get(e);if(i)return this.stats.coalesced++,i;this.stats.misses++;let a=(async()=>{try{let n=await t();return this.set(e,n),n}finally{this.inflight.delete(e)}})();return this.inflight.set(e,a),a}prime(e,t){this.set(e,t)}set(e,t){let n=Date.now();this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictLRU(),this.cache.set(e,{data:t,timestamp:n,accessCount:1,lastAccessed:n})}evictLRU(){let e=this.cache.keys().next().value;e!==void 0&&(this.cache.delete(e),this.stats.evictions++)}invalidate(e){e?this.cache.delete(e):this.cache.clear()}clear(){this.cache.clear(),this.inflight.clear(),this.stats={hits:0,misses:0,evictions:0,coalesced:0}}getStats(){let e=this.stats.hits+this.stats.misses,t=e>0?this.stats.hits/e:0;return{size:this.cache.size,maxSize:this.maxSize,hits:this.stats.hits,misses:this.stats.misses,evictions:this.stats.evictions,coalesced:this.stats.coalesced,hitRate:t}}getCachedSync(e){let t=this.cache.get(e);if(t){if(this.ttl>0&&Date.now()-t.timestamp>this.ttl){this.cache.delete(e);return}return this.cache.delete(e),this.cache.set(e,t),this.stats.hits++,t.data}}has(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>=this.ttl?(this.cache.delete(e),!1):!0:!1}},r=class extends Error{code;statusCode;details;constructor(e,t,n,r){super(e),this.code=t,this.statusCode=n,this.details=r,this.name=`ObjectStackError`,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,details:this.details,stack:this.stack}}},i=class extends r{constructor(e,t){super(`Metadata not found for object: ${e}`,`METADATA_NOT_FOUND`,404,{objectName:e,...t}),this.name=`MetadataNotFoundError`}},a=class extends r{successCount;failureCount;errors;constructor(e,t,n,r,i){super(`Bulk ${e} operation failed: ${t} succeeded, ${n} failed`,`BULK_OPERATION_ERROR`,500,{operation:e,successCount:t,failureCount:n,errors:r,...i}),this.successCount=t,this.failureCount=n,this.errors=r,this.name=`BulkOperationError`}getSummary(){let e=this.successCount+this.failureCount,t=e>0?this.failureCount/e:0;return{operation:this.details?.operation,total:e,successful:this.successCount,failed:this.failureCount,failureRate:t,errors:this.errors}}},o=class extends r{url;constructor(e,t,n,r){super(`Connection error: ${e}`,`CONNECTION_ERROR`,r||503,{url:t,...n}),this.url=t,this.name=`ConnectionError`}},s=class extends r{constructor(e=`Authentication failed`,t,n){super(e,`AUTHENTICATION_ERROR`,n||401,t),this.name=`AuthenticationError`}},c=class extends r{field;validationErrors;constructor(e,t,n,r){super(e,`VALIDATION_ERROR`,400,{field:t,validationErrors:n,...r}),this.field=t,this.validationErrors=n,this.name=`ValidationError`}getValidationErrors(){return this.validationErrors||[]}};function l(e,t){let n=e?.status||e?.statusCode||500,a=e?.message||e?.statusText||`Unknown error`,l={context:t,response:{status:n,data:e?.data,headers:e?.headers}};switch(n){case 401:return new s(a,l,401);case 403:return new s(a,l,403);case 404:return t?.includes(`metadata`)||t?.includes(`schema`)||t?.includes(`getObjectSchema`)?new i(u(t),l):new r(a,`NOT_FOUND`,404,l);case 400:return new c(a,void 0,e?.data?.errors,l);case 503:return new o(a,e?.config?.url,l,503);case 504:return new o(a,e?.config?.url,l,504);default:return new r(a,`UNKNOWN_ERROR`,n,l)}}function u(e){if(!e)return`unknown`;let t=e.match(/\(([^)]+)\)/);return t?t[1]:`unknown`}var d=`sys_user_preference`;function f(e){let{dataSource:t,userId:n,key:r,resource:i=d,onError:a=()=>{}}=e,o=null,s=async()=>{let e={$filter:{user_id:n,key:r},$top:1};return((await t.find(i,e))?.data??[]).find(e=>{if(!e)return!1;let t=e.user_id!==void 0&&e.user_id!==n,i=e.key!==void 0&&e.key!==r;return!t&&!i})??null},c=e=>{if(Array.isArray(e))return e;if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}return[]};return{async load(){try{let e=await s();return e?(e.id!==void 0&&e.id!==null&&(o=e.id),c(e.value)):(o=null,[])}catch(e){return a(`load`,e),[]}},async save(e){try{let c=new Date().toISOString();if(o!==null)try{await t.update(i,o,{value:e,updated_at:c});return}catch(e){o=null,a(`save`,e)}let l=await s();if(l&&l.id!==void 0&&l.id!==null){o=l.id,await t.update(i,l.id,{value:e,updated_at:c});return}let u=(await t.create(i,{user_id:n,key:r,value:e,updated_at:c}))?.id;u!=null&&(o=u)}catch(e){a(`save`,e)}}}}var p=`/meta`,m=`/api/v1`;function h(e){let t=e.baseUrl.replace(/\/+$/,``),n=e.environmentId?`${m}/environments/${encodeURIComponent(e.environmentId)}${p}`:`${m}${p}`;return/\/api\/v\d+$/i.test(t)?`${t.replace(/\/api\/v\d+$/i,``)}${e.environmentId?`${m}/environments/${encodeURIComponent(e.environmentId)}${p}`:`${m}${p}`}`:`${t}${n}`}async function g(e){let t;try{t=await e.json()}catch{t=await e.text().catch(()=>void 0)}let n=(t&&typeof t==`object`&&`error`in t?String(t.error):void 0)??`Metadata request failed: ${e.status} ${e.statusText}`,r=Error(n);return r.status=e.status,r.body=t,t&&typeof t==`object`&&`code`in t&&(r.code=String(t.code)),r}var _=class e{base;fetchImpl;headers;previewDrafts;constructor(e){this.base=h(e),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.headers={Accept:`application/json`,...e.headers??{}},this.previewDrafts=e.previewDrafts===!0}withEnvironment(t){return new e({baseUrl:this.base.replace(/\/api\/v\d+(?:\/environments\/[^/]+)?\/meta$/,``).replace(/\/+$/,``),environmentId:t,fetch:this.fetchImpl,headers:this.headers,previewDrafts:this.previewDrafts})}withPreviewDrafts(t){if(t===this.previewDrafts)return this;let n=this.base.match(/\/api\/v\d+\/environments\/([^/]+)\/meta$/);return new e({baseUrl:this.base.replace(/\/api\/v\d+(?:\/environments\/[^/]+)?\/meta$/,``).replace(/\/+$/,``),...n?{environmentId:decodeURIComponent(n[1])}:{},fetch:this.fetchImpl,headers:this.headers,previewDrafts:t})}async listTypes(){let e=await this.fetchImpl(this.base,{method:`GET`,headers:this.headers,cache:`no-store`});if(!e.ok)throw await g(e);let t=await e.json();return Array.isArray(t)?t:t&&Array.isArray(t.entries)?t.entries:t&&Array.isArray(t.items)?t.items:t&&Array.isArray(t.types)?t.types.map(e=>({type:e})):[]}async list(e,t={}){let n=[];t.packageId&&n.push(`package=${encodeURIComponent(t.packageId)}`),this.previewDrafts&&n.push(`preview=draft`);let r=n.length?`?${n.join(`&`)}`:``,i=`${this.base}/${encodeURIComponent(e)}${r}`,a=await this.fetchImpl(i,{method:`GET`,headers:this.headers,cache:`no-store`});if(!a.ok)throw await g(a);let o=await a.json();return Array.isArray(o)?o:o&&Array.isArray(o.items)?o.items:[]}async listDrafts(e={}){let t=[];e.packageId&&t.push(`packageId=${encodeURIComponent(e.packageId)}`),e.type&&t.push(`type=${encodeURIComponent(e.type)}`);let n=t.length?`?${t.join(`&`)}`:``,r=`${this.base}/_drafts${n}`,i=await this.fetchImpl(r,{method:`GET`,headers:this.headers,cache:`no-store`});if(!i.ok)throw await g(i);let a=await i.json();return Array.isArray(a)?a:a?.drafts??a?.data?.drafts??[]}async get(e,t,n={}){let r=[];n.state===`draft`?r.push(`state=draft`):this.previewDrafts&&r.push(`preview=draft`),n.packageId&&r.push(`package=${encodeURIComponent(n.packageId)}`);let i=r.length?`?${r.join(`&`)}`:``,a=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}${i}`,o=await this.fetchImpl(a,{method:`GET`,headers:this.headers,cache:`no-store`});if(o.status===404)return null;if(!o.ok)throw await g(o);return await o.json()}async getDraft(e,t,n={}){return this.get(e,t,{state:`draft`,...n.packageId?{packageId:n.packageId}:{}})}async save(e,t,n,r={}){let i=[];r.force&&i.push(`force=true`),r.mode===`draft`&&i.push(`mode=draft`),r.packageId&&i.push(`package=${encodeURIComponent(r.packageId)}`);let a=i.length?`?${i.join(`&`)}`:``,o=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}${a}`,s={...this.headers,"Content-Type":`application/json`};r.ifMatch&&(s[`If-Match`]=r.ifMatch),r.actor&&(s[`X-Actor`]=r.actor);let c=await this.fetchImpl(o,{method:`PUT`,headers:s,body:JSON.stringify(n)});if(!c.ok)throw await g(c);return await c.json()}async publishDraft(e,t){let n=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/publish`,r=await this.fetchImpl(n,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`});if(!r.ok)throw await g(r);let i=await r.json().catch(()=>({}));return i?.data&&typeof i.data==`object`?i.data:i}async layered(e,t,n={}){let r=n.packageId?`&package=${encodeURIComponent(n.packageId)}`:``,i=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}?layers=true${r}`,a=await this.fetchImpl(i,{method:`GET`,headers:this.headers,cache:`no-store`});if(a.status===404)return{code:null,overlay:null,overlayScope:null,effective:null};if(!a.ok)throw await g(a);let o=await a.json();return o&&(`code`in o||`overlay`in o||`effective`in o)?{code:o.code??null,overlay:o.overlay??null,overlayScope:o.overlayScope??null,effective:o.effective??null,...o._diagnostics?{_diagnostics:o._diagnostics}:{},...o.lock===void 0?{}:{lock:o.lock},...o.lockReason===void 0?{}:{lockReason:o.lockReason},...o.lockSource===void 0?{}:{lockSource:o.lockSource},...o.lockDocsUrl===void 0?{}:{lockDocsUrl:o.lockDocsUrl},...o.provenance===void 0?{}:{provenance:o.provenance},...o.packageId===void 0?{}:{packageId:o.packageId},...o.packageVersion===void 0?{}:{packageVersion:o.packageVersion},...o.editable===void 0?{}:{editable:o.editable},...o.deletable===void 0?{}:{deletable:o.deletable},...o.resettable===void 0?{}:{resettable:o.resettable}}:{code:null,overlay:null,overlayScope:null,effective:o}}async diagnostics(e={}){let t=[];e.type&&t.push(`type=${encodeURIComponent(e.type)}`),e.severity&&t.push(`severity=${encodeURIComponent(e.severity)}`),e.packageId&&t.push(`package=${encodeURIComponent(e.packageId)}`);let n=t.length?`?${t.join(`&`)}`:``,r=`${this.base}/diagnostics${n}`,i=await this.fetchImpl(r,{method:`GET`,headers:this.headers,cache:`no-store`});if(i.status===404)return{entries:[],total:0,scannedTypes:0,scannedItems:0,stats:{}};if(!i.ok)throw await g(i);let a=await i.json();return{entries:Array.isArray(a.entries)?a.entries:[],total:typeof a.total==`number`?a.total:0,scannedTypes:typeof a.scannedTypes==`number`?a.scannedTypes:0,scannedItems:typeof a.scannedItems==`number`?a.scannedItems:0,stats:a.stats&&typeof a.stats==`object`?a.stats:{}}}async references(e,t){let n=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/references`,r=await this.fetchImpl(n,{method:`GET`,headers:this.headers,cache:`no-store`});if(r.status===404)return[];if(!r.ok)throw await g(r);let i=await r.json();return Array.isArray(i)?i:i?.items??[]}async reset(e,t,n={}){let r=n.state===`draft`?`?state=draft`:``,i=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}${r}`,a={...this.headers};n.ifMatch&&(a[`If-Match`]=n.ifMatch),n.actor&&(a[`X-Actor`]=n.actor);let o=await this.fetchImpl(i,{method:`DELETE`,headers:a});if(!o.ok)throw await g(o);return await o.json()}async publish(e,t,n={}){let r=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/publish`,i={...this.headers,"Content-Type":`application/json`};n.actor&&(i[`X-Actor`]=n.actor);let a=await this.fetchImpl(r,{method:`POST`,headers:i,body:JSON.stringify(n.message?{message:n.message}:{})});if(!a.ok)throw await g(a);return await a.json()}async rollback(e,t,n,r={}){let i=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/rollback`,a={...this.headers,"Content-Type":`application/json`};r.actor&&(a[`X-Actor`]=r.actor);let o=await this.fetchImpl(i,{method:`POST`,headers:a,body:JSON.stringify({toVersion:n,...r.message?{message:r.message}:{}})});if(!o.ok)throw await g(o);return await o.json()}async diff(e,t,n,r){let i=new URLSearchParams;n!==void 0&&i.set(`from`,String(n)),r!==void 0&&i.set(`to`,String(r));let a=i.toString(),o=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/diff${a?`?${a}`:``}`,s=await this.fetchImpl(o,{method:`GET`,headers:this.headers,cache:`no-store`});if(!s.ok)throw await g(s);return await s.json()}async history(e,t,n={}){let r=new URLSearchParams;n.sinceSeq!==void 0&&r.set(`sinceSeq`,String(n.sinceSeq)),n.limit!==void 0&&r.set(`limit`,String(n.limit));let i=r.toString(),a=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/history${i?`?${i}`:``}`,o=await this.fetchImpl(a,{method:`GET`,headers:this.headers,cache:`no-store`});if(!o.ok)throw await g(o);return await o.json()}async audit(e,t,n={}){let r=new URLSearchParams;n.limit!==void 0&&r.set(`limit`,String(n.limit));let i=r.toString(),a=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/audit${i?`?${i}`:``}`,o=await this.fetchImpl(a,{method:`GET`,headers:this.headers,cache:`no-store`});if(!o.ok)throw await g(o);return await o.json()}},v={equals:`=`,eq:`=`,"==":`=`,not_equals:`!=`,notequals:`!=`,ne:`!=`,greater_than:`>`,greaterthan:`>`,gt:`>`,greater_than_or_equal:`>=`,greater_than_or_equals:`>=`,greaterthanorequal:`>=`,gte:`>=`,less_than:`<`,lessthan:`<`,lt:`<`,less_than_or_equal:`<=`,less_than_or_equals:`<=`,lessthanorequal:`<=`,lte:`<=`,in:`in`,not_in:`nin`,notin:`nin`,nin:`nin`,contains:`contains`,not_contains:`notcontains`,notcontains:`notcontains`,starts_with:`startswith`,startswith:`startswith`,ends_with:`endswith`,endswith:`endswith`,between:`between`,is_null:`isnull`,isnull:`isnull`,is_not_null:`isnotnull`,isnotnull:`isnotnull`};function y(e){return typeof e==`string`?v[e.toLowerCase()]??v[e]??e:null}function b(e){if(!e||typeof e!=`object`)return null;let t=e.field??e.name,n=y(e.operator??e.op??`=`);return!t||!n?null:[String(t),n,e.value]}function x(e){if(e!=null){if(Array.isArray(e)){if(e.length===0)return;let t=e[0];if(e.length>0&&typeof t==`object`&&t&&!Array.isArray(t)&&t.field!==void 0){let t=e.map(e=>b(e)).filter(e=>e!==null);return t.length===0?void 0:t.length===1?t[0]:[`and`,...t]}return e}if(typeof e==`object`)return Object.keys(e).length===0?void 0:e}}var S=new Map;async function C(e,t){let n=e||`<default>`,r=S.get(n);if(r)return r;let i=t().catch(e=>{throw S.delete(n),e});return S.set(n,i),i}function w(e){if(!e||typeof e!=`object`)return!1;let t=e;if(t.httpStatus===404||t.status===404||t.statusCode===404)return!0;let n=typeof t.code==`string`?t.code:``;return n===`object_not_found`||n===`record_not_found`}var T=class extends Error{code=`CONCURRENT_UPDATE`;httpStatus=409;currentVersion;currentRecord;constructor(e){super(e.message??`Record was modified by another user`),this.name=`ConcurrentUpdateError`,this.currentVersion=e.currentVersion,this.currentRecord=e.currentRecord}};function E(e){if(!e||typeof e!=`object`)return e;let t=e;if(t.code!==`CONCURRENT_UPDATE`&&t.httpStatus!==409||t.code!==`CONCURRENT_UPDATE`)return e;let n=t.details??{};return new T({currentVersion:typeof n.currentVersion==`string`?n.currentVersion:null,currentRecord:n.currentRecord??null,message:typeof t.message==`string`?t.message:void 0})}function D(){let e=e=>{if(!e||typeof e!=`object`)return!1;if(e.status===404||e.statusCode===404)return!0;let t=e.error;if(t&&typeof t==`object`){let e=t.code;if(e===`object_not_found`||e===`record_not_found`)return!0}return!1},t={debug:(e,t)=>console.debug(e,t??``),info:(e,t)=>console.info(e,t??``),warn:(e,t)=>console.warn(e,t??``),error:(t,n,r)=>{if(e(r)){console.debug(`[ObjectStack] ${t} (suppressed expected 404)`,r);return}console.error(t,n??``,r??``)},fatal:(e,t,n)=>console.error(e,t??``,n??``),log:(e,...t)=>console.log(e,...t),child:()=>t,withTrace:()=>t};return t}function O(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(O).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${O(t[e])}`).join(`,`)}}`}var k=class{client;connected=!1;connectPromise=null;metadataCache;connectionState=`disconnected`;connectionStateListeners=[];batchProgressListeners=[];autoReconnect;maxReconnectAttempts;reconnectDelay;reconnectAttempts=0;baseUrl;token;fetchImpl;inflightFinds=new Map;missingResources=new Set;constructor(e){this.client=new t({...e,logger:D()}),this.metadataCache=new n(e.cache),this.autoReconnect=e.autoReconnect??!0,this.maxReconnectAttempts=e.maxReconnectAttempts??3,this.reconnectDelay=e.reconnectDelay??1e3,this.baseUrl=e.baseUrl,this.token=e.token,this.fetchImpl=e.fetch||globalThis.fetch.bind(globalThis)}async connect(){if(!this.connected)return this.connectPromise?this.connectPromise:(this.setConnectionState(`connecting`),this.connectPromise=(async()=>{try{let e=this.baseUrl||``,t=e?`${e.replace(/\/$/,``)}/api/v1/discovery`:`/api/v1/discovery`,n=await C(e,async()=>{let e=await this.fetchImpl(t,{method:`GET`,headers:this.token?{Authorization:`Bearer ${this.token}`}:void 0});if(!e.ok)throw Error(`discovery ${e.status} ${e.statusText}`);let n=await e.json();return n&&typeof n.success==`boolean`&&`data`in n?n.data:n});this.client.discoveryInfo=n,this.connected=!0,this.reconnectAttempts=0,this.setConnectionState(`connected`)}catch(e){let t=new o(e instanceof Error?e.message:`Failed to connect to ObjectStack server`,void 0,{originalError:e});if(this.setConnectionState(`error`,t),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts)await this.attemptReconnect();else throw t}finally{this.connectPromise=null}})(),this.connectPromise)}async attemptReconnect(){this.reconnectAttempts++,this.setConnectionState(`reconnecting`);let e=this.reconnectDelay*2**(this.reconnectAttempts-1);await new Promise(t=>setTimeout(t,e)),this.connected=!1,await this.connect()}getConnectionState(){return this.connectionState}isConnected(){return this.connected&&this.connectionState===`connected`}onConnectionStateChange(e){return this.connectionStateListeners.push(e),()=>{let t=this.connectionStateListeners.indexOf(e);t>-1&&this.connectionStateListeners.splice(t,1)}}onBatchProgress(e){return this.batchProgressListeners.push(e),()=>{let t=this.batchProgressListeners.indexOf(e);t>-1&&this.batchProgressListeners.splice(t,1)}}setConnectionState(e,t){this.connectionState=e;let n={state:e,timestamp:Date.now(),error:t};this.connectionStateListeners.forEach(e=>{try{e(n)}catch(e){console.error(`Error in connection state listener:`,e)}})}emitBatchProgress(e){this.batchProgressListeners.forEach(t=>{try{t(e)}catch(e){console.error(`Error in batch progress listener:`,e)}})}async find(e,t){if(this.missingResources.has(e))return{data:[],total:0};let n=`${e}::${O(t)}`,r=this.inflightFinds.get(n);if(r)return r;let i=(async()=>{if(await this.connect(),t?.$expand&&t.$expand.length>0){let n=await this.rawFindWithPopulate(e,t);return this.normalizeQueryResult(n,t)}let n=this.convertQueryParams(t);try{let r=await this.client.data.find(e,n);return this.normalizeQueryResult(r,t)}catch(t){if(w(t))return this.missingResources.add(e),{data:[],total:0};throw t}})();this.inflightFinds.set(n,i);let a=()=>{this.inflightFinds.get(n)===i&&this.inflightFinds.delete(n)};return i.then(a,a),i}async findOne(e,t,n){if(await this.connect(),n?.$expand&&n.$expand.length>0)try{let r={...n,$filter:{id:String(t)},$top:1},i=await this.rawFindWithPopulate(e,r);if(Array.isArray(i))return i[0]||null;let a=i;return(a.records||a.value||[])[0]||null}catch(e){if(w(e))return null}try{return(await this.client.data.get(e,String(t))).record}catch(e){if(w(e))return null;throw e}}async create(e,t){return await this.connect(),(await this.client.data.create(e,t)).record}async update(e,t,n,r){await this.connect();try{return(await this.client.data.update(e,String(t),n,r?.ifMatch?{ifMatch:r.ifMatch}:void 0)).record}catch(e){throw E(e)}}async delete(e,t,n){await this.connect();try{return(await this.client.data.delete(e,String(t),n?.ifMatch?{ifMatch:n.ifMatch}:void 0)).deleted}catch(e){throw E(e)}}async bulkUpdate(e,t,n){if(await this.connect(),!t||t.length===0)return 0;let r=t.map(e=>({id:String(e),data:n})),i=this.client.data.updateMany;if(typeof i==`function`)try{let n=await i(e,r,{continueOnError:!0});return n&&typeof n==`object`&&typeof n.succeeded==`number`?n.succeeded:Array.isArray(n)?n.length:t.length}catch(e){throw E(e)}let a=0;for(let r of t)try{await this.client.data.update(e,String(r),n),a++}catch{}return a}async bulkDelete(e,t){if(await this.connect(),!t||t.length===0)return 0;let n=t.map(e=>String(e)),r=this.client.data.deleteMany;if(typeof r==`function`)try{let t=await r(e,n,{continueOnError:!0});return t&&typeof t==`object`&&typeof t.succeeded==`number`?t.succeeded:Array.isArray(t)?t.length:n.length}catch(e){throw E(e)}let i=0;for(let t of n)try{await this.client.data.delete(e,t),i++}catch{}return i}async batchTransaction(e){let t=`${this.baseUrl}/api/v1/batch`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,...this.getAuthHeaders()},body:JSON.stringify({operations:e})});if(!n.ok){let e=await n.json().catch(()=>({message:n.statusText}));throw new r(e.error||e.message||`Batch failed with status ${n.status}`,`BATCH_ERROR`,n.status)}return n.json()}async bulk(e,t,n){if(await this.connect(),!n||n.length===0)return[];let i=n.length,o=0,s=0,c=()=>{this.emitBatchProgress({operation:t,total:i,completed:o,failed:s,percentage:i>0?(o+s)/i*100:0})};try{switch(t){case`create`:{c();let t=await this.client.data.createMany(e,n);return o=t.length,s=i-o,c(),t}case`delete`:{let t=n.map(e=>e.id).filter(Boolean);if(t.length===0){let e=n.map((e,t)=>({index:t,error:`Missing ID for item at index ${t}`}));throw s=n.length,c(),new a(`delete`,0,n.length,e)}return c(),await this.client.data.deleteMany(e,t),o=t.length,s=i-o,c(),[]}case`update`:{if(typeof this.client.data.updateMany==`function`)try{c();let t=this.client.data.updateMany,r=await t(e,n);return o=r.length,s=i-o,c(),r}catch{}let t=[],r=[];for(let i=0;i<n.length;i++){let a=n[i],l=a.id;if(!l){r.push({index:i,error:`Missing ID`}),s++,c();continue}try{let n=await this.client.data.update(e,String(l),a);t.push(n.record),o++,c()}catch(e){let t=e instanceof Error?e.message:String(e);r.push({index:i,error:t}),s++,c()}}if(r.length>0)throw new a(`update`,t.length,r.length,r,{resource:e,totalRecords:n.length});return t}default:throw new r(`Unsupported bulk operation: ${t}`,`UNSUPPORTED_OPERATION`,400)}}catch(i){if(c(),i instanceof a||i instanceof r)throw i;let o=i instanceof Error?i.message:String(i),s=n.map((e,t)=>({index:t,error:o}));throw new a(t,0,n.length,s,{resource:e,originalError:i})}}normalizeQueryResult(e,t){if(Array.isArray(e))return{data:e,total:e.length,page:1,pageSize:e.length,hasMore:!1};let n=e,r=n.records||n.value||[];return{data:r,total:n.total??n.count??r.length,page:t?.$skip&&t.$top?Math.floor(t.$skip/t.$top)+1:1,pageSize:t?.$top,hasMore:t?.$top?r.length===t.$top:!1}}async rawFindWithPopulate(e,t){let n=new URLSearchParams;if(t.$expand&&t.$expand.length>0&&n.set(`populate`,t.$expand.join(`,`)),t.$top!==void 0&&n.set(`top`,String(t.$top)),t.$skip!==void 0&&n.set(`skip`,String(t.$skip)),t.$select&&t.$select.length>0){let e=t.$select.includes(`id`)?t.$select:[`id`,...t.$select];n.set(`select`,e.join(`,`))}if(t.$orderby)if(Array.isArray(t.$orderby)){let e=t.$orderby.map(e=>{if(typeof e==`string`)return e;let t=e.field;return(e.order||`asc`)===`desc`?`-${t}`:t}).join(`,`);n.set(`sort`,e)}else{let e=Object.entries(t.$orderby).map(([e,t])=>t===`desc`?`-${e}`:e).join(`,`);n.set(`sort`,e)}if(t.$filter!==void 0&&t.$filter!==null){let e=x(t.$filter);e!==void 0&&n.set(`filter`,JSON.stringify(e))}let r=this.baseUrl.replace(/\/$/,``),i=n.toString(),a=`${r}${/\/api\/v\d+$/i.test(r)?`/data`:`/api/v1/data`}/${e}${i?`?${i}`:``}`,o={"Content-Type":`application/json`};this.token&&(o.Authorization=`Bearer ${this.token}`);let s=await this.fetchImpl(a,{method:`GET`,headers:o});if(!s.ok){let e=await s.json().catch(()=>({message:s.statusText})),t=Error(e?.error?.message||e?.message||s.statusText);throw t.status=s.status,t}let c=await s.json();return c&&typeof c.success==`boolean`&&`data`in c?c.data:c}convertQueryParams(t){if(!t)return{};let n={};if(t.$select&&(n.select=t.$select.includes(`id`)?t.$select:[`id`,...t.$select]),t.$filter!==void 0&&t.$filter!==null&&!(Array.isArray(t.$filter)?t.$filter.length===0:typeof t.$filter==`object`&&Object.keys(t.$filter).length===0))if(Array.isArray(t.$filter))if(t.$filter.length>0&&typeof t.$filter[0]==`object`&&!Array.isArray(t.$filter[0])&&t.$filter[0].field!==void 0){let e=t.$filter.map(e=>b(e)).filter(e=>e!==null);e.length===0||(e.length===1?n.filters=e[0]:n.filters=[`and`,...e])}else n.filters=t.$filter;else n.filters=e(t.$filter);return t.$orderby&&(Array.isArray(t.$orderby)?n.sort=t.$orderby.map(e=>{if(typeof e==`string`)return e;let t=e.field;return(e.order||`asc`)===`desc`?`-${t}`:t}):n.sort=Object.entries(t.$orderby).map(([e,t])=>t===`desc`?`-${e}`:e)),t.$skip!==void 0&&(n.skip=t.$skip),t.$top!==void 0&&(n.top=t.$top),n}async getObjectSchema(e){await this.connect();try{return await this.metadataCache.get(e,async()=>{let t=await this.client.meta.getItem(`object`,e);return t&&t.item?t.item:t})}catch(t){let n=t;throw w(n)?new i(e,{originalError:t}):t instanceof r?t:l(n,`getObjectSchema(${e})`)}}getClient(){return this.client}async getDiscovery(){try{return await this.connect(),this.client.discoveryInfo||null}catch{return null}}async listViewOverrides(e){await this.connect();try{let t=`view-overrides:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItems(e),n=Array.isArray(t?.items)?t.items:[],r={};for(let e of n){if(!e||typeof e!=`object`)continue;let t=e.name??e.id??e._name;typeof t==`string`&&t&&(r[t]=e)}return r})}catch{return{}}}async getView(e,t){await this.connect();try{let n=`view:${e}:${t}`;return await this.metadataCache.get(n,async()=>{let e=await this.client.meta.getItem(`view`,t);return e&&e.item?e.item:e??null})}catch{return null}}async updateViewConfig(e,t,n){await this.connect();try{let r={...n||{},object:n?.object||e,name:t},i=await this.client.meta.saveItem(`view`,t,r),a=`view:${e}:${t}`;return this.metadataCache.invalidate?.(a),this.metadataCache.invalidate?.(`view-overrides:${e}`),this.metadataCache.invalidate?.(`views:${e}`),i&&i.item?i.item:i??void 0}catch(e){throw e}}async listViews(e){await this.connect();try{let t=await this.client.meta.getItems(`view`),n=Array.isArray(t?.items)?t.items:Array.isArray(t)?t:[],r=new Set([`form`,`detail`]);return n.filter(t=>{if(!t)return!1;let n=t.list??t;if((n?.data?.object??n?.object??n?.objectName)!==e)return!1;let i=t.viewKind??n?.viewKind;return!(i&&r.has(i))}).map(e=>{let t=e.list??e;return t&&t.config&&typeof t.config==`object`?{...t.config,name:t.name??t.config.name,label:t.label??t.config.label,isDefault:!!t.isDefault}:t})}catch(e){return console.warn(`[OBJECTSTACKDataSource] listViews failed:`,e),[]}}async createView(e,t){await this.connect();let n=String(t?.name||``).trim();if(!n){let r=String(t?.label||e||`view`).toLowerCase().replace(/[^a-z0-9_]+/g,`_`).replace(/^_+|_+$/g,``).slice(0,40);(!r||/^[0-9]/.test(r))&&(r=r?`view_${r}`:`view`);let i=Date.now().toString(36);n=`${r}_${i}`}let r={...t,name:n,object:t?.object||e,data:t?.data||{provider:`object`,object:e}};try{let t=await this.client.meta.saveItem(`view`,n,r);return this.metadataCache.invalidate?.(`views:${e}`),t&&t.item?t.item:r}catch(e){throw e}}async updateView(e,t,n){await this.connect();let r={};try{let e=await this.client.meta.getItem(`view`,t);r=e&&(e.item||e)||{},r?.list&&(r=r.list)}catch{}let i={...r,...n,name:t,object:r?.object||r?.data?.object||e};try{let n=await this.client.meta.saveItem(`view`,t,i);return this.metadataCache.invalidate?.(`views:${e}`),this.metadataCache.invalidate?.(`view:${e}:${t}`),n&&n.item?n.item:i}catch(e){throw e}}async deleteView(e,t){await this.connect();try{let n=await this.client.meta.deleteItem(`view`,t);return this.metadataCache.invalidate?.(`views:${e}`),this.metadataCache.invalidate?.(`view:${e}:${t}`),{deleted:!!(n?.deleted??n?.reset??!0)}}catch(e){throw e}}async getApp(e){await this.connect();try{let t=`app:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItem(`apps`,e);return t&&t.item?t.item:t??null})}catch{return null}}async getPage(e){await this.connect();try{let t=`page:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItem(`pages`,e);return t&&t.item?t.item:t??null})}catch{return null}}async updateDashboard(e,t){await this.connect();try{let n=await this.client.meta.saveItem(`dashboard`,e,t);return this.metadataCache.invalidate?.(`dashboards`),this.metadataCache.invalidate?.(`dashboard:${e}`),n&&n.item?n.item:n??void 0}catch(e){throw e}}async aggregate(e,t){if(await this.connect(),t!=null&&(Array.isArray(t.groupBy)||Array.isArray(t.aggregations)||t.where!==void 0)){let n={};Array.isArray(t.groupBy)&&(n.groupBy=t.groupBy),Array.isArray(t.aggregations)&&(n.aggregations=t.aggregations),t.where!==void 0&&(n.where=t.where),typeof t.limit==`number`&&(n.limit=t.limit);let r=await this.client.data.query(e,n);return Array.isArray(r)?r:Array.isArray(r?.records)?r.records:Array.isArray(r?.data)?r.data:[]}try{let n=t.function===`count`?`count`:`${t.field}_${t.function}`,r={cube:e,measures:[n],dimensions:t.groupBy&&t.groupBy!==`_all`?[t.groupBy]:[]};t.filter&&(r.where=t.filter);let i=await this.client.analytics.query(r),a=Array.isArray(i)?i:i?.rows&&Array.isArray(i.rows)?i.rows:i?.data&&Array.isArray(i.data)?i.data:i?.data?.rows&&Array.isArray(i.data.rows)?i.data.rows:i?.results&&Array.isArray(i.results)?i.results:[];if(a.length>0&&a.every(e=>e==null?!0:!(n in e&&e[n]!=null||t.field in e&&e[t.field]!=null))){let n=(await this.find(e,t.filter?{$filter:t.filter}:void 0)).data||[];return n.length===0?[]:this.aggregateClientSide(n,t)}return a.map(e=>{let r={...e};return n!==t.field&&n in r&&(r[t.field]=r[n],delete r[n]),r})}catch{let n=(await this.find(e,t.filter?{$filter:t.filter}:void 0)).data||[];return n.length===0?[]:this.aggregateClientSide(n,t)}}async queryDataset(e,t){await this.connect();let n=`${(this.baseUrl||``).replace(/\/$/,``)}/api/v1/analytics/dataset/query`,r=typeof window<`u`&&new URLSearchParams(window.location.search).get(`preview`)===`draft`,i=typeof e==`string`?{datasetName:e,selection:t,...r?{previewDrafts:!0}:{}}:{dataset:e,selection:t,...r?{previewDrafts:!0}:{}},a=await this.fetchImpl(n,{method:`POST`,headers:{"Content-Type":`application/json`,...this.token?{Authorization:`Bearer ${this.token}`}:{}},body:JSON.stringify(i)});if(!a.ok){let e=``;try{let t=await a.json();e=t?.message||t?.error||JSON.stringify(t)}catch{}throw Error(`Dataset query failed: ${a.status} ${a.statusText}${e?` — ${e}`:``}`)}let o=await a.json(),s=o&&typeof o==`object`&&`success`in o&&`data`in o?o.data:o;return{rows:Array.isArray(s?.rows)?s.rows:Array.isArray(s)?s:[],fields:Array.isArray(s?.fields)?s.fields:[]}}aggregateClientSide(e,t){let{field:n,function:r,groupBy:i}=t,a={};for(let t of e){let e=String(t[i]??`Unknown`);a[e]||(a[e]=[]),a[e].push(t)}return Object.entries(a).map(([e,t])=>{let a=t.map(e=>Number(e[n])||0),o;switch(r){case`count`:o=t.length;break;case`avg`:o=a.length>0?a.reduce((e,t)=>e+t,0)/a.length:0;break;case`min`:o=a.length>0?Math.min(...a):0;break;case`max`:o=a.length>0?Math.max(...a):0;break;default:o=a.reduce((e,t)=>e+t,0);break}return{[i]:e,[n]:o}})}async getItems(e,t){return await this.connect(),await Promise.all(t.map(async t=>{let n=`${e}:${t}`;return this.metadataCache.get(n,async()=>{let n=await this.client.meta.getItem(e,t);return n&&n.item?n.item:n})}))}getCached(e){return this.metadataCache.getCachedSync(e)}getCacheStats(){return this.metadataCache.getStats()}invalidateCache(e){this.metadataCache.invalidate(e)}clearCache(){this.metadataCache.clear()}async uploadFile(e,t,n){await this.connect();let i=new FormData;i.append(`file`,t),n?.recordId&&i.append(`recordId`,n.recordId),n?.fieldName&&i.append(`fieldName`,n.fieldName),n?.metadata&&i.append(`metadata`,JSON.stringify(n.metadata));let a=`${this.baseUrl}/api/data/${encodeURIComponent(e)}/upload`,o=await fetch(a,{method:`POST`,body:i,headers:{...this.getAuthHeaders()}});if(!o.ok)throw new r((await o.json().catch(()=>({message:o.statusText}))).message||`Upload failed with status ${o.status}`,`UPLOAD_ERROR`,o.status);return o.json()}async uploadFiles(e,t,n){await this.connect();let i=new FormData;t.forEach((e,t)=>{i.append(`files`,e,e.name||`file-${t}`)}),n?.recordId&&i.append(`recordId`,n.recordId),n?.fieldName&&i.append(`fieldName`,n.fieldName),n?.metadata&&i.append(`metadata`,JSON.stringify(n.metadata));let a=`${this.baseUrl}/api/data/${encodeURIComponent(e)}/upload`,o=await fetch(a,{method:`POST`,body:i,headers:{...this.getAuthHeaders()}});if(!o.ok)throw new r((await o.json().catch(()=>({message:o.statusText}))).message||`Upload failed with status ${o.status}`,`UPLOAD_ERROR`,o.status);return o.json()}async cancelPendingApproval(e,t){await this.connect();let n=`${this.baseUrl}/api/v1/approvals/requests?recordId=${encodeURIComponent(t)}&object=${encodeURIComponent(e)}`,i=await this.fetchImpl(n,{method:`GET`,headers:{"Content-Type":`application/json`,...this.getAuthHeaders()}});if(!i.ok)throw new r(`Failed to look up approval requests (status ${i.status})`,`APPROVAL_LOOKUP_FAILED`,i.status);let a=await i.json().catch(()=>({})),o=(Array.isArray(a)?a:a?.data??[]).find(e=>e?.status===`pending`||e?.status===`in_approval`);if(!o?.id)throw new r(`No pending approval request found for this record`,`NO_PENDING_REQUEST`,404);let s=`${this.baseUrl}/api/v1/approvals/requests/${encodeURIComponent(o.id)}/recall`,c=await this.fetchImpl(s,{method:`POST`,headers:{"Content-Type":`application/json`,...this.getAuthHeaders()},body:JSON.stringify({})});if(!c.ok){let e=await c.json().catch(()=>({}));throw new r(e?.error||e?.message||`Recall failed with status ${c.status}`,e?.code||`APPROVAL_RECALL_FAILED`,c.status)}let l=await c.json().catch(()=>({}));return{requestId:o.id,status:l?.data?.request?.status??`recalled`}}getAuthHeaders(){let e={};return this.token&&(e.Authorization=`Bearer ${this.token}`),e}};export{_ as n,f as r,k as t};
|
|
1
|
+
import{mt as e}from"./framework-DLckRGJs.js";import{s as t}from"./vendor-objectstack-BNd856rx.js";var n=class{cache;inflight;maxSize;ttl;stats;constructor(e={}){this.cache=new Map,this.inflight=new Map,this.maxSize=e.maxSize||100,this.ttl=e.ttl||300*1e3,this.stats={hits:0,misses:0,evictions:0,coalesced:0}}async get(e,t){let n=Date.now(),r=this.cache.get(e);if(r){if(n-r.timestamp<this.ttl)return r.accessCount++,r.lastAccessed=n,this.stats.hits++,this.cache.delete(e),this.cache.set(e,r),r.data;this.cache.delete(e)}let i=this.inflight.get(e);if(i)return this.stats.coalesced++,i;this.stats.misses++;let a=(async()=>{try{let n=await t();return this.set(e,n),n}finally{this.inflight.delete(e)}})();return this.inflight.set(e,a),a}prime(e,t){this.set(e,t)}set(e,t){let n=Date.now();this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictLRU(),this.cache.set(e,{data:t,timestamp:n,accessCount:1,lastAccessed:n})}evictLRU(){let e=this.cache.keys().next().value;e!==void 0&&(this.cache.delete(e),this.stats.evictions++)}invalidate(e){e?this.cache.delete(e):this.cache.clear()}clear(){this.cache.clear(),this.inflight.clear(),this.stats={hits:0,misses:0,evictions:0,coalesced:0}}getStats(){let e=this.stats.hits+this.stats.misses,t=e>0?this.stats.hits/e:0;return{size:this.cache.size,maxSize:this.maxSize,hits:this.stats.hits,misses:this.stats.misses,evictions:this.stats.evictions,coalesced:this.stats.coalesced,hitRate:t}}getCachedSync(e){let t=this.cache.get(e);if(t){if(this.ttl>0&&Date.now()-t.timestamp>this.ttl){this.cache.delete(e);return}return this.cache.delete(e),this.cache.set(e,t),this.stats.hits++,t.data}}has(e){let t=this.cache.get(e);return t?Date.now()-t.timestamp>=this.ttl?(this.cache.delete(e),!1):!0:!1}},r=class extends Error{code;statusCode;details;constructor(e,t,n,r){super(e),this.code=t,this.statusCode=n,this.details=r,this.name=`ObjectStackError`,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,details:this.details,stack:this.stack}}},i=class extends r{constructor(e,t){super(`Metadata not found for object: ${e}`,`METADATA_NOT_FOUND`,404,{objectName:e,...t}),this.name=`MetadataNotFoundError`}},a=class extends r{successCount;failureCount;errors;constructor(e,t,n,r,i){super(`Bulk ${e} operation failed: ${t} succeeded, ${n} failed`,`BULK_OPERATION_ERROR`,500,{operation:e,successCount:t,failureCount:n,errors:r,...i}),this.successCount=t,this.failureCount=n,this.errors=r,this.name=`BulkOperationError`}getSummary(){let e=this.successCount+this.failureCount,t=e>0?this.failureCount/e:0;return{operation:this.details?.operation,total:e,successful:this.successCount,failed:this.failureCount,failureRate:t,errors:this.errors}}},o=class extends r{url;constructor(e,t,n,r){super(`Connection error: ${e}`,`CONNECTION_ERROR`,r||503,{url:t,...n}),this.url=t,this.name=`ConnectionError`}},s=class extends r{constructor(e=`Authentication failed`,t,n){super(e,`AUTHENTICATION_ERROR`,n||401,t),this.name=`AuthenticationError`}},c=class extends r{field;validationErrors;constructor(e,t,n,r){super(e,`VALIDATION_ERROR`,400,{field:t,validationErrors:n,...r}),this.field=t,this.validationErrors=n,this.name=`ValidationError`}getValidationErrors(){return this.validationErrors||[]}};function l(e,t){let n=e?.status||e?.statusCode||500,a=e?.message||e?.statusText||`Unknown error`,l={context:t,response:{status:n,data:e?.data,headers:e?.headers}};switch(n){case 401:return new s(a,l,401);case 403:return new s(a,l,403);case 404:return t?.includes(`metadata`)||t?.includes(`schema`)||t?.includes(`getObjectSchema`)?new i(u(t),l):new r(a,`NOT_FOUND`,404,l);case 400:return new c(a,void 0,e?.data?.errors,l);case 503:return new o(a,e?.config?.url,l,503);case 504:return new o(a,e?.config?.url,l,504);default:return new r(a,`UNKNOWN_ERROR`,n,l)}}function u(e){if(!e)return`unknown`;let t=e.match(/\(([^)]+)\)/);return t?t[1]:`unknown`}var d=`sys_user_preference`;function f(e){let{dataSource:t,userId:n,key:r,resource:i=d,onError:a=()=>{}}=e,o=null,s=async()=>{let e={$filter:{user_id:n,key:r},$top:1};return((await t.find(i,e))?.data??[]).find(e=>{if(!e)return!1;let t=e.user_id!==void 0&&e.user_id!==n,i=e.key!==void 0&&e.key!==r;return!t&&!i})??null},c=e=>{if(Array.isArray(e))return e;if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}return[]};return{async load(){try{let e=await s();return e?(e.id!==void 0&&e.id!==null&&(o=e.id),c(e.value)):(o=null,[])}catch(e){return a(`load`,e),[]}},async save(e){try{let c=new Date().toISOString();if(o!==null)try{await t.update(i,o,{value:e,updated_at:c});return}catch(e){o=null,a(`save`,e)}let l=await s();if(l&&l.id!==void 0&&l.id!==null){o=l.id,await t.update(i,l.id,{value:e,updated_at:c});return}let u=(await t.create(i,{user_id:n,key:r,value:e,updated_at:c}))?.id;u!=null&&(o=u)}catch(e){a(`save`,e)}}}}var p=`/meta`,m=`/api/v1`;function h(e){let t=e.baseUrl.replace(/\/+$/,``),n=e.environmentId?`${m}/environments/${encodeURIComponent(e.environmentId)}${p}`:`${m}${p}`;return/\/api\/v\d+$/i.test(t)?`${t.replace(/\/api\/v\d+$/i,``)}${e.environmentId?`${m}/environments/${encodeURIComponent(e.environmentId)}${p}`:`${m}${p}`}`:`${t}${n}`}async function g(e){let t;try{t=await e.json()}catch{t=await e.text().catch(()=>void 0)}let n=(t&&typeof t==`object`&&`error`in t?String(t.error):void 0)??`Metadata request failed: ${e.status} ${e.statusText}`,r=Error(n);return r.status=e.status,r.body=t,t&&typeof t==`object`&&`code`in t&&(r.code=String(t.code)),r}var _=class e{base;fetchImpl;headers;previewDrafts;constructor(e){this.base=h(e),this.fetchImpl=e.fetch??globalThis.fetch.bind(globalThis),this.headers={Accept:`application/json`,...e.headers??{}},this.previewDrafts=e.previewDrafts===!0}withEnvironment(t){return new e({baseUrl:this.base.replace(/\/api\/v\d+(?:\/environments\/[^/]+)?\/meta$/,``).replace(/\/+$/,``),environmentId:t,fetch:this.fetchImpl,headers:this.headers,previewDrafts:this.previewDrafts})}withPreviewDrafts(t){if(t===this.previewDrafts)return this;let n=this.base.match(/\/api\/v\d+\/environments\/([^/]+)\/meta$/);return new e({baseUrl:this.base.replace(/\/api\/v\d+(?:\/environments\/[^/]+)?\/meta$/,``).replace(/\/+$/,``),...n?{environmentId:decodeURIComponent(n[1])}:{},fetch:this.fetchImpl,headers:this.headers,previewDrafts:t})}async listTypes(){let e=await this.fetchImpl(this.base,{method:`GET`,headers:this.headers,cache:`no-store`});if(!e.ok)throw await g(e);let t=await e.json();return Array.isArray(t)?t:t&&Array.isArray(t.entries)?t.entries:t&&Array.isArray(t.items)?t.items:t&&Array.isArray(t.types)?t.types.map(e=>({type:e})):[]}async list(e,t={}){let n=[];t.packageId&&n.push(`package=${encodeURIComponent(t.packageId)}`),this.previewDrafts&&n.push(`preview=draft`);let r=n.length?`?${n.join(`&`)}`:``,i=`${this.base}/${encodeURIComponent(e)}${r}`,a=await this.fetchImpl(i,{method:`GET`,headers:this.headers,cache:`no-store`});if(!a.ok)throw await g(a);let o=await a.json();return Array.isArray(o)?o:o&&Array.isArray(o.items)?o.items:[]}async listDrafts(e={}){let t=[];e.packageId&&t.push(`packageId=${encodeURIComponent(e.packageId)}`),e.type&&t.push(`type=${encodeURIComponent(e.type)}`);let n=t.length?`?${t.join(`&`)}`:``,r=`${this.base}/_drafts${n}`,i=await this.fetchImpl(r,{method:`GET`,headers:this.headers,cache:`no-store`});if(!i.ok)throw await g(i);let a=await i.json();return Array.isArray(a)?a:a?.drafts??a?.data?.drafts??[]}async get(e,t,n={}){let r=[];n.state===`draft`?r.push(`state=draft`):this.previewDrafts&&r.push(`preview=draft`),n.packageId&&r.push(`package=${encodeURIComponent(n.packageId)}`);let i=r.length?`?${r.join(`&`)}`:``,a=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}${i}`,o=await this.fetchImpl(a,{method:`GET`,headers:this.headers,cache:`no-store`});if(o.status===404)return null;if(!o.ok)throw await g(o);return await o.json()}async getDraft(e,t,n={}){return this.get(e,t,{state:`draft`,...n.packageId?{packageId:n.packageId}:{}})}async save(e,t,n,r={}){let i=[];r.force&&i.push(`force=true`),r.mode===`draft`&&i.push(`mode=draft`),r.packageId&&i.push(`package=${encodeURIComponent(r.packageId)}`);let a=i.length?`?${i.join(`&`)}`:``,o=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}${a}`,s={...this.headers,"Content-Type":`application/json`};r.ifMatch&&(s[`If-Match`]=r.ifMatch),r.actor&&(s[`X-Actor`]=r.actor);let c=await this.fetchImpl(o,{method:`PUT`,headers:s,body:JSON.stringify(n)});if(!c.ok)throw await g(c);return await c.json()}async publishDraft(e,t){let n=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/publish`,r=await this.fetchImpl(n,{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`});if(!r.ok)throw await g(r);let i=await r.json().catch(()=>({}));return i?.data&&typeof i.data==`object`?i.data:i}async layered(e,t,n={}){let r=n.packageId?`&package=${encodeURIComponent(n.packageId)}`:``,i=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}?layers=true${r}`,a=await this.fetchImpl(i,{method:`GET`,headers:this.headers,cache:`no-store`});if(a.status===404)return{code:null,overlay:null,overlayScope:null,effective:null};if(!a.ok)throw await g(a);let o=await a.json();return o&&(`code`in o||`overlay`in o||`effective`in o)?{code:o.code??null,overlay:o.overlay??null,overlayScope:o.overlayScope??null,effective:o.effective??null,...o._diagnostics?{_diagnostics:o._diagnostics}:{},...o.lock===void 0?{}:{lock:o.lock},...o.lockReason===void 0?{}:{lockReason:o.lockReason},...o.lockSource===void 0?{}:{lockSource:o.lockSource},...o.lockDocsUrl===void 0?{}:{lockDocsUrl:o.lockDocsUrl},...o.provenance===void 0?{}:{provenance:o.provenance},...o.packageId===void 0?{}:{packageId:o.packageId},...o.packageVersion===void 0?{}:{packageVersion:o.packageVersion},...o.editable===void 0?{}:{editable:o.editable},...o.deletable===void 0?{}:{deletable:o.deletable},...o.resettable===void 0?{}:{resettable:o.resettable}}:{code:null,overlay:null,overlayScope:null,effective:o}}async diagnostics(e={}){let t=[];e.type&&t.push(`type=${encodeURIComponent(e.type)}`),e.severity&&t.push(`severity=${encodeURIComponent(e.severity)}`),e.packageId&&t.push(`package=${encodeURIComponent(e.packageId)}`);let n=t.length?`?${t.join(`&`)}`:``,r=`${this.base}/diagnostics${n}`,i=await this.fetchImpl(r,{method:`GET`,headers:this.headers,cache:`no-store`});if(i.status===404)return{entries:[],total:0,scannedTypes:0,scannedItems:0,stats:{}};if(!i.ok)throw await g(i);let a=await i.json();return{entries:Array.isArray(a.entries)?a.entries:[],total:typeof a.total==`number`?a.total:0,scannedTypes:typeof a.scannedTypes==`number`?a.scannedTypes:0,scannedItems:typeof a.scannedItems==`number`?a.scannedItems:0,stats:a.stats&&typeof a.stats==`object`?a.stats:{}}}async references(e,t){let n=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/references`,r=await this.fetchImpl(n,{method:`GET`,headers:this.headers,cache:`no-store`});if(r.status===404)return[];if(!r.ok)throw await g(r);let i=await r.json();return Array.isArray(i)?i:i?.items??[]}async reset(e,t,n={}){let r=n.state===`draft`?`?state=draft`:``,i=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}${r}`,a={...this.headers};n.ifMatch&&(a[`If-Match`]=n.ifMatch),n.actor&&(a[`X-Actor`]=n.actor);let o=await this.fetchImpl(i,{method:`DELETE`,headers:a});if(!o.ok)throw await g(o);return await o.json()}async publish(e,t,n={}){let r=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/publish`,i={...this.headers,"Content-Type":`application/json`};n.actor&&(i[`X-Actor`]=n.actor);let a=await this.fetchImpl(r,{method:`POST`,headers:i,body:JSON.stringify(n.message?{message:n.message}:{})});if(!a.ok)throw await g(a);return await a.json()}async rollback(e,t,n,r={}){let i=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/rollback`,a={...this.headers,"Content-Type":`application/json`};r.actor&&(a[`X-Actor`]=r.actor);let o=await this.fetchImpl(i,{method:`POST`,headers:a,body:JSON.stringify({toVersion:n,...r.message?{message:r.message}:{}})});if(!o.ok)throw await g(o);return await o.json()}async diff(e,t,n,r){let i=new URLSearchParams;n!==void 0&&i.set(`from`,String(n)),r!==void 0&&i.set(`to`,String(r));let a=i.toString(),o=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/diff${a?`?${a}`:``}`,s=await this.fetchImpl(o,{method:`GET`,headers:this.headers,cache:`no-store`});if(!s.ok)throw await g(s);return await s.json()}async history(e,t,n={}){let r=new URLSearchParams;n.sinceSeq!==void 0&&r.set(`sinceSeq`,String(n.sinceSeq)),n.limit!==void 0&&r.set(`limit`,String(n.limit));let i=r.toString(),a=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/history${i?`?${i}`:``}`,o=await this.fetchImpl(a,{method:`GET`,headers:this.headers,cache:`no-store`});if(!o.ok)throw await g(o);return await o.json()}async audit(e,t,n={}){let r=new URLSearchParams;n.limit!==void 0&&r.set(`limit`,String(n.limit));let i=r.toString(),a=`${this.base}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/audit${i?`?${i}`:``}`,o=await this.fetchImpl(a,{method:`GET`,headers:this.headers,cache:`no-store`});if(!o.ok)throw await g(o);return await o.json()}},v={equals:`=`,eq:`=`,"==":`=`,not_equals:`!=`,notequals:`!=`,ne:`!=`,greater_than:`>`,greaterthan:`>`,gt:`>`,greater_than_or_equal:`>=`,greater_than_or_equals:`>=`,greaterthanorequal:`>=`,gte:`>=`,less_than:`<`,lessthan:`<`,lt:`<`,less_than_or_equal:`<=`,less_than_or_equals:`<=`,lessthanorequal:`<=`,lte:`<=`,in:`in`,not_in:`nin`,notin:`nin`,nin:`nin`,contains:`contains`,not_contains:`notcontains`,notcontains:`notcontains`,starts_with:`startswith`,startswith:`startswith`,ends_with:`endswith`,endswith:`endswith`,between:`between`,is_null:`isnull`,isnull:`isnull`,is_not_null:`isnotnull`,isnotnull:`isnotnull`};function y(e){return typeof e==`string`?v[e.toLowerCase()]??v[e]??e:null}function b(e){if(!e||typeof e!=`object`)return null;let t=e.field??e.name,n=y(e.operator??e.op??`=`);return!t||!n?null:[String(t),n,e.value]}function x(e){if(e!=null){if(Array.isArray(e)){if(e.length===0)return;let t=e[0];if(e.length>0&&typeof t==`object`&&t&&!Array.isArray(t)&&t.field!==void 0){let t=e.map(e=>b(e)).filter(e=>e!==null);return t.length===0?void 0:t.length===1?t[0]:[`and`,...t]}return e}if(typeof e==`object`)return Object.keys(e).length===0?void 0:e}}var S=new Map;async function C(e,t){let n=e||`<default>`,r=S.get(n);if(r)return r;let i=t().catch(e=>{throw S.delete(n),e});return S.set(n,i),i}function w(e){if(!e||typeof e!=`object`)return!1;let t=e;if(t.httpStatus===404||t.status===404||t.statusCode===404)return!0;let n=typeof t.code==`string`?t.code:``;return n===`object_not_found`||n===`record_not_found`}var T=class extends Error{code=`CONCURRENT_UPDATE`;httpStatus=409;currentVersion;currentRecord;constructor(e){super(e.message??`Record was modified by another user`),this.name=`ConcurrentUpdateError`,this.currentVersion=e.currentVersion,this.currentRecord=e.currentRecord}};function E(e){if(!e||typeof e!=`object`)return e;let t=e;if(t.code!==`CONCURRENT_UPDATE`&&t.httpStatus!==409||t.code!==`CONCURRENT_UPDATE`)return e;let n=t.details??{};return new T({currentVersion:typeof n.currentVersion==`string`?n.currentVersion:null,currentRecord:n.currentRecord??null,message:typeof t.message==`string`?t.message:void 0})}function D(){let e=e=>{if(!e||typeof e!=`object`)return!1;if(e.status===404||e.statusCode===404)return!0;let t=e.error;if(t&&typeof t==`object`){let e=t.code;if(e===`object_not_found`||e===`record_not_found`)return!0}return!1},t={debug:(e,t)=>console.debug(e,t??``),info:(e,t)=>console.info(e,t??``),warn:(e,t)=>console.warn(e,t??``),error:(t,n,r)=>{if(e(r)){console.debug(`[ObjectStack] ${t} (suppressed expected 404)`,r);return}console.error(t,n??``,r??``)},fatal:(e,t,n)=>console.error(e,t??``,n??``),log:(e,...t)=>console.log(e,...t),child:()=>t,withTrace:()=>t};return t}function O(e){if(typeof e!=`object`||!e)return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(O).join(`,`)}]`;let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${O(t[e])}`).join(`,`)}}`}var k=class{client;connected=!1;connectPromise=null;metadataCache;connectionState=`disconnected`;connectionStateListeners=[];batchProgressListeners=[];autoReconnect;maxReconnectAttempts;reconnectDelay;reconnectAttempts=0;baseUrl;token;fetchImpl;inflightFinds=new Map;missingResources=new Set;constructor(e){this.client=new t({...e,logger:D()}),this.metadataCache=new n(e.cache),this.autoReconnect=e.autoReconnect??!0,this.maxReconnectAttempts=e.maxReconnectAttempts??3,this.reconnectDelay=e.reconnectDelay??1e3,this.baseUrl=e.baseUrl,this.token=e.token,this.fetchImpl=e.fetch||globalThis.fetch.bind(globalThis)}async connect(){if(!this.connected)return this.connectPromise?this.connectPromise:(this.setConnectionState(`connecting`),this.connectPromise=(async()=>{try{let e=this.baseUrl||``,t=e?`${e.replace(/\/$/,``)}/api/v1/discovery`:`/api/v1/discovery`,n=await C(e,async()=>{let e=await this.fetchImpl(t,{method:`GET`,headers:this.token?{Authorization:`Bearer ${this.token}`}:void 0});if(!e.ok)throw Error(`discovery ${e.status} ${e.statusText}`);let n=await e.json();return n&&typeof n.success==`boolean`&&`data`in n?n.data:n});this.client.discoveryInfo=n,this.connected=!0,this.reconnectAttempts=0,this.setConnectionState(`connected`)}catch(e){let t=new o(e instanceof Error?e.message:`Failed to connect to ObjectStack server`,void 0,{originalError:e});if(this.setConnectionState(`error`,t),this.autoReconnect&&this.reconnectAttempts<this.maxReconnectAttempts)await this.attemptReconnect();else throw t}finally{this.connectPromise=null}})(),this.connectPromise)}async attemptReconnect(){this.reconnectAttempts++,this.setConnectionState(`reconnecting`);let e=this.reconnectDelay*2**(this.reconnectAttempts-1);await new Promise(t=>setTimeout(t,e)),this.connected=!1,await this.connect()}getConnectionState(){return this.connectionState}isConnected(){return this.connected&&this.connectionState===`connected`}onConnectionStateChange(e){return this.connectionStateListeners.push(e),()=>{let t=this.connectionStateListeners.indexOf(e);t>-1&&this.connectionStateListeners.splice(t,1)}}onBatchProgress(e){return this.batchProgressListeners.push(e),()=>{let t=this.batchProgressListeners.indexOf(e);t>-1&&this.batchProgressListeners.splice(t,1)}}setConnectionState(e,t){this.connectionState=e;let n={state:e,timestamp:Date.now(),error:t};this.connectionStateListeners.forEach(e=>{try{e(n)}catch(e){console.error(`Error in connection state listener:`,e)}})}emitBatchProgress(e){this.batchProgressListeners.forEach(t=>{try{t(e)}catch(e){console.error(`Error in batch progress listener:`,e)}})}async find(e,t){if(this.missingResources.has(e))return{data:[],total:0};let n=`${e}::${O(t)}`,r=this.inflightFinds.get(n);if(r)return r;let i=(async()=>{if(await this.connect(),t?.$expand&&t.$expand.length>0){let n=await this.rawFindWithPopulate(e,t);return this.normalizeQueryResult(n,t)}let n=this.convertQueryParams(t);try{let r=await this.client.data.find(e,n);return this.normalizeQueryResult(r,t)}catch(t){if(w(t))return this.missingResources.add(e),{data:[],total:0};throw t}})();this.inflightFinds.set(n,i);let a=()=>{this.inflightFinds.get(n)===i&&this.inflightFinds.delete(n)};return i.then(a,a),i}async findOne(e,t,n){if(await this.connect(),n?.$expand&&n.$expand.length>0)try{let r={...n,$filter:{id:String(t)},$top:1},i=await this.rawFindWithPopulate(e,r);if(Array.isArray(i))return i[0]||null;let a=i;return(a.records||a.value||[])[0]||null}catch(e){if(w(e))return null}try{return(await this.client.data.get(e,String(t))).record}catch(e){if(w(e))return null;throw e}}async create(e,t){return await this.connect(),(await this.client.data.create(e,t)).record}async update(e,t,n,r){await this.connect();try{return(await this.client.data.update(e,String(t),n,r?.ifMatch?{ifMatch:r.ifMatch}:void 0)).record}catch(e){throw E(e)}}async delete(e,t,n){await this.connect();try{return(await this.client.data.delete(e,String(t),n?.ifMatch?{ifMatch:n.ifMatch}:void 0)).deleted}catch(e){throw E(e)}}async bulkUpdate(e,t,n){if(await this.connect(),!t||t.length===0)return 0;let r=t.map(e=>({id:String(e),data:n})),i=this.client.data.updateMany;if(typeof i==`function`)try{let n=await i(e,r,{continueOnError:!0});return n&&typeof n==`object`&&typeof n.succeeded==`number`?n.succeeded:Array.isArray(n)?n.length:t.length}catch(e){throw E(e)}let a=0;for(let r of t)try{await this.client.data.update(e,String(r),n),a++}catch{}return a}async bulkDelete(e,t){if(await this.connect(),!t||t.length===0)return 0;let n=t.map(e=>String(e)),r=this.client.data.deleteMany;if(typeof r==`function`)try{let t=await r(e,n,{continueOnError:!0});return t&&typeof t==`object`&&typeof t.succeeded==`number`?t.succeeded:Array.isArray(t)?t.length:n.length}catch(e){throw E(e)}let i=0;for(let t of n)try{await this.client.data.delete(e,t),i++}catch{}return i}async batchTransaction(e){let t=`${this.baseUrl}/api/v1/batch`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,...this.getAuthHeaders()},body:JSON.stringify({operations:e})});if(!n.ok){let e=await n.json().catch(()=>({message:n.statusText}));throw new r(e.error||e.message||`Batch failed with status ${n.status}`,`BATCH_ERROR`,n.status)}return n.json()}async bulk(e,t,n){if(await this.connect(),!n||n.length===0)return[];let i=n.length,o=0,s=0,c=()=>{this.emitBatchProgress({operation:t,total:i,completed:o,failed:s,percentage:i>0?(o+s)/i*100:0})};try{switch(t){case`create`:{c();let t=await this.client.data.createMany(e,n);return o=t.length,s=i-o,c(),t}case`delete`:{let t=n.map(e=>e.id).filter(Boolean);if(t.length===0){let e=n.map((e,t)=>({index:t,error:`Missing ID for item at index ${t}`}));throw s=n.length,c(),new a(`delete`,0,n.length,e)}return c(),await this.client.data.deleteMany(e,t),o=t.length,s=i-o,c(),[]}case`update`:{if(typeof this.client.data.updateMany==`function`)try{c();let t=this.client.data.updateMany,r=await t(e,n);return o=r.length,s=i-o,c(),r}catch{}let t=[],r=[];for(let i=0;i<n.length;i++){let a=n[i],l=a.id;if(!l){r.push({index:i,error:`Missing ID`}),s++,c();continue}try{let n=await this.client.data.update(e,String(l),a);t.push(n.record),o++,c()}catch(e){let t=e instanceof Error?e.message:String(e);r.push({index:i,error:t}),s++,c()}}if(r.length>0)throw new a(`update`,t.length,r.length,r,{resource:e,totalRecords:n.length});return t}default:throw new r(`Unsupported bulk operation: ${t}`,`UNSUPPORTED_OPERATION`,400)}}catch(i){if(c(),i instanceof a||i instanceof r)throw i;let o=i instanceof Error?i.message:String(i),s=n.map((e,t)=>({index:t,error:o}));throw new a(t,0,n.length,s,{resource:e,originalError:i})}}normalizeQueryResult(e,t){if(Array.isArray(e))return{data:e,total:e.length,page:1,pageSize:e.length,hasMore:!1};let n=e,r=n.records||n.value||[];return{data:r,total:n.total??n.count??r.length,page:t?.$skip&&t.$top?Math.floor(t.$skip/t.$top)+1:1,pageSize:t?.$top,hasMore:t?.$top?r.length===t.$top:!1}}async rawFindWithPopulate(e,t){let n=new URLSearchParams;if(t.$expand&&t.$expand.length>0&&n.set(`populate`,t.$expand.join(`,`)),t.$top!==void 0&&n.set(`top`,String(t.$top)),t.$skip!==void 0&&n.set(`skip`,String(t.$skip)),t.$select&&t.$select.length>0){let e=t.$select.includes(`id`)?t.$select:[`id`,...t.$select];n.set(`select`,e.join(`,`))}if(t.$orderby)if(Array.isArray(t.$orderby)){let e=t.$orderby.map(e=>{if(typeof e==`string`)return e;let t=e.field;return(e.order||`asc`)===`desc`?`-${t}`:t}).join(`,`);n.set(`sort`,e)}else{let e=Object.entries(t.$orderby).map(([e,t])=>t===`desc`?`-${e}`:e).join(`,`);n.set(`sort`,e)}if(t.$filter!==void 0&&t.$filter!==null){let e=x(t.$filter);e!==void 0&&n.set(`filter`,JSON.stringify(e))}let r=this.baseUrl.replace(/\/$/,``),i=n.toString(),a=`${r}${/\/api\/v\d+$/i.test(r)?`/data`:`/api/v1/data`}/${e}${i?`?${i}`:``}`,o={"Content-Type":`application/json`};this.token&&(o.Authorization=`Bearer ${this.token}`);let s=await this.fetchImpl(a,{method:`GET`,headers:o});if(!s.ok){let e=await s.json().catch(()=>({message:s.statusText})),t=Error(e?.error?.message||e?.message||s.statusText);throw t.status=s.status,t}let c=await s.json();return c&&typeof c.success==`boolean`&&`data`in c?c.data:c}convertQueryParams(t){if(!t)return{};let n={};if(t.$select&&(n.select=t.$select.includes(`id`)?t.$select:[`id`,...t.$select]),t.$filter!==void 0&&t.$filter!==null&&!(Array.isArray(t.$filter)?t.$filter.length===0:typeof t.$filter==`object`&&Object.keys(t.$filter).length===0))if(Array.isArray(t.$filter))if(t.$filter.length>0&&typeof t.$filter[0]==`object`&&!Array.isArray(t.$filter[0])&&t.$filter[0].field!==void 0){let e=t.$filter.map(e=>b(e)).filter(e=>e!==null);e.length===0||(e.length===1?n.filters=e[0]:n.filters=[`and`,...e])}else n.filters=t.$filter;else n.filters=e(t.$filter);return t.$orderby&&(Array.isArray(t.$orderby)?n.sort=t.$orderby.map(e=>{if(typeof e==`string`)return e;let t=e.field;return(e.order||`asc`)===`desc`?`-${t}`:t}):n.sort=Object.entries(t.$orderby).map(([e,t])=>t===`desc`?`-${e}`:e)),t.$skip!==void 0&&(n.skip=t.$skip),t.$top!==void 0&&(n.top=t.$top),n}async getObjectSchema(e){await this.connect();try{return await this.metadataCache.get(e,async()=>{let t=await this.client.meta.getItem(`object`,e);return t&&t.item?t.item:t})}catch(t){let n=t;throw w(n)?new i(e,{originalError:t}):t instanceof r?t:l(n,`getObjectSchema(${e})`)}}getClient(){return this.client}async getDiscovery(){try{return await this.connect(),this.client.discoveryInfo||null}catch{return null}}async listViewOverrides(e){await this.connect();try{let t=`view-overrides:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItems(e),n=Array.isArray(t?.items)?t.items:[],r={};for(let e of n){if(!e||typeof e!=`object`)continue;let t=e.name??e.id??e._name;typeof t==`string`&&t&&(r[t]=e)}return r})}catch{return{}}}async getView(e,t){await this.connect();try{let n=`view:${e}:${t}`;return await this.metadataCache.get(n,async()=>{let e=await this.client.meta.getItem(`view`,t);return e&&e.item?e.item:e??null})}catch{return null}}async updateViewConfig(e,t,n){await this.connect();try{let r={...n||{},object:n?.object||e,name:t},i=await this.client.meta.saveItem(`view`,t,r),a=`view:${e}:${t}`;return this.metadataCache.invalidate?.(a),this.metadataCache.invalidate?.(`view-overrides:${e}`),this.metadataCache.invalidate?.(`views:${e}`),i&&i.item?i.item:i??void 0}catch(e){throw e}}async listViews(e){await this.connect();try{let t=await this.client.meta.getItems(`view`),n=Array.isArray(t?.items)?t.items:Array.isArray(t)?t:[],r=new Set([`form`,`detail`]);return n.filter(t=>{if(!t)return!1;let n=t.list??t;if((n?.data?.object??n?.object??n?.objectName)!==e)return!1;let i=t.viewKind??n?.viewKind;return!(i&&r.has(i))}).map(e=>{let t=e.list??e;return t&&t.config&&typeof t.config==`object`?{...t.config,name:t.name??t.config.name,label:t.label??t.config.label,isDefault:!!t.isDefault}:t})}catch(e){return console.warn(`[OBJECTSTACKDataSource] listViews failed:`,e),[]}}async createView(e,t){await this.connect();let n=String(t?.name||``).trim();if(!n){let r=String(t?.label||e||`view`).toLowerCase().replace(/[^a-z0-9_]+/g,`_`).replace(/^_+|_+$/g,``).slice(0,40);(!r||/^[0-9]/.test(r))&&(r=r?`view_${r}`:`view`);let i=Date.now().toString(36);n=`${r}_${i}`}let r={...t,name:n,object:t?.object||e,data:t?.data||{provider:`object`,object:e}};try{let t=await this.client.meta.saveItem(`view`,n,r);return this.metadataCache.invalidate?.(`views:${e}`),t&&t.item?t.item:r}catch(e){throw e}}async updateView(e,t,n){await this.connect();let r={};try{let e=await this.client.meta.getItem(`view`,t);r=e&&(e.item||e)||{},r?.list&&(r=r.list)}catch{}let i={...r,...n,name:t,object:r?.object||r?.data?.object||e};try{let n=await this.client.meta.saveItem(`view`,t,i);return this.metadataCache.invalidate?.(`views:${e}`),this.metadataCache.invalidate?.(`view:${e}:${t}`),n&&n.item?n.item:i}catch(e){throw e}}async deleteView(e,t){await this.connect();try{let n=await this.client.meta.deleteItem(`view`,t);return this.metadataCache.invalidate?.(`views:${e}`),this.metadataCache.invalidate?.(`view:${e}:${t}`),{deleted:!!(n?.deleted??n?.reset??!0)}}catch(e){throw e}}async getApp(e){await this.connect();try{let t=`app:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItem(`apps`,e);return t&&t.item?t.item:t??null})}catch{return null}}async getPage(e){await this.connect();try{let t=`page:${e}`;return await this.metadataCache.get(t,async()=>{let t=await this.client.meta.getItem(`pages`,e);return t&&t.item?t.item:t??null})}catch{return null}}async updateDashboard(e,t){await this.connect();try{let n=await this.client.meta.saveItem(`dashboard`,e,t);return this.metadataCache.invalidate?.(`dashboards`),this.metadataCache.invalidate?.(`dashboard:${e}`),n&&n.item?n.item:n??void 0}catch(e){throw e}}async aggregate(e,t){if(await this.connect(),t!=null&&(Array.isArray(t.groupBy)||Array.isArray(t.aggregations)||t.where!==void 0)){let n={};Array.isArray(t.groupBy)&&(n.groupBy=t.groupBy),Array.isArray(t.aggregations)&&(n.aggregations=t.aggregations),t.where!==void 0&&(n.where=t.where),typeof t.limit==`number`&&(n.limit=t.limit);let r=await this.client.data.query(e,n);return Array.isArray(r)?r:Array.isArray(r?.records)?r.records:Array.isArray(r?.data)?r.data:[]}try{let n=t.function===`count`?`count`:`${t.field}_${t.function}`,r={cube:e,measures:[n],dimensions:t.groupBy&&t.groupBy!==`_all`?[t.groupBy]:[]};t.filter&&(r.where=t.filter);let i=await this.client.analytics.query(r),a=Array.isArray(i)?i:i?.rows&&Array.isArray(i.rows)?i.rows:i?.data&&Array.isArray(i.data)?i.data:i?.data?.rows&&Array.isArray(i.data.rows)?i.data.rows:i?.results&&Array.isArray(i.results)?i.results:[];if(a.length>0&&a.every(e=>e==null?!0:!(n in e&&e[n]!=null||t.field in e&&e[t.field]!=null))){let n=(await this.find(e,t.filter?{$filter:t.filter}:void 0)).data||[];return n.length===0?[]:this.aggregateClientSide(n,t)}return a.map(e=>{let r={...e};return n!==t.field&&n in r&&(r[t.field]=r[n],delete r[n]),r})}catch{let n=(await this.find(e,t.filter?{$filter:t.filter}:void 0)).data||[];return n.length===0?[]:this.aggregateClientSide(n,t)}}async queryDataset(e,t){await this.connect();let n=`${(this.baseUrl||``).replace(/\/$/,``)}/api/v1/analytics/dataset/query`,r=typeof window<`u`&&new URLSearchParams(window.location.search).get(`preview`)===`draft`,i=typeof e==`string`?{datasetName:e,selection:t,...r?{previewDrafts:!0}:{}}:{dataset:e,selection:t,...r?{previewDrafts:!0}:{}},a=await this.fetchImpl(n,{method:`POST`,headers:{"Content-Type":`application/json`,...this.token?{Authorization:`Bearer ${this.token}`}:{}},body:JSON.stringify(i)});if(!a.ok){let e=``;try{let t=await a.json();e=t?.message||t?.error||JSON.stringify(t)}catch{}throw Error(`Dataset query failed: ${a.status} ${a.statusText}${e?` — ${e}`:``}`)}let o=await a.json(),s=o&&typeof o==`object`&&`success`in o&&`data`in o?o.data:o;return{rows:Array.isArray(s?.rows)?s.rows:Array.isArray(s)?s:[],fields:Array.isArray(s?.fields)?s.fields:[]}}aggregateClientSide(e,t){let{field:n,function:r,groupBy:i}=t,a={};for(let t of e){let e=String(t[i]??`Unknown`);a[e]||(a[e]=[]),a[e].push(t)}return Object.entries(a).map(([e,t])=>{let a=t.map(e=>Number(e[n])||0),o;switch(r){case`count`:o=t.length;break;case`avg`:o=a.length>0?a.reduce((e,t)=>e+t,0)/a.length:0;break;case`min`:o=a.length>0?Math.min(...a):0;break;case`max`:o=a.length>0?Math.max(...a):0;break;default:o=a.reduce((e,t)=>e+t,0);break}return{[i]:e,[n]:o}})}async getItems(e,t){return await this.connect(),await Promise.all(t.map(async t=>{let n=`${e}:${t}`;return this.metadataCache.get(n,async()=>{let n=await this.client.meta.getItem(e,t);return n&&n.item?n.item:n})}))}getCached(e){return this.metadataCache.getCachedSync(e)}getCacheStats(){return this.metadataCache.getStats()}invalidateCache(e){this.metadataCache.invalidate(e)}clearCache(){this.metadataCache.clear()}async uploadFile(e,t,n){await this.connect();let i=new FormData;i.append(`file`,t),n?.recordId&&i.append(`recordId`,n.recordId),n?.fieldName&&i.append(`fieldName`,n.fieldName),n?.metadata&&i.append(`metadata`,JSON.stringify(n.metadata));let a=`${this.baseUrl}/api/data/${encodeURIComponent(e)}/upload`,o=await fetch(a,{method:`POST`,body:i,headers:{...this.getAuthHeaders()}});if(!o.ok)throw new r((await o.json().catch(()=>({message:o.statusText}))).message||`Upload failed with status ${o.status}`,`UPLOAD_ERROR`,o.status);return o.json()}async uploadFiles(e,t,n){await this.connect();let i=new FormData;t.forEach((e,t)=>{i.append(`files`,e,e.name||`file-${t}`)}),n?.recordId&&i.append(`recordId`,n.recordId),n?.fieldName&&i.append(`fieldName`,n.fieldName),n?.metadata&&i.append(`metadata`,JSON.stringify(n.metadata));let a=`${this.baseUrl}/api/data/${encodeURIComponent(e)}/upload`,o=await fetch(a,{method:`POST`,body:i,headers:{...this.getAuthHeaders()}});if(!o.ok)throw new r((await o.json().catch(()=>({message:o.statusText}))).message||`Upload failed with status ${o.status}`,`UPLOAD_ERROR`,o.status);return o.json()}async cancelPendingApproval(e,t){await this.connect();let n=`${this.baseUrl}/api/v1/approvals/requests?recordId=${encodeURIComponent(t)}&object=${encodeURIComponent(e)}`,i=await this.fetchImpl(n,{method:`GET`,headers:{"Content-Type":`application/json`,...this.getAuthHeaders()}});if(!i.ok)throw new r(`Failed to look up approval requests (status ${i.status})`,`APPROVAL_LOOKUP_FAILED`,i.status);let a=await i.json().catch(()=>({})),o=(Array.isArray(a)?a:a?.data??[]).find(e=>e?.status===`pending`||e?.status===`in_approval`);if(!o?.id)throw new r(`No pending approval request found for this record`,`NO_PENDING_REQUEST`,404);let s=`${this.baseUrl}/api/v1/approvals/requests/${encodeURIComponent(o.id)}/recall`,c=await this.fetchImpl(s,{method:`POST`,headers:{"Content-Type":`application/json`,...this.getAuthHeaders()},body:JSON.stringify({})});if(!c.ok){let e=await c.json().catch(()=>({}));throw new r(e?.error||e?.message||`Recall failed with status ${c.status}`,e?.code||`APPROVAL_RECALL_FAILED`,c.status)}let l=await c.json().catch(()=>({}));return{requestId:o.id,status:l?.data?.request?.status??`recalled`}}getAuthHeaders(){let e={};return this.token&&(e.Authorization=`Bearer ${this.token}`),e}};export{_ as n,f as r,k as t};
|