@sqsoffice/slide 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +81 -2
  3. package/dist/THIRD-PARTY-NOTICES.txt +19871 -0
  4. package/dist/api-CLyi4j4N.js +4030 -0
  5. package/dist/api.js +1 -0
  6. package/dist/assets/engine/files-worker.js +1 -0
  7. package/dist/assets/engine/host-artifact-jgAXg8CH.js +1 -0
  8. package/dist/assets/engine/host-load-wasm-DyYR5qIL.js +1 -0
  9. package/dist/assets/engine/host-manifest.json +42 -0
  10. package/dist/assets/engine/host-pdf-import-BOPMPpUS.js +1 -0
  11. package/dist/assets/engine/host.js +1 -0
  12. package/dist/assets/engine/manifest.json +66 -0
  13. package/dist/assets/engine/office_web.js +1491 -0
  14. package/dist/assets/engine/office_web_bg.wasm +4 -0
  15. package/dist/assets/engine/worker.js +1 -0
  16. package/dist/assets/fonts/source-han-sans/2.005/LICENSE.txt +96 -0
  17. package/dist/assets/fonts/source-han-sans/2.005/SourceHanSansCN-Bold.otf +0 -0
  18. package/dist/assets/fonts/source-han-sans/2.005/SourceHanSansCN-Regular.otf +0 -0
  19. package/dist/assets/fonts/source-han-sans/2.005/manifest.json +20 -0
  20. package/dist/index.js +835 -0
  21. package/dist/package-manifest.json +181 -0
  22. package/dist/style.css +2 -0
  23. package/dist/types/app/lib/automation/protocol.d.ts +25 -0
  24. package/dist/types/app/lib/engine/client.d.ts +129 -0
  25. package/dist/types/app/lib/engine/docx.d.ts +67 -0
  26. package/dist/types/app/lib/engine/grid.d.ts +330 -0
  27. package/dist/types/app/lib/engine/image.d.ts +15 -0
  28. package/dist/types/app/lib/engine/markdown.d.ts +220 -0
  29. package/dist/types/app/lib/engine/pdf-import.d.ts +18 -0
  30. package/dist/types/app/lib/engine/pdf-ocr.d.ts +70 -0
  31. package/dist/types/app/lib/engine/pdf-output.d.ts +22 -0
  32. package/dist/types/app/lib/engine/pdf.d.ts +191 -0
  33. package/dist/types/app/lib/engine/presentation-clipboard.d.ts +26 -0
  34. package/dist/types/app/lib/engine/presentation-media.d.ts +156 -0
  35. package/dist/types/app/lib/engine/presentation.d.ts +145 -0
  36. package/dist/types/app/lib/engine/printing.d.ts +91 -0
  37. package/dist/types/app/lib/engine/protocol.d.ts +233 -0
  38. package/dist/types/app/lib/engine/script.d.ts +46 -0
  39. package/dist/types/app/lib/engine/sheet-clipboard.d.ts +42 -0
  40. package/dist/types/app/lib/engine/sheet-validation.d.ts +19 -0
  41. package/dist/types/app/lib/engine/view.d.ts +186 -0
  42. package/dist/types/app/lib/files/session.d.ts +114 -0
  43. package/dist/types/app/lib/files/storage.d.ts +20 -0
  44. package/dist/types/packages/slide/api.d.ts +4 -0
  45. package/dist/types/packages/slide/index.d.ts +5 -0
  46. package/dist/types/sdk/types.d.ts +59 -0
  47. package/package.json +40 -3
