dsh-cait 1.1.3 → 1.1.7

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/lib/tools.js CHANGED
@@ -888,6 +888,250 @@ export function registerCatTools(ctx, store) {
888
888
  }
889
889
  },
890
890
  }),
891
+ ctx.tools.register({
892
+ name: 'cat_get_brief',
893
+ description:
894
+ 'Read the active CAIT document translation brief: domain, audience, tone, notes, do-not-translate terms and a style sample. Read it before translating so terminology and register match the document.',
895
+ parameters: {
896
+ type: 'object',
897
+ properties: {
898
+ documentId: {
899
+ type: 'string',
900
+ description: 'Optional CAIT document id. Defaults to the active document.',
901
+ },
902
+ },
903
+ additionalProperties: false,
904
+ },
905
+ output: {
906
+ schema: { type: 'object', additionalProperties: true },
907
+ render(_args, value) {
908
+ if (!value || value.ok === false) {
909
+ return text(`CAIT: ${value?.message || 'No active document.'}`)
910
+ }
911
+ const brief = value.brief
912
+ if (!brief) return text('CAIT brief: not set for this document.')
913
+ const labels = {
914
+ domain: 'Domain',
915
+ audience: 'Audience',
916
+ tone: 'Tone',
917
+ notes: 'Notes',
918
+ doNotTranslate: 'Do not translate',
919
+ styleSample: 'Style sample',
920
+ }
921
+ const lines = ['CAIT brief:']
922
+ for (const field of Object.keys(labels)) {
923
+ if (brief[field]) lines.push(`${labels[field]}: ${brief[field]}`)
924
+ }
925
+ return text(lines.join('\n'))
926
+ },
927
+ },
928
+ async execute(args = {}) {
929
+ try {
930
+ return { ok: true, ...store.getBrief(args) }
931
+ } catch (error) {
932
+ return failure(error)
933
+ }
934
+ },
935
+ }),
936
+
937
+ ctx.tools.register({
938
+ name: 'cat_set_brief',
939
+ description:
940
+ 'Update the active CAIT document translation brief. Send only the fields to change; an empty string clears one field, and clear=true removes the whole brief. The brief is saved with the document and used by later translation.',
941
+ parameters: {
942
+ type: 'object',
943
+ properties: {
944
+ documentId: {
945
+ type: 'string',
946
+ description: 'Optional CAIT document id. Defaults to the active document.',
947
+ },
948
+ domain: { type: 'string', description: 'Subject domain, for example legal or gaming.' },
949
+ audience: { type: 'string', description: 'Intended readers and their background.' },
950
+ tone: { type: 'string', description: 'Register and voice, for example concise and neutral.' },
951
+ notes: { type: 'string', description: 'Other instructions for the translator.' },
952
+ doNotTranslate: { type: 'string', description: 'Terms or fragments that must stay unchanged.' },
953
+ styleSample: { type: 'string', description: 'A short sample of the desired target style.' },
954
+ clear: { type: 'boolean', description: 'Remove the whole brief. Defaults to false.' },
955
+ },
956
+ additionalProperties: false,
957
+ },
958
+ output: {
959
+ schema: { type: 'object', additionalProperties: true },
960
+ render(_args, value) {
961
+ if (!value || value.ok === false) {
962
+ return text(`CAIT: ${value?.message || 'Could not update the brief.'}`)
963
+ }
964
+ return text(value.brief ? 'CAIT brief updated.' : 'CAIT brief cleared.')
965
+ },
966
+ },
967
+ async execute(args = {}) {
968
+ try {
969
+ const { documentId, clear, ...fields } = args
970
+ return { ok: true, ...store.setBrief({ documentId, brief: fields, clear }) }
971
+ } catch (error) {
972
+ return failure(error)
973
+ }
974
+ },
975
+ }),
976
+
977
+ ctx.tools.register({
978
+ name: 'cat_get_context',
979
+ description:
980
+ 'Read a bounded context window around a CAIT segment: the document brief, the current segment and its previous/next source segments. Use it before translating or reviewing so pronouns, terms and omitted subjects are resolved from context.',
981
+ parameters: {
982
+ type: 'object',
983
+ properties: {
984
+ documentId: {
985
+ type: 'string',
986
+ description: 'Optional CAIT document id. Defaults to the active document.',
987
+ },
988
+ index: {
989
+ type: 'integer',
990
+ minimum: 0,
991
+ description: 'Zero-based segment index. Defaults to the document cursor.',
992
+ },
993
+ before: {
994
+ type: 'integer',
995
+ minimum: 0,
996
+ maximum: 5,
997
+ description: 'Previous source segments to include. Defaults to 2.',
998
+ },
999
+ after: {
1000
+ type: 'integer',
1001
+ minimum: 0,
1002
+ maximum: 5,
1003
+ description: 'Following source segments to include. Defaults to 2.',
1004
+ },
1005
+ },
1006
+ additionalProperties: false,
1007
+ },
1008
+ output: {
1009
+ schema: { type: 'object', additionalProperties: true },
1010
+ render(_args, value) {
1011
+ if (!value || value.ok === false) {
1012
+ return text(`CAIT: ${value?.message || 'No active document.'}`)
1013
+ }
1014
+ const lines = [
1015
+ `CAIT context — ${value.document.name} (${value.document.sourceLang} → ${value.document.targetLang})`,
1016
+ `Segment ${value.segment.index + 1}/${value.document.total} · ${value.segment.status}`,
1017
+ ]
1018
+ if (value.brief) {
1019
+ lines.push('', 'BRIEF:')
1020
+ for (const [field, fieldValue] of Object.entries(value.brief)) {
1021
+ if (field !== 'updatedAt' && fieldValue) lines.push(`- ${field}: ${fieldValue}`)
1022
+ }
1023
+ }
1024
+ if (value.before.length) {
1025
+ lines.push('', 'BEFORE:')
1026
+ for (const item of value.before) lines.push(`- ${item.index + 1}. ${item.source}`)
1027
+ }
1028
+ lines.push('', 'CURRENT:', value.segment.source)
1029
+ if (value.segment.target) lines.push('', 'CURRENT TARGET:', value.segment.target)
1030
+ if (value.after.length) {
1031
+ lines.push('', 'AFTER:')
1032
+ for (const item of value.after) lines.push(`- ${item.index + 1}. ${item.source}`)
1033
+ }
1034
+ return text(lines.join('\n'))
1035
+ },
1036
+ },
1037
+ async execute(args = {}) {
1038
+ try {
1039
+ return { ok: true, ...store.contextForTool(args) }
1040
+ } catch (error) {
1041
+ return failure(error)
1042
+ }
1043
+ },
1044
+ }),
1045
+
1046
+ ctx.tools.register({
1047
+ name: 'cat_unconfirm_segment',
1048
+ description:
1049
+ 'Revoke the confirmation of a CAIT segment. The translated text stays as a draft and translation memory is not changed. Use it when a confirmed segment needs rework before it is confirmed again.',
1050
+ parameters: {
1051
+ type: 'object',
1052
+ properties: {
1053
+ documentId: {
1054
+ type: 'string',
1055
+ description: 'Optional CAIT document id. Defaults to the active document.',
1056
+ },
1057
+ index: {
1058
+ type: 'integer',
1059
+ minimum: 0,
1060
+ description: 'Zero-based segment index. Defaults to the document cursor.',
1061
+ },
1062
+ },
1063
+ additionalProperties: false,
1064
+ },
1065
+ output: {
1066
+ schema: { type: 'object', additionalProperties: true },
1067
+ render(_args, value) {
1068
+ if (!value || value.ok === false) {
1069
+ return text(`CAIT: ${value?.message || 'Could not unconfirm the segment.'}`)
1070
+ }
1071
+ return text(
1072
+ `CAIT: segment ${value.index + 1} is now ${value.segment.status}; translation memory was left unchanged.`,
1073
+ )
1074
+ },
1075
+ },
1076
+ async execute(args = {}) {
1077
+ try {
1078
+ return { ok: true, ...store.unconfirmSegment(args) }
1079
+ } catch (error) {
1080
+ return failure(error)
1081
+ }
1082
+ },
1083
+ }),
1084
+
1085
+ ctx.tools.register({
1086
+ name: 'cat_concordance',
1087
+ description:
1088
+ 'Search every mounted CAIT translation-memory entry for a word or phrase in the source or target text. Use it to check how a term was translated elsewhere; results are capped and carry their surrounding context.',
1089
+ parameters: {
1090
+ type: 'object',
1091
+ properties: {
1092
+ query: { type: 'string', description: 'Word or phrase to search for.' },
1093
+ documentId: {
1094
+ type: 'string',
1095
+ description: 'Optional CAIT document id whose language pair filters results.',
1096
+ },
1097
+ sourceLang: { type: 'string', description: 'Optional source language filter.' },
1098
+ targetLang: { type: 'string', description: 'Optional target language filter.' },
1099
+ limit: {
1100
+ type: 'integer',
1101
+ minimum: 1,
1102
+ maximum: 50,
1103
+ description: 'Maximum matches to return. Defaults to 20.',
1104
+ },
1105
+ },
1106
+ required: ['query'],
1107
+ additionalProperties: false,
1108
+ },
1109
+ output: {
1110
+ schema: { type: 'object', additionalProperties: true },
1111
+ render(_args, value) {
1112
+ if (!value || value.ok === false) {
1113
+ return text(`CAIT: ${value?.message || 'Concordance search failed.'}`)
1114
+ }
1115
+ if (!value.entries.length) return text(`CAIT concordance: no match for “${value.query}”.`)
1116
+ const lines = [`CAIT concordance: ${value.total} match(es), showing ${value.entries.length}.`]
1117
+ for (const entry of value.entries) {
1118
+ lines.push('', `${entry.source} → ${entry.target}`)
1119
+ if (entry.context?.prev || entry.context?.next) {
1120
+ lines.push(` context: ${entry.context.prev || '—'} | ${entry.context.next || '—'}`)
1121
+ }
1122
+ }
1123
+ return text(lines.join('\n'))
1124
+ },
1125
+ },
1126
+ async execute(args = {}) {
1127
+ try {
1128
+ return { ok: true, ...store.concordance(args) }
1129
+ } catch (error) {
1130
+ return failure(error)
1131
+ }
1132
+ },
1133
+ }),
1134
+
891
1135
  ctx.tools.register({
892
1136
  name: 'cat_add_terms',
893
1137
  description:
@@ -910,6 +1154,14 @@ export function registerCatTools(ctx, store) {
910
1154
  note: { type: 'string', description: 'Optional note.' },
911
1155
  sourceLang: { type: 'string', description: 'Optional source language tag.' },
912
1156
  caseSensitive: { type: 'boolean', description: 'Match this term case-sensitively.' },
1157
+ forbidden: {
1158
+ type: 'boolean',
1159
+ description: 'Never use this translation; it is a forbidden rendering of the source term.',
1160
+ },
1161
+ preferred: {
1162
+ type: 'boolean',
1163
+ description: 'Require this translation when the source term appears.',
1164
+ },
913
1165
  },
914
1166
  required: ['source', 'target'],
915
1167
  additionalProperties: false,
@@ -936,6 +1188,48 @@ export function registerCatTools(ctx, store) {
936
1188
  }
937
1189
  },
938
1190
  }),
