'use strict'; var api = require('@flatfile/api'); var utilCommon = require('@flatfile/util-common'); var utilFileBuffer = require('@flatfile/util-file-buffer'); var i=new api.FlatfileClient,j=3e3,N=(t,r,a,n)=>o=>{o.on("file:created",async e=>{let{fileId:l}=e.context,{data:d}=await i.files.get(l);if(d.mode==="export"||typeof t=="string"&&!d.name.endsWith(t)||t instanceof RegExp&&!t.test(d.name))return;let m=await i.jobs.create({type:api.Flatfile.JobType.File,operation:`extract-plugin-${r}`,status:api.Flatfile.JobStatus.Ready,source:l});await i.jobs.execute(m.data.id);}),o.on("job:ready",{operation:`extract-plugin-${r}`},async e=>{let{fileId:l,jobId:d,spaceId:m}=e.context,{chunkSize:K,parallel:L,debug:w}={chunkSize:5e3,parallel:1,debug:!1,...n},f=async(c,p)=>{await i.jobs.ack(d,{progress:c,info:p}),w&&console.log(`Job progress: ${c}, Info: ${p}`);};try{await f(1,"Retrieving file");let{data:c}=await i.files.get(l),p=await utilFileBuffer.getFileBuffer(e),{data:k}=await i.entitlements.list({resourceId:m}),h=!!k.find(s=>s.key==="headerSelection"),y=!!k.find(s=>s.key==="sourceEditor");await f(3,"Parsing Sheets");let u=await a(p,{...n,fileId:l,fileExt:c.ext,headerSelectionEnabled:h});await f(5,"Creating workbook");let g=await I(e.context.environmentId,c,u,y);if(await i.files.update(c.id,{workbookId:g.id}),!g.sheets||g.sheets.length===0)throw new Error("No Sheets found");await f(10,"Adding records to Sheets");let z=0,T=Object.values(u).reduce((s,R)=>s+(R?.data?.length||0),0);await new Promise(s=>{setTimeout(s,j);});for(let s of g.sheets)u[s.name]&&await utilCommon.createAllRecords(s.id,u[s.name].data.map($),async(R,F,C)=>{await f(Math.min(99,Math.round(10+90*(F/C))),"Adding records to Sheets");});h&&await D(g,u),await i.files.update(c.id,{status:"complete"}),await i.jobs.complete(d,{info:"Extraction complete",outcome:{message:"Extracted file"}});}catch(c){w&&console.log(`Extractor error: ${c.message}`),await i.files.update(l,{status:"failed"}),await i.jobs.fail(d,{info:"Extraction failed",outcome:{message:c.message}});}});};async function I(t,r,a,n){let o=O(r.name,r.spaceId,t,a,n),{data:e}=await i.workbooks.create(o);return e}function O(t,r,a,n,o){let e=Object.entries(n).map(([l,d])=>P(l,d,o));return {name:`[file] ${t}`,labels:["file"],spaceId:r,environmentId:a,sheets:e,treatments:[api.Flatfile.WorkbookTreatments.ExtractedFromSource]}}function P(t,{headers:r,descriptions:a},n){return {name:t,slug:utilCommon.slugify(t),fields:A({keys:r,descriptions:a}),allowAdditionalFields:n}}function x(t){return t.trim().replace(/%/g,"_PERCENT_").replace(/\$/g,"_DOLLAR_")}function $(t){let r={};for(let a in t)t.hasOwnProperty(a)&&(r[x(a)]=t[a]);return r}function A({keys:t,descriptions:r={}}){let a=0,n=t.reduce((o,e)=>{if(e||(e=""),typeof e!="string"&&(e=String(e)),e=e.trim(),e===""&&(e="empty"),o[e]){let l=`${e}_${o[e].count}`;o[l]={count:1,index:a},o[e].count++;}else o[e]={count:1,index:a};return a++,o},{});return Object.entries(n).sort((o,e)=>o[1].index-e[1].index).map(([o,e])=>({key:x(o),label:o,description:r?.[o]||"",type:"string"}))}async function D(t,r){await Promise.all(t.sheets.map(async a=>{let{metadata:n}=r[a.name];await i.sheets.updateSheet(a.id,{metadata:n});}));} exports.Extractor = N; exports.keysToFields = A; //# sourceMappingURL=index.cjs.map //# sourceMappingURL=index.cjs.map