plugin-file-preview-auth 1.3.9 → 1.3.10

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("react"),require("antd"),require("@nocobase/client"),require("@ant-design/icons"),require("@nocobase/plugin-file-manager/client"),require("@nocobase/plugin-ai/client")):"function"==typeof define&&define.amd?define("plugin-file-preview-auth",["react","antd","@nocobase/client","@ant-design/icons","@nocobase/plugin-file-manager/client","@nocobase/plugin-ai/client"],t):"object"==typeof exports?exports["plugin-file-preview-auth"]=t(require("react"),require("antd"),require("@nocobase/client"),require("@ant-design/icons"),require("@nocobase/plugin-file-manager/client"),require("@nocobase/plugin-ai/client")):e["plugin-file-preview-auth"]=t(e.react,e.antd,e["@nocobase/client"],e["@ant-design/icons"],e["@nocobase/plugin-file-manager/client"],e["@nocobase/plugin-ai/client"])}(self,function(e,t,n,r,i,l){return function(){"use strict";var o,a,u,c={375:function(e){e.exports=r},342:function(e){e.exports=n},75:function(e){e.exports=l},609:function(e){e.exports=i},59:function(e){e.exports=t},155:function(t){t.exports=e}},s={};function f(e){var t=s[e];if(void 0!==t)return t.exports;var n=s[e]={exports:{}};return c[e](n,n.exports,f),n.exports}f.m=c,f.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(t,{a:t}),t},f.d=function(e,t){for(var n in t)f.o(t,n)&&!f.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},f.f={},f.e=function(e){return Promise.all(Object.keys(f.f).reduce(function(t,n){return f.f[n](e,t),t},[]))},f.u=function(e){return""+e+"."+({713:"79a55458f5b67f39",823:"8b0ab22c181d4523",828:"ae8e47a2e7a3bc9e",892:"a568eb42fd6f0047"})[e]+".js"},f.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}}(),f.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},d={},f.l=function(e,t,n,r){if(d[e])return void d[e].push(t);if(void 0!==n)for(var i,l,o=document.getElementsByTagName("script"),a=0;a<o.length;a++){var u=o[a];if(u.getAttribute("src")==e||u.getAttribute("data-rspack")=="plugin-file-preview-auth:"+n){i=u;break}}i||(l=!0,(i=document.createElement("script")).timeout=120,f.nc&&i.setAttribute("nonce",f.nc),i.setAttribute("data-rspack","plugin-file-preview-auth:"+n),i.src=e),d[e]=[t];var c=function(t,n){i.onerror=i.onload=null,clearTimeout(s);var r=d[e];if(delete d[e],i.parentNode&&i.parentNode.removeChild(i),r&&r.forEach(function(e){return e(n)}),t)return t(n)},s=setTimeout(c.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=c.bind(null,i.onerror),i.onload=c.bind(null,i.onload),l&&document.head.appendChild(i)},f.r=function(e){"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},f.g.importScripts&&(p=f.g.location+"");var d,p,m=f.g.document;if(!p&&m&&(m.currentScript&&"SCRIPT"===m.currentScript.tagName.toUpperCase()&&(p=m.currentScript.src),!p)){var v=m.getElementsByTagName("script");if(v.length)for(var g=v.length-1;g>-1&&(!p||!/^http(s?):/.test(p));)p=v[g--].src}if(!p)throw Error("Automatic publicPath is not supported in this browser");f.p=p.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),o={889:0},f.f.j=function(e,t){var n=f.o(o,e)?o[e]:void 0;if(0!==n)if(n)t.push(n[2]);else{var r=new Promise(function(t,r){n=o[e]=[t,r]});t.push(n[2]=r);var i=f.p+f.u(e),l=Error();f.l(i,function(t){if(f.o(o,e)&&(0!==(n=o[e])&&(o[e]=void 0),n)){var r=t&&("load"===t.type?"missing":t.type),i=t&&t.target&&t.target.src;l.message="Loading chunk "+e+" failed.\n("+r+": "+i+")",l.name="ChunkLoadError",l.type=r,l.request=i,n[1](l)}},"chunk-"+e,e)}},a=function(e,t){var n,r,i=t[0],l=t[1],a=t[2],u=0;if(i.some(function(e){return 0!==o[e]})){for(n in l)f.o(l,n)&&(f.m[n]=l[n]);a&&a(f)}for(e&&e(t);u<i.length;u++)r=i[u],f.o(o,r)&&o[r]&&o[r][0](),o[r]=0},(u=self.webpackChunkplugin_file_preview_auth=self.webpackChunkplugin_file_preview_auth||[]).forEach(a.bind(null,0)),u.push=a.bind(null,u.push.bind(u));var h={};return!function(){var e="",t="u">typeof document?document.currentScript:null;if(t&&t.src&&(e=t.src.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/")),!e){var n=window.__webpack_public_path__||"";n&&("/"!==n.charAt(n.length-1)&&(n+="/"),e=n+"static/plugins/plugin-file-preview-auth/dist/client/")}if(!e){var r=window.__nocobase_modern_client_prefix__||"v",i="/"+(r=String(r).replace(/^\/+|\/+$/g,"")||"v")+"/";if(!(e=window.__nocobase_public_path__||"")&&window.location&&window.location.pathname){var l=window.location.pathname||"/",o=l.indexOf(i);e=o>=0?l.slice(0,o+1):"/"}e&&(e=e.replace(RegExp("/"+r+"/?$"),"/")),e||(e="/"),"/"!==e.charAt(e.length-1)&&(e+="/"),e+="static/plugins/plugin-file-preview-auth/dist/client/"}f.p=e}(),!function(){f.r(h),f.d(h,{normalizeOcrAttachmentId:function(){return et},default:function(){return eN},PluginFilePreviewAuthClient:function(){return eF},extractOcrStatusRecord:function(){return ep},getOcrAttachmentId:function(){return en},isOcrCompleteStatus:function(){return ed}});var e=f(155),t=f.n(e),n=f(375),r=f(59),i=f(342),l=f(609),o=JSON.parse('{"UU":"plugin-file-preview-auth"}');function a(){var e=(0,i.useApp)();return function(t){return e.i18n.t(t,{ns:[o.UU,"client"]})}}var u=f(75);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,l,o){try{var a=e[l](o),u=a.value}catch(e){n(e);return}a.done?t(u):Promise.resolve(u).then(r,i)}function d(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function p(e){return(p=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function m(e,t){return(m=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function v(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,i=null==e?null:"u">typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var l=[],o=!0,a=!1;try{for(i=i.call(e);!(o=(n=i.next()).done)&&(l.push(n.value),!t||l.length!==t);o=!0);}catch(e){a=!0,r=e}finally{try{o||null==i.return||i.return()}finally{if(a)throw r}}return l}}(e,t)||y(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function g(e){return function(e){if(Array.isArray(e))return c(e)}(e)||function(e){if("u">typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||y(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 y(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=p(n),(t=function(e,t){var n;if(t&&("object"==((n=t)&&"u">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||[],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&&m(r,e),n=[{key:"getDerivedStateFromError",value:function(){return{hasError:!0}}}],t=[{key:"render",value:function(){return this.state.hasError?null:this.props.children}}],d(r.prototype,t),n&&d(r,n),r}(t().Component),k=function(i){var l=i.file,o=a(),c=(0,u.useAIConfigRepository)(),f=(0,u.useChatBoxActions)().triggerTask,d=v((0,e.useState)([]),2),p=d[0],m=d[1],h=v((0,e.useState)(!1),2),y=h[0],b=h[1],S=v((0,e.useState)(!1),2),k=S[0],O=S[1];(0,e.useEffect)(function(){var e=!1;if(null==c?void 0:c.getAIEmployees){var t=c.aiEmployees||[];return t.length?void m(g(t)):(b(!0),c.getAIEmployees().then(function(t){e||(m(g(t||[])),b(!1))}).catch(function(){e||(m([]),b(!1))}),function(){e=!0})}},[c]);var C=(0,e.useMemo)(function(){var e=function(){try{return window.localStorage.getItem(x)||""}catch(e){return""}}();return e?g(p).sort(function(t,n){return t.username===e?-1:+(n.username===e)}):p},[p]),P=(0,e.useCallback)(function(e){var t;return(t=function(){return function(e,t){var n,r,i,l={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),a=Object.defineProperty;return a(o,"next",{value:u(0)}),a(o,"throw",{value:u(1)}),a(o,"return",{value:u(2)}),"function"==typeof Symbol&&a(o,Symbol.iterator,{value:function(){return this}}),o;function u(a){return function(u){var c=[a,u];if(n)throw TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(l=0)),l;)try{if(n=1,r&&(i=2&c[0]?r.return:c[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,c[1])).done)return i;switch(r=0,i&&(c=[2&c[0],i.value]),c[0]){case 0:case 1:i=c;break;case 4:return l.label++,{value:c[1],done:!1};case 5:l.label++,r=c[1],c=[0];continue;case 7:c=l.ops.pop(),l.trys.pop();continue;default:if(!(i=(i=l.trys).length>0&&i[i.length-1])&&(6===c[0]||2===c[0])){l=0;continue}if(3===c[0]&&(!i||c[1]>i[0]&&c[1]<i[3])){l.label=c[1];break}if(6===c[0]&&l.label<i[1]){l.label=i[1],i=c;break}if(i&&l.label<i[2]){l.label=i[2],l.ops.push(c);break}i[2]&&l.ops.pop(),l.trys.pop();continue}c=t.call(e,l)}catch(e){c=[6,e],r=0}finally{n=i=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}}(this,function(t){switch(t.label){case 0:if(!e||!l)return[2];O(!0),t.label=1;case 1:t.trys.push([1,3,4,5]);var n,i,a,u,c,s,d,p,m,v,g=e.username;try{window.localStorage.setItem(x,g)}catch(e){}return[4,f({aiEmployee:e,tasks:[{title:E(l),message:{user:o("Please help me analyze the file currently open in preview."),workContext:[{type:w,uid:(c=null!=(n=null!=(i=null!=(a=null!=(u=null==l?void 0:l.id)?u:null==l?void 0:l.uid)?a:null==l?void 0:l.url)?i:null==l?void 0:l.path)?n:E(l),"file-preview:".concat(String(c))),title:E(l),content:{source:"plugin-file-preview-auth",file:{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!=(s=null!=(d=null==l?void 0:l.storageId)?d:null==l?void 0:l.storage_id)?s:null==l||null==(p=l.storage)?void 0:p.id,storage_id:null==l?void 0:l.storage_id,storageType:(null==l?void 0:l.storageType)||(null==l||null==(m=l.storage)?void 0:m.type),storageName:(null==l?void 0:l.storageName)||(null==l||null==(v=l.storage)?void 0:v.name),storage:null==l?void 0:l.storage,collectionName:null==l?void 0:l.collectionName}}}]},autoSend:!1}]})];case 2:return t.sent(),[3,5];case 3:return t.sent(),r.message.error(o("Failed to open AI chat")),[3,5];case 4:return O(!1),[7];case 5:return[2]}})},function(){var e=this,n=arguments;return new Promise(function(r,i){var l=t.apply(e,n);function o(e){s(l,r,i,o,a,"next",e)}function a(e){s(l,r,i,o,a,"throw",e)}o(void 0)})})()},[l,o,f]),j=C.map(function(e){return{key:e.username,label:(null==e?void 0:e.nickname)||(null==e?void 0:e.username)||"",onClick:function(){return P(e)}}});return y||C.length?1===C.length?t().createElement(r.Tooltip,{title:o("Ask AI")},t().createElement(r.Button,{type:"text",size:"small",icon:t().createElement(n.RobotOutlined,null),loading:k||y,onClick:function(e){e.stopPropagation(),P(C[0])}},o("Ask AI"))):t().createElement(r.Tooltip,{title:o("Ask AI")},t().createElement(r.Dropdown,{menu:{items:j},trigger:["click"],placement:"bottomRight",disabled:k||y},t().createElement(r.Button,{type:"text",size:"small",icon:t().createElement(n.RobotOutlined,null),loading:k||y,onClick:function(e){return e.stopPropagation()}},o("Ask AI")))):null},O=function(e){var n=e.file;return t().createElement(S,null,t().createElement(k,{file:n}))};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 P(e,t,n,r,i,l,o){try{var a=e[l](o),u=a.value}catch(e){n(e);return}a.done?t(u):Promise.resolve(u).then(r,i)}function j(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var l=e.apply(t,n);function o(e){P(l,r,i,o,a,"next",e)}function a(e){P(l,r,i,o,a,"throw",e)}o(void 0)})}}function T(e,t,n){return(T=B()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&A(i,n.prototype),i}).apply(null,arguments)}function R(e){return(R=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 I(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):(function(e){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t.push.apply(t,n)}return t})(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}function A(e,t){return(A=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function F(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,i=null==e?null:"u">typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var l=[],o=!0,a=!1;try{for(i=i.call(e);!(o=(n=i.next()).done)&&(l.push(n.value),!t||l.length!==t);o=!0);}catch(e){a=!0,r=e}finally{try{o||null==i.return||i.return()}finally{if(a)throw r}}return l}}(e,t)||function(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)}}(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 N(e){return e&&"u">typeof Symbol&&e.constructor===Symbol?"symbol":typeof e}function L(e){var t="function"==typeof Map?new Map:void 0;return(L=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 T(e,arguments,R(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),A(n,e)})(e)}function B(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(B=function(){return!!e})()}function U(e,t){var n,r,i,l={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),a=Object.defineProperty;return a(o,"next",{value:u(0)}),a(o,"throw",{value:u(1)}),a(o,"return",{value:u(2)}),"function"==typeof Symbol&&a(o,Symbol.iterator,{value:function(){return this}}),o;function u(a){return function(u){var c=[a,u];if(n)throw TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(l=0)),l;)try{if(n=1,r&&(i=2&c[0]?r.return:c[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,c[1])).done)return i;switch(r=0,i&&(c=[2&c[0],i.value]),c[0]){case 0:case 1:i=c;break;case 4:return l.label++,{value:c[1],done:!1};case 5:l.label++,r=c[1],c=[0];continue;case 7:c=l.ops.pop(),l.trys.pop();continue;default:if(!(i=(i=l.trys).length>0&&i[i.length-1])&&(6===c[0]||2===c[0])){l=0;continue}if(3===c[0]&&(!i||c[1]>i[0]&&c[1]<i[3])){l.label=c[1];break}if(6===c[0]&&l.label<i[1]){l.label=i[1],i=c;break}if(i&&l.label<i[2]){l.label=i[2],l.ops.push(c);break}i[2]&&l.ops.pop(),l.trys.pop();continue}c=t.call(e,l)}catch(e){c=[6,e],r=0}finally{n=i=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}}var z=["application/pdf"],D=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],M=["text/plain","text/csv","text/html","text/css","text/javascript","application/json","application/xml","text/xml","text/yaml","application/x-yaml"],W=["application/vnd.openxmlformats-officedocument.wordprocessingml.document"],q=["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-excel"],V=["pdf"],$=["png","jpg","jpeg","gif","webp","svg","bmp"],H=["txt","csv","html","css","js","json","xml","log","md","yaml","yml","xaml"],X=["docx"],G=["xlsx","xls"],J=["application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-powerpoint"],Y=["pptx","ppt"],K={png:"png-200-200.png",jpg:"jpeg-200-200.png",jpeg:"jpeg-200-200.png",gif:"gif-200-200.png",webp:"png-200-200.png",bmp:"png-200-200.png",svg:"svg-200-200.png"},Q={"image/png":K.png,"image/jpeg":K.jpeg,"image/jpg":K.jpeg,"image/gif":K.gif,"image/webp":K.webp,"image/bmp":K.bmp,"image/svg+xml":K.svg};function Z(e){if(!e||"string"==typeof e)return e;var t,n,r,i,l,o,a,u,c,s,f,d,p,m,v,g,h,y,b,w,x,E,S,k,O=e.response;return O&&(void 0===O?"undefined":N(O))==="object"?I(_({},O,e),{id:null!=(t=e.id)?t:O.id,uid:null!=(n=e.uid)?n:O.uid,url:null!=(r=e.url)?r:O.url,preview:e.preview||O.preview,filename:null!=(i=e.filename)?i:O.filename,name:null!=(l=e.name)?l:O.name,title:null!=(o=e.title)?o:O.title,extname:null!=(a=e.extname)?a:O.extname,mimetype:null!=(u=e.mimetype)?u:O.mimetype,size:null!=(c=e.size)?c:O.size,path:null!=(s=e.path)?s:O.path,storageId:null!=(f=e.storageId)?f:O.storageId,storageType:null!=(d=null!=(p=null!=(m=e.storageType)?m:O.storageType)?p:null==(x=e.storage)?void 0:x.type)?d:null==(E=O.storage)?void 0:E.type,storageName:null!=(v=null!=(g=null!=(h=e.storageName)?h:O.storageName)?g:null==(S=e.storage)?void 0:S.name)?v:null==(k=O.storage)?void 0:k.name,storage:null!=(y=e.storage)?y:O.storage,collectionName:null!=(b=e.collectionName)?b:O.collectionName,lastModified:null!=(w=e.lastModified)?w:O.lastModified}):e}function ee(e){return null!==e&&(void 0===e?"undefined":N(e))==="object"}function et(e){if("number"==typeof e)return Number.isInteger(e)&&e>0?e:null;if("string"==typeof e){var t=e.trim();return/^\d+$/.test(t)?t:null}return null}function en(e){var t=ee(e)?e:{},n=ee(t.response)?t.response:{},r=Z(e),i=ee(r)?r:{},l=[i.attachmentId,i.id,n.attachmentId,n.id,t.attachmentId,t.id,i.uid,n.uid,t.uid],o=!0,a=!1,u=void 0;try{for(var c,s=l[Symbol.iterator]();!(o=(c=s.next()).done);o=!0){var f=c.value,d=et(f);if(null!=d)return d}}catch(e){a=!0,u=e}finally{try{o||null==s.return||s.return()}finally{if(a)throw u}}return null}var er=function(e){var t=Z(e),n=("string"==typeof t?t:(null==t?void 0:t.extname)||(null==t?void 0:t.name)||(null==t?void 0:t.filename)||(null==t?void 0:t.url)||"").split("?")[0].split("#")[0],r=n.lastIndexOf(".");return -1!==r?n.slice(r+1).toLowerCase().replace(/^\./,""):""},ei=function(e){var t=Z(e),n="string"==typeof t?t:(null==t?void 0:t.url)||(null==t?void 0:t.preview)||(null==t?void 0:t.path);return n?n.startsWith("https://")||n.startsWith("http://")?n:"".concat(location.origin,"/").concat(n.replace(/^\//,"")):""},el=function(e){if("string"==typeof e)return e;var t=Z(e);return t?[t.id,t.uid,t.url,t.preview,t.path,t.storageId,t.storageType,t.storageName,t.collectionName,t.lastModified,t.size].filter(function(e){return null!=e&&""!==e}).join(":"):""},eo=function(e){var t=Z(e);if((null==t?void 0:t.mimetype)&&z.includes(t.mimetype))return!0;var n=er(e);return!!n&&V.includes(n)},ea=function(e){var t=Z(e);if((null==t?void 0:t.mimetype)&&D.includes(t.mimetype)||(null==t?void 0:t.mimetype)&&(0,i.matchMimetype)(t,"image/*"))return!0;var n=er(e);return!!n&&$.includes(n)},eu=function(e){var t=Z(e);if((null==t?void 0:t.mimetype)&&M.includes(t.mimetype))return!0;var n=er(e);return!!n&&H.includes(n)},ec=function(e){var t=Z(e);if((null==t?void 0:t.mimetype)&&W.includes(t.mimetype))return!0;var n=er(e);return!!n&&X.includes(n)},es=function(e){var t=Z(e);if((null==t?void 0:t.mimetype)&&q.includes(t.mimetype))return!0;var n=er(e);return!!n&&G.includes(n)},ef=function(e){var t=Z(e);if((null==t?void 0:t.mimetype)&&J.includes(t.mimetype))return!0;var n=er(e);return!!n&&Y.includes(n)};function ed(e){return["waiting-verify","success","verified","accepted","rejected"].includes(e||"")}function ep(e){for(var t,n=e,r=0;r<5;r+=1){if(ee(t=n)&&("string"==typeof t.status||null!=et(t.attachmentId)||null!=et(t.id)))return n;if(!ee(n))break;n=n.data}return null}var em=function(e){var t=Z(e);return t?t.title&&t.extname?"".concat(t.title).concat(t.extname):t.filename||t.name||t.title||"download":"download"},ev=new Map;function eg(e){var t,n,r,i,l,o=Z(e);return{id:null==o?void 0:o.id,uid:null==o?void 0:o.uid,url:null==o?void 0:o.url,preview:null==o?void 0:o.preview,filename:(null==o?void 0:o.filename)||(null==o?void 0:o.name),name:(null==o?void 0:o.name)||(null==o?void 0:o.filename),title:null==o?void 0:o.title,extname:null==o?void 0:o.extname,mimetype:null==o?void 0:o.mimetype,size:null==o?void 0:o.size,path:null==o?void 0:o.path,storageId:null!=(t=null!=(n=null==o?void 0:o.storageId)?n:null==o?void 0:o.storage_id)?t:null==o||null==(r=o.storage)?void 0:r.id,storage_id:null==o?void 0:o.storage_id,storageType:(null==o?void 0:o.storageType)||(null==o||null==(i=o.storage)?void 0:i.type),storageName:(null==o?void 0:o.storageName)||(null==o||null==(l=o.storage)?void 0:l.name),storage:null==o?void 0:o.storage,collectionName:null==o?void 0:o.collectionName,lastModified:null==o?void 0:o.lastModified}}function eh(e){if(!e)return!1;try{var t=new URL(e,location.origin);if(t.origin!==location.origin)return!1;return["/api/filePreviewAuth:download","/api/extStorage:download","/api/skillHub:download","/api/worker-monitor","/api/carboneTemplates:download","/api/attachments:stream","/api/attachments:sftpStream"].some(function(e){return t.pathname===e||t.pathname.startsWith("".concat(e,"/"))||t.pathname.startsWith("".concat(e,":"))})}catch(e){return!1}}function ey(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"inline";return j(function(){var r,i,l;return U(this,function(o){if(!(r=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"inline",n=eg("string"==typeof e?{url:e}:e||{}),r=ei(e);if(r&&eh(r))return r;if(function(e,t){var n,r,i,l=eg("string"==typeof e?{url:e}:e||{}),o=l.collectionName||"attachments";return null!=(l.id||l.uid)&&("s3-private"===(i=(r=eg("string"==typeof e?{url:e}:e||{})).storageType||(null==(n=r.storage)?void 0:n.type))||"aws-s3-private"===i||"attachments"===o&&!t)}(e,r)){var i=eg("string"==typeof e?{url:e}:e||{}),l=i.id||i.uid;if(null==l)return"";var o=new URLSearchParams({filterByTk:String(l),mode:t,collection:i.collectionName||"attachments"});return"/api/attachments:stream?".concat(o.toString())}var a=n.id||n.uid;if(null!=a){var u,c=n.collectionName||"attachments",s=new URLSearchParams;s.set("id",String(a)),s.set("collection",c),r&&s.set("url",r);var f=n.storageId||n.storage_id||(null==(u=n.storage)?void 0:u.id);return null!=f&&""!==f&&s.set("storageId",String(f)),(n.filename||n.name)&&s.set("filename",n.filename||n.name),n.mimetype&&s.set("mimetype",n.mimetype),"/api/filePreviewAuth:download?".concat(s.toString())}return r||""}(e,n))||r.endsWith("?"))throw Error("No file URL");return i="".concat(t?"auth":"anon",":").concat(t||"",":").concat(el(e)||r),(l=ev.get(i))||(l=j(function(){var e,n;return U(this,function(i){switch(i.label){case 0:return e={},t&&(e.Authorization="Bearer ".concat(t)),[4,fetch(r,{method:"GET",headers:e,credentials:"include"})];case 1:if(!(n=i.sent()).ok)throw Error("Failed to fetch file: ".concat(n.status," ").concat(n.statusText));return[2,n.blob()]}})})().catch(function(e){throw ev.delete(i),e}),ev.set(i,l)),[2,l]})})()}function eb(e,t){return j(function(){var n,r,i,l;return U(this,function(o){switch(o.label){case 0:return[4,ey(e,t,"attachment")];case 1:return n=o.sent(),r=em(e),(i=document.createElement("a")).href=l=URL.createObjectURL(n),i.download=r,document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(function(){return URL.revokeObjectURL(l)},1e3),[2]}})})()}function ew(t,n){var r=F((0,e.useState)(null),2),i=r[0],l=r[1],o=F((0,e.useState)(!0),2),a=o[0],u=o[1],c=F((0,e.useState)(null),2),s=c[0],f=c[1],d=(0,e.useRef)(null),p=(0,e.useRef)(t);p.current=t;var m=el(t);return(0,e.useEffect)(function(){var e=!1,t=p.current;if(!(ei(t)||"string"!=typeof t&&((null==t?void 0:t.id)||(null==t?void 0:t.uid)))){u(!1),f("No file URL");return}return u(!0),f(null),ey(t,n).then(function(t){if(!e){var n=URL.createObjectURL(t);d.current=n,l(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)}},[m,n]),{blobUrl:i,loading:a,error:s}}function ex(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 eE(e){var n=e.message;return t().createElement("div",{style:{padding:20,textAlign:"center",color:"#ff4d4f"}},n)}function eS(e){var i=e.file,l=e.title,o=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:l},l),function(){if(!u||!o)return null;switch(o){case"pending-ocr":return t().createElement(r.Tag,{color:"processing",icon:t().createElement(n.SyncOutlined,{spin:!0})},c("OCR Pending"));case"waiting-verify":case"success":return t().createElement(r.Tag,{color:"warning",icon:t().createElement(n.ClockCircleOutlined,null)},c("Waiting Verify"));case"verified":case"accepted":return t().createElement(r.Tag,{color:"success",icon:t().createElement(n.CheckCircleOutlined,null)},c("OCR Verified"));case"rejected":return t().createElement(r.Tag,{color:"error"},c("OCR Rejected"));case"failed":return t().createElement(r.Tag,{color:"error"},c("OCR Failed"));default:return t().createElement(r.Tag,{color:"default"},c("No OCR"))}}()),t().createElement(O,{file:i}))}function ek(e){var n,r=e.file,l=(0,i.useAPIClient)(),o=a(),u=ew(r,(null==(n=l.auth)?void 0:n.token)||""),c=u.blobUrl,s=u.loading,f=u.error;return s?t().createElement(ex,{message:o("Loading preview...")}):f||!c?t().createElement(eE,{message:o("Failed to load file preview")}):t().createElement("iframe",{src:c,width:"100%",height:"100%",style:{border:"none"}})}function eO(e){var n,r=e.file,l=(0,i.useAPIClient)(),o=a(),u=ew(r,(null==(n=l.auth)?void 0:n.token)||""),c=u.blobUrl,s=u.loading,f=u.error;return s?t().createElement(ex,{message:o("Loading preview...")}):f||!c?t().createElement(eE,{message:o("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 eC(n){var r,l,o,u,c,s,f,d,p,m,v,g,h=n.file,y=(0,i.useAPIClient)(),b=a(),w=(null==(g=y.auth)?void 0:g.token)||"",x=(l=(r=F((0,e.useState)(null),2))[0],o=r[1],c=(u=F((0,e.useState)(!0),2))[0],s=u[1],d=(f=F((0,e.useState)(null),2))[0],p=f[1],(m=(0,e.useRef)(h)).current=h,v=el(h),(0,e.useEffect)(function(){var e=!1,t=m.current;if(!(ei(t)||"string"!=typeof t&&((null==t?void 0:t.id)||(null==t?void 0:t.uid)))){s(!1),p("No file URL");return}return s(!0),p(null),ey(t,w).then(function(e){return e.text()}).then(function(t){e||(o(t),s(!1))}).catch(function(t){e||(p(t.message||"Failed to load"),s(!1))}),function(){e=!0}},[v,w]),{text:l,loading:c,error:d}),E=x.text,S=x.loading,k=x.error;return S?t().createElement(ex,{message:b("Loading preview...")}):k||null===E?t().createElement(eE,{message:b("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"}},E)}function eP(n){var r,l=n.file,o=(0,i.useAPIClient)(),u=a(),c=(null==(r=o.auth)?void 0:r.token)||"",s=(0,e.useRef)(null),d=(0,e.useRef)(l);d.current=l;var p=el(l),m=F((0,e.useState)(!0),2),v=m[0],g=m[1],h=F((0,e.useState)(null),2),y=h[0],b=h[1];return(0,e.useEffect)(function(){var e=!1,t=d.current;if(!(ei(t)||"string"!=typeof t&&((null==t?void 0:t.id)||(null==t?void 0:t.uid)))||!s.current){g(!1),b("No file URL");return}return g(!0),b(null),j(function(){var n,r,i;return U(this,function(l){switch(l.label){case 0:return l.trys.push([0,4,,5]),[4,ey(t,c)];case 1:if(n=l.sent(),e)return[2];return[4,f.e("713").then(f.bind(f,440))];case 2:if(r=l.sent(),e||!s.current)return[2];return s.current.innerHTML="",[4,r.renderAsync(n,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 l.sent(),g(!1),[3,5];case 4:if(i=l.sent(),e)return[2];return b(i.message||"Failed to render DOCX"),g(!1),[3,5];case 5:return[2]}})})(),function(){e=!0}},[p,c]),t().createElement("div",{style:{width:"100%",height:"100%",position:"relative"}},v&&t().createElement(ex,{message:u("Loading preview...")}),y&&t().createElement(eE,{message:u("Failed to load file preview")}),t().createElement("div",{ref:s,style:{width:"100%",height:"100%",overflow:"auto",display:v||y?"none":"block"}}))}function ej(n){var r,l=n.file,o=(0,i.useAPIClient)(),u=a(),c=(null==(r=o.auth)?void 0:r.token)||"",s=(0,e.useRef)(null),d=(0,e.useRef)(l);d.current=l;var p=el(l),m=F((0,e.useState)(!0),2),v=m[0],g=m[1],h=F((0,e.useState)(null),2),y=h[0],b=h[1],w=F((0,e.useState)([]),2),x=w[0],E=w[1],S=F((0,e.useState)(""),2),k=S[0],O=S[1],C=F((0,e.useState)({}),2),P=C[0],T=C[1];return(0,e.useEffect)(function(){var e=!1,t=d.current;if(!(ei(t)||"string"!=typeof t&&((null==t?void 0:t.id)||(null==t?void 0:t.uid)))){g(!1),b("No file URL");return}return g(!0),b(null),j(function(){var n,r,i,l,o,a,u,s,d,p,m,v,h,y;return U(this,function(w){switch(w.label){case 0:return w.trys.push([0,4,,5]),[4,ey(t,c)];case 1:if(n=w.sent(),e)return[2];return[4,f.e("892").then(f.bind(f,959))];case 2:if(r=w.sent(),e)return[2];return[4,n.arrayBuffer()];case 3:if(i=w.sent(),e)return[2];o=(l=r.read(i,{type:"array"})).SheetNames,a={},u=!0,s=!1,d=void 0;try{for(p=o[Symbol.iterator]();!(u=(m=p.next()).done);u=!0)v=m.value,h=l.Sheets[v],a[v]=r.utils.sheet_to_html(h,{id:"xlsx-preview-table"})}catch(e){s=!0,d=e}finally{try{u||null==p.return||p.return()}finally{if(s)throw d}}if(e)return[2];return E(o),O(o[0]||""),T(a),g(!1),[3,5];case 4:if(y=w.sent(),e)return[2];return b(y.message||"Failed to render XLSX"),g(!1),[3,5];case 5:return[2]}})})(),function(){e=!0}},[p,c]),t().createElement("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column"}},v&&t().createElement(ex,{message:u("Loading preview...")}),y&&t().createElement(eE,{message:u("Failed to load file preview")}),!v&&!y&&t().createElement(t().Fragment,null,x.length>1&&t().createElement("div",{style:{display:"flex",gap:0,borderBottom:"1px solid #e8e8e8",background:"#fafafa",padding:"0 8px",flexShrink:0,overflowX:"auto"}},x.map(function(e){return t().createElement("button",{key:e,onClick:function(){return O(e)},style:{padding:"8px 16px",border:"none",borderBottom:k===e?"2px solid #1890ff":"2px solid transparent",background:k===e?"#fff":"transparent",color:k===e?"#1890ff":"#666",fontWeight:k===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:P[k]||""}}),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 eT(n){var r,l=n.file,o=(0,i.useAPIClient)(),u=a(),c=(null==(r=o.auth)?void 0:r.token)||"",s=F((0,e.useState)(!0),2),d=s[0],p=s[1],m=F((0,e.useState)(null),2),v=m[0],g=m[1],h=F((0,e.useState)(null),2),y=h[0],b=h[1],w=F((0,e.useState)(null),2),x=w[0],E=w[1],S=(0,e.useRef)(l);S.current=l;var k=el(l);return(0,e.useEffect)(function(){var e=!1,t=S.current;if(!(ei(t)||"string"!=typeof t&&((null==t?void 0:t.id)||(null==t?void 0:t.uid)))){p(!1),g("No file URL");return}return p(!0),g(null),j(function(){var n,r,i,l;return U(this,function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,Promise.all([ey(t,c),f.e("828").then(f.bind(f,559))])];case 1:if(r=(n=F.apply(void 0,[o.sent(),2]))[0],i=n[1],e)return[2];return b(r),E(function(){return i.PptxPreview}),p(!1),[3,3];case 2:if(l=o.sent(),e)return[2];return g(l.message||"Failed to render PPTX"),p(!1),[3,3];case 3:return[2]}})})(),function(){e=!0}},[k,c]),t().createElement("div",{style:{width:"100%",height:"100%",position:"relative"}},d&&t().createElement(ex,{message:u("Loading preview...")}),v&&t().createElement(eE,{message:u("Failed to load file preview")}),!d&&!v&&x&&t().createElement("div",{style:{width:"100%",height:"100%",overflow:"auto"}},t().createElement(x,{file:y})))}var eR=function(l){return function(o){var u=o.open,c=o.onOpenChange,s=o.onClose,f=o.file,d=o.index,p=o.list,m=o.onSwitchIndex;o.onDownload;var v=(0,i.useAPIClient)(),g=a(),h=F((0,e.useState)("visual"),2),y=h[0],b=h[1],w=(0,e.useCallback)(function(e){return j(function(){var t,n,i;return U(this,function(l){switch(l.label){case 0:if(!(n=e||f))return[2];i=(null==(t=v.auth)?void 0:t.token)||"",l.label=1;case 1:return l.trys.push([1,3,,4]),[4,eb(n,i)];case 2:return l.sent(),[3,4];case 3:return l.sent(),r.message.error(g("Failed to download file")),[3,4];case 4:return[2]}})})()},[f,v,g]);if("boolean"!=typeof u)return t().createElement(l,I(_({},o),{onDownload:w}));var x=em(f),E="number"==typeof d&&!!m&&d>0,S="number"==typeof d&&!!m&&d<p.length-1;return t().createElement(r.Modal,{open:u,title:t().createElement(eS,{file:f,title:x}),onCancel:function(){null==c||c(!1),null==s||s(),b("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 b(function(e){return"visual"===e?"raw":"visual"})}},"visual"===y?g("View Raw Parsed Text"):g("View Visual Preview"))),t().createElement(r.Space,{size:14,style:{fontSize:"20px"}},t().createElement(n.LeftOutlined,{style:{cursor:E?"pointer":"not-allowed"},onClick:function(){return E&&(null==m?void 0:m(d-1))}}),t().createElement(n.RightOutlined,{style:{cursor:S?"pointer":"not-allowed"},onClick:function(){return S&&(null==m?void 0:m(d+1))}}),t().createElement(n.DownloadOutlined,{onClick:function(){return w(f)}}))),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"===y?t().createElement(e_,{file:f}):t().createElement(l,I(_({},o),{onDownload:w}))))}};function e_(l){var o=l.file,u=(0,i.useAPIClient)(),c=a(),s=F((0,e.useState)(""),2),f=s[0],d=s[1],p=F((0,e.useState)(!0),2),m=p[0],v=p[1],g=F((0,e.useState)(null),2),h=g[0],y=g[1],b=(0,i.useComponent)("MarkdownVditor"),w=(0,i.useComponent)("Markdown.Void");return((0,e.useEffect)(function(){var e=!1;return j(function(){var t,n,r,i,l,a,c,s,f,p;return U(this,function(m){switch(m.label){case 0:v(!0),y(null),m.label=1;case 1:return m.trys.push([1,4,,5]),[4,ey(o,(null==(t=u.auth)?void 0:t.token)||"")];case 2:if(i=m.sent(),e)return[2];return(l=new FormData).append("file",i,em(o)),l.append("attachment",JSON.stringify(eg(o))),[4,u.request({url:"filePreviewAuth:getContent",method:"post",data:l,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 y(p.message||"Failed to fetch raw text"),v(!1),[3,5];case 5:return[2]}})})(),function(){e=!0}},[o,u]),m)?t().createElement(r.Spin,{size:"large",tip:c("Extracting raw text..."),style:{marginTop:"40px"}}):h?t().createElement(r.Alert,{type:"error",message:h,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 eI(l){var o=l.index,u=l.list,c=l.onSwitchIndex,s=a(),f=(0,i.useAPIClient)(),d=u[o],p=F((0,e.useState)(!1),2),m=p[0],v=p[1],g=F((0,e.useState)("visual"),2),h=g[0],y=g[1],b=F((0,e.useState)("preview"),2),w=b[0],x=b[1],E=F((0,e.useState)("no-ocr"),2),S=E[0],k=E[1],O=F((0,e.useState)(null),2),C=O[0],P=O[1],T=F((0,e.useState)(null),2),R=T[0],A=T[1],N=(0,e.useMemo)(function(){return en(d)},[d]),L=(0,e.useMemo)(function(){return!!d&&!!N&&(eo(d)||ea(d))},[d,N]),B=(0,i.useComponent)("OcrVerifyBlock"),z=(0,e.useCallback)(function(e){e&&(P(e.id||null),k(e.status||"no-ocr"),A(e.error||null))},[]),D=(0,e.useCallback)(function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.updateState,n=void 0===t||t;return j(function(){var e;return U(this,function(t){switch(t.label){case 0:if(!N)return[2,null];return[4,f.request({url:"filePreviewAuth:getOcrStatus",method:"post",data:{attachmentId:N}})];case 1:return(e=ep(t.sent()))&&n&&z(e),[2,e]}})})()},[f,z,N]);(0,e.useEffect)(function(){if(N){var e=!1;return P(null),k("no-ocr"),A(null),D().then(function(){if(e)return}).catch(console.error),function(){e=!0}}},[N,D]),(0,e.useEffect)(function(){if("pending-ocr"===S&&N){var e=null,t=!1,n=0,i=function(){return j(function(){var l,o;return U(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),[4,D({updateState:!1})];case 1:if(l=a.sent(),t)return[2];if(l){if("pending-ocr"===(o=l.status||"no-ocr"))return z(l),e=setTimeout(i,3e3),[2];if(ed(o))return z(l),x("ocr"),r.message.success(s("OCR processing completed!")),[2];if("failed"===o)return z(l),r.message.error(l.error||s("OCR processing failed")),[2];if("no-ocr"===o&&n<3)return n+=1,e=setTimeout(i,3e3),[2];z(l)}else n<3?(n+=1,e=setTimeout(i,3e3)):(P(null),k("no-ocr"),A(null));return[3,3];case 2:return console.error("Polling error",a.sent()),e=setTimeout(i,3e3),[3,3];case 3:return[2]}})})()};return e=setTimeout(i,3e3),function(){t=!0,e&&clearTimeout(e)}}},[z,S,N,D,s]);var M=function(){return j(function(){var e,t;return U(this,function(n){switch(n.label){case 0:if(!N)return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),k("pending-ocr"),[4,f.request({url:"filePreviewAuth:runOcr",method:"post",data:{attachmentId:N}})];case 2:return(e=ep(n.sent()))&&z(I(_({},e),{status:e.status||"pending-ocr"})),r.message.info(s("OCR process started in the background.")),[3,4];case 3:return t=n.sent(),r.message.error((null==t?void 0:t.message)||s("Failed to start OCR process.")),k("no-ocr"),[3,4];case 4:return[2]}})})()},W=(0,e.useCallback)(function(e){return j(function(){var t,n,i,l;return U(this,function(o){switch(o.label){case 0:null==e||null==(t=e.preventDefault)||t.call(e),null==e||null==(n=e.stopPropagation)||n.call(e),l=(null==(i=f.auth)?void 0:i.token)||"",v(!0),o.label=1;case 1:return o.trys.push([1,3,4,5]),[4,eb(d,l)];case 2:return o.sent(),[3,5];case 3:return o.sent(),r.message.error(s("Failed to download file")),[3,5];case 4:return v(!1),[7];case 5:return[2]}})})()},[d,f,s]),q=(0,e.useCallback)(function(){c(null),y("visual"),x("preview")},[c]),V=(0,e.useMemo)(function(){return eo(d)?ek:ea(d)?eO:eu(d)?eC:ec(d)?eP:es(d)?ej:ef(d)?eT:null},[d]),$=null!=V||"raw"===h,H=[{key:"preview",label:t().createElement("span",null,t().createElement(n.EyeOutlined,null)," ",s("Visual Preview")),children:t().createElement("div",{style:{height:"70vh",width:"100%",overflow:"auto",background:"#f5f5f5",display:"flex",justifyContent:"center",alignItems:"center"}},V?t().createElement(V,{file:d}):null)},{key:"ocr",label:t().createElement("span",null,t().createElement(n.ScanOutlined,null)," ",s("OCR & Verify")),children:t().createElement("div",{style:{height:"70vh",width:"100%",display:"flex",flexDirection:"column"}},"no-ocr"===S&&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"}},s("Word-level Song ngữ (English & Vietnamese) OCR")),t().createElement("p",{style:{color:"#8c8c8c",maxWidth:"480px",textAlign:"center",marginBottom:"24px"}},s("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:M},s("Run Tesseract OCR"))),"pending-ocr"===S&&t().createElement("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100%",padding:"40px"}},t().createElement(r.Spin,{size:"large",tip:s("Analyzing layout structure and running song ngữ OCR...")}),t().createElement("p",{style:{color:"#8c8c8c",marginTop:"20px",fontSize:"13px",textAlign:"center"}},s("Extracting word-level coordinates via Tesseract-OCR. This will automatically refresh when complete."))),"failed"===S&&t().createElement("div",{style:{padding:"40px"}},t().createElement(r.Alert,{type:"error",showIcon:!0,message:s("OCR processing failed"),description:R||s("Please try running OCR again."),style:{marginBottom:24}}),t().createElement(r.Button,{type:"primary",icon:t().createElement(n.ThunderboltOutlined,null),onClick:M},s("Run Tesseract OCR"))),ed(S)&&t().createElement("div",{style:{flex:1,height:"100%",overflow:"hidden"}},B&&C?t().createElement(B,{collection:"attachmentOcrResults",recordId:C,pdfField:"attachment",jsonField:"data",statusField:"status"}):B?t().createElement("div",{style:{padding:"20px"}},t().createElement(r.Alert,{type:"error",message:s("OCR result record not found"),description:s("Please try running OCR again."),showIcon:!0})):t().createElement("div",{style:{padding:"20px"}},t().createElement(r.Alert,{type:"error",message:s("Plugin OCR Verify Block is not enabled"),description:s("Please enable the plugin-ocr-verify-block plugin to display the verify splitter layout."),showIcon:!0}))))}];return t().createElement(r.Modal,{open:null!=o,title:t().createElement(eS,{file:d,title:(null==d?void 0:d.title)||(null==d?void 0:d.filename)||(null==d?void 0:d.name)||"File",ocrStatus:S,isOcrSupported:L}),onCancel:q,footer:t().createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%"}},t().createElement("div",{key:"left-actions"},!L&&t().createElement(r.Button,{onClick:function(){return y(function(e){return"visual"===e?"raw":"visual"})}},"visual"===h?s("View Raw Parsed Text"):s("View Visual Preview"))),t().createElement(r.Space,null,t().createElement(r.Button,{key:"download",onClick:W,loading:m},s("Download")),t().createElement(r.Button,{key:"close",onClick:q},s("Close")))),width:$?"90%":520,centered:!0},L?t().createElement(r.Tabs,{activeKey:w,onChange:function(e){return x(e)},items:H,style:{width:"100%",height:"100%"}}):t().createElement("div",{style:{maxWidth:"100%",maxHeight:$?"calc(100vh - 256px)":"auto",height:$?"70vh":"auto",width:"100%",background:"white",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",overflowY:"auto"}},"raw"===h?t().createElement(e_,{file:d}):V?t().createElement(V,{file:d}):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 eA(n){var l=n.file,o=(0,i.useAPIClient)(),u=a(),c=(0,e.useCallback)(function(){return j(function(){var e,t;return U(this,function(n){switch(n.label){case 0:t=(null==(e=o.auth)?void 0:e.token)||"",n.label=1;case 1:return n.trys.push([1,3,,4]),[4,eb(l,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]}})})()},[l,o,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 eF=function(e){var o;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=R(e),function(e,t){if(t&&("object"===N(t)||"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(e,t||[],R(this).constructor):e.apply(this,t))}return a.prototype=Object.create(e&&e.prototype,{constructor:{value:a,writable:!0,configurable:!0}}),e&&A(a,e),o=[{key:"load",value:function(){return j(function(){return U(this,function(e){return this.patchUploadPreviewBase64Fallback(),!function(e){try{i=e.pm.get("ai")}catch(e){return}var i,l,o=null==i?void 0:i.aiManager;if(null==o?void 0:o.registerWorkContext)try{(null==(l=o.getWorkContext)?void 0:l.call(o,w))||o.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){}}(this.app),i.attachmentFileTypes.add({match:function(){return!0},Previewer:eI}),l.filePreviewTypes.add({match:function(){return!0},Previewer:eR(eA)}),l.filePreviewTypes.add({match:eo,Previewer:eR(ek)}),l.filePreviewTypes.add({match:ea,getThumbnailURL:function(e){var t,n,r,i,l,o,a,u;return(u=[null==(a=Z(e))?void 0:a.preview,null==a?void 0:a.url].find(function(e){return"string"==typeof e&&e}))&&!eh(u)?u:(n=er(t=Z(a)),r="string"==typeof(null==t?void 0:t.mimetype)?t.mimetype.toLowerCase():"",i=K[n]||Q[r]||"unknown-200-200.png",l="file-placeholder/".concat(i),o="u"<typeof window?"/":window.__nocobase_dev_public_path__||window.__nocobase_public_path__||"/","".concat(o.replace(/\/?$/,"/")).concat(l.replace(/^\//,"")))},Previewer:eR(eO)}),l.filePreviewTypes.add({match:eu,Previewer:eR(eC)}),l.filePreviewTypes.add({match:ec,Previewer:eR(eP)}),l.filePreviewTypes.add({match:es,Previewer:eR(ej)}),l.filePreviewTypes.add({match:ef,Previewer:eR(eT)}),[2]})}).call(this)}},{key:"patchUploadPreviewBase64Fallback",value:function(){if(!("u"<typeof window)){var e,t=null==(e=window.FileReader)?void 0:e.prototype;if(t&&!t.__filePreviewAuthBase64FallbackPatched){var n=t.readAsDataURL;"function"==typeof n&&(Object.defineProperty(t,"__filePreviewAuthBase64FallbackPatched",{value:!0,configurable:!0}),t.readAsDataURL=function(e){var t=this;if(null!=e)return n.call(this,e);setTimeout(function(){var e,n;try{Object.defineProperty(t,"result",{value:"",configurable:!0})}catch(e){}null==(e=t.onload)||e.call(t,new ProgressEvent("load")),null==(n=t.onloadend)||n.call(t,new ProgressEvent("loadend"))},0)})}}}}],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,o),a}(L(i.Plugin)),eN=eF}(),h}()});
10
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("antd"),require("@nocobase/client"),require("@ant-design/icons"),require("@nocobase/plugin-file-manager/client"),require("@nocobase/plugin-ai/client")):"function"==typeof define&&define.amd?define("plugin-file-preview-auth",["react","antd","@nocobase/client","@ant-design/icons","@nocobase/plugin-file-manager/client","@nocobase/plugin-ai/client"],t):"object"==typeof exports?exports["plugin-file-preview-auth"]=t(require("react"),require("antd"),require("@nocobase/client"),require("@ant-design/icons"),require("@nocobase/plugin-file-manager/client"),require("@nocobase/plugin-ai/client")):e["plugin-file-preview-auth"]=t(e.react,e.antd,e["@nocobase/client"],e["@ant-design/icons"],e["@nocobase/plugin-file-manager/client"],e["@nocobase/plugin-ai/client"])}(self,function(e,t,n,r,i,l){return function(){"use strict";var o,a,u,c={375:function(e){e.exports=r},342:function(e){e.exports=n},75:function(e){e.exports=l},609:function(e){e.exports=i},59:function(e){e.exports=t},155:function(t){t.exports=e}},s={};function f(e){var t=s[e];if(void 0!==t)return t.exports;var n=s[e]={exports:{}};return c[e](n,n.exports,f),n.exports}f.m=c,f.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(t,{a:t}),t},f.d=function(e,t){for(var n in t)f.o(t,n)&&!f.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},f.f={},f.e=function(e){return Promise.all(Object.keys(f.f).reduce(function(t,n){return f.f[n](e,t),t},[]))},f.u=function(e){return""+e+"."+({713:"79a55458f5b67f39",823:"8b0ab22c181d4523",828:"ae8e47a2e7a3bc9e",892:"a568eb42fd6f0047"})[e]+".js"},f.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}}(),f.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},d={},f.l=function(e,t,n,r){if(d[e])return void d[e].push(t);if(void 0!==n)for(var i,l,o=document.getElementsByTagName("script"),a=0;a<o.length;a++){var u=o[a];if(u.getAttribute("src")==e||u.getAttribute("data-rspack")=="plugin-file-preview-auth:"+n){i=u;break}}i||(l=!0,(i=document.createElement("script")).timeout=120,f.nc&&i.setAttribute("nonce",f.nc),i.setAttribute("data-rspack","plugin-file-preview-auth:"+n),i.src=e),d[e]=[t];var c=function(t,n){i.onerror=i.onload=null,clearTimeout(s);var r=d[e];if(delete d[e],i.parentNode&&i.parentNode.removeChild(i),r&&r.forEach(function(e){return e(n)}),t)return t(n)},s=setTimeout(c.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=c.bind(null,i.onerror),i.onload=c.bind(null,i.onload),l&&document.head.appendChild(i)},f.r=function(e){"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},f.g.importScripts&&(p=f.g.location+"");var d,p,m=f.g.document;if(!p&&m&&(m.currentScript&&"SCRIPT"===m.currentScript.tagName.toUpperCase()&&(p=m.currentScript.src),!p)){var v=m.getElementsByTagName("script");if(v.length)for(var g=v.length-1;g>-1&&(!p||!/^http(s?):/.test(p));)p=v[g--].src}if(!p)throw Error("Automatic publicPath is not supported in this browser");f.p=p.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),o={889:0},f.f.j=function(e,t){var n=f.o(o,e)?o[e]:void 0;if(0!==n)if(n)t.push(n[2]);else{var r=new Promise(function(t,r){n=o[e]=[t,r]});t.push(n[2]=r);var i=f.p+f.u(e),l=Error();f.l(i,function(t){if(f.o(o,e)&&(0!==(n=o[e])&&(o[e]=void 0),n)){var r=t&&("load"===t.type?"missing":t.type),i=t&&t.target&&t.target.src;l.message="Loading chunk "+e+" failed.\n("+r+": "+i+")",l.name="ChunkLoadError",l.type=r,l.request=i,n[1](l)}},"chunk-"+e,e)}},a=function(e,t){var n,r,i=t[0],l=t[1],a=t[2],u=0;if(i.some(function(e){return 0!==o[e]})){for(n in l)f.o(l,n)&&(f.m[n]=l[n]);a&&a(f)}for(e&&e(t);u<i.length;u++)r=i[u],f.o(o,r)&&o[r]&&o[r][0](),o[r]=0},(u=self.webpackChunkplugin_file_preview_auth=self.webpackChunkplugin_file_preview_auth||[]).forEach(a.bind(null,0)),u.push=a.bind(null,u.push.bind(u));var h={};return!function(){var e="",t="u">typeof document?document.currentScript:null;if(t&&t.src&&(e=t.src.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/")),!e){var n=window.__webpack_public_path__||"";n&&("/"!==n.charAt(n.length-1)&&(n+="/"),e=n+"static/plugins/plugin-file-preview-auth/dist/client/")}if(!e){var r=window.__nocobase_modern_client_prefix__||"v",i="/"+(r=String(r).replace(/^\/+|\/+$/g,"")||"v")+"/";if(!(e=window.__nocobase_public_path__||"")&&window.location&&window.location.pathname){var l=window.location.pathname||"/",o=l.indexOf(i);e=o>=0?l.slice(0,o+1):"/"}e&&(e=e.replace(RegExp("/"+r+"/?$"),"/")),e||(e="/"),"/"!==e.charAt(e.length-1)&&(e+="/"),e+="static/plugins/plugin-file-preview-auth/dist/client/"}f.p=e}(),!function(){f.r(h),f.d(h,{isOcrCompleteStatus:function(){return ep},normalizeOcrAttachmentId:function(){return et},default:function(){return eL},PluginFilePreviewAuthClient:function(){return eN},extractOcrStatusRecord:function(){return em},getOcrAttachmentId:function(){return en},isOcrCapableCollection:function(){return er}});var e=f(155),t=f.n(e),n=f(375),r=f(59),i=f(342),l=f(609),o=JSON.parse('{"UU":"plugin-file-preview-auth"}');function a(){var e=(0,i.useApp)();return function(t){return e.i18n.t(t,{ns:[o.UU,"client"]})}}var u=f(75);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,l,o){try{var a=e[l](o),u=a.value}catch(e){n(e);return}a.done?t(u):Promise.resolve(u).then(r,i)}function d(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function p(e){return(p=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function m(e,t){return(m=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function v(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,i=null==e?null:"u">typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var l=[],o=!0,a=!1;try{for(i=i.call(e);!(o=(n=i.next()).done)&&(l.push(n.value),!t||l.length!==t);o=!0);}catch(e){a=!0,r=e}finally{try{o||null==i.return||i.return()}finally{if(a)throw r}}return l}}(e,t)||y(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function g(e){return function(e){if(Array.isArray(e))return c(e)}(e)||function(e){if("u">typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||y(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 y(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=p(n),(t=function(e,t){var n;if(t&&("object"==((n=t)&&"u">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||[],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&&m(r,e),n=[{key:"getDerivedStateFromError",value:function(){return{hasError:!0}}}],t=[{key:"render",value:function(){return this.state.hasError?null:this.props.children}}],d(r.prototype,t),n&&d(r,n),r}(t().Component),O=function(i){var l=i.file,o=a(),c=(0,u.useAIConfigRepository)(),f=(0,u.useChatBoxActions)().triggerTask,d=v((0,e.useState)([]),2),p=d[0],m=d[1],h=v((0,e.useState)(!1),2),y=h[0],b=h[1],S=v((0,e.useState)(!1),2),O=S[0],k=S[1];(0,e.useEffect)(function(){var e=!1;if(null==c?void 0:c.getAIEmployees){var t=c.aiEmployees||[];return t.length?void m(g(t)):(b(!0),c.getAIEmployees().then(function(t){e||(m(g(t||[])),b(!1))}).catch(function(){e||(m([]),b(!1))}),function(){e=!0})}},[c]);var C=(0,e.useMemo)(function(){var e=function(){try{return window.localStorage.getItem(x)||""}catch(e){return""}}();return e?g(p).sort(function(t,n){return t.username===e?-1:+(n.username===e)}):p},[p]),P=(0,e.useCallback)(function(e){var t;return(t=function(){return function(e,t){var n,r,i,l={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),a=Object.defineProperty;return a(o,"next",{value:u(0)}),a(o,"throw",{value:u(1)}),a(o,"return",{value:u(2)}),"function"==typeof Symbol&&a(o,Symbol.iterator,{value:function(){return this}}),o;function u(a){return function(u){var c=[a,u];if(n)throw TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(l=0)),l;)try{if(n=1,r&&(i=2&c[0]?r.return:c[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,c[1])).done)return i;switch(r=0,i&&(c=[2&c[0],i.value]),c[0]){case 0:case 1:i=c;break;case 4:return l.label++,{value:c[1],done:!1};case 5:l.label++,r=c[1],c=[0];continue;case 7:c=l.ops.pop(),l.trys.pop();continue;default:if(!(i=(i=l.trys).length>0&&i[i.length-1])&&(6===c[0]||2===c[0])){l=0;continue}if(3===c[0]&&(!i||c[1]>i[0]&&c[1]<i[3])){l.label=c[1];break}if(6===c[0]&&l.label<i[1]){l.label=i[1],i=c;break}if(i&&l.label<i[2]){l.label=i[2],l.ops.push(c);break}i[2]&&l.ops.pop(),l.trys.pop();continue}c=t.call(e,l)}catch(e){c=[6,e],r=0}finally{n=i=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}}(this,function(t){switch(t.label){case 0:if(!e||!l)return[2];k(!0),t.label=1;case 1:t.trys.push([1,3,4,5]);var n,i,a,u,c,s,d,p,m,v,g=e.username;try{window.localStorage.setItem(x,g)}catch(e){}return[4,f({aiEmployee:e,tasks:[{title:E(l),message:{user:o("Please help me analyze the file currently open in preview."),workContext:[{type:w,uid:(c=null!=(n=null!=(i=null!=(a=null!=(u=null==l?void 0:l.id)?u:null==l?void 0:l.uid)?a:null==l?void 0:l.url)?i:null==l?void 0:l.path)?n:E(l),"file-preview:".concat(String(c))),title:E(l),content:{source:"plugin-file-preview-auth",file:{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!=(s=null!=(d=null==l?void 0:l.storageId)?d:null==l?void 0:l.storage_id)?s:null==l||null==(p=l.storage)?void 0:p.id,storage_id:null==l?void 0:l.storage_id,storageType:(null==l?void 0:l.storageType)||(null==l||null==(m=l.storage)?void 0:m.type),storageName:(null==l?void 0:l.storageName)||(null==l||null==(v=l.storage)?void 0:v.name),storage:null==l?void 0:l.storage,collectionName:null==l?void 0:l.collectionName}}}]},autoSend:!1}]})];case 2:return t.sent(),[3,5];case 3:return t.sent(),r.message.error(o("Failed to open AI chat")),[3,5];case 4:return k(!1),[7];case 5:return[2]}})},function(){var e=this,n=arguments;return new Promise(function(r,i){var l=t.apply(e,n);function o(e){s(l,r,i,o,a,"next",e)}function a(e){s(l,r,i,o,a,"throw",e)}o(void 0)})})()},[l,o,f]);return y||C.length?t().createElement(r.Tooltip,{title:o("Ask AI")},t().createElement(r.Button,{type:"text",size:"small",icon:t().createElement(n.RobotOutlined,null),loading:O||y,disabled:!C.length,onClick:function(e){e.stopPropagation(),P(C[0])}},o("Ask AI"))):null},k=function(e){var n=e.file;return t().createElement(S,null,t().createElement(O,{file:n}))};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 P(e,t,n,r,i,l,o){try{var a=e[l](o),u=a.value}catch(e){n(e);return}a.done?t(u):Promise.resolve(u).then(r,i)}function j(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var l=e.apply(t,n);function o(e){P(l,r,i,o,a,"next",e)}function a(e){P(l,r,i,o,a,"throw",e)}o(void 0)})}}function T(e,t,n){return(T=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&&A(i,n.prototype),i}).apply(null,arguments)}function _(e){return(_=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function R(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 I(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):(function(e){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t.push.apply(t,n)}return t})(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}function A(e,t){return(A=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function F(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,i=null==e?null:"u">typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var l=[],o=!0,a=!1;try{for(i=i.call(e);!(o=(n=i.next()).done)&&(l.push(n.value),!t||l.length!==t);o=!0);}catch(e){a=!0,r=e}finally{try{o||null==i.return||i.return()}finally{if(a)throw r}}return l}}(e,t)||function(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)}}(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 N(e){return e&&"u">typeof Symbol&&e.constructor===Symbol?"symbol":typeof e}function L(e){var t="function"==typeof Map?new Map:void 0;return(L=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 T(e,arguments,_(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),A(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,l={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),a=Object.defineProperty;return a(o,"next",{value:u(0)}),a(o,"throw",{value:u(1)}),a(o,"return",{value:u(2)}),"function"==typeof Symbol&&a(o,Symbol.iterator,{value:function(){return this}}),o;function u(a){return function(u){var c=[a,u];if(n)throw TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(l=0)),l;)try{if(n=1,r&&(i=2&c[0]?r.return:c[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,c[1])).done)return i;switch(r=0,i&&(c=[2&c[0],i.value]),c[0]){case 0:case 1:i=c;break;case 4:return l.label++,{value:c[1],done:!1};case 5:l.label++,r=c[1],c=[0];continue;case 7:c=l.ops.pop(),l.trys.pop();continue;default:if(!(i=(i=l.trys).length>0&&i[i.length-1])&&(6===c[0]||2===c[0])){l=0;continue}if(3===c[0]&&(!i||c[1]>i[0]&&c[1]<i[3])){l.label=c[1];break}if(6===c[0]&&l.label<i[1]){l.label=i[1],i=c;break}if(i&&l.label<i[2]){l.label=i[2],l.ops.push(c);break}i[2]&&l.ops.pop(),l.trys.pop();continue}c=t.call(e,l)}catch(e){c=[6,e],r=0}finally{n=i=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}}var z=["application/pdf"],M=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],D=["text/plain","text/csv","text/html","text/css","text/javascript","application/json","application/xml","text/xml","text/yaml","application/x-yaml"],W=["application/vnd.openxmlformats-officedocument.wordprocessingml.document"],q=["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-excel"],V=["pdf"],$=["png","jpg","jpeg","gif","webp","svg","bmp"],H=["txt","csv","html","css","js","json","xml","log","md","yaml","yml","xaml"],X=["docx"],G=["xlsx","xls"],J=["application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-powerpoint"],Y=["pptx","ppt"],K={png:"png-200-200.png",jpg:"jpeg-200-200.png",jpeg:"jpeg-200-200.png",gif:"gif-200-200.png",webp:"png-200-200.png",bmp:"png-200-200.png",svg:"svg-200-200.png"},Q={"image/png":K.png,"image/jpeg":K.jpeg,"image/jpg":K.jpeg,"image/gif":K.gif,"image/webp":K.webp,"image/bmp":K.bmp,"image/svg+xml":K.svg};function Z(e){if(!e||"string"==typeof e)return e;var t,n,r,i,l,o,a,u,c,s,f,d,p,m,v,g,h,y,b,w,x,E,S,O,k=e.response;return k&&(void 0===k?"undefined":N(k))==="object"?I(R({},k,e),{id:null!=(t=e.id)?t:k.id,uid:null!=(n=e.uid)?n:k.uid,url:null!=(r=e.url)?r:k.url,preview:e.preview||k.preview,filename:null!=(i=e.filename)?i:k.filename,name:null!=(l=e.name)?l:k.name,title:null!=(o=e.title)?o:k.title,extname:null!=(a=e.extname)?a:k.extname,mimetype:null!=(u=e.mimetype)?u:k.mimetype,size:null!=(c=e.size)?c:k.size,path:null!=(s=e.path)?s:k.path,storageId:null!=(f=e.storageId)?f:k.storageId,storageType:null!=(d=null!=(p=null!=(m=e.storageType)?m:k.storageType)?p:null==(x=e.storage)?void 0:x.type)?d:null==(E=k.storage)?void 0:E.type,storageName:null!=(v=null!=(g=null!=(h=e.storageName)?h:k.storageName)?g:null==(S=e.storage)?void 0:S.name)?v:null==(O=k.storage)?void 0:O.name,storage:null!=(y=e.storage)?y:k.storage,collectionName:null!=(b=e.collectionName)?b:k.collectionName,lastModified:null!=(w=e.lastModified)?w:k.lastModified}):e}function ee(e){return null!==e&&(void 0===e?"undefined":N(e))==="object"}function et(e){if("number"==typeof e)return Number.isInteger(e)&&e>0?e:null;if("string"==typeof e){var t=e.trim();return/^\d+$/.test(t)?t:null}return null}function en(e){var t=ee(e)?e:{},n=ee(t.response)?t.response:{},r=Z(e),i=ee(r)?r:{},l=[i.attachmentId,i.id,n.attachmentId,n.id,t.attachmentId,t.id,i.uid,n.uid,t.uid],o=!0,a=!1,u=void 0;try{for(var c,s=l[Symbol.iterator]();!(o=(c=s.next()).done);o=!0){var f=c.value,d=et(f);if(null!=d)return d}}catch(e){a=!0,u=e}finally{try{o||null==s.return||s.return()}finally{if(a)throw u}}return null}function er(e){var t,n=ee(e)?e:{},r=Z(e),i=null!=(t=(ee(r)?r:{}).collectionName)?t:n.collectionName;return null==i||""===i||"attachments"===i}var ei=function(e){var t=Z(e),n=("string"==typeof t?t:(null==t?void 0:t.extname)||(null==t?void 0:t.name)||(null==t?void 0:t.filename)||(null==t?void 0:t.url)||"").split("?")[0].split("#")[0],r=n.lastIndexOf(".");return -1!==r?n.slice(r+1).toLowerCase().replace(/^\./,""):""},el=function(e){var t=Z(e),n="string"==typeof t?t:(null==t?void 0:t.url)||(null==t?void 0:t.preview)||(null==t?void 0:t.path);return n?n.startsWith("https://")||n.startsWith("http://")?n:"".concat(location.origin,"/").concat(n.replace(/^\//,"")):""},eo=function(e){if("string"==typeof e)return e;var t=Z(e);return t?[t.id,t.uid,t.url,t.preview,t.path,t.storageId,t.storageType,t.storageName,t.collectionName,t.lastModified,t.size].filter(function(e){return null!=e&&""!==e}).join(":"):""},ea=function(e){var t=Z(e);if((null==t?void 0:t.mimetype)&&z.includes(t.mimetype))return!0;var n=ei(e);return!!n&&V.includes(n)},eu=function(e){var t=Z(e);if((null==t?void 0:t.mimetype)&&M.includes(t.mimetype)||(null==t?void 0:t.mimetype)&&(0,i.matchMimetype)(t,"image/*"))return!0;var n=ei(e);return!!n&&$.includes(n)},ec=function(e){var t=Z(e);if((null==t?void 0:t.mimetype)&&D.includes(t.mimetype))return!0;var n=ei(e);return!!n&&H.includes(n)},es=function(e){var t=Z(e);if((null==t?void 0:t.mimetype)&&W.includes(t.mimetype))return!0;var n=ei(e);return!!n&&X.includes(n)},ef=function(e){var t=Z(e);if((null==t?void 0:t.mimetype)&&q.includes(t.mimetype))return!0;var n=ei(e);return!!n&&G.includes(n)},ed=function(e){var t=Z(e);if((null==t?void 0:t.mimetype)&&J.includes(t.mimetype))return!0;var n=ei(e);return!!n&&Y.includes(n)};function ep(e){return["waiting-verify","success","verified","accepted","rejected"].includes(e||"")}function em(e){for(var t,n=e,r=0;r<5;r+=1){if(ee(t=n)&&("string"==typeof t.status||null!=et(t.attachmentId)||null!=et(t.id)))return n;if(!ee(n))break;n=n.data}return null}var ev=function(e){var t=Z(e);return t?t.title&&t.extname?"".concat(t.title).concat(t.extname):t.filename||t.name||t.title||"download":"download"},eg=new Map;function eh(e){var t,n,r,i,l,o=Z(e);return{id:null==o?void 0:o.id,uid:null==o?void 0:o.uid,url:null==o?void 0:o.url,preview:null==o?void 0:o.preview,filename:(null==o?void 0:o.filename)||(null==o?void 0:o.name),name:(null==o?void 0:o.name)||(null==o?void 0:o.filename),title:null==o?void 0:o.title,extname:null==o?void 0:o.extname,mimetype:null==o?void 0:o.mimetype,size:null==o?void 0:o.size,path:null==o?void 0:o.path,storageId:null!=(t=null!=(n=null==o?void 0:o.storageId)?n:null==o?void 0:o.storage_id)?t:null==o||null==(r=o.storage)?void 0:r.id,storage_id:null==o?void 0:o.storage_id,storageType:(null==o?void 0:o.storageType)||(null==o||null==(i=o.storage)?void 0:i.type),storageName:(null==o?void 0:o.storageName)||(null==o||null==(l=o.storage)?void 0:l.name),storage:null==o?void 0:o.storage,collectionName:null==o?void 0:o.collectionName,lastModified:null==o?void 0:o.lastModified}}function ey(e){if(!e)return!1;try{var t=new URL(e,location.origin);if(t.origin!==location.origin)return!1;return["/api/filePreviewAuth:download","/api/extStorage:download","/api/skillHub:download","/api/worker-monitor","/api/carboneTemplates:download","/api/attachments:stream","/api/attachments:sftpStream"].some(function(e){return t.pathname===e||t.pathname.startsWith("".concat(e,"/"))||t.pathname.startsWith("".concat(e,":"))})}catch(e){return!1}}function eb(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"inline";return j(function(){var r,i,l;return B(this,function(o){if(!(r=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"inline",n=eh("string"==typeof e?{url:e}:e||{}),r=el(e);if(r&&ey(r))return r;if(function(e,t){var n,r,i,l=eh("string"==typeof e?{url:e}:e||{}),o=l.collectionName||"attachments";return null!=(l.id||l.uid)&&("s3-private"===(i=(r=eh("string"==typeof e?{url:e}:e||{})).storageType||(null==(n=r.storage)?void 0:n.type))||"aws-s3-private"===i||"attachments"===o&&!t)}(e,r)){var i=eh("string"==typeof e?{url:e}:e||{}),l=i.id||i.uid;if(null==l)return"";var o=new URLSearchParams({filterByTk:String(l),mode:t,collection:i.collectionName||"attachments"});return"/api/attachments:stream?".concat(o.toString())}var a=n.id||n.uid;if(null!=a){var u,c=n.collectionName||"attachments",s=new URLSearchParams;s.set("id",String(a)),s.set("collection",c),r&&s.set("url",r);var f=n.storageId||n.storage_id||(null==(u=n.storage)?void 0:u.id);return null!=f&&""!==f&&s.set("storageId",String(f)),(n.filename||n.name)&&s.set("filename",n.filename||n.name),n.mimetype&&s.set("mimetype",n.mimetype),"/api/filePreviewAuth:download?".concat(s.toString())}return r||""}(e,n))||r.endsWith("?"))throw Error("No file URL");return i="".concat(t?"auth":"anon",":").concat(t||"",":").concat(eo(e)||r),(l=eg.get(i))||(l=j(function(){var e,n;return B(this,function(i){switch(i.label){case 0:return e={},t&&(e.Authorization="Bearer ".concat(t)),[4,fetch(r,{method:"GET",headers:e,credentials:"include"})];case 1:if(!(n=i.sent()).ok)throw Error("Failed to fetch file: ".concat(n.status," ").concat(n.statusText));return[2,n.blob()]}})})().catch(function(e){throw eg.delete(i),e}),eg.set(i,l)),[2,l]})})()}function ew(e,t){return j(function(){var n,r,i,l;return B(this,function(o){switch(o.label){case 0:return[4,eb(e,t,"attachment")];case 1:return n=o.sent(),r=ev(e),(i=document.createElement("a")).href=l=URL.createObjectURL(n),i.download=r,document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(function(){return URL.revokeObjectURL(l)},1e3),[2]}})})()}function ex(t,n){var r=F((0,e.useState)(null),2),i=r[0],l=r[1],o=F((0,e.useState)(!0),2),a=o[0],u=o[1],c=F((0,e.useState)(null),2),s=c[0],f=c[1],d=(0,e.useRef)(null),p=(0,e.useRef)(t);p.current=t;var m=eo(t);return(0,e.useEffect)(function(){var e=!1,t=p.current;if(!(el(t)||"string"!=typeof t&&((null==t?void 0:t.id)||(null==t?void 0:t.uid)))){u(!1),f("No file URL");return}return u(!0),f(null),eb(t,n).then(function(t){if(!e){var n=URL.createObjectURL(t);d.current=n,l(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)}},[m,n]),{blobUrl:i,loading:a,error:s}}function eE(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 eS(e){var n=e.message;return t().createElement("div",{style:{padding:20,textAlign:"center",color:"#ff4d4f"}},n)}function eO(e){var i=e.file,l=e.title,o=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:l},l),function(){if(!u||!o)return null;switch(o){case"pending-ocr":return t().createElement(r.Tag,{color:"processing",icon:t().createElement(n.SyncOutlined,{spin:!0})},c("OCR Pending"));case"waiting-verify":case"success":return t().createElement(r.Tag,{color:"warning",icon:t().createElement(n.ClockCircleOutlined,null)},c("Waiting Verify"));case"verified":case"accepted":return t().createElement(r.Tag,{color:"success",icon:t().createElement(n.CheckCircleOutlined,null)},c("OCR Verified"));case"rejected":return t().createElement(r.Tag,{color:"error"},c("OCR Rejected"));case"failed":return t().createElement(r.Tag,{color:"error"},c("OCR Failed"));default:return t().createElement(r.Tag,{color:"default"},c("No OCR"))}}()),t().createElement(k,{file:i}))}function ek(e){var n,r=e.file,l=(0,i.useAPIClient)(),o=a(),u=ex(r,(null==(n=l.auth)?void 0:n.token)||""),c=u.blobUrl,s=u.loading,f=u.error;return s?t().createElement(eE,{message:o("Loading preview...")}):f||!c?t().createElement(eS,{message:o("Failed to load file preview")}):t().createElement("iframe",{src:c,width:"100%",height:"100%",style:{border:"none"}})}function eC(e){var n,r=e.file,l=(0,i.useAPIClient)(),o=a(),u=ex(r,(null==(n=l.auth)?void 0:n.token)||""),c=u.blobUrl,s=u.loading,f=u.error;return s?t().createElement(eE,{message:o("Loading preview...")}):f||!c?t().createElement(eS,{message:o("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 eP(n){var r,l,o,u,c,s,f,d,p,m,v,g,h=n.file,y=(0,i.useAPIClient)(),b=a(),w=(null==(g=y.auth)?void 0:g.token)||"",x=(l=(r=F((0,e.useState)(null),2))[0],o=r[1],c=(u=F((0,e.useState)(!0),2))[0],s=u[1],d=(f=F((0,e.useState)(null),2))[0],p=f[1],(m=(0,e.useRef)(h)).current=h,v=eo(h),(0,e.useEffect)(function(){var e=!1,t=m.current;if(!(el(t)||"string"!=typeof t&&((null==t?void 0:t.id)||(null==t?void 0:t.uid)))){s(!1),p("No file URL");return}return s(!0),p(null),eb(t,w).then(function(e){return e.text()}).then(function(t){e||(o(t),s(!1))}).catch(function(t){e||(p(t.message||"Failed to load"),s(!1))}),function(){e=!0}},[v,w]),{text:l,loading:c,error:d}),E=x.text,S=x.loading,O=x.error;return S?t().createElement(eE,{message:b("Loading preview...")}):O||null===E?t().createElement(eS,{message:b("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"}},E)}function ej(n){var r,l=n.file,o=(0,i.useAPIClient)(),u=a(),c=(null==(r=o.auth)?void 0:r.token)||"",s=(0,e.useRef)(null),d=(0,e.useRef)(l);d.current=l;var p=eo(l),m=F((0,e.useState)(!0),2),v=m[0],g=m[1],h=F((0,e.useState)(null),2),y=h[0],b=h[1];return(0,e.useEffect)(function(){var e=!1,t=d.current;if(!(el(t)||"string"!=typeof t&&((null==t?void 0:t.id)||(null==t?void 0:t.uid)))||!s.current){g(!1),b("No file URL");return}return g(!0),b(null),j(function(){var n,r,i;return B(this,function(l){switch(l.label){case 0:return l.trys.push([0,4,,5]),[4,eb(t,c)];case 1:if(n=l.sent(),e)return[2];return[4,f.e("713").then(f.bind(f,440))];case 2:if(r=l.sent(),e||!s.current)return[2];return s.current.innerHTML="",[4,r.renderAsync(n,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 l.sent(),g(!1),[3,5];case 4:if(i=l.sent(),e)return[2];return b(i.message||"Failed to render DOCX"),g(!1),[3,5];case 5:return[2]}})})(),function(){e=!0}},[p,c]),t().createElement("div",{style:{width:"100%",height:"100%",position:"relative"}},v&&t().createElement(eE,{message:u("Loading preview...")}),y&&t().createElement(eS,{message:u("Failed to load file preview")}),t().createElement("div",{ref:s,style:{width:"100%",height:"100%",overflow:"auto",display:v||y?"none":"block"}}))}function eT(n){var r,l=n.file,o=(0,i.useAPIClient)(),u=a(),c=(null==(r=o.auth)?void 0:r.token)||"",s=(0,e.useRef)(null),d=(0,e.useRef)(l);d.current=l;var p=eo(l),m=F((0,e.useState)(!0),2),v=m[0],g=m[1],h=F((0,e.useState)(null),2),y=h[0],b=h[1],w=F((0,e.useState)([]),2),x=w[0],E=w[1],S=F((0,e.useState)(""),2),O=S[0],k=S[1],C=F((0,e.useState)({}),2),P=C[0],T=C[1];return(0,e.useEffect)(function(){var e=!1,t=d.current;if(!(el(t)||"string"!=typeof t&&((null==t?void 0:t.id)||(null==t?void 0:t.uid)))){g(!1),b("No file URL");return}return g(!0),b(null),j(function(){var n,r,i,l,o,a,u,s,d,p,m,v,h,y;return B(this,function(w){switch(w.label){case 0:return w.trys.push([0,4,,5]),[4,eb(t,c)];case 1:if(n=w.sent(),e)return[2];return[4,f.e("892").then(f.bind(f,959))];case 2:if(r=w.sent(),e)return[2];return[4,n.arrayBuffer()];case 3:if(i=w.sent(),e)return[2];o=(l=r.read(i,{type:"array"})).SheetNames,a={},u=!0,s=!1,d=void 0;try{for(p=o[Symbol.iterator]();!(u=(m=p.next()).done);u=!0)v=m.value,h=l.Sheets[v],a[v]=r.utils.sheet_to_html(h,{id:"xlsx-preview-table"})}catch(e){s=!0,d=e}finally{try{u||null==p.return||p.return()}finally{if(s)throw d}}if(e)return[2];return E(o),k(o[0]||""),T(a),g(!1),[3,5];case 4:if(y=w.sent(),e)return[2];return b(y.message||"Failed to render XLSX"),g(!1),[3,5];case 5:return[2]}})})(),function(){e=!0}},[p,c]),t().createElement("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column"}},v&&t().createElement(eE,{message:u("Loading preview...")}),y&&t().createElement(eS,{message:u("Failed to load file preview")}),!v&&!y&&t().createElement(t().Fragment,null,x.length>1&&t().createElement("div",{style:{display:"flex",gap:0,borderBottom:"1px solid #e8e8e8",background:"#fafafa",padding:"0 8px",flexShrink:0,overflowX:"auto"}},x.map(function(e){return t().createElement("button",{key:e,onClick:function(){return k(e)},style:{padding:"8px 16px",border:"none",borderBottom:O===e?"2px solid #1890ff":"2px solid transparent",background:O===e?"#fff":"transparent",color:O===e?"#1890ff":"#666",fontWeight:O===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:P[O]||""}}),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 e_(n){var r,l=n.file,o=(0,i.useAPIClient)(),u=a(),c=(null==(r=o.auth)?void 0:r.token)||"",s=F((0,e.useState)(!0),2),d=s[0],p=s[1],m=F((0,e.useState)(null),2),v=m[0],g=m[1],h=F((0,e.useState)(null),2),y=h[0],b=h[1],w=F((0,e.useState)(null),2),x=w[0],E=w[1],S=(0,e.useRef)(l);S.current=l;var O=eo(l);return(0,e.useEffect)(function(){var e=!1,t=S.current;if(!(el(t)||"string"!=typeof t&&((null==t?void 0:t.id)||(null==t?void 0:t.uid)))){p(!1),g("No file URL");return}return p(!0),g(null),j(function(){var n,r,i,l;return B(this,function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),[4,Promise.all([eb(t,c),f.e("828").then(f.bind(f,559))])];case 1:if(r=(n=F.apply(void 0,[o.sent(),2]))[0],i=n[1],e)return[2];return b(r),E(function(){return i.PptxPreview}),p(!1),[3,3];case 2:if(l=o.sent(),e)return[2];return g(l.message||"Failed to render PPTX"),p(!1),[3,3];case 3:return[2]}})})(),function(){e=!0}},[O,c]),t().createElement("div",{style:{width:"100%",height:"100%",position:"relative"}},d&&t().createElement(eE,{message:u("Loading preview...")}),v&&t().createElement(eS,{message:u("Failed to load file preview")}),!d&&!v&&x&&t().createElement("div",{style:{width:"100%",height:"100%",overflow:"auto"}},t().createElement(x,{file:y})))}var eR=function(l){return function(o){var u=o.open,c=o.onOpenChange,s=o.onClose,f=o.file,d=o.index,p=o.list,m=o.onSwitchIndex;o.onDownload;var v=(0,i.useAPIClient)(),g=a(),h=F((0,e.useState)("visual"),2),y=h[0],b=h[1],w=(0,e.useCallback)(function(e){return j(function(){var t,n,i;return B(this,function(l){switch(l.label){case 0:if(!(n=e||f))return[2];i=(null==(t=v.auth)?void 0:t.token)||"",l.label=1;case 1:return l.trys.push([1,3,,4]),[4,ew(n,i)];case 2:return l.sent(),[3,4];case 3:return l.sent(),r.message.error(g("Failed to download file")),[3,4];case 4:return[2]}})})()},[f,v,g]);if("boolean"!=typeof u)return t().createElement(l,I(R({},o),{onDownload:w}));var x=ev(f),E="number"==typeof d&&!!m&&d>0,S="number"==typeof d&&!!m&&d<p.length-1;return t().createElement(r.Modal,{open:u,title:t().createElement(eO,{file:f,title:x}),onCancel:function(){null==c||c(!1),null==s||s(),b("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 b(function(e){return"visual"===e?"raw":"visual"})}},"visual"===y?g("View Raw Parsed Text"):g("View Visual Preview"))),t().createElement(r.Space,{size:14,style:{fontSize:"20px"}},t().createElement(n.LeftOutlined,{style:{cursor:E?"pointer":"not-allowed"},onClick:function(){return E&&(null==m?void 0:m(d-1))}}),t().createElement(n.RightOutlined,{style:{cursor:S?"pointer":"not-allowed"},onClick:function(){return S&&(null==m?void 0:m(d+1))}}),t().createElement(n.DownloadOutlined,{onClick:function(){return w(f)}}))),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"===y?t().createElement(eI,{file:f}):t().createElement(l,I(R({},o),{onDownload:w}))))}};function eI(l){var o=l.file,u=(0,i.useAPIClient)(),c=a(),s=F((0,e.useState)(""),2),f=s[0],d=s[1],p=F((0,e.useState)(!0),2),m=p[0],v=p[1],g=F((0,e.useState)(null),2),h=g[0],y=g[1],b=(0,i.useComponent)("MarkdownVditor"),w=(0,i.useComponent)("Markdown.Void");return((0,e.useEffect)(function(){var e=!1;return j(function(){var t,n,r,i,l,a,c,s,f,p;return B(this,function(m){switch(m.label){case 0:v(!0),y(null),m.label=1;case 1:return m.trys.push([1,4,,5]),[4,eb(o,(null==(t=u.auth)?void 0:t.token)||"")];case 2:if(i=m.sent(),e)return[2];return(l=new FormData).append("file",i,ev(o)),l.append("attachment",JSON.stringify(eh(o))),[4,u.request({url:"filePreviewAuth:getContent",method:"post",data:l,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 y(p.message||"Failed to fetch raw text"),v(!1),[3,5];case 5:return[2]}})})(),function(){e=!0}},[o,u]),m)?t().createElement(r.Spin,{size:"large",tip:c("Extracting raw text..."),style:{marginTop:"40px"}}):h?t().createElement(r.Alert,{type:"error",message:h,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 eA(l){var o=l.index,u=l.list,c=l.onSwitchIndex,s=a(),f=(0,i.useAPIClient)(),d=u[o],p=F((0,e.useState)(!1),2),m=p[0],v=p[1],g=F((0,e.useState)("visual"),2),h=g[0],y=g[1],b=F((0,e.useState)("preview"),2),w=b[0],x=b[1],E=F((0,e.useState)("no-ocr"),2),S=E[0],O=E[1],k=F((0,e.useState)(null),2),C=k[0],P=k[1],T=F((0,e.useState)(null),2),_=T[0],A=T[1],N=(0,e.useMemo)(function(){return er(d)?en(d):null},[d]),L=(0,e.useMemo)(function(){return!!d&&!!N&&(ea(d)||eu(d))},[d,N]),U=(0,i.useComponent)("OcrVerifyBlock"),z=(0,e.useCallback)(function(e){e&&(P(e.id||null),O(e.status||"no-ocr"),A(e.error||null))},[]),M=(0,e.useCallback)(function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.updateState,n=void 0===t||t;return j(function(){var e;return B(this,function(t){switch(t.label){case 0:if(!N)return[2,null];return[4,f.request({url:"filePreviewAuth:getOcrStatus",method:"post",data:{attachmentId:N}})];case 1:return(e=em(t.sent()))&&n&&z(e),[2,e]}})})()},[f,z,N]);(0,e.useEffect)(function(){if(N){var e=!1;return P(null),O("no-ocr"),A(null),M().then(function(){if(e)return}).catch(console.error),function(){e=!0}}},[N,M]),(0,e.useEffect)(function(){if("pending-ocr"===S&&N){var e=null,t=!1,n=0,i=function(){return j(function(){var l,o;return B(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,,3]),[4,M({updateState:!1})];case 1:if(l=a.sent(),t)return[2];if(l){if("pending-ocr"===(o=l.status||"no-ocr"))return z(l),e=setTimeout(i,3e3),[2];if(ep(o))return z(l),x("ocr"),r.message.success(s("OCR processing completed!")),[2];if("failed"===o)return z(l),r.message.error(l.error||s("OCR processing failed")),[2];if("no-ocr"===o&&n<3)return n+=1,e=setTimeout(i,3e3),[2];z(l)}else n<3?(n+=1,e=setTimeout(i,3e3)):(P(null),O("no-ocr"),A(null));return[3,3];case 2:return console.error("Polling error",a.sent()),e=setTimeout(i,3e3),[3,3];case 3:return[2]}})})()};return e=setTimeout(i,3e3),function(){t=!0,e&&clearTimeout(e)}}},[z,S,N,M,s]);var D=function(){return j(function(){var e,t;return B(this,function(n){switch(n.label){case 0:if(!N)return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),O("pending-ocr"),[4,f.request({url:"filePreviewAuth:runOcr",method:"post",data:{attachmentId:N}})];case 2:return(e=em(n.sent()))&&z(I(R({},e),{status:e.status||"pending-ocr"})),r.message.info(s("OCR process started in the background.")),[3,4];case 3:return t=n.sent(),r.message.error((null==t?void 0:t.message)||s("Failed to start OCR process.")),O("no-ocr"),[3,4];case 4:return[2]}})})()},W=(0,e.useCallback)(function(e){return j(function(){var t,n,i,l;return B(this,function(o){switch(o.label){case 0:null==e||null==(t=e.preventDefault)||t.call(e),null==e||null==(n=e.stopPropagation)||n.call(e),l=(null==(i=f.auth)?void 0:i.token)||"",v(!0),o.label=1;case 1:return o.trys.push([1,3,4,5]),[4,ew(d,l)];case 2:return o.sent(),[3,5];case 3:return o.sent(),r.message.error(s("Failed to download file")),[3,5];case 4:return v(!1),[7];case 5:return[2]}})})()},[d,f,s]),q=(0,e.useCallback)(function(){c(null),y("visual"),x("preview")},[c]),V=(0,e.useMemo)(function(){return ea(d)?ek:eu(d)?eC:ec(d)?eP:es(d)?ej:ef(d)?eT:ed(d)?e_:null},[d]),$=null!=V||"raw"===h,H=[{key:"preview",label:t().createElement("span",null,t().createElement(n.EyeOutlined,null)," ",s("Visual Preview")),children:t().createElement("div",{style:{height:"70vh",width:"100%",overflow:"auto",background:"#f5f5f5",display:"flex",justifyContent:"center",alignItems:"center"}},V?t().createElement(V,{file:d}):null)},{key:"ocr",label:t().createElement("span",null,t().createElement(n.ScanOutlined,null)," ",s("OCR & Verify")),children:t().createElement("div",{style:{height:"70vh",width:"100%",display:"flex",flexDirection:"column"}},"no-ocr"===S&&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"}},s("Word-level Song ngữ (English & Vietnamese) OCR")),t().createElement("p",{style:{color:"#8c8c8c",maxWidth:"480px",textAlign:"center",marginBottom:"24px"}},s("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},s("Run Tesseract OCR"))),"pending-ocr"===S&&t().createElement("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100%",padding:"40px"}},t().createElement(r.Spin,{size:"large",tip:s("Analyzing layout structure and running song ngữ OCR...")}),t().createElement("p",{style:{color:"#8c8c8c",marginTop:"20px",fontSize:"13px",textAlign:"center"}},s("Extracting word-level coordinates via Tesseract-OCR. This will automatically refresh when complete."))),"failed"===S&&t().createElement("div",{style:{padding:"40px"}},t().createElement(r.Alert,{type:"error",showIcon:!0,message:s("OCR processing failed"),description:_||s("Please try running OCR again."),style:{marginBottom:24}}),t().createElement(r.Button,{type:"primary",icon:t().createElement(n.ThunderboltOutlined,null),onClick:D},s("Run Tesseract OCR"))),ep(S)&&t().createElement("div",{style:{flex:1,height:"100%",overflow:"hidden"}},U&&C?t().createElement(U,{collection:"attachmentOcrResults",recordId:C,pdfField:"attachment",jsonField:"data",statusField:"status"}):U?t().createElement("div",{style:{padding:"20px"}},t().createElement(r.Alert,{type:"error",message:s("OCR result record not found"),description:s("Please try running OCR again."),showIcon:!0})):t().createElement("div",{style:{padding:"20px"}},t().createElement(r.Alert,{type:"error",message:s("Plugin OCR Verify Block is not enabled"),description:s("Please enable the plugin-ocr-verify-block plugin to display the verify splitter layout."),showIcon:!0}))))}];return t().createElement(r.Modal,{open:null!=o,title:t().createElement(eO,{file:d,title:(null==d?void 0:d.title)||(null==d?void 0:d.filename)||(null==d?void 0:d.name)||"File",ocrStatus:S,isOcrSupported:L}),onCancel:q,footer:t().createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",width:"100%"}},t().createElement("div",{key:"left-actions"},!L&&t().createElement(r.Button,{onClick:function(){return y(function(e){return"visual"===e?"raw":"visual"})}},"visual"===h?s("View Raw Parsed Text"):s("View Visual Preview"))),t().createElement(r.Space,null,t().createElement(r.Button,{key:"download",onClick:W,loading:m},s("Download")),t().createElement(r.Button,{key:"close",onClick:q},s("Close")))),width:$?"90%":520,centered:!0},L?t().createElement(r.Tabs,{activeKey:w,onChange:function(e){return x(e)},items:H,style:{width:"100%",height:"100%"}}):t().createElement("div",{style:{maxWidth:"100%",maxHeight:$?"calc(100vh - 256px)":"auto",height:$?"70vh":"auto",width:"100%",background:"white",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",overflowY:"auto"}},"raw"===h?t().createElement(eI,{file:d}):V?t().createElement(V,{file:d}):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 eF(n){var l=n.file,o=(0,i.useAPIClient)(),u=a(),c=(0,e.useCallback)(function(){return j(function(){var e,t;return B(this,function(n){switch(n.label){case 0:t=(null==(e=o.auth)?void 0:e.token)||"",n.label=1;case 1:return n.trys.push([1,3,,4]),[4,ew(l,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]}})})()},[l,o,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 eN=function(e){var o;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=_(e),function(e,t){if(t&&("object"===N(t)||"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||[],_(this).constructor):e.apply(this,t))}return a.prototype=Object.create(e&&e.prototype,{constructor:{value:a,writable:!0,configurable:!0}}),e&&A(a,e),o=[{key:"load",value:function(){return j(function(){return B(this,function(e){return this.patchUploadPreviewBase64Fallback(),!function(e){try{i=e.pm.get("ai")}catch(e){return}var i,l,o=null==i?void 0:i.aiManager;if(null==o?void 0:o.registerWorkContext)try{(null==(l=o.getWorkContext)?void 0:l.call(o,w))||o.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){}}(this.app),i.attachmentFileTypes.add({match:function(){return!0},Previewer:eA}),l.filePreviewTypes.add({match:function(){return!0},Previewer:eR(eF)}),l.filePreviewTypes.add({match:ea,Previewer:eR(ek)}),l.filePreviewTypes.add({match:eu,getThumbnailURL:function(e){var t,n,r,i,l,o,a,u;return(u=[null==(a=Z(e))?void 0:a.preview,null==a?void 0:a.url].find(function(e){return"string"==typeof e&&e}))&&!ey(u)?u:(n=ei(t=Z(a)),r="string"==typeof(null==t?void 0:t.mimetype)?t.mimetype.toLowerCase():"",i=K[n]||Q[r]||"unknown-200-200.png",l="file-placeholder/".concat(i),o="u"<typeof window?"/":window.__nocobase_dev_public_path__||window.__nocobase_public_path__||"/","".concat(o.replace(/\/?$/,"/")).concat(l.replace(/^\//,"")))},Previewer:eR(eC)}),l.filePreviewTypes.add({match:ec,Previewer:eR(eP)}),l.filePreviewTypes.add({match:es,Previewer:eR(ej)}),l.filePreviewTypes.add({match:ef,Previewer:eR(eT)}),l.filePreviewTypes.add({match:ed,Previewer:eR(e_)}),[2]})}).call(this)}},{key:"patchUploadPreviewBase64Fallback",value:function(){if(!("u"<typeof window)){var e,t=null==(e=window.FileReader)?void 0:e.prototype;if(t&&!t.__filePreviewAuthBase64FallbackPatched){var n=t.readAsDataURL;"function"==typeof n&&(Object.defineProperty(t,"__filePreviewAuthBase64FallbackPatched",{value:!0,configurable:!0}),t.readAsDataURL=function(e){var t=this;if(null!=e)return n.call(this,e);setTimeout(function(){var e,n;try{Object.defineProperty(t,"result",{value:"",configurable:!0})}catch(e){}null==(e=t.onload)||e.call(t,new ProgressEvent("load")),null==(n=t.onloadend)||n.call(t,new ProgressEvent("loadend"))},0)})}}}}],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,o),a}(L(i.Plugin)),eL=eN}(),h}()});
@@ -11,13 +11,13 @@ 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.1.6",
15
- "@nocobase/plugin-ai": "2.1.6",
16
- "@nocobase/plugin-file-manager": "2.1.6",
17
- "@nocobase/client-v2": "2.1.6",
18
- "@nocobase/actions": "2.1.6",
19
- "@nocobase/server": "2.1.6",
20
- "@nocobase/utils": "2.1.6",
14
+ "@nocobase/client": "2.1.8",
15
+ "@nocobase/plugin-ai": "2.1.8",
16
+ "@nocobase/plugin-file-manager": "2.1.8",
17
+ "@nocobase/client-v2": "2.1.8",
18
+ "@nocobase/actions": "2.1.8",
19
+ "@nocobase/server": "2.1.8",
20
+ "@nocobase/utils": "2.1.8",
21
21
  "sequelize": "6.35.2",
22
- "@nocobase/database": "2.1.6"
22
+ "@nocobase/database": "2.1.8"
23
23
  };
@@ -279,45 +279,60 @@ class PluginFilePreviewAuthServer extends import_server.Plugin {
279
279
  await this.assertCanAccessAttachment(ctx, attachment);
280
280
  }
281
281
  try {
282
- const attachmentObj = await this.prepareAttachmentForFileManager(
282
+ const attachmentObj2 = await this.prepareAttachmentForFileManager(
283
283
  attachment,
284
284
  fileManager,
285
285
  attachmentCollection
286
286
  );
287
- const storageModel = getStorageFromCache(fileManager.storagesCache, attachmentObj.storageId);
287
+ const storageModel2 = getStorageFromCache(fileManager.storagesCache, attachmentObj2.storageId);
288
288
  this.log.debug(
289
289
  `[FilePreviewAuth] Attachment prepared for stream ${safeDebugJson({
290
- ...summarizeAttachmentForLog(attachmentObj, attachmentCollection),
291
- storageModel: summarizeStorageForLog(storageModel),
290
+ ...summarizeAttachmentForLog(attachmentObj2, attachmentCollection),
291
+ storageModel: summarizeStorageForLog(storageModel2),
292
292
  storageCache: summarizeStorageCache(fileManager.storagesCache)
293
293
  })}`
294
294
  );
295
- if (storageModel && (storageModel.type === "s3" || storageModel.type === "aws-s3" || storageModel.type === "s3-private")) {
296
- const StorageTypeClass = fileManager.storageTypes.get(storageModel.type);
297
- const storageInstance = new StorageTypeClass(storageModel);
295
+ if (storageModel2 && (storageModel2.type === "s3" || storageModel2.type === "aws-s3" || storageModel2.type === "s3-private")) {
296
+ const StorageTypeClass = fileManager.storageTypes.get(storageModel2.type);
297
+ const storageInstance = new StorageTypeClass(storageModel2);
298
298
  const s3Client = storageInstance.client || (typeof storageInstance.getS3Client === "function" ? storageInstance.getS3Client() : null);
299
299
  if (s3Client) {
300
300
  const { GetObjectCommand } = require("@aws-sdk/client-s3");
301
- const key = storageInstance.getFileKey(attachmentObj);
301
+ const key = storageInstance.getFileKey(attachmentObj2);
302
302
  const getCommand = new GetObjectCommand({
303
- Bucket: storageModel.options.bucket,
303
+ Bucket: storageModel2.options.bucket,
304
304
  Key: key
305
305
  });
306
306
  const response = await s3Client.send(getCommand);
307
- ctx.type = response.ContentType || attachmentObj.mimetype || "application/octet-stream";
308
- ctx.attachment(attachmentObj.filename);
307
+ ctx.type = response.ContentType || attachmentObj2.mimetype || "application/octet-stream";
308
+ ctx.attachment(attachmentObj2.filename);
309
309
  ctx.body = response.Body;
310
310
  await next();
311
311
  return;
312
312
  }
313
313
  }
314
- const { stream, contentType } = await fileManager.getFileStream(attachmentObj);
315
- ctx.type = contentType || attachmentObj.mimetype || "application/octet-stream";
316
- ctx.attachment(attachmentObj.filename);
314
+ const { stream, contentType } = await fileManager.getFileStream(attachmentObj2);
315
+ ctx.type = contentType || attachmentObj2.mimetype || "application/octet-stream";
316
+ ctx.attachment(attachmentObj2.filename);
317
317
  ctx.body = stream;
318
318
  } catch (err) {
319
319
  this.log.error(`[FilePreviewAuth] Error fetching stream for URL ${url}: ${err.message}`);
320
- ctx.throw(500, "Failed to fetch the file from storage");
320
+ try {
321
+ require("fs").writeFileSync(
322
+ require("path").join(process.cwd(), "preview_error.log"),
323
+ `Error fetching stream for URL ${url}:
324
+ Time: ${(/* @__PURE__ */ new Date()).toISOString()}
325
+ Message: ${err.message}
326
+ Stack: ${err.stack}
327
+ Attachment: ${JSON.stringify(attachment, null, 2)}
328
+ AttachmentObj: ${JSON.stringify(attachmentObj, null, 2)}
329
+ StorageModel: ${JSON.stringify(storageModel, null, 2)}
330
+ `
331
+ );
332
+ } catch (fsErr) {
333
+ this.log.error(`[FilePreviewAuth] Failed to write preview_error.log: ${fsErr.message}`);
334
+ }
335
+ ctx.throw(500, `Failed to fetch the file from storage: ${err.message}`);
321
336
  }
322
337
  await next();
323
338
  },
@@ -728,8 +743,8 @@ class PluginFilePreviewAuthServer extends import_server.Plugin {
728
743
  if (!(fileManager == null ? void 0 : fileManager.getFileStream)) {
729
744
  return "";
730
745
  }
731
- const attachmentObj = await this.prepareAttachmentForFileManager(attachment, fileManager);
732
- const { stream } = await fileManager.getFileStream(attachmentObj);
746
+ const attachmentObj2 = await this.prepareAttachmentForFileManager(attachment, fileManager);
747
+ const { stream } = await fileManager.getFileStream(attachmentObj2);
733
748
  const chunks = [];
734
749
  for await (const chunk of stream) {
735
750
  chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
@@ -737,22 +752,22 @@ class PluginFilePreviewAuthServer extends import_server.Plugin {
737
752
  return Buffer.concat(chunks).toString("utf-8");
738
753
  }
739
754
  async prepareAttachmentForFileManager(attachment, fileManager, recordCollection) {
740
- const attachmentObj = typeof attachment.toJSON === "function" ? attachment.toJSON() : { ...attachment };
755
+ const attachmentObj2 = typeof attachment.toJSON === "function" ? attachment.toJSON() : { ...attachment };
741
756
  const collection = this.resolveCollection(
742
- recordCollection || attachmentObj.collectionName || attachment.collectionName
757
+ recordCollection || attachmentObj2.collectionName || attachment.collectionName
743
758
  );
744
- const storageId = await this.resolveStorageId(attachment, attachmentObj, fileManager, collection);
759
+ const storageId = await this.resolveStorageId(attachment, attachmentObj2, fileManager, collection);
745
760
  if (!isMissingFileValue(storageId)) {
746
- attachmentObj.storageId = storageId;
761
+ attachmentObj2.storageId = storageId;
747
762
  }
748
- this.copyFileFieldsFromRecord(attachment, attachmentObj);
749
- await this.ensureFileFields(attachment, attachmentObj, collection);
750
- this.copyFileFieldsFromRecord(attachment, attachmentObj);
751
- if (attachmentObj.storageId && attachmentObj.url) {
752
- const storageModel = getStorageFromCache(fileManager.storagesCache, attachmentObj.storageId);
753
- if (storageModel) {
754
- const baseUrl = storageModel.baseUrl || "";
755
- let relativeUrl = attachmentObj.url.split("?")[0];
763
+ this.copyFileFieldsFromRecord(attachment, attachmentObj2);
764
+ await this.ensureFileFields(attachment, attachmentObj2, collection);
765
+ this.copyFileFieldsFromRecord(attachment, attachmentObj2);
766
+ if (attachmentObj2.storageId && attachmentObj2.url) {
767
+ const storageModel2 = getStorageFromCache(fileManager.storagesCache, attachmentObj2.storageId);
768
+ if (storageModel2) {
769
+ const baseUrl = storageModel2.baseUrl || "";
770
+ let relativeUrl = attachmentObj2.url.split("?")[0];
756
771
  if (baseUrl && relativeUrl.includes(baseUrl)) {
757
772
  relativeUrl = relativeUrl.substring(relativeUrl.indexOf(baseUrl) + baseUrl.length);
758
773
  }
@@ -761,16 +776,16 @@ class PluginFilePreviewAuthServer extends import_server.Plugin {
761
776
  const parts = relativeUrl.split("/");
762
777
  const filename = parts.pop();
763
778
  const filePath = parts.join("/");
764
- if (filename && (!attachmentObj.filename || attachmentObj.filename === "file")) {
765
- attachmentObj.filename = filename;
779
+ if (filename && (!attachmentObj2.filename || attachmentObj2.filename === "file")) {
780
+ attachmentObj2.filename = filename;
766
781
  }
767
- if (filePath && !attachmentObj.path) {
768
- attachmentObj.path = filePath;
782
+ if (filePath && !attachmentObj2.path) {
783
+ attachmentObj2.path = filePath;
769
784
  }
770
785
  }
771
786
  }
772
787
  }
773
- return attachmentObj;
788
+ return attachmentObj2;
774
789
  }
775
790
  resolveCollection(recordCollection) {
776
791
  if (!recordCollection) {
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.3.9",
9
+ "version": "1.3.10",
10
10
  "main": "dist/server/index.js",
11
11
  "files": [
12
12
  "dist",
@@ -1,282 +1,256 @@
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
- import React, { useCallback, useEffect, useMemo, useState } from 'react';
11
- import { FileTextOutlined, RobotOutlined } from '@ant-design/icons';
12
- import { Button, Dropdown, Space, Tooltip, message } from 'antd';
13
- import type { MenuProps } from 'antd';
14
- import type { Application } from '@nocobase/client';
15
- import { useChatBoxActions, useAIConfigRepository, type AIEmployee } from '@nocobase/plugin-ai/client';
16
- import { useT } from './locale';
17
-
18
- export const FILE_PREVIEW_WORK_CONTEXT_TYPE = 'file-preview';
19
-
20
- const AI_EMPLOYEE_STORAGE_KEY = 'plugin-file-preview-auth.aiEmployee';
21
-
22
- function getFileDisplayName(file: any): string {
23
- if (!file) return 'file';
24
- if (file.title && file.extname) return `${file.title}${file.extname}`;
25
- return file.filename || file.name || file.title || 'file';
26
- }
27
-
28
- function getFileContextUid(file: any): string {
29
- const stableValue = file?.id ?? file?.uid ?? file?.url ?? file?.path ?? getFileDisplayName(file);
30
- return `file-preview:${String(stableValue)}`;
31
- }
32
-
33
- function normalizePreviewFile(file: any) {
34
- return {
35
- id: file?.id,
36
- uid: file?.uid,
37
- url: file?.url,
38
- preview: file?.preview,
39
- filename: file?.filename || file?.name,
40
- name: file?.name || file?.filename,
41
- title: file?.title,
42
- extname: file?.extname,
43
- mimetype: file?.mimetype,
44
- size: file?.size,
45
- path: file?.path,
46
- storageId: file?.storageId ?? file?.storage_id ?? file?.storage?.id,
47
- storage_id: file?.storage_id,
48
- storageType: file?.storageType || file?.storage?.type,
49
- storageName: file?.storageName || file?.storage?.name,
50
- storage: file?.storage,
51
- collectionName: file?.collectionName,
52
- };
53
- }
54
-
55
- export function createFilePreviewWorkContext(file: any) {
56
- return {
57
- type: FILE_PREVIEW_WORK_CONTEXT_TYPE,
58
- uid: getFileContextUid(file),
59
- title: getFileDisplayName(file),
60
- content: {
61
- source: 'plugin-file-preview-auth',
62
- file: normalizePreviewFile(file),
63
- },
64
- };
65
- }
66
-
67
- function getStoredAIEmployeeUsername() {
68
- try {
69
- return window.localStorage.getItem(AI_EMPLOYEE_STORAGE_KEY) || '';
70
- } catch {
71
- return '';
72
- }
73
- }
74
-
75
- function setStoredAIEmployeeUsername(username: string) {
76
- try {
77
- window.localStorage.setItem(AI_EMPLOYEE_STORAGE_KEY, username);
78
- } catch {
79
- // Ignore storage restrictions in embedded/sandboxed clients.
80
- }
81
- }
82
-
83
- function getEmployeeLabel(employee: AIEmployee) {
84
- return employee?.nickname || employee?.username || '';
85
- }
86
-
87
- class AIFilePreviewActionBoundary extends React.Component<{ children: React.ReactNode }, { hasError: boolean }> {
88
- constructor(props: { children: React.ReactNode }) {
89
- super(props);
90
- this.state = { hasError: false };
91
- }
92
-
93
- static getDerivedStateFromError() {
94
- return { hasError: true };
95
- }
96
-
97
- render() {
98
- if (this.state.hasError) {
99
- return null;
100
- }
101
- return this.props.children;
102
- }
103
- }
104
-
105
- const AIFilePreviewActionInner: React.FC<{ file: any }> = ({ file }) => {
106
- const t = useT();
107
- const aiConfigRepository = useAIConfigRepository();
108
- const { triggerTask } = useChatBoxActions();
109
- const [employees, setEmployees] = useState<AIEmployee[]>([]);
110
- const [loading, setLoading] = useState(false);
111
- const [asking, setAsking] = useState(false);
112
-
113
- useEffect(() => {
114
- let cancelled = false;
115
- if (!aiConfigRepository?.getAIEmployees) {
116
- return;
117
- }
118
-
119
- const cached = aiConfigRepository.aiEmployees || [];
120
- if (cached.length) {
121
- setEmployees([...cached]);
122
- return;
123
- }
124
-
125
- setLoading(true);
126
- aiConfigRepository
127
- .getAIEmployees()
128
- .then((list) => {
129
- if (!cancelled) {
130
- setEmployees([...(list || [])]);
131
- setLoading(false);
132
- }
133
- })
134
- .catch(() => {
135
- if (!cancelled) {
136
- setEmployees([]);
137
- setLoading(false);
138
- }
139
- });
140
-
141
- return () => {
142
- cancelled = true;
143
- };
144
- }, [aiConfigRepository]);
145
-
146
- const orderedEmployees = useMemo(() => {
147
- const selected = getStoredAIEmployeeUsername();
148
- if (!selected) {
149
- return employees;
150
- }
151
- return [...employees].sort((a, b) => {
152
- if (a.username === selected) return -1;
153
- if (b.username === selected) return 1;
154
- return 0;
155
- });
156
- }, [employees]);
157
-
158
- const openAIChat = useCallback(
159
- async (employee: AIEmployee) => {
160
- if (!employee || !file) {
161
- return;
162
- }
163
-
164
- setAsking(true);
165
- try {
166
- setStoredAIEmployeeUsername(employee.username);
167
- await triggerTask({
168
- aiEmployee: employee,
169
- tasks: [
170
- {
171
- title: getFileDisplayName(file),
172
- message: {
173
- user: t('Please help me analyze the file currently open in preview.'),
174
- workContext: [createFilePreviewWorkContext(file)],
175
- },
176
- autoSend: false,
177
- },
178
- ],
179
- });
180
- } catch {
181
- message.error(t('Failed to open AI chat'));
182
- } finally {
183
- setAsking(false);
184
- }
185
- },
186
- [file, t, triggerTask],
187
- );
188
-
189
- const menuItems: MenuProps['items'] = orderedEmployees.map((employee) => ({
190
- key: employee.username,
191
- label: getEmployeeLabel(employee),
192
- onClick: () => openAIChat(employee),
193
- }));
194
-
195
- if (!loading && !orderedEmployees.length) {
196
- return null;
197
- }
198
-
199
- if (orderedEmployees.length === 1) {
200
- return (
201
- <Tooltip title={t('Ask AI')}>
202
- <Button
203
- type="text"
204
- size="small"
205
- icon={<RobotOutlined />}
206
- loading={asking || loading}
207
- onClick={(event) => {
208
- event.stopPropagation();
209
- openAIChat(orderedEmployees[0]);
210
- }}
211
- >
212
- {t('Ask AI')}
213
- </Button>
214
- </Tooltip>
215
- );
216
- }
217
-
218
- return (
219
- <Tooltip title={t('Ask AI')}>
220
- <Dropdown menu={{ items: menuItems }} trigger={['click']} placement="bottomRight" disabled={asking || loading}>
221
- <Button
222
- type="text"
223
- size="small"
224
- icon={<RobotOutlined />}
225
- loading={asking || loading}
226
- onClick={(event) => event.stopPropagation()}
227
- >
228
- {t('Ask AI')}
229
- </Button>
230
- </Dropdown>
231
- </Tooltip>
232
- );
233
- };
234
-
235
- export const AIFilePreviewAction: React.FC<{ file: any }> = ({ file }) => {
236
- return (
237
- <AIFilePreviewActionBoundary>
238
- <AIFilePreviewActionInner file={file} />
239
- </AIFilePreviewActionBoundary>
240
- );
241
- };
242
-
243
- export function registerFilePreviewAIWorkContext(app: Application) {
244
- let aiPlugin: any;
245
- try {
246
- aiPlugin = app.pm.get('ai') as any;
247
- } catch {
248
- return;
249
- }
250
- const aiManager = aiPlugin?.aiManager;
251
- if (!aiManager?.registerWorkContext) {
252
- return;
253
- }
254
-
255
- const options = {
256
- name: FILE_PREVIEW_WORK_CONTEXT_TYPE,
257
- tag: {
258
- Component: ({ item }: { item: any }) => (
259
- <Space>
260
- <FileTextOutlined />
261
- <span>{item?.title || ''}</span>
262
- </Space>
263
- ),
264
- },
265
- chatbox: {
266
- Component: ({ item }: { item: any }) => (
267
- <Space>
268
- <FileTextOutlined />
269
- <span>{item?.title || ''}</span>
270
- </Space>
271
- ),
272
- },
273
- };
274
-
275
- try {
276
- if (!aiManager.getWorkContext?.(FILE_PREVIEW_WORK_CONTEXT_TYPE)) {
277
- aiManager.registerWorkContext(FILE_PREVIEW_WORK_CONTEXT_TYPE, options);
278
- }
279
- } catch {
280
- // Duplicate registration can happen during hot reload. It is harmless.
281
- }
282
- }
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
+ import React, { useCallback, useEffect, useMemo, useState } from 'react';
11
+ import { FileTextOutlined, RobotOutlined } from '@ant-design/icons';
12
+ import { Button, Space, Tooltip, message } from 'antd';
13
+ import type { Application } from '@nocobase/client';
14
+ import { useChatBoxActions, useAIConfigRepository, type AIEmployee } from '@nocobase/plugin-ai/client';
15
+ import { useT } from './locale';
16
+
17
+ export const FILE_PREVIEW_WORK_CONTEXT_TYPE = 'file-preview';
18
+
19
+ const AI_EMPLOYEE_STORAGE_KEY = 'plugin-file-preview-auth.aiEmployee';
20
+
21
+ function getFileDisplayName(file: any): string {
22
+ if (!file) return 'file';
23
+ if (file.title && file.extname) return `${file.title}${file.extname}`;
24
+ return file.filename || file.name || file.title || 'file';
25
+ }
26
+
27
+ function getFileContextUid(file: any): string {
28
+ const stableValue = file?.id ?? file?.uid ?? file?.url ?? file?.path ?? getFileDisplayName(file);
29
+ return `file-preview:${String(stableValue)}`;
30
+ }
31
+
32
+ function normalizePreviewFile(file: any) {
33
+ return {
34
+ id: file?.id,
35
+ uid: file?.uid,
36
+ url: file?.url,
37
+ preview: file?.preview,
38
+ filename: file?.filename || file?.name,
39
+ name: file?.name || file?.filename,
40
+ title: file?.title,
41
+ extname: file?.extname,
42
+ mimetype: file?.mimetype,
43
+ size: file?.size,
44
+ path: file?.path,
45
+ storageId: file?.storageId ?? file?.storage_id ?? file?.storage?.id,
46
+ storage_id: file?.storage_id,
47
+ storageType: file?.storageType || file?.storage?.type,
48
+ storageName: file?.storageName || file?.storage?.name,
49
+ storage: file?.storage,
50
+ collectionName: file?.collectionName,
51
+ };
52
+ }
53
+
54
+ export function createFilePreviewWorkContext(file: any) {
55
+ return {
56
+ type: FILE_PREVIEW_WORK_CONTEXT_TYPE,
57
+ uid: getFileContextUid(file),
58
+ title: getFileDisplayName(file),
59
+ content: {
60
+ source: 'plugin-file-preview-auth',
61
+ file: normalizePreviewFile(file),
62
+ },
63
+ };
64
+ }
65
+
66
+ function getStoredAIEmployeeUsername() {
67
+ try {
68
+ return window.localStorage.getItem(AI_EMPLOYEE_STORAGE_KEY) || '';
69
+ } catch {
70
+ return '';
71
+ }
72
+ }
73
+
74
+ function setStoredAIEmployeeUsername(username: string) {
75
+ try {
76
+ window.localStorage.setItem(AI_EMPLOYEE_STORAGE_KEY, username);
77
+ } catch {
78
+ // Ignore storage restrictions in embedded/sandboxed clients.
79
+ }
80
+ }
81
+
82
+ class AIFilePreviewActionBoundary extends React.Component<{ children: React.ReactNode }, { hasError: boolean }> {
83
+ constructor(props: { children: React.ReactNode }) {
84
+ super(props);
85
+ this.state = { hasError: false };
86
+ }
87
+
88
+ static getDerivedStateFromError() {
89
+ return { hasError: true };
90
+ }
91
+
92
+ render() {
93
+ if (this.state.hasError) {
94
+ return null;
95
+ }
96
+ return this.props.children;
97
+ }
98
+ }
99
+
100
+ const AIFilePreviewActionInner: React.FC<{ file: any }> = ({ file }) => {
101
+ const t = useT();
102
+ const aiConfigRepository = useAIConfigRepository();
103
+ const { triggerTask } = useChatBoxActions();
104
+ const [employees, setEmployees] = useState<AIEmployee[]>([]);
105
+ const [loading, setLoading] = useState(false);
106
+ const [asking, setAsking] = useState(false);
107
+
108
+ useEffect(() => {
109
+ let cancelled = false;
110
+ if (!aiConfigRepository?.getAIEmployees) {
111
+ return;
112
+ }
113
+
114
+ const cached = aiConfigRepository.aiEmployees || [];
115
+ if (cached.length) {
116
+ setEmployees([...cached]);
117
+ return;
118
+ }
119
+
120
+ setLoading(true);
121
+ aiConfigRepository
122
+ .getAIEmployees()
123
+ .then((list) => {
124
+ if (!cancelled) {
125
+ setEmployees([...(list || [])]);
126
+ setLoading(false);
127
+ }
128
+ })
129
+ .catch(() => {
130
+ if (!cancelled) {
131
+ setEmployees([]);
132
+ setLoading(false);
133
+ }
134
+ });
135
+
136
+ return () => {
137
+ cancelled = true;
138
+ };
139
+ }, [aiConfigRepository]);
140
+
141
+ const orderedEmployees = useMemo(() => {
142
+ const selected = getStoredAIEmployeeUsername();
143
+ if (!selected) {
144
+ return employees;
145
+ }
146
+ return [...employees].sort((a, b) => {
147
+ if (a.username === selected) return -1;
148
+ if (b.username === selected) return 1;
149
+ return 0;
150
+ });
151
+ }, [employees]);
152
+
153
+ const openAIChat = useCallback(
154
+ async (employee: AIEmployee) => {
155
+ if (!employee || !file) {
156
+ return;
157
+ }
158
+
159
+ setAsking(true);
160
+ try {
161
+ setStoredAIEmployeeUsername(employee.username);
162
+ await triggerTask({
163
+ aiEmployee: employee,
164
+ tasks: [
165
+ {
166
+ title: getFileDisplayName(file),
167
+ message: {
168
+ user: t('Please help me analyze the file currently open in preview.'),
169
+ workContext: [createFilePreviewWorkContext(file)],
170
+ },
171
+ autoSend: false,
172
+ },
173
+ ],
174
+ });
175
+ } catch {
176
+ message.error(t('Failed to open AI chat'));
177
+ } finally {
178
+ setAsking(false);
179
+ }
180
+ },
181
+ [file, t, triggerTask],
182
+ );
183
+
184
+ if (!loading && !orderedEmployees.length) {
185
+ return null;
186
+ }
187
+
188
+ // Single click attaches the file content to the chat box using the preferred
189
+ // employee (last used, otherwise the first available) without listing employees.
190
+ return (
191
+ <Tooltip title={t('Ask AI')}>
192
+ <Button
193
+ type="text"
194
+ size="small"
195
+ icon={<RobotOutlined />}
196
+ loading={asking || loading}
197
+ disabled={!orderedEmployees.length}
198
+ onClick={(event) => {
199
+ event.stopPropagation();
200
+ openAIChat(orderedEmployees[0]);
201
+ }}
202
+ >
203
+ {t('Ask AI')}
204
+ </Button>
205
+ </Tooltip>
206
+ );
207
+ };
208
+
209
+ export const AIFilePreviewAction: React.FC<{ file: any }> = ({ file }) => {
210
+ return (
211
+ <AIFilePreviewActionBoundary>
212
+ <AIFilePreviewActionInner file={file} />
213
+ </AIFilePreviewActionBoundary>
214
+ );
215
+ };
216
+
217
+ export function registerFilePreviewAIWorkContext(app: Application) {
218
+ let aiPlugin: any;
219
+ try {
220
+ aiPlugin = app.pm.get('ai') as any;
221
+ } catch {
222
+ return;
223
+ }
224
+ const aiManager = aiPlugin?.aiManager;
225
+ if (!aiManager?.registerWorkContext) {
226
+ return;
227
+ }
228
+
229
+ const options = {
230
+ name: FILE_PREVIEW_WORK_CONTEXT_TYPE,
231
+ tag: {
232
+ Component: ({ item }: { item: any }) => (
233
+ <Space>
234
+ <FileTextOutlined />
235
+ <span>{item?.title || ''}</span>
236
+ </Space>
237
+ ),
238
+ },
239
+ chatbox: {
240
+ Component: ({ item }: { item: any }) => (
241
+ <Space>
242
+ <FileTextOutlined />
243
+ <span>{item?.title || ''}</span>
244
+ </Space>
245
+ ),
246
+ },
247
+ };
248
+
249
+ try {
250
+ if (!aiManager.getWorkContext?.(FILE_PREVIEW_WORK_CONTEXT_TYPE)) {
251
+ aiManager.registerWorkContext(FILE_PREVIEW_WORK_CONTEXT_TYPE, options);
252
+ }
253
+ } catch {
254
+ // Duplicate registration can happen during hot reload. It is harmless.
255
+ }
256
+ }
@@ -1,4 +1,10 @@
1
- import { extractOcrStatusRecord, getOcrAttachmentId, isOcrCompleteStatus, normalizeOcrAttachmentId } from '../index';
1
+ import {
2
+ extractOcrStatusRecord,
3
+ getOcrAttachmentId,
4
+ isOcrCapableCollection,
5
+ isOcrCompleteStatus,
6
+ normalizeOcrAttachmentId,
7
+ } from '../index';
2
8
 
3
9
  describe('file preview OCR client utils', () => {
4
10
  describe('normalizeOcrAttachmentId', () => {
@@ -38,6 +44,18 @@ describe('file preview OCR client utils', () => {
38
44
  });
39
45
  });
40
46
 
47
+ describe('isOcrCapableCollection', () => {
48
+ it('allows attachments and collection-less records', () => {
49
+ expect(isOcrCapableCollection({ id: 1 })).toBe(true);
50
+ expect(isOcrCapableCollection({ id: 1, collectionName: 'attachments' })).toBe(true);
51
+ expect(isOcrCapableCollection({ id: 1, collectionName: '' })).toBe(true);
52
+ });
53
+
54
+ it('rejects non-attachment collections like aiFiles', () => {
55
+ expect(isOcrCapableCollection({ id: 1, collectionName: 'aiFiles' })).toBe(false);
56
+ });
57
+ });
58
+
41
59
  describe('isOcrCompleteStatus', () => {
42
60
  it('only treats result statuses as completed', () => {
43
61
  expect(isOcrCompleteStatus('waiting-verify')).toBe(true);
@@ -157,6 +157,17 @@ export function getOcrAttachmentId(file: unknown): string | number | null {
157
157
  return null;
158
158
  }
159
159
 
160
+ // Server-side OCR (runOcr/getOcrStatus) only queries the `attachments` collection,
161
+ // so files from other collections (e.g. aiFiles in the AI chat) must skip OCR to
162
+ // avoid 404s from filePreviewAuth:getOcrStatus.
163
+ export function isOcrCapableCollection(file: unknown): boolean {
164
+ const inputRecord = isObjectRecord(file) ? file : {};
165
+ const previewRecord = getPreviewFileRecord(file);
166
+ const normalizedPreviewRecord = isObjectRecord(previewRecord) ? previewRecord : {};
167
+ const collectionName = normalizedPreviewRecord.collectionName ?? inputRecord.collectionName;
168
+ return collectionName == null || collectionName === '' || collectionName === 'attachments';
169
+ }
170
+
160
171
  const getFileExt = (file: any): string => {
161
172
  const record = getPreviewFileRecord(file);
162
173
  const value =
@@ -1277,7 +1288,7 @@ function AuthCatchAllModalPreviewer({ index, list, onSwitchIndex }: any) {
1277
1288
  const [ocrStatus, setOcrStatus] = useState<string>('no-ocr');
1278
1289
  const [ocrResultId, setOcrResultId] = useState<string | number | null>(null);
1279
1290
  const [ocrError, setOcrError] = useState<string | null>(null);
1280
- const ocrAttachmentId = useMemo(() => getOcrAttachmentId(file), [file]);
1291
+ const ocrAttachmentId = useMemo(() => (isOcrCapableCollection(file) ? getOcrAttachmentId(file) : null), [file]);
1281
1292
 
1282
1293
  const isOcrSupported = useMemo(() => {
1283
1294
  if (!file || !ocrAttachmentId) return false;
@@ -380,9 +380,23 @@ export class PluginFilePreviewAuthServer extends Plugin {
380
380
  ctx.attachment(attachmentObj.filename);
381
381
  ctx.body = stream;
382
382
  // S3 Private Bucket Handler
383
- } catch (err) {
383
+ } catch (err: any) {
384
384
  this.log.error(`[FilePreviewAuth] Error fetching stream for URL ${url}: ${err.message}`);
385
- ctx.throw(500, 'Failed to fetch the file from storage');
385
+ try {
386
+ require('fs').writeFileSync(
387
+ require('path').join(process.cwd(), 'preview_error.log'),
388
+ `Error fetching stream for URL ${url}:\n` +
389
+ `Time: ${new Date().toISOString()}\n` +
390
+ `Message: ${err.message}\n` +
391
+ `Stack: ${err.stack}\n` +
392
+ `Attachment: ${JSON.stringify(attachment, null, 2)}\n` +
393
+ `AttachmentObj: ${JSON.stringify(attachmentObj, null, 2)}\n` +
394
+ `StorageModel: ${JSON.stringify(storageModel, null, 2)}\n`
395
+ );
396
+ } catch (fsErr: any) {
397
+ this.log.error(`[FilePreviewAuth] Failed to write preview_error.log: ${fsErr.message}`);
398
+ }
399
+ ctx.throw(500, `Failed to fetch the file from storage: ${err.message}`);
386
400
  }
387
401
 
388
402
  await next();