1191
+
1192
+ ctx.tools.register({
1193
+ name: 'cat_review',
1194
+ description:
1195
+ 'Run one LLM review pass over a bounded range of translated segments. Returns structured issues with severity, code, message and an optional replacement suggestion. It never writes to the document; report the issues or apply a suggestion through cat_submit_translation after the user agrees.',
1196
+ parameters: {
1197
+ type: 'object',
1198
+ properties: {
1199
+ documentId: { type: 'string', description: 'CAIT document id. Defaults to the active document.' },
1200
+ from: { type: 'integer', minimum: 0, description: 'Zero-based first segment index. Defaults to 0.' },
1201
+ count: {
1202
+ type: 'integer',
1203
+ minimum: 1,
1204
+ maximum: 20,
1205
+ description: 'Segments to review in this pass. Defaults to 20.',
1206
+ },
1207
+ },
1208
+ additionalProperties: false,
1209
+ },
1210
+ output: {
1211
+ schema: { type: 'object', additionalProperties: true },
1212
+ render(_args, value) {
1213
+ if (!value || value.ok === false) {
1214
+ return text(`CAIT: ${value?.message || 'AI review failed.'}`)
1215
+ }
1216
+ if (!value.issues.length) return text(`CAIT review: no issue found in segments ${value.from}–${value.to - 1}.`)
1217
+ const lines = [`CAIT review: ${value.issues.length} issue(s) in segments ${value.from}–${value.to - 1}.`]
1218
+ for (const issue of value.issues) {
1219
+ lines.push('', `[${issue.severity}] #${issue.index} ${issue.code}: ${issue.message}`)
1220
+ if (issue.suggestion) lines.push(` suggestion: ${issue.suggestion}`)
1221
+ }
1222
+ return text(lines.join('\n'))
1223
+ },
1224
+ },
1225
+ async execute(args = {}) {
1226
+ try {
1227
+ return { ok: true, ...(await store.reviewDocument(args)) }
1228
+ } catch (error) {
1229
+ return failure(error)
1230
+ }
1231
+ },
1232
+ }),
939
1233
  ]
