@nocobase/plugin-async-task-manager 1.6.0-alpha.8 → 1.6.0-beta.1

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.
@@ -7,4 +7,4 @@
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
9
 
10
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("antd"),require("@nocobase/client"),require("dayjs"),require("react")):"function"==typeof define&&define.amd?define("@nocobase/plugin-async-task-manager",["antd","@nocobase/client","dayjs","react"],t):"object"==typeof exports?exports["@nocobase/plugin-async-task-manager"]=t(require("antd"),require("@nocobase/client"),require("dayjs"),require("react")):e["@nocobase/plugin-async-task-manager"]=t(e.antd,e["@nocobase/client"],e.dayjs,e.react)}(self,function(e,t,n,r){return function(){var o={379:function(e,t,n){var r,o;r=0,o=function(e){"use strict";var t,n=(t=e)&&"object"==typeof t&&"default"in t?t:{default:t},r={name:"zh-cn",weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"周日_周一_周二_周三_周四_周五_周六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),ordinal:function(e,t){return"W"===t?e+"周":e+"日"},weekStart:1,yearStart:4,formats:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY/MM/DD",LL:"YYYY年M月D日",LLL:"YYYY年M月D日Ah点mm分",LLLL:"YYYY年M月D日ddddAh点mm分",l:"YYYY/M/D",ll:"YYYY年M月D日",lll:"YYYY年M月D日 HH:mm",llll:"YYYY年M月D日dddd HH:mm"},relativeTime:{future:"%s内",past:"%s前",s:"几秒",m:"1 分钟",mm:"%d 分钟",h:"1 小时",hh:"%d 小时",d:"1 天",dd:"%d 天",M:"1 个月",MM:"%d 个月",y:"1 年",yy:"%d 年"},meridiem:function(e,t){var n=100*e+t;return n<600?"凌晨":n<900?"早上":n<1100?"上午":n<1300?"中午":n<1800?"下午":"晚上"}};return n.default.locale(r,null,!0),r},e.exports=o(n(760))},809:function(e){var t,n;t=0,n=function(){return function(e,t,n){e=e||{};var r=t.prototype,o={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function a(e,t,n,o){return r.fromToBase(e,t,n,o)}n.en.relativeTime=o,r.fromToBase=function(t,r,a,s,i){for(var c,u,l,f=a.$locale().relativeTime||o,d=e.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],p=d.length,y=0;y<p;y+=1){var m=d[y];m.d&&(c=s?n(t).diff(a,m.d,!0):a.diff(t,m.d,!0));var v=(e.rounding||Math.round)(Math.abs(c));if(l=c>0,v<=m.r||!m.r){v<=1&&y>0&&(m=d[y-1]);var b=f[m.l];i&&(v=i(""+v)),u="string"==typeof b?b.replace("%d",v):b(v,r,m.l,l);break}}if(r)return u;var h=l?f.future:f.past;return"function"==typeof h?h(u):h.replace("%s",u)},r.to=function(e,t){return a(e,t,this,!0)},r.from=function(e,t){return a(e,t,this)};var s=function(e){return e.$u?n.utc():n()};r.toNow=function(e){return this.to(s(this),e)},r.fromNow=function(e){return this.from(s(this),e)}}},e.exports=n()},772:function(e){"use strict";e.exports=t},721:function(t){"use strict";t.exports=e},760:function(e){"use strict";e.exports=n},156:function(e){"use strict";e.exports=r}},a={};function s(e){var t=a[e];if(void 0!==t)return t.exports;var n=a[e]={exports:{}};return o[e].call(n.exports,n,n.exports,s),n.exports}s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,{a:t}),t},s.d=function(e,t){for(var n in t)s.o(t,n)&&!s.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};return!function(){"use strict";s.r(i),s.d(i,{default:function(){return I},PluginAsyncExportClient:function(){return Y}});var e=s("772"),t=s("156"),n=s.n(t),r=s("721"),o=s("760"),a=s.n(o);s("379");var c=s("809"),u=s.n(c),l=JSON.parse('{"u2":"@nocobase/plugin-async-task-manager"}');function f(){var t=(0,e.useApp)();return function(e){return t.i18n.t(e,{ns:[l.u2,"client"]})}}a().extend(u());var d=function(e,t){if("success"!==e.type||!(null===(a=e.payload)||void 0===a?void 0:null===(o=a.message)||void 0===o?void 0:o.messageId))return null;var o,a,s=e.payload.message,i=s.messageId,c=s.messageValues;return n().createElement("div",{style:{marginLeft:8}},n().createElement(r.Tag,{color:"success"},t(i,c)))},p=function(){var o=w(),s=o.tasks,i=o.popoverVisible,c=o.setPopoverVisible,u=o.hasProcessingTasks,l=o.cancellingTasks,p=o.modalVisible,y=o.setModalVisible,m=o.currentError,v=o.setCurrentError,b=o.resultModalVisible,h=o.setResultModalVisible,g=o.currentTask,k=o.setCurrentTask,E=o.handleCancelTask,O=(0,e.usePlugin)("async-task-manager"),_=(0,e.useApp)(),x=(0,e.useCurrentAppInfo)(),S=f();(0,t.useEffect)(function(){var e=function(e){if(i){var t=document.querySelectorAll(".ant-popover"),n=document.querySelector(".sync-task-button"),r=!1;t.forEach(function(t){t.contains(e.target)&&(r=!0)}),(null==n?void 0:n.contains(e.target))&&(r=!0),!r&&c(!1)}};return document.addEventListener("click",e),function(){document.removeEventListener("click",e)}},[i,c]);var T=function(e){k(e),h(!0),c(!1)},C=[{title:S("Created at"),dataIndex:"createdAt",key:"createdAt",width:180,render:function(e){return n().createElement(r.Tooltip,{title:a()(e).format("YYYY-MM-DD HH:mm:ss")},a()(e).fromNow())}},{title:S("Task"),dataIndex:"title",key:"title",render:function(e,t){var n=t.title;if(!n)return"-";var r={export:S("Export"),import:S("Import"),"export-attachments":S("Export attachments")}[n.actionType]||n.actionType;return(({"export-attachments":S("Export {collection} attachments"),export:S("Export {collection} data"),import:S("Import {collection} data")})[n.actionType]||"".concat(r," ").concat(n.collection," ").concat(S("Data"))).replace("{collection}",n.collection)}},{title:S("Status"),dataIndex:"status",key:"status",width:160,render:function(t,o){var a,s={pending:{color:"default",text:S("Waiting"),icon:"ClockCircleOutlined"},running:{color:"processing",text:S("Processing"),icon:"LoadingOutlined"},success:{color:"success",text:S("Completed"),icon:"CheckCircleOutlined"},failed:{color:"error",text:S("Failed"),icon:"CloseCircleOutlined"},cancelled:{color:"warning",text:S("Cancelled"),icon:"StopOutlined"}},i=s[t.type]||{},c=i.color;return i.text,n().createElement("div",{style:{display:"flex",alignItems:"center",gap:8}},n().createElement("div",{style:{flex:1}},function(){var e,a,s={width:100,margin:0};switch(t.indicator){case"spinner":return n().createElement(r.Progress,{type:"line",size:"small",strokeWidth:4,percent:100,status:"active",showInfo:!1,style:s});case"progress":return n().createElement(r.Progress,{type:"line",size:"small",strokeWidth:4,percent:Number(((null===(e=o.progress)||void 0===e?void 0:e.current)/(null===(a=o.progress)||void 0===a?void 0:a.total)*100).toFixed(2)),status:"active",style:s,format:function(e){return"".concat(e.toFixed(1),"%")}});case"success":return n().createElement(r.Progress,{type:"line",size:"small",strokeWidth:4,percent:100,status:"success",style:s,format:function(){return""}});case"error":return n().createElement(r.Progress,{type:"line",size:"small",strokeWidth:4,percent:100,status:"exception",style:s,format:function(){return""}});default:return null}}()),n().createElement(r.Tag,{color:c,icon:(null===(a=s[t.type])||void 0===a?void 0:a.icon)?n().createElement(e.Icon,{type:s[t.type].icon}):null,style:{margin:0,padding:"0 4px",height:22,width:22}}),d(t,S))}},{title:S("Actions"),key:"actions",width:180,render:function(t,o){var a=[],s=l.has(o.taskId);return("running"===o.status.type||"pending"===o.status.type)&&a.push(n().createElement(r.Popconfirm,{key:"cancel",title:S("Confirm cancel"),description:S("Confirm cancel description"),onConfirm:function(){return E(o.taskId)},okText:S("Confirm"),cancelText:S("Cancel"),disabled:s},n().createElement(r.Button,{type:"link",size:"small",icon:n().createElement(e.Icon,{type:s?"LoadingOutlined":"StopOutlined"}),disabled:s},s?S("Cancelling"):S("Cancel")))),"success"===o.status.type&&("file"===o.status.resultType?a.push(n().createElement(r.Button,{key:"download",type:"link",size:"small",icon:n().createElement(e.Icon,{type:"DownloadOutlined"}),onClick:function(){var e,t=_.apiClient.auth.token,n=_.getApiUrl("asyncTasks:fetchFile/".concat(o.taskId,"?token=").concat(t,"&__appName=").concat((null==x?void 0:null===(e=x.data)||void 0===e?void 0:e.name)||_.name));window.open(n)}},S("Download"))):o.status.payload&&a.push(n().createElement(r.Button,{key:"view",type:"link",size:"small",icon:n().createElement(e.Icon,{type:"EyeOutlined"}),onClick:function(){return T(o)}},S("View result")))),"failed"===o.status.type&&a.push(n().createElement(r.Button,{key:"error",type:"link",size:"small",icon:n().createElement(e.Icon,{type:"ExclamationCircleOutlined"}),onClick:function(){v(o.status.errors),y(!0),c(!1)}},S("Error details"))),n().createElement(r.Space,{size:"middle"},a)}}],P=n().createElement("div",{style:{width:s.length>0?800:200}},s.length>0?n().createElement(r.Table,{columns:C,dataSource:s,size:"small",pagination:!1,rowKey:"taskId"}):n().createElement("div",{style:{padding:"24px 0",display:"flex",justifyContent:"center"}},n().createElement(r.Empty,{description:S("No tasks"),image:r.Empty.PRESENTED_IMAGE_SIMPLE})));return n().createElement(n().Fragment,null,n().createElement(r.Popover,{content:P,trigger:"hover",placement:"bottom",open:i,onOpenChange:c},n().createElement(r.Button,{className:"sync-task-button",icon:n().createElement(e.Icon,{type:"SyncOutlined",spin:u}),onClick:function(){return c(!i)}})),function(){if(!!g){var e=g.status.payload,t=O.taskResultRendererManager.get(g.title.actionType);return n().createElement(r.Modal,{title:S("Task result"),open:b,footer:[n().createElement(r.Button,{key:"close",onClick:function(){return h(!1)}},S("Close"))],onCancel:function(){return h(!1)}},t?n().createElement(t,{payload:e,task:g}):n().createElement("div",null,S("No renderer available for this task type, payload: ".concat(e))))}}(),n().createElement(r.Modal,{title:S("Error Details"),open:p,onCancel:function(){return y(!1)},footer:[n().createElement(r.Button,{key:"ok",type:"primary",onClick:function(){return y(!1)}},S("OK"))],width:400},null==m?void 0:m.map(function(e,t){return n().createElement("div",{key:t,style:{marginBottom:16}},n().createElement("div",{style:{color:"#ff4d4f",marginBottom:8}},e.message),e.code&&n().createElement("div",{style:{color:"#999",fontSize:12}},S("Error code"),": ",e.code))})))};function y(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function m(e,t,n,r,o,a,s){try{var i=e[a](s),c=i.value}catch(e){n(e);return}i.done?t(c):Promise.resolve(c).then(r,o)}function v(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){var r,o,a;r=e,o=t,a=n[t],o in r?Object.defineProperty(r,o,{value:a,enumerable:!0,configurable:!0,writable:!0}):r[o]=a})}return e}function b(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):(function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n.push.apply(n,r)}return n})(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}function h(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,o=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=o){var a=[],s=!0,i=!1;try{for(o=o.call(e);!(s=(n=o.next()).done)&&(a.push(n.value),!t||a.length!==t);s=!0);}catch(e){i=!0,r=e}finally{try{!s&&null!=o.return&&o.return()}finally{if(i)throw r}}return a}}(e,t)||g(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function g(e,t){if(e){if("string"==typeof e)return y(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return y(e,t)}}var k=(0,t.createContext)(null),w=function(){var e=(0,t.useContext)(k);if(!e)throw Error("useAsyncTask must be used within AsyncTaskManagerProvider");return e},E=function(o){var a,s,i=(0,e.useApp)(),c=f(),u=h((0,t.useState)([]),2),l=u[0],d=u[1],w=h((0,t.useState)(!1),2),E=w[0],O=w[1],_=h((0,t.useState)(!1),2),x=_[0],S=_[1],T=h((0,t.useState)(new Set),2),C=T[0],P=T[1],M=h((0,t.useState)(!1),2),j=M[0],Y=M[1],I=h((0,t.useState)(null),2),A=I[0],L=I[1],B=h((0,t.useState)(!1),2),D=B[0],z=B[1],V=h((0,t.useState)(null),2),q=V[0],N=V[1],R=h((0,t.useState)(function(){return i.isWsAuthorized}),2),H=R[0],F=R[1];(0,t.useEffect)(function(){S(l.some(function(e){return"success"!==e.status.type&&"failed"!==e.status.type}))},[l]);var W=(0,t.useCallback)(function(e){var t=e.detail;d(t?t.sort(function(e,t){return new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()}):[])},[]),G=(0,t.useCallback)(function(e){var t=e.detail;d(function(e){var n;return[t].concat(function(e){if(Array.isArray(e))return y(e)}(n=e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(n)||g(n)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()).sort(function(e,t){return new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()})}),O(!0)},[]),J=(0,t.useCallback)(function(e){var t=e.detail,n=t.taskId,r=t.progress;d(function(e){return e.map(function(e){return e.taskId===n?b(v({},e),{progress:r}):e})})},[]),$=(0,t.useCallback)(function(e){var t=e.detail,n=t.taskId,o=t.status;"cancelled"===o.type?d(function(e){return e.filter(function(e){return e.taskId!==n})}):d(function(e){return e.map(function(e){return e.taskId===n?("success"===o.type&&"success"!==e.status.type&&r.message.success(c("Task completed")),"failed"===o.type&&"failed"!==e.status.type&&r.message.error(c("Task failed")),b(v({},e),{status:o})):e})})},[]),K=(0,t.useCallback)(function(){F(!0)},[]),U=(0,t.useCallback)(function(e){var t=e.detail.taskId;P(function(e){var n=new Set(e);return n.delete(t),n}),r.message.success(c("Task cancelled"))},[]);(0,t.useEffect)(function(){return i.eventBus.addEventListener("ws:message:async-tasks",W),i.eventBus.addEventListener("ws:message:async-tasks:created",G),i.eventBus.addEventListener("ws:message:async-tasks:progress",J),i.eventBus.addEventListener("ws:message:async-tasks:status",$),i.eventBus.addEventListener("ws:message:authorized",K),i.eventBus.addEventListener("ws:message:async-tasks:cancelled",U),H&&i.ws.send(JSON.stringify({type:"request:async-tasks:list"})),function(){i.eventBus.removeEventListener("ws:message:async-tasks",W),i.eventBus.removeEventListener("ws:message:async-tasks:created",G),i.eventBus.removeEventListener("ws:message:async-tasks:progress",J),i.eventBus.removeEventListener("ws:message:async-tasks:status",$),i.eventBus.removeEventListener("ws:message:authorized",K),i.eventBus.removeEventListener("ws:message:async-tasks:cancelled",U)}},[i,W,G,J,$,K,U,H]);var Q=(s=(a=function(e){return function(e,t){var n,r,o,a,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(a){return function(i){return function(a){if(n)throw TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===a[0]||2===a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,i])}}}(this,function(t){P(function(t){return new Set(t).add(e)});try{i.ws.send(JSON.stringify({type:"request:async-tasks:cancel",payload:{taskId:e}}))}catch(t){console.error("Failed to cancel task:",t),P(function(t){var n=new Set(t);return n.delete(e),n})}return[2]})},function(){var e=this,t=arguments;return new Promise(function(n,r){var o=a.apply(e,t);function s(e){m(o,n,r,s,i,"next",e)}function i(e){m(o,n,r,s,i,"throw",e)}s(void 0)})}),function(e){return s.apply(this,arguments)});return n().createElement(k.Provider,{value:{tasks:l,popoverVisible:E,setPopoverVisible:O,hasProcessingTasks:x,cancellingTasks:C,modalVisible:j,setModalVisible:Y,currentError:A,setCurrentError:L,resultModalVisible:D,setResultModalVisible:z,currentTask:q,setCurrentTask:N,handleCancelTask:Q}},n().createElement(e.PinnedPluginListProvider,{items:l.length>0?{asyncTasks:{order:300,component:"AsyncTasks",pin:!0,snippet:"*"}}:{}},n().createElement(e.SchemaComponentOptions,{components:{AsyncTasks:p}},o.children)))};function O(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}var _=function(){var e,t,n;function r(){var e,t,n;!function(e,t){if(!(e instanceof t))throw TypeError("Cannot call a class as a function")}(this,r),e=this,t="renderers",n=new Map,t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}return e=r,t=[{key:"register",value:function(e,t){this.renderers.set(e,t)}},{key:"get",value:function(e){return this.renderers.get(e)}}],O(e.prototype,t),r}();function x(e,t,n,r,o,a,s){try{var i=e[a](s),c=i.value}catch(e){n(e);return}i.done?t(c):Promise.resolve(c).then(r,o)}function S(e,t,n){return(S=j()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&P(o,n.prototype),o}).apply(null,arguments)}function T(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function C(e){return(C=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function P(e,t){return(P=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function M(e){var t="function"==typeof Map?new Map:void 0;return(M=function(e){var n;if(null===e||(n=e,-1===Function.toString.call(n).indexOf("[native code]")))return e;if("function"!=typeof e)throw TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return S(e,arguments,C(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),P(r,e)})(e)}function j(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(j=function(){return!!e})()}var Y=function(e){var t,n,r;function o(){var e,t,n,r,a,s,i;return!function(e,t){if(!(e instanceof t))throw TypeError("Cannot call a class as a function")}(this,o),t=this,n=o,r=arguments,n=C(n),a=e=function(e,t){return t&&("object"===function(e){return e&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e}(t)||"function"==typeof t)?t:function(e){if(void 0===e)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(t,j()?Reflect.construct(n,r||[],C(t).constructor):n.apply(t,r)),s="taskResultRendererManager",i=new _,s in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,e}return!function(e,t){if("function"!=typeof t&&null!==t)throw TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&P(e,t)}(o,e),t=o,n=[{key:"load",value:function(){var e,t=this;return(e=function(){return function(e,t){var n,r,o,a,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(a){return function(i){return function(a){if(n)throw TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===a[0]||2===a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,i])}}}(this,function(e){return t.app.use(E),[2]})},function(){var t=this,n=arguments;return new Promise(function(r,o){var a=e.apply(t,n);function s(e){x(a,r,o,s,i,"next",e)}function i(e){x(a,r,o,s,i,"throw",e)}s(void 0)})})()}}],T(t.prototype,n),o}(M(e.Plugin)),I=Y}(),i}()});
10
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("antd"),require("@nocobase/client"),require("dayjs"),require("react")):"function"==typeof define&&define.amd?define("@nocobase/plugin-async-task-manager",["antd","@nocobase/client","dayjs","react"],t):"object"==typeof exports?exports["@nocobase/plugin-async-task-manager"]=t(require("antd"),require("@nocobase/client"),require("dayjs"),require("react")):e["@nocobase/plugin-async-task-manager"]=t(e.antd,e["@nocobase/client"],e.dayjs,e.react)}(self,function(e,t,n,r){return function(){var o={379:function(e,t,n){var r,o;r=0,o=function(e){"use strict";var t,n=(t=e)&&"object"==typeof t&&"default"in t?t:{default:t},r={name:"zh-cn",weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"周日_周一_周二_周三_周四_周五_周六".split("_"),weekdaysMin:"日_一_二_三_四_五_六".split("_"),months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),ordinal:function(e,t){return"W"===t?e+"周":e+"日"},weekStart:1,yearStart:4,formats:{LT:"HH:mm",LTS:"HH:mm:ss",L:"YYYY/MM/DD",LL:"YYYY年M月D日",LLL:"YYYY年M月D日Ah点mm分",LLLL:"YYYY年M月D日ddddAh点mm分",l:"YYYY/M/D",ll:"YYYY年M月D日",lll:"YYYY年M月D日 HH:mm",llll:"YYYY年M月D日dddd HH:mm"},relativeTime:{future:"%s内",past:"%s前",s:"几秒",m:"1 分钟",mm:"%d 分钟",h:"1 小时",hh:"%d 小时",d:"1 天",dd:"%d 天",M:"1 个月",MM:"%d 个月",y:"1 年",yy:"%d 年"},meridiem:function(e,t){var n=100*e+t;return n<600?"凌晨":n<900?"早上":n<1100?"上午":n<1300?"中午":n<1800?"下午":"晚上"}};return n.default.locale(r,null,!0),r},e.exports=o(n(760))},809:function(e){var t,n;t=0,n=function(){return function(e,t,n){e=e||{};var r=t.prototype,o={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function a(e,t,n,o){return r.fromToBase(e,t,n,o)}n.en.relativeTime=o,r.fromToBase=function(t,r,a,s,i){for(var c,u,l,f=a.$locale().relativeTime||o,d=e.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],p=d.length,y=0;y<p;y+=1){var m=d[y];m.d&&(c=s?n(t).diff(a,m.d,!0):a.diff(t,m.d,!0));var v=(e.rounding||Math.round)(Math.abs(c));if(l=c>0,v<=m.r||!m.r){v<=1&&y>0&&(m=d[y-1]);var b=f[m.l];i&&(v=i(""+v)),u="string"==typeof b?b.replace("%d",v):b(v,r,m.l,l);break}}if(r)return u;var h=l?f.future:f.past;return"function"==typeof h?h(u):h.replace("%s",u)},r.to=function(e,t){return a(e,t,this,!0)},r.from=function(e,t){return a(e,t,this)};var s=function(e){return e.$u?n.utc():n()};r.toNow=function(e){return this.to(s(this),e)},r.fromNow=function(e){return this.from(s(this),e)}}},e.exports=n()},772:function(e){"use strict";e.exports=t},721:function(t){"use strict";t.exports=e},760:function(e){"use strict";e.exports=n},156:function(e){"use strict";e.exports=r}},a={};function s(e){var t=a[e];if(void 0!==t)return t.exports;var n=a[e]={exports:{}};return o[e].call(n.exports,n,n.exports,s),n.exports}s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,{a:t}),t},s.d=function(e,t){for(var n in t)s.o(t,n)&&!s.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};return!function(){"use strict";s.r(i),s.d(i,{default:function(){return A},PluginAsyncExportClient:function(){return I}});var e=s("772"),t=s("156"),n=s.n(t),r=s("721"),o=s("760"),a=s.n(o);s("379");var c=s("809"),u=s.n(c),l=JSON.parse('{"u2":"@nocobase/plugin-async-task-manager"}');function f(){var t=(0,e.useApp)();return function(e){return t.i18n.t(e,{ns:[l.u2,"client"]})}}var d=(0,e.createStyles)(function(e){return{button:{color:e.token.colorTextHeaderMenu+" !important"}}});a().extend(u());var p=function(e,t){if("success"!==e.type||!(null===(a=e.payload)||void 0===a?void 0:null===(o=a.message)||void 0===o?void 0:o.messageId))return null;var o,a,s=e.payload.message,i=s.messageId,c=s.messageValues;return n().createElement("div",{style:{marginLeft:8}},n().createElement(r.Tag,{color:"success"},t(i,c)))},y=function(){var o=E(),s=o.tasks,i=o.popoverVisible,c=o.setPopoverVisible,u=o.hasProcessingTasks,l=o.cancellingTasks,y=o.modalVisible,m=o.setModalVisible,v=o.currentError,b=o.setCurrentError,h=o.resultModalVisible,g=o.setResultModalVisible,k=o.currentTask,w=o.setCurrentTask,O=o.handleCancelTask,_=(0,e.usePlugin)("async-task-manager"),x=(0,e.useApp)(),S=(0,e.useCurrentAppInfo)(),T=f(),C=d().styles;(0,t.useEffect)(function(){var e=function(e){if(i){var t=document.querySelectorAll(".ant-popover"),n=document.querySelector(".sync-task-button"),r=!1;t.forEach(function(t){t.contains(e.target)&&(r=!0)}),(null==n?void 0:n.contains(e.target))&&(r=!0),!r&&c(!1)}};return document.addEventListener("click",e),function(){document.removeEventListener("click",e)}},[i,c]);var P=function(e){w(e),g(!0),c(!1)},M=[{title:T("Created at"),dataIndex:"createdAt",key:"createdAt",width:180,render:function(e){return n().createElement(r.Tooltip,{title:a()(e).format("YYYY-MM-DD HH:mm:ss")},a()(e).fromNow())}},{title:T("Task"),dataIndex:"title",key:"title",render:function(e,t){var n=t.title;if(!n)return"-";var r={export:T("Export"),import:T("Import"),"export-attachments":T("Export attachments")}[n.actionType]||n.actionType;return(({"export-attachments":T("Export {collection} attachments"),export:T("Export {collection} data"),import:T("Import {collection} data")})[n.actionType]||"".concat(r," ").concat(n.collection," ").concat(T("Data"))).replace("{collection}",n.collection)}},{title:T("Status"),dataIndex:"status",key:"status",width:160,render:function(t,o){var a,s={pending:{color:"default",text:T("Waiting"),icon:"ClockCircleOutlined"},running:{color:"processing",text:T("Processing"),icon:"LoadingOutlined"},success:{color:"success",text:T("Completed"),icon:"CheckCircleOutlined"},failed:{color:"error",text:T("Failed"),icon:"CloseCircleOutlined"},cancelled:{color:"warning",text:T("Cancelled"),icon:"StopOutlined"}},i=s[t.type]||{},c=i.color;return i.text,n().createElement("div",{style:{display:"flex",alignItems:"center",gap:8}},n().createElement("div",{style:{flex:1}},function(){var e,a,s={width:100,margin:0};switch(t.indicator){case"spinner":return n().createElement(r.Progress,{type:"line",size:"small",strokeWidth:4,percent:100,status:"active",showInfo:!1,style:s});case"progress":return n().createElement(r.Progress,{type:"line",size:"small",strokeWidth:4,percent:Number(((null===(e=o.progress)||void 0===e?void 0:e.current)/(null===(a=o.progress)||void 0===a?void 0:a.total)*100).toFixed(2)),status:"active",style:s,format:function(e){return"".concat(e.toFixed(1),"%")}});case"success":return n().createElement(r.Progress,{type:"line",size:"small",strokeWidth:4,percent:100,status:"success",style:s,format:function(){return""}});case"error":return n().createElement(r.Progress,{type:"line",size:"small",strokeWidth:4,percent:100,status:"exception",style:s,format:function(){return""}});default:return null}}()),n().createElement(r.Tag,{color:c,icon:(null===(a=s[t.type])||void 0===a?void 0:a.icon)?n().createElement(e.Icon,{type:s[t.type].icon}):null,style:{margin:0,padding:"0 4px",height:22,width:22}}),p(t,T))}},{title:T("Actions"),key:"actions",width:180,render:function(t,o){var a=[],s=l.has(o.taskId);return("running"===o.status.type||"pending"===o.status.type)&&a.push(n().createElement(r.Popconfirm,{key:"cancel",title:T("Confirm cancel"),description:T("Confirm cancel description"),onConfirm:function(){return O(o.taskId)},okText:T("Confirm"),cancelText:T("Cancel"),disabled:s},n().createElement(r.Button,{type:"link",size:"small",icon:n().createElement(e.Icon,{type:s?"LoadingOutlined":"StopOutlined"}),disabled:s},s?T("Cancelling"):T("Cancel")))),"success"===o.status.type&&("file"===o.status.resultType?a.push(n().createElement(r.Button,{key:"download",type:"link",size:"small",icon:n().createElement(e.Icon,{type:"DownloadOutlined"}),onClick:function(){var e,t=x.apiClient.auth.token,n=x.getApiUrl("asyncTasks:fetchFile/".concat(o.taskId,"?token=").concat(t,"&__appName=").concat((null==S?void 0:null===(e=S.data)||void 0===e?void 0:e.name)||x.name));window.open(n)}},T("Download"))):o.status.payload&&a.push(n().createElement(r.Button,{key:"view",type:"link",size:"small",icon:n().createElement(e.Icon,{type:"EyeOutlined"}),onClick:function(){return P(o)}},T("View result")))),"failed"===o.status.type&&a.push(n().createElement(r.Button,{key:"error",type:"link",size:"small",icon:n().createElement(e.Icon,{type:"ExclamationCircleOutlined"}),onClick:function(){b(o.status.errors),m(!0),c(!1)}},T("Error details"))),n().createElement(r.Space,{size:"middle"},a)}}],j=n().createElement("div",{style:{width:s.length>0?800:200}},s.length>0?n().createElement(r.Table,{columns:M,dataSource:s,size:"small",pagination:!1,rowKey:"taskId"}):n().createElement("div",{style:{padding:"24px 0",display:"flex",justifyContent:"center"}},n().createElement(r.Empty,{description:T("No tasks"),image:r.Empty.PRESENTED_IMAGE_SIMPLE})));return n().createElement(n().Fragment,null,n().createElement(r.Popover,{content:j,trigger:"hover",placement:"bottom",open:i,onOpenChange:c},n().createElement(r.Button,{className:["sync-task-button",C.button].join(" "),icon:n().createElement(e.Icon,{type:"SyncOutlined",spin:u}),onClick:function(){return c(!i)}})),function(){if(!!k){var e=k.status.payload,t=_.taskResultRendererManager.get(k.title.actionType);return n().createElement(r.Modal,{title:T("Task result"),open:h,footer:[n().createElement(r.Button,{key:"close",onClick:function(){return g(!1)}},T("Close"))],onCancel:function(){return g(!1)}},t?n().createElement(t,{payload:e,task:k}):n().createElement("div",null,T("No renderer available for this task type, payload: ".concat(e))))}}(),n().createElement(r.Modal,{title:T("Error Details"),open:y,onCancel:function(){return m(!1)},footer:[n().createElement(r.Button,{key:"ok",type:"primary",onClick:function(){return m(!1)}},T("OK"))],width:400},null==v?void 0:v.map(function(e,t){return n().createElement("div",{key:t,style:{marginBottom:16}},n().createElement("div",{style:{color:"#ff4d4f",marginBottom:8}},e.message),e.code&&n().createElement("div",{style:{color:"#999",fontSize:12}},T("Error code"),": ",e.code))})))};function m(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function v(e,t,n,r,o,a,s){try{var i=e[a](s),c=i.value}catch(e){n(e);return}i.done?t(c):Promise.resolve(c).then(r,o)}function b(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){var r,o,a;r=e,o=t,a=n[t],o in r?Object.defineProperty(r,o,{value:a,enumerable:!0,configurable:!0,writable:!0}):r[o]=a})}return e}function h(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):(function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n.push.apply(n,r)}return n})(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}function g(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,o=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=o){var a=[],s=!0,i=!1;try{for(o=o.call(e);!(s=(n=o.next()).done)&&(a.push(n.value),!t||a.length!==t);s=!0);}catch(e){i=!0,r=e}finally{try{!s&&null!=o.return&&o.return()}finally{if(i)throw r}}return a}}(e,t)||k(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function k(e,t){if(e){if("string"==typeof e)return m(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return m(e,t)}}var w=(0,t.createContext)(null),E=function(){var e=(0,t.useContext)(w);if(!e)throw Error("useAsyncTask must be used within AsyncTaskManagerProvider");return e},O=function(o){var a,s,i=(0,e.useApp)(),c=f(),u=g((0,t.useState)([]),2),l=u[0],d=u[1],p=g((0,t.useState)(!1),2),E=p[0],O=p[1],_=g((0,t.useState)(!1),2),x=_[0],S=_[1],T=g((0,t.useState)(new Set),2),C=T[0],P=T[1],M=g((0,t.useState)(!1),2),j=M[0],Y=M[1],I=g((0,t.useState)(null),2),A=I[0],L=I[1],B=g((0,t.useState)(!1),2),D=B[0],z=B[1],V=g((0,t.useState)(null),2),q=V[0],N=V[1],H=g((0,t.useState)(function(){return i.isWsAuthorized}),2),R=H[0],F=H[1];(0,t.useEffect)(function(){S(l.some(function(e){return"success"!==e.status.type&&"failed"!==e.status.type}))},[l]);var W=(0,t.useCallback)(function(e){var t=e.detail;d(t?t.sort(function(e,t){return new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()}):[])},[]),G=(0,t.useCallback)(function(e){var t=e.detail;d(function(e){var n;return[t].concat(function(e){if(Array.isArray(e))return m(e)}(n=e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(n)||k(n)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()).sort(function(e,t){return new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()})}),O(!0)},[]),J=(0,t.useCallback)(function(e){var t=e.detail,n=t.taskId,r=t.progress;d(function(e){return e.map(function(e){return e.taskId===n?h(b({},e),{progress:r}):e})})},[]),$=(0,t.useCallback)(function(e){var t=e.detail,n=t.taskId,o=t.status;"cancelled"===o.type?d(function(e){return e.filter(function(e){return e.taskId!==n})}):d(function(e){return e.map(function(e){return e.taskId===n?("success"===o.type&&"success"!==e.status.type&&r.message.success(c("Task completed")),"failed"===o.type&&"failed"!==e.status.type&&r.message.error(c("Task failed")),h(b({},e),{status:o})):e})})},[]),K=(0,t.useCallback)(function(){F(!0)},[]),U=(0,t.useCallback)(function(e){var t=e.detail.taskId;P(function(e){var n=new Set(e);return n.delete(t),n}),r.message.success(c("Task cancelled"))},[]);(0,t.useEffect)(function(){return i.eventBus.addEventListener("ws:message:async-tasks",W),i.eventBus.addEventListener("ws:message:async-tasks:created",G),i.eventBus.addEventListener("ws:message:async-tasks:progress",J),i.eventBus.addEventListener("ws:message:async-tasks:status",$),i.eventBus.addEventListener("ws:message:authorized",K),i.eventBus.addEventListener("ws:message:async-tasks:cancelled",U),R&&i.ws.send(JSON.stringify({type:"request:async-tasks:list"})),function(){i.eventBus.removeEventListener("ws:message:async-tasks",W),i.eventBus.removeEventListener("ws:message:async-tasks:created",G),i.eventBus.removeEventListener("ws:message:async-tasks:progress",J),i.eventBus.removeEventListener("ws:message:async-tasks:status",$),i.eventBus.removeEventListener("ws:message:authorized",K),i.eventBus.removeEventListener("ws:message:async-tasks:cancelled",U)}},[i,W,G,J,$,K,U,R]);var Q=(s=(a=function(e){return function(e,t){var n,r,o,a,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(a){return function(i){return function(a){if(n)throw TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===a[0]||2===a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,i])}}}(this,function(t){P(function(t){return new Set(t).add(e)});try{i.ws.send(JSON.stringify({type:"request:async-tasks:cancel",payload:{taskId:e}}))}catch(t){console.error("Failed to cancel task:",t),P(function(t){var n=new Set(t);return n.delete(e),n})}return[2]})},function(){var e=this,t=arguments;return new Promise(function(n,r){var o=a.apply(e,t);function s(e){v(o,n,r,s,i,"next",e)}function i(e){v(o,n,r,s,i,"throw",e)}s(void 0)})}),function(e){return s.apply(this,arguments)});return n().createElement(w.Provider,{value:{tasks:l,popoverVisible:E,setPopoverVisible:O,hasProcessingTasks:x,cancellingTasks:C,modalVisible:j,setModalVisible:Y,currentError:A,setCurrentError:L,resultModalVisible:D,setResultModalVisible:z,currentTask:q,setCurrentTask:N,handleCancelTask:Q}},n().createElement(e.PinnedPluginListProvider,{items:l.length>0?{asyncTasks:{order:300,component:"AsyncTasks",pin:!0,snippet:"*"}}:{}},n().createElement(e.SchemaComponentOptions,{components:{AsyncTasks:y}},o.children)))};function _(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}var x=function(){var e,t,n;function r(){var e,t,n;!function(e,t){if(!(e instanceof t))throw TypeError("Cannot call a class as a function")}(this,r),e=this,t="renderers",n=new Map,t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n}return e=r,t=[{key:"register",value:function(e,t){this.renderers.set(e,t)}},{key:"get",value:function(e){return this.renderers.get(e)}}],_(e.prototype,t),r}();function S(e,t,n,r,o,a,s){try{var i=e[a](s),c=i.value}catch(e){n(e);return}i.done?t(c):Promise.resolve(c).then(r,o)}function T(e,t,n){return(T=Y()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&M(o,n.prototype),o}).apply(null,arguments)}function C(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function P(e){return(P=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function M(e,t){return(M=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function j(e){var t="function"==typeof Map?new Map:void 0;return(j=function(e){var n;if(null===e||(n=e,-1===Function.toString.call(n).indexOf("[native code]")))return e;if("function"!=typeof e)throw TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return T(e,arguments,P(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),M(r,e)})(e)}function Y(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Y=function(){return!!e})()}var I=function(e){var t,n,r;function o(){var e,t,n,r,a,s,i;return!function(e,t){if(!(e instanceof t))throw TypeError("Cannot call a class as a function")}(this,o),t=this,n=o,r=arguments,n=P(n),a=e=function(e,t){return t&&("object"===function(e){return e&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e}(t)||"function"==typeof t)?t:function(e){if(void 0===e)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(t,Y()?Reflect.construct(n,r||[],P(t).constructor):n.apply(t,r)),s="taskResultRendererManager",i=new x,s in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,e}return!function(e,t){if("function"!=typeof t&&null!==t)throw TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&M(e,t)}(o,e),t=o,n=[{key:"load",value:function(){var e,t=this;return(e=function(){return function(e,t){var n,r,o,a,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(a){return function(i){return function(a){if(n)throw TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===a[0]||2===a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,i])}}}(this,function(e){return t.app.use(O),[2]})},function(){var t=this,n=arguments;return new Promise(function(r,o){var a=e.apply(t,n);function s(e){S(a,r,o,s,i,"next",e)}function i(e){S(a,r,o,s,i,"throw",e)}s(void 0)})})()}}],C(t.prototype,n),o}(j(e.Plugin)),A=I}(),i}()});
@@ -8,12 +8,12 @@
8
8
  */
9
9
 
10
10
  module.exports = {
11
- "@nocobase/client": "1.6.0-alpha.8",
11
+ "@nocobase/client": "1.6.0-beta.1",
12
12
  "react": "18.2.0",
13
13
  "antd": "5.12.8",
14
- "@nocobase/logger": "1.6.0-alpha.8",
15
- "@nocobase/server": "1.6.0-alpha.8",
16
- "@nocobase/plugin-error-handler": "1.6.0-alpha.8",
17
- "@ant-design/icons": "5.2.6",
14
+ "@nocobase/logger": "1.6.0-beta.1",
15
+ "@nocobase/server": "1.6.0-beta.1",
16
+ "lodash": "4.17.21",
17
+ "@nocobase/plugin-error-handler": "1.6.0-beta.1",
18
18
  "dayjs": "1.11.10"
19
19
  };
@@ -1 +1 @@
1
- {"name":"uuid","version":"3.4.0","description":"RFC4122 (v1, v4, and v5) UUIDs","commitlint":{"extends":["@commitlint/config-conventional"]},"keywords":["uuid","guid","rfc4122"],"license":"MIT","bin":{"uuid":"./bin/uuid"},"devDependencies":{"@commitlint/cli":"~8.2.0","@commitlint/config-conventional":"~8.2.0","eslint":"~6.4.0","husky":"~3.0.5","mocha":"6.2.0","runmd":"1.2.1","standard-version":"7.0.0"},"scripts":{"lint":"eslint .","test":"npm run lint && mocha test/test.js","md":"runmd --watch --output=README.md README_js.md","release":"standard-version","prepare":"runmd --output=README.md README_js.md"},"browser":{"./lib/rng.js":"./lib/rng-browser.js","./lib/sha1.js":"./lib/sha1-browser.js","./lib/md5.js":"./lib/md5-browser.js"},"repository":{"type":"git","url":"https://github.com/uuidjs/uuid.git"},"husky":{"hooks":{"commit-msg":"commitlint -E HUSKY_GIT_PARAMS"}},"_lastModified":"2025-01-02T11:38:54.439Z"}
1
+ {"name":"uuid","version":"3.4.0","description":"RFC4122 (v1, v4, and v5) UUIDs","commitlint":{"extends":["@commitlint/config-conventional"]},"keywords":["uuid","guid","rfc4122"],"license":"MIT","bin":{"uuid":"./bin/uuid"},"devDependencies":{"@commitlint/cli":"~8.2.0","@commitlint/config-conventional":"~8.2.0","eslint":"~6.4.0","husky":"~3.0.5","mocha":"6.2.0","runmd":"1.2.1","standard-version":"7.0.0"},"scripts":{"lint":"eslint .","test":"npm run lint && mocha test/test.js","md":"runmd --watch --output=README.md README_js.md","release":"standard-version","prepare":"runmd --output=README.md README_js.md"},"browser":{"./lib/rng.js":"./lib/rng-browser.js","./lib/sha1.js":"./lib/sha1-browser.js","./lib/md5.js":"./lib/md5-browser.js"},"repository":{"type":"git","url":"https://github.com/uuidjs/uuid.git"},"husky":{"hooks":{"commit-msg":"commitlint -E HUSKY_GIT_PARAMS"}},"_lastModified":"2025-02-05T14:08:25.983Z"}
@@ -117,7 +117,7 @@ class BaseTaskManager extends import_events.EventEmitter {
117
117
  return task.status;
118
118
  }
119
119
  registerTaskType(taskType) {
120
- this.logger.info(`Registering task type: ${taskType.type}`);
120
+ this.logger.debug(`Registering task type: ${taskType.type}`);
121
121
  this.taskTypes.set(taskType.type, taskType);
122
122
  }
123
123
  async getTasksByTag(tagKey, tagValue) {
@@ -1,7 +1,9 @@
1
1
  import { Plugin } from '@nocobase/server';
2
2
  export declare class PluginAsyncExportServer extends Plugin {
3
+ private progressThrottles;
3
4
  afterAdd(): Promise<void>;
4
5
  beforeLoad(): Promise<void>;
6
+ getThrottledProgressEmitter(taskId: string, userId: string): Function;
5
7
  load(): Promise<void>;
6
8
  }
7
9
  export default PluginAsyncExportServer;
@@ -44,7 +44,9 @@ var import_server = require("@nocobase/server");
44
44
  var import_base_task_manager = require("./base-task-manager");
45
45
  var import_command_task_type = require("./command-task-type");
46
46
  var import_async_tasks = __toESM(require("./resourcers/async-tasks"));
47
+ var import_lodash = require("lodash");
47
48
  class PluginAsyncExportServer extends import_server.Plugin {
49
+ progressThrottles = /* @__PURE__ */ new Map();
48
50
  async afterAdd() {
49
51
  }
50
52
  async beforeLoad() {
@@ -57,11 +59,36 @@ class PluginAsyncExportServer extends import_server.Plugin {
57
59
  this.app.container.get("AsyncTaskManager").registerTaskType(import_command_task_type.CommandTaskType);
58
60
  this.app.acl.allow("asyncTasks", ["get", "fetchFile"], "loggedIn");
59
61
  }
62
+ getThrottledProgressEmitter(taskId, userId) {
63
+ if (!this.progressThrottles.has(taskId)) {
64
+ this.progressThrottles.set(
65
+ taskId,
66
+ (0, import_lodash.throttle)(
67
+ (progress) => {
68
+ this.app.emit("ws:sendToTag", {
69
+ tagKey: "userId",
70
+ tagValue: userId,
71
+ message: {
72
+ type: "async-tasks:progress",
73
+ payload: {
74
+ taskId,
75
+ progress
76
+ }
77
+ }
78
+ });
79
+ },
80
+ 500,
81
+ { leading: true, trailing: true }
82
+ )
83
+ );
84
+ }
85
+ return this.progressThrottles.get(taskId);
86
+ }
60
87
  async load() {
61
88
  this.app.resourceManager.define(import_async_tasks.default);
62
89
  const asyncTaskManager = this.app.container.get("AsyncTaskManager");
63
90
  this.app.on(`ws:message:request:async-tasks:list`, async (message) => {
64
- const { tags } = message;
91
+ const { tags, clientId } = message;
65
92
  this.app.logger.info(`Received request for async tasks with tags: ${JSON.stringify(tags)}`);
66
93
  const userTag = tags == null ? void 0 : tags.find((tag) => tag.startsWith("userId#"));
67
94
  const userId = userTag ? userTag.split("#")[1] : null;
@@ -69,9 +96,8 @@ class PluginAsyncExportServer extends import_server.Plugin {
69
96
  this.app.logger.info(`Fetching tasks for userId: ${userId}`);
70
97
  const tasks = await asyncTaskManager.getTasksByTag("userId", userId);
71
98
  this.app.logger.info(`Found ${tasks.length} tasks for userId: ${userId}`);
72
- this.app.emit("ws:sendToTag", {
73
- tagKey: "userId",
74
- tagValue: userId,
99
+ this.app.emit("ws:sendToClient", {
100
+ clientId,
75
101
  message: {
76
102
  type: "async-tasks",
77
103
  payload: tasks.map((task) => task.toJSON())
@@ -97,36 +123,31 @@ class PluginAsyncExportServer extends import_server.Plugin {
97
123
  asyncTaskManager.on("taskProgress", ({ task, progress }) => {
98
124
  const userId = task.tags["userId"];
99
125
  if (userId) {
100
- this.app.emit("ws:sendToTag", {
101
- tagKey: "userId",
102
- tagValue: userId,
103
- message: {
104
- type: "async-tasks:progress",
105
- payload: {
106
- taskId: task.taskId,
107
- progress
108
- }
109
- }
110
- });
126
+ const throttledEmit = this.getThrottledProgressEmitter(task.taskId, userId);
127
+ throttledEmit(progress);
111
128
  }
112
129
  });
113
130
  asyncTaskManager.on("taskStatusChange", ({ task, status }) => {
114
131
  const userId = task.tags["userId"];
115
- if (userId) {
116
- this.app.emit("ws:sendToTag", {
117
- tagKey: "userId",
118
- tagValue: userId,
119
- message: {
120
- type: "async-tasks:status",
121
- payload: {
122
- taskId: task.taskId,
123
- status: task.toJSON().status
124
- }
132
+ if (!userId) return;
133
+ this.app.emit("ws:sendToTag", {
134
+ tagKey: "userId",
135
+ tagValue: userId,
136
+ message: {
137
+ type: "async-tasks:status",
138
+ payload: {
139
+ taskId: task.taskId,
140
+ status: task.toJSON().status
125
141
  }
126
- });
142
+ }
143
+ });
144
+ if (status.type !== "running" && status.type !== "pending") {
145
+ const throttled = this.progressThrottles.get(task.taskId);
146
+ if (throttled) {
147
+ throttled.cancel();
148
+ this.progressThrottles.delete(task.taskId);
149
+ }
127
150
  }
128
- });
129
- asyncTaskManager.on("taskStatusChange", ({ status }) => {
130
151
  if (status.type === "success") {
131
152
  this.app.emit("workflow:dispatch");
132
153
  }
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "displayName.zh-CN": "异步任务管理器",
5
5
  "description": "Manage and monitor asynchronous tasks such as data import/export. Support task progress tracking and notification.",
6
6
  "description.zh-CN": "管理和监控数据导入导出等异步任务。支持任务进度跟踪和通知。",
7
- "version": "1.6.0-alpha.8",
7
+ "version": "1.6.0-beta.1",
8
8
  "main": "dist/server/index.js",
9
9
  "peerDependencies": {
10
10
  "@nocobase/client": "1.x",
@@ -12,5 +12,5 @@
12
12
  "@nocobase/server": "1.x",
13
13
  "@nocobase/test": "1.x"
14
14
  },
15
- "gitHead": "f7ab757a5d7fb723c96bc9c1340291e4deec03ea"
15
+ "gitHead": "69a79d1ed9660beb14ee956ec634f0c6d142acfa"
16
16
  }