@nocobase/client 2.0.39 → 2.0.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/es/index.mjs +952 -948
  2. package/lib/index.js +2 -2
  3. package/package.json +6 -6
package/lib/index.js CHANGED
@@ -62,7 +62,7 @@
62
62
  width: 100%;
63
63
  }
64
64
  }
65
- `,items:a},n))})},SchemaInitializerSubMenu=e=>{var t;const o=e,{children:r,items:i,title:n,name:l,onOpenChange:a,icon:c}=o,u=te(o,["children","items","title","name","onOpenChange","icon"]),d=useCompile(),m=useSchemaInitializerItem(),p=(0,import_react2.useMemo)(()=>l||(m==null?void 0:m.name)||(0,import_shared.uid)(),[l,m]),h=(t=i||r)==null?void 0:t.filter(_=>_.useVisible?_.useVisible():!0),g=useSchemaInitializerMenuItems(h,l),f=(0,import_react2.useMemo)(()=>[I(x({},u),{key:p,label:d(n),icon:typeof c=="string"?(0,import_jsx_runtime.jsx)(import_icons.default,{type:c}):c,children:g})],[g,d,c,p,u,n]);return(0,import_jsx_runtime.jsx)(SchemaInitializerMenu,{onOpenChange:a,items:f})},SchemaInitializerSubMenuInternal=()=>{const e=useSchemaInitializerItem();return(0,import_jsx_runtime.jsx)(SchemaInitializerSubMenu,x({},e))},useAriaAttributeOfMenuItem=()=>{const{isInMenu:e}=useSchemaInitializerSubMenuContext();return{attribute:(0,import_react2.useMemo)(()=>e?{}:{role:"menuitem"},[e])}},{Paragraph:Paragraph$1,Text:Text$2}=import_antd.Typography,ErrorFallbackModal=e=>{const[t,o]=import_react2.default.useState(!1),r=(0,import_jsx_runtime.jsx)(Paragraph$1,{style:{display:"flex",marginBottom:0},copyable:{text:e.error.message},children:(0,import_jsx_runtime.jsxs)(Text$2,{type:"danger",style:{whiteSpace:"nowrap",textOverflow:"ellipsis",overflow:"hidden",display:"inline-block",maxWidth:"200px"},children:["Error: ",e.error.message]})});return(0,import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment,{children:[(0,import_jsx_runtime.jsx)("div",{onMouseOver:()=>o(!0),children:e.children||r}),(0,import_jsx_runtime.jsx)(import_antd.Modal,{zIndex:1e4,open:t,footer:null,onCancel:()=>o(!1),width:"60%",children:(0,import_jsx_runtime.jsx)(ErrorFallback,x({},e))})]})},{Paragraph,Text:Text$1,Link}=import_antd.Typography,useDownloadLogs=(e,t={})=>{const o=useLocationNoUpdate(),[r,i]=import_react2.default.useState(!1),n=useAPIClient();return{loading:r,download:()=>L(void 0,null,function*(){i(!0);try{const l=yield n.request({url:"logger:collect",method:"post",responseType:"blob",data:x({error:{message:e.message,stack:e.stack},location:o},t)}),a=window.URL.createObjectURL(new Blob([l.data],{type:"application/gzip"})),c=document.createElement("a");c.setAttribute("href",a),c.setAttribute("download","logs.tar.gz"),c.click(),c.remove()}catch(l){console.log(l)}i(!1)})}},ErrorFallback=({error:e})=>{const t=(0,import_react.useFieldSchema)(),{t:o}=(0,import_react_i18next.useTranslation)(),{loading:r,download:i}=useDownloadLogs(e,{schema:t}),n=(0,import_jsx_runtime.jsxs)(import_react_i18next.Trans,{children:["This is likely a NocoBase internals bug. Please open an issue at ",(0,import_jsx_runtime.jsx)(Link,{href:"https://github.com/nocobase/nocobase/issues",target:"_blank",children:"here"})]});return(0,import_jsx_runtime.jsx)("div",{style:{backgroundColor:"white"},children:(0,import_jsx_runtime.jsx)(import_antd.Result,{style:{maxWidth:"60vw",margin:"auto"},status:"error",title:o("Render Failed"),subTitle:n,extra:[(0,import_jsx_runtime.jsx)(import_antd.Button,{type:"primary",href:"https://github.com/nocobase/nocobase/issues",target:"_blank",children:o("Feedback")},"feedback"),(0,import_jsx_runtime.jsx)(import_antd.Button,{loading:r,onClick:i,children:o("Download logs")},"log")],children:(0,import_jsx_runtime.jsx)(Paragraph,{copyable:{text:e.stack},children:(0,import_jsx_runtime.jsx)(Text$1,{type:"danger",style:{whiteSpace:"pre-line",textAlign:"center"},children:e.stack})})})})};ErrorFallback.Modal=ErrorFallbackModal;const AppNotFound=()=>{const e=(0,import_react_router_dom.useNavigate)(),{t}=(0,import_react_i18next.useTranslation)();return(0,import_jsx_runtime.jsx)(import_antd.Result,{status:"404",title:"404",subTitle:t("Sorry, the page you visited does not exist."),extra:(0,import_jsx_runtime.jsx)(import_antd.Button,{onClick:()=>e("/",{replace:!0}),type:"primary",children:"Back Home"})})};class Plugin{constructor(t,o){this.options=t,this.app=o,this.options=t,this.app=o}get pluginManager(){return this.app.pluginManager}get context(){return this.app.context}get flowEngine(){return this.app.flowEngine}get engine(){return this.app.flowEngine}get ai(){return this.app.aiManager}get pm(){return this.app.pm}get router(){return this.app.router}get pluginSettingsManager(){return this.app.pluginSettingsManager}get pluginSettingsRouter(){return this.app.pluginSettingsManager}get schemaInitializerManager(){return this.app.schemaInitializerManager}get schemaSettingsManager(){return this.app.schemaSettingsManager}get dataSourceManager(){return this.app.dataSourceManager}afterAdd(){return L(this,null,function*(){})}beforeLoad(){return L(this,null,function*(){})}load(){return L(this,null,function*(){})}t(t,o={}){var r;return this.app.i18n.t(t,x({ns:(r=this.options)==null?void 0:r.packageName},o))}}const titleWrapperStyle={display:"flex",alignItems:"center",gap:4},withTooltipComponent=e=>t=>{const{tooltip:o}=t;return o?(0,import_jsx_runtime.jsxs)("div",{style:titleWrapperStyle,children:[(0,import_jsx_runtime.jsx)(e,x({},t)),(0,import_jsx_runtime.jsx)(import_antd.Tooltip,{title:o,children:(0,import_jsx_runtime.jsx)(import_icons.QuestionCircleOutlined,{style:{zIndex:1}})})]}):(0,import_jsx_runtime.jsx)(e,x({},t))},{evaluate}=import_client4.evaluators.get("formula.js"),useEvaluatedExpression=e=>{const t=useVariables$1(),o=useLocalVariables$1(),[r,i]=(0,import_react2.useState)();return(0,import_react2.useEffect)(()=>{L(void 0,null,function*(){if(e==null||e===""){i(void 0);return}const{exp:n,scope:l}=yield replaceVariables(e,{variables:t,localVariables:o});try{const a=evaluate(n,x({now:()=>new Date().toString()},l));i(a)}catch(a){console.error(a)}})},[t.parseVariable,e,o]),r};class SchemaInitializer{constructor(t){R(this,"options"),R(this,"name"),this.options=Object.assign({items:[]},t),this.name=t.name}get items(){return this.options.items}add(t,o){const r=t.split("."),i=r[r.length-1],n=I(x({},o),{name:i}),l=(u,d)=>{const m=this.items.findIndex(p=>p.name===u);m===-1?this.items.push(d):this.items[m]=d};if(r.length===1){l(i,n);return}const a=r.slice(0,-1).join("."),c=this.get(a);if(c){c.children||(c.children=[]);const u=t.replace(`${c.name}.`,""),d=c.children.findIndex(m=>m.name===u);d===-1?c.children.push(n):c.children[d]=n}else l(i,n)}get(t){var o;if(!t)return;const r=t.split(".");let i={children:this.items};for(let n=0;n<r.length;n++){const l=r[n],a=(o=i.children)==null?void 0:o.find(c=>c.name===l);if(a&&(i=a),n===r.length-1)return a}}remove(t){const o=t.split(".");if(o.length===1){const i=this.items.findIndex(n=>n.name===o[0]);i!==-1&&this.items.splice(i,1);return}const r=this.get(o.slice(0,-1).join("."));if(r&&r.children){const i=o[o.length-1],n=r.children.findIndex(l=>l.name===i);n!==-1&&r.children.splice(n,1)}}}var NocoBaseDesktopRouteType=(e=>(e.group="group",e.page="page",e.flowRoute="flowRoute",e.link="link",e.tabs="tabs",e.flowPage="flowPage",e))(NocoBaseDesktopRouteType||{});const useStyles$h=genStyleHook("nb-menu-item",e=>{const{componentCls:t}=e;return{[t]:{paddingLeft:`${e.padding}px !important`,paddingRight:`${e.padding}px !important`}}}),useInsertFlowPageSchema=()=>{const e=useAPIClient();return(0,import_react2.useCallback)(t=>L(void 0,null,function*(){yield e.request({method:"POST",url:"/uiSchemas:insert",data:t})}),[e])},FlowPageMenuItem=()=>{const{t:e}=(0,import_react_i18next.useTranslation)(),t=(0,import_react2.useContext)(import_react.SchemaOptionsContext),{theme:o}=useGlobalTheme(),{componentCls:r,hashId:i}=useStyles$h(),n=useParentRoute(),{createRoute:l}=useNocoBaseRoutes(),a=useInsertFlowPageSchema(),c=(0,import_react2.useCallback)(()=>L(void 0,null,function*(){const u=yield FormDialog(e("Add page"),()=>(0,import_jsx_runtime.jsx)(SchemaComponentOptions,{scope:t.scope,components:x({},t.components),children:(0,import_jsx_runtime.jsx)(import_antd_v5.FormLayout,{layout:"vertical",children:(0,import_jsx_runtime.jsx)(zIndexContext.Provider,{value:ICON_POPUP_Z_INDEX,children:(0,import_jsx_runtime.jsx)(SchemaComponent,{schema:{properties:{title:{title:e("Menu item title"),required:!0,"x-component":"Input","x-decorator":"FormItem"},icon:{title:e("Icon"),"x-component":"IconPicker","x-decorator":"FormItem"}}}})})})}),o).open({initialValues:{}}),d=(0,import_shared.uid)(),m=(0,import_shared.uid)(),p=(0,import_shared.uid)(),h=(0,import_shared.uid)();yield l({type:NocoBaseDesktopRouteType.flowPage,title:u.title,icon:u.icon,parentId:n==null?void 0:n.id,schemaUid:m,menuSchemaUid:d,enableTabs:!1,children:[{type:NocoBaseDesktopRouteType.tabs,schemaUid:p,tabSchemaName:h,hidden:!0}]}),a(getFlowPageMenuSchema({pageSchemaUid:m}))}),[l,a,t==null?void 0:t.components,t==null?void 0:t.scope,n==null?void 0:n.id,e,o]);return(0,import_jsx_runtime.jsx)(SchemaInitializerItem,{title:e("Modern page (v2)"),onClick:c,className:`${r} ${i}`})};function getFlowPageMenuSchema({pageSchemaUid:e}){return{type:"void","x-component":"FlowRoute","x-uid":e}}const GroupItem$1=()=>{const{t:e}=(0,import_react_i18next.useTranslation)(),t=(0,import_react2.useContext)(import_react.SchemaOptionsContext),{theme:o}=useGlobalTheme(),{componentCls:r,hashId:i}=useStyles$h(),n=useParentRoute(),{createRoute:l}=useNocoBaseRoutes(),a=(0,import_react2.useCallback)(()=>L(void 0,null,function*(){const c=yield FormDialog(e("Add group"),()=>(0,import_jsx_runtime.jsx)(SchemaComponentOptions,{scope:t.scope,components:x({},t.components),children:(0,import_jsx_runtime.jsx)(import_antd_v5.FormLayout,{layout:"vertical",children:(0,import_jsx_runtime.jsx)(zIndexContext.Provider,{value:ICON_POPUP_Z_INDEX,children:(0,import_jsx_runtime.jsx)(SchemaComponent,{schema:{properties:{title:{title:e("Menu item title"),"x-component":"Input","x-decorator":"FormItem",required:!0},icon:{title:e("Icon"),"x-component":"IconPicker","x-decorator":"FormItem"}}}})})})}),o).open({initialValues:{}}),{title:u,icon:d}=c,m=(0,import_shared.uid)();yield l({type:NocoBaseDesktopRouteType.group,title:u,icon:d,parentId:n==null?void 0:n.id,schemaUid:m})}),[t.components,t.scope,e,o]);return(0,import_jsx_runtime.jsx)(SchemaInitializerItem,{title:e("Group"),onClick:a,className:`${r} ${i}`})},useAttach=e=>{const t=(0,import_react2.useRef)(null);return(0,import_react2.useEffect)(()=>(t.current&&e!==t.current&&t.current.onUnmount(),t.current=e,e.onMount(),()=>{e.onUnmount()}),[e]),e},compileCache={},hasVariable=e=>/{{.*?}}/g.test(e),useCompile=({noCache:e}={noCache:!1})=>{const t=(0,import_react2.useContext)(import_react.SchemaOptionsContext),o=(0,import_react2.useContext)(import_react.SchemaExpressionScopeContext);return(r,i)=>{let n=!1,l;if(typeof r=="string"&&r.startsWith("{{")&&(n=!0,l=r),r&&typeof r=="object"&&!(0,import_react2.isValidElement)(r)){try{l=JSON.stringify(r)}catch(a){return console.warn("Failed to stringify:",a),r}if(compileCache[l])return compileCache[l];n=hasVariable(l)}if(Array.isArray(r)){try{l=JSON.stringify(r)}catch(a){return console.warn("Failed to stringify:",a),r}if(compileCache[l])return compileCache[l];n=hasVariable(l)}if(n){const a=x(x(x({},t==null?void 0:t.scope),o),i);if(!l)return import_react.Schema.compile(r,a);try{return e?import_react.Schema.compile(r,a):(compileCache[l]=compileCache[l]||import_react.Schema.compile(r,a),compileCache[l])}catch(c){return console.log("useCompile error",r,c),import_react.Schema.compile(r,a)}}return r}},useComponent=(e,t)=>{const{components:o}=(0,import_react2.useContext)(import_react.SchemaOptionsContext);return e?typeof e!="string"?e:(0,import_lodash.get)(o,e)||t:t},LAZY_COMPONENT_KEY=Symbol("LAZY_COMPONENT_KEY");function lazy(e,...t){if(t.length===0){const o=(0,import_react2.lazy)(()=>e().then(i=>{const n=i.default;return r[LAZY_COMPONENT_KEY]=n,{default:n}})),r=i=>(0,import_jsx_runtime.jsx)(import_react2.default.Suspense,{fallback:(0,import_jsx_runtime.jsx)(import_antd.Spin,{}),children:(0,import_jsx_runtime.jsx)(o,x({},i))});return r}return t.reduce((o,r)=>{const i=(0,import_react2.lazy)(()=>e().then(n=>{const l=(0,import_lodash.get)(n,r);return o[r][LAZY_COMPONENT_KEY]=l,{default:l}}));return o[r]=n=>(0,import_jsx_runtime.jsx)(import_react2.default.Suspense,{fallback:(0,import_jsx_runtime.jsx)(import_antd.Spin,{}),children:(0,import_jsx_runtime.jsx)(i,x({},n))}),o},{})}function useLazy(e,t){const o=typeof t=="function"?t:i=>i[t],r=(0,import_react_imported_component.loadableResource)(e);if(!r.payload)throw new Promise((i,n)=>{r.loadIfNeeded(),r.resolution.then(i).catch(n)});return o(r.payload)}function addAppVersion(e,t){if(e)return e["x-app-version"]||(e["x-app-version"]=t),Object.keys(e.properties||{}).forEach(o=>{var r;addAppVersion((r=e.properties)==null?void 0:r[o],t)}),e}const name="@nocobase/client",version="2.0.39",license="Apache-2.0",main="lib/index.js",module$1="es/index.mjs",types="es/index.d.ts",dependencies={"@ahooksjs/use-url-state":"3.5.1","@ant-design/cssinjs":"^1.11.1","@ant-design/icons":"^5.6.1","@ant-design/pro-layout":"^7.22.1","@antv/g2plot":"^2.4.18","@budibase/handlebars-helpers":"0.14.0","@codemirror/lang-html":"^6.4.10","@codemirror/theme-one-dark":"^6.1.3","@ctrl/tinycolor":"^3.6.0","@dnd-kit/core":"^6.0.0","@dnd-kit/sortable":"^7.0.0","@emotion/css":"^11.7.1","@formily/antd-v5":"1.2.3","@formily/core":"^2.2.27","@formily/grid":"^2.2.27","@formily/json-schema":"^2.2.27","@formily/path":"^2.2.27","@formily/react":"^2.2.27","@formily/reactive":"^2.2.27","@formily/reactive-react":"^2.2.27","@formily/shared":"^2.2.27","@formily/validator":"^2.2.27","@nocobase/evaluators":"2.0.39","@nocobase/flow-engine":"2.0.39","@nocobase/sdk":"2.0.39","@nocobase/utils":"2.0.39","@tanstack/react-table":"^8.21.3","@types/tabulator-tables":"^6.2.6","acorn-jsx":"^5.3.2",ahooks:"^3.7.2",antd:"5.24.2","antd-mobile":"^5.41.1","antd-mobile-icons":"^0.3.0","antd-style":"3.7.1",axios:"^1.7.0","bignumber.js":"^9.1.2",classnames:"^2.3.1",codemirror:"^6.0.2",cronstrue:"^2.11.0","file-saver":"^2.0.5",filesize:"9.0.11",flat:"^5.0.2","html5-qrcode":"^2.3.8",i18next:"^22.4.9","i18next-http-backend":"^2.1.1",ignore:"^5.2.0",json5:"^2.2.3",liquidjs:"^10.0.0",lodash:"^4.17.21","lru-cache":"6.0.0","markdown-it":"14.1.0","markdown-it-highlightjs":"3.3.1",mathjs:"^15.1.0",mermaid:"9.4.3",mime:"^4.0.4","mime-match":"^1.0.2","quill-image-resize-module-react":"^3.0.0","react-beautiful-dnd":"^13.1.0","react-device-detect":"2.2.3","react-drag-listview":"^0.1.9","react-error-boundary":"^4.0.10","react-helmet":"^6.1.0","react-hotkeys-hook":"^3.4.7","react-i18next":"^11.15.1","react-iframe":"~1.8.5","react-image-lightbox":"^5.1.4","react-intersection-observer":"9.14.0","react-js-cron":"^3.1.0","react-quill":"^2.0.0","react-router-dom":"^6.30.1","react-to-print":"^2.14.7","sanitize-html":"2.13.0","tabulator-tables":"^6.3.1","use-deep-compare-effect":"^1.8.1",vditor:"^3.10.3"},peerDependencies={react:">=18.0.0","react-dom":">=18.0.0","react-is":">=18.0.0"},devDependencies={"@testing-library/react":"^14.0.0","@types/markdown-it":"14.1.1","@types/markdown-it-highlightjs":"3.3.1","@types/react-big-calendar":"^1.6.4","axios-mock-adapter":"^1.20.0",dumi:"2.2.14","dumi-theme-nocobase":"^0.2.32"},clientPkg={name,version,license,main,module:module$1,types,dependencies,peerDependencies,devDependencies};function createDesignable(e){return new Designable(e)}const generateUid=e=>{e&&(e["x-uid"]||(e["x-uid"]=(0,import_shared.uid)()),Object.keys(e.properties||{}).forEach(t=>{generateUid(e.properties[t])}))},defaultWrap=e=>e,matchSchema=(e,t)=>{if(!(!e||!t)){for(const o in t)if(Object.prototype.hasOwnProperty.call(t,o)&&t[o]!==(e==null?void 0:e[o]))return!1;return!0}},splitWrapSchema=(e,t)=>{if(e["x-uid"]&&e["x-uid"]===t["x-uid"])return[null,e.toJSON()];const o=e.toJSON(),r=I(x({},o),{properties:{}});let i=null;const n=(l,a)=>{Object.keys(l||{}).forEach(c=>{const u=l[c];if(u["x-uid"]===t["x-uid"]){i=l[c];return}else a.properties[c]=I(x({},u),{properties:{}}),n(u==null?void 0:u.properties,a.properties[c])})};return n(o.properties,r),[r,i]},translate=e=>e;class Designable{constructor(t){R(this,"current"),R(this,"options"),R(this,"appVersion"),R(this,"events",{}),this.options=t,this.current=t.current,this.appVersion=t.appVersion}get model(){return this.options.model}get query(){return this.options.query}loadAPIClientEvents(){const{api:t,t:o=translate}=this.options;if(!t)return;const r=i=>{if(!i)return[];const n=Object.values(i.properties).length,l=[];return i.mapProperties(a=>{a["x-component-props"]=a["x-component-props"]||{},a["x-component-props"].width=100/n,a["x-uid"]&&l.push({"x-uid":a["x-uid"],"x-component-props":a["x-component-props"]})}),i["x-uid"]&&l.length?l:[]};this.on("insertAdjacent",i=>L(this,[i],function*({onSuccess:n,current:l,position:a,schema:c,wrap:u,wrapped:d,removed:m}){var p;let h=[];if((d==null?void 0:d["x-component"])==="Grid.Col"&&(h=h.concat(r(d.parent))),(m==null?void 0:m["x-component"])==="Grid.Col"&&(h=h.concat(r(m.parent))),this.refresh(),!l["x-uid"])return;const g=yield t.request({url:`/uiSchemas:insertAdjacent/${l["x-uid"]}?position=${a}`,method:"post",data:{schema:addAppVersion(c,this.appVersion),wrap:u}});h.length&&(yield t.request({url:"/uiSchemas:batchPatch",method:"post",data:h})),m!=null&&m["x-uid"]&&(yield t.request({url:`/uiSchemas:remove/${m["x-uid"]}`,method:"post"})),n==null||n((p=g==null?void 0:g.data)==null?void 0:p.data),import_antd.message.success(o("Saved successfully"),.2)})),this.on("patch",i=>L(this,[i],function*({schema:n}){this.refresh(),n!=null&&n["x-uid"]&&(yield t.request({url:"/uiSchemas:patch",method:"post",data:x({},n)}),import_antd.message.success(o("Saved successfully"),.2))})),this.on("initializeActionContext",i=>L(this,[i],function*({schema:n}){n!=null&&n["x-uid"]&&(yield t.request({url:"/uiSchemas:initializeActionContext",method:"post",data:x({},n)}))})),this.on("batchPatch",i=>L(this,[i],function*({schemas:n}){this.refresh(),yield t.request({url:"/uiSchemas:batchPatch",method:"post",data:n}),import_antd.message.success(o("Saved successfully"),.2)})),this.on("remove",i=>L(this,[i],function*({removed:n}){let l=[];(n==null?void 0:n["x-component"])==="Grid.Col"&&(l=r(n.parent)),this.refresh(),n!=null&&n["x-uid"]&&(yield t.request({url:`/uiSchemas:remove/${n["x-uid"]}`,method:"post"}),l.length&&(yield t.request({url:"/uiSchemas:batchPatch",method:"post",data:l})),import_antd.message.success(o("Saved successfully"),.2))}))}prepareProperty(t){t.type||(t.type="void"),t.name||(t.name=(0,import_shared.uid)()),this.current["x-uid"]&&generateUid(t)}on(t,o){this.events[t]||(this.events[t]=[]),this.events[t].push(o)}emit(t,...o){return L(this,null,function*(){if(!this.events[t])return;const[r,...i]=o;return Promise.all(this.events[t].map(n=>n.bind(this)(x({current:this.current},r),...i)))})}parentsIn(t){if(!t||!import_react.Schema.isSchemaInstance(t))return!1;let o=this.current;for(;o!=null&&o.parent;){if(o.parent===t)return!0;o=o.parent}return!1}refresh(t){const{refresh:o}=this.options;return o==null?void 0:o(t)}deepMerge(t){const o={title:"title",description:"description",default:"initialValue",readOnly:"readOnly",writeOnly:"editable",enum:"dataSource","x-pattern":"pattern","x-display":"display","x-validator":"validator","x-decorator":"decorator","x-component":"component","x-reactions":"reactions","x-content":"content","x-visible":"visible","x-hidden":"hidden","x-disabled":"disabled","x-editable":"editable","x-read-only":"readOnly"},r={"x-decorator-props":"decoratorProps","x-component-props":"componentProps","x-data":"data"};Object.keys(t).forEach(i=>{o[i]?(this.current[i]=t[i],this.updateModel(o[i],t[i])):r[i]?Object.keys(t[i]).forEach(n=>{(0,import_set.default)(this.current,[i,n],t[i][n]),this.updateModel([r[i],n],t[i][n])}):this.current[i]=t[i]}),this.emit("patch",{schema:t})}getSchemaAttribute(t,o){return(0,import_get.default)(this.current,t,o)}shallowMerge(t){const o={title:"title",description:"description",default:"initialValue",readOnly:"readOnly",writeOnly:"editable",enum:"dataSource","x-pattern":"pattern","x-display":"display","x-validator":"validator","x-decorator":"decorator","x-component":"component","x-reactions":"reactions","x-content":"content","x-visible":"visible","x-hidden":"hidden","x-disabled":"disabled","x-editable":"editable","x-read-only":"readOnly","x-decorator-props":"decoratorProps","x-component-props":"componentProps","x-data":"data"};Object.keys(t).forEach(r=>{this.current[r]=t[r],o[r]&&this.updateModel(o[r],t[r])}),this.emit("patch",{schema:t})}updateModel(t,o){const r=i=>{(0,import_set.default)(i,t,o)};this.model&&r(this.model),this.query&&this.query.take(r)}insertAdjacent(t,o,r={}){switch(t){case"beforeBegin":return this.insertBeforeBegin(o,r);case"afterBegin":return this.insertAfterBegin(o,r);case"beforeEnd":return this.insertBeforeEnd(o,r);case"afterEnd":return this.insertAfterEnd(o,r)}}recursiveRemoveIfNoChildren(t,o){if(!t)return;let r=t,i;const n=o==null?void 0:o.breakRemoveOn;for(;r;){if(typeof n=="function"){if(n(r))break}else if(matchSchema(r,n))break;if(Object.keys(r.properties||{}).length>0)break;r.parent&&(i=r.parent.removeProperty(r.name)),r=r.parent}return i}remove(t,o={}){const{breakRemoveOn:r,removeParentsIfNoChildren:i}=o,n=t||this.current;let l=n.parent.removeProperty(n.name);if(i){const a=this.recursiveRemoveIfNoChildren(n.parent,{breakRemoveOn:r});a&&(l=a)}return this.emit("remove",{removed:l})}removeWithoutEmit(t,o={}){const{breakRemoveOn:r,removeParentsIfNoChildren:i}=o,n=t||this.current;let l=n.parent.removeProperty(n.name);if(i){const a=this.recursiveRemoveIfNoChildren(n.parent,{breakRemoveOn:r});a&&(l=a)}return l}insertBeforeBeginOrAfterEnd(t,o={}){if(!import_react.Schema.isSchemaInstance(this.current)||!import_react.Schema.isSchemaInstance(t)||this.current.parent!==t.parent)return;let r=0,i=0;return this.current.parent.mapProperties((n,l,a)=>{this.current.name===l&&(i=a),t.name===l&&(r=a)}),r>i?this.insertBeforeBegin(t,o):this.insertAfterEnd(t,o)}insertBeforeBegin(t,o={}){if(!import_react.Schema.isSchemaInstance(this.current))return;const r={onSuccess:o.onSuccess},{wrap:i=defaultWrap,breakRemoveOn:n,removeParentsIfNoChildren:l}=o;if(import_react.Schema.isSchemaInstance(t)){if(this.parentsIn(t)){this.emit("error",{code:"parent_is_not_allowed",schema:t});return}t.parent.removeProperty(t.name),l&&(r.removed=this.recursiveRemoveIfNoChildren(t.parent,{breakRemoveOn:n}))}else t&&(t=(0,import_cloneDeep.default)(t));const a={};let c=!1,u=0,d=0;this.current.parent.mapProperties((f,_)=>{_===this.current.name&&(d=u,c=!0,++u),f["x-index"]=u,++u,c&&(a[_]=f,this.current.parent.removeProperty(_))}),this.prepareProperty(t);const m=i(t),p=this.current.parent.addProperty(m.name||(0,import_shared.uid)(),m);p["x-index"]=d,p.parent=this.current.parent,this.current.parent.setProperties(a);const[h,g]=splitWrapSchema(p,t);this.emit("insertAdjacent",x({position:"beforeBegin",schema:g,wrapped:m,wrap:h},r))}insertAfterBegin(t,o={}){if(!import_react.Schema.isSchemaInstance(this.current))return;const r={onSuccess:o.onSuccess},{wrap:i=defaultWrap,breakRemoveOn:n,removeParentsIfNoChildren:l}=o;if(import_react.Schema.isSchemaInstance(t)){if(this.parentsIn(t)){this.emit("error",{code:"parent_is_not_allowed",schema:t});return}t.parent.removeProperty(t.name),l&&(r.removed=this.recursiveRemoveIfNoChildren(t.parent,{breakRemoveOn:n}))}else t&&(t=(0,import_cloneDeep.default)(t));const a={};let c=1;this.current.mapProperties((h,g)=>{h["x-index"]=c,++c,a[g]=h}),this.current.properties={},this.prepareProperty(t);const u=i(t),d=this.current.addProperty(u.name||(0,import_shared.uid)(),u);d["x-index"]=0,d.parent=this.current,this.current.setProperties(a);const[m,p]=splitWrapSchema(d,t);this.emit("insertAdjacent",x({position:"afterBegin",schema:p,wrap:m,wrapped:u},r))}insertBeforeEnd(t,o={}){if(!import_react.Schema.isSchemaInstance(this.current))return;delete t["x-index"];const r={onSuccess:o.onSuccess},{wrap:i=defaultWrap,breakRemoveOn:n,removeParentsIfNoChildren:l}=o;if(import_react.Schema.isSchemaInstance(t)){if(this.parentsIn(t)){this.emit("error",{code:"parent_is_not_allowed",schema:t});return}t.parent.removeProperty(t.name),l&&(r.removed=this.recursiveRemoveIfNoChildren(t.parent,{breakRemoveOn:n}))}else t&&(t=(0,import_cloneDeep.default)(t));this.prepareProperty(t);const a=i(t),c=this.current.addProperty(a.name||(0,import_shared.uid)(),a);c.parent=this.current;const[u,d]=splitWrapSchema(c,t);return this.emit("insertAdjacent",x({position:"beforeEnd",schema:d,wrap:u,wrapped:a},r))}insertAfterEnd(t,o={}){if(!import_react.Schema.isSchemaInstance(this.current))return;const r={onSuccess:o==null?void 0:o.onSuccess},{wrap:i=defaultWrap,breakRemoveOn:n,removeParentsIfNoChildren:l}=o;let a=0,c=0,u=!1;const d={};if(this.current.parent.mapProperties((f,_)=>{f["x-index"]=a,_===this.current.name&&(++a,c=a,u=!0),++a,u&&_!==this.current.name&&(d[_]=f,this.current.parent.removeProperty(_))}),import_react.Schema.isSchemaInstance(t)){if(this.parentsIn(t)){this.emit("error",{code:"parent_is_not_allowed",schema:t});return}t.parent.removeProperty(t.name),l&&(r.removed=this.recursiveRemoveIfNoChildren(t.parent,{breakRemoveOn:n})),t.parent=null}else t&&(t=(0,import_cloneDeep.default)(t));this.prepareProperty(t);const m=i(t),p=this.current.parent.addProperty(m.name||(0,import_shared.uid)(),m);p.parent=this.current.parent,p["x-index"]=c,this.current.parent.setProperties(d);const[h,g]=splitWrapSchema(p,t);this.emit("insertAdjacent",x({position:"afterEnd",schema:g,wrap:h,wrapped:m},r))}}function useFindComponent(){const e=(0,import_react2.useContext)(import_react.SchemaOptionsContext),t=(0,import_react2.useMemo)(()=>(e==null?void 0:e.components)||{},[e]);return o=>{if(!o)return null;if(typeof o!="string")return o;const r=(0,import_get.default)(t,o);return r||console.error(`[nocobase]: Component "${o}" not found`),r}}function useDesignable(){const{designable:e,setDesignable:t,refresh:o,reset:r}=(0,import_react2.useContext)(SchemaComponentContext),i=(0,import_react2.useContext)(import_react.SchemaOptionsContext),n=(0,import_react2.useMemo)(()=>(i==null?void 0:i.components)||{},[i]),l=(0,import_react2.useMemo)(()=>()=>(0,import_jsx_runtime.jsx)(import_jsx_runtime.Fragment,{}),[]),a=(0,import_ahooks.useUpdate)(),c=useRefreshFieldSchema(),u=useRefreshComponent(),d=(0,import_react2.useCallback)(v=>{o==null||o(),a(),c==null||c(v),u==null||u()},[o,a,c,u]),m=(0,import_react.useField)(),p=(0,import_react.useFieldSchema)(),h=useAPIClient(),{t:g}=(0,import_react_i18next.useTranslation)(),f=(0,import_react2.useMemo)(()=>createDesignable({t:g,api:h,refresh:d,current:p,model:m,appVersion:clientPkg.version}),[g,h,d,p,m]);(0,import_react2.useEffect)(()=>{f.loadAPIClientEvents()},[f]);const{isMobileLayout:_}=useMobileLayout();return{dn:f,designable:_?!1:e,reset:r,refresh:d,setDesignable:t,DesignableBar:l,findComponent:(0,import_react2.useCallback)(v=>{var b;if(!v)return null;if(typeof v!="string")return v;const F=(0,import_get.default)(n,v);return(b=F==null?void 0:F[LAZY_COMPONENT_KEY])!=null?b:F},[import_get.default]),on:f.on.bind(f),patch:(0,import_react2.useCallback)((v,b)=>{const F=y=>{Object.keys(y).forEach(C=>{const S=y[C];C==="title"&&(m.title=S,p.title=S),C==="x-decorator-props"&&(m.decoratorProps||(m.decoratorProps={}),p["x-decorator-props"]||(p["x-decorator-props"]={}),Object.keys(S).forEach(P=>{m.decoratorProps[P]=S[P],p["x-decorator-props"][P]=S[P]})),C==="x-component-props"&&(m.componentProps||(m.componentProps={}),p["x-component-props"]||(p["x-component-props"]={}),Object.keys(S).forEach(P=>{m.componentProps[P]=S[P],p["x-component-props"][P]=S[P]}))})};if(typeof v=="string"){const y={};return(0,import_set.default)(y,v,b),F(y)}F(v),d()},[f]),shallowMerge:(0,import_react2.useCallback)(v=>{f.shallowMerge(v)},[f]),deepMerge:(0,import_react2.useCallback)(v=>{f.deepMerge(v)},[f]),remove:(0,import_react2.useCallback)((v,b)=>{f.remove(v,b)},[f]),insertAdjacent:(0,import_react2.useCallback)((v,b,F)=>{f.insertAdjacent(v,b,F)},[f]),insertBeforeBegin:(0,import_react2.useCallback)(v=>{f.insertBeforeBegin(v)},[f]),insertAfterBegin:(0,import_react2.useCallback)(v=>{f.insertAfterBegin(v)},[f]),insertBeforeEnd:(0,import_react2.useCallback)(v=>{f.insertBeforeEnd(v)},[f]),insertAfterEnd:(0,import_react2.useCallback)(v=>{f.insertAfterEnd(v)},[f])}}const DefaultSchemaToolbar=()=>null;DefaultSchemaToolbar.isNullComponent=!0;const useDesigner=()=>{const{designable:e}=useDesignable(),t=(0,import_react.useFieldSchema)(),o=(0,import_react2.useMemo)(()=>t["x-designer"]||t["x-toolbar"]?t["x-designer"]||t["x-toolbar"]:t["x-settings"]?SchemaToolbar:DefaultSchemaToolbar,[t]),r=useComponent(o);return e&&r||DefaultSchemaToolbar},useFieldProps$1=e=>{const t=(0,import_react2.useContext)(import_react.SchemaOptionsContext),o=(0,import_react2.useContext)(import_react.SchemaExpressionScopeContext),r=(0,import_react2.useRef)();return r.current=o,e.toFieldProps(I(x({},t),{get scope(){return x(x({},t.scope),r.current)}}))};function useSchemaComponentContext(){return(0,import_react2.useContext)(SchemaComponentContext)}const useFieldComponentOptions=()=>{var e;const{getCollectionJoinField:t,getCollection:o}=useCollectionManager_deprecated(),r=(0,import_react.useFieldSchema)(),{getField:i}=useCollection_deprecated(),n=i(r.name)||t(r["x-collection-field"]),{t:l}=(0,import_react_i18next.useTranslation)(),{label:a}=((e=r["x-component-props"])==null?void 0:e.fieldNames)||{};return(0,import_react2.useMemo)(()=>{if(!n||!(n!=null&&n.interface)||!["o2o","oho","obo","o2m","linkTo","m2o","m2m"].includes(n.interface))return;const c=o(n.target);if((c==null?void 0:c.template)==="file")return[{label:l("Record picker"),value:"CollectionField"},{label:l("Select"),value:"AssociationSelect"}];switch(n.interface){case"o2m":return[{label:l("Record picker"),value:"CollectionField"},{label:l("Subtable"),value:"TableField"},{label:l("Select"),value:"AssociationSelect"}];case"m2o":case"m2m":case"linkTo":return[{label:l("Record picker"),value:"CollectionField"},{label:l("Select"),value:"AssociationSelect"}];default:return[{label:l("Record picker"),value:"CollectionField"},{label:l("Subform"),value:"FormField"},{label:l("Select"),value:"AssociationSelect"}]}},[l,n==null?void 0:n.interface,a])},useFieldTitle=()=>{var e;const t=(0,import_react.useField)(),o=(0,import_react.useFieldSchema)(),r=useCollection(),i=useCollectionManager(),n=(r==null?void 0:r.getField(o.name))||(i==null?void 0:i.getCollectionField(o["x-collection-field"])),l=useCompile();(0,import_react2.useEffect)(()=>{var a;t!=null&&t.title||(t.title=l((a=n==null?void 0:n.uiSchema)==null?void 0:a.title))},[(e=n==null?void 0:n.uiSchema)==null?void 0:e.title])},useDef$4=()=>({}),useProps=(e={})=>{const t=e,{useProps:o=useDef$4}=t,r=te(t,["useProps"]);let i=o;typeof o!="function"&&(i=useDef$4);const n=i();return x(x({},r),n)};function useParsedFilter({filterOption:e,onFilterChange:t}){const{parseFilter:o,findVariable:r}=useParseDataScopeFilter(),i=JSON.stringify(e),n=(0,import_react2.useRef)(e),l=(0,import_react2.useRef)(t),[a,c]=(0,import_react2.useState)({}),[u,d]=(0,import_react2.useState)(()=>e?null:i),m=!!e&&u!==i;return n.current=e,l.current=t,(0,import_react2.useEffect)(()=>{const p=n.current;if(!p){c({}),d(i);return}let h=!1;const g=()=>L(this,null,function*(){var v;const b=yield o(p);h||(c(b),d(i),(v=l.current)==null||v.call(l,b))});g();const f=import_lodash.default.debounce(g,DEBOUNCE_WAIT),_=(0,import_reactive.reaction)(()=>(0,import_client.flatten)(p,{breakOn({key:v}){return v.startsWith("$")&&v!=="$and"&&v!=="$or"},transformValue(v){if(!isVariable$1(v))return v;const b=getVariableName(v),F=r(b);let y=null;const C=getPath(v).split(".");return C.forEach((S,P)=>{const j=C.slice(0,P+1).join("."),A=(0,import_client.getValuesByPath)({[b]:(F==null?void 0:F.ctx)||{}},j);import_lodash.default.isEmpty(A)||(y=A)}),y}}),f,{equals:import_lodash.default.isEqual});return()=>{h=!0,f.cancel(),_()}},[i,r,o]),{filter:a,parseVariableLoading:m}}const useParentRecordCommon=e=>{const t=useCollectionRecordData();if(e)return t},useTableBlockDecoratorProps=e=>{var t;const{params:o,parseVariableLoading:r}=useTableBlockParams(e),i=useParentRecordCommon(e.association),n=(t=useDataSourceManager().getDataSource(e.dataSource))==null?void 0:t.collectionManager.getCollection(e.collection);return{params:o,parentRecord:i,parseVariableLoading:r,rowKey:(n==null?void 0:n.filterTargetKey)||"id"}};function useTableBlockParams(e){var t;const o=(0,import_react.useFieldSchema)(),{filter:r,parseVariableLoading:i}=useParsedFilter({filterOption:(t=e.params)==null?void 0:t.filter});return{params:(0,import_react2.useMemo)(()=>{const n=e.params||{},{dragSortBy:l}=(o==null?void 0:o["x-decorator-props"])||{};return e.dragSort&&l&&(n.sort=l),I(x({},n),{filter:r})},[o,r,e.dragSort,e.params]),parseVariableLoading:i}}const key="__isNewRecord__",isNewRecord=e=>(0,import_reactive.untracked)(()=>!!(e!=null&&e[key])),markRecordAsNew=e=>{if(!(0,import_lodash.isObject)(e))throw new Error("markRecordAsNew: record must be an object");return e[key]=!0,e},useDefaultLoading=()=>{var e;return!!((e=useDataBlockRequest())!=null&&e.loading)},withSkeletonComponent=(e,t)=>{const{useLoading:o=useDefaultLoading,displayName:r,SkeletonComponent:i=import_antd.Skeleton}=t||{},n=import_react2.default.memo(l=>{const a=o(),c=(0,import_react2.useRef)(!1),u=(0,import_react2.useDeferredValue)(a);return!c.current&&u?(0,import_jsx_runtime.jsx)(i,{}):(c.current=!0,(0,import_jsx_runtime.jsx)(e,x({},l)))});return n.displayName=r||`${e.displayName}(withSkeletonComponent)`||`${e.name}(withSkeletonComponent)`,n},getActionValue=(e,t)=>{const o=r=>(r==null?void 0:r.mode)==="constant"?r.value:null;switch(!0){case[ActionType.Color,ActionType.BackgroundColor,ActionType.TextAlign,ActionType.FontSize,ActionType.FontWeight,ActionType.FontStyle].includes(e):return o(t);default:return null}},getSatisfiedActions=(e,t)=>L(void 0,[e,t],function*({rules:o,variables:r,localVariables:i},n){return(yield Promise.all(o.filter(l=>!l.disabled).map(l=>L(void 0,null,function*(){return(yield conditionAnalyses({ruleGroup:l.condition,variables:r,localVariables:i,conditionType:l.conditionType},n))?l:null})))).filter(Boolean).map(l=>l.actions).flat()}),getSatisfiedValues=(e,t)=>L(void 0,[e,t],function*({rules:o,variables:r,localVariables:i},n){return(yield getSatisfiedActions({rules:o,variables:r,localVariables:i},n)).map(l=>I(x({},l),{value:getActionValue(l.operator,l.value)}))}),getSatisfiedValueMap=(e,t)=>L(void 0,[e,t],function*({rules:o,variables:r,localVariables:i},n){return(yield getSatisfiedValues({rules:o,variables:r,localVariables:i},n)).reduce((l,a)=>I(x({},l),{[a.operator]:a.value}),{})});function useSatisfiedActionValues({formValues:e,category:t="default",rules:o,schema:r,form:i}){const[n,l]=(0,import_react2.useState)({}),a=(0,import_react.useFieldSchema)(),c=useVariables$1(),u=useLocalVariables$1({currentForm:{values:e}}),d=r??a,m=o??(d[LinkageRuleDataKeyMap[t]]||(d==null?void 0:d.parent[LinkageRuleDataKeyMap[t]])),p=useApp(),h=(0,import_react2.useCallback)(()=>{m&&e&&getSatisfiedValueMap({rules:m,variables:c,localVariables:u},p.jsonLogic).then(g=>{(0,import_lodash.isEmpty)(g)?l({}):l(g)}).catch(g=>{throw new Error(g.message)})},[c,u,m,e]);return(0,import_react2.useEffect)(()=>{if(h(),i){const g=(0,import_shared.uid)();return i.addEffects(g,()=>{(0,import_core.onFormValuesChange)(()=>{h()})}),()=>{i.removeEffects(g)}}},[i,h,e]),{valueMap:n}}const GetStyleRules=import_react2.default.memo(({record:e,schema:t,onStyleChange:o})=>{const{valueMap:r}=useSatisfiedActionValues({formValues:e,category:"style",schema:t});return(0,import_react2.useEffect)(()=>{o(r)},[o,r]),null});GetStyleRules.displayName="GetStyleRules";const opacityStyle={opacity:.5},containerStyle={position:"relative"},spinStyle={display:"flex",alignItems:"center",justifyContent:"center",position:"absolute",left:0,right:0,height:"100%",maxHeight:400,zIndex:1e3},displayNone$3={display:"none"},HighPerformanceSpin=import_react2.default.memo(e=>(0,import_jsx_runtime.jsxs)("div",{style:containerStyle,children:[(0,import_jsx_runtime.jsx)(import_antd.Spin,I(x({},import_lodash.default.omit(e,"children")),{style:e.spinning?spinStyle:displayNone$3})),(0,import_jsx_runtime.jsx)("div",{style:e.spinning?opacityStyle:null,children:e.children})]}));HighPerformanceSpin.displayName="HighPerformanceSpin";var FilterBlockType=(e=>(e[e.FORM=0]="FORM",e[e.TABLE=1]="TABLE",e[e.TREE=2]="TREE",e[e.COLLAPSE=3]="COLLAPSE",e))(FilterBlockType||{});const mergeFilter=(e,t="$and")=>{const o=e.filter(r=>{if(r&&typeof r=="object"&&!Array.isArray(r))return Object.values(r).filter(i=>i!==void 0).length});return o.length===0?{}:o.length===1?o[0]:{[t]:o}},getSupportFieldsByAssociation=(e,t)=>{var o;return(o=t.associatedFields)==null?void 0:o.filter(r=>e==null?void 0:e.some(i=>i===r.target))},getSupportFieldsByForeignKey=(e,t)=>{var o;return(o=t.foreignKeyFields)==null?void 0:o.filter(r=>e.fields.some(i=>i.type!=="belongsTo"&&i.foreignKey===r.name&&i.target===r.collectionName))},useSupportedBlocks=e=>{const{getDataBlocks:t}=useFilterBlock(),o=(0,import_react.useFieldSchema)(),r=useCollection(),{getAllCollectionsInheritChain:i}=useAllCollectionsInheritChainGetter();if(e===0||e===3)return t().filter(n=>isSameCollection(n.collection,r));if(e===1||e===2)return t().filter(n=>{var l,a;return o["x-uid"]!==n.uid&&(isSameCollection(n.collection,r)||((l=getSupportFieldsByAssociation(i(r.name,r.dataSource),n))==null?void 0:l.length)||((a=getSupportFieldsByForeignKey(r,n))==null?void 0:a.length))})},transformToFilter=(e,t,o,r)=>(e=(0,import_client.flatten)(e,{breakOn({value:i,path:n}){if(["$match","$notMatch","$anyOf","$noneOf","$childIn","$childNotIn","$dateBetween","$in","$notIn"].includes(t[n]))return!0;const l=o(`${r}.${n}`);if(["datetime","datetimeNoTz","date","unixTimestamp","createdAt","updatedAt"].includes(l==null?void 0:l.interface))return!0;if(l!=null&&l.target){if(Array.isArray(i))return!0;const a=l.targetKey||"id";if(i&&i[a]!=null)return!0}return!1}}),{$and:Object.keys(e).map(i=>{let n=import_lodash.default.get(e,i);const l=o(`${r}.${i}`);return l!=null&&l.target&&["hasOne","hasMany","belongsTo","belongsToMany","belongsToArray"].includes(l.type)&&(n=(0,import_client.getValuesByPath)(n,l.targetKey||"id"),i=`${i}.${l.targetKey||"id"}`,(l==null?void 0:l.interface)==="chinaRegion"&&(n=import_lodash.default.last(n))),!n&&n!==0&&n!==!1?null:{[i]:{[t[i]||"$eq"]:n}}}).filter(Boolean)}),useAssociatedFields=()=>{var e;return((e=useCollection())==null?void 0:e.fields.filter(t=>isAssocField(t)))||[]},isAssocField=e=>["o2o","oho","obo","m2o","createdBy","updatedBy","o2m","m2m","linkTo","chinaRegion","mbm"].includes(e==null?void 0:e.interface),isSameCollection=(e,t)=>e.name===t.name&&e.dataSource===t.dataSource,useFilterAPI=()=>{const e=(0,import_react.useFieldSchema)(),{getDataBlocks:t}=useFilterBlock(),{targets:o,uid:r}=findFilterTargets(e),i=t(),[n,l]=(0,import_react2.useState)(()=>o&&o.some(u=>i.some(d=>d.uid===u.uid))),a=Object.keys(o||{});(0,import_react2.useEffect)(()=>{l(o&&o.some(u=>i.some(d=>d.uid===u.uid)))},[a.length,o,i]);const c=(0,import_react2.useCallback)((u,d="id",m="$eq")=>{const p=i.find(h=>h.uid===e.parent["x-uid"]);i.forEach(h=>{var g,f,_,v;let b=d;const F=o.find(P=>P.uid===h.uid);if(!F)return;import_lodash.default.isFunction(u)&&(u=u(F,h,getSourceKey$1(p,F.field))),import_lodash.default.isFunction(d)&&(b=d(F,h)),import_lodash.default.isFunction(m)&&(m=m(F));const y=((g=h.service.params)==null?void 0:g[0])||{},C=((_=(f=h.service.params)==null?void 0:f[1])==null?void 0:_.filters)||{};if(u!=null)C[r]={$and:[{[b]:{[m]:u}}]};else if((v=h.clearSelection)==null||v.call(h),delete C[r],h.dataLoadingMode==="manual")return h.clearData();const S=mergeFilter([...Object.values(C).map(P=>removeNullCondition(P)),h.defaultFilter]);h.doFilter(I(x({},y),{page:1,filter:S}),{filters:C})})},[i,o,r,e]);return{isConnected:n,doFilter:c}},isInFilterFormBlock=e=>{for(;e;){if(e["x-filter-targets"])return e["x-decorator"]==="FilterFormBlockProvider";e=e.parent}return!1};function getSourceKey$1(e,t){var o,r,i;const n=(o=e==null?void 0:e.associatedFields)==null?void 0:o.find(l=>l.foreignKey===t);return(n==null?void 0:n.sourceKey)||((i=(r=t==null?void 0:t.split)==null?void 0:r.call(t,"."))==null?void 0:i[1])}const AssociationFieldContext=(0,import_react2.createContext)({});AssociationFieldContext.displayName="AssociationFieldContext";const useInsertSchema$1=e=>{const t=(0,import_react.useFieldSchema)(),{insertAfterBegin:o}=useDesignable(),{isMobileLayout:r}=useMobileLayout();return(0,import_react2.useCallback)(i=>{r||t.reduceProperties((n,l)=>l["x-component"]==="AssociationField."+e?l:n,null)||o((0,import_cloneDeep.default)(i))},[e,t,o,r])};function useAssociationFieldContext(){return(0,import_react2.useContext)(AssociationFieldContext)}function useServiceOptions$1(e){var t,o,r,i,n,l,a,c,u,d;const{action:m="list",service:p,useOriginalFilter:h}=e,g=(0,import_react.useFieldSchema)(),f=(0,import_react.useField)(),{getField:_}=useCollection_deprecated(),{getCollectionJoinField:v}=useCollectionManager_deprecated(),b=useRecord(),{isNew:F}=useCollectionRecord()||{},y=((0,import_lodash.isString)((r=(o=(t=g==null?void 0:g["x-component-props"])==null?void 0:t.service)==null?void 0:o.params)==null?void 0:r.filter)?(l=(n=(i=f.componentProps)==null?void 0:i.service)==null?void 0:n.params)==null?void 0:l.filter:(u=(c=(a=g==null?void 0:g["x-component-props"])==null?void 0:a.service)==null?void 0:c.params)==null?void 0:u.filter)||((d=p==null?void 0:p.params)==null?void 0:d.filter),{filter:C}=useParsedFilter({filterOption:y,onFilterChange:()=>{F&&f.reset()}}),S=(0,import_react2.useMemo)(()=>_(g.name)||v(g==null?void 0:g["x-collection-field"]),[g]),P=b==null?void 0:b[S==null?void 0:S.sourceKey],j=(0,import_react2.useMemo)(()=>{const A=["oho","o2m"].includes(S==null?void 0:S.interface);return mergeFilter([mergeFilter([A&&!isInFilterFormBlock(g)&&S!=null&&S.foreignKey&&!h?{[S.foreignKey]:{$is:null}}:null,C]),A&&P!==void 0&&P!==null&&!isInFilterFormBlock(g)&&S!=null&&S.foreignKey&&!h?{[S.foreignKey]:{$eq:P}}:null],"$or")},[S==null?void 0:S.interface,S==null?void 0:S.foreignKey,g,C,P,h]);return(0,import_react2.useMemo)(()=>I(x({resource:S==null?void 0:S.target,action:m},p),{params:I(x({},p==null?void 0:p.params),{filter:j})}),[S==null?void 0:S.target,m,j,p])}const useFieldNames$1=(e={})=>{var t,o,r,i,n;const l=(0,import_react.useFieldSchema)(),a=((i=(r=(o=(t=l["x-component-props"])==null?void 0:t.field)==null?void 0:o.uiSchema)==null?void 0:r["x-component-props"])==null?void 0:i.fieldNames)||((n=l["x-component-props"])==null?void 0:n.fieldNames)||e.fieldNames;return x({label:"label",value:"value"},a)},SubFormContext=(0,import_react2.createContext)(null);SubFormContext.displayName="SubFormContext";const SubFormProvider=e=>{const t=(0,import_react2.useContext)(SubFormContext),{value:o,collection:r,fieldSchema:i,parent:n,skip:l}=e.value,a=(0,import_react2.useMemo)(()=>import_lodash.default.omitBy({value:o,collection:r,fieldSchema:i,skip:l,parent:n||(t!=null&&t.skip?t.parent:t)},import_lodash.default.isUndefined),[o,r,i,l,n,t]);return(0,import_jsx_runtime.jsx)(SubFormContext.Provider,{value:a,children:e.children})},useSubFormValue=()=>{const{value:e,collection:t,fieldSchema:o,parent:r}=(0,import_react2.useContext)(SubFormContext)||{};return{formValue:e,collection:t,fieldSchema:o,parent:r}},TableUidContext=(0,import_react2.createContext)(null),useColumnSettings=e=>{const{t}=(0,import_react_i18next.useTranslation)(),o=(0,import_react2.useContext)(TableUidContext),r=`nocobase_table_column_settings_${o}`,i=(0,import_react2.useCallback)(()=>{try{const a=localStorage.getItem(r);return a?JSON.parse(a):null}catch(a){return console.warn("Failed to parse table column settings from localStorage:",a),null}},[r]),n=(0,import_react2.useCallback)(a=>{try{const c=JSON.stringify(a);localStorage.setItem(r,c);const u=new CustomEvent("nocobase-table-settings-changed",{detail:{key:r,tableId:o,settings:a}});window.dispatchEvent(u)}catch(c){console.warn("Failed to save table column settings to localStorage:",c),import_antd.message.error(t("Failed to save table settings"))}},[r,o,t]),l=(0,import_react2.useCallback)(()=>{try{localStorage.removeItem(r);const a=new CustomEvent("nocobase-table-settings-changed",{detail:{key:r,tableId:o,settings:null}});window.dispatchEvent(a)}catch(a){console.warn("Failed to clear table column settings from localStorage:",a),import_antd.message.error(t("Failed to clear table settings"))}},[r,o,t]);return{getSettings:i,saveSettings:n,clearSettings:l}},useTableColumnIntegration=(e,t=!0)=>{const o=(0,import_react2.useContext)(TableUidContext),{getSettings:r}=useColumnSettings(),[i,n]=(0,import_react2.useState)(0);(0,import_react2.useEffect)(()=>{const a=c=>{const{key:u,tableId:d}=c.detail;(u.includes(o)||d===o)&&n(m=>m+1)};return window.addEventListener("nocobase-table-settings-changed",a),()=>{window.removeEventListener("nocobase-table-settings-changed",a)}},[o]);const l=(0,import_react2.useMemo)(()=>r(),[r,i]);return{columns:(0,import_react2.useMemo)(()=>{if(!t||!l||l.length===0)return e;const a=new Map;l.forEach(p=>{a.set(p.key,p)});const c=e.map(p=>{const h=a.get(p.key);if(h){const g=p.columnHidden||!h.visible,f=h.width||p.width,_=h.fixed||p.fixed;return I(x({},p),{columnHidden:g,fixed:_,width:f,_orderIndex:h.order})}return p}),u=[],d=[];c.forEach(p=>{p._orderIndex!==void 0?u.push(p):d.push(p)}),u.sort((p,h)=>(p._orderIndex||0)-(h._orderIndex||0));const m=[...u,...d];return m.forEach(p=>{delete p._orderIndex}),m},[e,l])}},TableSkeleton=({rows:e=5,columns:t=6})=>{const{token:o}=useToken$1(),r=o.controlHeight*2.06,i=o.controlHeight*1.75,n=(0,import_react2.useMemo)(()=>import_css.css`
65
+ `,items:a},n))})},SchemaInitializerSubMenu=e=>{var t;const o=e,{children:r,items:i,title:n,name:l,onOpenChange:a,icon:c}=o,u=te(o,["children","items","title","name","onOpenChange","icon"]),d=useCompile(),m=useSchemaInitializerItem(),p=(0,import_react2.useMemo)(()=>l||(m==null?void 0:m.name)||(0,import_shared.uid)(),[l,m]),h=(t=i||r)==null?void 0:t.filter(_=>_.useVisible?_.useVisible():!0),g=useSchemaInitializerMenuItems(h,l),f=(0,import_react2.useMemo)(()=>[I(x({},u),{key:p,label:d(n),icon:typeof c=="string"?(0,import_jsx_runtime.jsx)(import_icons.default,{type:c}):c,children:g})],[g,d,c,p,u,n]);return(0,import_jsx_runtime.jsx)(SchemaInitializerMenu,{onOpenChange:a,items:f})},SchemaInitializerSubMenuInternal=()=>{const e=useSchemaInitializerItem();return(0,import_jsx_runtime.jsx)(SchemaInitializerSubMenu,x({},e))},useAriaAttributeOfMenuItem=()=>{const{isInMenu:e}=useSchemaInitializerSubMenuContext();return{attribute:(0,import_react2.useMemo)(()=>e?{}:{role:"menuitem"},[e])}},{Paragraph:Paragraph$1,Text:Text$2}=import_antd.Typography,ErrorFallbackModal=e=>{const[t,o]=import_react2.default.useState(!1),r=(0,import_jsx_runtime.jsx)(Paragraph$1,{style:{display:"flex",marginBottom:0},copyable:{text:e.error.message},children:(0,import_jsx_runtime.jsxs)(Text$2,{type:"danger",style:{whiteSpace:"nowrap",textOverflow:"ellipsis",overflow:"hidden",display:"inline-block",maxWidth:"200px"},children:["Error: ",e.error.message]})});return(0,import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment,{children:[(0,import_jsx_runtime.jsx)("div",{onMouseOver:()=>o(!0),children:e.children||r}),(0,import_jsx_runtime.jsx)(import_antd.Modal,{zIndex:1e4,open:t,footer:null,onCancel:()=>o(!1),width:"60%",children:(0,import_jsx_runtime.jsx)(ErrorFallback,x({},e))})]})},{Paragraph,Text:Text$1,Link}=import_antd.Typography,useDownloadLogs=(e,t={})=>{const o=useLocationNoUpdate(),[r,i]=import_react2.default.useState(!1),n=useAPIClient();return{loading:r,download:()=>L(void 0,null,function*(){i(!0);try{const l=yield n.request({url:"logger:collect",method:"post",responseType:"blob",data:x({error:{message:e.message,stack:e.stack},location:o},t)}),a=window.URL.createObjectURL(new Blob([l.data],{type:"application/gzip"})),c=document.createElement("a");c.setAttribute("href",a),c.setAttribute("download","logs.tar.gz"),c.click(),c.remove()}catch(l){console.log(l)}i(!1)})}},ErrorFallback=({error:e})=>{const t=(0,import_react.useFieldSchema)(),{t:o}=(0,import_react_i18next.useTranslation)(),{loading:r,download:i}=useDownloadLogs(e,{schema:t}),n=(0,import_jsx_runtime.jsxs)(import_react_i18next.Trans,{children:["This is likely a NocoBase internals bug. Please open an issue at ",(0,import_jsx_runtime.jsx)(Link,{href:"https://github.com/nocobase/nocobase/issues",target:"_blank",children:"here"})]});return(0,import_jsx_runtime.jsx)("div",{style:{backgroundColor:"white"},children:(0,import_jsx_runtime.jsx)(import_antd.Result,{style:{maxWidth:"60vw",margin:"auto"},status:"error",title:o("Render Failed"),subTitle:n,extra:[(0,import_jsx_runtime.jsx)(import_antd.Button,{type:"primary",href:"https://github.com/nocobase/nocobase/issues",target:"_blank",children:o("Feedback")},"feedback"),(0,import_jsx_runtime.jsx)(import_antd.Button,{loading:r,onClick:i,children:o("Download logs")},"log")],children:(0,import_jsx_runtime.jsx)(Paragraph,{copyable:{text:e.stack},children:(0,import_jsx_runtime.jsx)(Text$1,{type:"danger",style:{whiteSpace:"pre-line",textAlign:"center"},children:e.stack})})})})};ErrorFallback.Modal=ErrorFallbackModal;const AppNotFound=()=>{const e=(0,import_react_router_dom.useNavigate)(),{t}=(0,import_react_i18next.useTranslation)();return(0,import_jsx_runtime.jsx)(import_antd.Result,{status:"404",title:"404",subTitle:t("Sorry, the page you visited does not exist."),extra:(0,import_jsx_runtime.jsx)(import_antd.Button,{onClick:()=>e("/",{replace:!0}),type:"primary",children:"Back Home"})})};class Plugin{constructor(t,o){this.options=t,this.app=o,this.options=t,this.app=o}get pluginManager(){return this.app.pluginManager}get context(){return this.app.context}get flowEngine(){return this.app.flowEngine}get engine(){return this.app.flowEngine}get ai(){return this.app.aiManager}get pm(){return this.app.pm}get router(){return this.app.router}get pluginSettingsManager(){return this.app.pluginSettingsManager}get pluginSettingsRouter(){return this.app.pluginSettingsManager}get schemaInitializerManager(){return this.app.schemaInitializerManager}get schemaSettingsManager(){return this.app.schemaSettingsManager}get dataSourceManager(){return this.app.dataSourceManager}afterAdd(){return L(this,null,function*(){})}beforeLoad(){return L(this,null,function*(){})}load(){return L(this,null,function*(){})}t(t,o={}){var r;return this.app.i18n.t(t,x({ns:(r=this.options)==null?void 0:r.packageName},o))}}const titleWrapperStyle={display:"flex",alignItems:"center",gap:4},withTooltipComponent=e=>t=>{const{tooltip:o}=t;return o?(0,import_jsx_runtime.jsxs)("div",{style:titleWrapperStyle,children:[(0,import_jsx_runtime.jsx)(e,x({},t)),(0,import_jsx_runtime.jsx)(import_antd.Tooltip,{title:o,children:(0,import_jsx_runtime.jsx)(import_icons.QuestionCircleOutlined,{style:{zIndex:1}})})]}):(0,import_jsx_runtime.jsx)(e,x({},t))},{evaluate}=import_client4.evaluators.get("formula.js"),useEvaluatedExpression=e=>{const t=useVariables$1(),o=useLocalVariables$1(),[r,i]=(0,import_react2.useState)();return(0,import_react2.useEffect)(()=>{L(void 0,null,function*(){if(e==null||e===""){i(void 0);return}const{exp:n,scope:l}=yield replaceVariables(e,{variables:t,localVariables:o});try{const a=evaluate(n,x({now:()=>new Date().toString()},l));i(a)}catch(a){console.error(a)}})},[t.parseVariable,e,o]),r};class SchemaInitializer{constructor(t){R(this,"options"),R(this,"name"),this.options=Object.assign({items:[]},t),this.name=t.name}get items(){return this.options.items}add(t,o){const r=t.split("."),i=r[r.length-1],n=I(x({},o),{name:i}),l=(u,d)=>{const m=this.items.findIndex(p=>p.name===u);m===-1?this.items.push(d):this.items[m]=d};if(r.length===1){l(i,n);return}const a=r.slice(0,-1).join("."),c=this.get(a);if(c){c.children||(c.children=[]);const u=t.replace(`${c.name}.`,""),d=c.children.findIndex(m=>m.name===u);d===-1?c.children.push(n):c.children[d]=n}else l(i,n)}get(t){var o;if(!t)return;const r=t.split(".");let i={children:this.items};for(let n=0;n<r.length;n++){const l=r[n],a=(o=i.children)==null?void 0:o.find(c=>c.name===l);if(a&&(i=a),n===r.length-1)return a}}remove(t){const o=t.split(".");if(o.length===1){const i=this.items.findIndex(n=>n.name===o[0]);i!==-1&&this.items.splice(i,1);return}const r=this.get(o.slice(0,-1).join("."));if(r&&r.children){const i=o[o.length-1],n=r.children.findIndex(l=>l.name===i);n!==-1&&r.children.splice(n,1)}}}var NocoBaseDesktopRouteType=(e=>(e.group="group",e.page="page",e.flowRoute="flowRoute",e.link="link",e.tabs="tabs",e.flowPage="flowPage",e))(NocoBaseDesktopRouteType||{});const useStyles$h=genStyleHook("nb-menu-item",e=>{const{componentCls:t}=e;return{[t]:{paddingLeft:`${e.padding}px !important`,paddingRight:`${e.padding}px !important`}}}),useInsertFlowPageSchema=()=>{const e=useAPIClient();return(0,import_react2.useCallback)(t=>L(void 0,null,function*(){yield e.request({method:"POST",url:"/uiSchemas:insert",data:t})}),[e])},FlowPageMenuItem=()=>{const{t:e}=(0,import_react_i18next.useTranslation)(),t=(0,import_react2.useContext)(import_react.SchemaOptionsContext),{theme:o}=useGlobalTheme(),{componentCls:r,hashId:i}=useStyles$h(),n=useParentRoute(),{createRoute:l}=useNocoBaseRoutes(),a=useInsertFlowPageSchema(),c=(0,import_react2.useCallback)(()=>L(void 0,null,function*(){const u=yield FormDialog(e("Add page"),()=>(0,import_jsx_runtime.jsx)(SchemaComponentOptions,{scope:t.scope,components:x({},t.components),children:(0,import_jsx_runtime.jsx)(import_antd_v5.FormLayout,{layout:"vertical",children:(0,import_jsx_runtime.jsx)(zIndexContext.Provider,{value:ICON_POPUP_Z_INDEX,children:(0,import_jsx_runtime.jsx)(SchemaComponent,{schema:{properties:{title:{title:e("Menu item title"),required:!0,"x-component":"Input","x-decorator":"FormItem"},icon:{title:e("Icon"),"x-component":"IconPicker","x-decorator":"FormItem"}}}})})})}),o).open({initialValues:{}}),d=(0,import_shared.uid)(),m=(0,import_shared.uid)(),p=(0,import_shared.uid)(),h=(0,import_shared.uid)();yield l({type:NocoBaseDesktopRouteType.flowPage,title:u.title,icon:u.icon,parentId:n==null?void 0:n.id,schemaUid:m,menuSchemaUid:d,enableTabs:!1,children:[{type:NocoBaseDesktopRouteType.tabs,schemaUid:p,tabSchemaName:h,hidden:!0}]}),a(getFlowPageMenuSchema({pageSchemaUid:m}))}),[l,a,t==null?void 0:t.components,t==null?void 0:t.scope,n==null?void 0:n.id,e,o]);return(0,import_jsx_runtime.jsx)(SchemaInitializerItem,{title:e("Modern page (v2)"),onClick:c,className:`${r} ${i}`})};function getFlowPageMenuSchema({pageSchemaUid:e}){return{type:"void","x-component":"FlowRoute","x-uid":e}}const GroupItem$1=()=>{const{t:e}=(0,import_react_i18next.useTranslation)(),t=(0,import_react2.useContext)(import_react.SchemaOptionsContext),{theme:o}=useGlobalTheme(),{componentCls:r,hashId:i}=useStyles$h(),n=useParentRoute(),{createRoute:l}=useNocoBaseRoutes(),a=(0,import_react2.useCallback)(()=>L(void 0,null,function*(){const c=yield FormDialog(e("Add group"),()=>(0,import_jsx_runtime.jsx)(SchemaComponentOptions,{scope:t.scope,components:x({},t.components),children:(0,import_jsx_runtime.jsx)(import_antd_v5.FormLayout,{layout:"vertical",children:(0,import_jsx_runtime.jsx)(zIndexContext.Provider,{value:ICON_POPUP_Z_INDEX,children:(0,import_jsx_runtime.jsx)(SchemaComponent,{schema:{properties:{title:{title:e("Menu item title"),"x-component":"Input","x-decorator":"FormItem",required:!0},icon:{title:e("Icon"),"x-component":"IconPicker","x-decorator":"FormItem"}}}})})})}),o).open({initialValues:{}}),{title:u,icon:d}=c,m=(0,import_shared.uid)();yield l({type:NocoBaseDesktopRouteType.group,title:u,icon:d,parentId:n==null?void 0:n.id,schemaUid:m})}),[t.components,t.scope,e,o]);return(0,import_jsx_runtime.jsx)(SchemaInitializerItem,{title:e("Group"),onClick:a,className:`${r} ${i}`})},useAttach=e=>{const t=(0,import_react2.useRef)(null);return(0,import_react2.useEffect)(()=>(t.current&&e!==t.current&&t.current.onUnmount(),t.current=e,e.onMount(),()=>{e.onUnmount()}),[e]),e},compileCache={},hasVariable=e=>/{{.*?}}/g.test(e),useCompile=({noCache:e}={noCache:!1})=>{const t=(0,import_react2.useContext)(import_react.SchemaOptionsContext),o=(0,import_react2.useContext)(import_react.SchemaExpressionScopeContext);return(r,i)=>{let n=!1,l;if(typeof r=="string"&&r.startsWith("{{")&&(n=!0,l=r),r&&typeof r=="object"&&!(0,import_react2.isValidElement)(r)){try{l=JSON.stringify(r)}catch(a){return console.warn("Failed to stringify:",a),r}if(compileCache[l])return compileCache[l];n=hasVariable(l)}if(Array.isArray(r)){try{l=JSON.stringify(r)}catch(a){return console.warn("Failed to stringify:",a),r}if(compileCache[l])return compileCache[l];n=hasVariable(l)}if(n){const a=x(x(x({},t==null?void 0:t.scope),o),i);if(!l)return import_react.Schema.compile(r,a);try{return e?import_react.Schema.compile(r,a):(compileCache[l]=compileCache[l]||import_react.Schema.compile(r,a),compileCache[l])}catch(c){return console.log("useCompile error",r,c),import_react.Schema.compile(r,a)}}return r}},useComponent=(e,t)=>{const{components:o}=(0,import_react2.useContext)(import_react.SchemaOptionsContext);return e?typeof e!="string"?e:(0,import_lodash.get)(o,e)||t:t},LAZY_COMPONENT_KEY=Symbol("LAZY_COMPONENT_KEY");function lazy(e,...t){if(t.length===0){const o=(0,import_react2.lazy)(()=>e().then(i=>{const n=i.default;return r[LAZY_COMPONENT_KEY]=n,{default:n}})),r=i=>(0,import_jsx_runtime.jsx)(import_react2.default.Suspense,{fallback:(0,import_jsx_runtime.jsx)(import_antd.Spin,{}),children:(0,import_jsx_runtime.jsx)(o,x({},i))});return r}return t.reduce((o,r)=>{const i=(0,import_react2.lazy)(()=>e().then(n=>{const l=(0,import_lodash.get)(n,r);return o[r][LAZY_COMPONENT_KEY]=l,{default:l}}));return o[r]=n=>(0,import_jsx_runtime.jsx)(import_react2.default.Suspense,{fallback:(0,import_jsx_runtime.jsx)(import_antd.Spin,{}),children:(0,import_jsx_runtime.jsx)(i,x({},n))}),o},{})}function useLazy(e,t){const o=typeof t=="function"?t:i=>i[t],r=(0,import_react_imported_component.loadableResource)(e);if(!r.payload)throw new Promise((i,n)=>{r.loadIfNeeded(),r.resolution.then(i).catch(n)});return o(r.payload)}function addAppVersion(e,t){if(e)return e["x-app-version"]||(e["x-app-version"]=t),Object.keys(e.properties||{}).forEach(o=>{var r;addAppVersion((r=e.properties)==null?void 0:r[o],t)}),e}const name="@nocobase/client",version="2.0.40",license="Apache-2.0",main="lib/index.js",module$1="es/index.mjs",types="es/index.d.ts",dependencies={"@ahooksjs/use-url-state":"3.5.1","@ant-design/cssinjs":"^1.11.1","@ant-design/icons":"^5.6.1","@ant-design/pro-layout":"^7.22.1","@antv/g2plot":"^2.4.18","@budibase/handlebars-helpers":"0.14.0","@codemirror/lang-html":"^6.4.10","@codemirror/theme-one-dark":"^6.1.3","@ctrl/tinycolor":"^3.6.0","@dnd-kit/core":"^6.0.0","@dnd-kit/sortable":"^7.0.0","@emotion/css":"^11.7.1","@formily/antd-v5":"1.2.3","@formily/core":"^2.2.27","@formily/grid":"^2.2.27","@formily/json-schema":"^2.2.27","@formily/path":"^2.2.27","@formily/react":"^2.2.27","@formily/reactive":"^2.2.27","@formily/reactive-react":"^2.2.27","@formily/shared":"^2.2.27","@formily/validator":"^2.2.27","@nocobase/evaluators":"2.0.40","@nocobase/flow-engine":"2.0.40","@nocobase/sdk":"2.0.40","@nocobase/utils":"2.0.40","@tanstack/react-table":"^8.21.3","@types/tabulator-tables":"^6.2.6","acorn-jsx":"^5.3.2",ahooks:"^3.7.2",antd:"5.24.2","antd-mobile":"^5.41.1","antd-mobile-icons":"^0.3.0","antd-style":"3.7.1",axios:"^1.7.0","bignumber.js":"^9.1.2",classnames:"^2.3.1",codemirror:"^6.0.2",cronstrue:"^2.11.0","file-saver":"^2.0.5",filesize:"9.0.11",flat:"^5.0.2","html5-qrcode":"^2.3.8",i18next:"^22.4.9","i18next-http-backend":"^2.1.1",ignore:"^5.2.0",json5:"^2.2.3",liquidjs:"^10.0.0",lodash:"^4.17.21","lru-cache":"6.0.0","markdown-it":"14.1.0","markdown-it-highlightjs":"3.3.1",mathjs:"^15.1.0",mermaid:"9.4.3",mime:"^4.0.4","mime-match":"^1.0.2","quill-image-resize-module-react":"^3.0.0","react-beautiful-dnd":"^13.1.0","react-device-detect":"2.2.3","react-drag-listview":"^0.1.9","react-error-boundary":"^4.0.10","react-helmet":"^6.1.0","react-hotkeys-hook":"^3.4.7","react-i18next":"^11.15.1","react-iframe":"~1.8.5","react-image-lightbox":"^5.1.4","react-intersection-observer":"9.14.0","react-js-cron":"^3.1.0","react-quill":"^2.0.0","react-router-dom":"^6.30.1","react-to-print":"^2.14.7","sanitize-html":"2.13.0","tabulator-tables":"^6.3.1","use-deep-compare-effect":"^1.8.1",vditor:"^3.10.3"},peerDependencies={react:">=18.0.0","react-dom":">=18.0.0","react-is":">=18.0.0"},devDependencies={"@testing-library/react":"^14.0.0","@types/markdown-it":"14.1.1","@types/markdown-it-highlightjs":"3.3.1","@types/react-big-calendar":"^1.6.4","axios-mock-adapter":"^1.20.0",dumi:"2.2.14","dumi-theme-nocobase":"^0.2.32"},clientPkg={name,version,license,main,module:module$1,types,dependencies,peerDependencies,devDependencies};function createDesignable(e){return new Designable(e)}const generateUid=e=>{e&&(e["x-uid"]||(e["x-uid"]=(0,import_shared.uid)()),Object.keys(e.properties||{}).forEach(t=>{generateUid(e.properties[t])}))},defaultWrap=e=>e,matchSchema=(e,t)=>{if(!(!e||!t)){for(const o in t)if(Object.prototype.hasOwnProperty.call(t,o)&&t[o]!==(e==null?void 0:e[o]))return!1;return!0}},splitWrapSchema=(e,t)=>{if(e["x-uid"]&&e["x-uid"]===t["x-uid"])return[null,e.toJSON()];const o=e.toJSON(),r=I(x({},o),{properties:{}});let i=null;const n=(l,a)=>{Object.keys(l||{}).forEach(c=>{const u=l[c];if(u["x-uid"]===t["x-uid"]){i=l[c];return}else a.properties[c]=I(x({},u),{properties:{}}),n(u==null?void 0:u.properties,a.properties[c])})};return n(o.properties,r),[r,i]},translate=e=>e;class Designable{constructor(t){R(this,"current"),R(this,"options"),R(this,"appVersion"),R(this,"events",{}),this.options=t,this.current=t.current,this.appVersion=t.appVersion}get model(){return this.options.model}get query(){return this.options.query}loadAPIClientEvents(){const{api:t,t:o=translate}=this.options;if(!t)return;const r=i=>{if(!i)return[];const n=Object.values(i.properties).length,l=[];return i.mapProperties(a=>{a["x-component-props"]=a["x-component-props"]||{},a["x-component-props"].width=100/n,a["x-uid"]&&l.push({"x-uid":a["x-uid"],"x-component-props":a["x-component-props"]})}),i["x-uid"]&&l.length?l:[]};this.on("insertAdjacent",i=>L(this,[i],function*({onSuccess:n,current:l,position:a,schema:c,wrap:u,wrapped:d,removed:m}){var p;let h=[];if((d==null?void 0:d["x-component"])==="Grid.Col"&&(h=h.concat(r(d.parent))),(m==null?void 0:m["x-component"])==="Grid.Col"&&(h=h.concat(r(m.parent))),this.refresh(),!l["x-uid"])return;const g=yield t.request({url:`/uiSchemas:insertAdjacent/${l["x-uid"]}?position=${a}`,method:"post",data:{schema:addAppVersion(c,this.appVersion),wrap:u}});h.length&&(yield t.request({url:"/uiSchemas:batchPatch",method:"post",data:h})),m!=null&&m["x-uid"]&&(yield t.request({url:`/uiSchemas:remove/${m["x-uid"]}`,method:"post"})),n==null||n((p=g==null?void 0:g.data)==null?void 0:p.data),import_antd.message.success(o("Saved successfully"),.2)})),this.on("patch",i=>L(this,[i],function*({schema:n}){this.refresh(),n!=null&&n["x-uid"]&&(yield t.request({url:"/uiSchemas:patch",method:"post",data:x({},n)}),import_antd.message.success(o("Saved successfully"),.2))})),this.on("initializeActionContext",i=>L(this,[i],function*({schema:n}){n!=null&&n["x-uid"]&&(yield t.request({url:"/uiSchemas:initializeActionContext",method:"post",data:x({},n)}))})),this.on("batchPatch",i=>L(this,[i],function*({schemas:n}){this.refresh(),yield t.request({url:"/uiSchemas:batchPatch",method:"post",data:n}),import_antd.message.success(o("Saved successfully"),.2)})),this.on("remove",i=>L(this,[i],function*({removed:n}){let l=[];(n==null?void 0:n["x-component"])==="Grid.Col"&&(l=r(n.parent)),this.refresh(),n!=null&&n["x-uid"]&&(yield t.request({url:`/uiSchemas:remove/${n["x-uid"]}`,method:"post"}),l.length&&(yield t.request({url:"/uiSchemas:batchPatch",method:"post",data:l})),import_antd.message.success(o("Saved successfully"),.2))}))}prepareProperty(t){t.type||(t.type="void"),t.name||(t.name=(0,import_shared.uid)()),this.current["x-uid"]&&generateUid(t)}on(t,o){this.events[t]||(this.events[t]=[]),this.events[t].push(o)}emit(t,...o){return L(this,null,function*(){if(!this.events[t])return;const[r,...i]=o;return Promise.all(this.events[t].map(n=>n.bind(this)(x({current:this.current},r),...i)))})}parentsIn(t){if(!t||!import_react.Schema.isSchemaInstance(t))return!1;let o=this.current;for(;o!=null&&o.parent;){if(o.parent===t)return!0;o=o.parent}return!1}refresh(t){const{refresh:o}=this.options;return o==null?void 0:o(t)}deepMerge(t){const o={title:"title",description:"description",default:"initialValue",readOnly:"readOnly",writeOnly:"editable",enum:"dataSource","x-pattern":"pattern","x-display":"display","x-validator":"validator","x-decorator":"decorator","x-component":"component","x-reactions":"reactions","x-content":"content","x-visible":"visible","x-hidden":"hidden","x-disabled":"disabled","x-editable":"editable","x-read-only":"readOnly"},r={"x-decorator-props":"decoratorProps","x-component-props":"componentProps","x-data":"data"};Object.keys(t).forEach(i=>{o[i]?(this.current[i]=t[i],this.updateModel(o[i],t[i])):r[i]?Object.keys(t[i]).forEach(n=>{(0,import_set.default)(this.current,[i,n],t[i][n]),this.updateModel([r[i],n],t[i][n])}):this.current[i]=t[i]}),this.emit("patch",{schema:t})}getSchemaAttribute(t,o){return(0,import_get.default)(this.current,t,o)}shallowMerge(t){const o={title:"title",description:"description",default:"initialValue",readOnly:"readOnly",writeOnly:"editable",enum:"dataSource","x-pattern":"pattern","x-display":"display","x-validator":"validator","x-decorator":"decorator","x-component":"component","x-reactions":"reactions","x-content":"content","x-visible":"visible","x-hidden":"hidden","x-disabled":"disabled","x-editable":"editable","x-read-only":"readOnly","x-decorator-props":"decoratorProps","x-component-props":"componentProps","x-data":"data"};Object.keys(t).forEach(r=>{this.current[r]=t[r],o[r]&&this.updateModel(o[r],t[r])}),this.emit("patch",{schema:t})}updateModel(t,o){const r=i=>{(0,import_set.default)(i,t,o)};this.model&&r(this.model),this.query&&this.query.take(r)}insertAdjacent(t,o,r={}){switch(t){case"beforeBegin":return this.insertBeforeBegin(o,r);case"afterBegin":return this.insertAfterBegin(o,r);case"beforeEnd":return this.insertBeforeEnd(o,r);case"afterEnd":return this.insertAfterEnd(o,r)}}recursiveRemoveIfNoChildren(t,o){if(!t)return;let r=t,i;const n=o==null?void 0:o.breakRemoveOn;for(;r;){if(typeof n=="function"){if(n(r))break}else if(matchSchema(r,n))break;if(Object.keys(r.properties||{}).length>0)break;r.parent&&(i=r.parent.removeProperty(r.name)),r=r.parent}return i}remove(t,o={}){const{breakRemoveOn:r,removeParentsIfNoChildren:i}=o,n=t||this.current;let l=n.parent.removeProperty(n.name);if(i){const a=this.recursiveRemoveIfNoChildren(n.parent,{breakRemoveOn:r});a&&(l=a)}return this.emit("remove",{removed:l})}removeWithoutEmit(t,o={}){const{breakRemoveOn:r,removeParentsIfNoChildren:i}=o,n=t||this.current;let l=n.parent.removeProperty(n.name);if(i){const a=this.recursiveRemoveIfNoChildren(n.parent,{breakRemoveOn:r});a&&(l=a)}return l}insertBeforeBeginOrAfterEnd(t,o={}){if(!import_react.Schema.isSchemaInstance(this.current)||!import_react.Schema.isSchemaInstance(t)||this.current.parent!==t.parent)return;let r=0,i=0;return this.current.parent.mapProperties((n,l,a)=>{this.current.name===l&&(i=a),t.name===l&&(r=a)}),r>i?this.insertBeforeBegin(t,o):this.insertAfterEnd(t,o)}insertBeforeBegin(t,o={}){if(!import_react.Schema.isSchemaInstance(this.current))return;const r={onSuccess:o.onSuccess},{wrap:i=defaultWrap,breakRemoveOn:n,removeParentsIfNoChildren:l}=o;if(import_react.Schema.isSchemaInstance(t)){if(this.parentsIn(t)){this.emit("error",{code:"parent_is_not_allowed",schema:t});return}t.parent.removeProperty(t.name),l&&(r.removed=this.recursiveRemoveIfNoChildren(t.parent,{breakRemoveOn:n}))}else t&&(t=(0,import_cloneDeep.default)(t));const a={};let c=!1,u=0,d=0;this.current.parent.mapProperties((f,_)=>{_===this.current.name&&(d=u,c=!0,++u),f["x-index"]=u,++u,c&&(a[_]=f,this.current.parent.removeProperty(_))}),this.prepareProperty(t);const m=i(t),p=this.current.parent.addProperty(m.name||(0,import_shared.uid)(),m);p["x-index"]=d,p.parent=this.current.parent,this.current.parent.setProperties(a);const[h,g]=splitWrapSchema(p,t);this.emit("insertAdjacent",x({position:"beforeBegin",schema:g,wrapped:m,wrap:h},r))}insertAfterBegin(t,o={}){if(!import_react.Schema.isSchemaInstance(this.current))return;const r={onSuccess:o.onSuccess},{wrap:i=defaultWrap,breakRemoveOn:n,removeParentsIfNoChildren:l}=o;if(import_react.Schema.isSchemaInstance(t)){if(this.parentsIn(t)){this.emit("error",{code:"parent_is_not_allowed",schema:t});return}t.parent.removeProperty(t.name),l&&(r.removed=this.recursiveRemoveIfNoChildren(t.parent,{breakRemoveOn:n}))}else t&&(t=(0,import_cloneDeep.default)(t));const a={};let c=1;this.current.mapProperties((h,g)=>{h["x-index"]=c,++c,a[g]=h}),this.current.properties={},this.prepareProperty(t);const u=i(t),d=this.current.addProperty(u.name||(0,import_shared.uid)(),u);d["x-index"]=0,d.parent=this.current,this.current.setProperties(a);const[m,p]=splitWrapSchema(d,t);this.emit("insertAdjacent",x({position:"afterBegin",schema:p,wrap:m,wrapped:u},r))}insertBeforeEnd(t,o={}){if(!import_react.Schema.isSchemaInstance(this.current))return;delete t["x-index"];const r={onSuccess:o.onSuccess},{wrap:i=defaultWrap,breakRemoveOn:n,removeParentsIfNoChildren:l}=o;if(import_react.Schema.isSchemaInstance(t)){if(this.parentsIn(t)){this.emit("error",{code:"parent_is_not_allowed",schema:t});return}t.parent.removeProperty(t.name),l&&(r.removed=this.recursiveRemoveIfNoChildren(t.parent,{breakRemoveOn:n}))}else t&&(t=(0,import_cloneDeep.default)(t));this.prepareProperty(t);const a=i(t),c=this.current.addProperty(a.name||(0,import_shared.uid)(),a);c.parent=this.current;const[u,d]=splitWrapSchema(c,t);return this.emit("insertAdjacent",x({position:"beforeEnd",schema:d,wrap:u,wrapped:a},r))}insertAfterEnd(t,o={}){if(!import_react.Schema.isSchemaInstance(this.current))return;const r={onSuccess:o==null?void 0:o.onSuccess},{wrap:i=defaultWrap,breakRemoveOn:n,removeParentsIfNoChildren:l}=o;let a=0,c=0,u=!1;const d={};if(this.current.parent.mapProperties((f,_)=>{f["x-index"]=a,_===this.current.name&&(++a,c=a,u=!0),++a,u&&_!==this.current.name&&(d[_]=f,this.current.parent.removeProperty(_))}),import_react.Schema.isSchemaInstance(t)){if(this.parentsIn(t)){this.emit("error",{code:"parent_is_not_allowed",schema:t});return}t.parent.removeProperty(t.name),l&&(r.removed=this.recursiveRemoveIfNoChildren(t.parent,{breakRemoveOn:n})),t.parent=null}else t&&(t=(0,import_cloneDeep.default)(t));this.prepareProperty(t);const m=i(t),p=this.current.parent.addProperty(m.name||(0,import_shared.uid)(),m);p.parent=this.current.parent,p["x-index"]=c,this.current.parent.setProperties(d);const[h,g]=splitWrapSchema(p,t);this.emit("insertAdjacent",x({position:"afterEnd",schema:g,wrap:h,wrapped:m},r))}}function useFindComponent(){const e=(0,import_react2.useContext)(import_react.SchemaOptionsContext),t=(0,import_react2.useMemo)(()=>(e==null?void 0:e.components)||{},[e]);return o=>{if(!o)return null;if(typeof o!="string")return o;const r=(0,import_get.default)(t,o);return r||console.error(`[nocobase]: Component "${o}" not found`),r}}function useDesignable(){const{designable:e,setDesignable:t,refresh:o,reset:r}=(0,import_react2.useContext)(SchemaComponentContext),i=(0,import_react2.useContext)(import_react.SchemaOptionsContext),n=(0,import_react2.useMemo)(()=>(i==null?void 0:i.components)||{},[i]),l=(0,import_react2.useMemo)(()=>()=>(0,import_jsx_runtime.jsx)(import_jsx_runtime.Fragment,{}),[]),a=(0,import_ahooks.useUpdate)(),c=useRefreshFieldSchema(),u=useRefreshComponent(),d=(0,import_react2.useCallback)(v=>{o==null||o(),a(),c==null||c(v),u==null||u()},[o,a,c,u]),m=(0,import_react.useField)(),p=(0,import_react.useFieldSchema)(),h=useAPIClient(),{t:g}=(0,import_react_i18next.useTranslation)(),f=(0,import_react2.useMemo)(()=>createDesignable({t:g,api:h,refresh:d,current:p,model:m,appVersion:clientPkg.version}),[g,h,d,p,m]);(0,import_react2.useEffect)(()=>{f.loadAPIClientEvents()},[f]);const{isMobileLayout:_}=useMobileLayout();return{dn:f,designable:_?!1:e,reset:r,refresh:d,setDesignable:t,DesignableBar:l,findComponent:(0,import_react2.useCallback)(v=>{var b;if(!v)return null;if(typeof v!="string")return v;const F=(0,import_get.default)(n,v);return(b=F==null?void 0:F[LAZY_COMPONENT_KEY])!=null?b:F},[import_get.default]),on:f.on.bind(f),patch:(0,import_react2.useCallback)((v,b)=>{const F=y=>{Object.keys(y).forEach(C=>{const S=y[C];C==="title"&&(m.title=S,p.title=S),C==="x-decorator-props"&&(m.decoratorProps||(m.decoratorProps={}),p["x-decorator-props"]||(p["x-decorator-props"]={}),Object.keys(S).forEach(P=>{m.decoratorProps[P]=S[P],p["x-decorator-props"][P]=S[P]})),C==="x-component-props"&&(m.componentProps||(m.componentProps={}),p["x-component-props"]||(p["x-component-props"]={}),Object.keys(S).forEach(P=>{m.componentProps[P]=S[P],p["x-component-props"][P]=S[P]}))})};if(typeof v=="string"){const y={};return(0,import_set.default)(y,v,b),F(y)}F(v),d()},[f]),shallowMerge:(0,import_react2.useCallback)(v=>{f.shallowMerge(v)},[f]),deepMerge:(0,import_react2.useCallback)(v=>{f.deepMerge(v)},[f]),remove:(0,import_react2.useCallback)((v,b)=>{f.remove(v,b)},[f]),insertAdjacent:(0,import_react2.useCallback)((v,b,F)=>{f.insertAdjacent(v,b,F)},[f]),insertBeforeBegin:(0,import_react2.useCallback)(v=>{f.insertBeforeBegin(v)},[f]),insertAfterBegin:(0,import_react2.useCallback)(v=>{f.insertAfterBegin(v)},[f]),insertBeforeEnd:(0,import_react2.useCallback)(v=>{f.insertBeforeEnd(v)},[f]),insertAfterEnd:(0,import_react2.useCallback)(v=>{f.insertAfterEnd(v)},[f])}}const DefaultSchemaToolbar=()=>null;DefaultSchemaToolbar.isNullComponent=!0;const useDesigner=()=>{const{designable:e}=useDesignable(),t=(0,import_react.useFieldSchema)(),o=(0,import_react2.useMemo)(()=>t["x-designer"]||t["x-toolbar"]?t["x-designer"]||t["x-toolbar"]:t["x-settings"]?SchemaToolbar:DefaultSchemaToolbar,[t]),r=useComponent(o);return e&&r||DefaultSchemaToolbar},useFieldProps$1=e=>{const t=(0,import_react2.useContext)(import_react.SchemaOptionsContext),o=(0,import_react2.useContext)(import_react.SchemaExpressionScopeContext),r=(0,import_react2.useRef)();return r.current=o,e.toFieldProps(I(x({},t),{get scope(){return x(x({},t.scope),r.current)}}))};function useSchemaComponentContext(){return(0,import_react2.useContext)(SchemaComponentContext)}const useFieldComponentOptions=()=>{var e;const{getCollectionJoinField:t,getCollection:o}=useCollectionManager_deprecated(),r=(0,import_react.useFieldSchema)(),{getField:i}=useCollection_deprecated(),n=i(r.name)||t(r["x-collection-field"]),{t:l}=(0,import_react_i18next.useTranslation)(),{label:a}=((e=r["x-component-props"])==null?void 0:e.fieldNames)||{};return(0,import_react2.useMemo)(()=>{if(!n||!(n!=null&&n.interface)||!["o2o","oho","obo","o2m","linkTo","m2o","m2m"].includes(n.interface))return;const c=o(n.target);if((c==null?void 0:c.template)==="file")return[{label:l("Record picker"),value:"CollectionField"},{label:l("Select"),value:"AssociationSelect"}];switch(n.interface){case"o2m":return[{label:l("Record picker"),value:"CollectionField"},{label:l("Subtable"),value:"TableField"},{label:l("Select"),value:"AssociationSelect"}];case"m2o":case"m2m":case"linkTo":return[{label:l("Record picker"),value:"CollectionField"},{label:l("Select"),value:"AssociationSelect"}];default:return[{label:l("Record picker"),value:"CollectionField"},{label:l("Subform"),value:"FormField"},{label:l("Select"),value:"AssociationSelect"}]}},[l,n==null?void 0:n.interface,a])},useFieldTitle=()=>{var e;const t=(0,import_react.useField)(),o=(0,import_react.useFieldSchema)(),r=useCollection(),i=useCollectionManager(),n=(r==null?void 0:r.getField(o.name))||(i==null?void 0:i.getCollectionField(o["x-collection-field"])),l=useCompile();(0,import_react2.useEffect)(()=>{var a;t!=null&&t.title||(t.title=l((a=n==null?void 0:n.uiSchema)==null?void 0:a.title))},[(e=n==null?void 0:n.uiSchema)==null?void 0:e.title])},useDef$4=()=>({}),useProps=(e={})=>{const t=e,{useProps:o=useDef$4}=t,r=te(t,["useProps"]);let i=o;typeof o!="function"&&(i=useDef$4);const n=i();return x(x({},r),n)};function useParsedFilter({filterOption:e,onFilterChange:t}){const{parseFilter:o,findVariable:r}=useParseDataScopeFilter(),i=JSON.stringify(e),n=(0,import_react2.useRef)(e),l=(0,import_react2.useRef)(t),[a,c]=(0,import_react2.useState)({}),[u,d]=(0,import_react2.useState)(()=>e?null:i),m=!!e&&u!==i;return n.current=e,l.current=t,(0,import_react2.useEffect)(()=>{const p=n.current;if(!p){c({}),d(i);return}let h=!1;const g=()=>L(this,null,function*(){var v;const b=yield o(p);h||(c(b),d(i),(v=l.current)==null||v.call(l,b))});g();const f=import_lodash.default.debounce(g,DEBOUNCE_WAIT),_=(0,import_reactive.reaction)(()=>(0,import_client.flatten)(p,{breakOn({key:v}){return v.startsWith("$")&&v!=="$and"&&v!=="$or"},transformValue(v){if(!isVariable$1(v))return v;const b=getVariableName(v),F=r(b);let y=null;const C=getPath(v).split(".");return C.forEach((S,P)=>{const j=C.slice(0,P+1).join("."),A=(0,import_client.getValuesByPath)({[b]:(F==null?void 0:F.ctx)||{}},j);import_lodash.default.isEmpty(A)||(y=A)}),y}}),f,{equals:import_lodash.default.isEqual});return()=>{h=!0,f.cancel(),_()}},[i,r,o]),{filter:a,parseVariableLoading:m}}const useParentRecordCommon=e=>{const t=useCollectionRecordData();if(e)return t},useTableBlockDecoratorProps=e=>{var t;const{params:o,parseVariableLoading:r}=useTableBlockParams(e),i=useParentRecordCommon(e.association),n=(t=useDataSourceManager().getDataSource(e.dataSource))==null?void 0:t.collectionManager.getCollection(e.collection);return{params:o,parentRecord:i,parseVariableLoading:r,rowKey:(n==null?void 0:n.filterTargetKey)||"id"}};function useTableBlockParams(e){var t;const o=(0,import_react.useFieldSchema)(),{filter:r,parseVariableLoading:i}=useParsedFilter({filterOption:(t=e.params)==null?void 0:t.filter});return{params:(0,import_react2.useMemo)(()=>{const n=e.params||{},{dragSortBy:l}=(o==null?void 0:o["x-decorator-props"])||{};return e.dragSort&&l&&(n.sort=l),I(x({},n),{filter:r})},[o,r,e.dragSort,e.params]),parseVariableLoading:i}}const key="__isNewRecord__",isNewRecord=e=>(0,import_reactive.untracked)(()=>!!(e!=null&&e[key])),markRecordAsNew=e=>{if(!(0,import_lodash.isObject)(e))throw new Error("markRecordAsNew: record must be an object");return e[key]=!0,e},useDefaultLoading=()=>{var e;return!!((e=useDataBlockRequest())!=null&&e.loading)},withSkeletonComponent=(e,t)=>{const{useLoading:o=useDefaultLoading,displayName:r,SkeletonComponent:i=import_antd.Skeleton}=t||{},n=import_react2.default.memo(l=>{const a=o(),c=(0,import_react2.useRef)(!1),u=(0,import_react2.useDeferredValue)(a);return!c.current&&u?(0,import_jsx_runtime.jsx)(i,{}):(c.current=!0,(0,import_jsx_runtime.jsx)(e,x({},l)))});return n.displayName=r||`${e.displayName}(withSkeletonComponent)`||`${e.name}(withSkeletonComponent)`,n},getActionValue=(e,t)=>{const o=r=>(r==null?void 0:r.mode)==="constant"?r.value:null;switch(!0){case[ActionType.Color,ActionType.BackgroundColor,ActionType.TextAlign,ActionType.FontSize,ActionType.FontWeight,ActionType.FontStyle].includes(e):return o(t);default:return null}},getSatisfiedActions=(e,t)=>L(void 0,[e,t],function*({rules:o,variables:r,localVariables:i},n){return(yield Promise.all(o.filter(l=>!l.disabled).map(l=>L(void 0,null,function*(){return(yield conditionAnalyses({ruleGroup:l.condition,variables:r,localVariables:i,conditionType:l.conditionType},n))?l:null})))).filter(Boolean).map(l=>l.actions).flat()}),getSatisfiedValues=(e,t)=>L(void 0,[e,t],function*({rules:o,variables:r,localVariables:i},n){return(yield getSatisfiedActions({rules:o,variables:r,localVariables:i},n)).map(l=>I(x({},l),{value:getActionValue(l.operator,l.value)}))}),getSatisfiedValueMap=(e,t)=>L(void 0,[e,t],function*({rules:o,variables:r,localVariables:i},n){return(yield getSatisfiedValues({rules:o,variables:r,localVariables:i},n)).reduce((l,a)=>I(x({},l),{[a.operator]:a.value}),{})});function useSatisfiedActionValues({formValues:e,category:t="default",rules:o,schema:r,form:i}){const[n,l]=(0,import_react2.useState)({}),a=(0,import_react.useFieldSchema)(),c=useVariables$1(),u=useLocalVariables$1({currentForm:{values:e}}),d=r??a,m=o??(d[LinkageRuleDataKeyMap[t]]||(d==null?void 0:d.parent[LinkageRuleDataKeyMap[t]])),p=useApp(),h=(0,import_react2.useCallback)(()=>{m&&e&&getSatisfiedValueMap({rules:m,variables:c,localVariables:u},p.jsonLogic).then(g=>{(0,import_lodash.isEmpty)(g)?l({}):l(g)}).catch(g=>{throw new Error(g.message)})},[c,u,m,e]);return(0,import_react2.useEffect)(()=>{if(h(),i){const g=(0,import_shared.uid)();return i.addEffects(g,()=>{(0,import_core.onFormValuesChange)(()=>{h()})}),()=>{i.removeEffects(g)}}},[i,h,e]),{valueMap:n}}const GetStyleRules=import_react2.default.memo(({record:e,schema:t,onStyleChange:o})=>{const{valueMap:r}=useSatisfiedActionValues({formValues:e,category:"style",schema:t});return(0,import_react2.useEffect)(()=>{o(r)},[o,r]),null});GetStyleRules.displayName="GetStyleRules";const opacityStyle={opacity:.5},containerStyle={position:"relative"},spinStyle={display:"flex",alignItems:"center",justifyContent:"center",position:"absolute",left:0,right:0,height:"100%",maxHeight:400,zIndex:1e3},displayNone$3={display:"none"},HighPerformanceSpin=import_react2.default.memo(e=>(0,import_jsx_runtime.jsxs)("div",{style:containerStyle,children:[(0,import_jsx_runtime.jsx)(import_antd.Spin,I(x({},import_lodash.default.omit(e,"children")),{style:e.spinning?spinStyle:displayNone$3})),(0,import_jsx_runtime.jsx)("div",{style:e.spinning?opacityStyle:null,children:e.children})]}));HighPerformanceSpin.displayName="HighPerformanceSpin";var FilterBlockType=(e=>(e[e.FORM=0]="FORM",e[e.TABLE=1]="TABLE",e[e.TREE=2]="TREE",e[e.COLLAPSE=3]="COLLAPSE",e))(FilterBlockType||{});const mergeFilter=(e,t="$and")=>{const o=e.filter(r=>{if(r&&typeof r=="object"&&!Array.isArray(r))return Object.values(r).filter(i=>i!==void 0).length});return o.length===0?{}:o.length===1?o[0]:{[t]:o}},getSupportFieldsByAssociation=(e,t)=>{var o;return(o=t.associatedFields)==null?void 0:o.filter(r=>e==null?void 0:e.some(i=>i===r.target))},getSupportFieldsByForeignKey=(e,t)=>{var o;return(o=t.foreignKeyFields)==null?void 0:o.filter(r=>e.fields.some(i=>i.type!=="belongsTo"&&i.foreignKey===r.name&&i.target===r.collectionName))},useSupportedBlocks=e=>{const{getDataBlocks:t}=useFilterBlock(),o=(0,import_react.useFieldSchema)(),r=useCollection(),{getAllCollectionsInheritChain:i}=useAllCollectionsInheritChainGetter();if(e===0||e===3)return t().filter(n=>isSameCollection(n.collection,r));if(e===1||e===2)return t().filter(n=>{var l,a;return o["x-uid"]!==n.uid&&(isSameCollection(n.collection,r)||((l=getSupportFieldsByAssociation(i(r.name,r.dataSource),n))==null?void 0:l.length)||((a=getSupportFieldsByForeignKey(r,n))==null?void 0:a.length))})},transformToFilter=(e,t,o,r)=>(e=(0,import_client.flatten)(e,{breakOn({value:i,path:n}){if(["$match","$notMatch","$anyOf","$noneOf","$childIn","$childNotIn","$dateBetween","$in","$notIn"].includes(t[n]))return!0;const l=o(`${r}.${n}`);if(["datetime","datetimeNoTz","date","unixTimestamp","createdAt","updatedAt"].includes(l==null?void 0:l.interface))return!0;if(l!=null&&l.target){if(Array.isArray(i))return!0;const a=l.targetKey||"id";if(i&&i[a]!=null)return!0}return!1}}),{$and:Object.keys(e).map(i=>{let n=import_lodash.default.get(e,i);const l=o(`${r}.${i}`);return l!=null&&l.target&&["hasOne","hasMany","belongsTo","belongsToMany","belongsToArray"].includes(l.type)&&(n=(0,import_client.getValuesByPath)(n,l.targetKey||"id"),i=`${i}.${l.targetKey||"id"}`,(l==null?void 0:l.interface)==="chinaRegion"&&(n=import_lodash.default.last(n))),!n&&n!==0&&n!==!1?null:{[i]:{[t[i]||"$eq"]:n}}}).filter(Boolean)}),useAssociatedFields=()=>{var e;return((e=useCollection())==null?void 0:e.fields.filter(t=>isAssocField(t)))||[]},isAssocField=e=>["o2o","oho","obo","m2o","createdBy","updatedBy","o2m","m2m","linkTo","chinaRegion","mbm"].includes(e==null?void 0:e.interface),isSameCollection=(e,t)=>e.name===t.name&&e.dataSource===t.dataSource,useFilterAPI=()=>{const e=(0,import_react.useFieldSchema)(),{getDataBlocks:t}=useFilterBlock(),{targets:o,uid:r}=findFilterTargets(e),i=t(),[n,l]=(0,import_react2.useState)(()=>o&&o.some(u=>i.some(d=>d.uid===u.uid))),a=Object.keys(o||{});(0,import_react2.useEffect)(()=>{l(o&&o.some(u=>i.some(d=>d.uid===u.uid)))},[a.length,o,i]);const c=(0,import_react2.useCallback)((u,d="id",m="$eq")=>{const p=i.find(h=>h.uid===e.parent["x-uid"]);i.forEach(h=>{var g,f,_,v;let b=d;const F=o.find(P=>P.uid===h.uid);if(!F)return;import_lodash.default.isFunction(u)&&(u=u(F,h,getSourceKey$1(p,F.field))),import_lodash.default.isFunction(d)&&(b=d(F,h)),import_lodash.default.isFunction(m)&&(m=m(F));const y=((g=h.service.params)==null?void 0:g[0])||{},C=((_=(f=h.service.params)==null?void 0:f[1])==null?void 0:_.filters)||{};if(u!=null)C[r]={$and:[{[b]:{[m]:u}}]};else if((v=h.clearSelection)==null||v.call(h),delete C[r],h.dataLoadingMode==="manual")return h.clearData();const S=mergeFilter([...Object.values(C).map(P=>removeNullCondition(P)),h.defaultFilter]);h.doFilter(I(x({},y),{page:1,filter:S}),{filters:C})})},[i,o,r,e]);return{isConnected:n,doFilter:c}},isInFilterFormBlock=e=>{for(;e;){if(e["x-filter-targets"])return e["x-decorator"]==="FilterFormBlockProvider";e=e.parent}return!1};function getSourceKey$1(e,t){var o,r,i;const n=(o=e==null?void 0:e.associatedFields)==null?void 0:o.find(l=>l.foreignKey===t);return(n==null?void 0:n.sourceKey)||((i=(r=t==null?void 0:t.split)==null?void 0:r.call(t,"."))==null?void 0:i[1])}const AssociationFieldContext=(0,import_react2.createContext)({});AssociationFieldContext.displayName="AssociationFieldContext";const useInsertSchema$1=e=>{const t=(0,import_react.useFieldSchema)(),{insertAfterBegin:o}=useDesignable(),{isMobileLayout:r}=useMobileLayout();return(0,import_react2.useCallback)(i=>{r||t.reduceProperties((n,l)=>l["x-component"]==="AssociationField."+e?l:n,null)||o((0,import_cloneDeep.default)(i))},[e,t,o,r])};function useAssociationFieldContext(){return(0,import_react2.useContext)(AssociationFieldContext)}function useServiceOptions$1(e){var t,o,r,i,n,l,a,c,u,d;const{action:m="list",service:p,useOriginalFilter:h}=e,g=(0,import_react.useFieldSchema)(),f=(0,import_react.useField)(),{getField:_}=useCollection_deprecated(),{getCollectionJoinField:v}=useCollectionManager_deprecated(),b=useRecord(),{isNew:F}=useCollectionRecord()||{},y=((0,import_lodash.isString)((r=(o=(t=g==null?void 0:g["x-component-props"])==null?void 0:t.service)==null?void 0:o.params)==null?void 0:r.filter)?(l=(n=(i=f.componentProps)==null?void 0:i.service)==null?void 0:n.params)==null?void 0:l.filter:(u=(c=(a=g==null?void 0:g["x-component-props"])==null?void 0:a.service)==null?void 0:c.params)==null?void 0:u.filter)||((d=p==null?void 0:p.params)==null?void 0:d.filter),{filter:C}=useParsedFilter({filterOption:y,onFilterChange:()=>{F&&f.reset()}}),S=(0,import_react2.useMemo)(()=>_(g.name)||v(g==null?void 0:g["x-collection-field"]),[g]),P=b==null?void 0:b[S==null?void 0:S.sourceKey],j=(0,import_react2.useMemo)(()=>{const A=["oho","o2m"].includes(S==null?void 0:S.interface);return mergeFilter([mergeFilter([A&&!isInFilterFormBlock(g)&&S!=null&&S.foreignKey&&!h?{[S.foreignKey]:{$is:null}}:null,C]),A&&P!==void 0&&P!==null&&!isInFilterFormBlock(g)&&S!=null&&S.foreignKey&&!h?{[S.foreignKey]:{$eq:P}}:null],"$or")},[S==null?void 0:S.interface,S==null?void 0:S.foreignKey,g,C,P,h]);return(0,import_react2.useMemo)(()=>I(x({resource:S==null?void 0:S.target,action:m},p),{params:I(x({},p==null?void 0:p.params),{filter:j})}),[S==null?void 0:S.target,m,j,p])}const useFieldNames$1=(e={})=>{var t,o,r,i,n;const l=(0,import_react.useFieldSchema)(),a=((i=(r=(o=(t=l["x-component-props"])==null?void 0:t.field)==null?void 0:o.uiSchema)==null?void 0:r["x-component-props"])==null?void 0:i.fieldNames)||((n=l["x-component-props"])==null?void 0:n.fieldNames)||e.fieldNames;return x({label:"label",value:"value"},a)},SubFormContext=(0,import_react2.createContext)(null);SubFormContext.displayName="SubFormContext";const SubFormProvider=e=>{const t=(0,import_react2.useContext)(SubFormContext),{value:o,collection:r,fieldSchema:i,parent:n,skip:l}=e.value,a=(0,import_react2.useMemo)(()=>import_lodash.default.omitBy({value:o,collection:r,fieldSchema:i,skip:l,parent:n||(t!=null&&t.skip?t.parent:t)},import_lodash.default.isUndefined),[o,r,i,l,n,t]);return(0,import_jsx_runtime.jsx)(SubFormContext.Provider,{value:a,children:e.children})},useSubFormValue=()=>{const{value:e,collection:t,fieldSchema:o,parent:r}=(0,import_react2.useContext)(SubFormContext)||{};return{formValue:e,collection:t,fieldSchema:o,parent:r}},TableUidContext=(0,import_react2.createContext)(null),useColumnSettings=e=>{const{t}=(0,import_react_i18next.useTranslation)(),o=(0,import_react2.useContext)(TableUidContext),r=`nocobase_table_column_settings_${o}`,i=(0,import_react2.useCallback)(()=>{try{const a=localStorage.getItem(r);return a?JSON.parse(a):null}catch(a){return console.warn("Failed to parse table column settings from localStorage:",a),null}},[r]),n=(0,import_react2.useCallback)(a=>{try{const c=JSON.stringify(a);localStorage.setItem(r,c);const u=new CustomEvent("nocobase-table-settings-changed",{detail:{key:r,tableId:o,settings:a}});window.dispatchEvent(u)}catch(c){console.warn("Failed to save table column settings to localStorage:",c),import_antd.message.error(t("Failed to save table settings"))}},[r,o,t]),l=(0,import_react2.useCallback)(()=>{try{localStorage.removeItem(r);const a=new CustomEvent("nocobase-table-settings-changed",{detail:{key:r,tableId:o,settings:null}});window.dispatchEvent(a)}catch(a){console.warn("Failed to clear table column settings from localStorage:",a),import_antd.message.error(t("Failed to clear table settings"))}},[r,o,t]);return{getSettings:i,saveSettings:n,clearSettings:l}},useTableColumnIntegration=(e,t=!0)=>{const o=(0,import_react2.useContext)(TableUidContext),{getSettings:r}=useColumnSettings(),[i,n]=(0,import_react2.useState)(0);(0,import_react2.useEffect)(()=>{const a=c=>{const{key:u,tableId:d}=c.detail;(u.includes(o)||d===o)&&n(m=>m+1)};return window.addEventListener("nocobase-table-settings-changed",a),()=>{window.removeEventListener("nocobase-table-settings-changed",a)}},[o]);const l=(0,import_react2.useMemo)(()=>r(),[r,i]);return{columns:(0,import_react2.useMemo)(()=>{if(!t||!l||l.length===0)return e;const a=new Map;l.forEach(p=>{a.set(p.key,p)});const c=e.map(p=>{const h=a.get(p.key);if(h){const g=p.columnHidden||!h.visible,f=h.width||p.width,_=h.fixed||p.fixed;return I(x({},p),{columnHidden:g,fixed:_,width:f,_orderIndex:h.order})}return p}),u=[],d=[];c.forEach(p=>{p._orderIndex!==void 0?u.push(p):d.push(p)}),u.sort((p,h)=>(p._orderIndex||0)-(h._orderIndex||0));const m=[...u,...d];return m.forEach(p=>{delete p._orderIndex}),m},[e,l])}},TableSkeleton=({rows:e=5,columns:t=6})=>{const{token:o}=useToken$1(),r=o.controlHeight*2.06,i=o.controlHeight*1.75,n=(0,import_react2.useMemo)(()=>import_css.css`
66
66
  &.skeleton-wrapper {
67
67
  width: 100%;
68
68
  background: ${o.colorBgContainer};
@@ -1825,7 +1825,7 @@ if (!ctx.record) {
1825
1825
  flex-shrink: 0;
1826
1826
  flex: 1;
1827
1827
  }
1828
- `},properties:{name:{type:"string","x-decorator":"FormItem","x-component":"Input","x-component-props":{placeholder:'{{t("Name")}}'}},value:{type:"string","x-decorator":"FormItem","x-component":TextAreaWithContextSelector,"x-component-props":{rows:1}},remove:{type:"void","x-decorator":"FormItem","x-component":"ArrayItems.Remove"}}}}},"x-reactions":{dependencies:["mode"],fulfill:{state:{hidden:'{{$deps[0] === "html"}}'}}},properties:{add:{type:"void",title:'{{t("Add parameter")}}',"x-component":"ArrayItems.Addition"}}},openInNewWindow:{type:"boolean","x-content":t("Open in new window"),"x-decorator":"FormItem","x-component":"Checkbox","x-reactions":{dependencies:["mode"],fulfill:{state:{hidden:'{{$deps[0] === "html"}}'}}}}}},handler(e,t){e.model.setProps({url:t.url,searchParams:t.searchParams,openInNewWindow:t.openInNewWindow})}}}});class ExpandCollapseActionModel extends ActionModel{constructor(){super(...arguments),R(this,"expandFlag"),R(this,"defaultProps",{type:"default",icon:"DownOutlined"})}setTitle(t){this.setProps({title:t})}setExpandFlag(t){this.expandFlag=t}getTitle(){return this.expandFlag?this.context.t("Collapse all"):this.context.t("Expand all")}getIcon(){return this.expandFlag?"NodeCollapseOutlined":"NodeExpandOutlined"}}R(ExpandCollapseActionModel,"scene",ActionSceneEnum.collection);function getIdsWithChildren(e,{idKey:t="id",childrenKey:o="children"}={}){const r=[];function i(n){if(Array.isArray(n))for(const l of n){const a=l[o];r.push(l[t]),Array.isArray(a)&&a.length>0&&i(a)}}return i(e),r}const allIncludesChildren=e=>getIdsWithChildren(e);ExpandCollapseActionModel.registerFlow({key:"expandCollapseSettingsInit",sort:200,steps:{init:{handler(e,t){e.blockModel.props.defaultExpandAllRows?e.model.setExpandFlag(!0):e.model.setExpandFlag(!1)}}}});ExpandCollapseActionModel.registerFlow({key:"expandCollapseSettings",on:"click",steps:{expandCollapse:{handler(e,t){return L(this,null,function*(){var o;if(!((o=e.blockModel)!=null&&o.resource))return;const r=e.blockModel.resource,{treeTable:i}=e.blockModel.props;if(i)if(e.model.expandFlag)e.blockModel.setProps({expandedRowKeys:[]}),e.model.setExpandFlag(!1);else{const n=allIncludesChildren(r.getData());e.blockModel.setProps({expandedRowKeys:n}),e.model.setExpandFlag(!0)}})}}}});ExpandCollapseActionModel.define({label:(0,import_flow_engine.escapeT)("Expand/Collapse"),hide(e){var t;return((t=e.collection)==null?void 0:t.template)!=="tree"||e.model.props.treeTable===!1}});class AddChildActionModel extends PopupActionModel{constructor(){super(...arguments),R(this,"defaultProps",{type:"link",title:(0,import_flow_engine.tExpr)("Add child"),icon:"PlusOutlined"})}getAclActionName(){return"create"}onInit(t){super.onInit(t),this.context.defineProperty("association",{get:()=>this.context.blockModel.dataSource.getAssociation(`${this.context.blockModel.collection.name}.children`)})}}R(AddChildActionModel,"capabilityActionName",null);AddChildActionModel.registerFlow({key:"addChildSettingsInit",steps:{addChildInit:{handler(e,t){return L(this,null,function*(){e.model.onClick=o=>{e.model.dispatchEvent("click",I(x({event:o},e.inputArgs),{sourceId:e.record.id,filterByTk:null}),{debounce:!0})}})}}}});AddChildActionModel.define({label:(0,import_flow_engine.tExpr)("Add child"),hide(e){var t;return((t=e.collection)==null?void 0:t.template)!=="tree"||e.blockModel.props.treeTable===!1}});RecordActionGroupModel.registerActionModels({AddChildActionModel});const SAVE_STEP_PARAMS_WITH_SUB_MODELS_FLAG="__saveStepParamsWithSubModels";function markSaveStepParamsWithSubModels(e){if(!e||typeof e!="object"&&typeof e!="function")throw new Error("[saveStepParamsWithSubModels] model is not an object");e[SAVE_STEP_PARAMS_WITH_SUB_MODELS_FLAG]=!0}function saveStepParamsWithSubModelsIfNeeded(e,t){return L(this,null,function*(){if(!e||typeof e!="object"&&typeof e!="function")throw new Error("[saveStepParamsWithSubModels] model is not an object");const o=e;if(o[SAVE_STEP_PARAMS_WITH_SUB_MODELS_FLAG]!==!0)return yield t();if(typeof o.save!="function")throw new Error("[saveStepParamsWithSubModels] model.save is not a function");try{return yield o.save()}finally{delete o[SAVE_STEP_PARAMS_WITH_SUB_MODELS_FLAG]}})}function evaluateCondition(e,t){const o=(r,i,n)=>{var l,a,c;return i?(c=(a=(l=e==null?void 0:e.app)==null?void 0:l.jsonLogic)==null?void 0:a.apply)==null?void 0:c.call(a,{[i]:[r,n]}):!0};try{return(0,import_client.evaluateConditions)((0,import_client.removeInvalidFilterItems)(t),o)}catch{return!1}}function parsePathString(e){const t=[];let o=0;const r=e.length,i=()=>{const n=o;for(;o<r&&e[o]!=="."&&e[o]!=="[";)o++;const l=e.slice(n,o);l&&t.push(l)};for(;o<r;){const n=e[o];if(n==="."){o++;continue}if(n==="["){o++;const l=o;for(;o<r&&e[o]!=="]";)o++;const a=e.slice(l,o);o++,/^\d+$/.test(a)?t.push(Number(a)):a&&t.push({placeholder:a});continue}i()}return t}function parseFieldIndexEntries(e){const t=Array.isArray(e)?e:[],o=[];for(const r of t){if(typeof r!="string")continue;const[i,n]=r.split(":"),l=Number(n);!i||Number.isNaN(l)||o.push({name:i,index:l})}return o}function resolveDynamicNamePath(e,t){const o=Array.isArray(e)?[...e]:parsePathString(e),r=parseFieldIndexEntries(t),i=[];let n=0;for(let l=0;l<o.length;l++){const a=o[l];if(typeof a=="object"&&a&&"placeholder"in a){const c=i[i.length-1],u=typeof c=="string"?c:void 0;if(!u)return null;for(;n<r.length&&r[n].name!==u;)n++;if(n>=r.length)return null;i.push(r[n].index),n++;continue}if(i.push(a),typeof a=="string"&&n<r.length&&r[n].name===a){const c=o[l+1];typeof c=="number"?n++:typeof c=="object"&&c&&"placeholder"in c||(i.push(r[n].index),n++)}}return i}function namePathToPathKey(e){let t="";for(const o of e){if(typeof o=="number"){t+=`[${o}]`;continue}t?t+=`.${o}`:t=o}return t}function pathKeyToNamePath(e){return parsePathString(e).filter(t=>typeof t!="object")}function buildAncestorKeys(e){const t=[],o=[];for(const r of e)o.push(r),t.push(namePathToPathKey(o));return t}function shouldProxyObjectValue(e){return!e||typeof e!="object"?!1:Array.isArray(e)||import_lodash.default.isPlainObject(e)}function recordDep(e,t){if(t)for(const o of buildAncestorKeys(e))t.deps.add(`fv:${o}`)}function createFormValuesProxy(e){const{valuesMirror:t,collector:o,basePath:r,getFormValuesSnapshot:i,getFormValueAtPath:n}=e,l=()=>r.length?import_lodash.default.get(t,r):t,a=l(),c=a&&(typeof a=="object"||typeof a=="function")?a:Array.isArray(a)?[]:{},u=d=>createFormValuesProxy({valuesMirror:t,basePath:d,collector:o,getFormValuesSnapshot:i,getFormValueAtPath:n});return new Proxy(c,{get(d,m){if(m==="toJSON")return o&&(o.wildcard=!0),r.length===0?()=>i():()=>(0,import_reactive.toJS)(l());if(typeof m=="symbol"){o&&(o.wildcard=!0);const b=l();return b==null?void 0:b[m]}const p=l();if(p==null)return;if(m==="__raw")return p;if(m==="__proto__"||m==="prototype"||m==="constructor"){o&&(o.wildcard=!0);return}const h=Array.isArray(p),g=h&&(typeof m=="number"&&Number.isInteger(m)||typeof m=="string"&&/^\d+$/.test(m));if(h&&!g){o&&(o.wildcard=!0);const b=p[m];return typeof b=="function"?b.bind(p):b}const f=g?Number(m):m,_=[...r,f];recordDep(_,o);let v=p[m];if(typeof v>"u"){const b=n(_);import_lodash.default.isEqual(b,v)||(import_lodash.default.set(t,_,b),v=b)}return v==null||typeof v!="object"?v:shouldProxyObjectValue(v)?u(_):v},ownKeys(){o&&(o.wildcard=!0);const d=l();return d?Reflect.ownKeys(d):[]},getOwnPropertyDescriptor(d,m){const p=l();if(p)return Object.getOwnPropertyDescriptor(p,m)},has(d,m){const p=l();return p?m in p:!1}})}function collectStaticDepsFromTemplateValue(e,t){try{const o=(0,import_flow_engine.extractUsedVariablePaths)(e)||{};for(const[r,i]of Object.entries(o)){const n=Array.isArray(i)?i:[],l=n.length?n:[""];for(const a of l){if(r==="formValues"){if(!a){t.wildcard=!0;continue}const u=parsePathString(String(a)).filter(d=>typeof d!="object");recordDep(u,t);continue}const c=a?`ctx:${r}:${String(a)}`:`ctx:${r}`;t.deps.add(c)}}}catch{}}function collectStaticDepsFromRunJSValue(e,t){if((0,import_flow_engine.isRunJSValue)(e))try{const o=(0,import_flow_engine.extractUsedVariablePathsFromRunJS)(e.code)||{};for(const[r,i]of Object.entries(o)){const n=Array.isArray(i)?i:[],l=n.length?n:[""];for(const a of l){if(r==="formValues"){if(!a){t.wildcard=!0;continue}const u=parsePathString(String(a)).filter(d=>typeof d!="object");recordDep(u,t);continue}const c=a?`ctx:${r}:${String(a)}`:`ctx:${r}`;t.deps.add(c)}}}catch{}}function createFormPatcher(e){let t,o,r;const i=()=>{const n=t;n&&(o&&(n.setFieldValue=o),r&&(n.setFieldsValue=r),t=void 0,o=void 0,r=void 0)};return{patch:n=>{if(t===n)return;i();const l=typeof(n==null?void 0:n.setFieldValue)=="function"?n.setFieldValue.bind(n):void 0,a=typeof(n==null?void 0:n.setFieldsValue)=="function"?n.setFieldsValue.bind(n):void 0;t=n,o=l,r=a,l&&(n.setFieldValue=(c,u)=>{if(e.isSuppressed()){l(c,u);return}e.setFormValues(e.getCallerContext(),[{path:c,value:u}],{source:"system"}).catch(()=>{})}),a&&(n.setFieldsValue=c=>{if(e.isSuppressed()){a(c);return}e.setFormValues(e.getCallerContext(),c,{source:"system"}).catch(()=>{})})},restore:i}}const MAX_WRITES_PER_PATH_PER_TX=20;function isEmptyValue(e){return e==null?!0:typeof e=="string"||Array.isArray(e)?e.length===0:import_lodash.default.isPlainObject(e)?Object.keys(e).length===0:!1}function createTxId(){return`${Date.now()}-${Math.random().toString(16).slice(2)}`}const SKIP_RULE_VALUE=Symbol("SKIP_RULE_VALUE"),UNRESOLVED_ASSOCIATION_IDENTITY=Symbol("UNRESOLVED_ASSOCIATION_IDENTITY"),LINKAGE_DEFAULT_RULE_PRIORITY=1e3;class RuleEngine{constructor(t){R(this,"options"),R(this,"rules",new Map),R(this,"lastRuleWriteByTargetKey",new Map),R(this,"assignTemplatesByTargetPath",new Map),R(this,"formItemTargetPaths",new Set),R(this,"updateAssociationByTargetPath",new Map),R(this,"pendingRuleIds",new Set),R(this,"ruleDebounceUntilById",new Map),R(this,"ruleDebounceTimersById",new Map),R(this,"defaultRuleIdsByMasterUid",new Map),R(this,"defaultRuleMasterDisposers",new Map),R(this,"runningRules",!1),R(this,"rulesEnabled",!1),R(this,"currentRuleTxId",null),this.options=t}getAssignRuleBlockId(t){return`form-assign:${t}:block`}removeAssignRuleBlockInstance(t){const o=this.getAssignRuleBlockId(t);this.rules.has(o)&&this.removeRule(o)}removeRowGridAssignRuleInstances(t){var o,r;const i=`form-assign:${t}:`,n=this.getAssignRuleBlockId(t),l=[];for(const[a,c]of this.rules.entries()){if(!a.startsWith(i)||a===n)continue;const u=(r=(o=c==null?void 0:c.rule)==null?void 0:o.getContext)==null?void 0:r.call(o),d=u==null?void 0:u.model;d&&this.isRowGridModel(d)&&l.push(a)}for(const a of l)this.removeRule(a)}hasAnyNonBlockAssignRuleInstance(t){const o=`form-assign:${t}:`,r=this.getAssignRuleBlockId(t);for(const i of this.rules.keys())if(i.startsWith(o)&&i!==r)return!0;return!1}ensureBlockAssignRuleInstancesForTargetPath(t){if(this.options.isDisposed()||!t||!this.shouldCreateBlockLevelAssignRule(t))return;const o=this.assignTemplatesByTargetPath.get(t)||[];if(o.length)for(const r of o){const i=r!=null&&r.__key?String(r.__key):"";if(!i||this.hasAnyNonBlockAssignRuleInstance(i))continue;const n=((r==null?void 0:r.mode)==="default"?"default":"assign")=="default"?"default":"system",l=(r==null?void 0:r.enable)!==!1,a=this.getAssignRuleBlockId(i);if(this.rules.has(a))continue;const c={id:a,source:n,priority:10+(r.__order||0),debounceMs:0,getEnabled:()=>l&&!!t,getTarget:()=>t,getValue:()=>r==null?void 0:r.value,getCondition:()=>r==null?void 0:r.condition,getContext:()=>this.options.getBlockContext()};this.rules.set(a,{rule:c,state:{deps:new Set,depDisposers:[],runSeq:0,scheduledAtWriteSeq:0}}),this.scheduleRule(a)}}getCollectionFromContext(t){var o,r,i;return(i=t==null?void 0:t.collection)!=null?i:(r=(o=t==null?void 0:t.model)==null?void 0:o.context)==null?void 0:r.collection}getRootCollection(){const t=this.options.getBlockContext();return this.getCollectionFromContext(t)}shouldCreateBlockLevelAssignRule(t){var o,r;const i=this.options.getBlockContext();let n=this.getCollectionFromContext(i);if(!(n!=null&&n.getField))return!0;const l=parsePathString(t).filter(a=>typeof a!="object");if(l.length<=1)return!0;for(let a=0;a<l.length-1;a++){const c=l[a];if(typeof c!="string")continue;const u=(o=n==null?void 0:n.getField)==null?void 0:o.call(n,c);if(!((r=u==null?void 0:u.isAssociationField)!=null&&r.call(u)))break;if(isToManyAssociationField(u)){if(typeof l[a+1]!="number")return!1;a+=1}if(n=u==null?void 0:u.targetCollection,!(n!=null&&n.getField))break}return!0}collectAssociationPrefixPaths(t,o){var r,i;const n=[];let l=this.getRootCollection()||this.getCollectionFromContext(t);if(!(l!=null&&l.getField))return n;const a=[];for(let c=0;c<o.length-1;c++){const u=o[c];if(typeof u!="string")break;const d=(r=l==null?void 0:l.getField)==null?void 0:r.call(l,u);if(!((i=d==null?void 0:d.isAssociationField)!=null&&i.call(d)))break;if(a.push(u),isToManyAssociationField(d)){const m=o[c+1];if(typeof m!="number")break;a.push(m),c+=1}if(n.push([...a]),l=d==null?void 0:d.targetCollection,!(l!=null&&l.getField))break}return n}shouldSkipToManyAssociationWriteWithoutIndex(t,o){var r,i;let n=this.getRootCollection()||this.getCollectionFromContext(t);if(!(n!=null&&n.getField))return!1;for(let l=0;l<o.length-1;l++){const a=o[l];if(typeof a!="string")continue;const c=(r=n==null?void 0:n.getField)==null?void 0:r.call(n,a);if(!((i=c==null?void 0:c.isAssociationField)!=null&&i.call(c)))break;if(isToManyAssociationField(c)){if(typeof o[l+1]!="number")return!0;l+=1}if(n=c==null?void 0:c.targetCollection,!(n!=null&&n.getField))break}return!1}shouldSkipAssociationNestedWrite(t,o){const r=this.collectAssociationPrefixPaths(t,o);if(!r.length)return!1;for(const i of r){const n=this.options.getFormValueAtPath(i);if(n==null){const l=i.filter(a=>typeof a=="string").join(".");if(l&&this.getUpdateAssociationForTargetPath(l)||this.isAssociationTargetKeyWrite(t,o,i))continue;return!0}if(typeof n!="object")return!0}return!1}getAssociationTargetKeyFields(t){var o,r,i,n,l;const a=(l=(n=(r=t==null?void 0:t.targetKey)!=null?r:(o=t==null?void 0:t.targetCollection)==null?void 0:o.filterTargetKey)!=null?n:(i=t==null?void 0:t.targetCollection)==null?void 0:i.filterByTk)!=null?l:"id";return Array.isArray(a)?a.filter(c=>typeof c=="string"&&!!c):typeof a=="string"&&a?[a]:["id"]}resolveAssociationFieldByPrefixPath(t,o){var r,i;let n=this.getRootCollection()||this.getCollectionFromContext(t);if(!(n!=null&&n.getField))return null;let l=null;for(const a of o){if(typeof a=="number")continue;if(typeof a!="string"||!a)break;const c=(r=n==null?void 0:n.getField)==null?void 0:r.call(n,a);if(!((i=c==null?void 0:c.isAssociationField)!=null&&i.call(c))||(l=c,n=c==null?void 0:c.targetCollection,!(n!=null&&n.getField)))break}return l}isAssociationTargetKeyWrite(t,o,r){var i;if(!Array.isArray(o)||!Array.isArray(r)||o.length!==r.length+1)return!1;const n=o[r.length];if(typeof n!="string"||!n)return!1;const l=this.resolveAssociationFieldByPrefixPath(t,r);return!((i=l==null?void 0:l.isAssociationField)!=null&&i.call(l))||isToManyAssociationField(l)?!1:this.getAssociationTargetKeyFields(l).includes(n)}collectUpdateAssociationInitPatches(t,o){const r=this.collectAssociationPrefixPaths(t,o);if(!r.length)return[];const i=[];for(const l of r){const a=this.options.getFormValueAtPath(l);if(a==null){const c=l.filter(u=>typeof u=="string").join(".");if(!c)return null;if(this.getUpdateAssociationForTargetPath(c)){i.push({path:[...l,"__is_new__"],value:!0});continue}if(this.isAssociationTargetKeyWrite(t,o,l)){i.push({path:[...l],value:{}});continue}return null}if(typeof a!="object")return null}const n=new Map;for(const l of i){const a=namePathToPathKey(l.path);n.has(a)||n.set(a,l)}return Array.from(n.values())}dispose(){for(const{state:t}of this.rules.values())t.depDisposers.forEach(o=>o());this.rules.clear(),this.pendingRuleIds.clear(),this.assignTemplatesByTargetPath.clear();for(const t of this.defaultRuleMasterDisposers.values())t();this.defaultRuleMasterDisposers.clear(),this.defaultRuleIdsByMasterUid.clear();for(const t of this.ruleDebounceTimersById.values())clearTimeout(t);this.ruleDebounceTimersById.clear(),this.ruleDebounceUntilById.clear()}enable(){this.rulesEnabled=!0,this.pendingRuleIds.size&&!this.runningRules&&this.flushRules()}syncAssignRules(t){if(this.options.isDisposed())return;const o=(Array.isArray(t)?t:[]).map((a,c)=>I(x({},a),{key:a!=null&&a.key?String(a.key):`idx:${c}`})),r="form-assign:";for(const a of Array.from(this.rules.keys()))a.startsWith(r)&&this.removeRule(a);this.assignTemplatesByTargetPath.clear(),this.formItemTargetPaths.clear(),this.updateAssociationByTargetPath.clear();let i=0;for(const a of o){const c=a!=null&&a.targetPath?String(a.targetPath):"";if(!c)continue;const u=this.assignTemplatesByTargetPath.get(c)||[];i+=1,u.push(I(x({},a),{__key:String(a.key),__order:i})),this.assignTemplatesByTargetPath.set(c,u)}const n=this.options.getEngine(),l=new Set;if(n!=null&&n.forEachModel){n.forEachModel(c=>{var u;if(!this.isModelInThisForm(c)||!((u=c==null?void 0:c.subModels)!=null&&u.field))return;const d=this.getModelTargetPath(c);d&&this.formItemTargetPaths.add(d),this.cacheUpdateAssociationForModel(c)});const a=c=>{this.cacheUpdateAssociationForModel(c),this.tryRegisterAssignRuleInstancesForModel(c,l);const u=c==null?void 0:c.forks;u&&typeof u.forEach=="function"&&u.forEach(d=>{!d||d!=null&&d.disposed||this.tryRegisterAssignRuleInstancesForModel(d,l)})};n.forEachModel(c=>{a(c)})}for(const[a,c]of this.assignTemplatesByTargetPath.entries())if(!l.has(a)&&this.shouldCreateBlockLevelAssignRule(a))for(const u of c){const d=((u==null?void 0:u.mode)==="default"?"default":"assign")=="default"?"default":"system",m=(u==null?void 0:u.enable)!==!1,p=`${r}${u.__key}:block`;this.rules.has(p)&&this.removeRule(p);const h={id:p,source:d,priority:10+(u.__order||0),debounceMs:0,getEnabled:()=>m&&!!a,getTarget:()=>a,getValue:()=>u==null?void 0:u.value,getCondition:()=>u==null?void 0:u.condition,getContext:()=>this.options.getBlockContext()};this.rules.set(p,{rule:h,state:{deps:new Set,depDisposers:[],runSeq:0,scheduledAtWriteSeq:0}}),this.scheduleRule(p)}for(const a of Array.from(this.rules.keys()))a.startsWith("default:")&&this.scheduleRule(a)}onModelMounted(t){var o;if(this.isModelInThisForm(t)&&!(t!=null&&t.isFork)&&(o=t==null?void 0:t.subModels)!=null&&o.field){const r=this.getModelTargetPath(t);r&&this.formItemTargetPaths.add(r),this.cacheUpdateAssociationForModel(t)}this.tryRegisterDefaultRuleInstance(t),this.tryRegisterAssignRuleInstancesForModel(t)}onModelUnmounted(t){var o;if(this.tryUnregisterDefaultRuleInstance(t),this.tryUnregisterAssignRuleInstancesForModel(t),this.isModelInThisForm(t)&&(o=t==null?void 0:t.subModels)!=null&&o.field){const r=this.getModelTargetPath(t);if(r&&(this.ensureBlockAssignRuleInstancesForTargetPath(r),!(t!=null&&t.isFork))){this.updateAssociationByTargetPath.delete(r),this.formItemTargetPaths.delete(r);const i=`${r}.`;for(const l of this.assignTemplatesByTargetPath.keys())l.startsWith(i)&&this.ensureBlockAssignRuleInstancesForTargetPath(l);const n=this.options.getEngine();if(n!=null&&n.forEachModel){const l=a=>{this.tryRegisterAssignRuleInstancesForModel(a);const c=a==null?void 0:a.forks;c&&typeof c.forEach=="function"&&c.forEach(u=>{!u||u!=null&&u.disposed||this.tryRegisterAssignRuleInstancesForModel(u)})};n.forEachModel(a=>l(a))}}}}isModelInThisForm(t){var o;const r=(o=t==null?void 0:t.context)==null?void 0:o.blockModel;return r?String(r.uid)===String(this.options.getBlockModelUid()):!1}cacheUpdateAssociationForModel(t){var o,r;if(this.options.isDisposed()||!this.isModelInThisForm(t)||!t||typeof t!="object"||t!=null&&t.isFork||!((o=t==null?void 0:t.subModels)!=null&&o.field))return;const i=this.getModelTargetPath(t);if(!i)return;const n=(r=t==null?void 0:t.subModels)==null?void 0:r.field,l=!!(n!=null&&n.updateAssociation);this.updateAssociationByTargetPath.get(i)!==!0&&this.updateAssociationByTargetPath.set(i,l)}getUpdateAssociationForTargetPath(t){const o=String(t||"");if(!o)return!1;if(this.updateAssociationByTargetPath.has(o))return!!this.updateAssociationByTargetPath.get(o);const r=this.options.getEngine();return r!=null&&r.forEachModel&&r.forEachModel(i=>{this.cacheUpdateAssociationForModel(i)}),this.updateAssociationByTargetPath.has(o)?!!this.updateAssociationByTargetPath.get(o):(this.updateAssociationByTargetPath.set(o,!1),!1)}getDefaultRuleId(t){var o;const r=t!=null&&t.isFork?String((o=t==null?void 0:t.forkId)!=null?o:"fork"):"master";return`default:${t!=null&&t.uid?String(t.uid):String(t)}:${r}`}getModelTargetNamePath(t){var o;const r=(o=t==null?void 0:t.context)==null?void 0:o.fieldPathArray;if(Array.isArray(r)&&r.length)return r;const i=typeof(t==null?void 0:t.getProps)=="function"?t.getProps():t==null?void 0:t.props,n=i==null?void 0:i.name;return Array.isArray(n)?n:typeof n=="string"?n.includes(".")?n.split("."):[n]:null}getAssignTemplateTargetPathForModel(t){const o=this.getModelTargetPath(t);if(o)return o;const r=this.getModelTargetNamePath(t);if(!(r!=null&&r.length))return"";const i=r.filter(n=>typeof n!="number");return i.length?namePathToPathKey(i):""}hasAssignTemplateForTargetPath(t){const o=String(t||"");return o?this.assignTemplatesByTargetPath.has(o):!1}tryRegisterDefaultRuleInstance(t){if(this.options.isDisposed()||!this.isModelInThisForm(t)||!t||typeof t!="object")return;const o=typeof t.getProps=="function"?t.getProps():t.props;if(!o||typeof o!="object")return;const r=this.getModelTargetNamePath(t);if(!r)return;const i=this.getDefaultRuleId(t);if(this.rules.has(i))return;const n=t.master||t,l=this.getAssignTemplateTargetPathForModel(t);this.bindMasterInitialValue(n,i);const a=()=>{var g,f;const _=(f=(g=n==null?void 0:n.getProps)==null?void 0:g.call(n))!=null?f:n==null?void 0:n.props;return _==null?void 0:_.initialValue},c=a();let u=!1;const d=()=>{const g=a();if(!u&&!import_lodash.default.isEqual(g,c)&&(u=!0),!this.hasAssignTemplateForTargetPath(l)||u||typeof c>"u")return g},m=()=>typeof d()<"u"?LINKAGE_DEFAULT_RULE_PRIORITY:0,p=()=>{var g,f,_,v;if(!this.hasAssignTemplateForTargetPath(l))try{const b=(f=(g=n==null?void 0:n.getStepParams)==null?void 0:g.call(n,"editItemSettings","initialValue"))==null?void 0:f.defaultValue;if(typeof b<"u")return b;const F=(v=(_=n==null?void 0:n.getStepParams)==null?void 0:_.call(n,"formItemSettings","initialValue"))==null?void 0:v.defaultValue;if(typeof F<"u")return F}catch{}},h={id:i,source:"default",priority:m(),debounceMs:0,getEnabled:()=>typeof d()<"u"?!0:typeof p()<"u",getTarget:()=>this.getModelTargetNamePath(t)||r,getValue:()=>{const g=d();return typeof g<"u"?g:p()},getContext:()=>t==null?void 0:t.context};this.rules.set(i,{rule:h,state:{deps:new Set,depDisposers:[],runSeq:0,scheduledAtWriteSeq:0}}),this.scheduleRule(i)}getModelTargetPath(t){var o;try{const n=(o=t==null?void 0:t.getStepParams)==null?void 0:o.call(t,"fieldSettings","init"),l=n==null?void 0:n.fieldPath;if(l)return String(l)}catch{}const r=t==null?void 0:t.fieldPath;if(r)return String(r);const i=this.getModelTargetNamePath(t);return i!=null&&i.length&&i.filter(n=>typeof n=="string").join(".")||null}getAssignRuleInstanceId(t,o){var r;const i=o!=null&&o.isFork?String((r=o==null?void 0:o.forkId)!=null?r:"fork"):"master",n=o!=null&&o.uid?String(o.uid):String(o);return`form-assign:${t}:${n}:${i}`}getDeepestFieldIndexKey(t){var o,r,i;const n=(i=(r=(o=t==null?void 0:t.model)==null?void 0:o.context)==null?void 0:r.fieldIndex)!=null?i:t==null?void 0:t.fieldIndex,l=Array.isArray(n)?n:[];if(!l.length)return null;const a=l[l.length-1];if(typeof a!="string")return null;const[c,u]=a.split(":");if(!c)return null;const d=Number(u);return Number.isNaN(d)?null:c}getDeepestToManyAssociationKey(t){var o,r;const i=this.getRootCollection();if(!(i!=null&&i.getField))return null;const n=parsePathString(String(t||"")).filter(c=>typeof c!="object");if(n.length<2)return null;let l=i,a=null;for(let c=0;c<n.length-1;c++){const u=n[c];if(typeof u!="string")continue;const d=(o=l==null?void 0:l.getField)==null?void 0:o.call(l,u);if(!((r=d==null?void 0:d.isAssociationField)!=null&&r.call(d)))break;const m=isToManyAssociationField(d);if(m&&(a=u),m&&typeof n[c+1]=="number"&&(c+=1),l=d==null?void 0:d.targetCollection,!(l!=null&&l.getField))break}return a}isRowGridModel(t){var o,r;if(!t||typeof t!="object"||(o=t==null?void 0:t.subModels)!=null&&o.field||!((r=t==null?void 0:t.subModels)!=null&&r.items))return!1;const i=t==null?void 0:t.context;return!!this.getDeepestFieldIndexKey(i)}tryRegisterAssignRuleInstancesForModel(t,o){var r,i,n,l;if(this.options.isDisposed()||!this.isModelInThisForm(t))return;const a=(g,f)=>{var _;if(!(!f||f.length===0)){o==null||o.add(g);for(const v of f){this.removeAssignRuleBlockInstance(v.__key),(_=t==null?void 0:t.subModels)!=null&&_.field&&this.removeRowGridAssignRuleInstances(v.__key);const b=((v==null?void 0:v.mode)==="default"?"default":"assign")=="default"?"default":"system",F=(v==null?void 0:v.enable)!==!1,y=this.getAssignRuleInstanceId(v.__key,t);this.rules.has(y)&&this.removeRule(y);const C={id:y,source:b,priority:10+(v.__order||0),debounceMs:0,getEnabled:()=>F&&!!g,getTarget:()=>g,getValue:()=>v==null?void 0:v.value,getCondition:()=>v==null?void 0:v.condition,getContext:()=>t==null?void 0:t.context};this.rules.set(y,{rule:C,state:{deps:new Set,depDisposers:[],runSeq:0,scheduledAtWriteSeq:0}}),this.scheduleRule(y)}}};if(this.isRowGridModel(t)){const g=t==null?void 0:t.context,f=this.getDeepestFieldIndexKey(g);if(f)for(const[_,v]of this.assignTemplatesByTargetPath.entries()){if(this.formItemTargetPaths.has(_))continue;const b=this.getDeepestToManyAssociationKey(_);!b||b!==f||a(_,v)}return}if(!((r=t==null?void 0:t.subModels)!=null&&r.field))return;const c=this.getModelTargetPath(t);if(!c)return;const u=this.assignTemplatesByTargetPath.get(c)||[];u.length&&a(c,u);const d=(i=t==null?void 0:t.subModels)==null?void 0:i.field,m=(n=d==null?void 0:d.context)==null?void 0:n.collectionField,p=!!((l=m==null?void 0:m.isAssociationField)!=null&&l.call(m)),h=isToManyAssociationField(m);if(p&&!h){const g=`${c}.`;for(const[f,_]of this.assignTemplatesByTargetPath.entries())!f||typeof f!="string"||f.startsWith(g)&&a(f,_)}}tryUnregisterAssignRuleInstancesForModel(t){var o,r,i,n;if(this.options.isDisposed()||!this.isModelInThisForm(t))return;const l=h=>{for(const g of h||[]){const f=this.getAssignRuleInstanceId(g.__key,t);this.rules.has(f)&&this.removeRule(f)}};if(this.isRowGridModel(t)){const h=t==null?void 0:t.context,g=this.getDeepestFieldIndexKey(h);if(!g)return;for(const[f,_]of this.assignTemplatesByTargetPath.entries()){if(this.formItemTargetPaths.has(f))continue;const v=this.getDeepestToManyAssociationKey(f);!v||v!==g||l(_)}return}if(!((o=t==null?void 0:t.subModels)!=null&&o.field))return;const a=this.getModelTargetPath(t);if(!a)return;const c=this.assignTemplatesByTargetPath.get(a)||[];c.length&&l(c);const u=(r=t==null?void 0:t.subModels)==null?void 0:r.field,d=(i=u==null?void 0:u.context)==null?void 0:i.collectionField,m=!!((n=d==null?void 0:d.isAssociationField)!=null&&n.call(d)),p=isToManyAssociationField(d);if(m&&!p){const h=`${a}.`;for(const[g,f]of this.assignTemplatesByTargetPath.entries())!g||typeof g!="string"||g.startsWith(h)&&l(f)}}tryUnregisterDefaultRuleInstance(t){if(this.options.isDisposed()||!this.isModelInThisForm(t))return;const o=this.getDefaultRuleId(t);this.rules.has(o)&&this.removeRule(o)}bindMasterInitialValue(t,o){const r=t!=null&&t.uid?String(t.uid):o,i=this.defaultRuleIdsByMasterUid.get(r)||new Set;if(i.add(o),this.defaultRuleIdsByMasterUid.set(r,i),this.defaultRuleMasterDisposers.has(r))return;const n=(0,import_reactive.reaction)(()=>{var l,a;const c=(a=(l=t==null?void 0:t.getProps)==null?void 0:l.call(t))!=null?a:t==null?void 0:t.props;return c==null?void 0:c.initialValue},(l,a)=>{var c,u;if(import_lodash.default.isEqual(l,a))return;const d=this.defaultRuleIdsByMasterUid.get(r);if(!d)return;const m=(u=(c=t==null?void 0:t.getProps)==null?void 0:c.call(t))!=null?u:t==null?void 0:t.props,p=typeof(m==null?void 0:m.initialValue)<"u"?LINKAGE_DEFAULT_RULE_PRIORITY:0;for(const h of d){const g=this.rules.get(h);g&&(g.rule.priority=p),this.scheduleRule(h)}});this.defaultRuleMasterDisposers.set(r,n)}removeRule(t){const o=this.rules.get(t);if(!o)return;try{const i=o.rule.getContext(),n=o.rule.getTarget(),l=this.options.tryResolveNamePath(i,n);if(l){const a=namePathToPathKey(l),c=this.options.observableBindings.get(a);c&&c.source===o.rule.source&&(c.dispose(),this.options.observableBindings.delete(a))}}catch{}o.state.depDisposers.forEach(i=>i()),this.rules.delete(t),this.pendingRuleIds.delete(t);const r=this.ruleDebounceTimersById.get(t);r&&clearTimeout(r),this.ruleDebounceTimersById.delete(t),this.ruleDebounceUntilById.delete(t);for(const[i,n]of this.defaultRuleIdsByMasterUid.entries()){if(!n.has(t)||(n.delete(t),n.size>0))continue;this.defaultRuleIdsByMasterUid.delete(i);const l=this.defaultRuleMasterDisposers.get(i);l&&l(),this.defaultRuleMasterDisposers.delete(i)}}scheduleRule(t){var o;if(this.options.isDisposed())return;const r=this.rules.get(t);if(!r)return;const{rule:i,state:n}=r;n.scheduledAtWriteSeq=this.options.getWriteSeq();const l=(o=i==null?void 0:i.debounceMs)!=null?o:0;if(this.pendingRuleIds.add(t),l>0){const a=Date.now()+l,c=this.ruleDebounceUntilById.get(t)||0;a>c&&this.ruleDebounceUntilById.set(t,a);const u=this.ruleDebounceTimersById.get(t);u&&clearTimeout(u);const d=setTimeout(()=>{this.ruleDebounceTimersById.delete(t),this.rulesEnabled&&(this.runningRules||this.pendingRuleIds.has(t)&&this.flushRules())},l);this.ruleDebounceTimersById.set(t,d)}else{const a=this.ruleDebounceTimersById.get(t);a&&clearTimeout(a),this.ruleDebounceTimersById.delete(t),this.ruleDebounceUntilById.delete(t)}this.rulesEnabled&&(this.runningRules||this.flushRules())}flushRules(){return L(this,null,function*(){if(this.runningRules)return;this.runningRules=!0;const t=this.currentRuleTxId||createTxId();this.currentRuleTxId=t;try{for(;this.pendingRuleIds.size;){const o=Date.now(),r=[];for(const i of this.pendingRuleIds)(this.ruleDebounceUntilById.get(i)||0)>o||r.push(i);if(!r.length)break;for(const i of r)this.pendingRuleIds.delete(i),this.ruleDebounceUntilById.delete(i);r.sort((i,n)=>{var l,a,c,u;const d=(l=this.rules.get(i))==null?void 0:l.rule,m=(a=this.rules.get(n))==null?void 0:a.rule,p=(c=d==null?void 0:d.priority)!=null?c:0,h=(u=m==null?void 0:m.priority)!=null?u:0;return p!==h?p-h:i.localeCompare(n)});for(const i of r)yield this.runRule(i)}}finally{this.runningRules=!1,this.currentRuleTxId=null,this.options.txWriteCounts.delete(t)}})}runRule(t){return L(this,null,function*(){var o,r;const i=this.rules.get(t);if(!i)return;const{rule:n,state:l}=i;l.runSeq+=1;const a=l.runSeq,c=l.scheduledAtWriteSeq,u=this.prepareRuleContext(n),{baseCtx:d,targetNamePath:m,targetKey:p,clearDeps:h,disposeBinding:g}=u;if(!this.shouldRunRule(n,m,p,d)){h(l),g();return}if(!m||!p){h(l),g();return}const f=m,_=p,{collector:v,evalCtx:b}=this.createRuleCollectorAndContext(n,u);if(n.getCondition&&!(yield this.evaluateRuleCondition(n,l,a,b,v)))return;const F=yield this.resolveRuleValue(n,l,a,b,v);if(F===SKIP_RULE_VALUE||a!==l.runSeq)return;this.commitRuleDeps(n,l,v);const y=this.normalizeResolvedValueForTarget(d,F),C=this.normalizeResolvedValueForAssociationTarget(d,f,y);if(n.source==="default"&&!this.checkDefaultRuleCanApply(C,f,_,h,g,l))return;if(n.source==="default"){const N=this.lastRuleWriteByTargetKey.get(_);if((N==null?void 0:N.source)==="default"&&N.priority>n.priority&&N.writeSeq>=c){g();return}}if(n.source==="system"){const N=this.options.lastWriteMetaByPathKey.get(_);if((N==null?void 0:N.source)==="linkage"&&N.writeSeq>=c){g();return}}if(this.shouldSkipAssociationNestedWrite(d,f)||this.shouldSkipToManyAssociationWriteWithoutIndex(d,f))return;const S=C;if(this.isAssociationTargetSemanticallyEqual(d,f,this.options.getFormValueAtPath(f),S))return;const P=this.collectUpdateAssociationInitPatches(d,f);if(P==null)return;if(n.source==="system"||n.source==="default"){const N=d==null?void 0:d.model,D=(o=N==null?void 0:N.subModels)==null?void 0:o.field;if(D){const w=this.getModelTargetNamePath(N);w&&namePathToPathKey(w)===_&&(N.setProps({value:C}),(r=D.setProps)==null||r.call(D,{value:C}))}}const j=this.options.getWriteSeq(),A=[...P,{path:f,value:C}];yield this.options.setFormValues(b,A,{source:n.source,txId:this.currentRuleTxId||void 0});const T=this.options.getWriteSeq();T!==j&&this.lastRuleWriteByTargetKey.set(_,{source:n.source,priority:n.priority,writeSeq:T})})}isTzAwareTargetInterface(t){return typeof t!="string"?!1:["datetime","createdAt","updatedAt","unixTimestamp"].includes(t)}normalizeDateOnlyToStartOfDayIso(t){const o=String(t||"").trim();if(!o||!/^\d{4}-\d{2}-\d{2}$/.test(o))return t;const r=(0,import_client.dayjs)(o,"YYYY-MM-DD",!0);return r.isValid()?r.startOf("day").toISOString():t}normalizeResolvedValueForTarget(t,o){var r,i,n;const l=(n=(i=(r=t==null?void 0:t.model)==null?void 0:r.context)==null?void 0:i.collectionField)==null?void 0:n.interface;return this.isTzAwareTargetInterface(l)?typeof o=="string"?this.normalizeDateOnlyToStartOfDayIso(o):Array.isArray(o)?o.map(a=>typeof a=="string"?this.normalizeDateOnlyToStartOfDayIso(a):a):o:o}isPrimitiveAssociationTargetValue(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}extractAssociationIdentity(t,o){const r=this.getAssociationTargetKeyFields(t),i=r.length===1?r[0]:null,n=a=>{if(a==null)return a;if(this.isPrimitiveAssociationTargetValue(a))return i?a:UNRESOLVED_ASSOCIATION_IDENTITY;if(!a||typeof a!="object")return UNRESOLVED_ASSOCIATION_IDENTITY;if(i)return typeof a[i]>"u"?UNRESOLVED_ASSOCIATION_IDENTITY:a[i];const c={};for(const u of r){if(typeof a[u]>"u")return UNRESOLVED_ASSOCIATION_IDENTITY;c[u]=a[u]}return c};if(isToManyAssociationField(t)){const a=Array.isArray(o)?o:[o],c=[];for(const u of a){if(u==null)continue;const d=n(u);if(d===UNRESOLVED_ASSOCIATION_IDENTITY)return UNRESOLVED_ASSOCIATION_IDENTITY;c.push(d)}return c}const l=Array.isArray(o)?o.find(a=>a!=null):o;return l==null?l:n(l)}isAssociationTargetSemanticallyEqual(t,o,r,i){var n;const l=this.resolveCollectionFieldByNamePath(t,o);if(!((n=l==null?void 0:l.isAssociationField)!=null&&n.call(l)))return import_lodash.default.isEqual(r,i);const a=this.extractAssociationIdentity(l,r),c=this.extractAssociationIdentity(l,i);return a===UNRESOLVED_ASSOCIATION_IDENTITY||c===UNRESOLVED_ASSOCIATION_IDENTITY?import_lodash.default.isEqual(r,i):import_lodash.default.isEqual(a,c)}resolveCollectionFieldByNamePath(t,o){var r,i;if(!Array.isArray(o)||!o.length)return null;let n=this.getRootCollection()||this.getCollectionFromContext(t);if(!(n!=null&&n.getField))return null;for(let l=0;l<o.length;l++){const a=o[l];if(typeof a!="string"||!a)return null;const c=(r=n==null?void 0:n.getField)==null?void 0:r.call(n,a);if(!c)return null;if(l===o.length-1)return c;if(!((i=c==null?void 0:c.isAssociationField)!=null&&i.call(c))||!(c!=null&&c.targetCollection))return null;if(isToManyAssociationField(c)){if(typeof o[l+1]!="number")return null;l+=1}if(n=c.targetCollection,!(n!=null&&n.getField))return null}return null}normalizeResolvedValueForAssociationTarget(t,o,r){var i;const n=this.resolveCollectionFieldByNamePath(t,o);if(!((i=n==null?void 0:n.isAssociationField)!=null&&i.call(n)))return r;const l=this.getAssociationTargetKeyFields(n),a=l.length===1?l[0]:null,c=d=>{if(d!=null)return a&&this.isPrimitiveAssociationTargetValue(d)?{[a]:d}:d};if(isToManyAssociationField(n))return(Array.isArray(r)?r:[r]).map(d=>c(d)).filter(d=>typeof d<"u"&&d!==null);const u=Array.isArray(r)?r.find(d=>d!=null):r;return u==null?u:c(u)}prepareRuleContext(t){const o=t.getContext(),r=t.getTarget(),i=this.options.tryResolveNamePath(o,r),n=i?namePathToPathKey(i):null;return{baseCtx:o,targetNamePath:i,targetKey:n,clearDeps:l=>{l.depDisposers.forEach(a=>a()),l.depDisposers=[],l.deps=new Set},disposeBinding:()=>{if(!n)return;const l=this.options.observableBindings.get(n);l&&l.source===t.source&&(l.dispose(),this.options.observableBindings.delete(n))}}}shouldApplyDefaultRuleInCurrentState(t){var o,r;if(((r=(o=this.options).getActionName)==null?void 0:r.call(o))!=="update")return!0;let i;try{i=t==null?void 0:t.item}catch{i=void 0}return!i||typeof i!="object"?!1:i.__is_new__===!0}shouldRunRule(t,o,r,i){return!(!t.getEnabled()||!o||!r||t.source==="default"&&(!this.shouldApplyDefaultRuleInCurrentState(i)||this.options.findExplicitHit(r)))}createRuleCollectorAndContext(t,o){const{baseCtx:r,targetNamePath:i}=o,n=t.getValue(),l=(0,import_flow_engine.isRunJSValue)(n),a={deps:new Set,wildcard:!1};if(t.getCondition&&collectStaticDepsFromTemplateValue(t.getCondition(),a),l?collectStaticDepsFromRunJSValue(n,a):collectStaticDepsFromTemplateValue(n,a),i){recordDep(i,a);for(const u of this.collectAssociationPrefixPaths(r,i))recordDep(u,a)}const c=this.createRuleEvaluationContext(r,a,i);return{collector:a,evalCtx:c,rawValue:n,isRunJS:l}}evaluateRuleCondition(t,o,r,i,n){return L(this,null,function*(){var l;const a=t.getCondition;if(!a)return!0;const c=a();let u=c;if(c)try{u=yield(l=i==null?void 0:i.resolveJsonTemplate)==null?void 0:l.call(i,c)}catch{u=c}return r!==o.runSeq?!1:c&&!evaluateCondition(i,u)?(this.commitRuleDeps(t,o,n),!1):!0})}resolveRuleValue(t,o,r,i,n){return L(this,null,function*(){const l=t.getValue();return(0,import_flow_engine.isRunJSValue)(l)?this.resolveRunJSValue(l,o,r,i,n,t):this.resolveTemplateValue(l,o,r,i,n,t)})}resolveRunJSValue(t,o,r,i,n,l){return L(this,null,function*(){try{const{code:a,version:c}=(0,import_flow_engine.normalizeRunJSValue)(t),u=yield(0,import_flow_engine.runjsWithSafeGlobals)(i,a,{version:c});return u!=null&&u.success?u.value:(r!==o.runSeq||this.commitRuleDeps(l,o,n),SKIP_RULE_VALUE)}catch{return r!==o.runSeq||this.commitRuleDeps(l,o,n),SKIP_RULE_VALUE}})}resolveTemplateValue(t,o,r,i,n,l){return L(this,null,function*(){var a;try{return yield(a=i==null?void 0:i.resolveJsonTemplate)==null?void 0:a.call(i,t)}catch{return r!==o.runSeq||this.commitRuleDeps(l,o,n),SKIP_RULE_VALUE}})}commitRuleDeps(t,o,r){const i=new Set(r.deps);r.wildcard&&i.add("fv:*"),this.updateRuleDeps(t,o,i)}checkDefaultRuleCanApply(t,o,r,i,n,l){if(typeof t>"u")return!1;if(this.options.findExplicitHit(r))return i(l),n(),!1;const a=this.options.getFormValueAtPath(o),c=this.options.lastDefaultValueByPathKey.get(r),u=isEmptyValue(a)||typeof c<"u"&&import_lodash.default.isEqual(a,c),d=(0,import_reactive.isObservable)(t)?(0,import_reactive.toJS)(t):t;return!u&&import_lodash.default.isEqual(a,d)?(this.options.lastDefaultValueByPathKey.set(r,d),!1):u}createRuleEvaluationContext(t,o,r){var i;const n=this.options.createTrackingFormValues(o),l=new import_flow_engine.FlowContext;try{l.delegate(t)}catch{}const a=(i=t==null?void 0:t.getPropertyOptions)==null?void 0:i.call(t,"formValues");a&&typeof a=="object"?l.defineProperty("formValues",I(x({},a),{get:()=>n,cache:!1})):l.defineProperty("formValues",{get:()=>n,cache:!1});let c,u=!1;const d=()=>{if(!u){const m=this.buildItemChainValue(t,n,r);c=m??(t==null?void 0:t.item),u=!0}return c};return l.defineProperty("item",{get:d,cache:!1}),l}buildItemChainValue(t,o,r){var i,n;const l=this.getRootCollection()||this.getCollectionFromContext(t),a=(h,g,f,_)=>({index:g,length:f,__is_new__:h==null?void 0:h.__is_new__,__is_stored__:h==null?void 0:h.__is_stored__,value:h,parentItem:_}),c=a(o,void 0,void 0,void 0);if(!r||!Array.isArray(r)||!r.length||!(l!=null&&l.getField))return;const u=[],d=[];let m=l;for(let h=0;h<r.length-1;h++){const g=r[h];if(typeof g!="string")break;const f=(i=m==null?void 0:m.getField)==null?void 0:i.call(m,g);if(!((n=f==null?void 0:f.isAssociationField)!=null&&n.call(f)))break;const _=isToManyAssociationField(f);if(d.push(g),_){const b=r[h+1];if(typeof b!="number")break;d.push(b),h+=1}const v=f==null?void 0:f.targetCollection;if(!v)break;u.push({path:[...d],toMany:_}),m=v}const p=h=>{if(h<0)return c;const g=u[h],f=import_lodash.default.get(o,g.path),_=g.path[g.path.length-1],v=g.toMany&&typeof _=="number"?_:void 0,b=(()=>{if(!g.toMany)return;const F=g.path.slice(0,-1),y=import_lodash.default.get(o,F);return Array.isArray(y)?y.length:void 0})();return a(f,v,b,p(h-1))};return u.length?p(u.length-1):void 0}getFieldIndexSignature(t){var o,r,i;const n=(i=(r=(o=t==null?void 0:t.model)==null?void 0:o.context)==null?void 0:r.fieldIndex)!=null?i:t==null?void 0:t.fieldIndex;return(Array.isArray(n)?n:[]).filter(l=>typeof l=="string").join("|")}updateRuleDeps(t,o,r){if(o.depDisposers.forEach(n=>n()),o.depDisposers=[],o.deps=r,r.has("fv:*")){const n=(0,import_reactive.reaction)(()=>this.options.changeTick.value,()=>this.scheduleRule(t.id));o.depDisposers.push(n)}const i=(()=>{try{return t.getContext()}catch{return}})();for(const n of r){if(n==="fv:*")continue;if(!n.startsWith("fv:")&&!n.startsWith("ctx:")){const p=pathKeyToNamePath(n),h=(0,import_reactive.reaction)(()=>import_lodash.default.get(this.options.valuesMirror,p),()=>this.scheduleRule(t.id));o.depDisposers.push(h);continue}if(n.startsWith("fv:")){const p=n.slice(3),h=pathKeyToNamePath(p),g=(0,import_reactive.reaction)(()=>import_lodash.default.get(this.options.valuesMirror,h),()=>this.scheduleRule(t.id));o.depDisposers.push(g);continue}const l=n.slice(4),a=l.indexOf(":"),c=a>=0?l.slice(0,a):l,u=a>=0?l.slice(a+1):"",d=u?parsePathString(u).filter(p=>typeof p!="object"):[];if(c==="item"){const p=(0,import_reactive.reaction)(()=>this.getFieldIndexSignature(i),()=>this.scheduleRule(t.id));if(o.depDisposers.push(p),d.length){const h=this.options.createTrackingFormValues({deps:new Set,wildcard:!1}),g=(0,import_reactive.reaction)(()=>{var f,_;const v=(f=t.getTarget)==null?void 0:f.call(t),b=v?this.options.tryResolveNamePath(i,v):null,F=(_=this.buildItemChainValue(i,h,b))!=null?_:i==null?void 0:i.item;return import_lodash.default.get(F,d)},()=>this.scheduleRule(t.id));o.depDisposers.push(g)}continue}const m=(0,import_reactive.reaction)(()=>{const p=i?i[c]:void 0;return d.length?import_lodash.default.get(p,d):p},()=>this.scheduleRule(t.id));o.depDisposers.push(m)}}}class FormValueRuntime{constructor(t){R(this,"model"),R(this,"getForm"),R(this,"valuesMirror",(0,import_reactive.observable)({})),R(this,"explicitSet",new Set),R(this,"lastDefaultValueByPathKey",new Map),R(this,"lastWriteMetaByPathKey",new Map),R(this,"observableBindings",new Map),R(this,"changeTick",import_reactive.observable.ref(0)),R(this,"txWriteCounts",new Map),R(this,"writeSeq",0),R(this,"disposed",!1),R(this,"suppressFormCallbackDepth",0),R(this,"lastObservedChangedPaths",null),R(this,"lastObservedSource",null),R(this,"lastObservedToken",0),R(this,"formValuesProxy"),R(this,"mountedListener"),R(this,"unmountedListener"),R(this,"formPatcher"),R(this,"ruleEngine"),this.model=t.model,this.getForm=t.getForm,this.formPatcher=createFormPatcher({isSuppressed:()=>this.isSuppressed(),getCallerContext:()=>{var o;return(o=this.model)==null?void 0:o.context},setFormValues:this.setFormValues.bind(this)}),this.ruleEngine=new RuleEngine({getBlockModelUid:()=>{var o;return String((o=this.model)==null?void 0:o.uid)},getActionName:()=>{var o,r,i,n,l;return(l=(r=(o=this.model)==null?void 0:o.getAclActionName)==null?void 0:r.call(o))!=null?l:(n=(i=this.model)==null?void 0:i.context)==null?void 0:n.actionName},getBlockContext:()=>{var o;return(o=this.model)==null?void 0:o.context},getEngine:()=>{var o,r;return(r=(o=this.model)==null?void 0:o.context)==null?void 0:r.engine},getEngineModel:o=>{var r,i,n,l,a;return(a=(l=(n=(i=(r=this.model)==null?void 0:r.context)==null?void 0:i.engine)==null?void 0:n.getModel)==null?void 0:l.call(n,o))!=null?a:null},isDisposed:()=>this.disposed,valuesMirror:this.valuesMirror,changeTick:this.changeTick,getWriteSeq:()=>this.writeSeq,txWriteCounts:this.txWriteCounts,createTrackingFormValues:o=>createFormValuesProxy({valuesMirror:this.valuesMirror,basePath:[],collector:o,getFormValuesSnapshot:()=>this.getFormValuesSnapshot(),getFormValueAtPath:r=>this.getFormValueAtPath(r)}),tryResolveNamePath:(o,r)=>this.tryResolveNamePath(o,r),getFormValueAtPath:o=>this.getFormValueAtPath(o),setFormValues:(o,r,i)=>this.setFormValues(o,r,i),findExplicitHit:o=>this.findExplicitHit(o),lastDefaultValueByPathKey:this.lastDefaultValueByPathKey,lastWriteMetaByPathKey:this.lastWriteMetaByPathKey,observableBindings:this.observableBindings}),this.formValuesProxy=createFormValuesProxy({valuesMirror:this.valuesMirror,basePath:[],getFormValuesSnapshot:()=>this.getFormValuesSnapshot(),getFormValueAtPath:o=>this.getFormValueAtPath(o)})}syncAssignRules(t){this.ruleEngine.syncAssignRules(t)}get formValues(){return this.disposed||this.formPatcher.patch(this.getForm()),this.formValuesProxy}getFormValuesSnapshot(){if(!this.disposed){const t=this.getForm();this.formPatcher.patch(t)}return this.getForm().getFieldsValue(!0)}getFormValueAtPath(t){var o;const r=(o=this.getForm)==null?void 0:o.call(this);if(r&&typeof r.getFieldValue=="function")return r.getFieldValue(t);if(r&&typeof r.getFieldsValue=="function"){const i=r.getFieldsValue(!0);return import_lodash.default.get(i,t)}}mount(t){var o,r;if(this.disposed)return;this.formPatcher.patch(this.getForm());const i=(r=(o=this.model)==null?void 0:o.flowEngine)==null?void 0:r.emitter;if(i&&(!this.mountedListener&&!this.unmountedListener&&(this.mountedListener=({model:n})=>{this.ruleEngine.onModelMounted(n)},this.unmountedListener=({model:n})=>{this.ruleEngine.onModelUnmounted(n)},i.on("model:mounted",this.mountedListener),i.on("model:unmounted",this.unmountedListener)),t!=null&&t.sync)){const n=this.getFormValuesSnapshot();n&&typeof n=="object"&&(import_lodash.default.merge(this.valuesMirror,n),this.bumpChangeTick()),this.ruleEngine.enable()}}dispose(){var t,o;if(this.disposed)return;this.disposed=!0,this.formPatcher.restore();const r=(o=(t=this.model)==null?void 0:t.flowEngine)==null?void 0:o.emitter;r&&this.mountedListener&&this.unmountedListener&&(r.off("model:mounted",this.mountedListener),r.off("model:unmounted",this.unmountedListener)),this.ruleEngine.dispose();for(const i of this.observableBindings.values())i.dispose();this.observableBindings.clear(),this.txWriteCounts.clear()}isSuppressed(){return this.suppressFormCallbackDepth>0}handleFormFieldsChange(t){if(this.disposed)return;const o=this.getForm();if(!o.getFieldValue)return;const r=[],i=new Set;let n=!1;for(const d of t||[]){const m=d==null?void 0:d.name,p=Array.isArray(m)?m:typeof m=="string"||typeof m=="number"?[m]:null;if(!(p!=null&&p.length))continue;const h=o.getFieldValue(p),g=import_lodash.default.get(this.valuesMirror,p);import_lodash.default.isEqual(h,g)||(n||(this.writeSeq+=1,n=!0),import_lodash.default.set(this.valuesMirror,p,h),r.push(p),(d==null?void 0:d.touched)===!0&&i.add(namePathToPathKey(p)))}if(!r.length)return;const l=this.isSuppressed();if(!l&&i.size)for(const d of i)this.markExplicit(d);if(this.bumpChangeTick(),l)return;const a=t.some(d=>(d==null?void 0:d.touched)===!0)?"user":"system",c=this.writeSeq;for(const d of r)this.lastWriteMetaByPathKey.set(namePathToPathKey(d),{source:a,writeSeq:c});this.lastObservedChangedPaths=r,this.lastObservedSource=a;const u=++this.lastObservedToken;queueMicrotask(()=>{this.disposed||this.lastObservedToken===u&&(this.lastObservedChangedPaths=null,this.lastObservedSource=null)})}handleFormValuesChange(t,o){var r;if(this.disposed||this.isSuppressed())return;const i=this.lastObservedChangedPaths&&this.lastObservedChangedPaths.length?this.lastObservedChangedPaths:Object.keys(t||{}).map(p=>[p]),n=(r=this.lastObservedSource)!=null?r:"user";this.lastObservedChangedPaths=null,this.lastObservedSource=null;const l=o&&typeof o=="object"?o:this.getFormValuesSnapshot(),a=this.deriveExplicitPaths(i,l,this.valuesMirror);let c=!1,u=!1;const d=[];for(const p of i){if(!(p!=null&&p.length))continue;const h=import_lodash.default.get(l,p),g=import_lodash.default.get(this.valuesMirror,p);import_lodash.default.isEqual(g,h)||(u||(this.writeSeq+=1,u=!0),import_lodash.default.set(this.valuesMirror,p,h),c=!0,d.push(p))}c&&this.bumpChangeTick();for(const p of a)this.markExplicit(namePathToPathKey(p));if(c){const p=this.writeSeq;for(const h of d)h!=null&&h.length&&this.lastWriteMetaByPathKey.set(namePathToPathKey(h),{source:n,writeSeq:p})}const m=createTxId();this.emitFormValuesChange({source:n,txId:m,changedPaths:i,changedValues:t,allValues:l,allValuesSnapshot:l})}deriveExplicitPaths(t,o,r){const i=[],n=new Set;for(const l of t||[]){if(!(l!=null&&l.length))continue;const a=import_lodash.default.get(r,l),c=import_lodash.default.get(o,l);this.collectExplicitDiffPaths(a,c,l,i,n)}return i}collectExplicitDiffPaths(t,o,r,i,n){if(import_lodash.default.isEqual(t,o))return 0;const l=Array.isArray(t),a=Array.isArray(o);if(l||a){if(l&&a){const d=Math.min(t.length,o.length);let m=0;for(let p=0;p<d;p++)m+=this.collectExplicitDiffPaths(t[p],o[p],[...r,p],i,n);return m}return this.pushExplicitPath(r,i,n)?1:0}const c=this.isPlainObjectValue(t),u=this.isPlainObjectValue(o);if(c||u){if(c&&u){const d=new Set([...Object.keys(t),...Object.keys(o)]);let m=0;for(const p of d)m+=this.collectExplicitDiffPaths(t[p],o[p],[...r,p],i,n);return m===0&&this.isObjectCleared(t,o)?this.pushExplicitPath(r,i,n)?1:0:m}return this.isObjectCleared(t,o)?this.pushExplicitPath(r,i,n)?1:0:this.pushExplicitPath(r,i,n)?1:0}return this.pushExplicitPath(r,i,n)?1:0}pushExplicitPath(t,o,r){if(!(t!=null&&t.length))return!1;const i=namePathToPathKey(t);return!i||r.has(i)?!1:(r.add(i),o.push([...t]),!0)}isPlainObjectValue(t){return import_lodash.default.isPlainObject(t)}isObjectCleared(t,o){return this.isPlainObjectValue(t)?!!(o==null||this.isPlainObjectValue(o)&&Object.keys(o).length===0):!1}setFormValues(t,o,r){return L(this,null,function*(){var i,n,l,a,c,u;if(this.disposed)return;const d=(i=this.getForm)==null?void 0:i.call(this);if(!d)return;const m=(n=r==null?void 0:r.source)!=null?n:"system",p=(r==null?void 0:r.triggerEvent)!==!1,h=(l=r==null?void 0:r.txId)!=null?l:createTxId(),g=(a=r==null?void 0:r.markExplicit)!=null?a:m!=="default",f=typeof(r==null?void 0:r.txId)>"u",_=m==="linkage"&&Number.isFinite(Number(r==null?void 0:r.linkageScopeDepth))?Number(r==null?void 0:r.linkageScopeDepth):0,v=m==="linkage"&&typeof(r==null?void 0:r.linkageTxId)=="string"&&r.linkageTxId?String(r.linkageTxId):void 0,b=C=>{if(m!=="linkage"||!v)return!1;const S=this.lastWriteMetaByPathKey.get(C);return!S||S.source!=="linkage"||!S.linkageTxId||S.linkageTxId!==v?!1:(Number.isFinite(Number(S.linkageScopeDepth))?Number(S.linkageScopeDepth):0)>_},F=C=>m==="linkage"?{source:m,writeSeq:C,linkageScopeDepth:_,linkageTxId:v}:{source:m,writeSeq:C},y=C=>m==="linkage"&&v?I(x({},C),{linkageTxId:v}):C;try{const C=[];if(!Array.isArray(o)){const D=Object.entries(o||{}).filter(([E])=>!b(E)),w=Object.fromEntries(D),k=D.map(([E])=>E);if(!k.length)return;k.length&&(this.writeSeq+=1),this.suppressFormCallbackDepth++;try{(c=d.setFieldsValue)==null||c.call(d,w),import_lodash.default.merge(this.valuesMirror,w),this.bumpChangeTick()}finally{this.suppressFormCallbackDepth--}const B=this.writeSeq;for(const E of k)this.lastWriteMetaByPathKey.set(E,F(B));if(g)for(const E of k)this.markExplicit(E);if(p){const E=this.getFormValuesSnapshot();this.emitFormValuesChange(y({source:m,txId:h,changedPaths:k.map(M=>[M]),changedValues:w,allValues:E,allValuesSnapshot:E}))}return}const S=new Map;let P=0;for(const D of o){const w=D==null?void 0:D.condition;if(w&&!evaluateCondition(t,w))continue;const k=this.resolveNamePath(t,D.path),B=namePathToPathKey(k),E=D.value,M=(0,import_reactive.isObservable)(E)?(0,import_reactive.toJS)(E):E;if(b(B))continue;const O=this.getFormValueAtPath(k);import_lodash.default.isEqual(O,M)||(P+=1,S.set(B,{order:P,namePath:k,value:M,rawValue:E,pathKey:B}))}const j=Array.from(S.values()).sort((D,w)=>D.order-w.order).map(D=>({namePath:D.namePath,value:D.value,rawValue:D.rawValue,pathKey:D.pathKey}));if(!j.length)return;const A=this.txWriteCounts.get(h)||new Map;this.txWriteCounts.set(h,A);const T=[];for(const D of j){const w=(A.get(D.pathKey)||0)+1;A.set(D.pathKey,w),!(w>MAX_WRITES_PER_PATH_PER_TX)&&T.push(D)}if(!T.length)return;this.writeSeq+=1;const N=this.writeSeq;for(const{pathKey:D,rawValue:w}of T)if(!(0,import_reactive.isObservable)(w)){const k=this.observableBindings.get(D);k&&(k.dispose(),this.observableBindings.delete(D))}this.suppressFormCallbackDepth++;try{for(const{namePath:D,value:w}of T)(u=d.setFieldValue)==null||u.call(d,D,w),import_lodash.default.set(this.valuesMirror,D,w),C.push(D);this.bumpChangeTick()}finally{this.suppressFormCallbackDepth--}for(const{pathKey:D}of T)this.lastWriteMetaByPathKey.set(D,F(N));if(g)for(const{pathKey:D}of T)this.markExplicit(D);if(m==="default")for(const{namePath:D,pathKey:w}of T){const k=this.getFormValueAtPath(D);this.lastDefaultValueByPathKey.set(w,k)}for(const{namePath:D,rawValue:w,pathKey:k}of T){if(!(0,import_reactive.isObservable)(w))continue;const B=w,E=(0,import_reactive.observe)(B,()=>{this.applyBoundValue(t,D,k,(0,import_reactive.toJS)(B),m,_,v)}),M=this.observableBindings.get(k);M&&M.dispose(),this.observableBindings.set(k,{source:m,dispose:E})}if(p){const D=this.getFormValuesSnapshot();this.emitFormValuesChange(y({source:m,txId:h,changedPaths:C,changedValues:{},allValues:D,allValuesSnapshot:D}))}}finally{f&&this.txWriteCounts.delete(h)}})}applyBoundValue(t,o,r,i,n,l,a){var c,u;if(this.disposed)return;const d=(c=this.getForm)==null?void 0:c.call(this);if(!d)return;const m=import_lodash.default.get(this.valuesMirror,o);if(import_lodash.default.isEqual(m,i))return;this.writeSeq+=1;const p=this.writeSeq;this.suppressFormCallbackDepth++;try{(u=d.setFieldValue)==null||u.call(d,o,i),import_lodash.default.set(this.valuesMirror,o,i),this.bumpChangeTick()}finally{this.suppressFormCallbackDepth--}const h=n==="linkage"?{source:n,writeSeq:p,linkageScopeDepth:Number.isFinite(Number(l))?Number(l):0,linkageTxId:typeof a=="string"&&a?a:void 0}:{source:n,writeSeq:p};this.lastWriteMetaByPathKey.set(r,h);const g=createTxId(),f=this.getFormValuesSnapshot(),_={source:n,txId:g,changedPaths:[o],changedValues:{},allValues:f,allValuesSnapshot:f};if(n==="linkage"&&a&&(_.linkageTxId=a),this.emitFormValuesChange(_),n==="default"&&this.isExplicit(r)){const v=this.observableBindings.get(r);v&&(v.dispose(),this.observableBindings.delete(r))}n==="default"&&this.lastDefaultValueByPathKey.set(r,this.getFormValueAtPath(o))}resolveNamePath(t,o){const r=this.tryResolveNamePath(t,o);if(!r)throw new Error(`Failed to resolve path '${String(o)}'`);return r}tryResolveNamePath(t,o){var r,i,n;const l=(n=(i=(r=t==null?void 0:t.model)==null?void 0:r.context)==null?void 0:i.fieldIndex)!=null?n:t==null?void 0:t.fieldIndex;return resolveDynamicNamePath(o,l)}bumpChangeTick(){this.changeTick.value+=1}emitFormValuesChange(t){var o,r,i,n;(r=(o=this.model).dispatchEvent)==null||r.call(o,"formValuesChange",t,{debounce:!0}),(n=(i=this.model.emitter)==null?void 0:i.emit)==null||n.call(i,"formValuesChange",t)}markExplicit(t){if(!this.explicitSet.has(t)){this.explicitSet.add(t);for(const o of Array.from(this.lastDefaultValueByPathKey.keys()))(o===t||o.startsWith(`${t}.`)||o.startsWith(`${t}[`))&&this.lastDefaultValueByPathKey.delete(o);for(const[o,r]of Array.from(this.observableBindings.entries()))r.source==="default"&&this.isExplicit(o)&&(r.dispose(),this.observableBindings.delete(o))}}isExplicit(t){return!!this.findExplicitHit(t)}findExplicitHit(t){if(this.explicitSet.has(t))return t;const o=pathKeyToNamePath(t),r=[];for(let i=0;i<o.length;i++){r.push(o[i]);const n=namePathToPathKey(r);if(!(!this.explicitSet.has(n)||typeof o[i+1]=="number"))return n}return null}}function collectUpdateAssociationValuesFromAssignRules(e,t){const o=Array.isArray(e)?e:[],r=new Set,i=n=>{var l,a,c,u,d;if(!t||typeof t.getField!="function"||typeof n!="string"||!n.includes("."))return null;const m=n.split(".").filter(Boolean);if(m.length<2)return null;let p=t;const h=[];let g=null,f=null;for(let _=0;_<m.length-1;_++){const v=m[_],b=(l=p==null?void 0:p.getField)==null?void 0:l.call(p,v);if(!((a=b==null?void 0:b.isAssociationField)!=null&&a.call(b))||!(b!=null&&b.targetCollection))break;h.push(v),g=h.join("."),f=b,p=b.targetCollection}if(g&&f){const _=m[m.length-1],v=(d=(u=f==null?void 0:f.targetKey)!=null?u:(c=f==null?void 0:f.targetCollection)==null?void 0:c.filterTargetKey)!=null?d:"id",b=Array.isArray(v)?v.filter(F=>typeof F=="string"&&!!F):typeof v=="string"&&v?[v]:["id"];if(typeof _=="string"&&b.includes(_))return null}return g};for(const n of o){const l=n!=null&&n.targetPath?String(n.targetPath):"";if(!l)continue;const a=i(l);a&&r.add(a)}return Array.from(r)}function createEmptyCondition(){return{logic:"$and",items:[]}}function getPropsInitialValue(e){if(!e)return;const t=typeof e.getProps=="function"?e.getProps():e.props;if(t&&typeof t.initialValue<"u")return t.initialValue}function getStepParamsInitialValue(e,t){var o,r;if(e)return(r=(o=e.getStepParams)==null?void 0:o.call(e,t,"initialValue"))==null?void 0:r.defaultValue}function createLegacyValueExtractor(e){return t=>{if(!t)return;const o=getPropsInitialValue(t);if(typeof o<"u")return o;for(const r of e){const i=getStepParamsInitialValue(t,r);if(typeof i<"u")return i}}}function deleteStepParams(e,t,o){var r,i,n;if(!((r=e==null?void 0:e.stepParams)!=null&&r[t]))return;const l=e.stepParams[t];!l||typeof l!="object"||Object.prototype.hasOwnProperty.call(l,o)&&(delete l[o],import_lodash.default.isEmpty(l)&&delete e.stepParams[t],(n=(i=e.emitter)==null?void 0:i.emit)==null||n.call(i,"onStepParamsChanged"))}function createLegacyClearer(e){return t=>{var o;if(t){(o=t.setProps)==null||o.call(t,{initialValue:void 0}),t.props&&Object.prototype.hasOwnProperty.call(t.props,"initialValue")&&delete t.props.initialValue;for(const r of e)deleteStepParams(t,r,"initialValue")}}}function collectLegacyDefaultValueRules(e,t){var o,r,i,n,l;const a=(i=(r=(o=e==null?void 0:e.subModels)==null?void 0:o.grid)==null?void 0:r.subModels)==null?void 0:i.items,c=Array.isArray(a)?a:[],u=[];for(const d of c){const m=((l=(n=d==null?void 0:d.getStepParams)==null?void 0:n.call(d,"fieldSettings","init"))==null?void 0:l.fieldPath)||(d==null?void 0:d.fieldPath),p=m?String(m):"";if(!p)continue;const h=t(d);typeof h<"u"&&u.push({key:`legacy-default:${p}`,enable:!0,targetPath:p,mode:"default",condition:createEmptyCondition(),value:h})}return u}function mergeAssignRulesWithLegacyDefaults(e,t){var o,r;const i=Array.isArray(e)?e:[],n=Array.isArray(t)?t:[];if(!n.length)return i;const l=new Set;for(const u of i){if(!u||typeof u!="object")continue;const d=u.targetPath?String(u.targetPath):"";if(d){if(u.mode==="default"){l.add(d);continue}String((o=u.key)!=null?o:"").startsWith("legacy-default:")&&l.add(d)}}const a=new Set(i.map(u=>{var d;return String((d=u.key)!=null?d:"")})),c=[];for(const u of n){const d=u.targetPath?String(u.targetPath):"";if(!d||l.has(d))continue;const m=x({},u),p=String((r=m.key)!=null?r:"");p&&a.has(p)&&(m.key=`${p}:${d}`),c.push(m)}return c.length?[...i,...c]:i}function clearLegacyDefaultValues(e,t,o){var r,i,n;const l=(n=(i=(r=e==null?void 0:e.subModels)==null?void 0:r.grid)==null?void 0:i.subModels)==null?void 0:n.items,a=Array.isArray(l)?l:[],c=[];for(const u of a)typeof t(u)<"u"&&(o(u),c.push(u));return c}const FORM_FLOW_KEYS=["editItemSettings","formItemSettings"],getLegacyFieldInitialValue=createLegacyValueExtractor(FORM_FLOW_KEYS),clearLegacyFieldInitialValue=createLegacyClearer(FORM_FLOW_KEYS);function collectLegacyDefaultValueRulesFromFormModel(e){return collectLegacyDefaultValueRules(e,getLegacyFieldInitialValue)}function clearLegacyDefaultValuesFromFormModel(e){return clearLegacyDefaultValues(e,getLegacyFieldInitialValue,clearLegacyFieldInitialValue)}const GRID_DELEGATED_STEP_KEYS={formModelSettings:new Set(["layout","assignRules"]),eventSettings:new Set(["linkageRules"])},FLOW_KEEP_MOBILE_HORIZONTAL_CLASS="nb-flow-keep-mobile-horizontal",flowKeepMobileHorizontalClassName=import_css.css`
1828
+ `},properties:{name:{type:"string","x-decorator":"FormItem","x-component":"Input","x-component-props":{placeholder:'{{t("Name")}}'}},value:{type:"string","x-decorator":"FormItem","x-component":TextAreaWithContextSelector,"x-component-props":{rows:1}},remove:{type:"void","x-decorator":"FormItem","x-component":"ArrayItems.Remove"}}}}},"x-reactions":{dependencies:["mode"],fulfill:{state:{hidden:'{{$deps[0] === "html"}}'}}},properties:{add:{type:"void",title:'{{t("Add parameter")}}',"x-component":"ArrayItems.Addition"}}},openInNewWindow:{type:"boolean","x-content":t("Open in new window"),"x-decorator":"FormItem","x-component":"Checkbox","x-reactions":{dependencies:["mode"],fulfill:{state:{hidden:'{{$deps[0] === "html"}}'}}}}}},handler(e,t){e.model.setProps({url:t.url,searchParams:t.searchParams,openInNewWindow:t.openInNewWindow})}}}});class ExpandCollapseActionModel extends ActionModel{constructor(){super(...arguments),R(this,"expandFlag"),R(this,"defaultProps",{type:"default",icon:"DownOutlined"})}setTitle(t){this.setProps({title:t})}setExpandFlag(t){this.expandFlag=t}getTitle(){return this.expandFlag?this.context.t("Collapse all"):this.context.t("Expand all")}getIcon(){return this.expandFlag?"NodeCollapseOutlined":"NodeExpandOutlined"}}R(ExpandCollapseActionModel,"scene",ActionSceneEnum.collection);function getIdsWithChildren(e,{idKey:t="id",childrenKey:o="children"}={}){const r=[];function i(n){if(Array.isArray(n))for(const l of n){const a=l[o];r.push(l[t]),Array.isArray(a)&&a.length>0&&i(a)}}return i(e),r}const allIncludesChildren=e=>getIdsWithChildren(e);ExpandCollapseActionModel.registerFlow({key:"expandCollapseSettingsInit",sort:200,steps:{init:{handler(e,t){e.blockModel.props.defaultExpandAllRows?e.model.setExpandFlag(!0):e.model.setExpandFlag(!1)}}}});ExpandCollapseActionModel.registerFlow({key:"expandCollapseSettings",on:"click",steps:{expandCollapse:{handler(e,t){return L(this,null,function*(){var o;if(!((o=e.blockModel)!=null&&o.resource))return;const r=e.blockModel.resource,{treeTable:i}=e.blockModel.props;if(i)if(e.model.expandFlag)e.blockModel.setProps({expandedRowKeys:[]}),e.model.setExpandFlag(!1);else{const n=allIncludesChildren(r.getData());e.blockModel.setProps({expandedRowKeys:n}),e.model.setExpandFlag(!0)}})}}}});ExpandCollapseActionModel.define({label:(0,import_flow_engine.escapeT)("Expand/Collapse"),hide(e){var t;return((t=e.collection)==null?void 0:t.template)!=="tree"||e.model.props.treeTable===!1}});class AddChildActionModel extends PopupActionModel{constructor(){super(...arguments),R(this,"defaultProps",{type:"link",title:(0,import_flow_engine.tExpr)("Add child"),icon:"PlusOutlined"})}getAclActionName(){return"create"}onInit(t){super.onInit(t),this.context.defineProperty("association",{get:()=>this.context.blockModel.dataSource.getAssociation(`${this.context.blockModel.collection.name}.children`)})}}R(AddChildActionModel,"capabilityActionName",null);AddChildActionModel.registerFlow({key:"addChildSettingsInit",steps:{addChildInit:{handler(e,t){return L(this,null,function*(){e.model.onClick=o=>{e.model.dispatchEvent("click",I(x({event:o},e.inputArgs),{sourceId:e.record.id,filterByTk:null}),{debounce:!0})}})}}}});AddChildActionModel.define({label:(0,import_flow_engine.tExpr)("Add child"),hide(e){var t;return((t=e.collection)==null?void 0:t.template)!=="tree"||e.blockModel.props.treeTable===!1}});RecordActionGroupModel.registerActionModels({AddChildActionModel});const SAVE_STEP_PARAMS_WITH_SUB_MODELS_FLAG="__saveStepParamsWithSubModels";function markSaveStepParamsWithSubModels(e){if(!e||typeof e!="object"&&typeof e!="function")throw new Error("[saveStepParamsWithSubModels] model is not an object");e[SAVE_STEP_PARAMS_WITH_SUB_MODELS_FLAG]=!0}function saveStepParamsWithSubModelsIfNeeded(e,t){return L(this,null,function*(){if(!e||typeof e!="object"&&typeof e!="function")throw new Error("[saveStepParamsWithSubModels] model is not an object");const o=e;if(o[SAVE_STEP_PARAMS_WITH_SUB_MODELS_FLAG]!==!0)return yield t();if(typeof o.save!="function")throw new Error("[saveStepParamsWithSubModels] model.save is not a function");try{return yield o.save()}finally{delete o[SAVE_STEP_PARAMS_WITH_SUB_MODELS_FLAG]}})}function evaluateCondition(e,t){const o=(r,i,n)=>{var l,a,c;return i?(c=(a=(l=e==null?void 0:e.app)==null?void 0:l.jsonLogic)==null?void 0:a.apply)==null?void 0:c.call(a,{[i]:[r,n]}):!0};try{return(0,import_client.evaluateConditions)((0,import_client.removeInvalidFilterItems)(t),o)}catch{return!1}}function parsePathString(e){const t=[];let o=0;const r=e.length,i=()=>{const n=o;for(;o<r&&e[o]!=="."&&e[o]!=="[";)o++;const l=e.slice(n,o);l&&t.push(l)};for(;o<r;){const n=e[o];if(n==="."){o++;continue}if(n==="["){o++;const l=o;for(;o<r&&e[o]!=="]";)o++;const a=e.slice(l,o);o++,/^\d+$/.test(a)?t.push(Number(a)):a&&t.push({placeholder:a});continue}i()}return t}function parseFieldIndexEntries(e){const t=Array.isArray(e)?e:[],o=[];for(const r of t){if(typeof r!="string")continue;const[i,n]=r.split(":"),l=Number(n);!i||Number.isNaN(l)||o.push({name:i,index:l})}return o}function resolveDynamicNamePath(e,t){const o=Array.isArray(e)?[...e]:parsePathString(e),r=parseFieldIndexEntries(t),i=[];let n=0;for(let l=0;l<o.length;l++){const a=o[l];if(typeof a=="object"&&a&&"placeholder"in a){const c=i[i.length-1],u=typeof c=="string"?c:void 0;if(!u)return null;for(;n<r.length&&r[n].name!==u;)n++;if(n>=r.length)return null;i.push(r[n].index),n++;continue}if(i.push(a),typeof a=="string"&&n<r.length&&r[n].name===a){const c=o[l+1];typeof c=="number"?n++:typeof c=="object"&&c&&"placeholder"in c||(i.push(r[n].index),n++)}}return i}function namePathToPathKey(e){let t="";for(const o of e){if(typeof o=="number"){t+=`[${o}]`;continue}t?t+=`.${o}`:t=o}return t}function pathKeyToNamePath(e){return parsePathString(e).filter(t=>typeof t!="object")}function buildAncestorKeys(e){const t=[],o=[];for(const r of e)o.push(r),t.push(namePathToPathKey(o));return t}function shouldProxyObjectValue(e){return!e||typeof e!="object"?!1:Array.isArray(e)||import_lodash.default.isPlainObject(e)}function recordDep(e,t){if(t)for(const o of buildAncestorKeys(e))t.deps.add(`fv:${o}`)}function createFormValuesProxy(e){const{valuesMirror:t,collector:o,basePath:r,getFormValuesSnapshot:i,getFormValueAtPath:n}=e,l=()=>r.length?import_lodash.default.get(t,r):t,a=l(),c=a&&(typeof a=="object"||typeof a=="function")?a:Array.isArray(a)?[]:{},u=d=>createFormValuesProxy({valuesMirror:t,basePath:d,collector:o,getFormValuesSnapshot:i,getFormValueAtPath:n});return new Proxy(c,{get(d,m){if(m==="toJSON")return o&&(o.wildcard=!0),r.length===0?()=>i():()=>(0,import_reactive.toJS)(l());if(typeof m=="symbol"){o&&(o.wildcard=!0);const b=l();return b==null?void 0:b[m]}const p=l();if(p==null)return;if(m==="__raw")return p;if(m==="__proto__"||m==="prototype"||m==="constructor"){o&&(o.wildcard=!0);return}const h=Array.isArray(p),g=h&&(typeof m=="number"&&Number.isInteger(m)||typeof m=="string"&&/^\d+$/.test(m));if(h&&!g){o&&(o.wildcard=!0);const b=p[m];return typeof b=="function"?b.bind(p):b}const f=g?Number(m):m,_=[...r,f];recordDep(_,o);let v=p[m];if(typeof v>"u"){const b=n(_);import_lodash.default.isEqual(b,v)||(import_lodash.default.set(t,_,b),v=b)}return v==null||typeof v!="object"?v:shouldProxyObjectValue(v)?u(_):v},ownKeys(){o&&(o.wildcard=!0);const d=l();return d?Reflect.ownKeys(d):[]},getOwnPropertyDescriptor(d,m){const p=l();if(p)return Object.getOwnPropertyDescriptor(p,m)},has(d,m){const p=l();return p?m in p:!1}})}function collectStaticDepsFromTemplateValue(e,t){try{const o=(0,import_flow_engine.extractUsedVariablePaths)(e)||{};for(const[r,i]of Object.entries(o)){const n=Array.isArray(i)?i:[],l=n.length?n:[""];for(const a of l){if(r==="formValues"){if(!a){t.wildcard=!0;continue}const u=parsePathString(String(a)).filter(d=>typeof d!="object");recordDep(u,t);continue}const c=a?`ctx:${r}:${String(a)}`:`ctx:${r}`;t.deps.add(c)}}}catch{}}function collectStaticDepsFromRunJSValue(e,t){if((0,import_flow_engine.isRunJSValue)(e))try{const o=(0,import_flow_engine.extractUsedVariablePathsFromRunJS)(e.code)||{};for(const[r,i]of Object.entries(o)){const n=Array.isArray(i)?i:[],l=n.length?n:[""];for(const a of l){if(r==="formValues"){if(!a){t.wildcard=!0;continue}const u=parsePathString(String(a)).filter(d=>typeof d!="object");recordDep(u,t);continue}const c=a?`ctx:${r}:${String(a)}`:`ctx:${r}`;t.deps.add(c)}}}catch{}}function createFormPatcher(e){let t,o,r;const i=()=>{const n=t;n&&(o&&(n.setFieldValue=o),r&&(n.setFieldsValue=r),t=void 0,o=void 0,r=void 0)};return{patch:n=>{if(t===n)return;i();const l=typeof(n==null?void 0:n.setFieldValue)=="function"?n.setFieldValue.bind(n):void 0,a=typeof(n==null?void 0:n.setFieldsValue)=="function"?n.setFieldsValue.bind(n):void 0;t=n,o=l,r=a,l&&(n.setFieldValue=(c,u)=>{if(e.isSuppressed()){l(c,u);return}e.setFormValues(e.getCallerContext(),[{path:c,value:u}],{source:"system"}).catch(()=>{})}),a&&(n.setFieldsValue=c=>{if(e.isSuppressed()){a(c);return}e.setFormValues(e.getCallerContext(),c,{source:"system"}).catch(()=>{})})},restore:i}}const MAX_WRITES_PER_PATH_PER_TX=20;function isEmptyValue(e){return e==null?!0:typeof e=="string"||Array.isArray(e)?e.length===0:import_lodash.default.isPlainObject(e)?Object.keys(e).length===0:!1}function createTxId(){return`${Date.now()}-${Math.random().toString(16).slice(2)}`}const SKIP_RULE_VALUE=Symbol("SKIP_RULE_VALUE"),UNRESOLVED_ASSOCIATION_IDENTITY=Symbol("UNRESOLVED_ASSOCIATION_IDENTITY"),LINKAGE_DEFAULT_RULE_PRIORITY=1e3;class RuleEngine{constructor(t){R(this,"options"),R(this,"rules",new Map),R(this,"lastRuleWriteByTargetKey",new Map),R(this,"assignTemplatesByTargetPath",new Map),R(this,"formItemTargetPaths",new Set),R(this,"updateAssociationByTargetPath",new Map),R(this,"pendingRuleIds",new Set),R(this,"ruleDebounceUntilById",new Map),R(this,"ruleDebounceTimersById",new Map),R(this,"defaultRuleIdsByMasterUid",new Map),R(this,"defaultRuleMasterDisposers",new Map),R(this,"runningRules",!1),R(this,"rulesEnabled",!1),R(this,"currentRuleTxId",null),this.options=t}getAssignRuleBlockId(t){return`form-assign:${t}:block`}removeAssignRuleBlockInstance(t){const o=this.getAssignRuleBlockId(t);this.rules.has(o)&&this.removeRule(o)}removeRowGridAssignRuleInstances(t){var o,r;const i=`form-assign:${t}:`,n=this.getAssignRuleBlockId(t),l=[];for(const[a,c]of this.rules.entries()){if(!a.startsWith(i)||a===n)continue;const u=(r=(o=c==null?void 0:c.rule)==null?void 0:o.getContext)==null?void 0:r.call(o),d=u==null?void 0:u.model;d&&this.isRowGridModel(d)&&l.push(a)}for(const a of l)this.removeRule(a)}hasAnyNonBlockAssignRuleInstance(t){const o=`form-assign:${t}:`,r=this.getAssignRuleBlockId(t);for(const i of this.rules.keys())if(i.startsWith(o)&&i!==r)return!0;return!1}ensureBlockAssignRuleInstancesForTargetPath(t){if(this.options.isDisposed()||!t||!this.shouldCreateBlockLevelAssignRule(t))return;const o=this.assignTemplatesByTargetPath.get(t)||[];if(o.length)for(const r of o){const i=r!=null&&r.__key?String(r.__key):"";if(!i||this.hasAnyNonBlockAssignRuleInstance(i))continue;const n=((r==null?void 0:r.mode)==="default"?"default":"assign")=="default"?"default":"system",l=(r==null?void 0:r.enable)!==!1,a=this.getAssignRuleBlockId(i);if(this.rules.has(a))continue;const c={id:a,source:n,priority:10+(r.__order||0),debounceMs:0,getEnabled:()=>l&&!!t,getTarget:()=>t,getValue:()=>r==null?void 0:r.value,getCondition:()=>r==null?void 0:r.condition,getContext:()=>this.options.getBlockContext()};this.rules.set(a,{rule:c,state:{deps:new Set,depDisposers:[],runSeq:0,scheduledAtWriteSeq:0}}),this.scheduleRule(a)}}getCollectionFromContext(t){var o,r,i;return(i=t==null?void 0:t.collection)!=null?i:(r=(o=t==null?void 0:t.model)==null?void 0:o.context)==null?void 0:r.collection}getRootCollection(){const t=this.options.getBlockContext();return this.getCollectionFromContext(t)}shouldCreateBlockLevelAssignRule(t){var o,r;const i=this.options.getBlockContext();let n=this.getCollectionFromContext(i);if(!(n!=null&&n.getField))return!0;const l=parsePathString(t).filter(a=>typeof a!="object");if(l.length<=1)return!0;for(let a=0;a<l.length-1;a++){const c=l[a];if(typeof c!="string")continue;const u=(o=n==null?void 0:n.getField)==null?void 0:o.call(n,c);if(!((r=u==null?void 0:u.isAssociationField)!=null&&r.call(u)))break;if(isToManyAssociationField(u)){if(typeof l[a+1]!="number")return!1;a+=1}if(n=u==null?void 0:u.targetCollection,!(n!=null&&n.getField))break}return!0}collectAssociationPrefixPaths(t,o){var r,i;const n=[];let l=this.getRootCollection()||this.getCollectionFromContext(t);if(!(l!=null&&l.getField))return n;const a=[];for(let c=0;c<o.length-1;c++){const u=o[c];if(typeof u!="string")break;const d=(r=l==null?void 0:l.getField)==null?void 0:r.call(l,u);if(!((i=d==null?void 0:d.isAssociationField)!=null&&i.call(d)))break;if(a.push(u),isToManyAssociationField(d)){const m=o[c+1];if(typeof m!="number")break;a.push(m),c+=1}if(n.push([...a]),l=d==null?void 0:d.targetCollection,!(l!=null&&l.getField))break}return n}shouldSkipToManyAssociationWriteWithoutIndex(t,o){var r,i;let n=this.getRootCollection()||this.getCollectionFromContext(t);if(!(n!=null&&n.getField))return!1;for(let l=0;l<o.length-1;l++){const a=o[l];if(typeof a!="string")continue;const c=(r=n==null?void 0:n.getField)==null?void 0:r.call(n,a);if(!((i=c==null?void 0:c.isAssociationField)!=null&&i.call(c)))break;if(isToManyAssociationField(c)){if(typeof o[l+1]!="number")return!0;l+=1}if(n=c==null?void 0:c.targetCollection,!(n!=null&&n.getField))break}return!1}shouldSkipAssociationNestedWrite(t,o){const r=this.collectAssociationPrefixPaths(t,o);if(!r.length)return!1;for(const i of r){const n=this.options.getFormValueAtPath(i);if(n==null){const l=i.filter(a=>typeof a=="string").join(".");if(l&&this.getUpdateAssociationForTargetPath(l)||this.isAssociationTargetKeyWrite(t,o,i))continue;return!0}if(typeof n!="object")return!0}return!1}getAssociationTargetKeyFields(t){var o,r,i,n,l;const a=(l=(n=(r=t==null?void 0:t.targetKey)!=null?r:(o=t==null?void 0:t.targetCollection)==null?void 0:o.filterTargetKey)!=null?n:(i=t==null?void 0:t.targetCollection)==null?void 0:i.filterByTk)!=null?l:"id";return Array.isArray(a)?a.filter(c=>typeof c=="string"&&!!c):typeof a=="string"&&a?[a]:["id"]}resolveAssociationFieldByPrefixPath(t,o){var r,i;let n=this.getRootCollection()||this.getCollectionFromContext(t);if(!(n!=null&&n.getField))return null;let l=null;for(const a of o){if(typeof a=="number")continue;if(typeof a!="string"||!a)break;const c=(r=n==null?void 0:n.getField)==null?void 0:r.call(n,a);if(!((i=c==null?void 0:c.isAssociationField)!=null&&i.call(c))||(l=c,n=c==null?void 0:c.targetCollection,!(n!=null&&n.getField)))break}return l}isAssociationTargetKeyWrite(t,o,r){var i;if(!Array.isArray(o)||!Array.isArray(r)||o.length!==r.length+1)return!1;const n=o[r.length];if(typeof n!="string"||!n)return!1;const l=this.resolveAssociationFieldByPrefixPath(t,r);return!((i=l==null?void 0:l.isAssociationField)!=null&&i.call(l))||isToManyAssociationField(l)?!1:this.getAssociationTargetKeyFields(l).includes(n)}collectUpdateAssociationInitPatches(t,o){const r=this.collectAssociationPrefixPaths(t,o);if(!r.length)return[];const i=[];for(const l of r){const a=this.options.getFormValueAtPath(l);if(a==null){const c=l.filter(u=>typeof u=="string").join(".");if(!c)return null;if(this.getUpdateAssociationForTargetPath(c)){i.push({path:[...l,"__is_new__"],value:!0});continue}if(this.isAssociationTargetKeyWrite(t,o,l)){i.push({path:[...l],value:{}});continue}return null}if(typeof a!="object")return null}const n=new Map;for(const l of i){const a=namePathToPathKey(l.path);n.has(a)||n.set(a,l)}return Array.from(n.values())}dispose(){for(const{state:t}of this.rules.values())t.depDisposers.forEach(o=>o());this.rules.clear(),this.pendingRuleIds.clear(),this.assignTemplatesByTargetPath.clear();for(const t of this.defaultRuleMasterDisposers.values())t();this.defaultRuleMasterDisposers.clear(),this.defaultRuleIdsByMasterUid.clear();for(const t of this.ruleDebounceTimersById.values())clearTimeout(t);this.ruleDebounceTimersById.clear(),this.ruleDebounceUntilById.clear()}enable(){this.rulesEnabled=!0,this.pendingRuleIds.size&&!this.runningRules&&this.flushRules()}syncAssignRules(t){if(this.options.isDisposed())return;const o=(Array.isArray(t)?t:[]).map((a,c)=>I(x({},a),{key:a!=null&&a.key?String(a.key):`idx:${c}`})),r="form-assign:";for(const a of Array.from(this.rules.keys()))a.startsWith(r)&&this.removeRule(a);this.assignTemplatesByTargetPath.clear(),this.formItemTargetPaths.clear(),this.updateAssociationByTargetPath.clear();let i=0;for(const a of o){const c=a!=null&&a.targetPath?String(a.targetPath):"";if(!c)continue;const u=this.assignTemplatesByTargetPath.get(c)||[];i+=1,u.push(I(x({},a),{__key:String(a.key),__order:i})),this.assignTemplatesByTargetPath.set(c,u)}const n=this.options.getEngine(),l=new Set;if(n!=null&&n.forEachModel){n.forEachModel(c=>{var u;if(!this.isModelInThisForm(c)||!((u=c==null?void 0:c.subModels)!=null&&u.field))return;const d=this.getModelTargetPath(c);d&&this.formItemTargetPaths.add(d),this.cacheUpdateAssociationForModel(c)});const a=c=>{this.cacheUpdateAssociationForModel(c),this.tryRegisterAssignRuleInstancesForModel(c,l);const u=c==null?void 0:c.forks;u&&typeof u.forEach=="function"&&u.forEach(d=>{!d||d!=null&&d.disposed||this.tryRegisterAssignRuleInstancesForModel(d,l)})};n.forEachModel(c=>{a(c)})}for(const[a,c]of this.assignTemplatesByTargetPath.entries())if(!l.has(a)&&this.shouldCreateBlockLevelAssignRule(a))for(const u of c){const d=((u==null?void 0:u.mode)==="default"?"default":"assign")=="default"?"default":"system",m=(u==null?void 0:u.enable)!==!1,p=`${r}${u.__key}:block`;this.rules.has(p)&&this.removeRule(p);const h={id:p,source:d,priority:10+(u.__order||0),debounceMs:0,getEnabled:()=>m&&!!a,getTarget:()=>a,getValue:()=>u==null?void 0:u.value,getCondition:()=>u==null?void 0:u.condition,getContext:()=>this.options.getBlockContext()};this.rules.set(p,{rule:h,state:{deps:new Set,depDisposers:[],runSeq:0,scheduledAtWriteSeq:0}}),this.scheduleRule(p)}for(const a of Array.from(this.rules.keys()))a.startsWith("default:")&&this.scheduleRule(a)}onModelMounted(t){var o;if(this.isModelInThisForm(t)&&!(t!=null&&t.isFork)&&(o=t==null?void 0:t.subModels)!=null&&o.field){const r=this.getModelTargetPath(t);r&&this.formItemTargetPaths.add(r),this.cacheUpdateAssociationForModel(t)}this.tryRegisterDefaultRuleInstance(t),this.tryRegisterAssignRuleInstancesForModel(t)}onModelUnmounted(t){var o;if(this.tryUnregisterDefaultRuleInstance(t),this.tryUnregisterAssignRuleInstancesForModel(t),this.isModelInThisForm(t)&&(o=t==null?void 0:t.subModels)!=null&&o.field){const r=this.getModelTargetPath(t);if(r&&(this.ensureBlockAssignRuleInstancesForTargetPath(r),!(t!=null&&t.isFork))){this.updateAssociationByTargetPath.delete(r),this.formItemTargetPaths.delete(r);const i=`${r}.`;for(const l of this.assignTemplatesByTargetPath.keys())l.startsWith(i)&&this.ensureBlockAssignRuleInstancesForTargetPath(l);const n=this.options.getEngine();if(n!=null&&n.forEachModel){const l=a=>{this.tryRegisterAssignRuleInstancesForModel(a);const c=a==null?void 0:a.forks;c&&typeof c.forEach=="function"&&c.forEach(u=>{!u||u!=null&&u.disposed||this.tryRegisterAssignRuleInstancesForModel(u)})};n.forEachModel(a=>l(a))}}}}isModelInThisForm(t){var o;const r=(o=t==null?void 0:t.context)==null?void 0:o.blockModel;return r?String(r.uid)===String(this.options.getBlockModelUid()):!1}cacheUpdateAssociationForModel(t){var o,r;if(this.options.isDisposed()||!this.isModelInThisForm(t)||!t||typeof t!="object"||t!=null&&t.isFork||!((o=t==null?void 0:t.subModels)!=null&&o.field))return;const i=this.getModelTargetPath(t);if(!i)return;const n=(r=t==null?void 0:t.subModels)==null?void 0:r.field,l=!!(n!=null&&n.updateAssociation);this.updateAssociationByTargetPath.get(i)!==!0&&this.updateAssociationByTargetPath.set(i,l)}getUpdateAssociationForTargetPath(t){const o=String(t||"");if(!o)return!1;if(this.updateAssociationByTargetPath.has(o))return!!this.updateAssociationByTargetPath.get(o);const r=this.options.getEngine();return r!=null&&r.forEachModel&&r.forEachModel(i=>{this.cacheUpdateAssociationForModel(i)}),this.updateAssociationByTargetPath.has(o)?!!this.updateAssociationByTargetPath.get(o):(this.updateAssociationByTargetPath.set(o,!1),!1)}getDefaultRuleId(t){var o;const r=t!=null&&t.isFork?String((o=t==null?void 0:t.forkId)!=null?o:"fork"):"master";return`default:${t!=null&&t.uid?String(t.uid):String(t)}:${r}`}getModelTargetNamePath(t){var o;const r=(o=t==null?void 0:t.context)==null?void 0:o.fieldPathArray;if(Array.isArray(r)&&r.length)return r;const i=typeof(t==null?void 0:t.getProps)=="function"?t.getProps():t==null?void 0:t.props,n=i==null?void 0:i.name;return Array.isArray(n)?n:typeof n=="string"?n.includes(".")?n.split("."):[n]:null}getAssignTemplateTargetPathForModel(t){const o=this.getModelTargetPath(t);if(o)return o;const r=this.getModelTargetNamePath(t);if(!(r!=null&&r.length))return"";const i=r.filter(n=>typeof n!="number");return i.length?namePathToPathKey(i):""}hasAssignTemplateForTargetPath(t){const o=String(t||"");return o?this.assignTemplatesByTargetPath.has(o):!1}tryRegisterDefaultRuleInstance(t){if(this.options.isDisposed()||!this.isModelInThisForm(t)||!t||typeof t!="object")return;const o=typeof t.getProps=="function"?t.getProps():t.props;if(!o||typeof o!="object")return;const r=this.getModelTargetNamePath(t);if(!r)return;const i=this.getDefaultRuleId(t);if(this.rules.has(i))return;const n=t.master||t,l=this.getAssignTemplateTargetPathForModel(t);this.bindMasterInitialValue(n,i);const a=()=>{var g,f;const _=(f=(g=n==null?void 0:n.getProps)==null?void 0:g.call(n))!=null?f:n==null?void 0:n.props;return _==null?void 0:_.initialValue},c=a();let u=!1;const d=()=>{const g=a();if(!u&&!import_lodash.default.isEqual(g,c)&&(u=!0),!this.hasAssignTemplateForTargetPath(l)||u||typeof c>"u")return g},m=()=>typeof d()<"u"?LINKAGE_DEFAULT_RULE_PRIORITY:0,p=()=>{var g,f,_,v;if(!this.hasAssignTemplateForTargetPath(l))try{const b=(f=(g=n==null?void 0:n.getStepParams)==null?void 0:g.call(n,"editItemSettings","initialValue"))==null?void 0:f.defaultValue;if(typeof b<"u")return b;const F=(v=(_=n==null?void 0:n.getStepParams)==null?void 0:_.call(n,"formItemSettings","initialValue"))==null?void 0:v.defaultValue;if(typeof F<"u")return F}catch{}},h={id:i,source:"default",priority:m(),debounceMs:0,getEnabled:()=>typeof d()<"u"?!0:typeof p()<"u",getTarget:()=>this.getModelTargetNamePath(t)||r,getValue:()=>{const g=d();return typeof g<"u"?g:p()},getContext:()=>t==null?void 0:t.context};this.rules.set(i,{rule:h,state:{deps:new Set,depDisposers:[],runSeq:0,scheduledAtWriteSeq:0}}),this.scheduleRule(i)}getModelTargetPath(t){var o;try{const n=(o=t==null?void 0:t.getStepParams)==null?void 0:o.call(t,"fieldSettings","init"),l=n==null?void 0:n.fieldPath;if(l)return String(l)}catch{}const r=t==null?void 0:t.fieldPath;if(r)return String(r);const i=this.getModelTargetNamePath(t);return i!=null&&i.length&&i.filter(n=>typeof n=="string").join(".")||null}getAssignRuleInstanceId(t,o){var r;const i=o!=null&&o.isFork?String((r=o==null?void 0:o.forkId)!=null?r:"fork"):"master",n=o!=null&&o.uid?String(o.uid):String(o);return`form-assign:${t}:${n}:${i}`}getDeepestFieldIndexKey(t){var o,r,i;const n=(i=(r=(o=t==null?void 0:t.model)==null?void 0:o.context)==null?void 0:r.fieldIndex)!=null?i:t==null?void 0:t.fieldIndex,l=Array.isArray(n)?n:[];if(!l.length)return null;const a=l[l.length-1];if(typeof a!="string")return null;const[c,u]=a.split(":");if(!c)return null;const d=Number(u);return Number.isNaN(d)?null:c}getDeepestToManyAssociationKey(t){var o,r;const i=this.getRootCollection();if(!(i!=null&&i.getField))return null;const n=parsePathString(String(t||"")).filter(c=>typeof c!="object");if(n.length<2)return null;let l=i,a=null;for(let c=0;c<n.length-1;c++){const u=n[c];if(typeof u!="string")continue;const d=(o=l==null?void 0:l.getField)==null?void 0:o.call(l,u);if(!((r=d==null?void 0:d.isAssociationField)!=null&&r.call(d)))break;const m=isToManyAssociationField(d);if(m&&(a=u),m&&typeof n[c+1]=="number"&&(c+=1),l=d==null?void 0:d.targetCollection,!(l!=null&&l.getField))break}return a}isRowGridModel(t){var o,r;if(!t||typeof t!="object"||(o=t==null?void 0:t.subModels)!=null&&o.field||!((r=t==null?void 0:t.subModels)!=null&&r.items))return!1;const i=t==null?void 0:t.context;return!!this.getDeepestFieldIndexKey(i)}tryRegisterAssignRuleInstancesForModel(t,o){var r,i,n,l;if(this.options.isDisposed()||!this.isModelInThisForm(t))return;const a=(g,f)=>{var _;if(!(!f||f.length===0)){o==null||o.add(g);for(const v of f){this.removeAssignRuleBlockInstance(v.__key),(_=t==null?void 0:t.subModels)!=null&&_.field&&this.removeRowGridAssignRuleInstances(v.__key);const b=((v==null?void 0:v.mode)==="default"?"default":"assign")=="default"?"default":"system",F=(v==null?void 0:v.enable)!==!1,y=this.getAssignRuleInstanceId(v.__key,t);this.rules.has(y)&&this.removeRule(y);const C={id:y,source:b,priority:10+(v.__order||0),debounceMs:0,getEnabled:()=>F&&!!g,getTarget:()=>g,getValue:()=>v==null?void 0:v.value,getCondition:()=>v==null?void 0:v.condition,getContext:()=>t==null?void 0:t.context};this.rules.set(y,{rule:C,state:{deps:new Set,depDisposers:[],runSeq:0,scheduledAtWriteSeq:0}}),this.scheduleRule(y)}}};if(this.isRowGridModel(t)){const g=t==null?void 0:t.context,f=this.getDeepestFieldIndexKey(g);if(f)for(const[_,v]of this.assignTemplatesByTargetPath.entries()){if(this.formItemTargetPaths.has(_))continue;const b=this.getDeepestToManyAssociationKey(_);!b||b!==f||a(_,v)}return}if(!((r=t==null?void 0:t.subModels)!=null&&r.field))return;const c=this.getModelTargetPath(t);if(!c)return;const u=this.assignTemplatesByTargetPath.get(c)||[];u.length&&a(c,u);const d=(i=t==null?void 0:t.subModels)==null?void 0:i.field,m=(n=d==null?void 0:d.context)==null?void 0:n.collectionField,p=!!((l=m==null?void 0:m.isAssociationField)!=null&&l.call(m)),h=isToManyAssociationField(m);if(p&&!h){const g=`${c}.`;for(const[f,_]of this.assignTemplatesByTargetPath.entries())!f||typeof f!="string"||f.startsWith(g)&&a(f,_)}}tryUnregisterAssignRuleInstancesForModel(t){var o,r,i,n;if(this.options.isDisposed()||!this.isModelInThisForm(t))return;const l=h=>{for(const g of h||[]){const f=this.getAssignRuleInstanceId(g.__key,t);this.rules.has(f)&&this.removeRule(f)}};if(this.isRowGridModel(t)){const h=t==null?void 0:t.context,g=this.getDeepestFieldIndexKey(h);if(!g)return;for(const[f,_]of this.assignTemplatesByTargetPath.entries()){if(this.formItemTargetPaths.has(f))continue;const v=this.getDeepestToManyAssociationKey(f);!v||v!==g||l(_)}return}if(!((o=t==null?void 0:t.subModels)!=null&&o.field))return;const a=this.getModelTargetPath(t);if(!a)return;const c=this.assignTemplatesByTargetPath.get(a)||[];c.length&&l(c);const u=(r=t==null?void 0:t.subModels)==null?void 0:r.field,d=(i=u==null?void 0:u.context)==null?void 0:i.collectionField,m=!!((n=d==null?void 0:d.isAssociationField)!=null&&n.call(d)),p=isToManyAssociationField(d);if(m&&!p){const h=`${a}.`;for(const[g,f]of this.assignTemplatesByTargetPath.entries())!g||typeof g!="string"||g.startsWith(h)&&l(f)}}tryUnregisterDefaultRuleInstance(t){if(this.options.isDisposed()||!this.isModelInThisForm(t))return;const o=this.getDefaultRuleId(t);this.rules.has(o)&&this.removeRule(o)}bindMasterInitialValue(t,o){const r=t!=null&&t.uid?String(t.uid):o,i=this.defaultRuleIdsByMasterUid.get(r)||new Set;if(i.add(o),this.defaultRuleIdsByMasterUid.set(r,i),this.defaultRuleMasterDisposers.has(r))return;const n=(0,import_reactive.reaction)(()=>{var l,a;const c=(a=(l=t==null?void 0:t.getProps)==null?void 0:l.call(t))!=null?a:t==null?void 0:t.props;return c==null?void 0:c.initialValue},(l,a)=>{var c,u;if(import_lodash.default.isEqual(l,a))return;const d=this.defaultRuleIdsByMasterUid.get(r);if(!d)return;const m=(u=(c=t==null?void 0:t.getProps)==null?void 0:c.call(t))!=null?u:t==null?void 0:t.props,p=typeof(m==null?void 0:m.initialValue)<"u"?LINKAGE_DEFAULT_RULE_PRIORITY:0;for(const h of d){const g=this.rules.get(h);g&&(g.rule.priority=p),this.scheduleRule(h)}});this.defaultRuleMasterDisposers.set(r,n)}removeRule(t){const o=this.rules.get(t);if(!o)return;try{const i=o.rule.getContext(),n=o.rule.getTarget(),l=this.options.tryResolveNamePath(i,n);if(l){const a=namePathToPathKey(l),c=this.options.observableBindings.get(a);c&&c.source===o.rule.source&&(c.dispose(),this.options.observableBindings.delete(a))}}catch{}o.state.depDisposers.forEach(i=>i()),this.rules.delete(t),this.pendingRuleIds.delete(t);const r=this.ruleDebounceTimersById.get(t);r&&clearTimeout(r),this.ruleDebounceTimersById.delete(t),this.ruleDebounceUntilById.delete(t);for(const[i,n]of this.defaultRuleIdsByMasterUid.entries()){if(!n.has(t)||(n.delete(t),n.size>0))continue;this.defaultRuleIdsByMasterUid.delete(i);const l=this.defaultRuleMasterDisposers.get(i);l&&l(),this.defaultRuleMasterDisposers.delete(i)}}scheduleRule(t){var o;if(this.options.isDisposed())return;const r=this.rules.get(t);if(!r)return;const{rule:i,state:n}=r;n.scheduledAtWriteSeq=this.options.getWriteSeq();const l=(o=i==null?void 0:i.debounceMs)!=null?o:0;if(this.pendingRuleIds.add(t),l>0){const a=Date.now()+l,c=this.ruleDebounceUntilById.get(t)||0;a>c&&this.ruleDebounceUntilById.set(t,a);const u=this.ruleDebounceTimersById.get(t);u&&clearTimeout(u);const d=setTimeout(()=>{this.ruleDebounceTimersById.delete(t),this.rulesEnabled&&(this.runningRules||this.pendingRuleIds.has(t)&&this.flushRules())},l);this.ruleDebounceTimersById.set(t,d)}else{const a=this.ruleDebounceTimersById.get(t);a&&clearTimeout(a),this.ruleDebounceTimersById.delete(t),this.ruleDebounceUntilById.delete(t)}this.rulesEnabled&&(this.runningRules||this.flushRules())}flushRules(){return L(this,null,function*(){if(this.runningRules)return;this.runningRules=!0;const t=this.currentRuleTxId||createTxId();this.currentRuleTxId=t;try{for(;this.pendingRuleIds.size;){const o=Date.now(),r=[];for(const i of this.pendingRuleIds)(this.ruleDebounceUntilById.get(i)||0)>o||r.push(i);if(!r.length)break;for(const i of r)this.pendingRuleIds.delete(i),this.ruleDebounceUntilById.delete(i);r.sort((i,n)=>{var l,a,c,u;const d=(l=this.rules.get(i))==null?void 0:l.rule,m=(a=this.rules.get(n))==null?void 0:a.rule,p=(c=d==null?void 0:d.priority)!=null?c:0,h=(u=m==null?void 0:m.priority)!=null?u:0;return p!==h?p-h:i.localeCompare(n)});for(const i of r)yield this.runRule(i)}}finally{this.runningRules=!1,this.currentRuleTxId=null,this.options.txWriteCounts.delete(t)}})}runRule(t){return L(this,null,function*(){var o,r;const i=this.rules.get(t);if(!i)return;const{rule:n,state:l}=i;l.runSeq+=1;const a=l.runSeq,c=l.scheduledAtWriteSeq,u=this.prepareRuleContext(n),{baseCtx:d,targetNamePath:m,targetKey:p,clearDeps:h,disposeBinding:g}=u;if(!this.shouldRunRule(n,m,p,d)){h(l),g();return}if(!m||!p){h(l),g();return}const f=m,_=p,{collector:v,evalCtx:b}=this.createRuleCollectorAndContext(n,u);if(n.getCondition&&!(yield this.evaluateRuleCondition(n,l,a,b,v)))return;const F=yield this.resolveRuleValue(n,l,a,b,v);if(F===SKIP_RULE_VALUE||a!==l.runSeq)return;this.commitRuleDeps(n,l,v);const y=this.normalizeResolvedValueForTarget(d,F),C=this.normalizeResolvedValueForAssociationTarget(d,f,y);if(n.source==="default"&&!this.checkDefaultRuleCanApply(C,f,_,h,g,l))return;if(n.source==="default"){const N=this.lastRuleWriteByTargetKey.get(_);if((N==null?void 0:N.source)==="default"&&N.priority>n.priority&&N.writeSeq>=c){g();return}}if(n.source==="system"){const N=this.options.lastWriteMetaByPathKey.get(_);if((N==null?void 0:N.source)==="linkage"&&N.writeSeq>=c){g();return}}if(this.shouldSkipAssociationNestedWrite(d,f)||this.shouldSkipToManyAssociationWriteWithoutIndex(d,f))return;const S=C;if(this.isAssociationTargetSemanticallyEqual(d,f,this.options.getFormValueAtPath(f),S))return;const P=this.collectUpdateAssociationInitPatches(d,f);if(P==null)return;if(n.source==="system"||n.source==="default"){const N=d==null?void 0:d.model,D=(o=N==null?void 0:N.subModels)==null?void 0:o.field;if(D){const w=this.getModelTargetNamePath(N);w&&namePathToPathKey(w)===_&&(N.setProps({value:C}),(r=D.setProps)==null||r.call(D,{value:C}))}}const j=this.options.getWriteSeq(),A=[...P,{path:f,value:C}];yield this.options.setFormValues(b,A,{source:n.source,txId:this.currentRuleTxId||void 0});const T=this.options.getWriteSeq();T!==j&&this.lastRuleWriteByTargetKey.set(_,{source:n.source,priority:n.priority,writeSeq:T})})}isTzAwareTargetInterface(t){return typeof t!="string"?!1:["datetime","createdAt","updatedAt","unixTimestamp"].includes(t)}normalizeDateOnlyToStartOfDayIso(t){const o=String(t||"").trim();if(!o||!/^\d{4}-\d{2}-\d{2}$/.test(o))return t;const r=(0,import_client.dayjs)(o,"YYYY-MM-DD",!0);return r.isValid()?r.startOf("day").toISOString():t}normalizeResolvedValueForTarget(t,o){var r,i,n;const l=(n=(i=(r=t==null?void 0:t.model)==null?void 0:r.context)==null?void 0:i.collectionField)==null?void 0:n.interface;return this.isTzAwareTargetInterface(l)?typeof o=="string"?this.normalizeDateOnlyToStartOfDayIso(o):Array.isArray(o)?o.map(a=>typeof a=="string"?this.normalizeDateOnlyToStartOfDayIso(a):a):o:o}isPrimitiveAssociationTargetValue(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}extractAssociationIdentity(t,o){const r=this.getAssociationTargetKeyFields(t),i=r.length===1?r[0]:null,n=a=>{if(a==null)return a;if(this.isPrimitiveAssociationTargetValue(a))return i?a:UNRESOLVED_ASSOCIATION_IDENTITY;if(!a||typeof a!="object")return UNRESOLVED_ASSOCIATION_IDENTITY;if(i)return typeof a[i]>"u"?UNRESOLVED_ASSOCIATION_IDENTITY:a[i];const c={};for(const u of r){if(typeof a[u]>"u")return UNRESOLVED_ASSOCIATION_IDENTITY;c[u]=a[u]}return c};if(isToManyAssociationField(t)){const a=Array.isArray(o)?o:[o],c=[];for(const u of a){if(u==null)continue;const d=n(u);if(d===UNRESOLVED_ASSOCIATION_IDENTITY)return UNRESOLVED_ASSOCIATION_IDENTITY;c.push(d)}return c}const l=Array.isArray(o)?o.find(a=>a!=null):o;return l==null?l:n(l)}isAssociationTargetSemanticallyEqual(t,o,r,i){var n;const l=this.resolveCollectionFieldByNamePath(t,o);if(!((n=l==null?void 0:l.isAssociationField)!=null&&n.call(l)))return import_lodash.default.isEqual(r,i);const a=this.extractAssociationIdentity(l,r),c=this.extractAssociationIdentity(l,i);return a===UNRESOLVED_ASSOCIATION_IDENTITY||c===UNRESOLVED_ASSOCIATION_IDENTITY?import_lodash.default.isEqual(r,i):import_lodash.default.isEqual(a,c)}resolveCollectionFieldByNamePath(t,o){var r,i;if(!Array.isArray(o)||!o.length)return null;let n=this.getRootCollection()||this.getCollectionFromContext(t);if(!(n!=null&&n.getField))return null;for(let l=0;l<o.length;l++){const a=o[l];if(typeof a!="string"||!a)return null;const c=(r=n==null?void 0:n.getField)==null?void 0:r.call(n,a);if(!c)return null;if(l===o.length-1)return c;if(!((i=c==null?void 0:c.isAssociationField)!=null&&i.call(c))||!(c!=null&&c.targetCollection))return null;if(isToManyAssociationField(c)){if(typeof o[l+1]!="number")return null;l+=1}if(n=c.targetCollection,!(n!=null&&n.getField))return null}return null}normalizeResolvedValueForAssociationTarget(t,o,r){var i;const n=this.resolveCollectionFieldByNamePath(t,o);if(!((i=n==null?void 0:n.isAssociationField)!=null&&i.call(n)))return r;const l=this.getAssociationTargetKeyFields(n),a=l.length===1?l[0]:null,c=d=>{if(d!=null)return a&&this.isPrimitiveAssociationTargetValue(d)?{[a]:d}:d};if(isToManyAssociationField(n))return(Array.isArray(r)?r:[r]).map(d=>c(d)).filter(d=>typeof d<"u"&&d!==null);const u=Array.isArray(r)?r.find(d=>d!=null):r;return u==null?u:c(u)}prepareRuleContext(t){const o=t.getContext(),r=t.getTarget(),i=this.options.tryResolveNamePath(o,r),n=i?namePathToPathKey(i):null;return{baseCtx:o,targetNamePath:i,targetKey:n,clearDeps:l=>{l.depDisposers.forEach(a=>a()),l.depDisposers=[],l.deps=new Set},disposeBinding:()=>{if(!n)return;const l=this.options.observableBindings.get(n);l&&l.source===t.source&&(l.dispose(),this.options.observableBindings.delete(n))}}}shouldApplyDefaultRuleInCurrentState(t){var o,r;if(((r=(o=this.options).getActionName)==null?void 0:r.call(o))!=="update")return!0;let i;try{i=t==null?void 0:t.item}catch{i=void 0}return!i||typeof i!="object"?!1:i.__is_new__===!0}shouldRunRule(t,o,r,i){return!(!t.getEnabled()||!o||!r||t.source==="default"&&(!this.shouldApplyDefaultRuleInCurrentState(i)||this.options.findExplicitHit(r)))}createRuleCollectorAndContext(t,o){const{baseCtx:r,targetNamePath:i}=o,n=t.getValue(),l=(0,import_flow_engine.isRunJSValue)(n),a={deps:new Set,wildcard:!1};if(t.getCondition&&collectStaticDepsFromTemplateValue(t.getCondition(),a),l?collectStaticDepsFromRunJSValue(n,a):collectStaticDepsFromTemplateValue(n,a),i){recordDep(i,a);for(const u of this.collectAssociationPrefixPaths(r,i))recordDep(u,a)}const c=this.createRuleEvaluationContext(r,a,i);return{collector:a,evalCtx:c,rawValue:n,isRunJS:l}}evaluateRuleCondition(t,o,r,i,n){return L(this,null,function*(){var l;const a=t.getCondition;if(!a)return!0;const c=a();let u=c;if(c)try{u=yield(l=i==null?void 0:i.resolveJsonTemplate)==null?void 0:l.call(i,c)}catch{u=c}return r!==o.runSeq?!1:c&&!evaluateCondition(i,u)?(this.commitRuleDeps(t,o,n),!1):!0})}resolveRuleValue(t,o,r,i,n){return L(this,null,function*(){const l=t.getValue();return(0,import_flow_engine.isRunJSValue)(l)?this.resolveRunJSValue(l,o,r,i,n,t):this.resolveTemplateValue(l,o,r,i,n,t)})}resolveRunJSValue(t,o,r,i,n,l){return L(this,null,function*(){try{const{code:a,version:c}=(0,import_flow_engine.normalizeRunJSValue)(t),u=yield(0,import_flow_engine.runjsWithSafeGlobals)(i,a,{version:c});return u!=null&&u.success?u.value:(r!==o.runSeq||this.commitRuleDeps(l,o,n),SKIP_RULE_VALUE)}catch{return r!==o.runSeq||this.commitRuleDeps(l,o,n),SKIP_RULE_VALUE}})}resolveTemplateValue(t,o,r,i,n,l){return L(this,null,function*(){var a;try{return yield(a=i==null?void 0:i.resolveJsonTemplate)==null?void 0:a.call(i,t)}catch{return r!==o.runSeq||this.commitRuleDeps(l,o,n),SKIP_RULE_VALUE}})}commitRuleDeps(t,o,r){const i=new Set(r.deps);r.wildcard&&i.add("fv:*"),this.updateRuleDeps(t,o,i)}checkDefaultRuleCanApply(t,o,r,i,n,l){if(typeof t>"u")return!1;if(this.options.findExplicitHit(r))return i(l),n(),!1;const a=this.options.getFormValueAtPath(o),c=this.options.lastDefaultValueByPathKey.get(r),u=isEmptyValue(a)||typeof c<"u"&&import_lodash.default.isEqual(a,c),d=(0,import_reactive.isObservable)(t)?(0,import_reactive.toJS)(t):t;return!u&&import_lodash.default.isEqual(a,d)?(this.options.lastDefaultValueByPathKey.set(r,d),!1):u}createRuleEvaluationContext(t,o,r){var i;const n=this.options.createTrackingFormValues(o),l=new import_flow_engine.FlowContext;try{l.delegate(t)}catch{}const a=(i=t==null?void 0:t.getPropertyOptions)==null?void 0:i.call(t,"formValues");a&&typeof a=="object"?l.defineProperty("formValues",I(x({},a),{get:()=>n,cache:!1})):l.defineProperty("formValues",{get:()=>n,cache:!1});let c,u=!1;const d=()=>{if(!u){const m=this.buildItemChainValue(t,n,r);c=m??(t==null?void 0:t.item),u=!0}return c};return l.defineProperty("item",{get:d,cache:!1}),l}buildItemChainValue(t,o,r){var i,n;const l=this.getRootCollection()||this.getCollectionFromContext(t),a=(h,g,f,_)=>({index:g,length:f,__is_new__:h==null?void 0:h.__is_new__,__is_stored__:h==null?void 0:h.__is_stored__,value:h,parentItem:_}),c=a(o,void 0,void 0,void 0);if(!r||!Array.isArray(r)||!r.length||!(l!=null&&l.getField))return;const u=[],d=[];let m=l;for(let h=0;h<r.length-1;h++){const g=r[h];if(typeof g!="string")break;const f=(i=m==null?void 0:m.getField)==null?void 0:i.call(m,g);if(!((n=f==null?void 0:f.isAssociationField)!=null&&n.call(f)))break;const _=isToManyAssociationField(f);if(d.push(g),_){const b=r[h+1];if(typeof b!="number")break;d.push(b),h+=1}const v=f==null?void 0:f.targetCollection;if(!v)break;u.push({path:[...d],toMany:_}),m=v}const p=h=>{if(h<0)return c;const g=u[h],f=import_lodash.default.get(o,g.path),_=g.path[g.path.length-1],v=g.toMany&&typeof _=="number"?_:void 0,b=(()=>{if(!g.toMany)return;const F=g.path.slice(0,-1),y=import_lodash.default.get(o,F);return Array.isArray(y)?y.length:void 0})();return a(f,v,b,p(h-1))};return u.length?p(u.length-1):void 0}getFieldIndexSignature(t){var o,r,i;const n=(i=(r=(o=t==null?void 0:t.model)==null?void 0:o.context)==null?void 0:r.fieldIndex)!=null?i:t==null?void 0:t.fieldIndex;return(Array.isArray(n)?n:[]).filter(l=>typeof l=="string").join("|")}updateRuleDeps(t,o,r){if(o.depDisposers.forEach(n=>n()),o.depDisposers=[],o.deps=r,r.has("fv:*")){const n=(0,import_reactive.reaction)(()=>this.options.changeTick.value,()=>this.scheduleRule(t.id));o.depDisposers.push(n)}const i=(()=>{try{return t.getContext()}catch{return}})();for(const n of r){if(n==="fv:*")continue;if(!n.startsWith("fv:")&&!n.startsWith("ctx:")){const p=pathKeyToNamePath(n),h=(0,import_reactive.reaction)(()=>import_lodash.default.get(this.options.valuesMirror,p),()=>this.scheduleRule(t.id));o.depDisposers.push(h);continue}if(n.startsWith("fv:")){const p=n.slice(3),h=pathKeyToNamePath(p),g=(0,import_reactive.reaction)(()=>import_lodash.default.get(this.options.valuesMirror,h),()=>this.scheduleRule(t.id));o.depDisposers.push(g);continue}const l=n.slice(4),a=l.indexOf(":"),c=a>=0?l.slice(0,a):l,u=a>=0?l.slice(a+1):"",d=u?parsePathString(u).filter(p=>typeof p!="object"):[];if(c==="item"){const p=(0,import_reactive.reaction)(()=>this.getFieldIndexSignature(i),()=>this.scheduleRule(t.id));if(o.depDisposers.push(p),d.length){const h=this.options.createTrackingFormValues({deps:new Set,wildcard:!1}),g=(0,import_reactive.reaction)(()=>{var f,_;const v=(f=t.getTarget)==null?void 0:f.call(t),b=v?this.options.tryResolveNamePath(i,v):null,F=(_=this.buildItemChainValue(i,h,b))!=null?_:i==null?void 0:i.item;return import_lodash.default.get(F,d)},()=>this.scheduleRule(t.id));o.depDisposers.push(g)}continue}const m=(0,import_reactive.reaction)(()=>{const p=i?i[c]:void 0;return d.length?import_lodash.default.get(p,d):p},()=>this.scheduleRule(t.id));o.depDisposers.push(m)}}}class FormValueRuntime{constructor(t){R(this,"model"),R(this,"getForm"),R(this,"valuesMirror",(0,import_reactive.observable)({})),R(this,"explicitSet",new Set),R(this,"lastDefaultValueByPathKey",new Map),R(this,"lastWriteMetaByPathKey",new Map),R(this,"observableBindings",new Map),R(this,"changeTick",import_reactive.observable.ref(0)),R(this,"txWriteCounts",new Map),R(this,"writeSeq",0),R(this,"disposed",!1),R(this,"suppressFormCallbackDepth",0),R(this,"lastObservedChangedPaths",null),R(this,"lastObservedSource",null),R(this,"lastObservedToken",0),R(this,"formValuesProxy"),R(this,"mountedListener"),R(this,"unmountedListener"),R(this,"formPatcher"),R(this,"ruleEngine"),this.model=t.model,this.getForm=t.getForm,this.formPatcher=createFormPatcher({isSuppressed:()=>this.isSuppressed(),getCallerContext:()=>{var o;return(o=this.model)==null?void 0:o.context},setFormValues:this.setFormValues.bind(this)}),this.ruleEngine=new RuleEngine({getBlockModelUid:()=>{var o;return String((o=this.model)==null?void 0:o.uid)},getActionName:()=>{var o,r,i,n,l;return(l=(r=(o=this.model)==null?void 0:o.getAclActionName)==null?void 0:r.call(o))!=null?l:(n=(i=this.model)==null?void 0:i.context)==null?void 0:n.actionName},getBlockContext:()=>{var o;return(o=this.model)==null?void 0:o.context},getEngine:()=>{var o,r;return(r=(o=this.model)==null?void 0:o.context)==null?void 0:r.engine},getEngineModel:o=>{var r,i,n,l,a;return(a=(l=(n=(i=(r=this.model)==null?void 0:r.context)==null?void 0:i.engine)==null?void 0:n.getModel)==null?void 0:l.call(n,o))!=null?a:null},isDisposed:()=>this.disposed,valuesMirror:this.valuesMirror,changeTick:this.changeTick,getWriteSeq:()=>this.writeSeq,txWriteCounts:this.txWriteCounts,createTrackingFormValues:o=>createFormValuesProxy({valuesMirror:this.valuesMirror,basePath:[],collector:o,getFormValuesSnapshot:()=>this.getFormValuesSnapshot(),getFormValueAtPath:r=>this.getFormValueAtPath(r)}),tryResolveNamePath:(o,r)=>this.tryResolveNamePath(o,r),getFormValueAtPath:o=>this.getFormValueAtPath(o),setFormValues:(o,r,i)=>this.setFormValues(o,r,i),findExplicitHit:o=>this.findExplicitHit(o),lastDefaultValueByPathKey:this.lastDefaultValueByPathKey,lastWriteMetaByPathKey:this.lastWriteMetaByPathKey,observableBindings:this.observableBindings}),this.formValuesProxy=createFormValuesProxy({valuesMirror:this.valuesMirror,basePath:[],getFormValuesSnapshot:()=>this.getFormValuesSnapshot(),getFormValueAtPath:o=>this.getFormValueAtPath(o)})}syncAssignRules(t){this.ruleEngine.syncAssignRules(t)}get formValues(){return this.disposed||this.formPatcher.patch(this.getForm()),this.formValuesProxy}getFormValuesSnapshot(){if(!this.disposed){const t=this.getForm();this.formPatcher.patch(t)}return this.getForm().getFieldsValue(!0)}getFormValueAtPath(t){var o;const r=(o=this.getForm)==null?void 0:o.call(this);if(r&&typeof r.getFieldValue=="function")return r.getFieldValue(t);if(r&&typeof r.getFieldsValue=="function"){const i=r.getFieldsValue(!0);return import_lodash.default.get(i,t)}}mount(t){var o,r;if(this.disposed)return;this.formPatcher.patch(this.getForm());const i=(r=(o=this.model)==null?void 0:o.flowEngine)==null?void 0:r.emitter;if(i&&(!this.mountedListener&&!this.unmountedListener&&(this.mountedListener=({model:n})=>{this.ruleEngine.onModelMounted(n)},this.unmountedListener=({model:n})=>{this.ruleEngine.onModelUnmounted(n)},i.on("model:mounted",this.mountedListener),i.on("model:unmounted",this.unmountedListener)),t!=null&&t.sync)){const n=this.getFormValuesSnapshot();n&&typeof n=="object"&&(import_lodash.default.merge(this.valuesMirror,n),this.bumpChangeTick()),this.ruleEngine.enable()}}dispose(){var t,o;if(this.disposed)return;this.disposed=!0,this.formPatcher.restore();const r=(o=(t=this.model)==null?void 0:t.flowEngine)==null?void 0:o.emitter;r&&this.mountedListener&&this.unmountedListener&&(r.off("model:mounted",this.mountedListener),r.off("model:unmounted",this.unmountedListener)),this.ruleEngine.dispose();for(const i of this.observableBindings.values())i.dispose();this.observableBindings.clear(),this.txWriteCounts.clear()}isSuppressed(){return this.suppressFormCallbackDepth>0}handleFormFieldsChange(t){if(this.disposed)return;const o=this.getForm();if(!o.getFieldValue)return;const r=[],i=new Set;let n=!1;for(const d of t||[]){const m=d==null?void 0:d.name,p=Array.isArray(m)?m:typeof m=="string"||typeof m=="number"?[m]:null;if(!(p!=null&&p.length))continue;const h=o.getFieldValue(p),g=import_lodash.default.get(this.valuesMirror,p);import_lodash.default.isEqual(h,g)||(n||(this.writeSeq+=1,n=!0),import_lodash.default.set(this.valuesMirror,p,h),r.push(p),(d==null?void 0:d.touched)===!0&&i.add(namePathToPathKey(p)))}if(!r.length)return;const l=this.isSuppressed();if(!l&&i.size)for(const d of i)this.markExplicit(d);if(this.bumpChangeTick(),l)return;const a=t.some(d=>(d==null?void 0:d.touched)===!0)?"user":"system",c=this.writeSeq;for(const d of r)this.lastWriteMetaByPathKey.set(namePathToPathKey(d),{source:a,writeSeq:c});this.lastObservedChangedPaths=r,this.lastObservedSource=a;const u=++this.lastObservedToken;queueMicrotask(()=>{this.disposed||this.lastObservedToken===u&&(this.lastObservedChangedPaths=null,this.lastObservedSource=null)})}handleFormValuesChange(t,o){var r;if(this.disposed||this.isSuppressed())return;const i=this.lastObservedChangedPaths&&this.lastObservedChangedPaths.length?this.lastObservedChangedPaths:Object.keys(t||{}).map(p=>[p]),n=(r=this.lastObservedSource)!=null?r:"user";this.lastObservedChangedPaths=null,this.lastObservedSource=null;const l=o&&typeof o=="object"?o:this.getFormValuesSnapshot(),a=this.deriveExplicitPaths(i,l,this.valuesMirror);let c=!1,u=!1;const d=[];for(const p of i){if(!(p!=null&&p.length))continue;const h=import_lodash.default.get(l,p),g=import_lodash.default.get(this.valuesMirror,p);import_lodash.default.isEqual(g,h)||(u||(this.writeSeq+=1,u=!0),import_lodash.default.set(this.valuesMirror,p,h),c=!0,d.push(p))}c&&this.bumpChangeTick();for(const p of a)this.markExplicit(namePathToPathKey(p));if(c){const p=this.writeSeq;for(const h of d)h!=null&&h.length&&this.lastWriteMetaByPathKey.set(namePathToPathKey(h),{source:n,writeSeq:p})}const m=createTxId();this.emitFormValuesChange({source:n,txId:m,changedPaths:i,changedValues:t,allValues:l,allValuesSnapshot:l})}deriveExplicitPaths(t,o,r){const i=[],n=new Set;for(const l of t||[]){if(!(l!=null&&l.length))continue;const a=import_lodash.default.get(r,l),c=import_lodash.default.get(o,l);this.collectExplicitDiffPaths(a,c,l,i,n)}return i}collectExplicitDiffPaths(t,o,r,i,n){if(import_lodash.default.isEqual(t,o))return 0;const l=Array.isArray(t),a=Array.isArray(o);if(l||a){if(l&&a){const d=Math.min(t.length,o.length);let m=0;for(let p=0;p<d;p++)m+=this.collectExplicitDiffPaths(t[p],o[p],[...r,p],i,n);return m}return this.pushExplicitPath(r,i,n)?1:0}const c=this.isPlainObjectValue(t),u=this.isPlainObjectValue(o);if(c||u){if(c&&u){const d=new Set([...Object.keys(t),...Object.keys(o)]);let m=0;for(const p of d)m+=this.collectExplicitDiffPaths(t[p],o[p],[...r,p],i,n);return m===0&&this.isObjectCleared(t,o)?this.pushExplicitPath(r,i,n)?1:0:m}return this.isObjectCleared(t,o)?this.pushExplicitPath(r,i,n)?1:0:this.pushExplicitPath(r,i,n)?1:0}return this.pushExplicitPath(r,i,n)?1:0}pushExplicitPath(t,o,r){if(!(t!=null&&t.length))return!1;const i=namePathToPathKey(t);return!i||r.has(i)?!1:(r.add(i),o.push([...t]),!0)}isPlainObjectValue(t){return import_lodash.default.isPlainObject(t)}isObjectCleared(t,o){return this.isPlainObjectValue(t)?!!(o==null||this.isPlainObjectValue(o)&&Object.keys(o).length===0):!1}setFormValues(t,o,r){return L(this,null,function*(){var i,n,l,a,c,u;if(this.disposed)return;const d=(i=this.getForm)==null?void 0:i.call(this);if(!d)return;const m=(n=r==null?void 0:r.source)!=null?n:"system",p=(r==null?void 0:r.triggerEvent)!==!1,h=(l=r==null?void 0:r.txId)!=null?l:createTxId(),g=(a=r==null?void 0:r.markExplicit)!=null?a:m!=="default",f=typeof(r==null?void 0:r.txId)>"u",_=m==="linkage"&&Number.isFinite(Number(r==null?void 0:r.linkageScopeDepth))?Number(r==null?void 0:r.linkageScopeDepth):0,v=m==="linkage"&&typeof(r==null?void 0:r.linkageTxId)=="string"&&r.linkageTxId?String(r.linkageTxId):void 0,b=C=>{if(m!=="linkage"||!v)return!1;const S=this.lastWriteMetaByPathKey.get(C);return!S||S.source!=="linkage"||!S.linkageTxId||S.linkageTxId!==v?!1:(Number.isFinite(Number(S.linkageScopeDepth))?Number(S.linkageScopeDepth):0)>_},F=C=>m==="linkage"?{source:m,writeSeq:C,linkageScopeDepth:_,linkageTxId:v}:{source:m,writeSeq:C},y=C=>m==="linkage"&&v?I(x({},C),{linkageTxId:v}):C;try{const C=[];if(!Array.isArray(o)){const D=Object.entries(o||{}).filter(([E])=>!b(E)),w=Object.fromEntries(D),k=D.map(([E])=>E);if(!k.length)return;k.length&&(this.writeSeq+=1),this.suppressFormCallbackDepth++;try{for(const[E,M]of D){const O=(0,import_reactive.isObservable)(M)?(0,import_reactive.toJS)(M):M;typeof d.setFieldValue=="function"?d.setFieldValue(E,O):typeof d.setFields=="function"?d.setFields([{name:E,value:O}]):(c=d.setFieldsValue)==null||c.call(d,{[E]:O}),import_lodash.default.set(this.valuesMirror,[E],O)}this.bumpChangeTick()}finally{this.suppressFormCallbackDepth--}const B=this.writeSeq;for(const E of k)this.lastWriteMetaByPathKey.set(E,F(B));if(g)for(const E of k)this.markExplicit(E);if(p){const E=this.getFormValuesSnapshot();this.emitFormValuesChange(y({source:m,txId:h,changedPaths:k.map(M=>[M]),changedValues:w,allValues:E,allValuesSnapshot:E}))}return}const S=new Map;let P=0;for(const D of o){const w=D==null?void 0:D.condition;if(w&&!evaluateCondition(t,w))continue;const k=this.resolveNamePath(t,D.path),B=namePathToPathKey(k),E=D.value,M=(0,import_reactive.isObservable)(E)?(0,import_reactive.toJS)(E):E;if(b(B))continue;const O=this.getFormValueAtPath(k);import_lodash.default.isEqual(O,M)||(P+=1,S.set(B,{order:P,namePath:k,value:M,rawValue:E,pathKey:B}))}const j=Array.from(S.values()).sort((D,w)=>D.order-w.order).map(D=>({namePath:D.namePath,value:D.value,rawValue:D.rawValue,pathKey:D.pathKey}));if(!j.length)return;const A=this.txWriteCounts.get(h)||new Map;this.txWriteCounts.set(h,A);const T=[];for(const D of j){const w=(A.get(D.pathKey)||0)+1;A.set(D.pathKey,w),!(w>MAX_WRITES_PER_PATH_PER_TX)&&T.push(D)}if(!T.length)return;this.writeSeq+=1;const N=this.writeSeq;for(const{pathKey:D,rawValue:w}of T)if(!(0,import_reactive.isObservable)(w)){const k=this.observableBindings.get(D);k&&(k.dispose(),this.observableBindings.delete(D))}this.suppressFormCallbackDepth++;try{for(const{namePath:D,value:w}of T)(u=d.setFieldValue)==null||u.call(d,D,w),import_lodash.default.set(this.valuesMirror,D,w),C.push(D);this.bumpChangeTick()}finally{this.suppressFormCallbackDepth--}for(const{pathKey:D}of T)this.lastWriteMetaByPathKey.set(D,F(N));if(g)for(const{pathKey:D}of T)this.markExplicit(D);if(m==="default")for(const{namePath:D,pathKey:w}of T){const k=this.getFormValueAtPath(D);this.lastDefaultValueByPathKey.set(w,k)}for(const{namePath:D,rawValue:w,pathKey:k}of T){if(!(0,import_reactive.isObservable)(w))continue;const B=w,E=(0,import_reactive.observe)(B,()=>{this.applyBoundValue(t,D,k,(0,import_reactive.toJS)(B),m,_,v)}),M=this.observableBindings.get(k);M&&M.dispose(),this.observableBindings.set(k,{source:m,dispose:E})}if(p){const D=this.getFormValuesSnapshot();this.emitFormValuesChange(y({source:m,txId:h,changedPaths:C,changedValues:{},allValues:D,allValuesSnapshot:D}))}}finally{f&&this.txWriteCounts.delete(h)}})}applyBoundValue(t,o,r,i,n,l,a){var c,u;if(this.disposed)return;const d=(c=this.getForm)==null?void 0:c.call(this);if(!d)return;const m=import_lodash.default.get(this.valuesMirror,o);if(import_lodash.default.isEqual(m,i))return;this.writeSeq+=1;const p=this.writeSeq;this.suppressFormCallbackDepth++;try{(u=d.setFieldValue)==null||u.call(d,o,i),import_lodash.default.set(this.valuesMirror,o,i),this.bumpChangeTick()}finally{this.suppressFormCallbackDepth--}const h=n==="linkage"?{source:n,writeSeq:p,linkageScopeDepth:Number.isFinite(Number(l))?Number(l):0,linkageTxId:typeof a=="string"&&a?a:void 0}:{source:n,writeSeq:p};this.lastWriteMetaByPathKey.set(r,h);const g=createTxId(),f=this.getFormValuesSnapshot(),_={source:n,txId:g,changedPaths:[o],changedValues:{},allValues:f,allValuesSnapshot:f};if(n==="linkage"&&a&&(_.linkageTxId=a),this.emitFormValuesChange(_),n==="default"&&this.isExplicit(r)){const v=this.observableBindings.get(r);v&&(v.dispose(),this.observableBindings.delete(r))}n==="default"&&this.lastDefaultValueByPathKey.set(r,this.getFormValueAtPath(o))}resolveNamePath(t,o){const r=this.tryResolveNamePath(t,o);if(!r)throw new Error(`Failed to resolve path '${String(o)}'`);return r}tryResolveNamePath(t,o){var r,i,n;const l=(n=(i=(r=t==null?void 0:t.model)==null?void 0:r.context)==null?void 0:i.fieldIndex)!=null?n:t==null?void 0:t.fieldIndex;return resolveDynamicNamePath(o,l)}bumpChangeTick(){this.changeTick.value+=1}emitFormValuesChange(t){var o,r,i,n;(r=(o=this.model).dispatchEvent)==null||r.call(o,"formValuesChange",t,{debounce:!0}),(n=(i=this.model.emitter)==null?void 0:i.emit)==null||n.call(i,"formValuesChange",t)}markExplicit(t){if(!this.explicitSet.has(t)){this.explicitSet.add(t);for(const o of Array.from(this.lastDefaultValueByPathKey.keys()))(o===t||o.startsWith(`${t}.`)||o.startsWith(`${t}[`))&&this.lastDefaultValueByPathKey.delete(o);for(const[o,r]of Array.from(this.observableBindings.entries()))r.source==="default"&&this.isExplicit(o)&&(r.dispose(),this.observableBindings.delete(o))}}isExplicit(t){return!!this.findExplicitHit(t)}findExplicitHit(t){if(this.explicitSet.has(t))return t;const o=pathKeyToNamePath(t),r=[];for(let i=0;i<o.length;i++){r.push(o[i]);const n=namePathToPathKey(r);if(!(!this.explicitSet.has(n)||typeof o[i+1]=="number"))return n}return null}}function collectUpdateAssociationValuesFromAssignRules(e,t){const o=Array.isArray(e)?e:[],r=new Set,i=n=>{var l,a,c,u,d;if(!t||typeof t.getField!="function"||typeof n!="string"||!n.includes("."))return null;const m=n.split(".").filter(Boolean);if(m.length<2)return null;let p=t;const h=[];let g=null,f=null;for(let _=0;_<m.length-1;_++){const v=m[_],b=(l=p==null?void 0:p.getField)==null?void 0:l.call(p,v);if(!((a=b==null?void 0:b.isAssociationField)!=null&&a.call(b))||!(b!=null&&b.targetCollection))break;h.push(v),g=h.join("."),f=b,p=b.targetCollection}if(g&&f){const _=m[m.length-1],v=(d=(u=f==null?void 0:f.targetKey)!=null?u:(c=f==null?void 0:f.targetCollection)==null?void 0:c.filterTargetKey)!=null?d:"id",b=Array.isArray(v)?v.filter(F=>typeof F=="string"&&!!F):typeof v=="string"&&v?[v]:["id"];if(typeof _=="string"&&b.includes(_))return null}return g};for(const n of o){const l=n!=null&&n.targetPath?String(n.targetPath):"";if(!l)continue;const a=i(l);a&&r.add(a)}return Array.from(r)}function createEmptyCondition(){return{logic:"$and",items:[]}}function getPropsInitialValue(e){if(!e)return;const t=typeof e.getProps=="function"?e.getProps():e.props;if(t&&typeof t.initialValue<"u")return t.initialValue}function getStepParamsInitialValue(e,t){var o,r;if(e)return(r=(o=e.getStepParams)==null?void 0:o.call(e,t,"initialValue"))==null?void 0:r.defaultValue}function createLegacyValueExtractor(e){return t=>{if(!t)return;const o=getPropsInitialValue(t);if(typeof o<"u")return o;for(const r of e){const i=getStepParamsInitialValue(t,r);if(typeof i<"u")return i}}}function deleteStepParams(e,t,o){var r,i,n;if(!((r=e==null?void 0:e.stepParams)!=null&&r[t]))return;const l=e.stepParams[t];!l||typeof l!="object"||Object.prototype.hasOwnProperty.call(l,o)&&(delete l[o],import_lodash.default.isEmpty(l)&&delete e.stepParams[t],(n=(i=e.emitter)==null?void 0:i.emit)==null||n.call(i,"onStepParamsChanged"))}function createLegacyClearer(e){return t=>{var o;if(t){(o=t.setProps)==null||o.call(t,{initialValue:void 0}),t.props&&Object.prototype.hasOwnProperty.call(t.props,"initialValue")&&delete t.props.initialValue;for(const r of e)deleteStepParams(t,r,"initialValue")}}}function collectLegacyDefaultValueRules(e,t){var o,r,i,n,l;const a=(i=(r=(o=e==null?void 0:e.subModels)==null?void 0:o.grid)==null?void 0:r.subModels)==null?void 0:i.items,c=Array.isArray(a)?a:[],u=[];for(const d of c){const m=((l=(n=d==null?void 0:d.getStepParams)==null?void 0:n.call(d,"fieldSettings","init"))==null?void 0:l.fieldPath)||(d==null?void 0:d.fieldPath),p=m?String(m):"";if(!p)continue;const h=t(d);typeof h<"u"&&u.push({key:`legacy-default:${p}`,enable:!0,targetPath:p,mode:"default",condition:createEmptyCondition(),value:h})}return u}function mergeAssignRulesWithLegacyDefaults(e,t){var o,r;const i=Array.isArray(e)?e:[],n=Array.isArray(t)?t:[];if(!n.length)return i;const l=new Set;for(const u of i){if(!u||typeof u!="object")continue;const d=u.targetPath?String(u.targetPath):"";if(d){if(u.mode==="default"){l.add(d);continue}String((o=u.key)!=null?o:"").startsWith("legacy-default:")&&l.add(d)}}const a=new Set(i.map(u=>{var d;return String((d=u.key)!=null?d:"")})),c=[];for(const u of n){const d=u.targetPath?String(u.targetPath):"";if(!d||l.has(d))continue;const m=x({},u),p=String((r=m.key)!=null?r:"");p&&a.has(p)&&(m.key=`${p}:${d}`),c.push(m)}return c.length?[...i,...c]:i}function clearLegacyDefaultValues(e,t,o){var r,i,n;const l=(n=(i=(r=e==null?void 0:e.subModels)==null?void 0:r.grid)==null?void 0:i.subModels)==null?void 0:n.items,a=Array.isArray(l)?l:[],c=[];for(const u of a)typeof t(u)<"u"&&(o(u),c.push(u));return c}const FORM_FLOW_KEYS=["editItemSettings","formItemSettings"],getLegacyFieldInitialValue=createLegacyValueExtractor(FORM_FLOW_KEYS),clearLegacyFieldInitialValue=createLegacyClearer(FORM_FLOW_KEYS);function collectLegacyDefaultValueRulesFromFormModel(e){return collectLegacyDefaultValueRules(e,getLegacyFieldInitialValue)}function clearLegacyDefaultValuesFromFormModel(e){return clearLegacyDefaultValues(e,getLegacyFieldInitialValue,clearLegacyFieldInitialValue)}const GRID_DELEGATED_STEP_KEYS={formModelSettings:new Set(["layout","assignRules"]),eventSettings:new Set(["linkageRules"])},FLOW_KEEP_MOBILE_HORIZONTAL_CLASS="nb-flow-keep-mobile-horizontal",flowKeepMobileHorizontalClassName=import_css.css`
1829
1829
  &.${FLOW_KEEP_MOBILE_HORIZONTAL_CLASS} {
1830
1830
  @media (max-width: 575px) {
1831
1831
  .ant-form-item {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocobase/client",
3
- "version": "2.0.39",
3
+ "version": "2.0.40",
4
4
  "license": "Apache-2.0",
5
5
  "main": "lib/index.js",
6
6
  "module": "es/index.mjs",
@@ -28,10 +28,10 @@
28
28
  "@formily/reactive-react": "^2.2.27",
29
29
  "@formily/shared": "^2.2.27",
30
30
  "@formily/validator": "^2.2.27",
31
- "@nocobase/evaluators": "2.0.39",
32
- "@nocobase/flow-engine": "2.0.39",
33
- "@nocobase/sdk": "2.0.39",
34
- "@nocobase/utils": "2.0.39",
31
+ "@nocobase/evaluators": "2.0.40",
32
+ "@nocobase/flow-engine": "2.0.40",
33
+ "@nocobase/sdk": "2.0.40",
34
+ "@nocobase/utils": "2.0.40",
35
35
  "@tanstack/react-table": "^8.21.3",
36
36
  "@types/tabulator-tables": "^6.2.6",
37
37
  "acorn-jsx": "^5.3.2",
@@ -96,5 +96,5 @@
96
96
  "dumi": "2.2.14",
97
97
  "dumi-theme-nocobase": "^0.2.32"
98
98
  },
99
- "gitHead": "1bef474287b73aeef2580e2b949a587435639756"
99
+ "gitHead": "31cef2047fddf5a609cc820328bc88eea79c7b82"
100
100
  }