940
1234
 
941
1235
  return () => {
package/lib/xlsx.js CHANGED
@@ -33,24 +33,33 @@ function sharedStringTable(xml) {
33
33
  ))
34
34
  }
35
35
 
36
- function firstSheetPath(entries) {
36
+ function workbookSheets(entries) {
37
37
  const workbook = zipText(entries, 'xl/workbook.xml')
38
38
  const rels = zipText(entries, 'xl/_rels/workbook.xml.rels')
39
- if (workbook && rels) {
40
- const sheet = workbook.match(/<sheet\b([^>]*)\/?>/i)
41
- const id = sheet ? attributes(sheet[1])['r:id'] : ''
42
- if (id) {
43
- const relation = [...rels.matchAll(/<Relationship\b([^>]*)\/?>/gi)]
44
- .map((match) => attributes(match[1]))
45
- .find((item) => item.Id === id)
46
- if (relation?.Target) {
47
- const target = relation.Target.replace(/^\/+/, '')
48
- return target.startsWith('xl/') ? target : `xl/${target}`
49
- }
50
- }
39
+ const relationMap = new Map(
40
+ [...rels.matchAll(/<Relationship\b([^>]*)\/?>/gi)]
41
+ .map((match) => attributes(match[1]))
42
+ .filter((item) => item.Id && item.Target)
43
+ .map((item) => [item.Id, item.Target]),
44
+ )
45
+ const sheets = []
46
+ for (const match of workbook.matchAll(/<sheet\b([^>]*)\/?>/gi)) {
47
+ const attrs = attributes(match[1])
48
+ const id = attrs['r:id']
49
+ const target = relationMap.get(id)
50
+ if (!target) continue
51
+ const path = target.replace(/^\/+/, '')
52
+ sheets.push({
53
+ name: attrs.name || `Sheet${sheets.length + 1}`,
54
+ path: path.startsWith('xl/') ? path : `xl/${path}`,
55
+ })
51
56
  }
52
- const fallback = entries.find((item) => /^xl\/worksheets\/sheet\d+\.xml$/i.test(item.name))
53
- return fallback?.name ?? 'xl/worksheets/sheet1.xml'
57
+ if (sheets.length) return sheets
58
+ return entries
59
+ .map((entry) => entry.name)
60
+ .filter((name) => /^xl\/worksheets\/sheet\d+\.xml$/i.test(name))
61
+ .sort((left, right) => Number(left.match(/(\d+)\.xml$/)[1]) - Number(right.match(/(\d+)\.xml$/)[1]))
62
+ .map((path, index) => ({ name: `Sheet${index + 1}`, path }))
54
63
  }
55
64
 
56
65
  function columnIndex(reference) {
@@ -85,7 +94,12 @@ function parseRows(xml, shared) {
85
94
  for (const cellMatch of rowMatch[2].matchAll(/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/gi)) {
86
95
  const attrs = attributes(cellMatch[1])
87
96
  if (!attrs.r) continue
88
- cells.set(columnIndex(attrs.r), cellValue(attrs, cellMatch[2] ?? '', shared))
97
+ const body = cellMatch[2] ?? ''
98
+ cells.set(columnIndex(attrs.r), {
99
+ cell: attrs.r,
100
+ value: cellValue(attrs, body, shared),
101
+ formula: /<f\b/i.test(body),
102
+ })
89
103
  }
90
104
  if (cells.size) rows.set(rowNumber, cells)
91
105
  }
@@ -100,39 +114,53 @@ export function parseXlsx(buffer) {
100
114
  throw fail('XLSX_PARSE', `XLSX 文件不是有效的 ZIP/Excel 包: ${error.message}`)
101
115
  }
102
116
  const shared = sharedStringTable(zipText(entries, 'xl/sharedStrings.xml'))
103
- const sheetPath = firstSheetPath(entries)
104
- const sheetXml = zipText(entries, sheetPath)
105
- if (!sheetXml) throw fail('XLSX_PARSE', 'XLSX 中找不到工作表。')
106
- const rows = parseRows(sheetXml, shared)
107
- if (!rows.length) throw fail('XLSX_NO_UNITS', 'XLSX 中没有可用的行。')
108
-
109
- const maxColumns = rows.reduce((max, [, cells]) => Math.max(max, ...cells.keys(), -1), -1) + 1
110
- const first = rows[0][1]
111
- const header = (index) => String(first.get(index) ?? '').trim().toLowerCase()
112
- let sourceIndex = -1
113
- let targetIndex = -1
114
- for (let index = 0; index < maxColumns; index += 1) {
115
- if (SOURCE_HEADERS.has(header(index))) sourceIndex = index
116
- if (TARGET_HEADERS.has(header(index))) targetIndex = index
117
- }
118
- const hasHeader = sourceIndex >= 0 && targetIndex >= 0
119
- if (!hasHeader) {
120
- sourceIndex = 0
121
- targetIndex = maxColumns > 1 ? 1 : -1
122
- }
117
+ const sheets = workbookSheets(entries)
118
+ if (!sheets.length) throw fail('XLSX_PARSE', 'XLSX 中找不到工作表。')
123
119
 
124
120
  const segments = []
125
- for (const [rowNumber, cells] of rows) {
126
- if (hasHeader && rowNumber === rows[0][0]) continue
127
- const source = String(cells.get(sourceIndex) ?? '').trim()
128
- if (!source) continue
129
- const target = targetIndex >= 0 ? String(cells.get(targetIndex) ?? '').trim() : ''
130
- segments.push({
131
- source,
132
- target,
133
- paragraph: segments.length,
134
- meta: { format: 'xlsx', xlsxRow: rowNumber },
135
- })
121
+ for (const [sheetIndex, sheet] of sheets.entries()) {
122
+ const sheetXml = zipText(entries, sheet.path)
123
+ if (!sheetXml) continue
124
+ const rows = parseRows(sheetXml, shared)
125
+ if (!rows.length) continue
126
+
127
+ const maxColumns = rows.reduce((max, [, cells]) => Math.max(max, ...cells.keys(), -1), -1) + 1
128
+ const first = rows[0][1]
129
+ const header = (index) => String(first.get(index)?.value ?? '').trim().toLowerCase()
130
+ let sourceIndex = -1
131
+ let targetIndex = -1
132
+ for (let index = 0; index < maxColumns; index += 1) {
133
+ if (SOURCE_HEADERS.has(header(index))) sourceIndex = index
134
+ if (TARGET_HEADERS.has(header(index))) targetIndex = index
135
+ }
136
+ const hasHeader = sourceIndex >= 0 && targetIndex >= 0
137
+ if (!hasHeader) {
138
+ sourceIndex = 0
139
+ targetIndex = maxColumns > 1 ? 1 : -1
140
+ }
141
+
142
+ for (const [rowNumber, cells] of rows) {
143
+ if (hasHeader && rowNumber === rows[0][0]) continue
144
+ const sourceCell = cells.get(sourceIndex)
145
+ if (!sourceCell || sourceCell.formula) continue
146
+ const source = String(sourceCell.value ?? '').trim()
147
+ if (!source) continue
148
+ const targetCell = targetIndex >= 0 ? cells.get(targetIndex) : null
149
+ const target = targetCell ? String(targetCell.value ?? '').trim() : ''
150
+ segments.push({
151
+ source,
152
+ target,
153
+ paragraph: segments.length,
154
+ meta: {
155
+ format: 'xlsx',
156
+ xlsxRow: rowNumber,
157
+ sheet: sheetIndex + 1,
158
+ sheetName: sheet.name,
159
+ cell: sourceCell.cell,
160
+ ...(targetCell?.cell ? { targetCell: targetCell.cell } : {}),
161
+ },
162
+ })
163
+ }
136
164
  }
137
165
  if (!segments.length) throw fail('XLSX_NO_UNITS', 'XLSX 中没有可用的源文行。')
138
166
  return { format: 'xlsx', segments, warnings: [] }
@@ -153,23 +181,12 @@ function columnName(index) {
153
181
  return name
154
182
  }
155
183
 
156
- export function buildXlsx(doc) {
157
- const rows = [[
158
- inlineCell('A1', 'Source'),
159
- inlineCell('B1', 'Target'),
160
- ]]
161
- doc.segments.forEach((segment, index) => {
162
- const row = index + 2
163
- rows.push([
164
- inlineCell(`A${row}`, segment.source || ''),
165
- inlineCell(`B${row}`, segment.target || ''),
166
- ])
167
- })
184
+ function sheetXml(rows) {
168
185
  const sheetData = rows
169
186
  .map((cells, index) => ` <row r="${index + 1}">${cells.join('')}</row>`)
170
187
  .join('\n')
171
- const lastRow = rows.length + 1
172
- const sheet = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
188
+ const lastRow = Math.max(rows.length, 1)
189
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
173
190
  <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
174
191
  <dimension ref="A1:B${lastRow}"/>
175
192
  <sheetViews><sheetView workbookViewId="0"/></sheetViews>
@@ -178,12 +195,105 @@ export function buildXlsx(doc) {
178
195
  ${sheetData}
179
196
  </sheetData>
180
197
  </worksheet>`
198
+ }
199
+
200
+ function safeSheetName(name, used) {
201
+ let base = String(name ?? '').replace(/[\[\]:*?\/\\]/g, ' ').trim().slice(0, 31) || 'Sheet'
202
+ let candidate = base
203
+ let index = 2
204
+ while (used.has(candidate.toLowerCase())) {
205
+ const suffix = ` ${index}`
206
+ candidate = `${base.slice(0, 31 - suffix.length)}${suffix}`
207
+ index += 1
208
+ }
209
+ used.add(candidate.toLowerCase())
210
+ return candidate
211
+ }
212
+
213
+ function replaceCellText(xml, reference, value) {
214
+ const escaped = escapeXml(value)
215
+ const pattern = new RegExp(
216
+ `<c\\b([^>]*\\br="${reference}"[^>]*?)(?:/>|>([\\s\\S]*?)<\\/c>)`,
217
+ 'i',
218
+ )
219
+ let found = false
220
+ const output = String(xml).replace(pattern, (all, rawAttrs, body = '') => {
221
+ if (/<f\b/i.test(body)) return all
222
+ found = true
223
+ const attrs = rawAttrs.replace(/\s+t="[^"]*"/gi, '').replace(/\s*\/\s*$/g, '')
224
+ return `<c${attrs} t="inlineStr"><is><t xml:space="preserve">${escaped}</t></is></c>`
225
+ })
226
+ return { xml: output, found }
227
+ }
228
+
229
+ /**
230
+ * Write target text back into the original workbook. Rebuilding a workbook
231
+ * drops styles, column widths and merged ranges; patching the source zip keeps
232
+ * everything except the translated cell content intact.
233
+ */
234
+ export function patchXlsx(doc, template) {
235
+ let entries
236
+ try {
237
+ entries = readZipEntries(template)
238
+ } catch (error) {
239
+ throw fail('XLSX_SOURCE_INVALID', `XLSX 源文件不是有效的 ZIP/Excel 包: ${error.message}`)
240
+ }
241
+ const sheetPaths = new Map(workbookSheets(entries).map((sheet) => [sheet.name, sheet.path]))
242
+ const bySheet = new Map()
243
+ for (const segment of doc.segments) {
244
+ const sheetName = segment.meta?.sheetName
245
+ const cell = segment.meta?.targetCell
246
+ if (!sheetName || !cell) continue
247
+ if (!bySheet.has(sheetName)) bySheet.set(sheetName, new Map())
248
+ bySheet.get(sheetName).set(cell, String(segment.target || segment.source || ''))
249
+ }
250
+
251
+ let patched = 0
252
+ let missing = 0
253
+ const next = entries.map((entry) => {
254
+ const sheetName = [...sheetPaths.entries()].find(([, path]) => path === entry.name)?.[0]
255
+ const replacements = sheetName ? bySheet.get(sheetName) : null
256
+ if (!replacements?.size) return entry
257
+ let xml = entry.data.toString('utf8')
258
+ for (const [cell, text] of replacements) {
259
+ const result = replaceCellText(xml, cell, text)
260
+ xml = result.xml
261
+ if (result.found) patched += 1
262
+ else missing += 1
263
+ }
264
+ return { ...entry, data: Buffer.from(xml, 'utf8') }
265
+ })
266
+ return { buffer: writeZip(next), patched, missing }
267
+ }
268
+
269
+ export function buildXlsx(doc) {
270
+ const groups = new Map()
271
+ for (const segment of doc.segments) {
272
+ const key = segment.meta?.sheetName || `Sheet ${Number(segment.meta?.sheet) || 1}`
273
+ if (!groups.has(key)) groups.set(key, [])
274
+ groups.get(key).push(segment)
275
+ }
276
+ if (!groups.size) groups.set('Sheet 1', [])
277
+
278
+ const used = new Set()
279
+ const sheets = [...groups.entries()].map(([name, segments], index) => ({
280
+ name: safeSheetName(name, used),
281
+ path: `xl/worksheets/sheet${index + 1}.xml`,
282
+ rows: [
283
+ [inlineCell('A1', 'Source'), inlineCell('B1', 'Target')],
284
+ ...segments.map((segment, rowIndex) => [
285
+ inlineCell(`A${rowIndex + 2}`, segment.source || ''),
286
+ inlineCell(`B${rowIndex + 2}`, segment.target || ''),
287
+ ]),
288
+ ],
289
+ }))
290
+
181
291
  const contentTypes = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
182
292
  <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
183
293
  <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
184
294
  <Default Extension="xml" ContentType="application/xml"/>
185
295
  <Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
186
- <Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>
296
+ ${sheets.map((sheet) => ` <Override PartName="/${sheet.path}" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`).join('\n')}
187
297
  <Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>
188
298
  </Types>`
189
299
  const rootRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
@@ -192,12 +302,12 @@ ${sheetData}
192
302
  </Relationships>`
193
303
  const workbook = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
194
304
  <workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
195
- <sheets><sheet name="CAIT" sheetId="1" r:id="rId1"/></sheets>
305
+ <sheets>${sheets.map((sheet, index) => `<sheet name="${escapeXml(sheet.name)}" sheetId="${index + 1}" r:id="rId${index + 1}"/>`).join('')}</sheets>
196
306
  </workbook>`
197
307
  const workbookRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
198
308
  <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
199
- <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>
200
- <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
309
+ ${sheets.map((sheet, index) => ` <Relationship Id="rId${index + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet${index + 1}.xml"/>`).join('\n')}
310
+ <Relationship Id="rId${sheets.length + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
201
311
  </Relationships>`
202
312
  const styles = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
203
313
  <styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
@@ -212,7 +322,7 @@ ${sheetData}
212
322
  { name: '_rels/.rels', data: Buffer.from(rootRels, 'utf8') },
213
323
  { name: 'xl/workbook.xml', data: Buffer.from(workbook, 'utf8') },
214
324
  { name: 'xl/_rels/workbook.xml.rels', data: Buffer.from(workbookRels, 'utf8') },
215
- { name: 'xl/worksheets/sheet1.xml', data: Buffer.from(sheet, 'utf8') },
325
+ ...sheets.map((sheet) => ({ name: sheet.path, data: Buffer.from(sheetXml(sheet.rows), 'utf8') })),
216
326
  { name: 'xl/styles.xml', data: Buffer.from(styles, 'utf8') },
217
327
  ])
218
328
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cait",
3
- "version": "1.1.3",
3
+ "version": "1.1.7",
4
4
  "license": "Apache-2.0",
5
5
  "author": {
6
6
  "name": "Jovi Lecca",