plugin-file-preview-auth 1.2.2 → 1.2.3

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("@nocobase/plugin-ai/client"),require("@nocobase/plugin-file-manager/client"),require("@nocobase/client"),require("react"),require("@ant-design/icons"),require("antd")):"function"==typeof define&&define.amd?define("plugin-file-preview-auth",["@nocobase/plugin-ai/client","@nocobase/plugin-file-manager/client","@nocobase/client","react","@ant-design/icons","antd"],t):"object"==typeof exports?exports["plugin-file-preview-auth"]=t(require("@nocobase/plugin-ai/client"),require("@nocobase/plugin-file-manager/client"),require("@nocobase/client"),require("react"),require("@ant-design/icons"),require("antd")):e["plugin-file-preview-auth"]=t(e["@nocobase/plugin-ai/client"],e["@nocobase/plugin-file-manager/client"],e["@nocobase/client"],e.react,e["@ant-design/icons"],e.antd)}(self,function(e,t,n,r,i,o){return function(){var l,a,u,c,s,f,p={41:function(e){e.exports=function(e,t){return"undefined"!=typeof __deoptimization_sideEffect__&&__deoptimization_sideEffect__(e,t),t}},482:function(e){"use strict";e.exports=i},772:function(e){"use strict";e.exports=n},645:function(t){"use strict";t.exports=e},183:function(e){"use strict";e.exports=t},721:function(e){"use strict";e.exports=o},156:function(e){"use strict";e.exports=r}},d={};function m(e){var t=d[e];if(void 0!==t)return t.exports;var n=d[e]={exports:{}};return p[e](n,n.exports,m),n.exports}m.m=p,m.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return m.d(t,{a:t}),t},m.d=function(e,t){for(var n in t)m.o(t,n)&&!m.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},m.f={},m.e=function(e){return Promise.all(Object.keys(m.f).reduce(function(t,n){return m.f[n](e,t),t},[]))},m.u=function(e){return""+e+"."+({166:"17caa11c2ba40313",351:"0f0ce45c92425c8f",374:"96762d13b15e7467",514:"2a8b6aa0d2fcd4b2"})[e]+".js"},m.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}}(),m.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},l={},a="plugin-file-preview-auth:",m.l=function(e,t,n,r){if(l[e])return void l[e].push(t);if(void 0!==n)for(var i,o,u=document.getElementsByTagName("script"),c=0;c<u.length;c++){var s=u[c];if(s.getAttribute("src")==e||s.getAttribute("data-webpack")==a+n){i=s;break}}i||(o=!0,(i=document.createElement("script")).charset="utf-8",i.timeout=120,m.nc&&i.setAttribute("nonce",m.nc),i.setAttribute("data-webpack",a+n),i.src=e),l[e]=[t];var f=function(t,n){i.onerror=i.onload=null,clearTimeout(p);var r=l[e];if(delete l[e],i.parentNode&&i.parentNode.removeChild(i),r&&r.forEach(function(e){return e(n)}),t)return t(n)},p=setTimeout(f.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=f.bind(null,i.onerror),i.onload=f.bind(null,i.onload),o&&document.head.appendChild(i)},m.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(u=window.__webpack_public_path__||"/").endsWith("/")||(u+="/"),m.p=u+"static/plugins/plugin-file-preview-auth/dist/client/",c={909:0},m.f.j=function(e,t){var n=m.o(c,e)?c[e]:void 0;if(0!==n)if(n)t.push(n[2]);else{var r=new Promise(function(t,r){n=c[e]=[t,r]});t.push(n[2]=r);var i=m.p+m.u(e),o=Error();m.l(i,function(t){if(m.o(c,e)&&(0!==(n=c[e])&&(c[e]=void 0),n)){var r=t&&("load"===t.type?"missing":t.type),i=t&&t.target&&t.target.src;o.message="Loading chunk "+e+" failed.\n("+r+": "+i+")",o.name="ChunkLoadError",o.type=r,o.request=i,n[1](o)}},"chunk-"+e,e)}},s=function(e,t){var n,r,i=t[0],o=t[1],l=t[2],a=0;if(i.some(function(e){return 0!==c[e]})){for(n in o)m.o(o,n)&&(m.m[n]=o[n]);l&&l(m)}for(e&&e(t);a<i.length;a++)r=i[a],m.o(c,r)&&c[r]&&c[r][0](),c[r]=0},(f=self.webpackChunkplugin_file_preview_auth=self.webpackChunkplugin_file_preview_auth||[]).forEach(s.bind(null,0)),f.push=s.bind(null,f.push.bind(f));var v={};return!function(){"use strict";m.r(v),m.d(v,{default:function(){return eO},PluginFilePreviewAuthClient:function(){return eP}});var e=m(156),t=m.n(e),n=m(482),r=m(721),i=m(772),o=m(183),l=JSON.parse('{"u2":"plugin-file-preview-auth"}');function a(){var e=(0,i.useApp)();return function(t){return e.i18n.t(t,{ns:[l.u2,"client"]})}}var u=m(645);function c(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 s(e,t,n,r,i,o,l){try{var a=e[o](l),u=a.value}catch(e){n(e);return}a.done?t(u):Promise.resolve(u).then(r,i)}function f(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 d(e,t){return(d=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function h(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var o=[],l=!0,a=!1;try{for(i=i.call(e);!(l=(n=i.next()).done)&&(o.push(n.value),!t||o.length!==t);l=!0);}catch(e){a=!0,r=e}finally{try{l||null==i.return||i.return()}finally{if(a)throw r}}return o}}(e,t)||b(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 y(e){return function(e){if(Array.isArray(e))return c(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||b(e)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function b(e,t){if(e){if("string"==typeof e)return c(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 c(e,t)}}function g(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(g=function(){return!!e})()}var w="file-preview",x="plugin-file-preview-auth.aiEmployee";function E(e){return e?e.title&&e.extname?"".concat(e.title).concat(e.extname):e.filename||e.name||e.title||"file":"file"}var k=function(e){var t,n;if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function r(e){var t,n,i;if(!(this instanceof r))throw TypeError("Cannot call a class as a function");return n=r,i=[e],n=p(n),(t=function(e,t){var n;if(t&&("object"==((n=t)&&"undefined"!=typeof Symbol&&n.constructor===Symbol?"symbol":typeof n)||"function"==typeof t))return t;if(void 0===e)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(this,g()?Reflect.construct(n,i||[],p(this).constructor):n.apply(this,i))).state={hasError:!1},t}return r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),e&&d(r,e),n=[{key:"getDerivedStateFromError",value:function(){return{hasError:!0}}}],t=[{key:"render",value:function(){return this.state.hasError?null:this.props.children}}],f(r.prototype,t),n&&f(r,n),r}(t().Component),S=function(i){var o,l,c=i.file,f=a(),p=(0,u.useAIConfigRepository)(),d=(0,u.useChatBoxActions)().triggerTask,m=h((0,e.useState)([]),2),v=m[0],b=m[1],g=h((0,e.useState)(!1),2),k=g[0],S=g[1],C=h((0,e.useState)(!1),2),P=C[0],O=C[1];(0,e.useEffect)(function(){var e=!1;if(null==p?void 0:p.getAIEmployees){var t=p.aiEmployees||[];return t.length?void b(y(t)):(S(!0),p.getAIEmployees().then(function(t){e||b(y(t||[]))}).catch(function(){e||b([])}).finally(function(){e||S(!1)}),function(){e=!0})}},[p]);var j=(0,e.useMemo)(function(){var e=function(){try{return window.localStorage.getItem(x)||""}catch(e){return""}}();return e?y(v).sort(function(t,n){return t.username===e?-1:+(n.username===e)}):v},[v]),_=(0,e.useCallback)((o=function(e){return function(e,t){var n,r,i,o,l={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){var u=[o,a];if(n)throw TypeError("Generator is already executing.");for(;l;)try{if(n=1,r&&(i=2&u[0]?r.return:u[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,u[1])).done)return i;switch(r=0,i&&(u=[2&u[0],i.value]),u[0]){case 0:case 1:i=u;break;case 4:return l.label++,{value:u[1],done:!1};case 5:l.label++,r=u[1],u=[0];continue;case 7:u=l.ops.pop(),l.trys.pop();continue;default:if(!(i=(i=l.trys).length>0&&i[i.length-1])&&(6===u[0]||2===u[0])){l=0;continue}if(3===u[0]&&(!i||u[1]>i[0]&&u[1]<i[3])){l.label=u[1];break}if(6===u[0]&&l.label<i[1]){l.label=i[1],i=u;break}if(i&&l.label<i[2]){l.label=i[2],l.ops.push(u);break}i[2]&&l.ops.pop(),l.trys.pop();continue}u=t.call(e,l)}catch(e){u=[6,e],r=0}finally{n=i=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}(this,function(t){switch(t.label){case 0:if(!e||!c)return[2];O(!0),t.label=1;case 1:t.trys.push([1,3,4,5]);var n,i,o,l,a,u=e.username;try{window.localStorage.setItem(x,u)}catch(e){}return[4,d({aiEmployee:e,tasks:[{title:E(c),message:{user:f("Please help me analyze the file currently open in preview."),workContext:[{type:w,uid:(a=null!=(l=null!=(o=null!=(i=null!=(n=null==c?void 0:c.id)?n:null==c?void 0:c.uid)?i:null==c?void 0:c.url)?o:null==c?void 0:c.path)?l:E(c),"file-preview:".concat(String(a))),title:E(c),content:{source:"plugin-file-preview-auth",file:{id:null==c?void 0:c.id,uid:null==c?void 0:c.uid,url:null==c?void 0:c.url,preview:null==c?void 0:c.preview,filename:(null==c?void 0:c.filename)||(null==c?void 0:c.name),name:(null==c?void 0:c.name)||(null==c?void 0:c.filename),title:null==c?void 0:c.title,extname:null==c?void 0:c.extname,mimetype:null==c?void 0:c.mimetype,size:null==c?void 0:c.size,path:null==c?void 0:c.path,storageId:null==c?void 0:c.storageId}}}]},autoSend:!1}]})];case 2:return t.sent(),[3,5];case 3:return t.sent(),r.message.error(f("Failed to open AI chat")),[3,5];case 4:return O(!1),[7];case 5:return[2]}})},l=function(){var e=this,t=arguments;return new Promise(function(n,r){var i=o.apply(e,t);function l(e){s(i,n,r,l,a,"next",e)}function a(e){s(i,n,r,l,a,"throw",e)}l(void 0)})},function(e){return l.apply(this,arguments)}),[c,f,d]),A=j.map(function(e){return{key:e.username,label:(null==e?void 0:e.nickname)||(null==e?void 0:e.username)||"",onClick:function(){return _(e)}}});return k||j.length?1===j.length?t().createElement(r.Tooltip,{title:f("Ask AI")},t().createElement(r.Button,{type:"text",size:"small",icon:t().createElement(n.RobotOutlined,null),loading:P||k,onClick:function(e){e.stopPropagation(),_(j[0])}},f("Ask AI"))):t().createElement(r.Tooltip,{title:f("Ask AI")},t().createElement(r.Dropdown,{menu:{items:A},trigger:["click"],placement:"bottomRight",disabled:P||k},t().createElement(r.Button,{type:"text",size:"small",icon:t().createElement(n.RobotOutlined,null),loading:P||k,onClick:function(e){return e.stopPropagation()}},f("Ask AI")))):null},C=function(e){var n=e.file;return t().createElement(k,null,t().createElement(S,{file:n}))},P=m(41);function O(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 j(e,t,n,r,i,o,l){try{var a=e[o](l),u=a.value}catch(e){n(e);return}a.done?t(u):Promise.resolve(u).then(r,i)}function _(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function l(e){j(o,r,i,l,a,"next",e)}function a(e){j(o,r,i,l,a,"throw",e)}l(void 0)})}}function A(e,t,n){return(A=U()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&F(i,n.prototype),i}).apply(null,arguments)}function I(e){return(I=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function T(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;r=n[t],t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r})}return e}function R(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 F(e,t){return(F=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function L(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var o=[],l=!0,a=!1;try{for(i=i.call(e);!(l=(n=i.next()).done)&&(o.push(n.value),!t||o.length!==t);l=!0);}catch(e){a=!0,r=e}finally{try{l||null==i.return||i.return()}finally{if(a)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return O(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 O(e,t)}}(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 D(e){var t="function"==typeof Map?new Map:void 0;return(D=function(e){if(null===e||-1===Function.toString.call(e).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,n)}function n(){return A(e,arguments,I(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),F(n,e)})(e)}function U(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(U=function(){return!!e})()}function B(e,t){var n,r,i,o,l={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){var u=[o,a];if(n)throw TypeError("Generator is already executing.");for(;l;)try{if(n=1,r&&(i=2&u[0]?r.return:u[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,u[1])).done)return i;switch(r=0,i&&(u=[2&u[0],i.value]),u[0]){case 0:case 1:i=u;break;case 4:return l.label++,{value:u[1],done:!1};case 5:l.label++,r=u[1],u=[0];continue;case 7:u=l.ops.pop(),l.trys.pop();continue;default:if(!(i=(i=l.trys).length>0&&i[i.length-1])&&(6===u[0]||2===u[0])){l=0;continue}if(3===u[0]&&(!i||u[1]>i[0]&&u[1]<i[3])){l.label=u[1];break}if(6===u[0]&&l.label<i[1]){l.label=i[1],i=u;break}if(i&&l.label<i[2]){l.label=i[2],l.ops.push(u);break}i[2]&&l.ops.pop(),l.trys.pop();continue}u=t.call(e,l)}catch(e){u=[6,e],r=0}finally{n=i=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}var M=["application/pdf"],z=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],N=["text/plain","text/csv","text/html","text/css","text/javascript","application/json","application/xml","text/xml","text/yaml","application/x-yaml"],q=["application/vnd.openxmlformats-officedocument.wordprocessingml.document"],W=["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-excel"],H=["pdf"],V=["png","jpg","jpeg","gif","webp","svg","bmp"],X=["txt","csv","html","css","js","json","xml","log","md","yaml","yml","xaml"],G=["docx"],J=["xlsx","xls"],Y=["application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-powerpoint"],$=["pptx","ppt"],K=function(e){var t=("string"==typeof e?e:(null==e?void 0:e.extname)||(null==e?void 0:e.name)||(null==e?void 0:e.filename)||(null==e?void 0:e.url)||"").split("?")[0].split("#")[0],n=t.lastIndexOf(".");return -1!==n?t.slice(n+1).toLowerCase().replace(/^\./,""):""},Q=function(e){var t="string"==typeof e?e:null==e?void 0:e.url;return t?t.startsWith("https://")||t.startsWith("http://")?t:"".concat(location.origin,"/").concat(t.replace(/^\//,"")):""},Z=function(e){if((null==e?void 0:e.mimetype)&&M.includes(e.mimetype))return!0;var t=K(e);return!!t&&H.includes(t)},ee=function(e){if((null==e?void 0:e.mimetype)&&z.includes(e.mimetype)||(null==e?void 0:e.mimetype)&&(0,i.matchMimetype)(e,"image/*"))return!0;var t=K(e);return!!t&&V.includes(t)},et=function(e){if((null==e?void 0:e.mimetype)&&N.includes(e.mimetype))return!0;var t=K(e);return!!t&&X.includes(t)},en=function(e){if((null==e?void 0:e.mimetype)&&q.includes(e.mimetype))return!0;var t=K(e);return!!t&&G.includes(t)},er=function(e){if((null==e?void 0:e.mimetype)&&W.includes(e.mimetype))return!0;var t=K(e);return!!t&&J.includes(t)},ei=function(e){if((null==e?void 0:e.mimetype)&&Y.includes(e.mimetype))return!0;var t=K(e);return!!t&&$.includes(t)},eo=function(e){return e?e.title&&e.extname?"".concat(e.title).concat(e.extname):e.filename||e.name||e.title||"download":"download"},el=new Map;function ea(){return(ea=_(function(e,t){var n,r;return B(this,function(i){switch(i.label){case 0:return n={},t&&(n.Authorization="Bearer ".concat(t)),[4,fetch(e,{method:"GET",headers:n,credentials:"include"})];case 1:if(!(r=i.sent()).ok)throw Error("Failed to fetch file: ".concat(r.status," ").concat(r.statusText));return[2,r.blob()]}})})).apply(this,arguments)}function eu(e,t){return ec.apply(this,arguments)}function ec(){return(ec=_(function(e,t){var n,r,i;return B(this,function(o){if(!(n=Q(e)))throw Error("No file URL");return r="".concat(t?"auth":"anon",":").concat(t||"",":").concat(n),(i=el.get(r))||(i=(function(e,t){return ea.apply(this,arguments)})(n,t).catch(function(e){throw el.delete(r),e}),el.set(r,i)),[2,i]})})).apply(this,arguments)}function es(e,t){return ef.apply(this,arguments)}function ef(){return(ef=_(function(e,t){var n,r,i,o;return B(this,function(l){switch(l.label){case 0:if(!Q(e))return[2];return[4,eu(e,t)];case 1:return n=l.sent(),r=eo(e),(i=document.createElement("a")).href=o=URL.createObjectURL(n),i.download=r,document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(function(){return URL.revokeObjectURL(o)},1e3),[2]}})})).apply(this,arguments)}function ep(t,n){var r=L((0,e.useState)(null),2),i=r[0],o=r[1],l=L((0,e.useState)(!0),2),a=l[0],u=l[1],c=L((0,e.useState)(null),2),s=c[0],f=c[1],p=(0,e.useRef)(null);return(0,e.useEffect)(function(){var e=!1;if(!Q(t)){u(!1),f("No file URL");return}return u(!0),f(null),eu(t,n).then(function(t){if(!e){var n=URL.createObjectURL(t);p.current=n,o(n),u(!1)}}).catch(function(t){e||(f(t.message||"Failed to load"),u(!1))}),function(){e=!0,p.current&&(URL.revokeObjectURL(p.current),p.current=null)}},["string"==typeof t?t:null==t?void 0:t.url,n]),{blobUrl:i,loading:a,error:s}}function ed(e){var n=e.message;return t().createElement("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%",width:"100%"}},t().createElement(r.Spin,{tip:n}))}function em(e){var n=e.message;return t().createElement("div",{style:{padding:20,textAlign:"center",color:"#ff4d4f"}},n)}function ev(e){var n=e.file,r=e.title;return t().createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,paddingRight:40}},t().createElement("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:r},r),t().createElement(C,{file:n}))}function eh(e){var n,r=e.file,o=(0,i.useAPIClient)(),l=a(),u=ep(r,(null==(n=o.auth)?void 0:n.token)||""),c=u.blobUrl,s=u.loading,f=u.error;return s?t().createElement(ed,{message:l("Loading preview...")}):f||!c?t().createElement(em,{message:l("Failed to load file preview")}):t().createElement("iframe",{src:c,width:"100%",height:"100%",style:{border:"none"}})}function ey(e){var n,r=e.file,o=(0,i.useAPIClient)(),l=a(),u=ep(r,(null==(n=o.auth)?void 0:n.token)||""),c=u.blobUrl,s=u.loading,f=u.error;return s?t().createElement(ed,{message:l("Loading preview...")}):f||!c?t().createElement(em,{message:l("Failed to load file preview")}):t().createElement("img",{src:c,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},alt:(null==r?void 0:r.title)||(null==r?void 0:r.filename)||""})}function eb(n){var r,o,l,u,c,s,f,p,d,m,v=n.file,h=(0,i.useAPIClient)(),y=a(),b=(null==(m=h.auth)?void 0:m.token)||"",g=(o=(r=L((0,e.useState)(null),2))[0],l=r[1],c=(u=L((0,e.useState)(!0),2))[0],s=u[1],p=(f=L((0,e.useState)(null),2))[0],d=f[1],(0,e.useEffect)(function(){var e=!1;if(!Q(v)){s(!1),d("No file URL");return}return s(!0),d(null),eu(v,b).then(function(e){return e.text()}).then(function(t){e||(l(t),s(!1))}).catch(function(t){e||(d(t.message||"Failed to load"),s(!1))}),function(){e=!0}},["string"==typeof v?v:null==v?void 0:v.url,b]),{text:o,loading:c,error:p}),w=g.text,x=g.loading,E=g.error;return x?t().createElement(ed,{message:y("Loading preview...")}):E||null===w?t().createElement(em,{message:y("Failed to load file preview")}):t().createElement("pre",{style:{width:"100%",height:"100%",overflow:"auto",padding:16,margin:0,fontSize:13,lineHeight:1.6,whiteSpace:"pre-wrap",wordWrap:"break-word",background:"#f5f5f5",border:"none"}},w)}function eg(n){var r,o=n.file,l=(0,i.useAPIClient)(),u=a(),c=(null==(r=l.auth)?void 0:r.token)||"",s=(0,e.useRef)(null),f=L((0,e.useState)(!0),2),p=f[0],d=f[1],v=L((0,e.useState)(null),2),h=v[0],y=v[1];return(0,e.useEffect)(function(){var e=!1;if(!Q(o)||!s.current){d(!1),y("No file URL");return}return d(!0),y(null),_(function(){var t,n,r;return B(this,function(i){switch(i.label){case 0:return i.trys.push([0,4,,5]),[4,eu(o,c)];case 1:if(t=i.sent(),e)return[2];return[4,P("imported_-1dm6lbf_component",m.e("374").then(m.bind(m,335)))];case 2:if(n=i.sent(),e||!s.current)return[2];return s.current.innerHTML="",[4,n.renderAsync(t,s.current,void 0,{className:"docx-preview-wrapper",inWrapper:!0,ignoreWidth:!1,ignoreHeight:!1,ignoreFonts:!1,breakPages:!0,ignoreLastRenderedPageBreak:!0,experimental:!1,trimXmlDeclaration:!0,useBase64URL:!0,renderHeaders:!0,renderFooters:!0,renderFootnotes:!0,renderEndnotes:!0})];case 3:return i.sent(),d(!1),[3,5];case 4:if(r=i.sent(),e)return[2];return y(r.message||"Failed to render DOCX"),d(!1),[3,5];case 5:return[2]}})})(),function(){e=!0}},["string"==typeof o?o:null==o?void 0:o.url,c]),t().createElement("div",{style:{width:"100%",height:"100%",position:"relative"}},p&&t().createElement(ed,{message:u("Loading preview...")}),h&&t().createElement(em,{message:u("Failed to load file preview")}),t().createElement("div",{ref:s,style:{width:"100%",height:"100%",overflow:"auto",display:p||h?"none":"block"}}))}function ew(n){var r,o=n.file,l=(0,i.useAPIClient)(),u=a(),c=(null==(r=l.auth)?void 0:r.token)||"",s=(0,e.useRef)(null),f=L((0,e.useState)(!0),2),p=f[0],d=f[1],v=L((0,e.useState)(null),2),h=v[0],y=v[1],b=L((0,e.useState)([]),2),g=b[0],w=b[1],x=L((0,e.useState)(""),2),E=x[0],k=x[1],S=L((0,e.useState)({}),2),C=S[0],O=S[1];return(0,e.useEffect)(function(){var e=!1;if(!Q(o)){d(!1),y("No file URL");return}return d(!0),y(null),_(function(){var t,n,r,i,l,a,u,s,f,p,v,h,b,g;return B(this,function(x){switch(x.label){case 0:return x.trys.push([0,4,,5]),[4,eu(o,c)];case 1:if(t=x.sent(),e)return[2];return[4,P("imported_-1lj2ifg_component",m.e("166").then(m.bind(m,907)))];case 2:if(n=x.sent(),e)return[2];return[4,t.arrayBuffer()];case 3:if(r=x.sent(),e)return[2];l=(i=n.read(r,{type:"array"})).SheetNames,a={},u=!0,s=!1,f=void 0;try{for(p=l[Symbol.iterator]();!(u=(v=p.next()).done);u=!0)h=v.value,b=i.Sheets[h],a[h]=n.utils.sheet_to_html(b,{id:"xlsx-preview-table"})}catch(e){s=!0,f=e}finally{try{u||null==p.return||p.return()}finally{if(s)throw f}}if(e)return[2];return w(l),k(l[0]||""),O(a),d(!1),[3,5];case 4:if(g=x.sent(),e)return[2];return y(g.message||"Failed to render XLSX"),d(!1),[3,5];case 5:return[2]}})})(),function(){e=!0}},["string"==typeof o?o:null==o?void 0:o.url,c]),t().createElement("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column"}},p&&t().createElement(ed,{message:u("Loading preview...")}),h&&t().createElement(em,{message:u("Failed to load file preview")}),!p&&!h&&t().createElement(t().Fragment,null,g.length>1&&t().createElement("div",{style:{display:"flex",gap:0,borderBottom:"1px solid #e8e8e8",background:"#fafafa",padding:"0 8px",flexShrink:0,overflowX:"auto"}},g.map(function(e){return t().createElement("button",{key:e,onClick:function(){return k(e)},style:{padding:"8px 16px",border:"none",borderBottom:E===e?"2px solid #1890ff":"2px solid transparent",background:E===e?"#fff":"transparent",color:E===e?"#1890ff":"#666",fontWeight:E===e?600:400,cursor:"pointer",fontSize:13,whiteSpace:"nowrap",transition:"all 0.2s"}},e)})),t().createElement("div",{ref:s,style:{flex:1,overflow:"auto",padding:0},dangerouslySetInnerHTML:{__html:C[E]||""}}),t().createElement("style",null,"\n #xlsx-preview-table {\n border-collapse: collapse;\n width: 100%;\n font-size: 13px;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n }\n #xlsx-preview-table td,\n #xlsx-preview-table th {\n border: 1px solid #e8e8e8;\n padding: 6px 10px;\n text-align: left;\n max-width: 33vw;\n white-space: normal;\n word-break: break-word;\n }\n #xlsx-preview-table tr:first-child td,\n #xlsx-preview-table tr:first-child th {\n background: #fafafa;\n font-weight: 600;\n position: sticky;\n top: 0;\n z-index: 1;\n }\n #xlsx-preview-table tr:nth-child(even) {\n background: #fafafa;\n }\n #xlsx-preview-table tr:hover {\n background: #f0f7ff;\n }\n ")))}function ex(n){var r,o=n.file,l=(0,i.useAPIClient)(),u=a(),c=(null==(r=l.auth)?void 0:r.token)||"",s=L((0,e.useState)(!0),2),f=s[0],p=s[1],d=L((0,e.useState)(null),2),v=d[0],h=d[1],y=L((0,e.useState)(null),2),b=y[0],g=y[1],w=L((0,e.useState)(null),2),x=w[0],E=w[1];return(0,e.useEffect)(function(){var e=!1;if(!Q(o)){p(!1),h("No file URL");return}return p(!0),h(null),_(function(){var t,n,r,i,l;return B(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),[4,Promise.all([eu(o,c),P("imported_tpp3om_component",m.e("514").then(m.bind(m,581)))])];case 1:if(n=(t=L.apply(void 0,[a.sent(),2]))[0],r=t[1],e)return[2];return[4,n.arrayBuffer()];case 2:if(i=a.sent(),e)return[2];return g(i),E(function(){return r.PptxPreview}),p(!1),[3,4];case 3:if(l=a.sent(),e)return[2];return h(l.message||"Failed to render PPTX"),p(!1),[3,4];case 4:return[2]}})})(),function(){e=!0}},["string"==typeof o?o:null==o?void 0:o.url,c]),t().createElement("div",{style:{width:"100%",height:"100%",position:"relative"}},f&&t().createElement(ed,{message:u("Loading preview...")}),v&&t().createElement(em,{message:u("Failed to load file preview")}),!f&&!v&&x&&t().createElement("div",{style:{width:"100%",height:"100%",overflow:"auto"}},t().createElement(x,{file:b})))}var eE=function(o){return function(l){var u,c=l.open,s=l.onOpenChange,f=l.onClose,p=l.file,d=l.index,m=l.list,v=l.onSwitchIndex;l.onDownload;var h=(0,i.useAPIClient)(),y=a(),b=(0,e.useCallback)((u=_(function(e){var t,n,i;return B(this,function(o){switch(o.label){case 0:if(!(n=e||p))return[2];i=(null==(t=h.auth)?void 0:t.token)||"",o.label=1;case 1:return o.trys.push([1,3,,4]),[4,es(n,i)];case 2:return o.sent(),[3,4];case 3:return o.sent(),r.message.error(y("Failed to download file")),[3,4];case 4:return[2]}})}),function(e){return u.apply(this,arguments)}),[p,h,y]);if("boolean"!=typeof c)return t().createElement(o,R(T({},l),{onDownload:b}));var g=eo(p),w="number"==typeof d&&!!v&&d>0,x="number"==typeof d&&!!v&&d<m.length-1,E=L((0,e.useState)("visual"),2),k=E[0],S=E[1];return t().createElement(r.Modal,{open:c,title:t().createElement(ev,{file:p,title:g}),onCancel:function(){null==s||s(!1),null==f||f(),S("visual")},footer:t().createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%"}},t().createElement("div",{key:"left-actions"},t().createElement(r.Button,{onClick:function(){return S(function(e){return"visual"===e?"raw":"visual"})}},"visual"===k?y("View Raw Parsed Text"):y("View Visual Preview"))),t().createElement(r.Space,{size:14,style:{fontSize:"20px"}},t().createElement(n.LeftOutlined,{style:{cursor:w?"pointer":"not-allowed"},onClick:function(){return w&&(null==v?void 0:v(d-1))}}),t().createElement(n.RightOutlined,{style:{cursor:x?"pointer":"not-allowed"},onClick:function(){return x&&(null==v?void 0:v(d+1))}}),t().createElement(n.DownloadOutlined,{onClick:function(){return b(p)}}))),width:"90%",centered:!0},t().createElement("div",{style:{maxWidth:"100%",maxHeight:"calc(100vh - 256px)",height:"80vh",width:"100%",background:"white",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",overflowY:"auto"}},"raw"===k?t().createElement(ek,{file:p}):t().createElement(o,R(T({},l),{onDownload:b}))))}};function ek(o){var l=o.file,u=(0,i.useAPIClient)(),c=a(),s=L((0,e.useState)(""),2),f=s[0],p=s[1],d=L((0,e.useState)(!0),2),m=d[0],v=d[1],h=L((0,e.useState)(null),2),y=h[0],b=h[1],g=(0,i.useComponent)("MarkdownVditor"),w=(0,i.useComponent)("Markdown.Void");return((0,e.useEffect)(function(){var e=!1;return _(function(){var t,n,r,i,o,a,c,s,f,d;return B(this,function(m){switch(m.label){case 0:v(!0),b(null),m.label=1;case 1:return m.trys.push([1,4,,5]),[4,eu(l,(null==(t=u.auth)?void 0:t.token)||"")];case 2:if(i=m.sent(),e)return[2];return(o=new FormData).append("file",i,eo(l)),o.append("attachment",JSON.stringify({id:null==l?void 0:l.id,uid:null==l?void 0:l.uid,url:null==l?void 0:l.url,preview:null==l?void 0:l.preview,filename:(null==l?void 0:l.filename)||(null==l?void 0:l.name),name:(null==l?void 0:l.name)||(null==l?void 0:l.filename),title:null==l?void 0:l.title,extname:null==l?void 0:l.extname,mimetype:null==l?void 0:l.mimetype,size:null==l?void 0:l.size,path:null==l?void 0:l.path,storageId:null==l?void 0:l.storageId,collectionName:null==l?void 0:l.collectionName,lastModified:null==l?void 0:l.lastModified})),[4,u.request({url:"filePreviewAuth:getContent",method:"post",data:o,headers:{"Content-Type":"multipart/form-data"}})];case 3:if(a=m.sent(),e)return[2];return s=c=(null==a||null==(r=a.data)||null==(n=r.data)?void 0:n.content)||"",(f=c.match(/<file_preview[^>]*>([\s\S]*?)<\/file_preview>/i))&&(s=f[1].trim()),p(s),v(!1),[3,5];case 4:if(d=m.sent(),e)return[2];return b(d.message||"Failed to fetch raw text"),v(!1),[3,5];case 5:return[2]}})})(),function(){e=!0}},[l,u]),m)?t().createElement(r.Spin,{size:"large",tip:c("Extracting raw text..."),style:{marginTop:"40px"}}):y?t().createElement(r.Alert,{type:"error",message:y,style:{width:"100%",margin:"20px"}}):f?t().createElement("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column",position:"relative"}},t().createElement("span",{onClick:function(){if(navigator.clipboard&&navigator.clipboard.writeText)navigator.clipboard.writeText(f).then(function(){r.message.success(c("Copied to clipboard"))}).catch(function(e){r.message.error(c("Failed to copy")),console.error("Copy error",e)});else{var e=document.createElement("textarea");e.value=f,document.body.appendChild(e),e.select();try{document.execCommand("copy"),r.message.success(c("Copied to clipboard"))}catch(e){r.message.error(c("Failed to copy"))}document.body.removeChild(e)}},style:{position:"absolute",top:"20px",right:"25px",zIndex:10,cursor:"pointer",padding:"4px 10px",background:"rgba(255, 255, 255, 0.85)",border:"1px solid #e8e8e8",borderRadius:"4px",color:"#1890ff",display:"flex",alignItems:"center",gap:"6px",boxShadow:"0 2px 4px rgba(0,0,0,0.05)",fontSize:"13px"},title:c("Copy")},t().createElement(n.CopyOutlined,null),c("Copy")),t().createElement("div",{style:{flex:1,overflow:"auto",padding:"20px",textAlign:"left"}},t().createElement("style",null,"\n .hide-vditor-toolbar .vditor-toolbar {\n display: none !important;\n }\n .hide-vditor-toolbar .vditor {\n border: none !important;\n }\n "),t().createElement("div",{className:"hide-vditor-toolbar",style:{height:"100%"}},g?t().createElement(g,{value:f,disabled:!1}):w?t().createElement(w,{content:f}):t().createElement("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"monospace",fontSize:"13px"}},f)))):t().createElement(r.Alert,{type:"info",style:{width:"100%",margin:"20px"},description:c("No text content could be extracted from this file."),showIcon:!0})}function eS(n){var o,l=n.index,u=n.list,c=n.onSwitchIndex,s=a(),f=(0,i.useAPIClient)(),p=u[l],d=L((0,e.useState)(!1),2),m=d[0],v=d[1],h=L((0,e.useState)("visual"),2),y=h[0],b=h[1],g=(0,e.useCallback)((o=_(function(e){var t,n,i,o;return B(this,function(l){switch(l.label){case 0:null==e||null==(t=e.preventDefault)||t.call(e),null==e||null==(n=e.stopPropagation)||n.call(e),o=(null==(i=f.auth)?void 0:i.token)||"",v(!0),l.label=1;case 1:return l.trys.push([1,3,4,5]),[4,es(p,o)];case 2:return l.sent(),[3,5];case 3:return l.sent(),r.message.error(s("Failed to download file")),[3,5];case 4:return v(!1),[7];case 5:return[2]}})}),function(e){return o.apply(this,arguments)}),[p,f,s]),w=(0,e.useCallback)(function(){c(null),b("visual")},[c]),x=(0,e.useMemo)(function(){return Z(p)?eh:ee(p)?ey:et(p)?eb:en(p)?eg:er(p)?ew:ei(p)?ex:null},[p]),E=null!=x||"raw"===y;return t().createElement(r.Modal,{open:null!=l,title:t().createElement(ev,{file:p,title:(null==p?void 0:p.title)||(null==p?void 0:p.filename)||(null==p?void 0:p.name)||"File"}),onCancel:w,footer:t().createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%"}},t().createElement("div",{key:"left-actions"},t().createElement(r.Button,{onClick:function(){return b(function(e){return"visual"===e?"raw":"visual"})}},"visual"===y?s("View Raw Parsed Text"):s("View Visual Preview"))),t().createElement(r.Space,null,t().createElement(r.Button,{key:"download",onClick:g,loading:m},s("Download")),t().createElement(r.Button,{key:"close",onClick:w},s("Close")))),width:E?"90%":520,centered:!0},t().createElement("div",{style:{maxWidth:"100%",maxHeight:E?"calc(100vh - 256px)":"auto",height:E?"70vh":"auto",width:"100%",background:"white",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",overflowY:"auto"}},"raw"===y?t().createElement(ek,{file:p}):x?t().createElement(x,{file:p}):t().createElement(r.Alert,{type:"info",style:{width:"100%"},description:s("This file type cannot be previewed. Click Download to save the file."),showIcon:!0})))}function eC(n){var o=n.file,l=(0,i.useAPIClient)(),u=a(),c=(0,e.useCallback)(_(function(){var e,t;return B(this,function(n){switch(n.label){case 0:t=(null==(e=l.auth)?void 0:e.token)||"",n.label=1;case 1:return n.trys.push([1,3,,4]),[4,es(o,t)];case 2:return n.sent(),[3,4];case 3:return n.sent(),r.message.error(u("Failed to download file")),[3,4];case 4:return[2]}})}),[o,l,u]);return t().createElement(r.Alert,{type:"info",style:{width:"100%"},description:t().createElement("span",null,u("This file type cannot be previewed. ")," ",t().createElement("a",{onClick:c,style:{textDecoration:"underline",cursor:"pointer"}},u("Download"))),showIcon:!0})}var eP=function(e){var l;if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function a(){var e,t;if(!(this instanceof a))throw TypeError("Cannot call a class as a function");return e=a,t=arguments,e=I(e),function(e,t){var n;if(t&&("object"==((n=t)&&"undefined"!=typeof Symbol&&n.constructor===Symbol?"symbol":typeof n)||"function"==typeof t))return t;if(void 0===e)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(this,U()?Reflect.construct(e,t||[],I(this).constructor):e.apply(this,t))}return a.prototype=Object.create(e&&e.prototype,{constructor:{value:a,writable:!0,configurable:!0}}),e&&F(a,e),l=[{key:"load",value:function(){var e=this;return _(function(){return B(this,function(l){return!function(e){try{i=e.pm.get("ai")}catch(e){return}var i,o,l=null==i?void 0:i.aiManager;if(null==l?void 0:l.registerWorkContext)try{(null==(o=l.getWorkContext)?void 0:o.call(l,w))||l.registerWorkContext(w,{name:w,tag:{Component:function(e){var i=e.item;return t().createElement(r.Space,null,t().createElement(n.FileTextOutlined,null),t().createElement("span",null,(null==i?void 0:i.title)||""))}},chatbox:{Component:function(e){var i=e.item;return t().createElement(r.Space,null,t().createElement(n.FileTextOutlined,null),t().createElement("span",null,(null==i?void 0:i.title)||""))}}})}catch(e){}}(e.app),i.attachmentFileTypes.add({match:function(){return!0},Previewer:eS}),o.filePreviewTypes.add({match:function(){return!0},Previewer:eE(eC)}),o.filePreviewTypes.add({match:Z,Previewer:eE(eh)}),o.filePreviewTypes.add({match:ee,getThumbnailURL:function(e){return(null==e?void 0:e.url)||(null==e?void 0:e.preview)||null},Previewer:eE(ey)}),o.filePreviewTypes.add({match:et,Previewer:eE(eb)}),o.filePreviewTypes.add({match:en,Previewer:eE(eg)}),o.filePreviewTypes.add({match:er,Previewer:eE(ew)}),o.filePreviewTypes.add({match:ei,Previewer:eE(ex)}),[2]})})()}}],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)}}(a.prototype,l),a}(D(i.Plugin)),eO=eP}(),v}()});
10
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("@nocobase/plugin-ai/client"),require("@nocobase/plugin-file-manager/client"),require("@nocobase/client"),require("react"),require("@ant-design/icons"),require("antd")):"function"==typeof define&&define.amd?define("plugin-file-preview-auth",["@nocobase/plugin-ai/client","@nocobase/plugin-file-manager/client","@nocobase/client","react","@ant-design/icons","antd"],t):"object"==typeof exports?exports["plugin-file-preview-auth"]=t(require("@nocobase/plugin-ai/client"),require("@nocobase/plugin-file-manager/client"),require("@nocobase/client"),require("react"),require("@ant-design/icons"),require("antd")):e["plugin-file-preview-auth"]=t(e["@nocobase/plugin-ai/client"],e["@nocobase/plugin-file-manager/client"],e["@nocobase/client"],e.react,e["@ant-design/icons"],e.antd)}(self,function(e,t,n,r,i,o){return function(){var l,a,u,c,s,f,d={41:function(e){e.exports=function(e,t){return"undefined"!=typeof __deoptimization_sideEffect__&&__deoptimization_sideEffect__(e,t),t}},482:function(e){"use strict";e.exports=i},772:function(e){"use strict";e.exports=n},645:function(t){"use strict";t.exports=e},183:function(e){"use strict";e.exports=t},721:function(e){"use strict";e.exports=o},156:function(e){"use strict";e.exports=r}},p={};function m(e){var t=p[e];if(void 0!==t)return t.exports;var n=p[e]={exports:{}};return d[e](n,n.exports,m),n.exports}m.m=d,m.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return m.d(t,{a:t}),t},m.d=function(e,t){for(var n in t)m.o(t,n)&&!m.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},m.f={},m.e=function(e){return Promise.all(Object.keys(m.f).reduce(function(t,n){return m.f[n](e,t),t},[]))},m.u=function(e){return""+e+"."+({166:"17caa11c2ba40313",351:"0f0ce45c92425c8f",374:"96762d13b15e7467",514:"2a8b6aa0d2fcd4b2"})[e]+".js"},m.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}}(),m.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},l={},a="plugin-file-preview-auth:",m.l=function(e,t,n,r){if(l[e])return void l[e].push(t);if(void 0!==n)for(var i,o,u=document.getElementsByTagName("script"),c=0;c<u.length;c++){var s=u[c];if(s.getAttribute("src")==e||s.getAttribute("data-webpack")==a+n){i=s;break}}i||(o=!0,(i=document.createElement("script")).charset="utf-8",i.timeout=120,m.nc&&i.setAttribute("nonce",m.nc),i.setAttribute("data-webpack",a+n),i.src=e),l[e]=[t];var f=function(t,n){i.onerror=i.onload=null,clearTimeout(d);var r=l[e];if(delete l[e],i.parentNode&&i.parentNode.removeChild(i),r&&r.forEach(function(e){return e(n)}),t)return t(n)},d=setTimeout(f.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=f.bind(null,i.onerror),i.onload=f.bind(null,i.onload),o&&document.head.appendChild(i)},m.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(u=window.__webpack_public_path__||"/").endsWith("/")||(u+="/"),m.p=u+"static/plugins/plugin-file-preview-auth/dist/client/",c={909:0},m.f.j=function(e,t){var n=m.o(c,e)?c[e]:void 0;if(0!==n)if(n)t.push(n[2]);else{var r=new Promise(function(t,r){n=c[e]=[t,r]});t.push(n[2]=r);var i=m.p+m.u(e),o=Error();m.l(i,function(t){if(m.o(c,e)&&(0!==(n=c[e])&&(c[e]=void 0),n)){var r=t&&("load"===t.type?"missing":t.type),i=t&&t.target&&t.target.src;o.message="Loading chunk "+e+" failed.\n("+r+": "+i+")",o.name="ChunkLoadError",o.type=r,o.request=i,n[1](o)}},"chunk-"+e,e)}},s=function(e,t){var n,r,i=t[0],o=t[1],l=t[2],a=0;if(i.some(function(e){return 0!==c[e]})){for(n in o)m.o(o,n)&&(m.m[n]=o[n]);l&&l(m)}for(e&&e(t);a<i.length;a++)r=i[a],m.o(c,r)&&c[r]&&c[r][0](),c[r]=0},(f=self.webpackChunkplugin_file_preview_auth=self.webpackChunkplugin_file_preview_auth||[]).forEach(s.bind(null,0)),f.push=s.bind(null,f.push.bind(f));var v={};return!function(){"use strict";m.r(v),m.d(v,{default:function(){return eP},PluginFilePreviewAuthClient:function(){return eO}});var e=m(156),t=m.n(e),n=m(482),r=m(721),i=m(772),o=m(183),l=JSON.parse('{"u2":"plugin-file-preview-auth"}');function a(){var e=(0,i.useApp)();return function(t){return e.i18n.t(t,{ns:[l.u2,"client"]})}}var u=m(645);function c(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 s(e,t,n,r,i,o,l){try{var a=e[o](l),u=a.value}catch(e){n(e);return}a.done?t(u):Promise.resolve(u).then(r,i)}function f(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 d(e){return(d=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 h(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var o=[],l=!0,a=!1;try{for(i=i.call(e);!(l=(n=i.next()).done)&&(o.push(n.value),!t||o.length!==t);l=!0);}catch(e){a=!0,r=e}finally{try{l||null==i.return||i.return()}finally{if(a)throw r}}return o}}(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 y(e){return function(e){if(Array.isArray(e))return c(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||g(e)||function(){throw TypeError("Invalid attempt to spread 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 c(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 c(e,t)}}function b(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(b=function(){return!!e})()}var w="file-preview",x="plugin-file-preview-auth.aiEmployee";function E(e){return e?e.title&&e.extname?"".concat(e.title).concat(e.extname):e.filename||e.name||e.title||"file":"file"}var S=function(e){var t,n;if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function r(e){var t,n,i;if(!(this instanceof r))throw TypeError("Cannot call a class as a function");return n=r,i=[e],n=d(n),(t=function(e,t){var n;if(t&&("object"==((n=t)&&"undefined"!=typeof Symbol&&n.constructor===Symbol?"symbol":typeof n)||"function"==typeof t))return t;if(void 0===e)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(this,b()?Reflect.construct(n,i||[],d(this).constructor):n.apply(this,i))).state={hasError:!1},t}return r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),e&&p(r,e),n=[{key:"getDerivedStateFromError",value:function(){return{hasError:!0}}}],t=[{key:"render",value:function(){return this.state.hasError?null:this.props.children}}],f(r.prototype,t),n&&f(r,n),r}(t().Component),k=function(i){var o,l,c=i.file,f=a(),d=(0,u.useAIConfigRepository)(),p=(0,u.useChatBoxActions)().triggerTask,m=h((0,e.useState)([]),2),v=m[0],g=m[1],b=h((0,e.useState)(!1),2),S=b[0],k=b[1],C=h((0,e.useState)(!1),2),O=C[0],P=C[1];(0,e.useEffect)(function(){var e=!1;if(null==d?void 0:d.getAIEmployees){var t=d.aiEmployees||[];return t.length?void g(y(t)):(k(!0),d.getAIEmployees().then(function(t){e||g(y(t||[]))}).catch(function(){e||g([])}).finally(function(){e||k(!1)}),function(){e=!0})}},[d]);var j=(0,e.useMemo)(function(){var e=function(){try{return window.localStorage.getItem(x)||""}catch(e){return""}}();return e?y(v).sort(function(t,n){return t.username===e?-1:+(n.username===e)}):v},[v]),T=(0,e.useCallback)((o=function(e){return function(e,t){var n,r,i,o,l={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){var u=[o,a];if(n)throw TypeError("Generator is already executing.");for(;l;)try{if(n=1,r&&(i=2&u[0]?r.return:u[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,u[1])).done)return i;switch(r=0,i&&(u=[2&u[0],i.value]),u[0]){case 0:case 1:i=u;break;case 4:return l.label++,{value:u[1],done:!1};case 5:l.label++,r=u[1],u=[0];continue;case 7:u=l.ops.pop(),l.trys.pop();continue;default:if(!(i=(i=l.trys).length>0&&i[i.length-1])&&(6===u[0]||2===u[0])){l=0;continue}if(3===u[0]&&(!i||u[1]>i[0]&&u[1]<i[3])){l.label=u[1];break}if(6===u[0]&&l.label<i[1]){l.label=i[1],i=u;break}if(i&&l.label<i[2]){l.label=i[2],l.ops.push(u);break}i[2]&&l.ops.pop(),l.trys.pop();continue}u=t.call(e,l)}catch(e){u=[6,e],r=0}finally{n=i=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}(this,function(t){switch(t.label){case 0:if(!e||!c)return[2];P(!0),t.label=1;case 1:t.trys.push([1,3,4,5]);var n,i,o,l,a,u=e.username;try{window.localStorage.setItem(x,u)}catch(e){}return[4,p({aiEmployee:e,tasks:[{title:E(c),message:{user:f("Please help me analyze the file currently open in preview."),workContext:[{type:w,uid:(a=null!=(l=null!=(o=null!=(i=null!=(n=null==c?void 0:c.id)?n:null==c?void 0:c.uid)?i:null==c?void 0:c.url)?o:null==c?void 0:c.path)?l:E(c),"file-preview:".concat(String(a))),title:E(c),content:{source:"plugin-file-preview-auth",file:{id:null==c?void 0:c.id,uid:null==c?void 0:c.uid,url:null==c?void 0:c.url,preview:null==c?void 0:c.preview,filename:(null==c?void 0:c.filename)||(null==c?void 0:c.name),name:(null==c?void 0:c.name)||(null==c?void 0:c.filename),title:null==c?void 0:c.title,extname:null==c?void 0:c.extname,mimetype:null==c?void 0:c.mimetype,size:null==c?void 0:c.size,path:null==c?void 0:c.path,storageId:null==c?void 0:c.storageId}}}]},autoSend:!1}]})];case 2:return t.sent(),[3,5];case 3:return t.sent(),r.message.error(f("Failed to open AI chat")),[3,5];case 4:return P(!1),[7];case 5:return[2]}})},l=function(){var e=this,t=arguments;return new Promise(function(n,r){var i=o.apply(e,t);function l(e){s(i,n,r,l,a,"next",e)}function a(e){s(i,n,r,l,a,"throw",e)}l(void 0)})},function(e){return l.apply(this,arguments)}),[c,f,p]),A=j.map(function(e){return{key:e.username,label:(null==e?void 0:e.nickname)||(null==e?void 0:e.username)||"",onClick:function(){return T(e)}}});return S||j.length?1===j.length?t().createElement(r.Tooltip,{title:f("Ask AI")},t().createElement(r.Button,{type:"text",size:"small",icon:t().createElement(n.RobotOutlined,null),loading:O||S,onClick:function(e){e.stopPropagation(),T(j[0])}},f("Ask AI"))):t().createElement(r.Tooltip,{title:f("Ask AI")},t().createElement(r.Dropdown,{menu:{items:A},trigger:["click"],placement:"bottomRight",disabled:O||S},t().createElement(r.Button,{type:"text",size:"small",icon:t().createElement(n.RobotOutlined,null),loading:O||S,onClick:function(e){return e.stopPropagation()}},f("Ask AI")))):null},C=function(e){var n=e.file;return t().createElement(S,null,t().createElement(k,{file:n}))},O=m(41);function P(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 j(e,t,n,r,i,o,l){try{var a=e[o](l),u=a.value}catch(e){n(e);return}a.done?t(u):Promise.resolve(u).then(r,i)}function T(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function l(e){j(o,r,i,l,a,"next",e)}function a(e){j(o,r,i,l,a,"throw",e)}l(void 0)})}}function A(e,t,n){return(A=D()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&F(i,n.prototype),i}).apply(null,arguments)}function I(e){return(I=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function _(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;r=n[t],t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r})}return e}function R(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 F(e,t){return(F=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function L(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var o=[],l=!0,a=!1;try{for(i=i.call(e);!(l=(n=i.next()).done)&&(o.push(n.value),!t||o.length!==t);l=!0);}catch(e){a=!0,r=e}finally{try{l||null==i.return||i.return()}finally{if(a)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return P(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 P(e,t)}}(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 B(e){var t="function"==typeof Map?new Map:void 0;return(B=function(e){if(null===e||-1===Function.toString.call(e).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,n)}function n(){return A(e,arguments,I(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),F(n,e)})(e)}function D(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(D=function(){return!!e})()}function z(e,t){var n,r,i,o,l={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){var u=[o,a];if(n)throw TypeError("Generator is already executing.");for(;l;)try{if(n=1,r&&(i=2&u[0]?r.return:u[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,u[1])).done)return i;switch(r=0,i&&(u=[2&u[0],i.value]),u[0]){case 0:case 1:i=u;break;case 4:return l.label++,{value:u[1],done:!1};case 5:l.label++,r=u[1],u=[0];continue;case 7:u=l.ops.pop(),l.trys.pop();continue;default:if(!(i=(i=l.trys).length>0&&i[i.length-1])&&(6===u[0]||2===u[0])){l=0;continue}if(3===u[0]&&(!i||u[1]>i[0]&&u[1]<i[3])){l.label=u[1];break}if(6===u[0]&&l.label<i[1]){l.label=i[1],i=u;break}if(i&&l.label<i[2]){l.label=i[2],l.ops.push(u);break}i[2]&&l.ops.pop(),l.trys.pop();continue}u=t.call(e,l)}catch(e){u=[6,e],r=0}finally{n=i=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}var M=["application/pdf"],U=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],W=["text/plain","text/csv","text/html","text/css","text/javascript","application/json","application/xml","text/xml","text/yaml","application/x-yaml"],N=["application/vnd.openxmlformats-officedocument.wordprocessingml.document"],q=["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-excel"],V=["pdf"],H=["png","jpg","jpeg","gif","webp","svg","bmp"],X=["txt","csv","html","css","js","json","xml","log","md","yaml","yml","xaml"],G=["docx"],J=["xlsx","xls"],Y=["application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-powerpoint"],$=["pptx","ppt"],K=function(e){var t=("string"==typeof e?e:(null==e?void 0:e.extname)||(null==e?void 0:e.name)||(null==e?void 0:e.filename)||(null==e?void 0:e.url)||"").split("?")[0].split("#")[0],n=t.lastIndexOf(".");return -1!==n?t.slice(n+1).toLowerCase().replace(/^\./,""):""},Q=function(e){var t="string"==typeof e?e:null==e?void 0:e.url;return t?t.startsWith("https://")||t.startsWith("http://")?t:"".concat(location.origin,"/").concat(t.replace(/^\//,"")):""},Z=function(e){if((null==e?void 0:e.mimetype)&&M.includes(e.mimetype))return!0;var t=K(e);return!!t&&V.includes(t)},ee=function(e){if((null==e?void 0:e.mimetype)&&U.includes(e.mimetype)||(null==e?void 0:e.mimetype)&&(0,i.matchMimetype)(e,"image/*"))return!0;var t=K(e);return!!t&&H.includes(t)},et=function(e){if((null==e?void 0:e.mimetype)&&W.includes(e.mimetype))return!0;var t=K(e);return!!t&&X.includes(t)},en=function(e){if((null==e?void 0:e.mimetype)&&N.includes(e.mimetype))return!0;var t=K(e);return!!t&&G.includes(t)},er=function(e){if((null==e?void 0:e.mimetype)&&q.includes(e.mimetype))return!0;var t=K(e);return!!t&&J.includes(t)},ei=function(e){if((null==e?void 0:e.mimetype)&&Y.includes(e.mimetype))return!0;var t=K(e);return!!t&&$.includes(t)},eo=function(e){return e?e.title&&e.extname?"".concat(e.title).concat(e.extname):e.filename||e.name||e.title||"download":"download"},el=new Map;function ea(){return(ea=T(function(e,t){var n,r;return z(this,function(i){switch(i.label){case 0:return n={},t&&(n.Authorization="Bearer ".concat(t)),[4,fetch(e,{method:"GET",headers:n,credentials:"include"})];case 1:if(!(r=i.sent()).ok)throw Error("Failed to fetch file: ".concat(r.status," ").concat(r.statusText));return[2,r.blob()]}})})).apply(this,arguments)}function eu(e,t){return ec.apply(this,arguments)}function ec(){return(ec=T(function(e,t){var n,r,i;return z(this,function(o){if(!(n=Q(e)))throw Error("No file URL");return r="".concat(t?"auth":"anon",":").concat(t||"",":").concat(n),(i=el.get(r))||(i=(function(e,t){return ea.apply(this,arguments)})(n,t).catch(function(e){throw el.delete(r),e}),el.set(r,i)),[2,i]})})).apply(this,arguments)}function es(e,t){return ef.apply(this,arguments)}function ef(){return(ef=T(function(e,t){var n,r,i,o;return z(this,function(l){switch(l.label){case 0:if(!Q(e))return[2];return[4,eu(e,t)];case 1:return n=l.sent(),r=eo(e),(i=document.createElement("a")).href=o=URL.createObjectURL(n),i.download=r,document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(function(){return URL.revokeObjectURL(o)},1e3),[2]}})})).apply(this,arguments)}function ed(t,n){var r=L((0,e.useState)(null),2),i=r[0],o=r[1],l=L((0,e.useState)(!0),2),a=l[0],u=l[1],c=L((0,e.useState)(null),2),s=c[0],f=c[1],d=(0,e.useRef)(null);return(0,e.useEffect)(function(){var e=!1;if(!Q(t)){u(!1),f("No file URL");return}return u(!0),f(null),eu(t,n).then(function(t){if(!e){var n=URL.createObjectURL(t);d.current=n,o(n),u(!1)}}).catch(function(t){e||(f(t.message||"Failed to load"),u(!1))}),function(){e=!0,d.current&&(URL.revokeObjectURL(d.current),d.current=null)}},["string"==typeof t?t:null==t?void 0:t.url,n]),{blobUrl:i,loading:a,error:s}}function ep(e){var n=e.message;return t().createElement("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%",width:"100%"}},t().createElement(r.Spin,{tip:n}))}function em(e){var n=e.message;return t().createElement("div",{style:{padding:20,textAlign:"center",color:"#ff4d4f"}},n)}function ev(e){var i=e.file,o=e.title,l=e.ocrStatus,u=e.isOcrSupported,c=a();return t().createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,paddingRight:40}},t().createElement(r.Space,{size:8,style:{minWidth:0,overflow:"hidden"}},t().createElement("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:600},title:o},o),function(){if(!u||!l)return null;switch(l){case"pending-ocr":return t().createElement(r.Tag,{color:"processing",icon:t().createElement(n.SyncOutlined,{spin:!0})},c("OCR Pending"));case"waiting-verify":return t().createElement(r.Tag,{color:"warning",icon:t().createElement(n.ClockCircleOutlined,null)},c("Waiting Verify"));case"verified":return t().createElement(r.Tag,{color:"success",icon:t().createElement(n.CheckCircleOutlined,null)},c("OCR Verified"));default:return t().createElement(r.Tag,{color:"default"},c("No OCR"))}}()),t().createElement(C,{file:i}))}function eh(e){var n,r=e.file,o=(0,i.useAPIClient)(),l=a(),u=ed(r,(null==(n=o.auth)?void 0:n.token)||""),c=u.blobUrl,s=u.loading,f=u.error;return s?t().createElement(ep,{message:l("Loading preview...")}):f||!c?t().createElement(em,{message:l("Failed to load file preview")}):t().createElement("iframe",{src:c,width:"100%",height:"100%",style:{border:"none"}})}function ey(e){var n,r=e.file,o=(0,i.useAPIClient)(),l=a(),u=ed(r,(null==(n=o.auth)?void 0:n.token)||""),c=u.blobUrl,s=u.loading,f=u.error;return s?t().createElement(ep,{message:l("Loading preview...")}):f||!c?t().createElement(em,{message:l("Failed to load file preview")}):t().createElement("img",{src:c,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"},alt:(null==r?void 0:r.title)||(null==r?void 0:r.filename)||""})}function eg(n){var r,o,l,u,c,s,f,d,p,m,v=n.file,h=(0,i.useAPIClient)(),y=a(),g=(null==(m=h.auth)?void 0:m.token)||"",b=(o=(r=L((0,e.useState)(null),2))[0],l=r[1],c=(u=L((0,e.useState)(!0),2))[0],s=u[1],d=(f=L((0,e.useState)(null),2))[0],p=f[1],(0,e.useEffect)(function(){var e=!1;if(!Q(v)){s(!1),p("No file URL");return}return s(!0),p(null),eu(v,g).then(function(e){return e.text()}).then(function(t){e||(l(t),s(!1))}).catch(function(t){e||(p(t.message||"Failed to load"),s(!1))}),function(){e=!0}},["string"==typeof v?v:null==v?void 0:v.url,g]),{text:o,loading:c,error:d}),w=b.text,x=b.loading,E=b.error;return x?t().createElement(ep,{message:y("Loading preview...")}):E||null===w?t().createElement(em,{message:y("Failed to load file preview")}):t().createElement("pre",{style:{width:"100%",height:"100%",overflow:"auto",padding:16,margin:0,fontSize:13,lineHeight:1.6,whiteSpace:"pre-wrap",wordWrap:"break-word",background:"#f5f5f5",border:"none"}},w)}function eb(n){var r,o=n.file,l=(0,i.useAPIClient)(),u=a(),c=(null==(r=l.auth)?void 0:r.token)||"",s=(0,e.useRef)(null),f=L((0,e.useState)(!0),2),d=f[0],p=f[1],v=L((0,e.useState)(null),2),h=v[0],y=v[1];return(0,e.useEffect)(function(){var e=!1;if(!Q(o)||!s.current){p(!1),y("No file URL");return}return p(!0),y(null),T(function(){var t,n,r;return z(this,function(i){switch(i.label){case 0:return i.trys.push([0,4,,5]),[4,eu(o,c)];case 1:if(t=i.sent(),e)return[2];return[4,O("imported_-1dm6lbf_component",m.e("374").then(m.bind(m,335)))];case 2:if(n=i.sent(),e||!s.current)return[2];return s.current.innerHTML="",[4,n.renderAsync(t,s.current,void 0,{className:"docx-preview-wrapper",inWrapper:!0,ignoreWidth:!1,ignoreHeight:!1,ignoreFonts:!1,breakPages:!0,ignoreLastRenderedPageBreak:!0,experimental:!1,trimXmlDeclaration:!0,useBase64URL:!0,renderHeaders:!0,renderFooters:!0,renderFootnotes:!0,renderEndnotes:!0})];case 3:return i.sent(),p(!1),[3,5];case 4:if(r=i.sent(),e)return[2];return y(r.message||"Failed to render DOCX"),p(!1),[3,5];case 5:return[2]}})})(),function(){e=!0}},["string"==typeof o?o:null==o?void 0:o.url,c]),t().createElement("div",{style:{width:"100%",height:"100%",position:"relative"}},d&&t().createElement(ep,{message:u("Loading preview...")}),h&&t().createElement(em,{message:u("Failed to load file preview")}),t().createElement("div",{ref:s,style:{width:"100%",height:"100%",overflow:"auto",display:d||h?"none":"block"}}))}function ew(n){var r,o=n.file,l=(0,i.useAPIClient)(),u=a(),c=(null==(r=l.auth)?void 0:r.token)||"",s=(0,e.useRef)(null),f=L((0,e.useState)(!0),2),d=f[0],p=f[1],v=L((0,e.useState)(null),2),h=v[0],y=v[1],g=L((0,e.useState)([]),2),b=g[0],w=g[1],x=L((0,e.useState)(""),2),E=x[0],S=x[1],k=L((0,e.useState)({}),2),C=k[0],P=k[1];return(0,e.useEffect)(function(){var e=!1;if(!Q(o)){p(!1),y("No file URL");return}return p(!0),y(null),T(function(){var t,n,r,i,l,a,u,s,f,d,v,h,g,b;return z(this,function(x){switch(x.label){case 0:return x.trys.push([0,4,,5]),[4,eu(o,c)];case 1:if(t=x.sent(),e)return[2];return[4,O("imported_-1lj2ifg_component",m.e("166").then(m.bind(m,907)))];case 2:if(n=x.sent(),e)return[2];return[4,t.arrayBuffer()];case 3:if(r=x.sent(),e)return[2];l=(i=n.read(r,{type:"array"})).SheetNames,a={},u=!0,s=!1,f=void 0;try{for(d=l[Symbol.iterator]();!(u=(v=d.next()).done);u=!0)h=v.value,g=i.Sheets[h],a[h]=n.utils.sheet_to_html(g,{id:"xlsx-preview-table"})}catch(e){s=!0,f=e}finally{try{u||null==d.return||d.return()}finally{if(s)throw f}}if(e)return[2];return w(l),S(l[0]||""),P(a),p(!1),[3,5];case 4:if(b=x.sent(),e)return[2];return y(b.message||"Failed to render XLSX"),p(!1),[3,5];case 5:return[2]}})})(),function(){e=!0}},["string"==typeof o?o:null==o?void 0:o.url,c]),t().createElement("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column"}},d&&t().createElement(ep,{message:u("Loading preview...")}),h&&t().createElement(em,{message:u("Failed to load file preview")}),!d&&!h&&t().createElement(t().Fragment,null,b.length>1&&t().createElement("div",{style:{display:"flex",gap:0,borderBottom:"1px solid #e8e8e8",background:"#fafafa",padding:"0 8px",flexShrink:0,overflowX:"auto"}},b.map(function(e){return t().createElement("button",{key:e,onClick:function(){return S(e)},style:{padding:"8px 16px",border:"none",borderBottom:E===e?"2px solid #1890ff":"2px solid transparent",background:E===e?"#fff":"transparent",color:E===e?"#1890ff":"#666",fontWeight:E===e?600:400,cursor:"pointer",fontSize:13,whiteSpace:"nowrap",transition:"all 0.2s"}},e)})),t().createElement("div",{ref:s,style:{flex:1,overflow:"auto",padding:0},dangerouslySetInnerHTML:{__html:C[E]||""}}),t().createElement("style",null,"\n #xlsx-preview-table {\n border-collapse: collapse;\n width: 100%;\n font-size: 13px;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n }\n #xlsx-preview-table td,\n #xlsx-preview-table th {\n border: 1px solid #e8e8e8;\n padding: 6px 10px;\n text-align: left;\n max-width: 33vw;\n white-space: normal;\n word-break: break-word;\n }\n #xlsx-preview-table tr:first-child td,\n #xlsx-preview-table tr:first-child th {\n background: #fafafa;\n font-weight: 600;\n position: sticky;\n top: 0;\n z-index: 1;\n }\n #xlsx-preview-table tr:nth-child(even) {\n background: #fafafa;\n }\n #xlsx-preview-table tr:hover {\n background: #f0f7ff;\n }\n ")))}function ex(n){var r,o=n.file,l=(0,i.useAPIClient)(),u=a(),c=(null==(r=l.auth)?void 0:r.token)||"",s=L((0,e.useState)(!0),2),f=s[0],d=s[1],p=L((0,e.useState)(null),2),v=p[0],h=p[1],y=L((0,e.useState)(null),2),g=y[0],b=y[1],w=L((0,e.useState)(null),2),x=w[0],E=w[1];return(0,e.useEffect)(function(){var e=!1;if(!Q(o)){d(!1),h("No file URL");return}return d(!0),h(null),T(function(){var t,n,r,i,l;return z(this,function(a){switch(a.label){case 0:return a.trys.push([0,3,,4]),[4,Promise.all([eu(o,c),O("imported_tpp3om_component",m.e("514").then(m.bind(m,581)))])];case 1:if(n=(t=L.apply(void 0,[a.sent(),2]))[0],r=t[1],e)return[2];return[4,n.arrayBuffer()];case 2:if(i=a.sent(),e)return[2];return b(i),E(function(){return r.PptxPreview}),d(!1),[3,4];case 3:if(l=a.sent(),e)return[2];return h(l.message||"Failed to render PPTX"),d(!1),[3,4];case 4:return[2]}})})(),function(){e=!0}},["string"==typeof o?o:null==o?void 0:o.url,c]),t().createElement("div",{style:{width:"100%",height:"100%",position:"relative"}},f&&t().createElement(ep,{message:u("Loading preview...")}),v&&t().createElement(em,{message:u("Failed to load file preview")}),!f&&!v&&x&&t().createElement("div",{style:{width:"100%",height:"100%",overflow:"auto"}},t().createElement(x,{file:g})))}var eE=function(o){return function(l){var u,c=l.open,s=l.onOpenChange,f=l.onClose,d=l.file,p=l.index,m=l.list,v=l.onSwitchIndex;l.onDownload;var h=(0,i.useAPIClient)(),y=a(),g=(0,e.useCallback)((u=T(function(e){var t,n,i;return z(this,function(o){switch(o.label){case 0:if(!(n=e||d))return[2];i=(null==(t=h.auth)?void 0:t.token)||"",o.label=1;case 1:return o.trys.push([1,3,,4]),[4,es(n,i)];case 2:return o.sent(),[3,4];case 3:return o.sent(),r.message.error(y("Failed to download file")),[3,4];case 4:return[2]}})}),function(e){return u.apply(this,arguments)}),[d,h,y]);if("boolean"!=typeof c)return t().createElement(o,R(_({},l),{onDownload:g}));var b=eo(d),w="number"==typeof p&&!!v&&p>0,x="number"==typeof p&&!!v&&p<m.length-1,E=L((0,e.useState)("visual"),2),S=E[0],k=E[1];return t().createElement(r.Modal,{open:c,title:t().createElement(ev,{file:d,title:b}),onCancel:function(){null==s||s(!1),null==f||f(),k("visual")},footer:t().createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%"}},t().createElement("div",{key:"left-actions"},t().createElement(r.Button,{onClick:function(){return k(function(e){return"visual"===e?"raw":"visual"})}},"visual"===S?y("View Raw Parsed Text"):y("View Visual Preview"))),t().createElement(r.Space,{size:14,style:{fontSize:"20px"}},t().createElement(n.LeftOutlined,{style:{cursor:w?"pointer":"not-allowed"},onClick:function(){return w&&(null==v?void 0:v(p-1))}}),t().createElement(n.RightOutlined,{style:{cursor:x?"pointer":"not-allowed"},onClick:function(){return x&&(null==v?void 0:v(p+1))}}),t().createElement(n.DownloadOutlined,{onClick:function(){return g(d)}}))),width:"90%",centered:!0},t().createElement("div",{style:{maxWidth:"100%",maxHeight:"calc(100vh - 256px)",height:"80vh",width:"100%",background:"white",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",overflowY:"auto"}},"raw"===S?t().createElement(eS,{file:d}):t().createElement(o,R(_({},l),{onDownload:g}))))}};function eS(o){var l=o.file,u=(0,i.useAPIClient)(),c=a(),s=L((0,e.useState)(""),2),f=s[0],d=s[1],p=L((0,e.useState)(!0),2),m=p[0],v=p[1],h=L((0,e.useState)(null),2),y=h[0],g=h[1],b=(0,i.useComponent)("MarkdownVditor"),w=(0,i.useComponent)("Markdown.Void");return((0,e.useEffect)(function(){var e=!1;return T(function(){var t,n,r,i,o,a,c,s,f,p;return z(this,function(m){switch(m.label){case 0:v(!0),g(null),m.label=1;case 1:return m.trys.push([1,4,,5]),[4,eu(l,(null==(t=u.auth)?void 0:t.token)||"")];case 2:if(i=m.sent(),e)return[2];return(o=new FormData).append("file",i,eo(l)),o.append("attachment",JSON.stringify({id:null==l?void 0:l.id,uid:null==l?void 0:l.uid,url:null==l?void 0:l.url,preview:null==l?void 0:l.preview,filename:(null==l?void 0:l.filename)||(null==l?void 0:l.name),name:(null==l?void 0:l.name)||(null==l?void 0:l.filename),title:null==l?void 0:l.title,extname:null==l?void 0:l.extname,mimetype:null==l?void 0:l.mimetype,size:null==l?void 0:l.size,path:null==l?void 0:l.path,storageId:null==l?void 0:l.storageId,collectionName:null==l?void 0:l.collectionName,lastModified:null==l?void 0:l.lastModified})),[4,u.request({url:"filePreviewAuth:getContent",method:"post",data:o,headers:{"Content-Type":"multipart/form-data"}})];case 3:if(a=m.sent(),e)return[2];return s=c=(null==a||null==(r=a.data)||null==(n=r.data)?void 0:n.content)||"",(f=c.match(/<file_preview[^>]*>([\s\S]*?)<\/file_preview>/i))&&(s=f[1].trim()),d(s),v(!1),[3,5];case 4:if(p=m.sent(),e)return[2];return g(p.message||"Failed to fetch raw text"),v(!1),[3,5];case 5:return[2]}})})(),function(){e=!0}},[l,u]),m)?t().createElement(r.Spin,{size:"large",tip:c("Extracting raw text..."),style:{marginTop:"40px"}}):y?t().createElement(r.Alert,{type:"error",message:y,style:{width:"100%",margin:"20px"}}):f?t().createElement("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column",position:"relative"}},t().createElement("span",{onClick:function(){if(navigator.clipboard&&navigator.clipboard.writeText)navigator.clipboard.writeText(f).then(function(){r.message.success(c("Copied to clipboard"))}).catch(function(e){r.message.error(c("Failed to copy")),console.error("Copy error",e)});else{var e=document.createElement("textarea");e.value=f,document.body.appendChild(e),e.select();try{document.execCommand("copy"),r.message.success(c("Copied to clipboard"))}catch(e){r.message.error(c("Failed to copy"))}document.body.removeChild(e)}},style:{position:"absolute",top:"20px",right:"25px",zIndex:10,cursor:"pointer",padding:"4px 10px",background:"rgba(255, 255, 255, 0.85)",border:"1px solid #e8e8e8",borderRadius:"4px",color:"#1890ff",display:"flex",alignItems:"center",gap:"6px",boxShadow:"0 2px 4px rgba(0,0,0,0.05)",fontSize:"13px"},title:c("Copy")},t().createElement(n.CopyOutlined,null),c("Copy")),t().createElement("div",{style:{flex:1,overflow:"auto",padding:"20px",textAlign:"left"}},t().createElement("style",null,"\n .hide-vditor-toolbar .vditor-toolbar {\n display: none !important;\n }\n .hide-vditor-toolbar .vditor {\n border: none !important;\n }\n "),t().createElement("div",{className:"hide-vditor-toolbar",style:{height:"100%"}},b?t().createElement(b,{value:f,disabled:!1}):w?t().createElement(w,{content:f}):t().createElement("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"monospace",fontSize:"13px"}},f)))):t().createElement(r.Alert,{type:"info",style:{width:"100%",margin:"20px"},description:c("No text content could be extracted from this file."),showIcon:!0})}function ek(o){var l,u,c=o.index,s=o.list,f=o.onSwitchIndex,d=a(),p=(0,i.useAPIClient)(),m=s[c],v=L((0,e.useState)(!1),2),h=v[0],y=v[1],g=L((0,e.useState)("visual"),2),b=g[0],w=g[1],x=L((0,e.useState)("preview"),2),E=x[0],S=x[1],k=L((0,e.useState)("no-ocr"),2),C=k[0],O=k[1],P=L((0,e.useState)(null),2),j=(P[0],P[1]),A=(0,e.useMemo)(function(){return!!m&&(Z(m)||ee(m))},[m]),I=(0,i.useComponent)("OcrVerifyBlock");(0,e.useEffect)(function(){if(null==m?void 0:m.id){var e=!1;return O(m.ocrStatus||"no-ocr"),j(m.ocrData||null),p.resource("attachments").get({filterByTk:m.id}).then(function(t){if(!e){var n,r=null==t||null==(n=t.data)?void 0:n.data;r&&(O(r.ocrStatus||"no-ocr"),j(r.ocrData||null))}}).catch(console.error),function(){e=!0}}},[null==m?void 0:m.id,p]),(0,e.useEffect)(function(){if("pending-ocr"===C&&(null==m?void 0:m.id)){var e,t=null,n=!1,i=(e=T(function(){var e,o,l;return z(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),[4,p.resource("attachments").get({filterByTk:m.id})];case 1:if(o=a.sent(),n)return[2];return(l=null==o||null==(e=o.data)?void 0:e.data)&&("pending-ocr"!==l.ocrStatus?(O(l.ocrStatus||"no-ocr"),j(l.ocrData||null),r.message.success(d("OCR processing completed!"))):t=setTimeout(i,3e3)),[3,3];case 2:return console.error("Polling error",a.sent()),t=setTimeout(i,3e3),[3,3];case 3:return[2]}})}),function(){return e.apply(this,arguments)});return t=setTimeout(i,3e3),function(){n=!0,t&&clearTimeout(t)}}},[C,null==m?void 0:m.id,p,d]);var _=(l=T(function(){var e;return z(this,function(t){switch(t.label){case 0:if(!(null==m?void 0:m.id))return[2];t.label=1;case 1:return t.trys.push([1,3,,4]),O("pending-ocr"),[4,p.request({url:"filePreviewAuth:runOcr",method:"post",data:{attachmentId:m.id}})];case 2:return t.sent(),r.message.info(d("OCR process started in the background.")),[3,4];case 3:return e=t.sent(),r.message.error((null==e?void 0:e.message)||d("Failed to start OCR process.")),O("no-ocr"),[3,4];case 4:return[2]}})}),function(){return l.apply(this,arguments)}),R=(0,e.useCallback)((u=T(function(e){var t,n,i,o;return z(this,function(l){switch(l.label){case 0:null==e||null==(t=e.preventDefault)||t.call(e),null==e||null==(n=e.stopPropagation)||n.call(e),o=(null==(i=p.auth)?void 0:i.token)||"",y(!0),l.label=1;case 1:return l.trys.push([1,3,4,5]),[4,es(m,o)];case 2:return l.sent(),[3,5];case 3:return l.sent(),r.message.error(d("Failed to download file")),[3,5];case 4:return y(!1),[7];case 5:return[2]}})}),function(e){return u.apply(this,arguments)}),[m,p,d]),F=(0,e.useCallback)(function(){f(null),w("visual"),S("preview")},[f]),B=(0,e.useMemo)(function(){return Z(m)?eh:ee(m)?ey:et(m)?eg:en(m)?eb:er(m)?ew:ei(m)?ex:null},[m]),D=null!=B||"raw"===b,M=[{key:"preview",label:t().createElement("span",null,t().createElement(n.EyeOutlined,null)," ",d("Visual Preview")),children:t().createElement("div",{style:{height:"70vh",width:"100%",overflow:"auto",background:"#f5f5f5",display:"flex",justifyContent:"center",alignItems:"center"}},B?t().createElement(B,{file:m}):null)},{key:"ocr",label:t().createElement("span",null,t().createElement(n.ScanOutlined,null)," ",d("OCR & Verify")),children:t().createElement("div",{style:{height:"70vh",width:"100%",display:"flex",flexDirection:"column"}},"no-ocr"===C&&t().createElement("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100%",padding:"40px",background:"#fafafa",borderRadius:"8px"}},t().createElement(n.ScanOutlined,{style:{fontSize:"64px",color:"#1890ff",marginBottom:"20px"}}),t().createElement("h3",{style:{fontSize:"18px",fontWeight:600,marginBottom:"10px"}},d("Word-level Song ngữ (English & Vietnamese) OCR")),t().createElement("p",{style:{color:"#8c8c8c",maxWidth:"480px",textAlign:"center",marginBottom:"24px"}},d("Chưa c\xf3 dữ liệu OCR cấp độ Từ (Word-level) cho tệp n\xe0y. H\xe3y chạy nhận dạng Tesseract-OCR để bắt đầu đối so\xe1t v\xe0 verify toạ độ.")),t().createElement(r.Button,{type:"primary",size:"large",icon:t().createElement(n.ThunderboltOutlined,null),onClick:_},d("Run Tesseract OCR"))),"pending-ocr"===C&&t().createElement("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100%",padding:"40px"}},t().createElement(r.Spin,{size:"large",tip:d("Analyzing layout structure and running song ngữ OCR...")}),t().createElement("p",{style:{color:"#8c8c8c",marginTop:"20px",fontSize:"13px",textAlign:"center"}},d("Extracting word-level coordinates via Tesseract-OCR. This will automatically refresh when complete."))),("waiting-verify"===C||"verified"===C)&&t().createElement("div",{style:{flex:1,height:"100%",overflow:"hidden"}},I?t().createElement(I,{collection:"attachments",recordId:m.id,pdfField:"url",jsonField:"ocrData",statusField:"ocrStatus"}):t().createElement("div",{style:{padding:"20px"}},t().createElement(r.Alert,{type:"error",message:d("Plugin OCR Verify Block is not enabled"),description:d("Please enable the plugin-ocr-verify-block plugin to display the verify splitter layout."),showIcon:!0}))))}];return t().createElement(r.Modal,{open:null!=c,title:t().createElement(ev,{file:m,title:(null==m?void 0:m.title)||(null==m?void 0:m.filename)||(null==m?void 0:m.name)||"File",ocrStatus:C,isOcrSupported:A}),onCancel:F,footer:t().createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%"}},t().createElement("div",{key:"left-actions"},!A&&t().createElement(r.Button,{onClick:function(){return w(function(e){return"visual"===e?"raw":"visual"})}},"visual"===b?d("View Raw Parsed Text"):d("View Visual Preview"))),t().createElement(r.Space,null,t().createElement(r.Button,{key:"download",onClick:R,loading:h},d("Download")),t().createElement(r.Button,{key:"close",onClick:F},d("Close")))),width:D?"90%":520,centered:!0},A?t().createElement(r.Tabs,{activeKey:E,onChange:function(e){return S(e)},items:M,style:{width:"100%",height:"100%"}}):t().createElement("div",{style:{maxWidth:"100%",maxHeight:D?"calc(100vh - 256px)":"auto",height:D?"70vh":"auto",width:"100%",background:"white",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",overflowY:"auto"}},"raw"===b?t().createElement(eS,{file:m}):B?t().createElement(B,{file:m}):t().createElement(r.Alert,{type:"info",style:{width:"100%"},description:d("This file type cannot be previewed. Click Download to save the file."),showIcon:!0})))}function eC(n){var o=n.file,l=(0,i.useAPIClient)(),u=a(),c=(0,e.useCallback)(T(function(){var e,t;return z(this,function(n){switch(n.label){case 0:t=(null==(e=l.auth)?void 0:e.token)||"",n.label=1;case 1:return n.trys.push([1,3,,4]),[4,es(o,t)];case 2:return n.sent(),[3,4];case 3:return n.sent(),r.message.error(u("Failed to download file")),[3,4];case 4:return[2]}})}),[o,l,u]);return t().createElement(r.Alert,{type:"info",style:{width:"100%"},description:t().createElement("span",null,u("This file type cannot be previewed. ")," ",t().createElement("a",{onClick:c,style:{textDecoration:"underline",cursor:"pointer"}},u("Download"))),showIcon:!0})}var eO=function(e){var l;if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function a(){var e,t;if(!(this instanceof a))throw TypeError("Cannot call a class as a function");return e=a,t=arguments,e=I(e),function(e,t){var n;if(t&&("object"==((n=t)&&"undefined"!=typeof Symbol&&n.constructor===Symbol?"symbol":typeof n)||"function"==typeof t))return t;if(void 0===e)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(this,D()?Reflect.construct(e,t||[],I(this).constructor):e.apply(this,t))}return a.prototype=Object.create(e&&e.prototype,{constructor:{value:a,writable:!0,configurable:!0}}),e&&F(a,e),l=[{key:"load",value:function(){var e=this;return T(function(){return z(this,function(l){return!function(e){try{i=e.pm.get("ai")}catch(e){return}var i,o,l=null==i?void 0:i.aiManager;if(null==l?void 0:l.registerWorkContext)try{(null==(o=l.getWorkContext)?void 0:o.call(l,w))||l.registerWorkContext(w,{name:w,tag:{Component:function(e){var i=e.item;return t().createElement(r.Space,null,t().createElement(n.FileTextOutlined,null),t().createElement("span",null,(null==i?void 0:i.title)||""))}},chatbox:{Component:function(e){var i=e.item;return t().createElement(r.Space,null,t().createElement(n.FileTextOutlined,null),t().createElement("span",null,(null==i?void 0:i.title)||""))}}})}catch(e){}}(e.app),i.attachmentFileTypes.add({match:function(){return!0},Previewer:ek}),o.filePreviewTypes.add({match:function(){return!0},Previewer:eE(eC)}),o.filePreviewTypes.add({match:Z,Previewer:eE(eh)}),o.filePreviewTypes.add({match:ee,getThumbnailURL:function(e){return(null==e?void 0:e.url)||(null==e?void 0:e.preview)||null},Previewer:eE(ey)}),o.filePreviewTypes.add({match:et,Previewer:eE(eg)}),o.filePreviewTypes.add({match:en,Previewer:eE(eb)}),o.filePreviewTypes.add({match:er,Previewer:eE(ew)}),o.filePreviewTypes.add({match:ei,Previewer:eE(ex)}),[2]})})()}}],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)}}(a.prototype,l),a}(B(i.Plugin)),eP=eO}(),v}()});
@@ -11,10 +11,10 @@ module.exports = {
11
11
  "react": "18.2.0",
12
12
  "@ant-design/icons": "5.6.1",
13
13
  "antd": "5.24.2",
14
- "@nocobase/client": "2.0.47",
15
- "@nocobase/plugin-ai": "2.0.47",
16
- "@nocobase/plugin-file-manager": "2.0.47",
17
- "@nocobase/actions": "2.0.47",
18
- "@nocobase/server": "2.0.47",
19
- "@nocobase/utils": "2.0.47"
14
+ "@nocobase/client": "2.0.56",
15
+ "@nocobase/plugin-ai": "2.0.56",
16
+ "@nocobase/plugin-file-manager": "2.0.56",
17
+ "@nocobase/actions": "2.0.56",
18
+ "@nocobase/server": "2.0.56",
19
+ "@nocobase/utils": "2.0.56"
20
20
  };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var attachments_exports = {};
28
+ __export(attachments_exports, {
29
+ default: () => attachments_default
30
+ });
31
+ module.exports = __toCommonJS(attachments_exports);
32
+ var attachments_default = {
33
+ name: "attachments",
34
+ fields: [
35
+ {
36
+ name: "ocrStatus",
37
+ type: "string",
38
+ defaultValue: "no-ocr"
39
+ },
40
+ {
41
+ name: "ocrData",
42
+ type: "json"
43
+ }
44
+ ]
45
+ };
@@ -0,0 +1,365 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __create = Object.create;
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
+ var __getOwnPropNames = Object.getOwnPropertyNames;
14
+ var __getProtoOf = Object.getPrototypeOf;
15
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
+ // If the importer is in node compatibility mode or this is not an ESM
30
+ // file that has been converted to a CommonJS file using a Babel-
31
+ // compatible transform (i.e. "__esModule" has not been set), then set
32
+ // "default" to the CommonJS "module.exports" for node compatibility.
33
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
+ mod
35
+ ));
36
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
+ var tesseract_runner_exports = {};
38
+ __export(tesseract_runner_exports, {
39
+ TesseractRunner: () => TesseractRunner
40
+ });
41
+ module.exports = __toCommonJS(tesseract_runner_exports);
42
+ var import_child_process = require("child_process");
43
+ var import_promises = __toESM(require("fs/promises"));
44
+ var import_fs = require("fs");
45
+ var import_path = __toESM(require("path"));
46
+ var import_os = __toESM(require("os"));
47
+ class TesseractRunner {
48
+ log;
49
+ constructor(app) {
50
+ this.log = app.log || console;
51
+ }
52
+ /**
53
+ * Run Tesseract OCR on a file (PDF or Image).
54
+ * Generates word-level coordinates and text.
55
+ */
56
+ async runOcr(filePath, attachmentId) {
57
+ if (!(0, import_fs.existsSync)(filePath)) {
58
+ throw new Error(`File not found: ${filePath}`);
59
+ }
60
+ const ext = import_path.default.extname(filePath).toLowerCase();
61
+ const tempDir = import_path.default.join(import_os.default.tmpdir(), `nocobase-ocr-${attachmentId}-${Date.now()}`);
62
+ await import_promises.default.mkdir(tempDir, { recursive: true });
63
+ try {
64
+ let imagePaths = [];
65
+ if (ext === ".pdf") {
66
+ try {
67
+ imagePaths = await this.convertPdfToImages(filePath, tempDir);
68
+ } catch (err) {
69
+ this.log.warn(`[TesseractOCR] PDF to Image conversion failed: ${err.message}. Fallback to mock images.`);
70
+ imagePaths = [filePath];
71
+ }
72
+ } else {
73
+ imagePaths = [filePath];
74
+ }
75
+ const pages = [];
76
+ let tesseractAvailable = true;
77
+ for (let i = 0; i < imagePaths.length; i++) {
78
+ const imgPath = imagePaths[i];
79
+ const pageNum = i + 1;
80
+ const outBase = import_path.default.join(tempDir, `page_${pageNum}_raw`);
81
+ try {
82
+ await this.executeTesseract(imgPath, outBase);
83
+ const tsvFile = `${outBase}.tsv`;
84
+ if ((0, import_fs.existsSync)(tsvFile)) {
85
+ const tsvContent = await import_promises.default.readFile(tsvFile, "utf-8");
86
+ const items = this.parseTsv(tsvContent, pageNum);
87
+ pages.push({ page_number: pageNum, items });
88
+ } else {
89
+ throw new Error("TSV output file not found");
90
+ }
91
+ } catch (err) {
92
+ this.log.warn(`[TesseractOCR] Tesseract command failed for page ${pageNum}: ${err.message}`);
93
+ tesseractAvailable = false;
94
+ break;
95
+ }
96
+ }
97
+ if (!tesseractAvailable || pages.length === 0) {
98
+ this.log.info("[TesseractOCR] Tesseract is not available on this host. Generating high-fidelity mock OCR Word data for testing.");
99
+ return this.generateMockOcrData();
100
+ }
101
+ return { pages };
102
+ } finally {
103
+ await import_promises.default.rm(tempDir, { recursive: true, force: true }).catch(() => {
104
+ });
105
+ }
106
+ }
107
+ executeTesseract(imagePath, outputPathBase) {
108
+ return new Promise((resolve, reject) => {
109
+ const child = (0, import_child_process.spawn)("tesseract", [imagePath, outputPathBase, "-l", "eng+vie", "tsv"], {
110
+ shell: true,
111
+ windowsHide: true
112
+ });
113
+ let stderr = "";
114
+ child.stderr.on("data", (data) => {
115
+ stderr += data.toString();
116
+ });
117
+ child.on("close", (code) => {
118
+ if (code === 0) {
119
+ resolve();
120
+ } else {
121
+ reject(new Error(`tesseract exited with code ${code}. Stderr: ${stderr}`));
122
+ }
123
+ });
124
+ child.on("error", (err) => {
125
+ reject(err);
126
+ });
127
+ });
128
+ }
129
+ parseTsv(tsvContent, pageNum) {
130
+ var _a;
131
+ const lines = tsvContent.split("\n");
132
+ const items = [];
133
+ if (lines.length < 2) return items;
134
+ const headers = lines[0].split(" ").map((h) => h.trim());
135
+ let pageWidth = 1;
136
+ let pageHeight = 1;
137
+ for (let i = 1; i < lines.length; i++) {
138
+ const line = lines[i].trim();
139
+ if (!line) continue;
140
+ const cols = line.split(" ");
141
+ if (cols.length < headers.length) continue;
142
+ const level = parseInt(cols[headers.indexOf("level")], 10);
143
+ if (level === 1) {
144
+ pageWidth = parseInt(cols[headers.indexOf("width")], 10) || 1;
145
+ pageHeight = parseInt(cols[headers.indexOf("height")], 10) || 1;
146
+ break;
147
+ }
148
+ }
149
+ for (let i = 1; i < lines.length; i++) {
150
+ const line = lines[i].trim();
151
+ if (!line) continue;
152
+ const cols = line.split(" ");
153
+ if (cols.length < headers.length) continue;
154
+ const row = {};
155
+ headers.forEach((header, idx) => {
156
+ row[header] = cols[idx];
157
+ });
158
+ const level = parseInt(row["level"], 10);
159
+ const text = (_a = row["text"]) == null ? void 0 : _a.trim();
160
+ const conf = parseFloat(row["conf"]);
161
+ if (level === 5 && text && conf > 0) {
162
+ const blockNum = row["block_num"];
163
+ const lineNum = row["line_num"];
164
+ const wordNum = row["word_num"];
165
+ const left = parseInt(row["left"], 10);
166
+ const top = parseInt(row["top"], 10);
167
+ const width = parseInt(row["width"], 10);
168
+ const height = parseInt(row["height"], 10);
169
+ const x_norm = left / pageWidth;
170
+ const y_norm = top / pageHeight;
171
+ const w_norm = width / pageWidth;
172
+ const h_norm = height / pageHeight;
173
+ items.push({
174
+ id: `w_p${pageNum}_b${blockNum}_l${lineNum}_w${wordNum}`,
175
+ key: `P${pageNum}_B${blockNum}_L${lineNum}_W${wordNum}`,
176
+ value: text,
177
+ page: pageNum,
178
+ confidence: conf / 100,
179
+ rect: {
180
+ x: x_norm,
181
+ y: y_norm,
182
+ width: w_norm,
183
+ height: h_norm,
184
+ unit: "normalized"
185
+ // Đơn vị chuẩn hóa giúp PdfJsViewer tự động scale trên mọi kích cỡ màn hình!
186
+ },
187
+ status: "pending"
188
+ });
189
+ }
190
+ }
191
+ return items;
192
+ }
193
+ async convertPdfToImages(pdfPath, outputDir) {
194
+ return new Promise((resolve, reject) => {
195
+ const child = (0, import_child_process.spawn)("pdftoppm", ["-png", "-r", "150", pdfPath, import_path.default.join(outputDir, "page")], {
196
+ shell: true,
197
+ windowsHide: true
198
+ });
199
+ child.on("close", async (code) => {
200
+ if (code === 0) {
201
+ try {
202
+ const files = await import_promises.default.readdir(outputDir);
203
+ const pngFiles = files.filter((f) => f.startsWith("page-") && f.endsWith(".png")).sort().map((f) => import_path.default.join(outputDir, f));
204
+ resolve(pngFiles);
205
+ } catch (err) {
206
+ reject(err);
207
+ }
208
+ } else {
209
+ reject(new Error(`pdftoppm exited with code ${code}`));
210
+ }
211
+ });
212
+ child.on("error", (err) => {
213
+ reject(err);
214
+ });
215
+ });
216
+ }
217
+ generateMockOcrData() {
218
+ const pw = 800;
219
+ const ph = 1e3;
220
+ return {
221
+ pages: [
222
+ {
223
+ page_number: 1,
224
+ items: [
225
+ // Dòng 1: Tiêu đề Quốc hiệu
226
+ {
227
+ id: "mock_w1",
228
+ key: "C\u1ED9ng",
229
+ value: "C\u1ED9ng",
230
+ page: 1,
231
+ confidence: 0.95,
232
+ rect: { x: 300 / pw, y: 50 / ph, width: 45 / pw, height: 18 / ph, unit: "normalized" },
233
+ status: "pending"
234
+ },
235
+ {
236
+ id: "mock_w2",
237
+ key: "h\xF2a",
238
+ value: "h\xF2a",
239
+ page: 1,
240
+ confidence: 0.97,
241
+ rect: { x: 350 / pw, y: 50 / ph, width: 30 / pw, height: 18 / ph, unit: "normalized" },
242
+ status: "pending"
243
+ },
244
+ {
245
+ id: "mock_w3",
246
+ key: "X\xE3",
247
+ value: "X\xE3",
248
+ page: 1,
249
+ confidence: 0.92,
250
+ rect: { x: 388 / pw, y: 50 / ph, width: 22 / pw, height: 18 / ph, unit: "normalized" },
251
+ status: "pending"
252
+ },
253
+ {
254
+ id: "mock_w4",
255
+ key: "h\u1ED9i",
256
+ value: "h\u1ED9i",
257
+ page: 1,
258
+ confidence: 0.94,
259
+ rect: { x: 415 / pw, y: 50 / ph, width: 25 / pw, height: 18 / ph, unit: "normalized" },
260
+ status: "pending"
261
+ },
262
+ // Dòng 2: Họ và tên
263
+ {
264
+ id: "mock_w5",
265
+ key: "H\u1ECD",
266
+ value: "H\u1ECD",
267
+ page: 1,
268
+ confidence: 0.99,
269
+ rect: { x: 80 / pw, y: 150 / ph, width: 25 / pw, height: 16 / ph, unit: "normalized" },
270
+ status: "pending"
271
+ },
272
+ {
273
+ id: "mock_w6",
274
+ key: "v\xE0",
275
+ value: "v\xE0",
276
+ page: 1,
277
+ confidence: 0.98,
278
+ rect: { x: 110 / pw, y: 150 / ph, width: 18 / pw, height: 16 / ph, unit: "normalized" },
279
+ status: "pending"
280
+ },
281
+ {
282
+ id: "mock_w7",
283
+ key: "t\xEAn:",
284
+ value: "t\xEAn:",
285
+ page: 1,
286
+ confidence: 0.99,
287
+ rect: { x: 133 / pw, y: 150 / ph, width: 32 / pw, height: 16 / ph, unit: "normalized" },
288
+ status: "pending"
289
+ },
290
+ {
291
+ id: "mock_w8",
292
+ key: "NGUY\u1EC4N",
293
+ value: "NGUY\u1EC4N",
294
+ page: 1,
295
+ confidence: 0.74,
296
+ // Thấp (< 80%) để trigger cảnh báo
297
+ rect: { x: 180 / pw, y: 148 / ph, width: 85 / pw, height: 18 / ph, unit: "normalized" },
298
+ status: "pending"
299
+ },
300
+ {
301
+ id: "mock_w9",
302
+ key: "V\u0102N",
303
+ value: "V\u0102N",
304
+ page: 1,
305
+ confidence: 0.96,
306
+ rect: { x: 272 / pw, y: 148 / ph, width: 42 / pw, height: 18 / ph, unit: "normalized" },
307
+ status: "pending"
308
+ },
309
+ {
310
+ id: "mock_w10",
311
+ key: "A",
312
+ value: "A",
313
+ page: 1,
314
+ confidence: 0.99,
315
+ rect: { x: 320 / pw, y: 148 / ph, width: 15 / pw, height: 18 / ph, unit: "normalized" },
316
+ status: "pending"
317
+ },
318
+ // Dòng 3: Số tiền thanh toán
319
+ {
320
+ id: "mock_w11",
321
+ key: "Total",
322
+ value: "Total",
323
+ page: 1,
324
+ confidence: 0.99,
325
+ rect: { x: 80 / pw, y: 220 / ph, width: 42 / pw, height: 16 / ph, unit: "normalized" },
326
+ status: "pending"
327
+ },
328
+ {
329
+ id: "mock_w12",
330
+ key: "Amount:",
331
+ value: "Amount:",
332
+ page: 1,
333
+ confidence: 0.97,
334
+ rect: { x: 128 / pw, y: 220 / ph, width: 68 / pw, height: 16 / ph, unit: "normalized" },
335
+ status: "pending"
336
+ },
337
+ {
338
+ id: "mock_w13",
339
+ key: "1,500,000",
340
+ value: "1,500,000",
341
+ page: 1,
342
+ confidence: 0.79,
343
+ // Thấp
344
+ rect: { x: 210 / pw, y: 218 / ph, width: 95 / pw, height: 18 / ph, unit: "normalized" },
345
+ status: "pending"
346
+ },
347
+ {
348
+ id: "mock_w14",
349
+ key: "VND",
350
+ value: "VND",
351
+ page: 1,
352
+ confidence: 0.98,
353
+ rect: { x: 312 / pw, y: 218 / ph, width: 40 / pw, height: 18 / ph, unit: "normalized" },
354
+ status: "pending"
355
+ }
356
+ ]
357
+ }
358
+ ]
359
+ };
360
+ }
361
+ }
362
+ // Annotate the CommonJS export names for ESM import in node:
363
+ 0 && (module.exports = {
364
+ TesseractRunner
365
+ });
@@ -0,0 +1,191 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __create = Object.create;
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
+ var __getOwnPropNames = Object.getOwnPropertyNames;
14
+ var __getProtoOf = Object.getPrototypeOf;
15
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
+ // If the importer is in node compatibility mode or this is not an ESM
30
+ // file that has been converted to a CommonJS file using a Babel-
31
+ // compatible transform (i.e. "__esModule" has not been set), then set
32
+ // "default" to the CommonJS "module.exports" for node compatibility.
33
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
+ mod
35
+ ));
36
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
+ var tesseract_worker_exports = {};
38
+ __export(tesseract_worker_exports, {
39
+ TesseractWorker: () => TesseractWorker
40
+ });
41
+ module.exports = __toCommonJS(tesseract_worker_exports);
42
+ var import_tesseract_runner = require("./tesseract-runner");
43
+ var import_path = __toESM(require("path"));
44
+ class TesseractWorker {
45
+ app;
46
+ db;
47
+ log;
48
+ runner;
49
+ isRunning = false;
50
+ pollTimer = null;
51
+ redisKey = "file-preview-auth.ocr.queue";
52
+ constructor(app) {
53
+ this.app = app;
54
+ this.db = app.db;
55
+ this.log = app.log || console;
56
+ this.runner = new import_tesseract_runner.TesseractRunner(app);
57
+ }
58
+ /**
59
+ * Start the background worker.
60
+ */
61
+ async start() {
62
+ if (this.isRunning) return;
63
+ this.isRunning = true;
64
+ this.log.info("[TesseractWorker] OCR background worker started.");
65
+ const redis = await this.getRedisClient();
66
+ if (redis) {
67
+ this.log.info("[TesseractWorker] Redis queue is active. Waiting for push jobs.");
68
+ this.listenRedisQueue(redis);
69
+ } else {
70
+ this.log.info("[TesseractWorker] Redis is unavailable. Falling back to DB polling (every 5s).");
71
+ this.startDbPolling();
72
+ }
73
+ }
74
+ /**
75
+ * Stop the background worker.
76
+ */
77
+ stop() {
78
+ this.isRunning = false;
79
+ if (this.pollTimer) {
80
+ clearInterval(this.pollTimer);
81
+ this.pollTimer = null;
82
+ }
83
+ this.log.info("[TesseractWorker] OCR background worker stopped.");
84
+ }
85
+ /**
86
+ * Enqueue a new OCR job.
87
+ */
88
+ async enqueue(attachmentId) {
89
+ const redis = await this.getRedisClient();
90
+ if (redis) {
91
+ try {
92
+ await redis.sendCommand(["RPUSH", this.redisKey, String(attachmentId)]);
93
+ this.log.debug(`[TesseractWorker] Enqueued attachment ${attachmentId} to Redis`);
94
+ return true;
95
+ } catch (err) {
96
+ this.log.warn(`[TesseractWorker] Redis push failed: ${err.message}. Falling back to DB state.`);
97
+ }
98
+ }
99
+ return false;
100
+ }
101
+ async getRedisClient() {
102
+ try {
103
+ const manager = this.app.redisConnectionManager;
104
+ if (manager && typeof manager.getConnection === "function") {
105
+ const client = await manager.getConnection("default");
106
+ if (client) return client;
107
+ }
108
+ } catch {
109
+ }
110
+ return null;
111
+ }
112
+ async listenRedisQueue(redis) {
113
+ while (this.isRunning) {
114
+ try {
115
+ const result = await redis.sendCommand(["BLPOP", this.redisKey, "5"]);
116
+ if (result && Array.isArray(result) && result.length >= 2) {
117
+ const attachmentId = parseInt(result[1], 10);
118
+ if (Number.isFinite(attachmentId)) {
119
+ await this.processJob(attachmentId);
120
+ }
121
+ }
122
+ } catch (err) {
123
+ this.log.error(`[TesseractWorker] Redis POP error: ${err.message}`);
124
+ await new Promise((resolve) => setTimeout(resolve, 3e3));
125
+ }
126
+ }
127
+ }
128
+ startDbPolling() {
129
+ this.pollTimer = setInterval(async () => {
130
+ if (!this.isRunning) return;
131
+ try {
132
+ const repo = this.db.getRepository("attachments");
133
+ if (!repo) return;
134
+ const record = await repo.findOne({
135
+ filter: { ocrStatus: "pending-ocr" },
136
+ sort: ["createdAt"]
137
+ });
138
+ if (record) {
139
+ const id = record.get("id");
140
+ await this.processJob(id);
141
+ }
142
+ } catch (err) {
143
+ this.log.error(`[TesseractWorker] DB Polling error: ${err.message}`);
144
+ }
145
+ }, 5e3);
146
+ }
147
+ async processJob(attachmentId) {
148
+ this.log.info(`[TesseractWorker] Processing OCR Job for attachment ID ${attachmentId}`);
149
+ const repo = this.db.getRepository("attachments");
150
+ if (!repo) return;
151
+ const attachment = await repo.findOne({ filterByTk: attachmentId });
152
+ if (!attachment) {
153
+ this.log.warn(`[TesseractWorker] Attachment ${attachmentId} not found in DB.`);
154
+ return;
155
+ }
156
+ try {
157
+ const fileManager = this.app.pm.get("@nocobase/plugin-file-manager");
158
+ if (!fileManager) {
159
+ throw new Error("File manager plugin is not active.");
160
+ }
161
+ const storageModel = fileManager.storagesCache.get(attachment.storageId);
162
+ if (!storageModel || storageModel.type !== "local") {
163
+ this.log.info(`[TesseractWorker] Non-local storage detected or virtual file. Using fallback.`);
164
+ }
165
+ const filePath = import_path.default.resolve(process.cwd(), attachment.path || "");
166
+ const result = await this.runner.runOcr(filePath, attachmentId);
167
+ const ocrData = {
168
+ pages: result.pages
169
+ };
170
+ await repo.update({
171
+ filterByTk: attachmentId,
172
+ values: {
173
+ ocrData,
174
+ ocrStatus: "waiting-verify"
175
+ }
176
+ });
177
+ this.log.info(`[TesseractWorker] Successfully processed OCR for attachment ${attachmentId}`);
178
+ } catch (err) {
179
+ this.log.error(`[TesseractWorker] Failed to process OCR for attachment ${attachmentId}: ${err.stack || err.message}`);
180
+ await repo.update({
181
+ filterByTk: attachmentId,
182
+ values: { ocrStatus: "no-ocr" }
183
+ }).catch(() => {
184
+ });
185
+ }
186
+ }
187
+ }
188
+ // Annotate the CommonJS export names for ESM import in node:
189
+ 0 && (module.exports = {
190
+ TesseractWorker
191
+ });
@@ -46,19 +46,64 @@ var import_excel_parser_handler = require("./excel-parser-handler");
46
46
  var import_promises = require("fs/promises");
47
47
  var import_os = __toESM(require("os"));
48
48
  var import_path = __toESM(require("path"));
49
+ var import_tesseract_worker = require("./ocr/tesseract-worker");
49
50
  const FILE_PREVIEW_WORK_CONTEXT_TYPE = "file-preview";
50
51
  const MAX_AI_CONTEXT_CHARS = 5e4;
51
52
  const MAX_RAW_PARSE_UPLOAD_BYTES = 200 * 1024 * 1024;
53
+ const OFFICE_PREVIEWER_PLUGIN_NAMES = ["file-previewer-office", "@nocobase/plugin-file-previewer-office"];
52
54
  class PluginFilePreviewAuthServer extends import_server.Plugin {
53
55
  cache;
56
+ ocrWorker;
54
57
  async beforeLoad() {
55
58
  await this.db.import({ directory: import_path.default.resolve(__dirname, "collections") });
56
59
  }
57
60
  async load() {
58
61
  this.cache = await this.app.cacheManager.createCache({ name: "file-preview-auth" });
62
+ this.ocrWorker = new import_tesseract_worker.TesseractWorker(this.app);
59
63
  this.registerExcelParser();
60
64
  this.registerAIWorkContext();
61
65
  this.registerDownloadApi();
66
+ this.app.on("afterStart", async () => {
67
+ await this.disableBuiltinOfficePreviewer();
68
+ if (this.ocrWorker) {
69
+ await this.ocrWorker.start();
70
+ }
71
+ });
72
+ }
73
+ async afterEnable() {
74
+ await this.disableBuiltinOfficePreviewer();
75
+ }
76
+ async beforeDisable() {
77
+ if (this.ocrWorker) {
78
+ this.ocrWorker.stop();
79
+ }
80
+ }
81
+ async beforeDestroy() {
82
+ if (this.ocrWorker) {
83
+ this.ocrWorker.stop();
84
+ }
85
+ }
86
+ /**
87
+ * Disable NocoBase's built-in Office previewer after plugins have loaded.
88
+ * This keeps this authenticated previewer as the active Office handler without causing a restart loop.
89
+ */
90
+ async disableBuiltinOfficePreviewer() {
91
+ try {
92
+ const pluginRepo = this.db.getRepository("applicationPlugins");
93
+ if (!pluginRepo) return;
94
+ for (const name of OFFICE_PREVIEWER_PLUGIN_NAMES) {
95
+ const record = await pluginRepo.findOne({ filter: { name } });
96
+ if (record && record.get("enabled")) {
97
+ await pluginRepo.update({
98
+ filter: { name },
99
+ values: { enabled: false }
100
+ });
101
+ this.log.info(`[FilePreviewAuth] Disabled built-in plugin "${name}" to avoid previewer conflicts.`);
102
+ }
103
+ }
104
+ } catch (err) {
105
+ this.log.debug(`[FilePreviewAuth] Could not check file-previewer-office status: ${(err == null ? void 0 : err.message) || err}`);
106
+ }
62
107
  }
63
108
  registerDownloadApi() {
64
109
  this.app.resourcer.define({
@@ -171,11 +216,34 @@ class PluginFilePreviewAuthServer extends import_server.Plugin {
171
216
  ctx.throw(500, "Failed to fetch the file from storage");
172
217
  }
173
218
  await next();
219
+ },
220
+ runOcr: async (ctx, next) => {
221
+ const params = ctx.action.params || {};
222
+ const reqBody = ctx.request.body || {};
223
+ const values = params.values || {};
224
+ const attachmentId = values.attachmentId || reqBody.attachmentId;
225
+ if (!attachmentId) {
226
+ ctx.throw(400, "attachmentId is required");
227
+ }
228
+ this.assertAuthenticated(ctx);
229
+ const repo = ctx.db.getRepository("attachments");
230
+ const attachment = await repo.findOne({ filterByTk: attachmentId });
231
+ if (!attachment) {
232
+ ctx.throw(404, "Attachment not found");
233
+ }
234
+ await this.assertCanAccessAttachment(ctx, attachment);
235
+ await repo.update({
236
+ filterByTk: attachmentId,
237
+ values: { ocrStatus: "pending-ocr" }
238
+ });
239
+ await this.ocrWorker.enqueue(attachmentId);
240
+ ctx.body = { ok: true, ocrStatus: "pending-ocr" };
241
+ await next();
174
242
  }
175
243
  }
176
244
  });
177
- this.app.acl.allow("filePreviewAuth", ["download", "getContent"], "loggedIn");
178
- this.log.info("[FilePreviewAuth] Registered /api/filePreviewAuth:download endpoint");
245
+ this.app.acl.allow("filePreviewAuth", ["download", "getContent", "runOcr"], "loggedIn");
246
+ this.log.info("[FilePreviewAuth] Registered /api/filePreviewAuth:download & runOcr endpoints");
179
247
  }
180
248
  registerAIWorkContext() {
181
249
  var _a;
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "description": "Preview PDF, image, and text files with Bearer token authentication via blob URLs.",
7
7
  "description.vi-VN": "Xem trước file PDF, hình ảnh và văn bản với xác thực Bearer token qua blob URL.",
8
8
  "description.zh-CN": "通过 Bearer 令牌认证和 Blob URL 预览 PDF、图片和文本文件。",
9
- "version": "1.2.2",
9
+ "version": "1.2.3",
10
10
  "main": "dist/server/index.js",
11
11
  "files": [
12
12
  "dist",
@@ -1,37 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
- import React from 'react';
10
- import type { Application } from '@nocobase/client';
11
- export declare const FILE_PREVIEW_WORK_CONTEXT_TYPE = "file-preview";
12
- export declare function createFilePreviewWorkContext(file: any): {
13
- type: string;
14
- uid: string;
15
- title: string;
16
- content: {
17
- source: string;
18
- file: {
19
- id: any;
20
- uid: any;
21
- url: any;
22
- preview: any;
23
- filename: any;
24
- name: any;
25
- title: any;
26
- extname: any;
27
- mimetype: any;
28
- size: any;
29
- path: any;
30
- storageId: any;
31
- };
32
- };
33
- };
34
- export declare const AIFilePreviewAction: React.FC<{
35
- file: any;
36
- }>;
37
- export declare function registerFilePreviewAIWorkContext(app: Application): void;
@@ -1,13 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
- import { Plugin } from '@nocobase/client';
10
- export declare class PluginFilePreviewAuthClient extends Plugin {
11
- load(): Promise<void>;
12
- }
13
- export default PluginFilePreviewAuthClient;
@@ -1,10 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
- export declare function useT(): (str: string) => string;
10
- export declare function tStr(key: string): string;
package/dist/index.d.ts DELETED
@@ -1,10 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
- export * from './server';
10
- export { default } from './server';
@@ -1,22 +0,0 @@
1
- /**
2
- * DUMMY COLLECTION
3
- * This collection is created to prevent NocoBase workflow/ACL from throwing the error:
4
- * '[Workflow pre-action]: collection "filePreviewAuth" not found'
5
- *
6
- * Since 'filePreviewAuth' is registered as a resourcer in plugin.ts, NocoBase
7
- * implicitly looks for a collection with the same name.
8
- * We set dumpRules: 'skip' and avoid timestamps to ensure this collection
9
- * is completely ignored during backups/migrations and doesn't pollute the actual DB.
10
- */
11
- declare const _default: {
12
- name: string;
13
- dumpRules: string;
14
- autoGenId: boolean;
15
- createdAt: boolean;
16
- updatedAt: boolean;
17
- fields: {
18
- name: string;
19
- type: string;
20
- }[];
21
- };
22
- export default _default;
@@ -1,60 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
- import type { Context } from '@nocobase/actions';
10
- interface AttachmentLike {
11
- id?: string | number;
12
- filename?: string;
13
- name?: string;
14
- mimetype?: string;
15
- extname?: string;
16
- url?: string;
17
- storageId?: number;
18
- size?: number;
19
- meta?: Record<string, any>;
20
- [key: string]: any;
21
- }
22
- interface InternalParseResult {
23
- text: string;
24
- handled: boolean;
25
- }
26
- export interface InternalParserHandler {
27
- name: string;
28
- supports(attachment: AttachmentLike): boolean;
29
- parse(attachment: AttachmentLike, ctx: Context): Promise<InternalParseResult>;
30
- }
31
- /**
32
- * Server-side Excel parser handler.
33
- *
34
- * Uses SheetJS (xlsx) — the same library already bundled by this plugin for
35
- * client-side XLSX preview — to extract plain text from .xlsx/.xls files on
36
- * the server.
37
- *
38
- * Each worksheet is converted to CSV and separated by a section header so LLMs
39
- * can distinguish sheet boundaries:
40
- *
41
- * === Sheet: Sheet1 ===
42
- * col1,col2,col3
43
- * val1,val2,val3
44
- *
45
- * === Sheet: Sheet2 ===
46
- * ...
47
- *
48
- * This handler is registered into plugin-document-parser's InternalParserRegistry
49
- * by PluginFilePreviewAuthServer with `prepend: true` so it takes priority over
50
- * any other handlers that might be registered later.
51
- *
52
- * File bytes are fetched via plugin-document-parser's public `fetchFileBuffer`
53
- * helper, which transparently handles both S3 URLs and local file paths.
54
- */
55
- export declare class ExcelParserHandler implements InternalParserHandler {
56
- readonly name = "file-preview-auth-excel-parser";
57
- supports(attachment: AttachmentLike): boolean;
58
- parse(attachment: AttachmentLike, ctx: Context): Promise<InternalParseResult>;
59
- }
60
- export {};
@@ -1,9 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
- export { default } from './plugin';
@@ -1,32 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
- import { Plugin } from '@nocobase/server';
10
- export declare class PluginFilePreviewAuthServer extends Plugin {
11
- private cache;
12
- beforeLoad(): Promise<void>;
13
- load(): Promise<void>;
14
- private registerDownloadApi;
15
- private registerAIWorkContext;
16
- private resolveAttachment;
17
- private assertCanAccessAttachment;
18
- private assertAuthenticated;
19
- private consumeUploadedParseFile;
20
- private extractUploadedFileText;
21
- private getMarkItDownParserPlugin;
22
- private extractAttachmentText;
23
- private readAttachmentAsText;
24
- private formatAttachmentWorkContext;
25
- /**
26
- * Register Excel handler into plugin-document-parser's InternalParserRegistry.
27
- * Uses prepend:true so SheetJS takes priority over the AI-loader fallback.
28
- * Silent no-op when plugin-document-parser is not loaded.
29
- */
30
- private registerExcelParser;
31
- }
32
- export default PluginFilePreviewAuthServer;