@ai-matrx/alchemy 0.18.0 → 0.19.1

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.
@@ -1204,7 +1204,7 @@ type Notice = {
1204
1204
  };
1205
1205
  interface FormatOptions {
1206
1206
  filename?: string;
1207
- /** Formula guard for delimited text; unset = kit `spreadsheetSafeByDefault(format)` (on for csv/tsv/xlsx). */
1207
+ /** Formula guard for delimited text; unset = kit `spreadsheetSafeByDefault(format)` (on for csv/tsv; an .xlsx's typed text cells are never evaluated, its plain text is the guarded TSV). */
1208
1208
  spreadsheetSafe?: boolean;
1209
1209
  /** Markdown→HTML skin: the two page looks plus "inline" for the rich clipboard (styles on elements). */
1210
1210
  skin?: "document" | "article" | "inline";
@@ -1224,8 +1224,8 @@ interface FormatEngine {
1224
1224
  * `@ai-matrx/alchemy/operate/read` — the one parse door (ALC-19 T4–T12). Write has `buildFile`; read has `readFile`.
1225
1225
  *
1226
1226
  * One engine per format across read and write:
1227
- * - CSV / TSV / delimited text: THIS module's parser (no library), the reverse of the `csv`/`tsv`
1228
- * serializers in `./core`. `parseDelimited` is Papa Parse–compatible in the options the platform
1227
+ * - CSV / TSV / delimited text: kit's `parseDelimited` (no library; it sits in `@ai-matrx/kit/delimited`
1228
+ * beside the one writer so packages below alchemy read through it too), re-exported here. `parseDelimited` is Papa Parse–compatible in the options the platform
1229
1229
  * uses (auto delimiter + line ending, quotes, `skipEmptyLines` true | "greedy", `header`,
1230
1230
  * `transformHeader`, `dynamicTyping`) and answers the same `{ data, errors, meta }` shape and
1231
1231
  * error codes, so a repointed importer keeps its behaviour.
@@ -1204,7 +1204,7 @@ type Notice = {
1204
1204
  };
1205
1205
  interface FormatOptions {
1206
1206
  filename?: string;
1207
- /** Formula guard for delimited text; unset = kit `spreadsheetSafeByDefault(format)` (on for csv/tsv/xlsx). */
1207
+ /** Formula guard for delimited text; unset = kit `spreadsheetSafeByDefault(format)` (on for csv/tsv; an .xlsx's typed text cells are never evaluated, its plain text is the guarded TSV). */
1208
1208
  spreadsheetSafe?: boolean;
1209
1209
  /** Markdown→HTML skin: the two page looks plus "inline" for the rich clipboard (styles on elements). */
1210
1210
  skin?: "document" | "article" | "inline";
@@ -1224,8 +1224,8 @@ interface FormatEngine {
1224
1224
  * `@ai-matrx/alchemy/operate/read` — the one parse door (ALC-19 T4–T12). Write has `buildFile`; read has `readFile`.
1225
1225
  *
1226
1226
  * One engine per format across read and write:
1227
- * - CSV / TSV / delimited text: THIS module's parser (no library), the reverse of the `csv`/`tsv`
1228
- * serializers in `./core`. `parseDelimited` is Papa Parse–compatible in the options the platform
1227
+ * - CSV / TSV / delimited text: kit's `parseDelimited` (no library; it sits in `@ai-matrx/kit/delimited`
1228
+ * beside the one writer so packages below alchemy read through it too), re-exported here. `parseDelimited` is Papa Parse–compatible in the options the platform
1229
1229
  * uses (auto delimiter + line ending, quotes, `skipEmptyLines` true | "greedy", `header`,
1230
1230
  * `transformHeader`, `dynamicTyping`) and answers the same `{ data, errors, meta }` shape and
1231
1231
  * error codes, so a repointed importer keeps its behaviour.
@@ -138,10 +138,9 @@ EOD`}return{to_workbook:dif_to_workbook,to_sheet:dif_to_sheet,from_sheet:sheet_t
138
138
  </table:calculation-settings>
139
139
  `);for(var i=0;i!=wb.SheetNames.length;++i)o.push(write_ws(wb.Sheets[wb.SheetNames[i]],wb,i,opts,nfs,((wb.Workbook||{}).WBProps||{}).date1904));return(wb.Workbook||{}).Names&&o.push(write_names_ods(wb.Workbook.Names,wb.SheetNames,-1)),o.push(` </office:spreadsheet>
140
140
  `),o.push(` </office:body>
141
- `),opts.bookType=="fods"?o.push("</office:document>"):o.push("</office:document-content>"),o.join("")}})();subarray=(function(){try{return typeof Uint8Array>"u"||typeof Uint8Array.prototype.subarray>"u"?"slice":typeof Buffer<"u"?typeof Buffer.prototype.subarray>"u"?"slice":(typeof Buffer.from=="function"?Buffer.from([72,62]):new Buffer([72,62]))instanceof Uint8Array?"subarray":"slice":"subarray"}catch{return"slice"}})();numbers_lut_new=function(){return{sst:[],rsst:[],ofmt:[],nfmt:[],fmla:[],ferr:[],cmnt:[]}};USE_WIDE_ROWS=!0;qreg=/"/g;utils={encode_col,encode_row,encode_cell,encode_range,decode_col,decode_row,split_cell,decode_cell,decode_range,format_cell,sheet_new,sheet_add_aoa,sheet_add_json,sheet_add_dom,aoa_to_sheet,json_to_sheet,table_to_sheet:parse_dom_table,table_to_book,sheet_to_csv,sheet_to_txt,sheet_to_json,sheet_to_html,sheet_to_formulae,sheet_to_row_object_array:sheet_to_json,sheet_get_cell:ws_get_cell_stub,book_new,book_append_sheet,book_set_sheet_visibility,cell_set_number_format,cell_set_hyperlink,cell_set_internal_link,cell_add_comment,sheet_set_array_formula,consts:{SHEET_VISIBLE:0,SHEET_HIDDEN:1,SHEET_VERY_HIDDEN:2}};__stream={to_json:write_json_stream,to_html:write_html_stream,to_csv:write_csv_stream,to_xlml:write_xlml_stream,set_readable},version=XLSX.version,xlsx_default={parse_xlscfb,parse_zip,read:readSync,readFile:readFileSync,readFileSync,write:writeSync,writeFile:writeFileSync,writeFileSync,writeFileAsync,writeXLSX:writeSyncXLSX,writeFileXLSX:writeFileSyncXLSX,utils,set_fs,set_cptable,stream:__stream,SSF,CFB}}});import{downloadFile}from"@ai-matrx/kit/download";import{stringifyJson}from"@ai-matrx/kit/json-format";import{escapeHtml}from"@ai-matrx/kit/html-escape";import{encodeDelimitedCell,spreadsheetSafeByDefault}from"@ai-matrx/kit/delimited";import{ContentTransferError,cloneTransferJson,normalizeTransferJsonAtPath}from"@ai-matrx/kit/transfer-json";import{ContentTransferError as ContentTransferError2,normalizeTransferJson}from"@ai-matrx/kit/transfer-json";var enc=x=>x.replace(/~/g,"~0").replace(/\//g,"~1"),dec=x=>x.replace(/~1/g,"/").replace(/~0/g,"~");function deepFreeze(v){if(ArrayBuffer.isView(v))return v;if(v&&typeof v=="object"&&!Object.isFrozen(v)){Object.freeze(v);for(let x of Object.values(v))deepFreeze(x)}return v}function at(v,path){if(validatePointer(path),path==="")return v;if(!path.startsWith("/"))throw new ContentTransferError("invalid-path","Expected RFC 6901 pointer",path);let cur=v;for(let part of path.slice(1).split("/").map(dec))if(Array.isArray(cur))cur=cur[Number(part)];else if(cur&&typeof cur=="object")cur=Object.hasOwn(cur,part)?cur[part]:void 0;else return;return cur}function validatePointer(path){if(path!==""&&!path.startsWith("/")||/~(?![01])/u.test(path))throw new ContentTransferError("invalid-path","Expected an RFC 6901 JSON pointer",path)}function readTransferCell(row,column){return at(row,column.path)}var textValue=value=>value==null?"":typeof value=="string"?value:stringifyJson(value,{style:"compact"});function sealTransferArtifact(artifact){if(!artifact.file)return deepFreeze({...artifact,omissions:artifact.omissions.map(o=>({...o}))});let bytes=artifact.file.bytes.slice(),file={filename:artifact.file.filename,mime:artifact.file.mime,get bytes(){return bytes.slice()}};return deepFreeze({...artifact,file,omissions:artifact.omissions.map(o=>({...o}))})}function exportedColumns(columns){return columns.filter(c=>c.visible&&c.exportable!==!1&&c.classification!=="secret"&&c.classification!=="credential")}function serialize(draft,format,options={}){let payload=draft.payload,omissions=draft.omissions.map(o=>({...o})),plainText="",html,mime="text/plain;charset=utf-8",extension="txt",columnCell=(row,column)=>textValue(readTransferCell(row,column));if((format==="csv"||format==="tsv")&&payload.kind!=="rows")throw new ContentTransferError("unsupported-format",`${format.toUpperCase()} requires tabular data`);if(format==="json"||format==="compact-json"){let value=payload.kind==="rows"?payload.rows:payload.kind==="text"||payload.kind==="markdown"?payload.text:payload.value;plainText=stringifyJson(value,{style:format==="json"?"pretty":"compact"}),mime="application/json;charset=utf-8",extension="json"}else if(payload.kind==="rows"){let columns=exportedColumns(payload.columns);if(format==="markdown"){let escapeCell=value=>escapeHtml(value).replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\r\n|\r|\n/g,"<br>");plainText=[`| ${columns.map(c=>escapeCell(c.label)).join(" | ")} |`,`| ${columns.map(()=>"---").join(" | ")} |`,...payload.rows.map(row=>`| ${columns.map(c=>escapeCell(columnCell(row,c))).join(" | ")} |`)].join(`
141
+ `),opts.bookType=="fods"?o.push("</office:document>"):o.push("</office:document-content>"),o.join("")}})();subarray=(function(){try{return typeof Uint8Array>"u"||typeof Uint8Array.prototype.subarray>"u"?"slice":typeof Buffer<"u"?typeof Buffer.prototype.subarray>"u"?"slice":(typeof Buffer.from=="function"?Buffer.from([72,62]):new Buffer([72,62]))instanceof Uint8Array?"subarray":"slice":"subarray"}catch{return"slice"}})();numbers_lut_new=function(){return{sst:[],rsst:[],ofmt:[],nfmt:[],fmla:[],ferr:[],cmnt:[]}};USE_WIDE_ROWS=!0;qreg=/"/g;utils={encode_col,encode_row,encode_cell,encode_range,decode_col,decode_row,split_cell,decode_cell,decode_range,format_cell,sheet_new,sheet_add_aoa,sheet_add_json,sheet_add_dom,aoa_to_sheet,json_to_sheet,table_to_sheet:parse_dom_table,table_to_book,sheet_to_csv,sheet_to_txt,sheet_to_json,sheet_to_html,sheet_to_formulae,sheet_to_row_object_array:sheet_to_json,sheet_get_cell:ws_get_cell_stub,book_new,book_append_sheet,book_set_sheet_visibility,cell_set_number_format,cell_set_hyperlink,cell_set_internal_link,cell_add_comment,sheet_set_array_formula,consts:{SHEET_VISIBLE:0,SHEET_HIDDEN:1,SHEET_VERY_HIDDEN:2}};__stream={to_json:write_json_stream,to_html:write_html_stream,to_csv:write_csv_stream,to_xlml:write_xlml_stream,set_readable},version=XLSX.version,xlsx_default={parse_xlscfb,parse_zip,read:readSync,readFile:readFileSync,readFileSync,write:writeSync,writeFile:writeFileSync,writeFileSync,writeFileAsync,writeXLSX:writeSyncXLSX,writeFileXLSX:writeFileSyncXLSX,utils,set_fs,set_cptable,stream:__stream,SSF,CFB}}});import{toDelimited}from"@ai-matrx/kit/delimited";import{downloadFile}from"@ai-matrx/kit/download";import{stringifyJson}from"@ai-matrx/kit/json-format";import{escapeHtml}from"@ai-matrx/kit/html-escape";import{encodeDelimitedCell,spreadsheetSafeByDefault}from"@ai-matrx/kit/delimited";import{ContentTransferError,cloneTransferJson,normalizeTransferJsonAtPath}from"@ai-matrx/kit/transfer-json";import{ContentTransferError as ContentTransferError2,normalizeTransferJson}from"@ai-matrx/kit/transfer-json";var enc=x=>x.replace(/~/g,"~0").replace(/\//g,"~1"),dec=x=>x.replace(/~1/g,"/").replace(/~0/g,"~");function deepFreeze(v){if(ArrayBuffer.isView(v))return v;if(v&&typeof v=="object"&&!Object.isFrozen(v)){Object.freeze(v);for(let x of Object.values(v))deepFreeze(x)}return v}function at(v,path){if(validatePointer(path),path==="")return v;if(!path.startsWith("/"))throw new ContentTransferError("invalid-path","Expected RFC 6901 pointer",path);let cur=v;for(let part of path.slice(1).split("/").map(dec))if(Array.isArray(cur))cur=cur[Number(part)];else if(cur&&typeof cur=="object")cur=Object.hasOwn(cur,part)?cur[part]:void 0;else return;return cur}function validatePointer(path){if(path!==""&&!path.startsWith("/")||/~(?![01])/u.test(path))throw new ContentTransferError("invalid-path","Expected an RFC 6901 JSON pointer",path)}function readTransferCell(row,column){return at(row,column.path)}var textValue=value=>value==null?"":typeof value=="string"?value:stringifyJson(value,{style:"compact"});function sealTransferArtifact(artifact){if(!artifact.file)return deepFreeze({...artifact,omissions:artifact.omissions.map(o=>({...o}))});let bytes=artifact.file.bytes.slice(),file={filename:artifact.file.filename,mime:artifact.file.mime,get bytes(){return bytes.slice()}};return deepFreeze({...artifact,file,omissions:artifact.omissions.map(o=>({...o}))})}function exportedColumns(columns){return columns.filter(c=>c.visible&&c.exportable!==!1&&c.classification!=="secret"&&c.classification!=="credential")}function serialize(draft,format,options={}){let payload=draft.payload,omissions=draft.omissions.map(o=>({...o})),plainText="",html,mime="text/plain;charset=utf-8",extension="txt",columnCell=(row,column)=>textValue(readTransferCell(row,column));if((format==="csv"||format==="tsv")&&payload.kind!=="rows")throw new ContentTransferError("unsupported-format",`${format.toUpperCase()} requires tabular data`);if(format==="json"||format==="compact-json"){let value=payload.kind==="rows"?payload.rows:payload.kind==="text"||payload.kind==="markdown"?payload.text:payload.value;plainText=stringifyJson(value,{style:format==="json"?"pretty":"compact"}),mime="application/json;charset=utf-8",extension="json"}else if(payload.kind==="rows"){let columns=exportedColumns(payload.columns);if(format==="markdown"){let escapeCell=value=>escapeHtml(value).replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\r\n|\r|\n/g,"<br>");plainText=[`| ${columns.map(c=>escapeCell(c.label)).join(" | ")} |`,`| ${columns.map(()=>"---").join(" | ")} |`,...payload.rows.map(row=>`| ${columns.map(c=>escapeCell(columnCell(row,c))).join(" | ")} |`)].join(`
142
142
  `),mime="text/markdown;charset=utf-8",extension="md"}else{let delimiter=format==="csv"?",":" ",safe=options.spreadsheetSafe??spreadsheetSafeByDefault(format),encode=(value,path,isString=!0)=>{let out=encodeDelimitedCell(value,{delimiter,spreadsheetSafe:safe&&isString});return out.escaped&&omissions.push({path,reason:"escaped",count:1}),out.text};plainText=[columns.map(c=>encode(c.label,`/columns/${enc(c.id)}`)).join(delimiter),...payload.rows.map((row,index)=>columns.map(c=>encode(columnCell(row,c),`/rows/${index}${c.path}`,typeof readTransferCell(row,c)=="string")).join(delimiter))].join(`
