@docx-editor.dev/editor-api 2.31.0 → 2.32.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.
- package/OFFICE_JS_GUIDE.md +186 -11
- package/README.md +31 -3
- package/dist/agent.d.mts +243 -0
- package/dist/agent.d.ts +243 -0
- package/dist/agent.js +5 -0
- package/dist/agent.mjs +5 -0
- package/dist/browser.d.mts +7 -3
- package/dist/browser.d.ts +7 -3
- package/dist/browser.js +1 -1
- package/dist/browser.mjs +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{server-Dw4k9h0p.d.mts → server-BB94GFr9.d.mts} +738 -453
- package/dist/{server-Dw4k9h0p.d.ts → server-BB94GFr9.d.ts} +738 -453
- package/docs/accept-reject-without-scrolling.md +95 -0
- package/docs/comment-on-found-text.md +72 -0
- package/docs/custom-review-cards.md +178 -0
- package/docs/highlight-ranges.md +48 -0
- package/docs/index.md +36 -0
- package/docs/propose-rewrite.md +247 -0
- package/docs/tracked-replacement.md +68 -0
- package/package.json +11 -2
package/dist/agent.d.ts
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for AI agents that edit documents through the editing API.
|
|
3
|
+
*
|
|
4
|
+
* `prepareRewrite` reads a paragraph into text for a model, and `draft.apply()` proposes the
|
|
5
|
+
* model's new text as the fewest tracked changes. Fields, pictures, equations, note references,
|
|
6
|
+
* and locked content controls reach the model as numbered placeholders, so they change whole or
|
|
7
|
+
* not at all. Either every change lands and the paragraph reads as the model text, or the
|
|
8
|
+
* paragraph stays as it was and `apply()` throws a `RewriteError` with a stable `code`.
|
|
9
|
+
*
|
|
10
|
+
* You own the model call: the prompt, the instruction, retries, timeouts, and concurrency. The
|
|
11
|
+
* helpers own only the document side, which is deterministic.
|
|
12
|
+
*
|
|
13
|
+
* The helpers sit next to the object model, not on it, and are outside its Office.js
|
|
14
|
+
* compatibility scope. They use only the Office.js-shaped calls of
|
|
15
|
+
* `@docx-editor.dev/editor-api`, on the `context` and `paragraph` that you pass in.
|
|
16
|
+
*
|
|
17
|
+
* @example Rewrite the first paragraph on a server
|
|
18
|
+
* ```ts
|
|
19
|
+
* import { DocxEditor } from '@docx-editor.dev/editor-api';
|
|
20
|
+
* import { prepareRewrite } from '@docx-editor.dev/editor-api/agent';
|
|
21
|
+
*
|
|
22
|
+
* const runtime = await DocxEditor.createServer(bytes, { author: 'Rewrite agent' });
|
|
23
|
+
* try {
|
|
24
|
+
* await runtime.run(async (context) => {
|
|
25
|
+
* const paragraph = context.document.body.paragraphs.getFirst();
|
|
26
|
+
* const draft = await prepareRewrite(context, paragraph);
|
|
27
|
+
* const prompt = `Make the paragraph shorter.\n\n${draft.legend}\n\n${draft.text}`;
|
|
28
|
+
* await draft.apply(await callModel(prompt));
|
|
29
|
+
* });
|
|
30
|
+
* const saved = await runtime.save();
|
|
31
|
+
* } finally {
|
|
32
|
+
* runtime.dispose();
|
|
33
|
+
* }
|
|
34
|
+
* ```
|
|
35
|
+
*
|
|
36
|
+
* @packageDocumentation
|
|
37
|
+
* @public
|
|
38
|
+
*/
|
|
39
|
+
import { RequestContext, Paragraph } from '@docx-editor.dev/editor-api';
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Why a rewrite was refused or failed.
|
|
43
|
+
*
|
|
44
|
+
* - The model text broke a rule, and nothing was written. `draft.check()` returns these too.
|
|
45
|
+
* Send `error.message` back to the model and ask again with the same draft:
|
|
46
|
+
* `invalid-output`, `placeholder-missing`, `placeholder-unknown`, `placeholder-moved`,
|
|
47
|
+
* `placeholder-repeated`, `placeholder-grouped`.
|
|
48
|
+
* - The request context is in use, and nothing was written: `busy` when another helper call
|
|
49
|
+
* runs on it, such as two `apply()` calls at once, and `context-used` when commands are
|
|
50
|
+
* queued on it that are not synced.
|
|
51
|
+
* - The paragraph cannot take a rewrite now, and nothing was written: `pending-changes`,
|
|
52
|
+
* `tracking-unavailable`, `draft-used`, `too-long`, `unsupported-text`, `read-failed`.
|
|
53
|
+
* - A write or the final check failed, and the helper rejected the changes it had written:
|
|
54
|
+
* `stale`, `locked`, `write-failed`, `verification-failed`. After `stale` or
|
|
55
|
+
* `verification-failed`, another edit moved the paragraph: prepare it again, and ask the model
|
|
56
|
+
* again with the new draft.
|
|
57
|
+
* - The rollback failed too, or could not find the paragraph after another edit joined or
|
|
58
|
+
* removed it, so the document can hold some of the proposal: `rollback-failed`. Do not retry
|
|
59
|
+
* automatically.
|
|
60
|
+
*
|
|
61
|
+
* @public
|
|
62
|
+
*/
|
|
63
|
+
type RewriteErrorCode = 'invalid-output' | 'placeholder-missing' | 'placeholder-unknown' | 'placeholder-moved' | 'placeholder-repeated' | 'placeholder-grouped' | 'context-used' | 'busy' | 'pending-changes' | 'tracking-unavailable' | 'draft-used' | 'too-long' | 'unsupported-text' | 'read-failed' | 'stale' | 'locked' | 'write-failed' | 'verification-failed' | 'rollback-failed';
|
|
64
|
+
/**
|
|
65
|
+
* A refused or failed rewrite. Every code except `rollback-failed` leaves the paragraph as it
|
|
66
|
+
* was before the rewrite.
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```ts
|
|
70
|
+
* try {
|
|
71
|
+
* const draft = await prepareRewrite(context, paragraph);
|
|
72
|
+
* await draft.apply(await callModel(`${draft.legend}\n\n${draft.text}`));
|
|
73
|
+
* } catch (error) {
|
|
74
|
+
* if (error instanceof RewriteError && error.code === 'pending-changes') {
|
|
75
|
+
* // Decide the tracked changes in the paragraph first.
|
|
76
|
+
* } else throw error;
|
|
77
|
+
* }
|
|
78
|
+
* ```
|
|
79
|
+
*
|
|
80
|
+
* @public
|
|
81
|
+
*/
|
|
82
|
+
declare class RewriteError extends Error {
|
|
83
|
+
/** Always `'RewriteError'`. */
|
|
84
|
+
readonly name = "RewriteError";
|
|
85
|
+
/** What went wrong. See {@link RewriteErrorCode} for what to do next. */
|
|
86
|
+
readonly code: RewriteErrorCode;
|
|
87
|
+
/**
|
|
88
|
+
* Whether the model output broke a rule. The message then explains the rule in words that you
|
|
89
|
+
* can send back to the model.
|
|
90
|
+
*/
|
|
91
|
+
readonly isModelError: boolean;
|
|
92
|
+
/**
|
|
93
|
+
* A second error that happened while the helper cleaned up after this one, such as a failure
|
|
94
|
+
* to turn tracking off again. It never replaces this error.
|
|
95
|
+
*/
|
|
96
|
+
suppressed?: unknown;
|
|
97
|
+
constructor(code: RewriteErrorCode, message: string, options?: {
|
|
98
|
+
cause?: unknown;
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* What a placeholder stands for.
|
|
104
|
+
*
|
|
105
|
+
* @public
|
|
106
|
+
*/
|
|
107
|
+
type RewritePlaceholderKind = 'field' | 'content-control' | 'picture' | 'equation' | 'note-reference' | 'line-break';
|
|
108
|
+
/**
|
|
109
|
+
* One placeholder in the draft text, and what it stands for.
|
|
110
|
+
*
|
|
111
|
+
* @public
|
|
112
|
+
*/
|
|
113
|
+
interface RewritePlaceholder {
|
|
114
|
+
/** The placeholder as the model sees it, such as `⟦1⟧`. */
|
|
115
|
+
readonly placeholder: string;
|
|
116
|
+
/** What the placeholder stands for. */
|
|
117
|
+
readonly kind: RewritePlaceholderKind;
|
|
118
|
+
/**
|
|
119
|
+
* The text the paragraph reads for it: a field result, a control's text, U+000B for a line
|
|
120
|
+
* break, or U+FFFC for an equation, a picture, or a note reference.
|
|
121
|
+
*/
|
|
122
|
+
readonly text: string;
|
|
123
|
+
/**
|
|
124
|
+
* A description for the model, such as `field REF _Ref1 \h, reads "Section 4.2"`,
|
|
125
|
+
* `equation`, or `locked content control "party", reads "Acme Corp"`.
|
|
126
|
+
*/
|
|
127
|
+
readonly description: string;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* How to read the paragraph and check the model text.
|
|
132
|
+
*
|
|
133
|
+
* @public
|
|
134
|
+
*/
|
|
135
|
+
interface PrepareRewriteOptions {
|
|
136
|
+
/**
|
|
137
|
+
* Refuse model text that leaves out a placeholder, with `placeholder-missing`. By default, a
|
|
138
|
+
* left-out placeholder deletes what it stands for as one tracked deletion. `draft.legend`
|
|
139
|
+
* states the rule that applies.
|
|
140
|
+
*/
|
|
141
|
+
readonly keepPlaceholders?: boolean;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* A paragraph read for a model: plain data, plus `check()` and `apply()` for the model text.
|
|
145
|
+
*
|
|
146
|
+
* Build the prompt from `text` and `legend` with your own instruction, and call your model.
|
|
147
|
+
* Then call `apply()` in the same `run()` as `prepareRewrite`.
|
|
148
|
+
*
|
|
149
|
+
* @public
|
|
150
|
+
*/
|
|
151
|
+
interface RewriteDraft {
|
|
152
|
+
/** The paragraph's `uniqueLocalId`. */
|
|
153
|
+
readonly paragraphId: string;
|
|
154
|
+
/** The paragraph text as it reads now. */
|
|
155
|
+
readonly original: string;
|
|
156
|
+
/**
|
|
157
|
+
* The paragraph text with each field, picture, equation, note reference, line break, and
|
|
158
|
+
* locked control as a placeholder, such as `Subject to ⟦1⟧, the fee applies`. A paragraph that
|
|
159
|
+
* already contains `⟦` or `⟧` gets another bracket pair, such as `⟪1⟫`; read the exact
|
|
160
|
+
* placeholders from `placeholders`.
|
|
161
|
+
*/
|
|
162
|
+
readonly text: string;
|
|
163
|
+
/** Each placeholder in `text`, in order, and what it stands for. */
|
|
164
|
+
readonly placeholders: readonly RewritePlaceholder[];
|
|
165
|
+
/**
|
|
166
|
+
* The placeholder contract as plain text for a prompt: what a placeholder is, the rules (copy
|
|
167
|
+
* each kept placeholder exactly, leave one out to delete it, keep the order, do not repeat
|
|
168
|
+
* one), and one line per placeholder, such as `⟦1⟧ = equation`. An empty string when `text`
|
|
169
|
+
* has no placeholder.
|
|
170
|
+
*
|
|
171
|
+
* It holds no instruction and no paragraph text. The descriptions come from the file, so treat
|
|
172
|
+
* the legend as document data in your prompt, as you treat `text`.
|
|
173
|
+
*/
|
|
174
|
+
readonly legend: string;
|
|
175
|
+
/**
|
|
176
|
+
* Check model text without writing. Returns the {@link RewriteError} that `apply()` would
|
|
177
|
+
* throw before it writes, or `null` when `apply()` may go ahead. Most often the error is a
|
|
178
|
+
* model error (`error.isModelError`), whose message you can send back to the model. It can
|
|
179
|
+
* also be `draft-used`; `too-long`, when the text makes too many edits to compare; or
|
|
180
|
+
* `verification-failed`, when the text differs only in spacing that the helper cannot write.
|
|
181
|
+
*
|
|
182
|
+
* A `null` result does not promise that the write succeeds: the document can change, and
|
|
183
|
+
* `apply()` also checks the request context.
|
|
184
|
+
*/
|
|
185
|
+
check(modelText: string): RewriteError | null;
|
|
186
|
+
/**
|
|
187
|
+
* Propose the model text as the fewest tracked changes. Either every change lands and the
|
|
188
|
+
* paragraph reads as the model text, or the paragraph stays as it was and this throws a
|
|
189
|
+
* {@link RewriteError}. After a model error, you can call it again with new model text. Call
|
|
190
|
+
* it once at a time on a request context: a helper call that overlaps another throws `busy`.
|
|
191
|
+
*/
|
|
192
|
+
apply(modelText: string): Promise<RewriteResult>;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* What a proposed rewrite changed. Plain data.
|
|
196
|
+
*
|
|
197
|
+
* @public
|
|
198
|
+
*/
|
|
199
|
+
interface RewriteResult {
|
|
200
|
+
/** The paragraph's `uniqueLocalId`. */
|
|
201
|
+
readonly paragraphId: string;
|
|
202
|
+
/** The text before the rewrite: what rejecting every proposed change gives. */
|
|
203
|
+
readonly original: string;
|
|
204
|
+
/**
|
|
205
|
+
* The text after the rewrite: what accepting every proposed change gives. As in
|
|
206
|
+
* `getReviewedText`, an equation, a picture, or a note reference reads as U+FFFC, and a line
|
|
207
|
+
* break as U+000B.
|
|
208
|
+
*/
|
|
209
|
+
readonly proposed: string;
|
|
210
|
+
/**
|
|
211
|
+
* How many word edits the helper wrote: each run of changed words counts once. A replacement
|
|
212
|
+
* counts once, though `revisions.items` lists it as a `Delete` and an `Insert`. `0` when the
|
|
213
|
+
* model changed nothing.
|
|
214
|
+
*/
|
|
215
|
+
readonly changes: number;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Read a paragraph for a model. The draft is plain data: build a prompt from `draft.text` and
|
|
220
|
+
* `draft.legend` with your own instruction, call your model, and pass its text to
|
|
221
|
+
* `draft.apply()` in the same `run()`. `draft.check()` tests model text without writing.
|
|
222
|
+
*
|
|
223
|
+
* The helper never calls a model and never retries. It reads the paragraph, checks model text,
|
|
224
|
+
* and writes the fewest tracked changes, all or nothing.
|
|
225
|
+
*
|
|
226
|
+
* Throws a {@link RewriteError}: `pending-changes` when the paragraph has tracked changes,
|
|
227
|
+
* `tracking-unavailable` when the runtime has no author, `too-long` or `unsupported-text` when
|
|
228
|
+
* the paragraph cannot be compared, `read-failed` when the document refuses a read, `busy` when
|
|
229
|
+
* another helper call runs on the context, and `context-used` when edits are queued on it.
|
|
230
|
+
*
|
|
231
|
+
* @example
|
|
232
|
+
* ```ts
|
|
233
|
+
* const draft = await prepareRewrite(context, paragraph);
|
|
234
|
+
* const prompt = `Make this paragraph formal.\n\n${draft.legend}\n\n${draft.text}`;
|
|
235
|
+
* const result = await draft.apply(await callModel(prompt));
|
|
236
|
+
* ```
|
|
237
|
+
*
|
|
238
|
+
* @public
|
|
239
|
+
*/
|
|
240
|
+
declare function prepareRewrite(context: RequestContext, paragraph: Paragraph, options?: PrepareRewriteOptions): Promise<RewriteDraft>;
|
|
241
|
+
|
|
242
|
+
export { RewriteError, prepareRewrite };
|
|
243
|
+
export type { PrepareRewriteOptions, RewriteDraft, RewriteErrorCode, RewritePlaceholder, RewritePlaceholderKind, RewriteResult };
|
package/dist/agent.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
'use strict';var je=new Set(["invalid-output","placeholder-missing","placeholder-unknown","placeholder-moved","placeholder-repeated","placeholder-grouped"]),P=class extends Error{name="RewriteError";code;isModelError;suppressed;constructor(t,n,o){super(n,o?.cause===void 0?void 0:{cause:o.cause}),this.code=t,this.isModelError=je.has(t);}};function K(e){return e instanceof Error?e.message:String(e)}var ce=/[ \t]+$/,Ie=[{open:"\u27E6",close:"\u27E7"},{open:"\u27EA",close:"\u27EB"},{open:"\u2983",close:"\u2984"},{open:"\u27EC",close:"\u27ED"}];function de(e){let t=Ie.find(({open:n,close:o})=>!e.includes(n)&&!e.includes(o));if(!t)throw new P("unsupported-text","The paragraph contains every bracket pair the placeholders can use, so a placeholder could not be told apart from its text.");return t}var ae=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Y=({open:e,close:t},n,o="")=>new RegExp(`${o}${ae(e)}(\\d+)${ae(t)}`,n),We=/[\r\n]/,le=/[\u2028\u2029]/g,X=2e4,Le=2e3,ie=e=>e.replace(ce,""),se=e=>ce.exec(e)?.[0]??"",D=(e,t)=>`${t.open}${e}${t.close}`;function ue(e,t){return e.map(n=>n.atom===null?n.text:D(n.atom,t)).join("")}function pe(e,t,n){if(e.length===0)return "";let r=[`The text contains placeholders, such as ${D(1,n)}. Each one stands for content that you cannot edit, such as a field or an equation.`,t?"Keep every placeholder, and copy each one exactly as written.":"Copy each placeholder that you keep exactly as written. Leave a placeholder out to delete what it stands for.","Write the text around a placeholder as usual. Do not change the order of the placeholders, and do not repeat one."].join(" "),c=e.map(a=>`${a.placeholder} = ${a.description}`);return `${r}
|
|
2
|
+
|
|
3
|
+
Placeholders:
|
|
4
|
+
${c.join(`
|
|
5
|
+
`)}`}function fe(e,t,n,o,r){if(e==="")throw new P("invalid-output","The model output is empty. Return the paragraph.");let c=new Set(r.match(le)??[]),a=[...e.match(le)??[]].some(p=>!c.has(p));if(We.test(e)||a)throw new P("invalid-output","The model output contains a line break. Return one paragraph on one line.");let i=new Set(t.map(p=>p.placeholder)),f=new Set;for(let[p]of e.matchAll(Y(o,"g"))){if(!i.has(p))throw new P("placeholder-unknown",`The model output contains ${p}, which is not in the paragraph. Use only the listed placeholders.`);if(f.has(p))throw new P("placeholder-repeated",`The model output contains ${p} more than once. Keep each placeholder once.`);f.add(p);}if(n){let p=t.find(x=>!f.has(x.placeholder));if(p)throw new P("placeholder-missing",`The model output leaves out ${p.placeholder}. Keep every placeholder.`)}}function he(e,t,n){let o=new Map(t.map(r=>[r.placeholder,r.text]));return e.replace(Y(n,"g"),r=>o.get(r)??r)}function De(e,t){let n=Y(t,"","^"),o=[],r="",c=()=>{r!==""&&o.push({text:r,atom:null}),r="";};for(let a=0;a<e.length;){let i=e.startsWith(t.open,a)?n.exec(e.slice(a)):null;if(i){c(),o.push({text:i[0],atom:Number(i[1])}),a+=i[0].length;continue}let f=e[a];r+=f,a+=1,(f===" "||f===" ")&&c();}return c(),o}function He(e,t){let n=e.length,o=t.length,r=(h,w)=>{let u=e[h],l=t[w];return u.atom!==null||l.atom!==null?u.atom===l.atom:u.text===l.text?true:(h===n-1||w===o-1)&&ie(u.text)===ie(l.text)};if(n>X||o>X)throw Q();let c=Math.min(n+o,Le),a=c+1,i=new Int32Array(2*c+3),f=[],p=-1;for(let h=0;h<=c&&p<0;h+=1){f.push(i.slice(a-h-1,a+h+2));for(let w=-h;w<=h;w+=2){let u=w===-h||w!==h&&i[a+w-1]<i[a+w+1]?i[a+w+1]:i[a+w-1]+1,l=u-w;for(;u<n&&l<o&&r(u,l);)u+=1,l+=1;if(i[a+w]=u,u>=n&&l>=o){p=h;break}}}if(p<0)throw Q();let x=[],m=n,b=o;for(let h=p;h>0;h-=1){let w=f[h],u=C=>w[C+h+1],l=m-b,k=l===-h||l!==h&&u(l-1)<u(l+1),S=k?l+1:l-1,d=u(S),y=d-S;for(;m>d&&b>y;)m-=1,b-=1,x.push({kind:"keep",unit:m,token:t[b]});k?(b-=1,x.push({kind:"insert",token:t[b]})):(m-=1,x.push({kind:"delete",unit:m}));}for(;m>0&&b>0;)m-=1,b-=1,x.push({kind:"keep",unit:m,token:t[b]});return x.reverse()}var Q=()=>new P("too-long","The paragraph and the model output are too long to compare. Rewrite a shorter paragraph.");function F(e){if(e.length>X)throw Q()}function ge(e,t,n){let o=[],r=null,c="",a=0;for(let i of He(e,De(t,n))){if(i.kind==="keep"){r=null;let f=e[i.unit];i.unit===e.length-1&&f.atom===null&&se(f.text)===""&&(c=se(i.token.text)),a=i.unit+1;continue}if(i.kind==="insert"&&i.token.atom!==null)throw new P("placeholder-moved",`The model output moves ${D(i.token.atom,n)}. Keep the placeholders in their order.`);r||(r={from:a,to:a,text:c},c="",o.push(r)),i.kind==="delete"?(r.to=i.unit+1,a=i.unit+1):r.text+=i.token.text;}return o}var _e=Symbol.for("@docx-editor.dev/editor-api/queue");function Ke(e){let t=e[_e];return typeof t=="object"&&t!==null?t:null}var B=new WeakMap,Ue=()=>new P("busy","A helper call is in progress on this request context. Await it before you call context.sync().");async function z(e,t){if(B.has(e))throw new P("busy","Another rewrite helper call runs on this request context. Await it before you start the next one: apply drafts one after another.");V(e);let n={entering:false};B.set(e,n);let o=Object.getOwnPropertyDescriptor(e,"sync"),r=o?o.value??o.get?.call(e):Object.getPrototypeOf(e).sync,c=!o||o.configurable===true;c&&Object.defineProperty(e,"sync",{configurable:true,value:function(){return n.entering?r.call(this):Promise.reject(Ue())}});try{return await t()}finally{c&&(o?Object.defineProperty(e,"sync",o):delete e.sync),B.delete(e);}}async function E(e){let t=B.get(e),n;t&&(t.entering=true);try{n=e.sync();}finally{t&&(t.entering=false);}await n;}function V(e){let t=Ke(e)?.writes()??0;if(t!==0)throw new P("context-used",t===1?"1 edit is queued on the request context. Sync it before you call the helper, so that its tracked writes never send it.":`${t} edits are queued on the request context. Sync them before you call the helper, so that its tracked writes never send them.`)}var me=e=>e.includes("\uFFFC")||e.includes("\v");function ye(e){let t=[];for(let n=0;n<e.length;){let o=e[n];if(o.controls.length===0&&o.fields===0&&!me(o.text)){t.push({kind:"text",word:n}),n+=1;continue}if(o.controls.length===0&&o.fields>0){t.push(me(o.text)?{kind:"whole",first:n,last:n}:{kind:"field",word:n}),n+=1;continue}let r=Ne(e,n);t.push(r),n=(r.kind==="atoms"||r.kind==="whole"?r.last:n)+1;}return t}function Ne(e,t){let n=[],o=[],r=0,c=null,a=t;for(let u=t;u<e.length;u+=1){let l=e[u];if(u>t&&c===null)break;if(l.fields>0)return {kind:"whole",first:t,last:a};o.push(r),a=u;let k=0,S=0;if(c){if(l.controls[0]===void 0||!l.text.startsWith(c.rest.slice(0,1)))return {kind:"whole",first:t,last:a};let d=Math.min(c.rest.length,l.text.length);if(l.text.slice(0,d)!==c.rest.slice(0,d))return {kind:"whole",first:t,last:a};let y=n[c.atom];n[c.atom]={...y,end:r+d},k=d,S=1;let{rest:C,atom:R}=c;if(c=d<C.length?{rest:C.slice(d),atom:R}:null,c){r+=l.text.length;continue}}for(;S<l.controls.length;S+=1){let{text:d,start:y}=l.controls[S],R=y!==null&&y>=k&&l.text.startsWith(d,y)?y:y===null?l.text.indexOf(d,k):-1;if(R>=0){n.push({start:r+R,end:r+R+d.length,source:{type:"control",word:u,index:S}}),k=R+d.length;continue}let O=y!==null&&y>=k&&d.startsWith(l.text.slice(y))?y:Fe(l.text,d,k);if(O<0||S!==l.controls.length-1)return {kind:"whole",first:t,last:a};n.push({start:r+O,end:r+l.text.length,source:{type:"control",word:u,index:S}}),c={rest:d.slice(l.text.length-O),atom:n.length-1},k=l.text.length;}r+=l.text.length;}if(c)return {kind:"whole",first:t,last:a};let i=e.slice(t,a+1).map(u=>u.text).join("");for(let u=t;u<=a;u+=1){let l=e[u],k=o[u-t];for(let[S,d]of [["\uFFFC","object"],["\v","break"]]){let y=0;for(let C=l.text.indexOf(S);C>=0;C=l.text.indexOf(S,C+1)){let R=k+C;if(n.some(v=>v.start<=R&&R<v.end))return {kind:"whole",first:t,last:a};n.push({start:R,end:R+1,source:{type:d,word:u,index:y}}),y+=1;}}}n.sort((u,l)=>u.start-l.start);let f=[],p=[],x=u=>n.findIndex(l=>l.end===u),m=u=>n.findIndex(l=>l.start===u),b=u=>{let l=0;return o.forEach((k,S)=>{k<=u&&(l=S);}),l},h=0,w=u=>{for(;h<u;){let l=b(h),k=o[l+1]??i.length,S=Math.min(u,k),d=h===o[l]?null:x(h),y=S===k?null:m(S);if(d===-1||y===-1)return false;p.push({piece:f.length}),f.push({start:h,end:S,word:t+l,after:d,before:y}),h=S;}return true};for(let[u,l]of n.entries()){if(!w(l.start))return {kind:"whole",first:t,last:a};p.push({atom:u}),h=l.end;}return w(i.length)?{kind:"atoms",first:t,last:a,text:i,atoms:n,order:p,pieces:f}:{kind:"whole",first:t,last:a}}function Fe(e,t,n){for(let o=n;o<e.length;o+=1)if(t.startsWith(e.slice(o)))return o;return -1}var be=/[ \t]+$/,Be=32,L=32,Ge=3,I=e=>JSON.stringify(e),U=(e,t)=>({range:e,text:t,atom:null});function Z(e,t,n,o){return e.getRange(t).expandTo(n.getRange(o))}function ee(e,t=()=>true){return {parts:e,checks:(e??[]).filter(t).map(n=>({range:n.range,text:n.text}))}}var Re=(e,t)=>`field with code ${I(e.trim())}, `+(t===""?"shows no text":`reads ${I(t)}`);function Pe(e,t,n){return t.map(o=>{let r=Re(o,"");return {range:e,text:"",group:n,atom:()=>({kind:"field",description:r})}})}var Je=0,Ce=()=>++Je;async function Se(e,t){let n=t.getTextRanges([" "," "]),o=t.getRange("Whole").revisions,r=t.getRange("Whole").fields,c=t.contentControls;if(n.load("items/text"),o.load("items"),r.load("items"),c.load("items/cannotEdit"),t.load("uniqueLocalId"),await E(e),o.items.length>0)throw new P("pending-changes","The paragraph has tracked changes. Accept or reject them before you rewrite it.");F(n.items);let a=r.items.length>0,i=c.items.some(s=>s.cannotEdit),f=n.items,p=Math.ceil(f.length/L),x=Array.from({length:a||i?p:0},(s,g)=>{let T=f[g*L],A=f[Math.min(f.length,(g+1)*L)-1],q=T.expandTo(A),$=a?q.fields:null,M=i?q.contentControls:null;return $?.load("items"),M?.load("items/cannotEdit"),{fields:$,controls:M}}),m=s=>{let g=f[s-1],T=f[s],q=(g?g.getRange("End"):t.getRange("Start")).expandTo(T?T.getRange("Start"):t.getRange("End"));return {range:q,fields:a?q.fields:null}},b=Array.from({length:f.length+1},(s,g)=>a&&g%L===0?m(g):null);a&&f.length%L!==0&&(b[f.length]=m(f.length));for(let s of b)s?.fields?.load("items/code");let h=f.map(s=>{let g=s.text.includes("\uFFFC")?s.search("\uFFFC"):null,T=s.text.includes("\v")?s.search("\v"):null;return g?.load("items"),T?.load("items"),{found:g,breaks:T}});await E(e);let w=f.map((s,g)=>{let T=x[Math.floor(g/L)],A=(T?.fields?.items.length??0)>0,q=T?.controls?.items.some(W=>W.cannotEdit)??false,$=A?s.fields:null,M=q?s.contentControls:null;return $?.load("items/code"),M?.load("items/tag,items/title,items/cannotEdit,items/text"),A&&g%L!==0&&(b[g]=m(g),b[g].fields?.load("items/code")),{word:s,fields:$,controls:M,objects:h[g].found,breaks:h[g].breaks}});await E(e);let u=w.map(s=>({word:s.word,codes:s.fields?.items.map(g=>g.code)??[],locked:s.controls?.items.filter(g=>g.cannotEdit)??[],objects:s.objects,breaks:s.breaks})),l=u.map(s=>{let g=s.locked.map(N=>{let _=Z(s.word,"Start",N.getRange("Whole"),"Start");return _.load("text"),_}),T=(s.objects?.items??[]).map(N=>{let _=N.inlinePictures,re=N.font;return _.load("items/altTextDescription"),re.load("superscript"),{pictures:_,font:re}}),A=[...new Set(s.word.text)],$=s.codes.length>0&&s.locked.length===0&&!s.objects&&A.length<=Be?s.word.getTextRanges(A):null;$?.load("items/text");let M=s.codes.length>0||s.locked.length>0||s.objects||s.breaks,W=be.exec(s.word.text)?.[0]??"",H=M&&W!==""?s.word.search(W):null;return H?.load("items"),{starts:g,kinds:T,pieces:$,spacing:H}});await E(e);let k=ye(u.map((s,g)=>({text:s.word.text,controls:s.locked.map((T,A)=>({text:T.text,start:l[g].starts[A].text.length})),fields:s.codes.length}))),S=l.map(s=>{let g=s.pieces?.items;if(!g)return null;let T=g.map($=>{let M=$.fields;return M.load("items"),M}),A=g.slice(1).map(($,M)=>{let W=g[M].getRange("End").expandTo($.getRange("Start")),H=W.fields;return H.load("items/code"),{range:W,fields:H}}),q=g.map($=>{if($.text.length<2)return null;let M=$.search($.text.slice(-1));return M.load("items"),M});return {fields:T,gaps:A,lastChars:q}});await E(e);let d=k.map(s=>({cluster:s,split:Xe(s,u,l,S),fallback:ee(ke(s,u,l))})),y=d.flatMap(({split:s,fallback:g})=>[...s.flatMap(T=>T.checks),...g.checks]);for(let s of y)s.range.load("text"),s.fields?.collection.load("items");await E(e);let C=s=>s.parts!==null&&s.checks.every(g=>g.range.text===g.text&&(g.fields===void 0||g.fields.collection.items.length===g.fields.count)),R=[],O=s=>{let g=b[s],T=g?.fields?.items.map(A=>A.code)??[];g&&T.length>0&&R.push(...Pe(g.range,T,Ce()));};for(let{cluster:s,split:g,fallback:T}of d){O(s.kind==="atoms"||s.kind==="whole"?s.first:s.word);let A=g.find(C)??(C(T)?T:null);R.push(...A?.parts??ke(s,u,null));}O(f.length);let v=0;return {units:R.map(s=>{let g=s.atom?.()??null;return {range:s.range,text:s.text,atom:g?++v:null,kind:g?.kind??null,description:g?.description??"",group:s.group??null}}),paragraphId:t.uniqueLocalId}}function Xe(e,t,n,o){if(e.kind==="text"){let{word:r}=t[e.word];return [{parts:[U(r,r.text)],checks:[]}]}return e.kind==="whole"?[]:e.kind==="field"?Qe(t[e.word],n[e.word],o[e.word]):[Ye(e,t,n)]}function Qe(e,t,n){let o=t.pieces?.items??[];if(!n||o.length===0)return [];let r=n.fields.flatMap((p,x)=>p.items.length>0?[x]:[]);if(r.some(p=>n.fields[p].items.length!==1))return [];let c=n.gaps.flatMap(p=>p.fields?.items.map(x=>x.code)??[]),a=[...e.codes];for(let p of c)a.splice(a.indexOf(p),1);if(a.length!==r.length)return [];let i=[],f=r.length;if(f<=Ge)for(let p=0;p<1<<f;p+=1)i.push(Array.from({length:f},(x,m)=>(p&1<<m)===0));else i.push(r.map(()=>true),r.map(()=>false));return i.map(p=>{let x=[],m=[],b=e.word.getRange("Start"),h="",w=l=>{if(h==="")return;let k=b.expandTo(l);x.push(U(k,h)),m.push({range:k,text:h,fields:{count:0,collection:k.fields}}),h="";},u=0;for(let[l,k]of o.entries()){let S=l>0?n.gaps[l-1]:void 0,d=S?.fields?.items.map(s=>s.code)??[];d.length>0&&(w(o[l-1].getRange("End")),x.push(...Pe(S.range,d,Ce())),b=k.getRange("Start"));let y=r.indexOf(l);if(y<0){h+=k.text;continue}w(l>0?o[l-1].getRange("End"):k.getRange("Start"));let R=p[y]&&k.text.length>1&&n.lastChars[l]?.items.at(-1)?n.lastChars[l].items.at(-1):null,O=R?k.text.slice(0,-1):k.text,v=R?k.getRange("Start").expandTo(R.getRange("Start")):k,j=Re(a[u],O);u+=1,x.push({range:v,text:O,atom:()=>({kind:"field",description:j})}),m.push({range:v,text:O,fields:{count:1,collection:v.fields}}),b=R?R.getRange("Start"):k.getRange("End"),h=R?k.text.slice(-1):"";}return w(e.word.getRange("End")),{parts:x,checks:m}})}function Ye(e,t,n){let o=e.atoms.map(a=>ze(a,t));if(o.some(a=>a===null))return ee(null);let r=[],c=new Set;for(let a of e.order){if("atom"in a){let m=e.atoms[a.atom],b=e.text.slice(m.start,m.end),h={range:o[a.atom],text:b,atom:Ve(m,t,n)};m.source.type==="control"&&c.add(h),r.push(h);continue}let i=e.pieces[a.piece],f=t[i.word].word,p=i.after===null?f.getRange("Start"):o[i.after].getRange("End"),x=i.before===null?f.getRange("End"):o[i.before].getRange("Start");r.push(U(p.expandTo(x),e.text.slice(i.start,i.end)));}return ee(r,a=>!c.has(a))}function ze(e,t){let n=t[e.source.word];return e.source.type==="control"?n.locked[e.source.index]?.getRange("Whole")??null:(e.source.type==="object"?n.objects:n.breaks)?.items[e.source.index]??null}function Ve(e,t,n){if(e.source.type==="break")return ()=>({kind:"line-break",description:"line break"});if(e.source.type==="control"){let r=t[e.source.word].locked[e.source.index],c=r.tag||r.title,a=`locked content control${c?` named ${I(c)}`:""}, reads `+I(r.text);return ()=>({kind:"content-control",description:a})}let o=n[e.source.word].kinds[e.source.index];return ()=>{let r=o?.pictures.items[0];if(r){let c=r.altTextDescription;return {kind:"picture",description:c?`picture, described as ${I(c)}`:"picture"}}return o?.font.superscript===true?{kind:"note-reference",description:"footnote or endnote reference mark"}:{kind:"equation",description:"equation"}}}function ke(e,t,n){let o=e.kind==="text"||e.kind==="field"?e.word:e.first,r=e.kind==="text"||e.kind==="field"?e.word:e.last,c=t.slice(o,r+1).map(l=>l.word),a=c.map(l=>l.text).join(""),i=c[0],f=c[c.length-1];if(e.kind==="text")return [U(i,a)];let p=t.slice(o,r+1).flatMap(l=>l.codes),x=a.replace(be,""),m=a.slice(x.length),b=p.length>0?{kind:"field",description:`text ${I(x)} with ${p.length===1?"a field":"fields"} ${p.map(l=>I(l.trim())).join(" and ")}, which change only together`}:{kind:"content-control",description:`content that cannot change, reads ${I(x)}`},h=n?.[r]?.spacing,w=h?.items[h.items.length-1];return m!==""&&w?[{range:Z(i,"Start",w,"Start"),text:x,atom:()=>b},U(Z(w,"Start",f,"End"),m)]:[{range:i===f?i:i.expandTo(f),text:a,atom:()=>b}]}var ve=3;function te(e){if(typeof e!="object"||e===null)return null;let{name:t,code:n,debugInfo:o}=e;if(t!=="DocxEditorError"||typeof n!="string")return null;let r=o?.innerError?.code;return {code:n,rule:typeof r=="string"?r:void 0}}var ne=e=>te(e)?.code==="StaleDocument";function J(e){if(e instanceof P)return e;let t=te(e);if(t?.code==="StaleDocument")return new P("stale","Another edit changed the document during the rewrite. Prepare the paragraph again and retry.",{cause:e});if(t?.rule==="edit.protected-content")return new P("locked","The rewrite edits protected content, such as part of a locked content control.",{cause:e});let n=t?`${t.code}${t.rule===void 0?"":` (${t.rule})`}`:K(e);return new P("write-failed",`The document refused an edit: ${n}`,{cause:e})}async function Ee(e,t){for(let n=1;;n+=1){if(e.document.load("changeTrackingMode"),await E(e),!t())return;try{await E(e);return}catch(o){if(n===ve||!ne(o))throw o}}}async function Oe(e){let t=false;try{await Ee(e,()=>e.document.changeTrackingMode==="TrackMineOnly"?false:(e.document.changeTrackingMode="TrackMineOnly",t=true,true));}catch(n){throw ne(n)?J(n):new P("tracking-unavailable","This runtime cannot record tracked changes. In a page, give the editor the review module.",{cause:n})}return t}async function oe(e){await Ee(e,()=>(e.document.changeTrackingMode="Off",true));}function Ze(e,t,n){if(n.to>n.from){let c=t[n.from].range,a=t[n.to-1].range,i=c===a?c:c.expandTo(a);n.text===""?i.delete():i.insertText(n.text,"Replace");return}if(t.length===0){e.insertText(n.text,"Start");return}let o=t[n.from],r=t[n.from-1];o&&(o.atom===null||!r||r.atom!==null)?o.range.insertText(n.text,"Before"):r.range.insertText(n.text,"After");}function et(e,t){return [e.type,e.author,e.date?.toISOString()??"",t].join("\0")}async function G(e,t){let n=t.getRange("Whole").revisions;n.load("items/author,items/type,items/date"),await E(e);let o=n.items.map(r=>{let c=r.range;return c.load("text"),c});return o.length>0&&await E(e),n.items.map((r,c)=>({revision:r,signature:et(r,o[c].text),author:r.author}))}function Te(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return t}async function Ae(e,t,n,o,r,c,a){let i=Te((await G(e,t)).map(p=>p.signature)),f=async()=>{let p=await G(e,t),x=new Map(i);for(let{signature:m,author:b}of p){let h=x.get(m)??0;h>0?x.set(m,h-1):b===r&&c.set(m,(c.get(m)??0)+1);}i=Te(p.map(m=>m.signature));};for(let p of [...o].reverse()){Ze(t,n,p),a.wrote=true;try{await E(e);}catch(x){throw te(x)===null&&await f().catch(()=>{}),x}await f();}}async function tt(e,t,n){try{if(t.load("uniqueLocalId"),await E(e),t.uniqueLocalId===n)return t}catch{}let o=e.document.body.paragraphs;return o.load("items/uniqueLocalId"),await E(e),o.items.find(r=>r.uniqueLocalId===n)??null}async function $e(e,t,n,o,r,c){let a=[...o.values()].reduce((m,b)=>m+b,0),i=t,f=0;for(let m=1;a>0;m+=1){if(i=await tt(e,t,n),!i)throw new Error(`The rollback could not find the paragraph to reject its ${a} recorded ${a===1?"change":"changes"}. Another edit joined it into another paragraph or removed it.`);let b=new Map(o),h=(await G(e,i)).filter(({signature:w})=>{let u=b.get(w)??0;return u===0?false:(b.set(w,u-1),true)});f=h.length;for(let{revision:w}of h)w.reject();try{await E(e);break}catch(w){if(m===ve||!ne(w))throw w}}if(!c||!i)return;let p=i.getReviewedText("Current"),x=i.getReviewedText("Original");if(await E(e),f<a)throw new Error(`The rollback found ${f} of the ${a} changes the rewrite made. The paragraph reads ${JSON.stringify(p.value)}.`);if(x.value===r&&p.value!==r&&((await G(e,i)).length===0||a===0))throw new Error(`The paragraph reads ${JSON.stringify(p.value)} after the rollback, not ${JSON.stringify(r)}.`)}var nt=Symbol.for("@docx-editor.dev/editor-api/author");function ot(e){let t=e[nt];return typeof t=="string"?t:void 0}var Me=()=>new P("stale","Another edit changed the paragraph during the rewrite. Prepare the paragraph again and retry."),qe=()=>new P("verification-failed","The proposed paragraph would not read as the model output.");async function rt(e,t,n={}){return z(e,()=>at(e,t,n))}async function at(e,t,n){let o=ot(e);if(o===void 0)throw new P("tracking-unavailable","The runtime has no author, so it cannot record tracked changes. Pass `author` when you create the runtime.");let{units:r,paragraphId:c}=await Se(e,t).catch(d=>{throw d instanceof P?d:new P("read-failed",`The document refused a read: ${K(d)}`,{cause:d})});F(r);let a=r.map(d=>d.text).join(""),i=de(a),f=r.flatMap(d=>d.atom===null||d.kind===null?[]:[{placeholder:D(d.atom,i),kind:d.kind,text:d.text,description:d.description}]),p=ue(r,i),x=n.keepPlaceholders===true,m=false,b=new Map;for(let d of r)d.group===null||d.atom===null||b.set(d.group,[...b.get(d.group)??[],D(d.atom,i)]);let h=d=>{for(let y of b.values()){let C=y.filter(R=>d.includes(R));if(!(C.length===0||C.length===y.length))throw new P("placeholder-grouped",`The model output keeps ${C.join(", ")} but leaves out ${y.filter(R=>!C.includes(R)).join(", ")}. These placeholders stand for fields at one place in the text: keep all of ${y.join(", ")}, or leave all of them out.`)}},w=d=>d.trim(),u=d=>{let y=String(d).trim();fe(y,f,x,i,a),h(y);let C=ge(r,y,i),R=w(he(y,f,i));if(C.length===0&&R!==w(a))throw qe();return {output:y,hunks:C,expected:R}},l=async(d,y)=>{m=true;let C=new Map,R={wrote:false};try{await Ae(e,t,r,d,o,C,R);let O=t.getReviewedText("Current"),v=t.getReviewedText("Original");if(await E(e),v.value!==a)throw Me();if(w(O.value)!==y)throw qe();return {paragraphId:c,original:a,proposed:O.value,changes:d.length}}catch(O){let v=J(O);try{await $e(e,t,c,C,a,R.wrote);}catch(j){throw new P("rollback-failed",`The rewrite failed, and rejecting its changes failed too, so the document can still hold part of the proposal. Do not retry automatically. First error: ${v.message} Rollback error: ${K(j)}`,{cause:new AggregateError([v,j])})}throw v}},k=()=>{if(m)throw new P("draft-used","This draft already wrote to the paragraph. Prepare the paragraph again.")},S=async d=>{V(e),k();let{hunks:y,expected:C}=u(d);if(y.length===0)try{let v=t.getReviewedText("Current"),j=t.getReviewedText("Original");if(await E(e),j.value!==a||w(v.value)!==C)throw Me();return {paragraphId:c,original:a,proposed:v.value,changes:0}}catch(v){throw J(v)}let R=await Oe(e),O;try{O=await l(y,C);}catch(v){throw R&&await oe(e).catch(j=>{v instanceof P&&(v.suppressed=j);}),v}return R&&await oe(e).catch(()=>{}),O};return {paragraphId:c,original:a,text:p,placeholders:f,legend:pe(f,x,i),check:d=>{try{return k(),u(d),null}catch(y){if(y instanceof P)return y;throw y}},apply:d=>z(e,()=>S(d))}}exports.RewriteError=P;exports.prepareRewrite=rt;
|
package/dist/agent.mjs
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
var je=new Set(["invalid-output","placeholder-missing","placeholder-unknown","placeholder-moved","placeholder-repeated","placeholder-grouped"]),P=class extends Error{name="RewriteError";code;isModelError;suppressed;constructor(t,n,o){super(n,o?.cause===void 0?void 0:{cause:o.cause}),this.code=t,this.isModelError=je.has(t);}};function K(e){return e instanceof Error?e.message:String(e)}var ce=/[ \t]+$/,Ie=[{open:"\u27E6",close:"\u27E7"},{open:"\u27EA",close:"\u27EB"},{open:"\u2983",close:"\u2984"},{open:"\u27EC",close:"\u27ED"}];function de(e){let t=Ie.find(({open:n,close:o})=>!e.includes(n)&&!e.includes(o));if(!t)throw new P("unsupported-text","The paragraph contains every bracket pair the placeholders can use, so a placeholder could not be told apart from its text.");return t}var ae=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Y=({open:e,close:t},n,o="")=>new RegExp(`${o}${ae(e)}(\\d+)${ae(t)}`,n),We=/[\r\n]/,le=/[\u2028\u2029]/g,X=2e4,Le=2e3,ie=e=>e.replace(ce,""),se=e=>ce.exec(e)?.[0]??"",D=(e,t)=>`${t.open}${e}${t.close}`;function ue(e,t){return e.map(n=>n.atom===null?n.text:D(n.atom,t)).join("")}function pe(e,t,n){if(e.length===0)return "";let r=[`The text contains placeholders, such as ${D(1,n)}. Each one stands for content that you cannot edit, such as a field or an equation.`,t?"Keep every placeholder, and copy each one exactly as written.":"Copy each placeholder that you keep exactly as written. Leave a placeholder out to delete what it stands for.","Write the text around a placeholder as usual. Do not change the order of the placeholders, and do not repeat one."].join(" "),c=e.map(a=>`${a.placeholder} = ${a.description}`);return `${r}
|
|
2
|
+
|
|
3
|
+
Placeholders:
|
|
4
|
+
${c.join(`
|
|
5
|
+
`)}`}function fe(e,t,n,o,r){if(e==="")throw new P("invalid-output","The model output is empty. Return the paragraph.");let c=new Set(r.match(le)??[]),a=[...e.match(le)??[]].some(p=>!c.has(p));if(We.test(e)||a)throw new P("invalid-output","The model output contains a line break. Return one paragraph on one line.");let i=new Set(t.map(p=>p.placeholder)),f=new Set;for(let[p]of e.matchAll(Y(o,"g"))){if(!i.has(p))throw new P("placeholder-unknown",`The model output contains ${p}, which is not in the paragraph. Use only the listed placeholders.`);if(f.has(p))throw new P("placeholder-repeated",`The model output contains ${p} more than once. Keep each placeholder once.`);f.add(p);}if(n){let p=t.find(x=>!f.has(x.placeholder));if(p)throw new P("placeholder-missing",`The model output leaves out ${p.placeholder}. Keep every placeholder.`)}}function he(e,t,n){let o=new Map(t.map(r=>[r.placeholder,r.text]));return e.replace(Y(n,"g"),r=>o.get(r)??r)}function De(e,t){let n=Y(t,"","^"),o=[],r="",c=()=>{r!==""&&o.push({text:r,atom:null}),r="";};for(let a=0;a<e.length;){let i=e.startsWith(t.open,a)?n.exec(e.slice(a)):null;if(i){c(),o.push({text:i[0],atom:Number(i[1])}),a+=i[0].length;continue}let f=e[a];r+=f,a+=1,(f===" "||f===" ")&&c();}return c(),o}function He(e,t){let n=e.length,o=t.length,r=(h,w)=>{let u=e[h],l=t[w];return u.atom!==null||l.atom!==null?u.atom===l.atom:u.text===l.text?true:(h===n-1||w===o-1)&&ie(u.text)===ie(l.text)};if(n>X||o>X)throw Q();let c=Math.min(n+o,Le),a=c+1,i=new Int32Array(2*c+3),f=[],p=-1;for(let h=0;h<=c&&p<0;h+=1){f.push(i.slice(a-h-1,a+h+2));for(let w=-h;w<=h;w+=2){let u=w===-h||w!==h&&i[a+w-1]<i[a+w+1]?i[a+w+1]:i[a+w-1]+1,l=u-w;for(;u<n&&l<o&&r(u,l);)u+=1,l+=1;if(i[a+w]=u,u>=n&&l>=o){p=h;break}}}if(p<0)throw Q();let x=[],m=n,b=o;for(let h=p;h>0;h-=1){let w=f[h],u=C=>w[C+h+1],l=m-b,k=l===-h||l!==h&&u(l-1)<u(l+1),S=k?l+1:l-1,d=u(S),y=d-S;for(;m>d&&b>y;)m-=1,b-=1,x.push({kind:"keep",unit:m,token:t[b]});k?(b-=1,x.push({kind:"insert",token:t[b]})):(m-=1,x.push({kind:"delete",unit:m}));}for(;m>0&&b>0;)m-=1,b-=1,x.push({kind:"keep",unit:m,token:t[b]});return x.reverse()}var Q=()=>new P("too-long","The paragraph and the model output are too long to compare. Rewrite a shorter paragraph.");function F(e){if(e.length>X)throw Q()}function ge(e,t,n){let o=[],r=null,c="",a=0;for(let i of He(e,De(t,n))){if(i.kind==="keep"){r=null;let f=e[i.unit];i.unit===e.length-1&&f.atom===null&&se(f.text)===""&&(c=se(i.token.text)),a=i.unit+1;continue}if(i.kind==="insert"&&i.token.atom!==null)throw new P("placeholder-moved",`The model output moves ${D(i.token.atom,n)}. Keep the placeholders in their order.`);r||(r={from:a,to:a,text:c},c="",o.push(r)),i.kind==="delete"?(r.to=i.unit+1,a=i.unit+1):r.text+=i.token.text;}return o}var _e=Symbol.for("@docx-editor.dev/editor-api/queue");function Ke(e){let t=e[_e];return typeof t=="object"&&t!==null?t:null}var B=new WeakMap,Ue=()=>new P("busy","A helper call is in progress on this request context. Await it before you call context.sync().");async function z(e,t){if(B.has(e))throw new P("busy","Another rewrite helper call runs on this request context. Await it before you start the next one: apply drafts one after another.");V(e);let n={entering:false};B.set(e,n);let o=Object.getOwnPropertyDescriptor(e,"sync"),r=o?o.value??o.get?.call(e):Object.getPrototypeOf(e).sync,c=!o||o.configurable===true;c&&Object.defineProperty(e,"sync",{configurable:true,value:function(){return n.entering?r.call(this):Promise.reject(Ue())}});try{return await t()}finally{c&&(o?Object.defineProperty(e,"sync",o):delete e.sync),B.delete(e);}}async function E(e){let t=B.get(e),n;t&&(t.entering=true);try{n=e.sync();}finally{t&&(t.entering=false);}await n;}function V(e){let t=Ke(e)?.writes()??0;if(t!==0)throw new P("context-used",t===1?"1 edit is queued on the request context. Sync it before you call the helper, so that its tracked writes never send it.":`${t} edits are queued on the request context. Sync them before you call the helper, so that its tracked writes never send them.`)}var me=e=>e.includes("\uFFFC")||e.includes("\v");function ye(e){let t=[];for(let n=0;n<e.length;){let o=e[n];if(o.controls.length===0&&o.fields===0&&!me(o.text)){t.push({kind:"text",word:n}),n+=1;continue}if(o.controls.length===0&&o.fields>0){t.push(me(o.text)?{kind:"whole",first:n,last:n}:{kind:"field",word:n}),n+=1;continue}let r=Ne(e,n);t.push(r),n=(r.kind==="atoms"||r.kind==="whole"?r.last:n)+1;}return t}function Ne(e,t){let n=[],o=[],r=0,c=null,a=t;for(let u=t;u<e.length;u+=1){let l=e[u];if(u>t&&c===null)break;if(l.fields>0)return {kind:"whole",first:t,last:a};o.push(r),a=u;let k=0,S=0;if(c){if(l.controls[0]===void 0||!l.text.startsWith(c.rest.slice(0,1)))return {kind:"whole",first:t,last:a};let d=Math.min(c.rest.length,l.text.length);if(l.text.slice(0,d)!==c.rest.slice(0,d))return {kind:"whole",first:t,last:a};let y=n[c.atom];n[c.atom]={...y,end:r+d},k=d,S=1;let{rest:C,atom:R}=c;if(c=d<C.length?{rest:C.slice(d),atom:R}:null,c){r+=l.text.length;continue}}for(;S<l.controls.length;S+=1){let{text:d,start:y}=l.controls[S],R=y!==null&&y>=k&&l.text.startsWith(d,y)?y:y===null?l.text.indexOf(d,k):-1;if(R>=0){n.push({start:r+R,end:r+R+d.length,source:{type:"control",word:u,index:S}}),k=R+d.length;continue}let O=y!==null&&y>=k&&d.startsWith(l.text.slice(y))?y:Fe(l.text,d,k);if(O<0||S!==l.controls.length-1)return {kind:"whole",first:t,last:a};n.push({start:r+O,end:r+l.text.length,source:{type:"control",word:u,index:S}}),c={rest:d.slice(l.text.length-O),atom:n.length-1},k=l.text.length;}r+=l.text.length;}if(c)return {kind:"whole",first:t,last:a};let i=e.slice(t,a+1).map(u=>u.text).join("");for(let u=t;u<=a;u+=1){let l=e[u],k=o[u-t];for(let[S,d]of [["\uFFFC","object"],["\v","break"]]){let y=0;for(let C=l.text.indexOf(S);C>=0;C=l.text.indexOf(S,C+1)){let R=k+C;if(n.some(v=>v.start<=R&&R<v.end))return {kind:"whole",first:t,last:a};n.push({start:R,end:R+1,source:{type:d,word:u,index:y}}),y+=1;}}}n.sort((u,l)=>u.start-l.start);let f=[],p=[],x=u=>n.findIndex(l=>l.end===u),m=u=>n.findIndex(l=>l.start===u),b=u=>{let l=0;return o.forEach((k,S)=>{k<=u&&(l=S);}),l},h=0,w=u=>{for(;h<u;){let l=b(h),k=o[l+1]??i.length,S=Math.min(u,k),d=h===o[l]?null:x(h),y=S===k?null:m(S);if(d===-1||y===-1)return false;p.push({piece:f.length}),f.push({start:h,end:S,word:t+l,after:d,before:y}),h=S;}return true};for(let[u,l]of n.entries()){if(!w(l.start))return {kind:"whole",first:t,last:a};p.push({atom:u}),h=l.end;}return w(i.length)?{kind:"atoms",first:t,last:a,text:i,atoms:n,order:p,pieces:f}:{kind:"whole",first:t,last:a}}function Fe(e,t,n){for(let o=n;o<e.length;o+=1)if(t.startsWith(e.slice(o)))return o;return -1}var be=/[ \t]+$/,Be=32,L=32,Ge=3,I=e=>JSON.stringify(e),U=(e,t)=>({range:e,text:t,atom:null});function Z(e,t,n,o){return e.getRange(t).expandTo(n.getRange(o))}function ee(e,t=()=>true){return {parts:e,checks:(e??[]).filter(t).map(n=>({range:n.range,text:n.text}))}}var Re=(e,t)=>`field with code ${I(e.trim())}, `+(t===""?"shows no text":`reads ${I(t)}`);function Pe(e,t,n){return t.map(o=>{let r=Re(o,"");return {range:e,text:"",group:n,atom:()=>({kind:"field",description:r})}})}var Je=0,Ce=()=>++Je;async function Se(e,t){let n=t.getTextRanges([" "," "]),o=t.getRange("Whole").revisions,r=t.getRange("Whole").fields,c=t.contentControls;if(n.load("items/text"),o.load("items"),r.load("items"),c.load("items/cannotEdit"),t.load("uniqueLocalId"),await E(e),o.items.length>0)throw new P("pending-changes","The paragraph has tracked changes. Accept or reject them before you rewrite it.");F(n.items);let a=r.items.length>0,i=c.items.some(s=>s.cannotEdit),f=n.items,p=Math.ceil(f.length/L),x=Array.from({length:a||i?p:0},(s,g)=>{let T=f[g*L],A=f[Math.min(f.length,(g+1)*L)-1],q=T.expandTo(A),$=a?q.fields:null,M=i?q.contentControls:null;return $?.load("items"),M?.load("items/cannotEdit"),{fields:$,controls:M}}),m=s=>{let g=f[s-1],T=f[s],q=(g?g.getRange("End"):t.getRange("Start")).expandTo(T?T.getRange("Start"):t.getRange("End"));return {range:q,fields:a?q.fields:null}},b=Array.from({length:f.length+1},(s,g)=>a&&g%L===0?m(g):null);a&&f.length%L!==0&&(b[f.length]=m(f.length));for(let s of b)s?.fields?.load("items/code");let h=f.map(s=>{let g=s.text.includes("\uFFFC")?s.search("\uFFFC"):null,T=s.text.includes("\v")?s.search("\v"):null;return g?.load("items"),T?.load("items"),{found:g,breaks:T}});await E(e);let w=f.map((s,g)=>{let T=x[Math.floor(g/L)],A=(T?.fields?.items.length??0)>0,q=T?.controls?.items.some(W=>W.cannotEdit)??false,$=A?s.fields:null,M=q?s.contentControls:null;return $?.load("items/code"),M?.load("items/tag,items/title,items/cannotEdit,items/text"),A&&g%L!==0&&(b[g]=m(g),b[g].fields?.load("items/code")),{word:s,fields:$,controls:M,objects:h[g].found,breaks:h[g].breaks}});await E(e);let u=w.map(s=>({word:s.word,codes:s.fields?.items.map(g=>g.code)??[],locked:s.controls?.items.filter(g=>g.cannotEdit)??[],objects:s.objects,breaks:s.breaks})),l=u.map(s=>{let g=s.locked.map(N=>{let _=Z(s.word,"Start",N.getRange("Whole"),"Start");return _.load("text"),_}),T=(s.objects?.items??[]).map(N=>{let _=N.inlinePictures,re=N.font;return _.load("items/altTextDescription"),re.load("superscript"),{pictures:_,font:re}}),A=[...new Set(s.word.text)],$=s.codes.length>0&&s.locked.length===0&&!s.objects&&A.length<=Be?s.word.getTextRanges(A):null;$?.load("items/text");let M=s.codes.length>0||s.locked.length>0||s.objects||s.breaks,W=be.exec(s.word.text)?.[0]??"",H=M&&W!==""?s.word.search(W):null;return H?.load("items"),{starts:g,kinds:T,pieces:$,spacing:H}});await E(e);let k=ye(u.map((s,g)=>({text:s.word.text,controls:s.locked.map((T,A)=>({text:T.text,start:l[g].starts[A].text.length})),fields:s.codes.length}))),S=l.map(s=>{let g=s.pieces?.items;if(!g)return null;let T=g.map($=>{let M=$.fields;return M.load("items"),M}),A=g.slice(1).map(($,M)=>{let W=g[M].getRange("End").expandTo($.getRange("Start")),H=W.fields;return H.load("items/code"),{range:W,fields:H}}),q=g.map($=>{if($.text.length<2)return null;let M=$.search($.text.slice(-1));return M.load("items"),M});return {fields:T,gaps:A,lastChars:q}});await E(e);let d=k.map(s=>({cluster:s,split:Xe(s,u,l,S),fallback:ee(ke(s,u,l))})),y=d.flatMap(({split:s,fallback:g})=>[...s.flatMap(T=>T.checks),...g.checks]);for(let s of y)s.range.load("text"),s.fields?.collection.load("items");await E(e);let C=s=>s.parts!==null&&s.checks.every(g=>g.range.text===g.text&&(g.fields===void 0||g.fields.collection.items.length===g.fields.count)),R=[],O=s=>{let g=b[s],T=g?.fields?.items.map(A=>A.code)??[];g&&T.length>0&&R.push(...Pe(g.range,T,Ce()));};for(let{cluster:s,split:g,fallback:T}of d){O(s.kind==="atoms"||s.kind==="whole"?s.first:s.word);let A=g.find(C)??(C(T)?T:null);R.push(...A?.parts??ke(s,u,null));}O(f.length);let v=0;return {units:R.map(s=>{let g=s.atom?.()??null;return {range:s.range,text:s.text,atom:g?++v:null,kind:g?.kind??null,description:g?.description??"",group:s.group??null}}),paragraphId:t.uniqueLocalId}}function Xe(e,t,n,o){if(e.kind==="text"){let{word:r}=t[e.word];return [{parts:[U(r,r.text)],checks:[]}]}return e.kind==="whole"?[]:e.kind==="field"?Qe(t[e.word],n[e.word],o[e.word]):[Ye(e,t,n)]}function Qe(e,t,n){let o=t.pieces?.items??[];if(!n||o.length===0)return [];let r=n.fields.flatMap((p,x)=>p.items.length>0?[x]:[]);if(r.some(p=>n.fields[p].items.length!==1))return [];let c=n.gaps.flatMap(p=>p.fields?.items.map(x=>x.code)??[]),a=[...e.codes];for(let p of c)a.splice(a.indexOf(p),1);if(a.length!==r.length)return [];let i=[],f=r.length;if(f<=Ge)for(let p=0;p<1<<f;p+=1)i.push(Array.from({length:f},(x,m)=>(p&1<<m)===0));else i.push(r.map(()=>true),r.map(()=>false));return i.map(p=>{let x=[],m=[],b=e.word.getRange("Start"),h="",w=l=>{if(h==="")return;let k=b.expandTo(l);x.push(U(k,h)),m.push({range:k,text:h,fields:{count:0,collection:k.fields}}),h="";},u=0;for(let[l,k]of o.entries()){let S=l>0?n.gaps[l-1]:void 0,d=S?.fields?.items.map(s=>s.code)??[];d.length>0&&(w(o[l-1].getRange("End")),x.push(...Pe(S.range,d,Ce())),b=k.getRange("Start"));let y=r.indexOf(l);if(y<0){h+=k.text;continue}w(l>0?o[l-1].getRange("End"):k.getRange("Start"));let R=p[y]&&k.text.length>1&&n.lastChars[l]?.items.at(-1)?n.lastChars[l].items.at(-1):null,O=R?k.text.slice(0,-1):k.text,v=R?k.getRange("Start").expandTo(R.getRange("Start")):k,j=Re(a[u],O);u+=1,x.push({range:v,text:O,atom:()=>({kind:"field",description:j})}),m.push({range:v,text:O,fields:{count:1,collection:v.fields}}),b=R?R.getRange("Start"):k.getRange("End"),h=R?k.text.slice(-1):"";}return w(e.word.getRange("End")),{parts:x,checks:m}})}function Ye(e,t,n){let o=e.atoms.map(a=>ze(a,t));if(o.some(a=>a===null))return ee(null);let r=[],c=new Set;for(let a of e.order){if("atom"in a){let m=e.atoms[a.atom],b=e.text.slice(m.start,m.end),h={range:o[a.atom],text:b,atom:Ve(m,t,n)};m.source.type==="control"&&c.add(h),r.push(h);continue}let i=e.pieces[a.piece],f=t[i.word].word,p=i.after===null?f.getRange("Start"):o[i.after].getRange("End"),x=i.before===null?f.getRange("End"):o[i.before].getRange("Start");r.push(U(p.expandTo(x),e.text.slice(i.start,i.end)));}return ee(r,a=>!c.has(a))}function ze(e,t){let n=t[e.source.word];return e.source.type==="control"?n.locked[e.source.index]?.getRange("Whole")??null:(e.source.type==="object"?n.objects:n.breaks)?.items[e.source.index]??null}function Ve(e,t,n){if(e.source.type==="break")return ()=>({kind:"line-break",description:"line break"});if(e.source.type==="control"){let r=t[e.source.word].locked[e.source.index],c=r.tag||r.title,a=`locked content control${c?` named ${I(c)}`:""}, reads `+I(r.text);return ()=>({kind:"content-control",description:a})}let o=n[e.source.word].kinds[e.source.index];return ()=>{let r=o?.pictures.items[0];if(r){let c=r.altTextDescription;return {kind:"picture",description:c?`picture, described as ${I(c)}`:"picture"}}return o?.font.superscript===true?{kind:"note-reference",description:"footnote or endnote reference mark"}:{kind:"equation",description:"equation"}}}function ke(e,t,n){let o=e.kind==="text"||e.kind==="field"?e.word:e.first,r=e.kind==="text"||e.kind==="field"?e.word:e.last,c=t.slice(o,r+1).map(l=>l.word),a=c.map(l=>l.text).join(""),i=c[0],f=c[c.length-1];if(e.kind==="text")return [U(i,a)];let p=t.slice(o,r+1).flatMap(l=>l.codes),x=a.replace(be,""),m=a.slice(x.length),b=p.length>0?{kind:"field",description:`text ${I(x)} with ${p.length===1?"a field":"fields"} ${p.map(l=>I(l.trim())).join(" and ")}, which change only together`}:{kind:"content-control",description:`content that cannot change, reads ${I(x)}`},h=n?.[r]?.spacing,w=h?.items[h.items.length-1];return m!==""&&w?[{range:Z(i,"Start",w,"Start"),text:x,atom:()=>b},U(Z(w,"Start",f,"End"),m)]:[{range:i===f?i:i.expandTo(f),text:a,atom:()=>b}]}var ve=3;function te(e){if(typeof e!="object"||e===null)return null;let{name:t,code:n,debugInfo:o}=e;if(t!=="DocxEditorError"||typeof n!="string")return null;let r=o?.innerError?.code;return {code:n,rule:typeof r=="string"?r:void 0}}var ne=e=>te(e)?.code==="StaleDocument";function J(e){if(e instanceof P)return e;let t=te(e);if(t?.code==="StaleDocument")return new P("stale","Another edit changed the document during the rewrite. Prepare the paragraph again and retry.",{cause:e});if(t?.rule==="edit.protected-content")return new P("locked","The rewrite edits protected content, such as part of a locked content control.",{cause:e});let n=t?`${t.code}${t.rule===void 0?"":` (${t.rule})`}`:K(e);return new P("write-failed",`The document refused an edit: ${n}`,{cause:e})}async function Ee(e,t){for(let n=1;;n+=1){if(e.document.load("changeTrackingMode"),await E(e),!t())return;try{await E(e);return}catch(o){if(n===ve||!ne(o))throw o}}}async function Oe(e){let t=false;try{await Ee(e,()=>e.document.changeTrackingMode==="TrackMineOnly"?false:(e.document.changeTrackingMode="TrackMineOnly",t=true,true));}catch(n){throw ne(n)?J(n):new P("tracking-unavailable","This runtime cannot record tracked changes. In a page, give the editor the review module.",{cause:n})}return t}async function oe(e){await Ee(e,()=>(e.document.changeTrackingMode="Off",true));}function Ze(e,t,n){if(n.to>n.from){let c=t[n.from].range,a=t[n.to-1].range,i=c===a?c:c.expandTo(a);n.text===""?i.delete():i.insertText(n.text,"Replace");return}if(t.length===0){e.insertText(n.text,"Start");return}let o=t[n.from],r=t[n.from-1];o&&(o.atom===null||!r||r.atom!==null)?o.range.insertText(n.text,"Before"):r.range.insertText(n.text,"After");}function et(e,t){return [e.type,e.author,e.date?.toISOString()??"",t].join("\0")}async function G(e,t){let n=t.getRange("Whole").revisions;n.load("items/author,items/type,items/date"),await E(e);let o=n.items.map(r=>{let c=r.range;return c.load("text"),c});return o.length>0&&await E(e),n.items.map((r,c)=>({revision:r,signature:et(r,o[c].text),author:r.author}))}function Te(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return t}async function Ae(e,t,n,o,r,c,a){let i=Te((await G(e,t)).map(p=>p.signature)),f=async()=>{let p=await G(e,t),x=new Map(i);for(let{signature:m,author:b}of p){let h=x.get(m)??0;h>0?x.set(m,h-1):b===r&&c.set(m,(c.get(m)??0)+1);}i=Te(p.map(m=>m.signature));};for(let p of [...o].reverse()){Ze(t,n,p),a.wrote=true;try{await E(e);}catch(x){throw te(x)===null&&await f().catch(()=>{}),x}await f();}}async function tt(e,t,n){try{if(t.load("uniqueLocalId"),await E(e),t.uniqueLocalId===n)return t}catch{}let o=e.document.body.paragraphs;return o.load("items/uniqueLocalId"),await E(e),o.items.find(r=>r.uniqueLocalId===n)??null}async function $e(e,t,n,o,r,c){let a=[...o.values()].reduce((m,b)=>m+b,0),i=t,f=0;for(let m=1;a>0;m+=1){if(i=await tt(e,t,n),!i)throw new Error(`The rollback could not find the paragraph to reject its ${a} recorded ${a===1?"change":"changes"}. Another edit joined it into another paragraph or removed it.`);let b=new Map(o),h=(await G(e,i)).filter(({signature:w})=>{let u=b.get(w)??0;return u===0?false:(b.set(w,u-1),true)});f=h.length;for(let{revision:w}of h)w.reject();try{await E(e);break}catch(w){if(m===ve||!ne(w))throw w}}if(!c||!i)return;let p=i.getReviewedText("Current"),x=i.getReviewedText("Original");if(await E(e),f<a)throw new Error(`The rollback found ${f} of the ${a} changes the rewrite made. The paragraph reads ${JSON.stringify(p.value)}.`);if(x.value===r&&p.value!==r&&((await G(e,i)).length===0||a===0))throw new Error(`The paragraph reads ${JSON.stringify(p.value)} after the rollback, not ${JSON.stringify(r)}.`)}var nt=Symbol.for("@docx-editor.dev/editor-api/author");function ot(e){let t=e[nt];return typeof t=="string"?t:void 0}var Me=()=>new P("stale","Another edit changed the paragraph during the rewrite. Prepare the paragraph again and retry."),qe=()=>new P("verification-failed","The proposed paragraph would not read as the model output.");async function rt(e,t,n={}){return z(e,()=>at(e,t,n))}async function at(e,t,n){let o=ot(e);if(o===void 0)throw new P("tracking-unavailable","The runtime has no author, so it cannot record tracked changes. Pass `author` when you create the runtime.");let{units:r,paragraphId:c}=await Se(e,t).catch(d=>{throw d instanceof P?d:new P("read-failed",`The document refused a read: ${K(d)}`,{cause:d})});F(r);let a=r.map(d=>d.text).join(""),i=de(a),f=r.flatMap(d=>d.atom===null||d.kind===null?[]:[{placeholder:D(d.atom,i),kind:d.kind,text:d.text,description:d.description}]),p=ue(r,i),x=n.keepPlaceholders===true,m=false,b=new Map;for(let d of r)d.group===null||d.atom===null||b.set(d.group,[...b.get(d.group)??[],D(d.atom,i)]);let h=d=>{for(let y of b.values()){let C=y.filter(R=>d.includes(R));if(!(C.length===0||C.length===y.length))throw new P("placeholder-grouped",`The model output keeps ${C.join(", ")} but leaves out ${y.filter(R=>!C.includes(R)).join(", ")}. These placeholders stand for fields at one place in the text: keep all of ${y.join(", ")}, or leave all of them out.`)}},w=d=>d.trim(),u=d=>{let y=String(d).trim();fe(y,f,x,i,a),h(y);let C=ge(r,y,i),R=w(he(y,f,i));if(C.length===0&&R!==w(a))throw qe();return {output:y,hunks:C,expected:R}},l=async(d,y)=>{m=true;let C=new Map,R={wrote:false};try{await Ae(e,t,r,d,o,C,R);let O=t.getReviewedText("Current"),v=t.getReviewedText("Original");if(await E(e),v.value!==a)throw Me();if(w(O.value)!==y)throw qe();return {paragraphId:c,original:a,proposed:O.value,changes:d.length}}catch(O){let v=J(O);try{await $e(e,t,c,C,a,R.wrote);}catch(j){throw new P("rollback-failed",`The rewrite failed, and rejecting its changes failed too, so the document can still hold part of the proposal. Do not retry automatically. First error: ${v.message} Rollback error: ${K(j)}`,{cause:new AggregateError([v,j])})}throw v}},k=()=>{if(m)throw new P("draft-used","This draft already wrote to the paragraph. Prepare the paragraph again.")},S=async d=>{V(e),k();let{hunks:y,expected:C}=u(d);if(y.length===0)try{let v=t.getReviewedText("Current"),j=t.getReviewedText("Original");if(await E(e),j.value!==a||w(v.value)!==C)throw Me();return {paragraphId:c,original:a,proposed:v.value,changes:0}}catch(v){throw J(v)}let R=await Oe(e),O;try{O=await l(y,C);}catch(v){throw R&&await oe(e).catch(j=>{v instanceof P&&(v.suppressed=j);}),v}return R&&await oe(e).catch(()=>{}),O};return {paragraphId:c,original:a,text:p,placeholders:f,legend:pe(f,x,i),check:d=>{try{return k(),u(d),null}catch(y){if(y instanceof P)return y;throw y}},apply:d=>z(e,()=>S(d))}}export{P as RewriteError,rt as prepareRewrite};
|
package/dist/browser.d.mts
CHANGED
|
@@ -20,8 +20,8 @@
|
|
|
20
20
|
* @packageDocumentation
|
|
21
21
|
* @public
|
|
22
22
|
*/
|
|
23
|
-
import {
|
|
24
|
-
export { A as Alignment, B as BesideLocation, b as Body, c as BodyInsertParagraphLocation, d as BodyInsertTextLocation, e as Bookmark, f as BookmarkCollection, g as BreakType, h as ChangeTrackingMode, i as
|
|
23
|
+
import { ao as RevisionTextView, N as DocxEditorRuntime, C as CreateServerOptions, D as DocxEditorServerRuntime, a as CreateCollaborativeOptions } from './server-BB94GFr9.mjs';
|
|
24
|
+
export { A as Alignment, B as BesideLocation, b as Body, c as BodyInsertParagraphLocation, d as BodyInsertTextLocation, e as Bookmark, f as BookmarkCollection, g as BreakType, h as ChangeTrackingMode, i as ChangeTrackingVersion, j as ClientObject, k as ClientResult, l as Comment, m as CommentCollection, n as CommentReply, o as CommentReplyCollection, p as CommitPreviewOptions, q as ContentControl, r as ContentControlCollection, s as ContentControlLockState, t as ContentControlSubtype, u as ContentControlType, v as ContentControlValue, w as Document, x as DocumentCapabilities, y as DocumentLimits, z as DocumentPreview, E as DocumentPreviewStatus, F as DocumentProperties, G as DocumentXmlLimits, H as DocumentZipLimits, I as DocxEditorDebugInfo, J as DocxEditorError, K as DocxEditorErrorCode, L as DocxEditorErrorInit, M as DocxEditorInnerError, O as EditorModule, P as Field, Q as FieldCollection, R as FieldType, S as FieldTypeLiteral, T as Font, U as HeaderFooterType, V as InlinePicture, W as InlinePictureCollection, X as InsertLocation, Y as List, Z as ListBullet, _ as ListCollection, $ as ListItem, a0 as ListNumbering, a1 as LoadOption, a2 as LoadQueryOptions, a3 as NoteItem, a4 as NoteItemCollection, a5 as NoteItemType, a6 as PageOrientation, a7 as PageSetup, a8 as Paragraph, a9 as ParagraphAlignment, aa as ParagraphCollection, ab as ParagraphInsertTextLocation, ac as ParagraphReadingOrder, ad as PreviewCallback, ae as Range, af as RangeCollection, ag as RangeInsertTextLocation, ah as RangeLocation, ai as RemoveDocInfoType, aj as RequestContext, ak as Revision, al as RevisionAuthorOptions, am as RevisionAuthorSelection, an as RevisionCollection, ap as RevisionType, aq as RunCallback, ar as RunOptions, as as RuntimeDiagnostic, at as SearchOptions, au as Section, av as SectionCollection, aw as SelectionMode, ax as ServerPaginationOptions, ay as Shape, az as ShapeCollection, aA as ShapeType, aB as Table, aC as TableCell, aD as TableCellCollection, aE as TableCollection, aF as TableRow, aG as TableRowCollection, aH as TrackedObjects, aI as UnderlineType, aJ as VerticalAlignment, aK as getReviewItemRange, aL as getReviewItemRangeOrNullObject, aM as getReviewItemRevisions, aN as isDocxEditorError } from './server-BB94GFr9.mjs';
|
|
25
25
|
import { EditorCollaborationSession } from '@docx-editor.dev/core/collaboration';
|
|
26
26
|
export { HistoryGroup, HistoryGroupOutcome, RevisionAuthorEntry, RevisionAuthorResult, RevisionAuthorSkipReason, RevisionBatchEntry, RevisionBatchResult, RevisionBatchSkipReason } from '@docx-editor.dev/core/automation';
|
|
27
27
|
import { DocxEditorInstance } from '@docx-editor.dev/core/editor';
|
|
@@ -37,7 +37,11 @@ interface CreateBrowserOptions {
|
|
|
37
37
|
*
|
|
38
38
|
* Required to reply to a comment: `CT_TrackChange` makes `@w:author` mandatory, and the editor
|
|
39
39
|
* does not expose a signed-in identity to automation. Omitted means comment writes refuse with
|
|
40
|
-
* `NotSupported`; ordinary document reads
|
|
40
|
+
* `NotSupported` and the diagnostic `edit.comment-author-required`; ordinary document reads
|
|
41
|
+
* and writes are unaffected.
|
|
42
|
+
*
|
|
43
|
+
* To build a review UI over this editor, use `useReview()` from `@docx-editor.dev/pro/react`
|
|
44
|
+
* or `@docx-editor.dev/pro/vue` instead. It comments and replies as the editor's author.
|
|
41
45
|
*/
|
|
42
46
|
readonly author?: string;
|
|
43
47
|
/**
|
package/dist/browser.d.ts
CHANGED
|
@@ -20,8 +20,8 @@
|
|
|
20
20
|
* @packageDocumentation
|
|
21
21
|
* @public
|
|
22
22
|
*/
|
|
23
|
-
import {
|
|
24
|
-
export { A as Alignment, B as BesideLocation, b as Body, c as BodyInsertParagraphLocation, d as BodyInsertTextLocation, e as Bookmark, f as BookmarkCollection, g as BreakType, h as ChangeTrackingMode, i as
|
|
23
|
+
import { ao as RevisionTextView, N as DocxEditorRuntime, C as CreateServerOptions, D as DocxEditorServerRuntime, a as CreateCollaborativeOptions } from './server-BB94GFr9.js';
|
|
24
|
+
export { A as Alignment, B as BesideLocation, b as Body, c as BodyInsertParagraphLocation, d as BodyInsertTextLocation, e as Bookmark, f as BookmarkCollection, g as BreakType, h as ChangeTrackingMode, i as ChangeTrackingVersion, j as ClientObject, k as ClientResult, l as Comment, m as CommentCollection, n as CommentReply, o as CommentReplyCollection, p as CommitPreviewOptions, q as ContentControl, r as ContentControlCollection, s as ContentControlLockState, t as ContentControlSubtype, u as ContentControlType, v as ContentControlValue, w as Document, x as DocumentCapabilities, y as DocumentLimits, z as DocumentPreview, E as DocumentPreviewStatus, F as DocumentProperties, G as DocumentXmlLimits, H as DocumentZipLimits, I as DocxEditorDebugInfo, J as DocxEditorError, K as DocxEditorErrorCode, L as DocxEditorErrorInit, M as DocxEditorInnerError, O as EditorModule, P as Field, Q as FieldCollection, R as FieldType, S as FieldTypeLiteral, T as Font, U as HeaderFooterType, V as InlinePicture, W as InlinePictureCollection, X as InsertLocation, Y as List, Z as ListBullet, _ as ListCollection, $ as ListItem, a0 as ListNumbering, a1 as LoadOption, a2 as LoadQueryOptions, a3 as NoteItem, a4 as NoteItemCollection, a5 as NoteItemType, a6 as PageOrientation, a7 as PageSetup, a8 as Paragraph, a9 as ParagraphAlignment, aa as ParagraphCollection, ab as ParagraphInsertTextLocation, ac as ParagraphReadingOrder, ad as PreviewCallback, ae as Range, af as RangeCollection, ag as RangeInsertTextLocation, ah as RangeLocation, ai as RemoveDocInfoType, aj as RequestContext, ak as Revision, al as RevisionAuthorOptions, am as RevisionAuthorSelection, an as RevisionCollection, ap as RevisionType, aq as RunCallback, ar as RunOptions, as as RuntimeDiagnostic, at as SearchOptions, au as Section, av as SectionCollection, aw as SelectionMode, ax as ServerPaginationOptions, ay as Shape, az as ShapeCollection, aA as ShapeType, aB as Table, aC as TableCell, aD as TableCellCollection, aE as TableCollection, aF as TableRow, aG as TableRowCollection, aH as TrackedObjects, aI as UnderlineType, aJ as VerticalAlignment, aK as getReviewItemRange, aL as getReviewItemRangeOrNullObject, aM as getReviewItemRevisions, aN as isDocxEditorError } from './server-BB94GFr9.js';
|
|
25
25
|
import { EditorCollaborationSession } from '@docx-editor.dev/core/collaboration';
|
|
26
26
|
export { HistoryGroup, HistoryGroupOutcome, RevisionAuthorEntry, RevisionAuthorResult, RevisionAuthorSkipReason, RevisionBatchEntry, RevisionBatchResult, RevisionBatchSkipReason } from '@docx-editor.dev/core/automation';
|
|
27
27
|
import { DocxEditorInstance } from '@docx-editor.dev/core/editor';
|
|
@@ -37,7 +37,11 @@ interface CreateBrowserOptions {
|
|
|
37
37
|
*
|
|
38
38
|
* Required to reply to a comment: `CT_TrackChange` makes `@w:author` mandatory, and the editor
|
|
39
39
|
* does not expose a signed-in identity to automation. Omitted means comment writes refuse with
|
|
40
|
-
* `NotSupported`; ordinary document reads
|
|
40
|
+
* `NotSupported` and the diagnostic `edit.comment-author-required`; ordinary document reads
|
|
41
|
+
* and writes are unaffected.
|
|
42
|
+
*
|
|
43
|
+
* To build a review UI over this editor, use `useReview()` from `@docx-editor.dev/pro/react`
|
|
44
|
+
* or `@docx-editor.dev/pro/vue` instead. It comments and replies as the editor's author.
|
|
41
45
|
*/
|
|
42
46
|
readonly author?: string;
|
|
43
47
|
/**
|