package/dist/api.js ADDED
@@ -0,0 +1 @@
1
+ export { r as EngineError, t as createApi } from "./api-CLyi4j4N.js";
@@ -0,0 +1 @@
1
+ import{t as e}from"./host-load-wasm-DyYR5qIL.js";const t=self;t.onmessage=async({data:n})=>{try{let{wasm:r}=await e();r.setRequestCancellation();let i=r.packageNativeFiles(n.format,n.main,JSON.stringify(n.paths),n.buffers.map(e=>new Uint8Array(e)));t.postMessage({bytes:i.buffer},[i.buffer])}catch(e){let n=`open_failed`,r=`完整资源目录读取失败`;try{let t=JSON.parse(String(e));n=t.code??n,r=t.message??r}catch{}t.postMessage({code:n,message:r})}};
@@ -0,0 +1 @@
1
+ var e=1;const t=2,n=e,r={sourceBytes:33554432,commandBytes:4194304,queuedTasks:32,queuedBytes:8388608,replayEntries:1024,replayBytes:16777216,artifactBytes:33554432,cancelGraceMs:400};function i(e){return[`docx_write`,`xlsx_write`,`pptx_write`,`pdf_write`,`markdown_write`,`text_write`].includes(e.kind)&&!e.dry_run}function a(){return typeof document>`u`&&typeof location<`u`?s(new URL(`../`,location.href).href):typeof __OFFICE_ASSET_BASE__==`string`?s(__OFFICE_ASSET_BASE__):new URL(`../`,import.meta.url).pathname}function o(e){return typeof e==`string`&&e.startsWith(`/`)&&!e.startsWith(`//`)&&e.endsWith(`/`)&&!/[?#\\]/.test(e)&&!Array.from(e).some(e=>e.charCodeAt(0)<=32)&&!e.split(`/`).some(e=>e===`.`||e===`..`)}function s(e){if(typeof location>`u`)throw Error(`Office resources require a browser`);if(typeof e!=`string`||!e.trim())throw Error(`Office assetBase must be a nonempty resource directory`);let t=new URL(e,location.href);if(![`http:`,`https:`].includes(t.protocol)||t.origin!==location.origin||t.username||t.password||t.search||t.hash)throw Error(`Office assetBase must be an HTTP(S) directory on the current origin`);let n=t.pathname.endsWith(`/`)?t.pathname:`${t.pathname}/`;if(!o(n))throw Error(`Invalid Office resource directory`);return n}function c(e,t=a()){if(!o(t)||e.startsWith(`/`)||e.split(`/`).includes(`..`))throw Error(`Invalid release resource path`);return`${t}${e}`}async function l(e){let t=await crypto.subtle.digest(`SHA-256`,e);return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function u(e){if(!e||typeof e!=`object`)throw Error(`Missing output manifest`);let t=e;if(new TextEncoder().encode(JSON.stringify(e)).byteLength>32768)throw Error(`Output manifest is too large`);if(t.kind!==`manifest`||!Number.isSafeInteger(t.revision)||t.revision<0||![`docx`,`sds`,`xlsx`,`sxs`,`pptx`,`pdf`,`markdown`,`text`].includes(t.format??``)||!Array.isArray(t.files)||t.files.length!==1)throw Error(`Invalid output manifest`);let n={docx:[`document.docx`],sds:[`document.sds.zip`],xlsx:[`document.xlsx`],sxs:[`document.sxs.zip`],pptx:[`document.pptx`],pdf:[`document.pdf`],markdown:[`document.md`,`document.md.zip`],text:[`document.txt`]},i=t.files[0];if(!n[t.format]?.includes(t.main??``)||i.relative_path!==t.main||i.role!==`main`||!Number.isSafeInteger(i.bytes)||i.bytes<+![`markdown`,`text`].includes(t.format)||i.bytes>r.artifactBytes||!/^[a-f0-9]{64}$/.test(i.sha256))throw Error(`Invalid output file`);return t}function d(e,t){let n=e=>JSON.stringify({id:e.id,name:e.name,revision:e.manifest.revision,format:e.manifest.format,main:e.manifest.main,files:e.manifest.files});return n(e)===n(t)}export{c as a,n as c,a as i,t as l,l as n,s as o,u as r,r as s,d as t,i as u};
@@ -0,0 +1 @@
1
+ import{a as e,c as t,l as n,n as r}from"./host-artifact-jgAXg8CH.js";async function i(){let i=await fetch(e(`engine/manifest.json`),{cache:`no-cache`});if(!i.ok)throw Error(`Engine manifest unavailable`);let a=await i.json(),o=a.wasm?.sha256,s=a.bindings?.sha256;if((a.protocolVersion??1)!==t||(a.replayVersion??2)!==n)throw Error(`The document engine protocol is incompatible with this page`);if(!o||!s||!/^[a-f0-9]{64}$/.test(o)||!/^[a-f0-9]{64}$/.test(s))throw Error(`Invalid engine version`);let c=await import(`${e(`engine/office_web.js`)}?v=${s}`),l=await fetch(`${e(`engine/office_web_bg.wasm`)}?v=${o}`);if(!l.ok)throw Error(`Document engine unavailable`);let u=await l.arrayBuffer();if(await r(u)!==o)throw Error(`Document engine version changed during loading`);return await c.default({module_or_path:u}),{wasm:c,identity:o}}export{i as t};
@@ -0,0 +1,42 @@
1
+ {
2
+ "protocolVersion": 1,
3
+ "replayVersion": 2,
4
+ "files": [
5
+ {
6
+ "file": "files-worker.js",
7
+ "bytes": 458,
8
+ "gzipBytes": 374,
9
+ "sha256": "300b2dc530ccff98aae0d84a6738ee69760a1bfdd364b5f824227cfd137c014b"
10
+ },
11
+ {
12
+ "file": "host.js",
13
+ "bytes": 42714,
14
+ "gzipBytes": 12489,
15
+ "sha256": "be7bc31d207e0bfa81a28ad924a150c3880f8a60a77f5a5221031b12735a622f"
16
+ },
17
+ {
18
+ "file": "worker.js",
19
+ "bytes": 14578,
20
+ "gzipBytes": 4824,
21
+ "sha256": "4205db8d72d960896567ff1beaf8ccef484f21bfdb2f09e5c671c319fba5c3b5"
22
+ },
23
+ {
24
+ "file": "host-artifact-jgAXg8CH.js",
25
+ "bytes": 2732,
26
+ "gzipBytes": 1272,
27
+ "sha256": "2fb78e3d16c3e99a7e5c966d99414961f0a6703521bbbf6a88bc504497ea841a"
28
+ },
29
+ {
30
+ "file": "host-load-wasm-DyYR5qIL.js",
31
+ "bytes": 850,
32
+ "gzipBytes": 486,
33
+ "sha256": "ba13a72ba42b390d87c1b8696e11fe5adb78daf22d3b5ff7b9c89ac0c9088e90"
34
+ },
35
+ {
36
+ "file": "host-pdf-import-BOPMPpUS.js",
37
+ "bytes": 1053,
38
+ "gzipBytes": 605,
39
+ "sha256": "5ad81514525f55ec4ad7e9edca011dd2006b327e873c4aa317f92898b507accf"
40
+ }
41
+ ]
42
+ }
@@ -0,0 +1 @@
1
+ import{s as e}from"./host-artifact-jgAXg8CH.js";function t(e){return e.sources.reduce((e,t)=>e+t.bytes.byteLength,0)}function n(e){return JSON.stringify({at:e.at,sources:e.sources.map(({bytes:e,...t})=>t)})}function r(t,r=!1){if(!t||!Number.isSafeInteger(t.at)||t.at<0||t.at>1e4||!Array.isArray(t.sources)||t.sources.length<1||t.sources.length>16)throw Error(`PDF 导入设置无效`);let i=0;for(let n of t.sources){if(!n||typeof n.name!=`string`||!n.name.length||n.name.length>1024||/[/\\\0]/.test(n.name)||!(n.bytes instanceof ArrayBuffer)||!n.bytes.byteLength||n.bytes.byteLength>e.sourceBytes||n.password!==void 0&&(typeof n.password!=`string`||n.password.length>4096||r&&n.password.length>0)||n.pages!==void 0&&(!Array.isArray(n.pages)||!n.pages.length||n.pages.length>1e4||n.pages.some(e=>!Number.isSafeInteger(e)||e<0||e>=1e4)))throw Error(`PDF 来源文件、密码或页码无效`);i+=n.bytes.byteLength}if(i>e.sourceBytes||new TextEncoder().encode(n(t)).byteLength>262144)throw Error(`PDF 导入源或设置超过容量上限`)}export{n,r,t};
@@ -0,0 +1 @@
1
+ import{a as e,c as t,i as n,l as r,n as i,o as a,s as o,u as s}from"./host-artifact-jgAXg8CH.js";import{r as c,t as l}from"./host-pdf-import-BOPMPpUS.js";var u=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`EngineError`}};function d(){let e=Date.now(),t=crypto.getRandomValues(new Uint32Array(2));return{seconds:String(Math.floor(e/1e3)),nanos:e%1e3*1e6,offset:-new Date(e).getTimezoneOffset()*60,seed:String(BigInt(t[0])<<32n|BigInt(t[1]))}}const f=()=>new u(`cancelled`,`请求已取消`),p=e=>new TextEncoder().encode(JSON.stringify(e)).byteLength,m=e=>p(e)+(e.kind===`pdf_import`?l(e.request):0);function h(e){return e.kind===`source_remote_resource`?e.bytes?[e.bytes]:[]:e.kind===`pdf_merge_copy`?e.sources:e.kind===`presentation_frame`?e.video?[e.video.pixels]:[]:e.kind===`pdf_ocr_load`?[e.detection,e.recognition,e.dictionary]:e.kind===`pdf_signed_output`?[e.certificate,e.privateKey]:[]}function g(e){if(e.kind===`open`&&(e.password=void 0),e.kind===`pdf_import`)for(let t of e.request.sources)t.password=void 0;if(e.kind===`view`&&(e.request.kind===`pdf_authenticate`&&(e.request.password=``),e.request.kind===`pdf_merge_copy`&&(e.request.passwords=void 0),e.request.kind===`pdf_signed_output`))for(let t of h(e.request))t.byteLength&&new Uint8Array(t).fill(0)}var _=class{worker;workerEpoch=0;ready=!1;closed=!1;recovering=!1;failed=!1;allowRecovery=!0;recoveryWaiters=[];listeners=new Set;queue=[];active;counter=0;cancelTimer;source;currentName=``;saving;replay=[];replayBytes=0;calculated=!1;inputLocale=`en-US`;currentValidationPolicy=`rules`;validationHandler;currentGeneration=0;currentRevision=0;activeCell;engineIdentity=``;resourceBase;constructor(e={}){this.resourceBase=e.assetBase===void 0?n():a(e.assetBase),this.spawn()}get generation(){return this.currentGeneration}get revision(){return this.currentRevision}get name(){return this.currentName}get savePending(){return!!this.saving}get preparedSaveReceipt(){return this.saving?.receipt?structuredClone(this.saving.receipt):void 0}get identity(){return this.engineIdentity}get recoveryAllowed(){return this.allowRecovery}whenReady(){return this.closed?Promise.reject(new u(`closed`,`会话已经关闭`)):this.failed?Promise.reject(new u(`engine_failure`,`文档引擎不可用`)):this.ready&&!this.recovering?Promise.resolve():new Promise((e,t)=>{let n=this.subscribe(r=>{r.phase===`ready`&&(n(),e()),(r.phase===`failed`||r.phase===`closed`)&&(n(),t(new u(r.phase===`closed`?`closed`:`engine_failure`,`文档引擎未能就绪`)))})})}whenIdle(){if(this.closed)return Promise.reject(new u(`closed`,`会话已经关闭`));if(this.failed)return Promise.reject(new u(`engine_failure`,`文档引擎不可用`));let e=()=>this.ready&&!this.recovering&&!this.active&&!this.queue.length;return e()?Promise.resolve():new Promise((t,n)=>{let r=this.subscribe(i=>{i.phase===`failed`||i.phase===`closed`?(r(),n(new u(`engine_failure`,`文档引擎未能恢复就绪`))):e()&&(r(),t())})})}history(e,t={}){return this.checkMutable(),this.enqueue({kind:`history`,action:e},t)}sheetClipboard(e,t={}){if(this.checkMutable(),t.replaceKey)throw new u(`invalid_argument`,`剪贴板操作不能合并或覆盖`);let n=JSON.stringify(e);if(p(e)>o.commandBytes)throw new u(`limit_exceeded`,`剪贴板请求超过 4 MiB`);return this.enqueue({kind:`sheet_clipboard`,request:JSON.parse(n)},t)}get locale(){return this.inputLocale}presentationClipboard(e,t={}){if(this.checkMutable(),t.replaceKey)throw new u(`invalid_argument`,`剪贴板操作不能合并或覆盖`);if(p(e)>o.commandBytes)throw new u(`limit_exceeded`,`剪贴板请求超过 4 MiB`);return this.enqueue({kind:`presentation_clipboard`,request:JSON.parse(JSON.stringify(e))},t)}importPdfPages(e,t={}){if(this.checkMutable(),t.replaceKey)throw new u(`invalid_argument`,`插入页面操作不能合并或覆盖`);try{c(e)}catch(e){throw new u(`invalid_argument`,e instanceof Error?e.message:`PDF 导入设置无效`)}return this.enqueue({kind:`pdf_import`,request:structuredClone(e)},t)}setInputLocale(e){if(this.checkMutable(),![`zh-CN`,`en-US`,`de-DE`,`en-GB`,`fr-FR`].includes(e))throw new u(`invalid_argument`,`输入地区无效`);this.inputLocale!==e&&(this.calculated=!1),this.inputLocale=e}get validationPolicy(){return this.currentValidationPolicy}setValidationPolicy(e){if(this.checkMutable(),![`rules`,`reject`,`prompt`,`allow`].includes(e))throw new u(`invalid_argument`,`输入验证策略无效`);this.currentValidationPolicy=e}setValidationHandler(e){this.validationHandler=e,!e&&this.active?.phase===`confirming`&&this.cancel(this.active)}prepareSave(e=this.currentName,t={}){if(this.checkAvailable(),this.checkMutable(),!e||e.length>1024||/[/\\\0]/.test(e))throw new u(`invalid_argument`,`需要有效的保存文件名`);let n=crypto.randomUUID();this.saving={id:n,name:e};try{let r=this.enqueue({kind:`prepare_save`,id:n,name:e},t),i=r.result.catch(e=>{throw this.saving?.id===n&&(this.saving=void 0),e});return{...r,result:i}}catch(e){throw this.saving=void 0,e}}commitSave(e){if(this.saving?.id!==e||!this.saving.receipt)throw new u(`busy`,`保存候选不存在或尚未准备完成`);return this.enqueue({kind:`commit_save`,receipt:structuredClone(this.saving.receipt)},{})}discardSave(e){if(this.saving?.id!==e)throw new u(`busy`,`保存候选不存在或已经失效`);return this.enqueue({kind:`discard_save`,id:e},{})}readPreparedSave(){if(!this.saving?.receipt)throw new u(`busy`,`没有已准备的保存副本`);return this.enqueue({kind:`read_save`,receipt:structuredClone(this.saving.receipt)},{})}get cancellationMode(){return globalThis.crossOriginIsolated&&typeof SharedArrayBuffer<`u`?`cooperative`:`restart`}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}open(e,t,n={},r){if(this.checkAvailable(),this.checkMutable(),t.byteLength>o.sourceBytes)throw new u(`limit_exceeded`,`文件超过 32 MiB 输入上限`);if(r!==void 0&&r.length>2048)throw new u(`invalid_argument`,`PDF 密码过长`);return n.signal?.aborted?this.enqueue({kind:`open`,name:e,bytes:t.slice(0),password:r},n):(this.cancelPending(),this.currentGeneration++,this.enqueue({kind:`open`,name:e,bytes:t.slice(0),password:r},n))}command(e,t={}){e.kind!==`status`&&this.checkMutable();let n=JSON.stringify(e);if(new TextEncoder().encode(n).byteLength>o.commandBytes)throw new u(`limit_exceeded`,`命令超过 4 MiB 上限`);if(t.replaceKey&&s(e))throw new u(`invalid_argument`,`编辑命令不能合并或覆盖`);return this.enqueue({kind:`command`,command:JSON.parse(n)},t)}exportBytes(e={}){return this.checkMutable(),this.enqueue({kind:`export`},e)}exportCopy(e,t={}){return this.checkMutable(),this.enqueue({kind:`export_copy`,format:e},t)}view(e,t={}){if(this.checkMutable(),e.kind===`presentation_frame`&&e.video){let{width:t,height:n,pixels:r}=e.video;if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n)||t<1||n<1||t>960||n>540||!(r instanceof ArrayBuffer)||r.byteLength!==t*n*4)throw new u(`limit_exceeded`,`视频采样帧无效或超过 960 × 540 像素上限`)}let n=h(e),r=e.kind===`pdf_ocr_load`||e.kind===`pdf_merge_copy`?33554432:e.kind===`source_remote_resource`?16777216:o.queuedBytes;if(n.some(e=>!(e instanceof ArrayBuffer))||n.reduce((e,t)=>e+t.byteLength,0)>r)throw new u(`limit_exceeded`,`请求中的二进制内容超过上限`);if(e.kind===`pdf_signed_output`&&(e.certificate.byteLength>1048576||e.privateKey.byteLength>65536))throw new u(`limit_exceeded`,`证书限 1 MiB,私钥限 64 KiB`);if(e.kind===`pdf_authenticate`&&e.password.length>2048)throw new u(`invalid_argument`,`PDF 密码过长`);if(e.kind===`pdf_merge_copy`&&(e.sources.length<1||e.sources.length>15||e.passwords&&(e.passwords.length!==e.sources.length||e.passwords.some(e=>e.length>2048))))throw new u(`invalid_argument`,`合并需要 1~15 份追加 PDF 及匹配的密码列表`);let i={kind:`view`,request:e.kind===`source_remote_resource`?structuredClone(e,{transfer:n}):structuredClone(e)};try{return this.enqueue(i,t)}catch(e){throw g(i),e}}input(e,t={}){if(this.checkMutable(),t.replaceKey)throw new u(`invalid_argument`,`输入操作不能合并或覆盖`);if(p(e)>o.commandBytes)throw new u(`limit_exceeded`,`输入内容超过 4 MiB 上限`);return this.enqueue({kind:`input`,input:structuredClone(e)},t)}runScript(e,t={}){if(this.checkMutable(),t.replaceKey)throw new u(`invalid_argument`,`脚本运行不能合并或覆盖`);if(new TextEncoder().encode(e.source).byteLength>262144)throw new u(`limit_exceeded`,`脚本超过 256 KiB 上限`);return this.enqueue({kind:`script`,request:structuredClone(e)},t)}runMcp(e,t={}){if(this.checkMutable(),t.replaceKey)throw new u(`invalid_argument`,`MCP 请求不能合并或覆盖`);if(p(e)>o.commandBytes)throw new u(`limit_exceeded`,`MCP 请求超过 4 MiB`);return this.enqueue({kind:`mcp`,request:structuredClone(e)},t)}recover(){if(this.closed)return Promise.reject(new u(`closed`,`会话已经关闭`));if(!this.allowRecovery)return Promise.reject(new u(`unsupported`,`此会话的安全设置不允许自动恢复,请先保存副本再重新打开。`));let e=new Promise((e,t)=>this.recoveryWaiters.push({resolve:e,reject:t}));return this.recovering||this.restart(),e}close(){this.closed||(this.closed=!0,this.worker.terminate(),clearTimeout(this.cancelTimer),this.failPending(new u(`closed`,`会话已经关闭`)),this.recoveryWaiters.splice(0).forEach(({reject:e})=>e(new u(`closed`,`会话已经关闭`))),this.source=void 0,this.saving=void 0,this.replay=[],this.replayBytes=0,this.currentGeneration++,this.emit(`closed`),this.listeners.clear())}emit(e,t){let n={phase:e,requestId:t?.id,generation:t?.generation??this.currentGeneration,revision:this.currentRevision,queued:this.queue.length};for(let e of this.listeners)try{e(n)}catch(e){globalThis.reportError(e)}}enqueue(e,t){if(this.checkAvailable(),t={...t},t.replaceKey)for(let e of[...this.queue,...this.active?[this.active]:[]])e.options.replaceKey===t.replaceKey&&this.cancel(e);let n=e.kind===`open`?e.bytes.byteLength:p(e)+(e.kind===`view`?h(e.request).reduce((e,t)=>e+t.byteLength,0):e.kind===`pdf_import`?l(e.request):0),r=e.kind===`pdf_import`||e.kind===`view`&&(e.request.kind===`pdf_ocr_load`||e.request.kind===`pdf_merge_copy`||e.request.kind===`source_remote_resource`)?33619968:o.queuedBytes,i=this.queue.reduce((e,t)=>e+(t.operation.kind===`open`?0:t.bytes),0);if(this.queue.length>=o.queuedTasks||e.kind!==`open`&&i+n>r)throw new u(`busy`,`等待中的请求过多,请稍后重试`);let a,s,c=new Promise((e,t)=>{a=t=>e(t),s=t}),f={id:++this.counter,generation:this.currentGeneration,revision:this.currentRevision,operation:e,options:t,bytes:n,environment:{...d(),locale:this.inputLocale,validationPolicy:this.currentValidationPolicy,...e.kind!==`open`&&this.activeCell?{activeCell:{...this.activeCell}}:{}},phase:`queued`,settled:!1,resolve:a,reject:s,cleanup:()=>{},replay:[]},m=()=>this.cancel(f);return f.cleanup=()=>t.signal?.removeEventListener(`abort`,m),t.signal?.addEventListener(`abort`,m,{once:!0}),this.queue.push(f),t.signal?.aborted?this.cancel(f):(this.emit(`queued`,f),this.pump()),{id:f.id,result:c,cancel:()=>this.cancel(f)}}checkAvailable(){if(this.closed)throw new u(`closed`,`会话已经关闭`);if(this.failed)throw new u(`engine_failure`,`引擎不可用,请先恢复会话`);if(this.recovering)throw new u(`busy`,`正在恢复最后确认的文档状态`)}checkMutable(){if(this.saving)throw new u(`busy`,`正在保存当前版本,请等待保存完成或取消保存`)}cancel(e){if(e.settled||e.phase===`committing`||e.operation.kind===`commit_save`||e.operation.kind===`discard_save`)return!1;let t=e.phase===`confirming`;return this.settle(e,f()),this.active===e?(e.phase=`cancelling`,t?(this.acknowledge(e,!0),!0):(e.flag&&Atomics.store(e.flag,0,1),this.allowRecovery&&(this.cancelTimer=setTimeout(()=>{this.active===e&&e.phase===`cancelling`&&this.restart()},e.flag?o.cancelGraceMs:0)),this.emit(`cancelling`,e),!0)):(this.queue=this.queue.filter(t=>t!==e),this.emit(`cancelled`,e),!0)}cancelPending(){for(let e of[...this.queue,...this.active?[this.active]:[]])this.cancel(e)}settle(e,t,n){e.settled||(e.settled=!0,e.confirmation?.abort(),e.cleanup(),g(e.operation),t?e.reject(t):e.resolve({requestId:e.id,generation:e.generation,revision:this.currentRevision,value:n,notices:e.response?.input?.warnings}))}pump(){if(!this.ready||this.active||this.closed||this.recovering)return;let e=this.queue.shift();if(!e)return;if(e.options.expectedRevision!==void 0&&e.options.expectedRevision!==this.currentRevision){this.settle(e,new u(`busy`,`文档已经变化,请刷新当前结果后重试`)),this.pump();return}let t=e.operation.kind===`command`&&s(e.operation.command)||e.operation.kind===`input`&&(`kind`in e.operation.input||e.operation.input.action!==`move`)||e.operation.kind===`script`||e.operation.kind===`mcp`||e.operation.kind===`pdf_import`||e.operation.kind===`sheet_clipboard`&&e.operation.request.action!==`inspect`||e.operation.kind===`presentation_clipboard`&&e.operation.request.action!==`inspect`||e.operation.kind===`history`,n=e.operation.kind===`prepare_save`,r=/\.(xlsx?|csv|tsv|sxs(?:\.zip)?)$/i.test(this.currentName),i=r&&(e.operation.kind===`export`||e.operation.kind===`view`||e.operation.kind===`command`&&e.operation.command.kind!==`status`),a=n?2:t&&r?3:1,c=n?36864:t?e.bytes+(r?1536:512):512;if(e.operation.kind!==`open`&&(t||n||i&&!this.calculated)&&(this.replay.length+a>o.replayEntries||this.replayBytes+c>o.replayBytes)){this.settle(e,new u(`limit_exceeded`,`本次会话恢复记录达到上限,请导出副本后重新打开`)),this.pump();return}this.active=e,e.revision=this.currentRevision,e.phase=`running`,this.cancellationMode===`cooperative`&&(e.flag=new Int32Array(new SharedArrayBuffer(4)));let l=e.operation.kind===`open`?{...e.operation,bytes:e.operation.bytes.slice(0)}:e.operation;this.post({kind:`run`,id:e.id,generation:e.generation,revision:e.revision,operation:l,environment:e.environment,cancellation:e.flag?.buffer},l.kind===`open`?[l.bytes]:l.kind===`view`&&(l.request.kind===`pdf_signed_output`||l.request.kind===`pdf_merge_copy`||l.request.kind===`pdf_ocr_load`||l.request.kind===`source_remote_resource`)?h(l.request):[])}post(e,t=[]){this.worker.postMessage(e,t)}spawn(){let t=++this.workerEpoch;this.ready=!1,this.failed=!1,this.worker=new Worker(e(`engine/worker.js`,this.resourceBase),{type:`module`,name:`office-document`}),this.worker.onmessage=({data:e})=>{t===this.workerEpoch&&!this.closed&&this.receive(e)},this.worker.onerror=e=>{e.preventDefault(),t===this.workerEpoch&&this.workerFailed()},this.worker.onmessageerror=()=>{t===this.workerEpoch&&this.workerFailed()}}receive(e){if(e.kind===`fatal`){this.workerFailed();return}if(e.kind===`ready`){if(e.protocolVersion!==t||e.replayVersion!==r||this.engineIdentity&&this.engineIdentity!==e.engine){this.worker.terminate(),this.ready=!1,this.recovering=!1,this.failed=!0;let e=new u(`incompatible_engine`,`文档引擎版本不兼容,当前会话未被替换`);this.failPending(e),this.recoveryWaiters.splice(0).forEach(({reject:t})=>t(e)),this.emit(`failed`);return}this.engineIdentity=e.engine,this.ready=!0,this.recovering?this.sendRestore():(this.emit(`ready`),this.pump());return}if(e.kind===`restored`){if(e.generation!==this.currentGeneration||e.revision!==this.currentRevision){this.workerFailed();return}this.recovering=!1,this.recoveryWaiters.splice(0).forEach(({resolve:e})=>e()),this.emit(`ready`),this.pump();return}let n=this.active;if(!(!n||n.id!==e.id||n.generation!==e.generation)){if(e.kind===`running`){n.phase===`running`&&this.emit(`running`,n);return}if(e.kind===`prepared`){if(clearTimeout(this.cancelTimer),n.response=e,e.calculated&&n.operation.kind!==`open`&&n.replay.push({kind:`command`,command:{kind:`xlsx_write`,target:`active`,write:{op:`batch_update`,requests:[{op:`recalculate`}]},dry_run:!1},environment:e.calculationEnvironment??n.environment,revision:n.revision}),e.input?.command){let t=p(e.input.command),r=e.input.sourceSelection?p(e.input.sourceSelection):0;(!s(e.input.command)||t>o.commandBytes||this.replayBytes+t+r+p(n.replay)+512>o.replayBytes)&&(e.error={code:`limit_exceeded`,message:`输入超过本次会话恢复记录上限`})}let t=e.script?.replay??e.mcp?.replay;if(t){let n=p(t);(n>o.commandBytes||this.replay.length+1>o.replayEntries||this.replayBytes+n+1024>o.replayBytes)&&(e.error={code:`limit_exceeded`,message:`脚本修改超过本次会话恢复记录上限,修改未提交`})}let r=e.error??(e.response?.kind===`error`?e.response:void 0),i=n.settled||n.generation!==this.currentGeneration||!!r;if(!i&&e.validation){this.confirmValidation(n,e.validation);return}this.acknowledge(n,i);return}if(e.kind===`committed`||e.kind===`discarded`){if(e.kind===`committed`)if(this.currentRevision=e.revision,this.allowRecovery=(n.operation.kind===`open`||this.allowRecovery)&&e.recoveryAllowed!==!1,this.allowRecovery||(this.replay=[],this.replayBytes=0),n.operation.kind===`open`)this.source={name:n.operation.name,bytes:n.operation.bytes},this.currentName=n.operation.name,this.replay=[],this.replayBytes=0,this.calculated=!1;else if(n.operation.kind===`command`&&s(n.operation.command)||n.operation.kind===`input`&&n.response?.input?.command)n.replay.push({kind:`command`,command:n.operation.kind===`command`?n.operation.command:n.response.input.command,environment:n.environment,revision:e.revision,...n.operation.kind===`input`&&n.response?.input?.sourceSelection?{sourceSelection:n.response.input.sourceSelection}:{},...n.validationConfirmed?{validationConfirmed:!0}:{}}),this.calculated=!1;else if((n.operation.kind===`script`||n.operation.kind===`mcp`)&&(n.response?.script?.replay||n.response?.mcp?.replay))n.replay.push({kind:`script`,replay:n.response.script?.replay??n.response.mcp?.replay,environment:n.environment,revision:e.revision});else if(n.operation.kind===`sheet_clipboard`&&n.operation.request.action!==`inspect`)n.replay.push({kind:`sheet_clipboard`,request:n.operation.request,environment:n.operation.request.action===`capture`?n.response?.calculationEnvironment??n.environment:n.environment,revision:e.revision,...n.validationConfirmed?{validationConfirmed:!0}:{}});else if(n.operation.kind===`presentation_clipboard`&&n.operation.request.action!==`inspect`)n.replay.push({kind:`presentation_clipboard`,request:n.operation.request,environment:n.environment,revision:e.revision});else if(n.operation.kind===`pdf_import`)n.replay.push({kind:`pdf_import`,request:n.operation.request,environment:n.environment,revision:e.revision});else if(n.operation.kind===`history`)n.replay.push({kind:`history`,action:n.operation.action,environment:n.environment,revision:e.revision});else if(n.operation.kind===`prepare_save`&&n.response?.save){let e={id:n.response.save.id,name:n.response.save.name,manifest:n.response.save.manifest};this.saving={id:e.id,name:e.name,receipt:structuredClone(e),environment:n.environment}}else n.operation.kind===`commit_save`?(n.replay.push({kind:`save`,receipt:n.operation.receipt,environment:this.saving?.environment??n.environment,revision:e.revision}),this.currentName=n.operation.receipt.name,this.saving=void 0):n.operation.kind===`discard_save`&&this.saving?.id===n.operation.id&&(this.saving=void 0);for(let e of this.allowRecovery?n.replay:[])this.replay.push(e),this.replayBytes+=m(e);this.calculated=e.calculated;let t=(e.response?.kind===`error`?e.response:void 0)??n.response?.error??(n.response?.response?.kind===`error`?n.response.response:void 0);if(t)this.settle(n,new u(t.code,t.message));else if(e.kind===`discarded`||n.generation!==this.currentGeneration)this.settle(n,f());else{if(n.operation.kind===`open`)this.activeCell=void 0;else if(n.operation.kind===`view`&&n.operation.request.kind===`grid_selection`){let e=n.response?.view;if(e?.context){let t=e.selection.active??e.selection.focus;this.activeCell={sheet:e.context.sheet_id,row:t.row,column:t.column}}}this.settle(n,void 0,e.response??n.response?.script??n.response?.mcp??n.response?.clipboard??n.response?.presentationClipboard??n.response?.pdfImport??n.response?.input?.selection??n.response?.view??n.response?.save??n.response?.copyExport??n.response?.bytes??n.response?.response)}this.active=void 0,this.emit(e.kind===`committed`?`completed`:`cancelled`,n),this.pump()}}}failPending(e){this.active&&this.settle(this.active,e);for(let t of this.queue)this.settle(t,e);this.active=void 0,this.queue=[]}acknowledge(e,t,n=!1){this.active!==e||this.closed||(t||(e.phase=`committing`,e.validationConfirmed=n,this.emit(`committing`,e)),this.post({kind:t?`discard`:`accept`,id:e.id,generation:e.generation,revision:e.revision,...n?{confirmValidation:!0}:{}}))}async confirmValidation(e,t){e.phase=`confirming`,e.confirmation=new AbortController,clearTimeout(this.cancelTimer),this.emit(`confirming`,e);let n=!1;try{this.validationHandler?n=await this.validationHandler(t,e.confirmation.signal):e.response&&(e.response.error={code:`validation_confirmation`,message:`输入不符合数据验证规则,整批修改未应用`})}catch{n=!1}this.active!==e||e.settled||e.confirmation.signal.aborted||this.closed||(!t.can_override&&e.response&&(e.response.error={code:`validation_rejected`,message:`输入不符合数据验证规则,整批修改未应用`}),this.acknowledge(e,!n||!t.can_override,n&&t.can_override))}sendRestore(){let e=this.source?{name:this.source.name,bytes:this.source.bytes.slice(0)}:void 0;this.post({kind:`restore`,generation:this.currentGeneration,revision:this.currentRevision,source:e,entries:this.replay,save:this.saving?.receipt&&this.saving.environment?{receipt:this.saving.receipt,environment:this.saving.environment}:void 0},e?[e.bytes]:[])}restart(){if(this.closed||this.recovering||!this.allowRecovery)return;clearTimeout(this.cancelTimer),this.worker.terminate();let e=this.queue.findLast(e=>e.operation.kind===`open`);this.queue=this.queue.filter(t=>t!==e),this.failPending(new u(`worker_restarted`,`引擎已重新启动,未确认的请求已取消`)),this.recovering=!0,this.currentGeneration++,e&&(e.generation=this.currentGeneration,this.queue.push(e)),this.emit(`recovering`),this.closed||this.spawn()}workerFailed(){if(!this.recovering&&this.ready&&this.allowRecovery){this.restart();return}this.worker.terminate(),this.ready=!1,this.recovering=!1,this.failed=!0;let e=new u(`engine_failure`,this.allowRecovery?`引擎恢复失败,最后确认的文档仍保留,可重试恢复`:`文档引擎已停止;此会话的安全设置禁止自动恢复,请重新打开已保存文件。`);this.failPending(e),this.recoveryWaiters.splice(0).forEach(({reject:t})=>t(e)),this.emit(`failed`)}};async function v(t,n,r,i){if(n?.aborted)throw new u(`cancelled`,`目录导入已取消`);if(!t.length||t.length>1024)throw new u(`limit_exceeded`,`目录最多包含 1024 个文件,总计不超过 32 MiB`);let a=r??t.map(e=>e.webkitRelativePath||e.name);if(a.length!==t.length)throw new u(`invalid_argument`,`目录文件与路径不一致`);let s=a.filter(e=>/\.(sds|sxs|md|markdown)$/i.test(e));if(s.length!==1)throw new u(`invalid_argument`,`请选择仅包含一份 SDS、SXS 或 Markdown 文档及其资源的目录`);let c=s[0],l=c.slice(0,c.lastIndexOf(`/`)+1);if(a.some(e=>!e.startsWith(l)))throw new u(`invalid_argument`,`资源必须位于主文档所在目录内`);let d=c.slice(l.length),f=/\.(md|markdown)$/i.test(d),p=t.map((e,t)=>({file:e,path:a[t].slice(l.length)})).filter(({path:e})=>f||e===d||e===`${d}.raw.xml`||e.startsWith(`${d}.assets/`));if(p.reduce((e,t)=>e+t.file.size,0)>o.sourceBytes)throw new u(`limit_exceeded`,`所选文档及资源超过 32 MiB 上限`);let m=p.map(({path:e})=>e),h=f?`markdown`:d.toLowerCase().endsWith(`.sds`)?`sds`:`sxs`,g=[];for(let{file:e}of p){if(n?.aborted)throw new u(`cancelled`,`目录导入已取消`);g.push(await e.arrayBuffer())}return new Promise((t,r)=>{let a=new Worker(e(`engine/files-worker.js`,i),{type:`module`,name:`office-file-import`}),o=()=>{a.terminate(),n?.removeEventListener(`abort`,s)},s=()=>{o(),r(new u(`cancelled`,`目录导入已取消`))};n?.addEventListener(`abort`,s,{once:!0}),a.onmessage=({data:e})=>{o(),e.bytes?t({name:`${d}.zip`,bytes:e.bytes}):r(new u(e.code??`open_failed`,e.message??`无法读取完整资源目录`))},a.onerror=e=>{e.preventDefault(),o(),r(new u(`engine_failure`,`资源导入失败,原文件未改变`))},a.onmessageerror=()=>{o(),r(new u(`engine_failure`,`资源导入结果无法读取`))},n?.aborted?s():a.postMessage({format:h,main:d,paths:m,buffers:g},g)})}async function y(e,t){let n=[],r=[],i=0,a=0;async function s(e,c,l){if(l>32)throw new u(`limit_exceeded`,`资源目录嵌套过深`);let d=e;if(typeof d.values!=`function`)throw new u(`unsupported_operation`,`当前浏览器无法遍历拖放目录,请使用目录选择器`);for await(let e of d.values()){if(t?.aborted)throw new u(`cancelled`,`目录导入已取消`);if(++i>1024)throw new u(`limit_exceeded`,`资源目录项目超过 1024 个`);let d=`${c}${e.name}`;if(e.kind===`directory`)await s(e,`${d}/`,l+1);else{let t=await e.getFile();if(a+=t.size,a>o.sourceBytes)throw new u(`limit_exceeded`,`资源目录超过 32 MiB 上限`);n.push(t),r.push(d)}}}return await s(e,``,0),{files:n,paths:r}}const b=Symbol.for(`office.retained-download`);function x(e,t){let n=window,r=n[b];if(!r){r={},n[b]=r;let e=r;window.addEventListener(`pagehide`,t=>{!t.persisted&&e.url&&(URL.revokeObjectURL(e.url),e.url=void 0)})}r.url&&URL.revokeObjectURL(r.url),r.url=void 0;let i=typeof e==`string`?e:URL.createObjectURL(e);typeof e!=`string`&&(r.url=i);let a=document.createElement(`a`);a.href=i,a.download=t,a.hidden=!0,document.body.append(a);try{a.click()}finally{a.remove()}}const S=[{description:`文档、文本、图片和完整资源包`,accept:{"application/msword":[`.doc`],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":[`.docx`],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":[`.xlsx`],"application/vnd.ms-excel":[`.xls`],"application/vnd.ms-powerpoint":[`.ppt`],"application/pdf":[`.pdf`],"application/vnd.openxmlformats-officedocument.presentationml.presentation":[`.pptx`],"text/csv":[`.csv`],"text/tab-separated-values":[`.tsv`],"text/markdown":[`.md`,`.markdown`],"text/plain":[`.txt`,`.log`],"image/svg+xml":[`.svg`,`.svgz`],"image/png":[`.png`],"image/jpeg":[`.jpg`,`.jpeg`],"image/bmp":[`.bmp`],"image/webp":[`.webp`],"application/json":[`.sds`,`.sxs`],"application/zip":[`.zip`]}}],C=e=>/\.(doc|docx|xls|xlsx|csv|tsv|ppt|pptx|pdf|sds|sxs|md|markdown|txt|log|svg|svgz|png|jpg|jpeg|bmp|webp|(?:sds|sxs|md|markdown)\.zip)$/i.test(e);function w(e,t){throw new u(e,t)}const T=e=>{e?.aborted&&w(`cancelled`,`操作已取消`)};async function E(e){let t=await e.getFile();return t.size>o.sourceBytes&&w(`limit_exceeded`,`文件超过 32 MiB 上限`),{bytes:t.size,modified:t.lastModified,sha256:await i(await t.arrayBuffer())}}const D=(e,t)=>e.bytes===t.bytes&&e.sha256===t.sha256;var O=class{validationHandler;requestPassword;confirmDiscard;engine;assetBase;access;detachEngine;listeners=new Set;lifecycle=new Set;handle;baseline;publication;fileAction=!1;deferFilePublication=!1;deferredFileEvent;selection=new AbortController;detachSelection;closed=!1;value={id:crypto.randomUUID(),name:``,dirty:!1,inputPending:!1,revision:0,savePhase:`idle`};beforeFileChange;whenIdle(){return this.engine.whenIdle()}constructor(e={}){this.assetBase=e.assetBase===void 0?n():a(e.assetBase),this.access=e.access?Object.freeze({...e.access}):void 0,this.engine=new _({assetBase:this.assetBase}),this.attach()}get state(){return{...this.value}}get changingFile(){return this.fileAction}setInputPending(e,t){e&&this.checkWritable(),!(this.closed||this.value.id!==t||this.value.inputPending===e)&&(this.value.inputPending=e,this.emit())}cancelOpen(){this.selection.abort()}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}emit(e){if(this.deferFilePublication){e&&(this.deferredFileEvent=e);return}let t=e??this.deferredFileEvent;this.deferredFileEvent=void 0;for(let e of this.listeners)try{e({...this.value},t)}catch(e){globalThis.reportError(e)}}attach(){this.engine.setValidationHandler(this.validationHandler),this.detachEngine=this.engine.subscribe(e=>this.emit(e))}check(){this.closed&&w(`closed`,`文件会话已经关闭`),this.fileAction&&w(`busy`,`正在切换文件,请稍后重试`)}checkChanging(){this.check(),this.value.savePhase!==`idle`&&w(`busy`,`请先完成当前保存事务`)}checkWritable(){this.access?.readOnly&&w(`read_only`,`此包仅提供浏览功能,请使用 @sqsoffice/kit 编辑`)}beginSelection(e){this.selection.abort(),this.detachSelection?.();let t=new AbortController;this.selection=t;let n=()=>t.abort();return e?.addEventListener(`abort`,n,{once:!0}),e?.aborted&&n(),this.detachSelection=()=>e?.removeEventListener(`abort`,n),t}checkSelection(e){(this.closed||e!==this.selection||e.signal.aborted)&&w(`cancelled`,`文件选择已被取消或替换`)}async status(){let e=(await this.engine.command({kind:`status`}).result).value;if(e.kind===`error`)throw new u(e.code,e.message);let t=e.value;this.value.dirty=t.unsaved===!0,this.value.canUndo=t.can_undo===!0,this.value.canRedo=t.can_redo===!0,this.value.sourceFormat=t.source_format,this.value.canSaveSource=t.can_save_source!==!1,this.value.importReport=t.import_report,this.value.recoveryAllowed=this.engine.recoveryAllowed,this.value.revision=this.engine.revision,this.value.name=this.engine.name,this.emit()}async command(e,t={}){this.check(),this.access?.checkCommand(e),e.kind!==`status`&&this.checkChanging();let n=await this.engine.command(e,t).result;return s(e)&&await this.status(),n}async history(e,t={}){this.checkWritable(),this.checkChanging();let n=await this.engine.history(e,t).result;return await this.status(),n}async sheetClipboard(e,t={}){this.checkWritable(),this.checkChanging();let n=await this.engine.sheetClipboard(e,t).result;return(e.action===`paste`||e.action===`paste_external`)&&await this.status(),n}get inputLocale(){return this.engine.locale}async importPdfPages(e,t={}){this.checkWritable(),this.checkChanging();let n=await this.engine.importPdfPages(e,t).result;return await this.status(),n}async presentationClipboard(e,t={}){this.checkWritable(),this.checkChanging();let n=await this.engine.presentationClipboard(e,t).result;return e.action===`paste`&&await this.status(),n}setInputLocale(e){this.checkWritable(),this.checkChanging(),this.engine.setInputLocale(e)}get validationPolicy(){return this.engine.validationPolicy}setValidationPolicy(e){this.checkWritable(),this.checkChanging(),this.engine.setValidationPolicy(e)}setValidationHandler(e){this.checkWritable(),this.validationHandler=e,this.engine.setValidationHandler(e)}async view(e,t={}){return this.checkChanging(),this.access?.checkView(e),this.engine.view(e,t).result}async input(e,t={}){this.checkWritable(),this.checkChanging();let n=await this.engine.input(e,t).result;return n.revision!==this.value.revision&&await this.status(),n}async openFile(e,t){this.checkChanging(),await this.openSelectedFile(e,t,this.beginSelection())}async runScript(e,t={}){this.checkWritable(),this.checkChanging();let n=await this.engine.runScript(e,t).result.catch(async e=>{throw await this.engine.whenIdle().catch(()=>{}),e});return await this.status(),n}async runMcp(e,t={}){this.checkWritable(),this.checkChanging();let n=await this.engine.runMcp(e,t).result.catch(async e=>{throw await this.engine.whenIdle().catch(()=>{}),e});return await this.status(),n}async authenticatePdf(e){this.checkChanging(),this.access?.checkView({kind:`pdf_authenticate`,password:e}),await this.engine.view({kind:`pdf_authenticate`,password:e}).result,await this.status()}async openSelectedFile(e,t,n){this.access?.checkFile(e.name),await this.beforeFileChange?.(),this.checkChanging(),this.checkSelection(n),C(e.name)||w(`unsupported_operation`,`请选择受支持的文字、表格、演示、Markdown、文本、SVG、图片或完整资源包`),e.size>o.sourceBytes&&w(`limit_exceeded`,`文件超过 32 MiB 上限`),this.fileAction=!0,this.deferFilePublication=!0;try{if(this.value.name&&(await this.status(),(this.value.dirty||this.value.inputPending)&&!await this.confirmDiscard?.(this.value.name)))throw new DOMException(`已保留当前文档`,`AbortError`);let r=await e.arrayBuffer(),a={bytes:r.byteLength,modified:e.lastModified,sha256:await i(r)};this.checkSelection(n);let o;try{for(;;){this.checkSelection(n);try{await this.engine.open(e.name,r,{signal:n.signal},o).result;break}catch(t){if(!(t instanceof u&&t.code===`unauthorized`&&/^PDF_PASSWORD_(REQUIRED|INVALID)/.test(t.message))||!this.requestPassword)throw t;if(o=await this.requestPassword(e.name,t.message.startsWith(`PDF_PASSWORD_INVALID`)),o===void 0)throw new DOMException(`已取消密码输入`,`AbortError`)}}}finally{o=void 0}this.value.id=crypto.randomUUID(),this.value.name=this.engine.name,this.value.revision=this.engine.revision,this.value.dirty=!1,this.value.inputPending=!1,this.handle=/\.(doc|xls|csv|tsv)$/i.test(e.name)?void 0:t,this.baseline=a,this.publication=void 0,this.value.savePhase=`idle`,this.value.saveError=void 0,await this.status()}finally{this.fileAction=!1,n===this.selection&&(this.detachSelection?.(),this.detachSelection=void 0),this.deferFilePublication=!1,this.emit()}}async pickFile(e){this.checkChanging();let t=this.beginSelection(),n=window.showOpenFilePicker;if(n){let r=(await n.call(window,{multiple:!1,types:S}))[0];r&&(await e?.(),await this.openSelectedFile(await r.getFile(),r,t));return}let r=await new Promise(e=>{let t=document.createElement(`input`);t.type=`file`,t.accept=`.doc,.docx,.xls,.xlsx,.csv,.tsv,.ppt,.pptx,.pdf,.sds,.sxs,.md,.markdown,.txt,.log,.svg,.svgz,.png,.jpg,.jpeg,.bmp,.webp,.zip`,t.addEventListener(`change`,()=>e(t.files?.[0]),{once:!0}),t.addEventListener(`cancel`,()=>e(void 0),{once:!0}),t.click()});r&&(await e?.(),await this.openSelectedFile(r,void 0,t))}async openDrop(e,t){this.checkChanging();let n=this.beginSelection(t),r=[...e.items].find(e=>e.kind===`file`)?.getAsFileSystemHandle?.(),i=[...e.files],a=await r;if(this.checkSelection(n),a?.kind===`directory`){let e=await y(a,n.signal),t=await v(e.files,n.signal,e.paths,this.assetBase);await this.openSelectedFile(new File([t.bytes],t.name,{type:`application/zip`}),void 0,n);return}if(i.length>1||i.some(e=>e.webkitRelativePath)){let e=await v(i,n.signal,void 0,this.assetBase);await this.openSelectedFile(new File([e.bytes],e.name,{type:`application/zip`}),void 0,n);return}if(a?.kind===`file`){let e=a;await this.openSelectedFile(await e.getFile(),e,n)}else i[0]?await this.openSelectedFile(i[0],void 0,n):w(`unsupported_operation`,`请通过目录选择器选择完整资源目录`)}async openDirectory(e,t){this.checkChanging();let n=this.beginSelection(t),r=await v(e,n.signal,void 0,this.assetBase);await this.openSelectedFile(new File([r.bytes],r.name,{type:`application/zip`}),void 0,n)}async pickDirectory(e){this.checkChanging();let t=this.beginSelection(e),n=await new Promise(e=>{let t=document.createElement(`input`);t.type=`file`,t.webkitdirectory=!0,t.addEventListener(`change`,()=>e([...t.files??[]]),{once:!0}),t.addEventListener(`cancel`,()=>e([]),{once:!0}),t.click()});if(n.length){let e=await v(n,t.signal,void 0,this.assetBase);await this.openSelectedFile(new File([e.bytes],e.name,{type:`application/zip`}),void 0,t)}}async pickSaveTarget(){this.checkWritable(),this.checkChanging(),this.value.canSaveSource===!1&&w(`unsupported`,`当前格式请通过导出副本保存`);let e=this.handle;if(!e){let t=window.showSaveFilePicker;t||w(`unsupported_operation`,`当前浏览器不支持直接写回文件,请下载副本`),e=await t.call(window,{suggestedName:this.value.name,types:S})}return e.requestPermission&&await e.requestPermission({mode:`readwrite`})!==`granted`&&w(`permission_denied`,`未获得文件写入权限,当前文档仍保留在本页`),e}async save(e,t){this.checkWritable(),this.check(),this.value.name||w(`no_document`,`尚未打开文档`),this.value.canSaveSource===!1&&w(`unsupported`,`此格式不支持原文件写回,请使用下载副本`),this.value.savePhase!==`idle`&&w(`busy`,`已有保存事务等待完成`);let n,r,a=!1,o=!1;this.value.saveError=void 0,this.value.savePhase=`permission`,this.emit();try{let s=e??this.handle;if(!s){let e=window.showSaveFilePicker;e||w(`unsupported_operation`,`当前浏览器不支持直接写回文件,请下载副本`),s=await e.call(window,{suggestedName:this.value.name,types:S})}s.requestPermission&&await s.requestPermission({mode:`readwrite`})!==`granted`&&w(`permission_denied`,`未获得文件写入权限,当前文档仍保留在本页`),T(t);let c=await E(s);this.handle&&this.baseline&&await s.isSameEntry(this.handle)&&!D(c,this.baseline)&&w(`conflict`,`原文件已被其他应用修改,请另存副本或重新打开`),this.value.savePhase=`preparing`,this.emit(),n=(await this.engine.prepareSave(s.name,{signal:t}).result).value,this.publication={stage:`prepared`,handle:s,before:c},await this.status(),T(t),D(c,await E(s))||w(`conflict`,`文件在准备保存期间发生了变化`),this.value.savePhase=`writing`,this.emit(),r=await s.createWritable({keepExistingData:!1}),await i(n.files[0])!==n.manifest.files[0].sha256&&w(`invalid_argument`,`保存候选内容已变化,未写入原文件`),await r.write(n.files[0]),T(t),D(c,await E(s))||w(`conflict`,`原文件在写入期间发生变化,保存已中止`),a=!0,await r.close(),r=void 0;let l=await E(s);return(l.sha256!==n.manifest.files[0].sha256||l.bytes!==n.manifest.files[0].bytes)&&w(`conflict`,`写入后的文件与保存候选不一致,文档仍保留未保存状态`),this.publication={stage:`published`,handle:s,before:c,after:l},this.value.savePhase=`confirming`,this.emit(),await this.confirm(n.id),o=!0,this.handle=s,this.baseline=l,this.publication=void 0,this.value.savePhase=`idle`,this.value.name=this.engine.name,this.value.revision=this.engine.revision,this.value.dirty=!1,this.emit(),{published:!0,confirmed:!0}}catch(e){if(o)return this.value.savePhase=`idle`,this.value.saveError=e instanceof Error?e.message:`文件已保存,状态更新未完成`,this.emit(),{published:!0,confirmed:!0};if(r&&!a&&await r.abort().catch(()=>{}),a&&n)return this.value.savePhase=`pending`,this.value.saveError=e instanceof Error?e.message:`保存确认待恢复`,this.emit(),{published:this.publication?.stage===`published`,confirmed:!1};if(n)try{await this.engine.discardSave(n.id).result}catch{if(this.engine.preparedSaveReceipt?.id===n.id)throw this.value.savePhase=`pending`,this.value.saveError=e instanceof Error?e.message:`保存取消待恢复`,this.emit(),e}throw this.publication=void 0,this.value.savePhase=`idle`,this.emit(),e}}async confirm(e){try{await this.engine.commitSave(e).result}catch(t){if(!(t instanceof u)||![`worker_restarted`,`engine_failure`].includes(t.code))throw t;await this.engine.recover(),await this.engine.commitSave(e).result}}async resumeSave(){this.checkWritable(),this.check();let e=this.publication,t=this.engine.preparedSaveReceipt;(!e||!t)&&w(`busy`,`没有待确认保存`),this.value.savePhase!==`pending`&&w(`busy`,`保存确认正在进行`);let n=this.value.id;this.value.savePhase=`confirming`,this.emit();let r=!1;try{e.handle.requestPermission&&await e.handle.requestPermission({mode:`read`})!==`granted`&&w(`permission_denied`,`未获得文件访问权限,待确认内容仍保留在本页`);let i=await E(e.handle),a=t.manifest.files[0];(this.value.id!==n||this.engine.preparedSaveReceipt?.id!==t.id)&&w(`busy`,`保存候选已经变化`),(i.sha256!==a.sha256||i.bytes!==a.bytes)&&w(`conflict`,`目标文件没有已准备的内容;请取消本次保存确认后重新保存副本`),this.publication={...e,stage:`published`,after:i},await this.confirm(t.id),r=!0,this.handle=e.handle,this.baseline=i,this.publication=void 0,this.value.name=this.engine.name,this.value.revision=this.engine.revision,this.value.dirty=!1,this.value.saveError=void 0}finally{this.value.savePhase=r?`idle`:`pending`,this.emit()}}async recover(){this.check(),await this.engine.recover(),await this.status()}async cancelPendingSave(){this.checkWritable(),this.check();let e=this.engine.preparedSaveReceipt;if(!e)return;this.value.savePhase!==`pending`&&w(`busy`,`保存正在进行,请等待当前写入结束`),this.value.savePhase=`cancelling`,this.emit();let t=!1;try{await this.engine.discardSave(e.id).result,t=!0,this.publication=void 0,await this.status(),this.value.saveError=void 0}finally{this.value.savePhase=t?`idle`:`pending`,this.emit()}}async downloadCopy(){this.checkWritable(),this.check(),this.value.canSaveSource===!1&&w(`unsupported_operation`,`兼容导入的文件需要选择导出新的文档或工作簿副本`);let e=this.engine.savePending?(await this.engine.readPreparedSave().result).value.files[0]:(await this.engine.exportBytes().result).value,t=/\.(sds|sxs)$/i.test(this.value.name)?`${this.value.name}.zip`:this.value.name;x(new Blob([e],{type:`application/octet-stream`}),t)}async downloadExportCopy(e){this.checkWritable(),this.checkChanging();let t=(await this.engine.exportCopy(e).result).value,n=this.value.name.replace(/\.(docx?|xlsx?|pptx?|pdf|csv|tsv|s[dx]s(?:\.zip)?|(?:md|markdown)(?:\.zip)?|txt|log|svgz?|png|jpe?g|bmp|webp)$/i,``),r=e===`original`?this.value.name:`${n}.${{docx:`docx`,sds:`sds.zip`,xlsx:`xlsx`,sxs:`sxs.zip`,pptx:`pptx`,pdf:`pdf`,markdown:`md`,markdown_bundle:`md.zip`,text:`txt`,html:`html`,original:``,png:`png`}[e]}`;return x(new Blob([t.bytes],{type:`application/octet-stream`}),r),t.report}bindLifecycle(e=window){let t=e=>{(this.value.dirty||this.value.inputPending||this.value.savePhase!==`idle`)&&(e.preventDefault(),e.returnValue=``)};e.addEventListener(`beforeunload`,t);let n=()=>{e.removeEventListener(`beforeunload`,t),this.lifecycle.delete(n)};return this.lifecycle.add(n),n}async close(e={}){if(!this.closed){await this.beforeFileChange?.(),this.check(),[`idle`,`pending`].includes(this.value.savePhase)||w(`busy`,`请等待文件写入结束后关闭`),this.fileAction=!0;try{if(this.value.name&&!e.discard&&(await this.status().catch(()=>{this.value.dirty=!0}),(this.value.dirty||this.value.inputPending||this.value.savePhase===`pending`)&&!await this.confirmDiscard?.(this.value.name)))throw new DOMException(`已保留当前文档`,`AbortError`);this.closed=!0,this.selection.abort(),this.detachSelection?.(),this.detachEngine?.(),this.engine.close(),this.listeners.clear();for(let e of[...this.lifecycle])e()}finally{this.fileAction=!1}}}};export{_ as BrowserEngine,O as BrowserFileSession,o as ENGINE_LIMITS,u as EngineError};
@@ -0,0 +1,66 @@
1
+ {
2
+ "rust": "1.98.1",
3
+ "target": "wasm32-unknown-unknown",
4
+ "wasmBindgen": "0.2.128",
5
+ "buildProfile": "web-release",
6
+ "wasmGzipBudgetBytes": 8388608,
7
+ "rustVersion": "rustc 1.98.1 (48a229cea 2026-09-01)",
8
+ "sourceRevision": "b9acd6c69df2ad490ef5baa4ce3302fc4e1752ed",
9
+ "sourceDirty": true,
10
+ "protocolVersion": 1,
11
+ "replayVersion": 2,
12
+ "wasm": {
13
+ "bytes": 44971980,
14
+ "gzipBytes": 14244367,
15
+ "sha256": "c182d83d10da462eff8724414923687db14338d0adf1c9f2161fa2e7e7747caa"
16
+ },
17
+ "optimization": {
18
+ "profile": "web-release"
19
+ },
20
+ "budget": {
21
+ "wasmGzipBytes": 8388608,
22
+ "withinBudget": false
23
+ },
24
+ "bindings": {
25
+ "bytes": 45783,
26
+ "sha256": "e3a0c0a7608615e2faeaf582bd0b6c6273fb23130a104e7e248dd55d011898de"
27
+ },
28
+ "host": [
29
+ {
30
+ "file": "files-worker.js",
31
+ "bytes": 458,
32
+ "gzipBytes": 374,
33
+ "sha256": "300b2dc530ccff98aae0d84a6738ee69760a1bfdd364b5f824227cfd137c014b"
34
+ },
35
+ {
36
+ "file": "host.js",
37
+ "bytes": 42714,
38
+ "gzipBytes": 12489,
39
+ "sha256": "be7bc31d207e0bfa81a28ad924a150c3880f8a60a77f5a5221031b12735a622f"
40
+ },
41
+ {
42
+ "file": "worker.js",
43
+ "bytes": 14578,
44
+ "gzipBytes": 4824,
45
+ "sha256": "4205db8d72d960896567ff1beaf8ccef484f21bfdb2f09e5c671c319fba5c3b5"
46
+ },
47
+ {
48
+ "file": "host-artifact-jgAXg8CH.js",
49
+ "bytes": 2732,
50
+ "gzipBytes": 1272,
51
+ "sha256": "2fb78e3d16c3e99a7e5c966d99414961f0a6703521bbbf6a88bc504497ea841a"
52
+ },
53
+ {
54
+ "file": "host-load-wasm-DyYR5qIL.js",
55
+ "bytes": 850,
56
+ "gzipBytes": 486,
57
+ "sha256": "ba13a72ba42b390d87c1b8696e11fe5adb78daf22d3b5ff7b9c89ac0c9088e90"
58
+ },
59
+ {
60
+ "file": "host-pdf-import-BOPMPpUS.js",
61
+ "bytes": 1053,
62
+ "gzipBytes": 605,
63
+ "sha256": "5ad81514525f55ec4ad7e9edca011dd2006b327e873c4aa317f92898b507accf"
64
+ }
65
+ ]
66
+ }