143
- `),format==="csv"&&(mime="text/csv;charset=utf-8",extension="csv"),format==="tsv"&&(mime="text/tab-separated-values;charset=utf-8",extension="tsv")}format==="html"&&(html=`<table><thead><tr>${columns.map(c=>`<th>${escapeHtml(c.label)}</th>`).join("")}</tr></thead><tbody>${payload.rows.map(row=>`<tr>${columns.map(c=>`<td>${escapeHtml(columnCell(row,c)).replace(/\r\n|\r|\n/g,"<br>")}</td>`).join("")}</tr>`).join("")}</tbody></table>`)}else plainText=payload.kind==="text"||payload.kind==="markdown"?payload.text:stringifyJson(payload.value,{style:"pretty"}),format==="markdown"&&(mime="text/markdown;charset=utf-8",extension="md"),format==="html"&&(html=`<pre>${escapeHtml(plainText)}</pre>`);return format==="html"&&(mime="text/html;charset=utf-8",extension="html"),sealTransferArtifact({snapshotId:draft.snapshotId,draftRevision:draft.revision,format,plainText,...html===void 0?{}:{html},file:{filename:options.filename??`export.${extension}`,mime,bytes:new TextEncoder().encode(format==="html"?html??plainText:plainText)},omissions})}var cell=value=>value==null?null:typeof value=="string"||typeof value=="number"||typeof value=="boolean"?value:JSON.stringify(value),xlsxEngine={async build(draft,options,signal){if(signal.aborted)throw new DOMException("Cancelled","AbortError");let p=draft.payload;if(p.kind!=="rows")throw new ContentTransferError2("unsupported-format","An Excel workbook needs table rows. Download it as CSV or JSON instead.");let columns=p.columns.filter(c=>c.visible&&c.exportable!==!1&&c.classification!=="secret"&&c.classification!=="credential"),XLSX2=await Promise.resolve().then(()=>(init_xlsx(),xlsx_exports));if(signal.aborted)throw new DOMException("Cancelled","AbortError");let sheet=XLSX2.utils.aoa_to_sheet([columns.map(c=>c.label),...p.rows.map(row=>columns.map(c=>cell(readTransferCell(row,c))))]),book=XLSX2.utils.book_new(),filename=options.filename??"export.xlsx",sheetName=filename.replace(/\.xlsx$/i,"").replace(/[\\/?*[\]:]/g," ").trim().slice(0,31)||"Data";XLSX2.utils.book_append_sheet(book,sheet,sheetName);let written=XLSX2.write(book,{type:"array",bookType:"xlsx",compression:!0});return sealTransferArtifact({snapshotId:draft.snapshotId,draftRevision:draft.revision,format:"xlsx",plainText:serialize(draft,"tsv").plainText,file:{filename,mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",bytes:written instanceof Uint8Array?written:new Uint8Array(written)},omissions:draft.omissions.map(o=>({...o}))})}},sheetJs=null;async function loadSheetJs(){return sheetJs??=await Promise.resolve().then(()=>(init_xlsx(),xlsx_exports)),sheetJs}function asCell(cell2){return{t:cell2.t,...cell2.v===void 0?{}:{v:cell2.v},...typeof cell2.w=="string"?{w:cell2.w}:{},...typeof cell2.f=="string"&&cell2.f.length>0?{f:cell2.f}:{},styled:!!cell2.s}}function wrapSheet(X,name,ws){let ref=ws["!ref"],range=ref?X.utils.decode_range(ref):null,merges=(ws["!merges"]??[]).map(m=>({s:{...m.s},e:{...m.e}}));return{name,range,merges,cell(r,c){let found=ws[X.utils.encode_cell({r,c})];return found?asCell(found):null},*cells(){for(let key in ws){if(key.startsWith("!"))continue;let found=ws[key];found&&(yield[X.utils.decode_cell(key),asCell(found)])}},grid(options={}){return X.utils.sheet_to_json(ws,{header:1,...options})},records(options={}){return X.utils.sheet_to_json(ws,options)}}}async function readWorkbookBytes(bytes,options={}){let X=await loadSheetJs(),book=X.read(bytes,{type:"array",...options.dates?{cellDates:!0}:{},...options.formulas?{cellFormula:!0}:{},...options.styles?{cellStyles:!0}:{}}),sheets=book.SheetNames.flatMap(name=>{let ws=book.Sheets[name];return ws?[wrapSheet(X,name,ws)]:[]});return{sheetNames:[...book.SheetNames],sheets,sheet:name=>sheets.find(s=>s.name===name)}}var XLSX_MIME="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";function dedupedSheetName(taken,raw){let name=raw.replace(/[\\/?*[\]:]/g," ").slice(0,31)||"Sheet1";if(!taken.includes(name))return name;let i=2;for(;taken.includes(`${name} (${i})`);)i++;return`${name} (${i})`}async function writeWorkbookBytes(value){let X=await loadSheetJs(),book=X.utils.book_new();for(let sheet of value.sheets){let ws={},maxR=-1,maxC=-1;sheet.rows.forEach((row,r)=>{row.forEach((raw,c)=>{if(raw==null)return;let typed=typeof raw=="object"?raw:null,v=typeof raw=="object"?raw.v:raw,out={t:typed?.t??(typeof v=="number"?"n":typeof v=="boolean"?"b":"s"),v:v??""};typed?.f&&(out.f=typed.f.replace(/^=/,"")),ws[X.utils.encode_cell({r,c})]=out,r>maxR&&(maxR=r),c>maxC&&(maxC=c)})}),ws["!ref"]=maxR<0?"A1:A1":X.utils.encode_range({s:{r:0,c:0},e:{r:maxR,c:maxC}}),sheet.merges?.length&&(ws["!merges"]=sheet.merges.map(m=>({s:{...m.s},e:{...m.e}}))),X.utils.book_append_sheet(book,ws,dedupedSheetName(book.SheetNames,sheet.name))}book.SheetNames.length===0&&X.utils.book_append_sheet(book,X.utils.aoa_to_sheet([[""]]),"Sheet1");let written=X.write(book,{type:"array",bookType:"xlsx",compression:!0});return written instanceof Uint8Array?written:new Uint8Array(written)}var workbookEngine={async build(draft,options,signal){if(signal.aborted)throw new DOMException("Cancelled","AbortError");let p=draft.payload;if(p.kind!=="registered"||p.format!=="workbook")throw new ContentTransferError2("unsupported-format","A formatted workbook needs workbook content. Download the table as Excel instead.");let value=p.value,bytes=await writeWorkbookBytes(value);if(signal.aborted)throw new DOMException("Cancelled","AbortError");let plainText=(value.sheets[0]?.rows??[]).map(row=>row.map(c=>c==null?"":String(typeof c=="object"?c.v??"":c)).join(" ")).join(`
144
- `);return sealTransferArtifact({snapshotId:draft.snapshotId,draftRevision:draft.revision,format:"xlsx-workbook",plainText,file:{filename:options.filename??"workbook.xlsx",mime:XLSX_MIME,bytes},omissions:draft.omissions.map(o=>({...o}))})}};export{loadSheetJs,readWorkbookBytes,workbookEngine,writeWorkbookBytes,xlsxEngine};
143
+ `),format==="csv"&&(mime="text/csv;charset=utf-8",extension="csv"),format==="tsv"&&(mime="text/tab-separated-values;charset=utf-8",extension="tsv")}format==="html"&&(html=`<table><thead><tr>${columns.map(c=>`<th>${escapeHtml(c.label)}</th>`).join("")}</tr></thead><tbody>${payload.rows.map(row=>`<tr>${columns.map(c=>`<td>${escapeHtml(columnCell(row,c)).replace(/\r\n|\r|\n/g,"<br>")}</td>`).join("")}</tr>`).join("")}</tbody></table>`)}else plainText=payload.kind==="text"||payload.kind==="markdown"?payload.text:stringifyJson(payload.value,{style:"pretty"}),format==="markdown"&&(mime="text/markdown;charset=utf-8",extension="md"),format==="html"&&(html=`<pre>${escapeHtml(plainText)}</pre>`);return format==="html"&&(mime="text/html;charset=utf-8",extension="html"),sealTransferArtifact({snapshotId:draft.snapshotId,draftRevision:draft.revision,format,plainText,...html===void 0?{}:{html},file:{filename:options.filename??`export.${extension}`,mime,bytes:new TextEncoder().encode(format==="html"?html??plainText:plainText)},omissions})}var cell=value=>value==null?null:typeof value=="string"||typeof value=="number"||typeof value=="boolean"?value:JSON.stringify(value),xlsxEngine={async build(draft,options,signal){if(signal.aborted)throw new DOMException("Cancelled","AbortError");let p=draft.payload;if(p.kind!=="rows")throw new ContentTransferError2("unsupported-format","An Excel workbook needs table rows. Download it as CSV or JSON instead.");let columns=p.columns.filter(c=>c.visible&&c.exportable!==!1&&c.classification!=="secret"&&c.classification!=="credential"),XLSX2=await Promise.resolve().then(()=>(init_xlsx(),xlsx_exports));if(signal.aborted)throw new DOMException("Cancelled","AbortError");let sheet=XLSX2.utils.aoa_to_sheet([columns.map(c=>c.label),...p.rows.map(row=>columns.map(c=>cell(readTransferCell(row,c))))]),book=XLSX2.utils.book_new(),filename=options.filename??"export.xlsx",sheetName=filename.replace(/\.xlsx$/i,"").replace(/[\\/?*[\]:]/g," ").trim().slice(0,31)||"Data";XLSX2.utils.book_append_sheet(book,sheet,sheetName);let written=XLSX2.write(book,{type:"array",bookType:"xlsx",compression:!0});return sealTransferArtifact({snapshotId:draft.snapshotId,draftRevision:draft.revision,format:"xlsx",plainText:serialize(draft,"tsv").plainText,file:{filename,mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",bytes:written instanceof Uint8Array?written:new Uint8Array(written)},omissions:draft.omissions.map(o=>({...o}))})}},sheetJs=null;async function loadSheetJs(){return sheetJs??=await Promise.resolve().then(()=>(init_xlsx(),xlsx_exports)),sheetJs}function asCell(cell2){return{t:cell2.t,...cell2.v===void 0?{}:{v:cell2.v},...typeof cell2.w=="string"?{w:cell2.w}:{},...typeof cell2.f=="string"&&cell2.f.length>0?{f:cell2.f}:{},styled:!!cell2.s}}function wrapSheet(X,name,ws){let ref=ws["!ref"],range=ref?X.utils.decode_range(ref):null,merges=(ws["!merges"]??[]).map(m=>({s:{...m.s},e:{...m.e}}));return{name,range,merges,cell(r,c){let found=ws[X.utils.encode_cell({r,c})];return found?asCell(found):null},*cells(){for(let key in ws){if(key.startsWith("!"))continue;let found=ws[key];found&&(yield[X.utils.decode_cell(key),asCell(found)])}},grid(options={}){return X.utils.sheet_to_json(ws,{header:1,...options})},records(options={}){return X.utils.sheet_to_json(ws,options)}}}async function readWorkbookBytes(bytes,options={}){let X=await loadSheetJs(),book=X.read(bytes,{type:"array",...options.dates?{cellDates:!0}:{},...options.formulas?{cellFormula:!0}:{},...options.styles?{cellStyles:!0}:{}}),sheets=book.SheetNames.flatMap(name=>{let ws=book.Sheets[name];return ws?[wrapSheet(X,name,ws)]:[]});return{sheetNames:[...book.SheetNames],sheets,sheet:name=>sheets.find(s=>s.name===name)}}var XLSX_MIME="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";function dedupedSheetName(taken,raw){let name=raw.replace(/[\\/?*[\]:]/g," ").slice(0,31)||"Sheet1";if(!taken.includes(name))return name;let i=2;for(;taken.includes(`${name} (${i})`);)i++;return`${name} (${i})`}async function writeWorkbookBytes(value){let X=await loadSheetJs(),book=X.utils.book_new();for(let sheet of value.sheets){let ws={},maxR=-1,maxC=-1;sheet.rows.forEach((row,r)=>{row.forEach((raw,c)=>{if(raw==null)return;let typed=typeof raw=="object"?raw:null,v=typeof raw=="object"?raw.v:raw,out={t:typed?.t??(typeof v=="number"?"n":typeof v=="boolean"?"b":"s"),v:v??""};typed?.f&&(out.f=typed.f.replace(/^=/,"")),ws[X.utils.encode_cell({r,c})]=out,r>maxR&&(maxR=r),c>maxC&&(maxC=c)})}),ws["!ref"]=maxR<0?"A1:A1":X.utils.encode_range({s:{r:0,c:0},e:{r:maxR,c:maxC}}),sheet.merges?.length&&(ws["!merges"]=sheet.merges.map(m=>({s:{...m.s},e:{...m.e}}))),X.utils.book_append_sheet(book,ws,dedupedSheetName(book.SheetNames,sheet.name))}book.SheetNames.length===0&&X.utils.book_append_sheet(book,X.utils.aoa_to_sheet([[""]]),"Sheet1");let written=X.write(book,{type:"array",bookType:"xlsx",compression:!0});return written instanceof Uint8Array?written:new Uint8Array(written)}var workbookEngine={async build(draft,options,signal){if(signal.aborted)throw new DOMException("Cancelled","AbortError");let p=draft.payload;if(p.kind!=="registered"||p.format!=="workbook")throw new ContentTransferError2("unsupported-format","A formatted workbook needs workbook content. Download the table as Excel instead.");let value=p.value,bytes=await writeWorkbookBytes(value);if(signal.aborted)throw new DOMException("Cancelled","AbortError");let plainText=toDelimited((value.sheets[0]?.rows??[]).map(row=>row.map(c=>c==null?null:typeof c=="object"?c.v??null:c)),{format:"tsv"});return sealTransferArtifact({snapshotId:draft.snapshotId,draftRevision:draft.revision,format:"xlsx-workbook",plainText,file:{filename:options.filename??"workbook.xlsx",mime:XLSX_MIME,bytes},omissions:draft.omissions.map(o=>({...o}))})}};export{loadSheetJs,readWorkbookBytes,workbookEngine,writeWorkbookBytes,xlsxEngine};
145
144
  /*! Bundled license information:
146
145
 
147
146
  xlsx/xlsx.mjs: